【NX】NX开发入门练习寻找倒圆角设置颜色和添加属性

实现功能如标题,当时学习nx开发用的练习题,用的是nx8.5的32位版本,对于设置属性,一种是可以在界面中查看的属性,一种是隐藏的不能再界面中查看的自定义属性(但是可以正常读取)。

 

下面是完整代码:

//==============================================================================
//  WARNING!!  This file is overwritten by the Block Styler while generating
//  the automation code. Any modifications to this file will be lost after
//  generating the code again.
//
//       Filename:  D:\NXOPEN\application\modelingExercise.hpp
//
//        This file was generated by the NX Block Styler
//        Created by: hp
//              Version: NX 8.5
//              Date: 04-24-2023  (Format: mm-dd-yyyy)
//              Time: 09:58
//
//==============================================================================

#ifndef MODELINGEXERCISE_H_INCLUDED
#define MODELINGEXERCISE_H_INCLUDED

//------------------------------------------------------------------------------
//These includes are needed for the following template code
//------------------------------------------------------------------------------
#include <uf_defs.h>
#include <uf_ui_types.h>
#include <iostream>
#include <NXOpen/Session.hxx>
#include <NXOpen/UI.hxx>
#include <NXOpen/NXMessageBox.hxx>
#include <NXOpen/Callback.hxx>
#include <NXOpen/NXException.hxx>
#include <NXOpen/BlockStyler_UIBlock.hxx>
#include <NXOpen/BlockStyler_BlockDialog.hxx>
#include <NXOpen/BlockStyler_PropertyList.hxx>
#include <NXOpen/BlockStyler_Group.hxx>
#include <NXOpen/BlockStyler_Button.hxx>

//------------------------------------------------------------------------------
// Namespaces needed for following template
//------------------------------------------------------------------------------
using namespace std;
using namespace NXOpen;
using namespace NXOpen::BlockStyler;

class DllExport modelingExercise
{
    // class members
public:
    static Session *theSession;
    static UI *theUI;
    modelingExercise();
    ~modelingExercise();
    int Show();
    
    //----------------------- BlockStyler Callback Prototypes ---------------------
    // The following member function prototypes define the callbacks 
    // specified in your BlockStyler dialog.  The empty implementation
    // of these prototypes is provided in the modelingExercise.cpp file. 
    // You are REQUIRED to write the implementation for these functions.
    //------------------------------------------------------------------------------
    void initialize_cb();
    void dialogShown_cb();
    int apply_cb();
    int ok_cb();
    int update_cb(NXOpen::BlockStyler::UIBlock* block);
    PropertyList* GetBlockProperties(const char *blockID);
    
private:
    const char* theDlxFileName;
    NXOpen::BlockStyler::BlockDialog* theDialog;
    NXOpen::BlockStyler::Group* gpexercise;// Block type: Group
    NXOpen::BlockStyler::Button* btnCreateBlock;// Block type: Button
    NXOpen::BlockStyler::Button* btnFillet;// Block type: Button
    NXOpen::BlockStyler::Button* btnCalcArea;// Block type: Button
    
};
#endif //MODELINGEXERCISE_H_INCLUDED

实现:

//==============================================================================
//  WARNING!!  This file is overwritten by the Block UI Styler while generating
//  the automation code. Any modifications to this file will be lost after
//  generating the code again.
//
//       Filename:  D:\NXOPEN\application\modelingExercise.cpp
//
//        This file was generated by the NX Block UI Styler
//        Created by: hp
//              Version: NX 8.5
//              Date: 04-24-2023  (Format: mm-dd-yyyy)
//              Time: 09:58 (Format: hh-mm)
//
//==============================================================================

//==============================================================================
//  Purpose:  This TEMPLATE file contains C++ source to guide you in the
//  construction of your Block application dialog. The generation of your
//  dialog file (.dlx extension) is the first step towards dialog construction
//  within NX.  You must now create a NX Open application that
//  utilizes this file (.dlx).
//
//  The information in this file provides you with the following:
//
//  1.  Help on how to load and display your Block UI Styler dialog in NX
//      using APIs provided in NXOpen.BlockStyler namespace
//  2.  The empty callback methods (stubs) associated with your dialog items
//      have also been placed in this file. These empty methods have been
//      created simply to start you along with your coding requirements.
//      The method name, argument list and possible return values have already
//      been provided for you.
//==============================================================================

//------------------------------------------------------------------------------
//These includes are needed for the following template code
//------------------------------------------------------------------------------
#include "modelingExercise.hpp"

#include <uf_defs.h>
#include <NXOpen/NXException.hxx>
#include <NXOpen/Session.hxx>
#include <NXOpen/AttributeManager.hxx>
#include <NXOpen/AttributePropertiesBaseBuilder.hxx>
#include <NXOpen/AttributePropertiesBuilder.hxx>
#include <NXOpen/BasePart.hxx>
#include <NXOpen/Body.hxx>
#include <NXOpen/Builder.hxx>
#include <NXOpen/DateBuilder.hxx>
#include <NXOpen/DateItemBuilder.hxx>
#include <NXOpen/DateItemBuilderList.hxx>
#include <NXOpen/Edge.hxx>
#include <NXOpen/EdgeMultipleSeedTangentRule.hxx>
#include <NXOpen/Expression.hxx>
#include <NXOpen/ExpressionCollection.hxx>
#include <NXOpen/FeatureGeneralPropertiesBuilder.hxx>
#include <NXOpen/Features_Block.hxx>
#include <NXOpen/Features_BlockFeatureBuilder.hxx>
#include <NXOpen/Features_EdgeBlend.hxx>
#include <NXOpen/Features_EdgeBlendBuilder.hxx>
#include <NXOpen/Features_Feature.hxx>
#include <NXOpen/Features_FeatureBuilder.hxx>
#include <NXOpen/Features_FeatureCollection.hxx>
#include <NXOpen/Features_IContainerFeature.hxx>
#include <NXOpen/GeometricUtilities_BlendLimitsData.hxx>
#include <NXOpen/GeometricUtilities_BooleanOperation.hxx>
#include <NXOpen/GeometricUtilities_FacePlaneSelectionBuilder.hxx>
#include <NXOpen/GeometricUtilities_FacePlaneSelectionBuilderCollection.hxx>
#include <NXOpen/NXObject.hxx>
#include <NXOpen/Part.hxx>
#include <NXOpen/PartCollection.hxx>
#include <NXOpen/Plane.hxx>
#include <NXOpen/PlaneCollection.hxx>
#include <NXOpen/Point.hxx>
#include <NXOpen/PointCollection.hxx>
#include <NXOpen/Preferences_PartModeling.hxx>
#include <NXOpen/Preferences_PartPreferences.hxx>
#include <NXOpen/PropertiesManager.hxx>
#include <NXOpen/ScCollector.hxx>
#include <NXOpen/ScCollectorCollection.hxx>
#include <NXOpen/ScRuleFactory.hxx>
#include <NXOpen/SelectNXObjectList.hxx>
#include <NXOpen/SelectionIntentRule.hxx>
#include <NXOpen/Session.hxx>
#include <NXOpen/TaggedObjectList.hxx>
#include <NXOpen/Unit.hxx>
#include <NXOpen/UnitCollection.hxx>

#include <NXOpen/DisplayableObject.hxx>
#include <NXOpen/DisplayManager.hxx>
#include <NXOpen/DisplayModification.hxx>
#include <NXOpen/Face.hxx>
#include <NXOpen/Body.hxx>
#include <NXOpen/BodyCollection.hxx>
#include <NXOpen/ListingWindow.hxx>
#include <sstream>

#include <NXOpen/MeasureFaces.hxx>
#include <NXOpen/MeasureFaceBuilder.hxx>
#include <NXOpen/SelectDisplayableObjectList.hxx>


//------------------------------------------------------------------------------
// Initialize static variables
//------------------------------------------------------------------------------
Session *(modelingExercise::theSession) = NULL;
UI *(modelingExercise::theUI) = NULL;
//------------------------------------------------------------------------------
// Constructor for NX Styler class
//------------------------------------------------------------------------------
modelingExercise::modelingExercise()
{
    try
    {
        // Initialize the NX Open C++ API environment
        modelingExercise::theSession = NXOpen::Session::GetSession();
        modelingExercise::theUI = UI::GetUI();
        theDlxFileName = "modelingExercise.dlx";
        theDialog = modelingExercise::theUI->CreateDialog(theDlxFileName);
        // Registration of callback functions
        theDialog->AddApplyHandler(make_callback(this, &modelingExercise::apply_cb));
        theDialog->AddOkHandler(make_callback(this, &modelingExercise::ok_cb));
        theDialog->AddUpdateHandler(make_callback(this, &modelingExercise::update_cb));
        theDialog->AddInitializeHandler(make_callback(this, &modelingExercise::initialize_cb));
        theDialog->AddDialogShownHandler(make_callback(this, &modelingExercise::dialogShown_cb));
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        throw;
    }
}

//------------------------------------------------------------------------------
// Destructor for NX Styler class
//------------------------------------------------------------------------------
modelingExercise::~modelingExercise()
{
    if (theDialog != NULL)
    {
        delete theDialog;
        theDialog = NULL;
    }
}
//------------------------------- DIALOG LAUNCHING ---------------------------------
//
//    Before invoking this application one needs to open any part/empty part in NX
//    because of the behavior of the blocks.
//
//    Make sure the dlx file is in one of the following locations:
//        1.) From where NX session is launched
//        2.) $UGII_USER_DIR/application
//        3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly
//            recommended. This variable is set to a full directory path to a file 
//            containing a list of root directories for all custom applications.
//            e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_ROOT_DIR\menus\custom_dirs.dat
//
//    You can create the dialog using one of the following way:
//
//    1. USER EXIT
//
//        1) Create the Shared Library -- Refer "Block UI Styler programmer's guide"
//        2) Invoke the Shared Library through File->Execute->NX Open menu.
//
//------------------------------------------------------------------------------
extern "C" DllExport void  ufusr(char *param, int *retcod, int param_len)
{
    modelingExercise *themodelingExercise = NULL;
    try
    {
        themodelingExercise = new modelingExercise();
        // The following method shows the dialog immediately
        themodelingExercise->Show();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    if(themodelingExercise != NULL)
    {
        delete themodelingExercise;
        themodelingExercise = NULL;
    }
}

//------------------------------------------------------------------------------
// This method specifies how a shared image is unloaded from memory
// within NX. This method gives you the capability to unload an
// internal NX Open application or user  exit from NX. Specify any
// one of the three constants as a return value to determine the type
// of unload to perform:
//
//
//    Immediately : unload the library as soon as the automation program has completed
//    Explicitly  : unload the library from the "Unload Shared Image" dialog
//    AtTermination : unload the library when the NX session terminates
//
//
// NOTE:  A program which associates NX Open applications with the menubar
// MUST NOT use this option since it will UNLOAD your NX Open application image
// from the menubar.
//------------------------------------------------------------------------------
extern "C" DllExport int ufusr_ask_unload()
{
    //return (int)Session::LibraryUnloadOptionExplicitly;
    return (int)Session::LibraryUnloadOptionImmediately;
    //return (int)Session::LibraryUnloadOptionAtTermination;
}

//------------------------------------------------------------------------------
// Following method cleanup any housekeeping chores that may be needed.
// This method is automatically called by NX.
//------------------------------------------------------------------------------
extern "C" DllExport void ufusr_cleanup(void)
{
    try
    {
        //---- Enter your callback code here -----
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
}

int modelingExercise::Show()
{
    try
    {
        theDialog->Show();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return 0;
}

//------------------------------------------------------------------------------
//---------------------Block UI Styler Callback Functions--------------------------
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//Callback Name: initialize_cb
//------------------------------------------------------------------------------
void modelingExercise::initialize_cb()
{
    try
    {
        gpexercise = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("gpexercise"));
        btnCreateBlock = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnCreateBlock"));
        btnFillet = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnFillet"));
        btnCalcArea = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnCalcArea"));
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
}

//------------------------------------------------------------------------------
//Callback Name: dialogShown_cb
//This callback is executed just before the dialog launch. Thus any value set 
//here will take precedence and dialog will be launched showing that value. 
//------------------------------------------------------------------------------
void modelingExercise::dialogShown_cb()
{
    try
    {
        //---- Enter your callback code here -----
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
}

/*!
 * @brief  创建立方体
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
static int CreateBlock()
{
	Session *theSession = Session::GetSession();
	Part *workPart(theSession->Parts()->Work());
	Part *displayPart(theSession->Parts()->Display());

	Features::Feature *nullFeatures_Feature(NULL);

	Features::BlockFeatureBuilder *blockFeatureBuilder1;
	blockFeatureBuilder1 = workPart->Features()->CreateBlockFeatureBuilder(nullFeatures_Feature);

	blockFeatureBuilder1->BooleanOption()->SetType(GeometricUtilities::BooleanOperation::BooleanTypeCreate);

	std::vector<Body *> targetBodies1(1);
	Body *nullBody(NULL);
	targetBodies1[0] = nullBody;
	blockFeatureBuilder1->BooleanOption()->SetTargetBodies(targetBodies1);

	blockFeatureBuilder1->BooleanOption()->SetType(GeometricUtilities::BooleanOperation::BooleanTypeCreate);

	std::vector<Body *> targetBodies2(1);
	targetBodies2[0] = nullBody;
	blockFeatureBuilder1->BooleanOption()->SetTargetBodies(targetBodies2);

	Point3d coordinates1(0.0, 0.0, 0.0);
	Point *point1;
	point1 = workPart->Points()->CreatePoint(coordinates1);

	Unit *unit1(dynamic_cast<Unit *>(workPart->UnitCollection()->FindObject("MilliMeter")));
	Expression *expression1;
	expression1 = workPart->Expressions()->CreateSystemExpressionWithUnits("0", unit1);

	blockFeatureBuilder1->SetType(Features::BlockFeatureBuilder::TypesOriginAndEdgeLengths);

	blockFeatureBuilder1->SetOriginPoint(point1);

	Point3d originPoint1(0.0, 0.0, 0.0);
	blockFeatureBuilder1->SetOriginAndLengths(originPoint1, "20", "20", "20");

	blockFeatureBuilder1->SetBooleanOperationAndTarget(Features::Feature::BooleanTypeCreate, nullBody);

	Features::Feature *feature1;
	feature1 = blockFeatureBuilder1->CommitFeature();

	blockFeatureBuilder1->Destroy();

	workPart->Expressions()->Delete(expression1);

	//倒圆角
	Features::EdgeBlendBuilder *edgeBlendBuilder1;
	edgeBlendBuilder1 = workPart->Features()->CreateEdgeBlendBuilder(nullFeatures_Feature);

	GeometricUtilities::BlendLimitsData *blendLimitsData1;
	blendLimitsData1 = edgeBlendBuilder1->LimitsListData();

	Point3d origin1(0.0, 0.0, 0.0);
	Vector3d normal1(0.0, 0.0, 1.0);
	Plane *plane1;
	plane1 = workPart->Planes()->CreatePlane(origin1, normal1, SmartObject::UpdateOptionWithinModeling);

	GeometricUtilities::FacePlaneSelectionBuilder *facePlaneSelectionBuilder1;
	facePlaneSelectionBuilder1 = workPart->FacePlaneSelectionBuilderData()->Create();

	ScCollector *scCollector1;
	scCollector1 = workPart->ScCollectors()->CreateCollector();

	std::vector<Edge *> seedEdges1(1);
	Features::Block *block1(dynamic_cast<Features::Block *>(feature1));
	Edge *edge1(dynamic_cast<Edge *>(block1->FindObject("EDGE * 1 * 6 {(20,20,20)(20,10,20)(20,0,20) BLOCK(2)}")));
	seedEdges1[0] = edge1;
	EdgeMultipleSeedTangentRule *edgeMultipleSeedTangentRule1;
	edgeMultipleSeedTangentRule1 = workPart->ScRuleFactory()->CreateRuleEdgeMultipleSeedTangent(seedEdges1, 0.05, true);

	std::vector<SelectionIntentRule *> rules1(1);
	rules1[0] = edgeMultipleSeedTangentRule1;
	scCollector1->ReplaceRules(rules1, false);

	edgeBlendBuilder1->SetTolerance(0.001);

	edgeBlendBuilder1->SetAllInstancesOption(false);

	edgeBlendBuilder1->SetRemoveSelfIntersection(true);

	edgeBlendBuilder1->SetPatchComplexGeometryAreas(true);

	edgeBlendBuilder1->SetLimitFailingAreas(true);

	edgeBlendBuilder1->SetConvexConcaveY(false);

	edgeBlendBuilder1->SetRollOverSmoothEdge(true);

	edgeBlendBuilder1->SetRollOntoEdge(true);

	edgeBlendBuilder1->SetMoveSharpEdge(true);

	edgeBlendBuilder1->SetTrimmingOption(false);

	edgeBlendBuilder1->SetOverlapOption(Features::EdgeBlendBuilder::OverlapAnyConvexityRollOver);

	edgeBlendBuilder1->SetBlendOrder(Features::EdgeBlendBuilder::OrderOfBlendingConvexFirst);

	edgeBlendBuilder1->SetSetbackOption(Features::EdgeBlendBuilder::SetbackSeparateFromCorner);

	int csIndex1;
	csIndex1 = edgeBlendBuilder1->AddChainset(scCollector1, "5");

	Features::Feature *feature2;
	feature2 = edgeBlendBuilder1->CommitFeature();

	workPart->FacePlaneSelectionBuilderData()->Destroy(facePlaneSelectionBuilder1);

	edgeBlendBuilder1->Destroy();

#if 0
	//添加界面属性
	Session::UndoMarkId markId7;
	markId7 = theSession->SetUndoMark(Session::MarkVisibilityVisible, "Start");

	std::vector<NXObject *> objects1(1);
	Features::EdgeBlend *edgeBlend1(dynamic_cast<Features::EdgeBlend *>(feature2));
	objects1[0] = edgeBlend1;
	AttributePropertiesBuilder *attributePropertiesBuilder1;
	attributePropertiesBuilder1 = theSession->AttributeManager()->CreateAttributePropertiesBuilder(workPart, objects1, AttributePropertiesBuilder::OperationTypeNone);

	attributePropertiesBuilder1->SetArray(false);

	attributePropertiesBuilder1->SetDataType(AttributePropertiesBaseBuilder::DataTypeOptionsString);

	attributePropertiesBuilder1->SetUnits("MilliMeter");

	std::vector<NXObject *> objects2(1);
	objects2[0] = edgeBlend1;
	FeatureGeneralPropertiesBuilder *featureGeneralPropertiesBuilder1;
	featureGeneralPropertiesBuilder1 = workPart->PropertiesManager()->CreateFeatureGeneralPropertiesBuilder(objects2);

	theSession->SetUndoMarkName(markId7, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247 \345\257\271\350\257\235\346\241\206", NXString::UTF8));

	attributePropertiesBuilder1->DateValue()->DateItem()->SetDay(DateItemBuilder::DayOfMonthDay23);

	attributePropertiesBuilder1->DateValue()->DateItem()->SetMonth(DateItemBuilder::MonthOfYearApr);

	attributePropertiesBuilder1->DateValue()->DateItem()->SetYear("2023");

	attributePropertiesBuilder1->DateValue()->DateItem()->SetTime("00:00:00");

	std::vector<NXObject *> objects3(1);
	objects3[0] = edgeBlend1;
	attributePropertiesBuilder1->SetAttributeObjects(objects3);

	attributePropertiesBuilder1->SetUnits("MilliMeter");

	attributePropertiesBuilder1->SetCategory("class");

	attributePropertiesBuilder1->SetTitle("FaceType");

	attributePropertiesBuilder1->SetArray(false);

	Session::UndoMarkId markId8;
	markId8 = theSession->SetUndoMark(Session::MarkVisibilityInvisible, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	attributePropertiesBuilder1->SetStringValue("cylinder");

	theSession->DeleteUndoMark(markId8, NULL);

	Session::UndoMarkId markId9;
	markId9 = theSession->SetUndoMark(Session::MarkVisibilityInvisible, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	NXObject *nXObject1;
	nXObject1 = attributePropertiesBuilder1->Commit();

	NXObject *nXObject2;
	nXObject2 = featureGeneralPropertiesBuilder1->Commit();

	theSession->DeleteUndoMark(markId9, NULL);

	theSession->SetUndoMarkName(markId7, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	attributePropertiesBuilder1->Destroy();

	featureGeneralPropertiesBuilder1->Destroy();

#else
	//NXOpen对部件加属性
	BodyCollection* bc = workPart->Bodies();

	//遍历所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		std::vector<NXOpen::Face *> faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			// 获取选择的面
			NXOpen::Face* face = dynamic_cast<NXOpen::Face*>(faces[j]);

			//找到圆角面,并且添加属性FaceType
			if (faces[j]->SolidFaceType() == Face::FaceTypeCylindrical)
			{
				Face* faceCylindrical = faces[j];

				std::vector<NXObject *> objects1(1);
				objects1[0] = faceCylindrical;

				AttributePropertiesBuilder *attributePropertiesBuilder1;
				attributePropertiesBuilder1 = theSession->AttributeManager()->CreateAttributePropertiesBuilder(workPart, objects1, AttributePropertiesBuilder::OperationTypeNone);
				attributePropertiesBuilder1->SetTitle("FaceType");
				attributePropertiesBuilder1->SetStringValue("cylinder");
				NXObject *nXObject1;
				nXObject1 = attributePropertiesBuilder1->Commit();

				attributePropertiesBuilder1->Destroy();
			}
		}
	}
#endif

	return 0;
}


/*!
 * @brief  改变面的颜色
 * @return 无
 * @param  对象组,颜色索引
 * @author zhanglu
 * @date   2023/04/24
 */
static void ChangeFaceColor(std::vector<NXOpen::DisplayableObject*> displayableobjects, int color)
{
	Session* theSession = Session::GetSession();
	NXOpen::DisplayModification* displaymodification = theSession->DisplayManager()->NewDisplayModification();
	displaymodification->ApplyToAllFaces();
	displaymodification->SetNewColor(color);
	displaymodification->Apply(displayableobjects);
}

/*!
 * @brief  圆角面涂色
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
int ColorFillet()
{
	// 获取所有的圆角面
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());

	//ListingWindow* lw = theSession->ListingWindow();
	//lw->Open();

	NXOpen::Part* displayPart(theSession->Parts()->Display());

	BodyCollection* bc = workPart->Bodies();

	std::vector<Face*> faces;

	int nFaceTypeCylindricalCount = 0;

	std::stringstream ss;

	std::vector<NXOpen::DisplayableObject*> vDisObjectsToRed;
	std::vector<NXOpen::DisplayableObject*> vDisObjectsToWhite;

	//便利所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			// 获取选择的面		
#if 1
			NXOpen::Face* face = dynamic_cast<NXOpen::Face*>(faces[j]);

			//std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetAttributeTitlesByType(NXOpen::NXObject::AttributeType::AttributeTypeString);
			std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetUserAttributes(NXOpen::NXObject::AttributeType::AttributeTypeString);

			int a = vAttributes.size();
			for (int k = 0; k < a; ++k)
			{
				std::string sA = vAttributes[k].Title.GetText();

				if (sA == "FaceType")
				{
					Face * faceCylindrical = faces[j];
					if (faces[j]->Color() != 186)
					{
						vDisObjectsToRed.push_back(faceCylindrical);
					}
					else
					{
						vDisObjectsToWhite.push_back(faceCylindrical);
					}
				}
			}
#else
			//找到圆角面
			if (faces[j]->SolidFaceType() == Face::FaceTypeCylindrical)
			{
				Face* faceCylindrical = faces[j];

				nFaceTypeCylindricalCount++;

				//此处为何没能获取界面添加的属性值 非界面正常获取
				//std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faceCylindrical->GetUserAttributes(NXOpen::NXObject::AttributeType::AttributeTypeString);
				std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetAttributeTitlesByType(NXOpen::NXObject::AttributeType::AttributeTypeString);

				ss << vAttributes.size() << std::endl;

				for (int j = 0; j < vAttributes.size(); ++j)
				{
					lw->WriteLine(vAttributes[j].Title.GetText());
				}

				if (faces[j]->Color() != 186)
				{
					vDisObjectsToRed.push_back(faceCylindrical);
				}
				else
				{
					vDisObjectsToWhite.push_back(faceCylindrical);
				}
			}
#endif
		}
	}

	ChangeFaceColor(vDisObjectsToRed, 186);
	ChangeFaceColor(vDisObjectsToWhite, 1);

	//lw->WriteLine(ss.str());

	return 0;
}

/*!
 * @brief  求面积
 * @return 0
 * @param  面对象,面积
 * @author zhanglu
 * @date   2023/04/24
 */
static void AskFaceAreas(Face* face, double& areaValue)
{
	//获取面积
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());
	NXOpen::Part* displayPart(theSession->Parts()->Display());

	NXObject* nullNXObject(NULL);
	NXOpen::MeasureFaceBuilder* measureFaceBuilder1;
	measureFaceBuilder1 = workPart->MeasureManager()->CreateMeasureFaceBuilder(nullNXObject);
	std::vector<IParameterizedSurface*> objects1(1);
	objects1[0] = face;

	MeasureFaces* measureFaces1;
	Unit* unit1 = workPart->UnitCollection()->FindObject("SquareMilliMeter");
	Unit* unit2 = workPart->UnitCollection()->FindObject("MilliMeter");
	measureFaces1 = workPart->MeasureManager()->NewFaceProperties(unit1, unit2, 0.9999, objects1);

	measureFaceBuilder1->FaceObjects()->Clear();
	measureFaceBuilder1->Destroy();
	theSession->CleanUpFacetedFacesAndEdges();
	areaValue = measureFaces1->Area();
}

/*!
 * @brief  获取红色面的面积
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
static int CalcArea()
{
	// 获取所有的圆角面
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());
	ListingWindow* lw = theSession->ListingWindow();

	NXOpen::Part* displayPart(theSession->Parts()->Display());

	BodyCollection* bc = workPart->Bodies();

	std::vector<Face*> faces;

	stringstream ss;

	std::vector<NXOpen::DisplayableObject*> vDisObjectsToCalcArea;

	double dArea = 0.0;

	//便利所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			if (faces[j]->Color() == 186)
			{
				double areaValue;
				AskFaceAreas(faces[j], areaValue);

				dArea += areaValue;
			}
		}
	}

	lw->Open();

	NXOpen::NXString strInfo;

	ss << dArea;

	lw->WriteLine(ss.str());

	return 0;
}


//------------------------------------------------------------------------------
//Callback Name: apply_cb
//------------------------------------------------------------------------------
int modelingExercise::apply_cb()
{
    int errorCode = 0;
    try
    {
        //---- Enter your callback code here -----
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        errorCode = 1;
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return errorCode;
}

//------------------------------------------------------------------------------
//Callback Name: update_cb
//------------------------------------------------------------------------------
int modelingExercise::update_cb(NXOpen::BlockStyler::UIBlock* block)
{
    try
    {
        if(block == btnCreateBlock)
        {
        //---------Enter your code here-----------
			if (CreateBlock() != 0)
			{

			}
        }
        else if(block == btnFillet)
        {
        //---------Enter your code here-----------
			if (ColorFillet() != 0)
			{

			}
        }
        else if(block == btnCalcArea)
        {
        //---------Enter your code here-----------
			if (CalcArea() != 0)
			{
				
			}
        }
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return 0;
}

//------------------------------------------------------------------------------
//Callback Name: ok_cb
//------------------------------------------------------------------------------
int modelingExercise::ok_cb()
{
    int errorCode = 0;
    try
    {
        errorCode = apply_cb();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        errorCode = 1;
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return errorCode;
}

//------------------------------------------------------------------------------
//Function Name: GetBlockProperties
//Description: Returns the propertylist of the specified BlockID
//------------------------------------------------------------------------------
PropertyList* modelingExercise::GetBlockProperties(const char *blockID)
{
    return theDialog->GetBlockProperties(blockID);
}

欢迎交流与讨论。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值