HOOPSVisualizeHPSAPIProgrammingGuide

%%%flush_merged_shells

omResults.FlushMerged();


%%%iterate_results

OptimizeMappingResultsIterator it = omResults.GetIterator();
while (it.IsValid())
{
if (it.GetMergedShellInfo(out out_shell_key, out out_vertex_offset, out out_face_offset, out out_edge_offset))
{
// do something with the merged shell data
}
it.Next();
}


%%%merge_shells

segmentOOK.SetScope(SegmentOptimizationOptions.Scope.SegmentOnly);
segmentOOK.SetShellMerging(true);
OptimizeMappingResults omResults = mySegmentKey.OptimizeWithMapping(segmentOOK);


%%%override_internal_color

HPS.VisibilityKit visibilityKit = new HPS.VisibilityKit();
visibilityKit.SetEverything(false).SetMarkers(true).SetLines(true);
mySegmentKey.GetDrawingAttributeControl().SetOverrideInternalColor(visibilityKit);


%%%pbrmaterialkit

PBRMaterialKit pbrKit = new PBRMaterialKit();
pbrKit.SetBaseColorFactor(new RGBAColor(1, 0.65f, 0, 1));
pbrKit.SetRoughnessFactor(0.5f);
pbrKit.SetMetalnessFactor(0.75f);
mySegmentKey.SetPBRMaterial(pbrKit);


%%%handles_operator_constrain

// do not translate in the Z axis direction
myHandlesOperator.RemoveHandles(HPS.HandlesOperator.HandleType.AxisTranslationZ);
// remove all rotation handles
myHandlesOperator.RemoveHandles(HPS.HandlesOperator.HandleType.Rotation);
// add rotation around Z
myHandlesOperator.AddHandles(HPS.HandlesOperator.HandleType.RotationZ);
// remove all plane translation handles
myHandlesOperator.RemoveHandles(HPS.HandlesOperator.HandleType.PlaneTranslation);
// add XY plane translation
myHandlesOperator.AddHandles(HPS.HandlesOperator.HandleType.PlaneTranslationXY);


%%%realdwg_import

notifier.Wait();
// get the status of the import
HPS.IOResult result = notifier.Status();
if (result == HPS.IOResult.Success)
{
// file loading successfully
modelFile = notifier.GetCADModel();
modelFile.ActivateDefaultCapture();
myCanvas.AttachViewAsLayout(myView);
// alternatively, if you already have a View object, you can simply
// get the Model and attach it directly:
HPS.Model model = modelFile.GetModel();
myView.AttachModel(model);
}
// you can cancel the import by calling:
notifier.Cancel();


%%%realdwg_layers

Component[] tables = modelFile.GetSubcomponents();
for (int i = 0; i < tables.Length; i++)
{
// access the layer table
if (tables[i].GetComponentType() == HPS.Component.ComponentType.DWGLayerTable)
{
Component[] layers = tables[i].GetSubcomponents();
for (int j = 0; j < layers.Length; j++)
{
// find the correct layer by name
HPS.StringMetadata layer_name = new HPS.StringMetadata(layers[j].GetMetadata("Name"));
if (layer_name.GetValue() == "0")
{
// toggle its visibility
HPS.DWG.Layer layer = new HPS.DWG.Layer(layers[j]);
if (layer.IsOn())
layer.TurnOff();
else
layer.TurnOn();
break;
}
}
}
}


%%%realdwg_activate_layout

HPS.DWG.CADModel cadModel = (HPS.DWG.CADModel) modelFile;
myView = cadModel.ActivateDefaultLayout();
myCanvas = HPS.Factory.CreateCanvas(myWindowKey);
myCanvas.AttachViewAsLayout(myView);


%%%realdwg_get_all_layouts

HPS.DWG.Layout[] layouts = cadModel.GetAllLayouts();
for (int i = 0; i < layouts.Length; i++)
{
HPS.StringMetadata name = new HPS.StringMetadata(layouts[i].GetMetadata("Name"));
if (name.GetValue().Equals("PDF"))
{
HPS.View new_view = layouts[i].Activate();
myCanvas.AttachViewAsLayout(myView);
}
}


%%%grids_1

HPS.GridKit gridKit = new HPS.GridKit();
gridKit.SetFirstCount(10);
gridKit.SetSecondCount(10);
gridKit.SetFirstPoint(new Point(0.3f, 0, 0));
gridKit.SetSecondPoint(new Point(0, 0.1f, 0));
gridKit.SetOrigin(new Point(0, 0, 0));
gridKit.SetType(HPS.Grid.Type.Quadrilateral);
mySegmentKey.InsertGrid(gridKit);


%%%grids_2

gridKit.SetType(HPS.Grid.Type.Radial);


%%%grids_3

// create a LinePatternKit
myLPK.SetJoin(HPS.LinePattern.Join.Bevel); // control how lines join at intersections
myPortfolio.DefineLinePattern("myPattern", myLPK); // make sure the portfolio is accessible in your segment hierarchy
mySegmentKey.GetLineAttributeControl().SetPattern("myPattern");
// set the weight and pattern of the grid
mySegmentKey.GetEdgeAttributeControl().SetPattern("myPattern").SetWeight(2.0f, Edge.SizeUnits.Pixels);
mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0.8f, 0.8f, 0.8f)); // set the grid color
mySegmentKey.GetMaterialMappingControl().SetLineColor(new HPS.RGBAColor(0.0f, 0.0f, 0.0f));
mySegmentKey.GetVisibilityControl().SetEdges(true); // enable the visibility of edges
mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.4f, 0.7f, 0.2f)); // set the background grid color


%%%navcube_material

MaterialKit[] materialKitArray = { new HPS.MaterialKit().SetDiffuse(new RGBAColor(1, 0, 0, 1)), // positive x-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(0, 1, 0, 1)), // positive y-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(1, 1, 0, 1)), // positive z-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(1, 0, 0, 1)), // negative x-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(0, 1, 0, 1)), // negative y-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(1, 1, 0, 1)), // negative z-face
new HPS.MaterialKit().SetDiffuse(new RGBAColor(1, 1, 1, 1)), // highlight
new HPS.MaterialKit().SetDiffuse(new HPS.RGBColor(0, 0, 0)), // text color
new HPS.MaterialKit().SetDiffuse(new HPS.RGBColor(0, 0.37f, 0.59f)) // line color
};
portfolio.DefineMaterialPalette("my_material", materialKitArray);
myView.GetNavigationCubeControl().SetMaterialPalette("my_material");


%%%navcube_text

TextAttributeKit myTextAttributeKit = TextAttributeKit.GetDefault();
myTextAttributeKit.SetUnderline(true).SetSize(20, HPS.Text.SizeUnits.Pixels).SetAlignment(HPS.Text.Alignment.Center);
myView.GetNavigationCubeControl().SetText("Bear", "Trout", "Lion", "Fish", "Birch", "Rana", myTextAttributeKit);


%%%image_glyphs

// import the image into the database
HPS.ImageKit myImageKit = HPS.Image.File.Import(filename, iok);
// define the image in a portfolio
HPS.ImageDefinition patternImageDef = myPortfolio.DefineImage("pattern", myImageKit);
// create a glyph kit to contain your new glyph - note the radius and offset settings are required
HPS.GlyphKit glyphKit = new HPS.GlyphKit();
glyphKit.SetRadius(0);
glyphKit.SetOffset(new HPS.GlyphPoint(0, 0));
// create an ImageGlyphElement from the defined image
HPS.ImageGlyphElement imageGlyphElement = new HPS.ImageGlyphElement();
imageGlyphElement.SetSource("pattern");
imageGlyphElement.SetFixedScaling(false);
// here we are only using a single glyph element to represent the glyph
HPS.GlyphElement[] glyphElements = { imageGlyphElement };
glyphKit.SetElements(glyphElements);
// defining the new glyph in a portfolio
myPortfolio.DefineGlyph("patternGlyph", glyphKit);
mySegmentKey.GetPortfolioControl().Push(myPortfolio);
mySegmentKey.GetMarkerAttributeControl().SetSymbol("patternGlyph");
// inserts the glyph into the scene
mySegmentKey.InsertMarker(new Point(0, 0, 0));


%%%database

// creating a root segment
// creating a window segment


%%%show_subsegments

HPS.SegmentKey[] children;
mySegmentKey.ShowSubsegments(out children);
for (int i = 0; i < children.Length; i++)
{
HPS.SegmentKey sk = children[i]; // get reference to a child
String s = sk.Name(); // get child's name
HPS.SegmentKey parent = sk.Owner(); // a new reference to the parent segment
}


%%%manipulate_segment

// creating two independent segments
// ...other logic
// "anotherSegmentKey" becomes a child of "mySegmentKey"
anotherSegmentKey.MoveTo(mySegmentKey);
// delete everything in the segment
anotherSegmentKey.Flush();
// delete the segment itself
anotherSegmentKey.Delete();



%%%create_subsegment

HPS.SegmentKey newSegmentKey = mySegmentKey.Down("new segment", true);
// alternatively, you may use the Subsegment function
HPS.SegmentKey anotherKey = mySegmentKey.Subsegment();


%%%create_root_segment

// creating the root segment for the turbine model


%%%include_segment

// including the turbine root segment
HPS.IncludeKey includeKey = windowKey.IncludeSegment(myTurbineModel);


%%%include_filter

// filters out lighting from an include segment
includeKey.SetFilter(HPS.AttributeLock.Type.VisibilityLights);


%%%delete_include

includeKey.Delete();


%%%conditional_include

// here, the condition is created
// including a segment subject to the condition
mySegmentKey.IncludeSegment(someSpecialSegment, condition1);
// the condition is set in the following line, and 'someSpecialSegment' becomes part of the tree
mySegmentKey.SetCondition("c1");


%%%reference_segment

mySegmentKey.ReferenceGeometry(anotherSegment); // brings in just the geometry from 'anotherSegment'


%%%keys

// insert a sphere into the segment via SegmentKey
HPS.SphereKey sphereKey = mySegmentKey.InsertSphere(new HPS.Point(0.0f, 0.0f, 0.0f), 2.0f);
// insert text into the segment via SegmentKey
HPS.TextKey myText = mySegmentKey.InsertText(new HPS.Point(0.0f, 0.0f, 0.0f), "My segment");
// set font on the text using the TextKey
myText.SetFont("times new roman");


%%%geometry_keys

myCircleKey.SetRadius(2.0f);
myCircleKey.SetCenter(new HPS.Point(1.0f, 2.5f, 3.2f));


%%%edge_attribute_control_example

mySegmentKey.GetLineAttributeControl().SetPattern("my_line_pattern");
mySegmentKey.GetEdgeAttributeControl().SetWeight(3.0f);


%%%camera_attribute_control_example

mySegmentKey.GetCameraControl().ShowProjection(out proj); // get the current projection type
mySegmentKey.GetCameraControl().Orbit(20, 30); // moves 20 degrees right, 30 up
mySegmentKey.GetCameraControl().Zoom(10); // zoom 10x


%%%insert_circle

HPS.CircleKit circleKit = new HPS.CircleKit();
// setting the attributes on the kit
circleKit.SetCenter(new HPS.Point(0, 0, 0));
circleKit.SetNormal(new HPS.Vector(0, 0, 1));
circleKit.SetRadius(0.75f);
// inserting first circle of radius 0.75, plus all other attributes committed at once:
HPS.CircleKey circleKey = mySegmentKey.InsertCircle(circleKit);
// change radius for second insert
circleKit.SetRadius(0.25f);
// same CircleKit used for second circle of radius 0.25 - all other attributes are the same
mySegmentKey.InsertCircle(circleKit);
// Circle instance parameters can be copied out of the database to another CircleKit for use elsewhere
circleKey.Show(out anotherCircleKit);


%%%modify_circle

circleKey.SetCenter(new HPS.Point(0, 0, 0));
circleKey.SetNormal(new HPS.Vector(0, 0, 1));
circleKey.SetRadius(0.5f);
// alternatively, the attributes can be set in one line of code using
// chaining, although the effect on performance is unchanged
circleKey.SetCenter(new HPS.Point(0, 0, 0)).SetNormal(new HPS.Vector(0, 0, 1)).SetRadius(0.5f);


%%%attribute_locks

HPS.SegmentKey childSegment = parentSegment.Subsegment();
// setting the color to red
parentSegment.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(1, 0, 0));
parentSegment.GetAttributeLockControl().SetLock(HPS.AttributeLock.Type.Everything);
// setting this blue color below has no effect because of the attribute lock
childSegment.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0, 0, 1));
// sphere appears in red
childSegment.InsertSphere(new HPS.Point(0, 0, 0), 0.5f);


%%%create_application_window

// creating a window segment based on an OpenGL2 rendering context
HPS.ApplicationWindowKey appWindowKey = HPS.Database.CreateApplicationWindow(myWindowHandle, HPS.Window.Driver.OpenGL2);
// after the window is created, you can build your tree and update it normally
appWindowKey.IncludeSegment(modelKey);
appWindowKey.Update();


%%%standalone


%%%attribute_locks

HPS.SegmentKey childSegment = parentSegment.Subsegment();
// setting the color to red
parentSegment.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(1, 0, 0));
parentSegment.GetAttributeLockControl().SetLock(HPS.AttributeLock.Type.Everything);
// setting this blue color below has no effect because of the attribute lock
childSegment.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0, 0, 1));
// sphere appears in red
childSegment.InsertSphere(new HPS.Point(0, 0, 0), 0.5f);


%%%sawok

// parameters are in window coordinates
sawok.SetSubscreen(new HPS.Rectangle(0.25f, 0.75f, -0.35f, 0.75f));
// fixes the aspect ratio
sawok.SetMobility(HPS.Window.Mobility.FixedRatio);


%%%traversal_1

// returns parent segment key
HPS.SegmentKey parent = mySegmentKey.Up();
// returns child key for segment named "child_segment_name". invalid key returned if segment is not present
HPS.SegmentKey child1 = mySegmentKey.Down("child_segment_name");
// overloaded Down() method will create the child segment if it doesn't exist
HPS.SegmentKey child2 = mySegmentKey.Down("new_segment", true);


%%%traversal_2

if (mySegmentKey.Type() == HPS.Type.None)
{
// mySegmentKey is invalid
}


%%%traversal_3

// the basic ShowSubsegments() gets the number of child segments
ulong numChildren = mySegmentKey.ShowSubsegments();
// the overloaded ShowSubsegments returns the count and also fills in the array with child SegmentKeys
HPS.SegmentKey[] childArray;
numChildren = mySegmentKey.ShowSubsegments(out childArray);


%%%search

HPS.SearchResults searchResults;
ulong numResults = mySegmentKey.Find(HPS.Search.Type.Circle, // searching for circles
HPS.Search.Space.Subsegments, // within all subsegments
out searchResults); // search results returned here
HPS.SearchResultsIterator it = searchResults.GetIterator();
while (it.IsValid())
{
HPS.Key key = it.GetItem();
if (key.Type() == HPS.Type.CircleKey)
{
// do something with this object
}
it.Next();
}


%%%examining_type

HPS.Key myKey = some_function();
HPS.Type myKeyType = myKey.Type();
switch (myKeyType)
{
case HPS.Type.ShellKey:
break; //object was a shell key
case HPS.Type.CircleKey:
break; // object was a circle key
case HPS.Type.MarkerKey:
break; // object was a marker
default:
break; // object was something else
}


%%%assuming_type

bool valid = false;
try
{
// assume it is a ShellKey
ShellKey selected_shell = new ShellKey(selected_key); // this will throw if not a ShellKey
selected_shell.GetFaceCount();
valid = true;
}
catch (InvalidObjectException ioe)
{
// fall back to using Type()
}


%%%set_projection

mySegmentKey.GetCameraControl().SetProjection(HPS.Camera.Projection.Orthographic);


%%%insert_example

mySegmentKey.InsertShell(shellKit);
mySegmentKey.InsertText(textKit);
mySegmentKey.InsertSphere(sphereKit);


%%%update

windowKey.Update(); // call Update on a WindowKey instance
myCanvas.Update(); // alternatively, if you're using the view hierarchy, call it on a Canvas


%%%keypath

HPS.Key[] keyArray = new HPS.Key[2];
keyArray[0] = shellKey;
keyArray[1] = includeKey;
HPS.KeyPath keyPath = new HPS.KeyPath();
keyPath.SetKeys(keyArray);


%%%shownet

keyPath.ShowNetCamera(out cameraKit);


%%%%010302_a

HPS.Point target, pos;
// retrieving information with a kit in one call to the database
HPS.CameraKit myCameraKit;
mySegmentKey.ShowCamera(out myCameraKit);
myCameraKit.ShowTarget(out target);
myCameraKit.ShowPosition(out pos);
// retrieving information from the database via the CameraControl
mySegmentKey.GetCameraControl().ShowTarget(out target);
mySegmentKey.GetCameraControl().ShowPosition(out pos);


%%%%010302_b

HPS.TextKey myText = mySegmentKey.InsertText(new HPS.Point(0.0f, 0.0f, 0.0f), "My string is here.");


%%%%010302_c

myText.SetBold(true);


%%%%010302_d

myText.SetColor(new HPS.RGBAColor(1, 1, 0));


%%%%010302_e

// create the kit
HPS.TextKit highlightText = new HPS.TextKit();
// set the attributes to highlight our text
highlightText.SetBold(true);
// using RGBColor to set text to yellow
highlightText.SetColor(new HPS.RGBAColor(1, 1, 0));
// apply the changes to the database
myTextKey.Set(highlightText);


%%%%010303_a

// four calls directly to the database - slower
HPS.TextKey myTextKey = mySegmentKey.InsertText(new HPS.Point(0.0f, 0.0f, 0.0f), "My important text string.");
myTextKey.SetBold(true);
myTextKey.SetLineSpacing(1.5f);
myTextKey.SetRotation(20);


%%%%010303_b

// preferred method is to build the kit, then make one database call:
HPS.TextKit textKit = new HPS.TextKit();
textKit.SetText("My important text string.");
textKit.SetPosition(new HPS.Point(0, 0, 0));
textKit.SetBold(true);
textKit.SetLineSpacing(1.5f);
textKit.SetRotation(20);
mySegmentKey.InsertText(textKit);


%%%%010303_c

HPS.TextKit textKit = new HPS.TextKit();
myTextKey.Show(out textKit); // copies existing database object into the kit
// adjusting the kit
textKit.SetFont("times new roman");
textKit.SetSize(10, HPS.Text.SizeUnits.Points);
textKit.SetColor(new HPS.RGBAColor(1, 0, 0));
// reinserting into database
myTextKey.Set(textKit);


%%%%010304_a

HPS.Point target, pos;
float w, h;
HPS.CameraControl myCameraControl = mySegmentKey.GetCameraControl();
myCameraControl.ShowTarget(out target);
myCameraControl.ShowField(out w, out h);
myCameraControl.ShowPosition(out pos);


%%%show_logic

bool state;
if (mySegmentKey.GetVisibilityControl().ShowLines(out state))
{
// visibility is defined for lines in seg
// if state == true then visibility for lines is explicitly set to ON for this segment
// if state == false then visibility for lines is explicitly set to OFF for this segment
}
else
{
// visibility has NOT been defined for lines in seg. It might be inherited from above, though.
// To get the NET visibility for lines you will need a KeyPath.
}


%%%%010305_a

highlightText.SetBold(true);


%%%%010305_b

highlightText.SetBold(true).SetColor(new RGBAColor(1, 0, 1));


%%%%010305_c

// create our highlight text kit
HPS.TextKit highlightText = new HPS.TextKit();
highlightText.SetBold(true).SetColor(new HPS.RGBAColor(1, 0, 1));
// apply the changes to the database
myTextKey.Set(highlightText);


%%%%010305_d

myTextKey.SetBold(true);
myTextKey.SetColor(new RGBAColor(1, 0, 1));


%%%%010305_e

// create the kit
HPS.TextKit highlightText = new HPS.TextKit();
// set the attributes highlight the text
highlightText.SetBold(true);
// using RGBColor to set text to yellow
highlightText.SetColor(new RGBAColor(1, 1, 0));
// apply the changes to the database
myTextKey.Set(highlightText);


%%%%010305_f

// create our highlight text kit
HPS.TextKit highlightText = new HPS.TextKit();
highlightText.SetBold(true).SetColor(new HPS.RGBAColor(1, 1, 0));
// apply the changes to the database
myTextKey.Set(highlightText);


%%%%010308_a

HPS.Point[] pointArray;


%%%user_data

byte [] myData = new byte[] { (byte) 'H', (byte) 'O', (byte) 'O', (byte) 'P', (byte) 'S' } ;
// set the data "HOOPS" on this segment at index 33
mySegmentKey.SetUserData(new IntPtr(33), 5, myData);
// get the user data into a ByteArray
byte[] myByteArray = new byte[100];
mySegmentKey.ShowUserData(new IntPtr(33), out myByteArray);
// get the count of the number of user data on this segment
ulong data_count = mySegmentKey.ShowUserDataCount();
// deletes the user data from index 33
mySegmentKey.UnsetUserData(new IntPtr(33));


%%%create_shell

HPS.Point[] points = { new HPS.Point(0, 0, 0), new HPS.Point(2, 0, 0), new HPS.Point(2, 2, 0), new HPS.Point(0, 2, 0),
new HPS.Point(0, 0, 2), new HPS.Point(2, 0, 2), new HPS.Point(2, 2, 2), new HPS.Point(0, 2, 2) };
int[] faceList = { 4, 0, 1, 2, 3,
4, 1, 5, 6, 2,
4, 5, 4, 7, 6,
4, 4, 0, 3, 7,
4, 3, 2, 6, 7,
4, 0, 4, 5, 1 };
mySegmentKey.InsertShell(points, faceList);


%%%set_normals

HPS.ShellKit myShellKit = new HPS.ShellKit();
// for smooth shading, set normals on vertices
myShellKit.SetVertexNormalsByRange(0, normalArray);
// if your model will be flat shaded, set normals on faces
myShellKit.SetFaceNormalsByRange(0, normalArray);
// you may also unset normals in a similar way
myShellKit.UnsetFaceNormals();


%%%hole

HPS.Point[] points = { new HPS.Point(0, 0, 0), new HPS.Point(3, 0, 0), new HPS.Point(3, 3, 0), new HPS.Point(0, 3, 0), // perimeter
new HPS.Point(1, 1, 0), new HPS.Point(2, 1, 0), new HPS.Point(2, 2, 0), new HPS.Point(1, 2, 0) }; // hole
int[] faces = { 4, 0, 1, 2, 3,
-4, 4, 5, 6, 7 }; // negated parameter indicates this face is a hole
mySegmentKey.InsertShell(points, faces);


%%%%020103_a

HPS.Point[] points = { new HPS.Point(-1, 0, 0), new HPS.Point(0, 0, 0), new HPS.Point(0, 1, 0), new HPS.Point(-1, 1, 0),
new HPS.Point( 0, 0, 0), new HPS.Point(1, 0, 0), new HPS.Point(1, 1, 0), new HPS.Point( 0, 1, 0),
new HPS.Point( 1, 0, 0), new HPS.Point(2, 0, 0), new HPS.Point(2, 1, 0), new HPS.Point( 1, 1, 0) };
int[] faces = { 4, 0, 1, 2, 3,
4, 4, 5, 6, 7,
4, 8, 9, 10, 11 };
mySegmentKey.InsertShell(points, faces);


%%%%020103_b

HPS.Point[] points = { new HPS.Point(-1, 0, 0), new HPS.Point(0, 0, 0), new HPS.Point(0, 1, 0), new HPS.Point(-1, 1, 0),
new HPS.Point( 1, 0, 0), new HPS.Point(1, 1, 0), new HPS.Point(2, 0, 0), new HPS.Point( 2, 1, 0) };
int[] faceList = { 4, 0, 1, 2, 3,
4, 1, 4, 5, 2,
4, 4, 6, 7, 5 };


%%%%020103_c

// deletes 1 face, starting at offset 1
myShellKey.EditFacelistByDeletion(1, 1);


%%%%020103_d

HPS.Point[] insertedPoints = new HPS.Point[1];
insertedPoints[0] = new HPS.Point(0.5f, 0.5f, 0);
int[] insertedFacelist = { 3, 1, 8, 2 };
myShellKey.EditPointsByInsertion(8, insertedPoints);
myShellKey.EditFacelistByInsertion(1, insertedFacelist);


%%%%020104_a

HPS.RGBAColor[] vertexColors = new HPS.RGBAColor[4];
vertexColors[0] = new HPS.RGBAColor(0, 0, 0, 1);
vertexColors[1] = new HPS.RGBAColor(0.25f, 0.75f, 0.5f, 1);
vertexColors[2] = new HPS.RGBAColor(0.75f, 0, 0, 1);
vertexColors[3] = new HPS.RGBAColor(1, 1, 1, 1);
myShellKey.SetVertexRGBAColorsByRange(0, vertexColors);


%%%%020104_b

mySegmentKey.GetVisibilityControl().SetFaces(false); // disables rendering of faces
mySegmentKey.GetVisibilityControl().SetFaces(true); // enables rendering of faces


%%%%020104_c

mySegmentKey.GetVisibilityControl().SetVertices(true).SetEdges(false).SetFaces(false);


%%%set_marker_size

mySegmentKey.GetMarkerAttributeControl().SetSize(0.25f, HPS.Marker.SizeUnits.WorldSpace);


%%%sphere_marker

PortfolioKey portfolioKey = HPS.Database.CreatePortfolio();
portfolioKey.DefineGlyph("my sphere", HPS.GlyphKit.GetDefault(Glyph.Default.Sphere));
mySegmentKey.GetPortfolioControl().Push(portfolioKey);
mySegmentKey.GetVisibilityControl().SetVertices(true);
mySegmentKey.GetVisibilityControl().SetMarkerLights(true).SetLights(true);
mySegmentKey.GetMaterialMappingControl().SetVertexColor(new RGBAColor(1, 1, 0));
mySegmentKey.GetMarkerAttributeControl().SetSymbol("my sphere").SetSize(0.75f);


%%%%020104_e

mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(1, 0, 0));


%%%shell_from_geometry

// convert a sphere to a shell
HPS.ShellKey newSphereShell = mySegmentKey.InsertShellFromGeometry(sphereKey);
// convert a cylinder to a shell
HPS.ShellKey newCylinderShell = mySegmentKey.InsertShellFromGeometry(cylinderKey);
// convert a text string to a shell
HPS.ShellKey newTextShell = mySegmentKey.InsertShellFromGeometry(textKey);


%%%%0202_a

HPS.Point[] PointArray = new HPS.Point[18];
PointArray[0] = new HPS.Point(-0.8f, 0.4f, -0.8f);
PointArray[1] = new HPS.Point(-0.8f, 0, -0.6f);
PointArray[2] = new HPS.Point(-0.8f, -0.4f, -0.4f);
PointArray[3] = new HPS.Point(-0.4f, 0.4f, -0.4f);
PointArray[4] = new HPS.Point(-0.4f, 0, -0.2f);
PointArray[5] = new HPS.Point(-0.4f, -0.4f, -0.3f);
PointArray[6] = new HPS.Point(0, 0.4f, 0.15f);
PointArray[7] = new HPS.Point(0, 0, 0.05f);
PointArray[8] = new HPS.Point(0, -0.4f, 0.05f);
PointArray[9] = new HPS.Point(0.4f, 0.4f, 0.2f);
PointArray[10] = new HPS.Point(0.4f, 0, 0.2f);
PointArray[11] = new HPS.Point(0.4f, -0.4f, 0.4f);
PointArray[12] = new HPS.Point(0.8f, 0.4f, 0.5f);
PointArray[13] = new HPS.Point(0.8f, 0, 0.3f);
PointArray[14] = new HPS.Point(0.8f, -0.4f, 0.3f);
PointArray[15] = new HPS.Point(1.2f, 0.4f, 0.3f);
PointArray[16] = new HPS.Point(1.2f, 0, 0.3f);
PointArray[17] = new HPS.Point(1.2f, -0.4f, 0.3f);
MeshKey meshKey = mySegmentKey.InsertMesh(6, 3, PointArray);


%%%mesh_normals

HPS.Vector[] normalArray = new HPS.Vector[] { new HPS.Vector(1, 0, 0),
new HPS.Vector(0.9f, 0.5f, 0.55f),
new HPS.Vector(0.8f, 0.4f, 0.4f) };
HPS.MeshKit myMeshKit = new HPS.MeshKit();
// for smooth shading, set normals on vertices
myMeshKit.SetVertexNormalsByRange(0, normalArray);
// if your model will be flat shaded, set normals on faces
myMeshKit.SetFaceNormalsByRange(0, normalArray);
// you may also unset normals in a similar way
myMeshKit.UnsetFaceNormals();


%%%%020202_a

mySegmentKey.GetVisibilityControl().SetEdges(false);
mySegmentKey.GetVisibilityControl().SetMeshQuadEdges(true);


%%%%020202_b

ulong[] faceList = new ulong[3];
faceList[0] = 5;
faceList[1] = 10;
faceList[2] = 13;
HPS.RGBColor rgbColor = new HPS.RGBColor(1, 0, 0);
meshKey.SetFaceRGBColorsByList(faceList, rgbColor);
// the same faces could also be made invisible using:
meshKey.SetFaceVisibilitiesByList(faceList, false);


%%%%0203_a

HPS.TextKit textKit = new HPS.TextKit();
textKit.SetPosition(new HPS.Point(0, 0, 0));
textKit.SetFont("verdana");
textKit.SetText("TECH SOFT 3D");
textKit.SetColor(new HPS.RGBAColor(1, 0.5f, 0));
textKit.SetSize(40, HPS.Text.SizeUnits.Pixels);
textKit.SetAlignment(HPS.Text.Alignment.Center); // aligns text horizontally relative to its insertion point
mySegmentKey.InsertText(textKit);


%%%text_region

TextKey myTextKey = mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "This is my text!");
HPS.Point[] pointArray = new HPS.Point[] { new HPS.Point(-1, 0, 0), new HPS.Point(1, 0, 0) };
bool adjust_direction = true;
bool relative_coordinates = true;
bool window_space = false;
myTextKey.SetRegion(pointArray,
adjust_direction,
relative_coordinates,
window_space);


%%%font_search

windowKey.FindFonts(out fsr);
HPS.FontSearchResultsIterator iter = fsr.GetIterator();
while (iter.IsValid())
{
HPS.FontInfoState state = iter.GetItem();
// get the name of the font
state.GetName();
iter.Next();
}


%%%%020301_a

uint width, height;
myWindowKey.GetWindowInfoControl().ShowPhysicalPixels(out width, out height);


%%%%020302_a

HPS.TextKey tk = mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "Good morning\nThis is another line");
tk.SetLineSpacing(2.0f); // doubles the default space between lines
tk.SetLineSpacing(0.5f); // halves the default space between lines


%%%%020303_a

HPS.TextKey textKey = mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "TECH SOFT 3D\nBUILD WITH THE BEST");
textKey.EditTextByDeletion(1, 6, 4); // modifying column 1, position 6, and deleting 4 chars
textKey.EditTextByInsertion(1, 6, 3, "FOR"); // inserting 3 chars into column 1, position 6


%%%%020304_a

mySegmentKey.GetTextAttributeControl().SetTransform(HPS.Text.Transform.Transformable);


%%%%020304_b

mySegmentKey.GetTextAttributeControl().SetTransform(HPS.Text.Transform.CharacterPositionOnly);


%%%%020305_a

mySegmentKey.GetTextAttributeControl().SetAlignment(HPS.Text.Alignment.BottomLeft);
mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "Tech Soft 3D");


%%%%020305_b

mySegmentKey.GetTextAttributeControl().SetAlignment(HPS.Text.Alignment.Center,
HPS.Text.ReferenceFrame.WorldAligned,
mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "Choose\nTech Soft 3D\nfor high\nperformance\ngraphics");


%%%rotated_text

HPS.TextKey textKey = mySegmentKey.InsertText(new HPS.Point(0, 0, 0), "Choose\nTech Soft 3D\nfor high\nperformance\ngraphics");
mySegmentKey.GetTextAttributeControl().SetFont("stroked");
mySegmentKey.GetTextAttributeControl().SetSize(40, HPS.Text.SizeUnits.Points);
mySegmentKey.GetModellingMatrixControl().Rotate(0, 0, 30); // text rotated 30 degrees
mySegmentKey.GetTextAttributeControl().SetTransform(HPS.Text.Transform.Transformable);


%%%%020305_d

mySegmentKey.GetTextAttributeControl().SetRotation(40);


%%%%020305_e

// allows text to be "rotated" even when not transformable
mySegmentKey.GetTextAttributeControl().SetPath(new HPS.Vector(1, 0.5f, 0));
// allows characters to be rotated with text block
mySegmentKey.GetTextAttributeControl().SetRotation(HPS.Text.Rotation.FollowPath);


%%%%020306_a

mySegmentKey.GetTextAttributeControl().SetTransform(HPS.Text.Transform.Transformable);
mySegmentKey.GetTextAttributeControl().SetGreeking(true, 6,


%%%%020307_a

String text = "TECH SOFT 3D\u2197\u2300\u21A7";
HPS.TextKey tk = mySegmentKey.InsertText(new HPS.Point(0, 0, 0), text);
mySegmentKey.GetTextAttributeControl().SetFont("ts3d");


%%%%0204_a

mySegmentKey.GetMaterialMappingControl().SetLightColor(new HPS.RGBAColor(1, 0, 1)); // changing light color to purple


%%%%020401_a

HPS.SpotlightKit spotlightKit = new HPS.SpotlightKit();
spotlightKit.SetCameraRelative(false)
.SetPosition(new HPS.Point(20, 40, 0))
.SetTarget(new HPS.Point(0, 0, 0))
.SetInnerCone(20, HPS.Spotlight.InnerConeUnits.Degrees)
HPS.SpotlightKey spotlightKey = mySegmentKey.InsertSpotlight(spotlightKit);


%%%%020402_a

mySegmentKey.InsertDistantLight(new HPS.Vector(x, y, z));


%%%camera_relative_lights

spotlightKey.SetCameraRelative(true);
distantLightKey.SetCameraRelative(true);


%%%%0205_a

HPS.Point[] pointArray = new HPS.Point[3];
// the points specified are the endpoints of the line segments
pointArray[0] = new HPS.Point(0, 0, 0);
pointArray[1] = new HPS.Point(0, 1, 0);
pointArray[2] = new HPS.Point(1, 0, 0);
// inserts a line according to the points contained in pointArray
mySegmentKey.InsertLine(pointArray);


%%%%0205_b

mySegmentKey.GetLineAttributeControl().SetWeight(2.0f);


%%%ray

rayKit.SetFirst(new HPS.Point(0, 0.5f, 0));
rayKit.SetSecond(new HPS.Point(1, 0.5f, 0));
mySegmentKey.InsertInfiniteLine(rayKit);


%%%editing_lines

// declare point array to hold edited points
HPS.Point[] editedPoints = new HPS.Point[1];
// declare the new point
editedPoints[0] = new HPS.Point(0, 0.5f, 0);
// this is the actual modification
myLineKey.EditPointsByReplacement(0, editedPoints);
// this is the insertion of the new point
myLineKey.EditPointsByInsertion(3, editedPoints);


%%%insert_nurbs_surface

HPS.Point[] pointArray = new HPS.Point[1000];
int index = 0;
for (int j = 0; j < 10; j++) // width in z direction
{
for (float i = 0; i < 10; i += 0.1f) // height and length
{
pointArray[index++] = new HPS.Point(i, (float)Math.Sin(i), (float)j);
}
}
nsk.SetPoints(pointArray);
nsk.SetUCount(10);
nsk.SetVCount(100);
nsk.SetUDegree(3);
nsk.SetVDegree(3);
mySegmentKey.InsertNURBSSurface(nsk);


%%%nst_step1

HPS.Point[] linePoints = new HPS.Point[3];
linePoints[0] = new HPS.Point(0.35f, 0.3f, 0);
linePoints[1] = new HPS.Point(0.70f, 0.3f, 0);
linePoints[2] = new HPS.Point(0.5f, 0.7f, 0);


%%%nst_step2

HPS.LineKit lineKit = new HPS.LineKit();
lineKit.SetPoints(linePoints);
HPS.TrimElement trimElement = new HPS.TrimElement();
trimElement.SetCurve(lineKit);


%%%nst_step3

HPS.TrimElement[] trimElementArray = new HPS.TrimElement[1];
trimElementArray[0] = trimElement;


%%%nst_step4

HPS.TrimKit trimKit = new HPS.TrimKit();
trimKit.SetOperation(HPS.Trim.Operation.Remove);
trimKit.SetShape(trimElementArray);


%%%nst_step5

HPS.TrimKit[] trimKitArray = new HPS.TrimKit[1];
trimKitArray[0] = trimKit;


%%%nst_step6

nurbsSurfaceKit.SetTrims(trimKitArray);
mySegmentKey.InsertNURBSSurface(nurbsSurfaceKit);


%%%end_caps_joins

lpok.SetEndCap("solid_circle");
lpok.SetStartCap("circle");
mySegmentKey.GetLineAttributeControl().SetPattern("solid", lpok);


%%%infinite_line

ilk.SetFirst(new Point(0, 0, 0));
ilk.SetSecond(new Point(1, 1, 0));
mySegmentKey.InsertInfiniteLine(ilk);


%%%%020601_a

HPS.CircleKit circleKit = new HPS.CircleKit();
// setting the attributes on the kit
circleKit.SetCenter(new HPS.Point(0, 0, 0));
circleKit.SetNormal(new HPS.Vector(0, 0, 1));
circleKit.SetRadius(0.75f);
// inserting circle into the database
HPS.CircleKey circleKey = mySegmentKey.InsertCircle(circleKit);


%%%%020602_a

mySegmentKey.InsertCircularArc(new HPS.Point(-0.5f, -0.5f, 0),
new HPS.Point(0, 0.75f, 0),
new HPS.Point(0.25f, 0.5f, 0));


%%%%020603_a

mySegmentKey.InsertCircularWedge(new HPS.Point(-0.5f, -0.5f, 0),
new HPS.Point(0, 0.75f, 0),
new HPS.Point(0.25f, 0.5f, 0));


%%%%020604_a

HPS.EllipseKit ellipseKit = new HPS.EllipseKit();
ellipseKit.SetCenter(new HPS.Point(0, 0, 0));
ellipseKit.SetMajor(new HPS.Point(0.75f, 0, 0)); // major axis
ellipseKit.SetMinor(new HPS.Point(0, 0.5f, 0)); // minor axis
mySegmentKey.InsertEllipse(ellipseKit);


%%%%020605_a

HPS.EllipticalArcKit ellipticalArcKit = new HPS.EllipticalArcKit();
ellipticalArcKit.SetCenter(new HPS.Point(0, 0, 0));
ellipticalArcKit.SetMajor(new HPS.Point(0.75f, 0, 0)); // major axis
ellipticalArcKit.SetMinor(new HPS.Point(0, 0.5f, 0)); // minor axis
ellipticalArcKit.SetStart(0.0f);
ellipticalArcKit.SetEnd(0.75f); // retained portion of ellipse ends at 75%
mySegmentKey.InsertEllipticalArc(ellipticalArcKit);


%%%%0207_a

// set the marker symbol (optional)
mySegmentKey.GetMarkerAttributeControl().SetSymbol("myMarkerName");
// insert a marker at the origin
mySegmentKey.InsertMarker(new Point(0, 0, 0));


%%%%020701_a

// since markers are segment-level attributes, the size examples below must go in different segments
HPS.SegmentKey segKey1 = mySegmentKey.Down("marker1", true);
HPS.SegmentKey segKey2 = mySegmentKey.Down("marker2", true);
HPS.SegmentKey segKey3 = mySegmentKey.Down("marker3", true);
// if second parameter to SetSize is omitted, the marker is scaled relative to its default size
segKey1.GetMarkerAttributeControl().SetSize(5).SetDrawingPreference(Marker.DrawingPreference.Fastest);
HPS.MarkerKey markerKey1 = segKey1.InsertMarker(new HPS.Point(0, 0.35f, 0));
// marker2 is 10 pixels in size
segKey2.GetMarkerAttributeControl().SetSize(10, HPS.Marker.SizeUnits.Pixels).SetDrawingPreference(Marker.DrawingPreference.Fastest);
HPS.MarkerKey markerKey2 = segKey2.InsertMarker(new HPS.Point(0, 0, 0));
// marker3 is 0.1 world space units in size
segKey3.GetMarkerAttributeControl().SetSize(0.1f, HPS.Marker.SizeUnits.WorldSpace).SetDrawingPreference(Marker.DrawingPreference.Fastest);
MarkerKey markerKey3 = segKey3.InsertMarker(new HPS.Point(0, -0.35f, 0));


%%%%020702_a

// ... continuing from the above example
markerKey2.SetPoint(new HPS.Point(-0.25f, 0, 0));
// delete a marker
someOtherMarkerKey.Delete();


%%%%020703_a

mySegmentKey.GetVisibilityControl().SetMarkers(false); // turn off markers
mySegmentKey.GetVisibilityControl().SetMarkers(true); // turn on markers
// sets marker color to red
mySegmentKey.GetMaterialMappingControl().SetMarkerColor(new HPS.RGBAColor(1, 0, 0));


%%%%0209_a

HPS.Point[] pointArray = new HPS.Point[5]; // a PointArray is a typedef'd STL vector
// specify points
pointArray[0] = new HPS.Point(0.15f, 0.25f, 0);
pointArray[1] = new HPS.Point(-0.35f, 0.35f, 0);
pointArray[2] = new HPS.Point(-0.65f, 0, 0);
pointArray[3] = new HPS.Point(-0.35f, -0.4f, 0);
pointArray[4] = new HPS.Point(0.15f, -0.15f, 0);
HPS.PolygonKey polygonKey = mySegmentKey.InsertPolygon(pointArray);


%%%%0209_b

mySegmentKey.GetVisibilityControl().SetFaces(true);
mySegmentKey.GetEdgeAttributeControl().SetWeight(2);
mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0, 0, 0));
mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.32f, 0.78f, 0.95f));


%%%%0209_c

// reassign the first point
editedPoints[0] = new HPS.Point(-0.35f, 0.65f, 0);
// replacing point at offset 1
polygonKey.EditPointsByReplacement(1, editedPoints);
// deleting point at offset 3
polygonKey.EditPointsByDeletion(3, 1);
// inserting a new HPS.Point at offset 4
editedPoints[0] = new HPS.Point(0.25f, 0, 0);
polygonKey.EditPointsByInsertion(4, editedPoints);
// to get a list of all the points in the polygon, use ShowPoints
polygonKey.ShowPoints(out editedPoints);


%%%%0210_a

HPS.SphereKit sphereKit = new HPS.SphereKit();
sphereKit.SetCenter(new HPS.Point(0, 0, 0));
sphereKit.SetRadius(0.5f);
sphereKit.SetBasis(new HPS.Vector(0, 1, 0), new HPS.Vector(1, 0, 0)); // basis includes 'axis'
// and 'up' vectors as params
mySegmentKey.InsertSphere(sphereKit);


%%%%0210_b

mySegmentKey.GetSphereAttributeControl().SetTessellation(50);


%%%%0211_a

HPS.CylinderKey cylinderKey = mySegmentKey.InsertCylinder(
new HPS.Point(0.5f, 0.5f, 1), // first point
new HPS.Point(-0.75f, -0.5f, -1), // second point
0.55f, // radius
HPS.Cylinder.Capping.Both); // capping enum


%%%%021101_a

HPS.Point[] endPoints = { new HPS.Point(0, 0.5f, 0), new HPS.Point(0, 0, 0) }; // location of end points
float[] radii = { 0.5f, 0 }; // the radius of the sphere at each end point
HPS.CylinderKit cylinderKit = new HPS.CylinderKit();
cylinderKit.SetPoints(endPoints);
cylinderKit.SetRadii(radii);
cylinderKit.SetCaps(HPS.Cylinder.Capping.Both);
mySegmentKey.InsertCylinder(cylinderKit);


%%%%021102_a

HPS.Point[] points = new HPS.Point[65];
float[] radius = { 0.25f };
for (int i = 0; i < 64; i++) {
/* Calculating points for the torus*/
float angle = 2.0f * 3.1415926536f * i / 64.0f;
float x = 0;
float y = (float) Math.Cos(angle);
float z = (float) Math.Sin(angle) - 1.5f;
points[i] = new Point(x, y, z);
}
points[64] = points[0];
mySegmentKey.InsertCylinder(points, radius, HPS.Cylinder.Capping.Both);


%%%%021102_b

float[] radii = { 0.25f, 0.3f };
// ...
// don't forget to also specify the new array length to InsertCylinder
mySegmentKey.InsertCylinder(points, radii, HPS.Cylinder.Capping.Both);


%%%%021102_c

mySegmentKey.GetCylinderAttributeControl().SetTessellation(40);


%%%%021102_d

float[] radius = { 0 };
Point[] points = { new HPS.Point(-0.5f, -0.5f, 0), new HPS.Point(0.5f, -0.5f, 0), new HPS.Point(0.5f, 0.5f, 0),
new HPS.Point(-0.5f, 0.5f, 0), new HPS.Point(-0.5f, 0, 0) };
RGBColor[] rgbColorArray = new HPS.RGBColor[5];
rgbColorArray[0] = new HPS.RGBColor(1, 0, 0);
rgbColorArray[1] = new HPS.RGBColor(1, 0.5f, 0);
rgbColorArray[2] = new HPS.RGBColor(1, 0, 1);
rgbColorArray[3] = new HPS.RGBColor(0, 1, 1);
rgbColorArray[4] = new HPS.RGBColor(0, 1, 0);
HPS.CylinderKey ck = mySegmentKey.InsertCylinder(points, radius);
ck.SetVertexRGBColorsByRange(0, rgbColorArray, HPS.Cylinder.Component.Faces);


%%%%021201_a

Point[] pointArray = { new HPS.Point(-1.75f, -1.75f, 0), new HPS.Point(-0.75f, -0.75f, 0), new HPS.Point(-0.5f, 0.5f, 0),
new HPS.Point( 0, -0.5f, 0), new HPS.Point( 0.5f, 0.75f, 0), new HPS.Point( 0.75f, 0, 0),
new HPS.Point( 2.75f, -1.5f, 0) };
float[] knotArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
float[] weightArray = { 1, 0.7f, 1, 0.5f, 1, 0.8f, 1 };
nck.SetPoints(pointArray);
nck.SetKnots(knotArray);
nck.SetWeights(weightArray);
nck.SetDegree(2);
nck.SetParameters(0, 1);
// enabling view-dependent tesselation
mySegmentKey.GetCurveAttributeControl().SetViewDependent(true);
HPS.NURBSCurveKey nurbsKey = mySegmentKey.InsertNURBSCurve(nck);


%%%%021201_b

float[] newKnots = { 3.5f, 4.5f };
nurbsKey.EditKnotsByReplacement(3, newKnots);
HPS.Point[] newPoints = { new HPS.Point(-2.5f, -1.5f, -0.5f), new HPS.Point(-1.0f, -0.5f, 0.5f) };
nurbsKey.EditPointsByReplacement(0, newPoints);
float[] newWeights = { 0.3f };
nurbsKey.EditWeightsByReplacement(5, newWeights);


%%%%021202_a

Point[] points = { new HPS.Point(3, 1, 0), new HPS.Point(1, 1, 0), new HPS.Point(0, 2, 0), new HPS.Point(-2, 2, 0), new HPS.Point(-2, 3, 0),
new HPS.Point(3, 1, 1), new HPS.Point(1, 1, 1), new HPS.Point(0, 2, 1), new HPS.Point(-2, 2, 1), new HPS.Point(-2, 3, 1),
new HPS.Point(3, -1, 2), new HPS.Point(1, -1, 2), new HPS.Point(0, 0, 2), new HPS.Point(-2, 0, 2), new HPS.Point(-2, 1, 2),
new HPS.Point(3, -1, 3), new HPS.Point(1, -1, 3), new HPS.Point(0, 0, 3), new HPS.Point(-2, 0, 3), new HPS.Point(-2, 1, 3),
new HPS.Point(3, 0, 4), new HPS.Point(1, 0, 4), new HPS.Point(0,-1, 4), new HPS.Point(-2, -1, 4), new HPS.Point(-2, 2, 4) };
float[] weights = { 1, 1, 1, 1, 1, 1, 0.5f, 0.5f, 0.5f, 1, 1, 0.5f, 0.5f,
0.5f, 1, 1, 0.5f, 0.5f, 0.5f, 1, 1, 1, 1, 1, 1 };
float[] uKnots = { 0, 0, 0, 1, 2, 3, 4, 4, 4 };
float[] vKnots = { 0, 0, 0, 1, 2, 3, 4, 4, 4 };
nsk.SetPoints(points);
nsk.SetWeights(weights);
nsk.SetUKnots(uKnots);
nsk.SetVKnots(vKnots);
nsk.SetUCount(5);
nsk.SetVCount(5);
nsk.SetUDegree(3);
nsk.SetVDegree(3);
mySegmentKey.InsertNURBSSurface(nsk);


%%%insert_cutting_section

// cut edges enabled
mySegmentKey.GetVisibilityControl().SetCutEdges(true);
// cut edges set to red
mySegmentKey.GetMaterialMappingControl().SetCutEdgeColor(new HPS.RGBAColor(1, 0, 0));
// cut plane is 0.42 units from the origin
mySegmentKey.InsertCuttingSection(new Plane(0, 1, 0, -0.42f));


%%%capping_plane

csk.SetVisualization(HPS.CuttingSection.Mode.Square, new HPS.RGBAColor(0.25f, 0.25f, 0.25f, 0.25f));
csk.SetPlanes(new HPS.Plane(0, 1, 0, -0.42f));
mySegmentKey.InsertCuttingSection(csk);


%%%capping_geometry

mySegmentKey.GetVisibilityControl().SetCutFaces(true); // make cut faces visible
mySegmentKey.GetMaterialMappingControl().SetCutFaceColor(new HPS.RGBAColor(0.5f, 0, 0));


%%%multiple_sections

HPS.Plane[] planeArray = new Plane[2];
planeArray[0] = new Plane(0, 1, 0, -0.1f);
planeArray[1] = new Plane(-1, 0, 0, 0);
csk.SetPlanes(planeArray);
mySegmentKey.InsertCuttingSection(csk);


%%%cutting_sections_gather

// enable visibility of cut geometry
myWindowKey.GetVisibilityControl().SetCutGeometry(true);
// set the cutting depth for cutting section
myWindowKey.GetCuttingSectionAttributeControl()
.SetCappingLevel(HPS.CuttingSection.CappingLevel.Segment)
.SetCuttingLevel(HPS.CuttingSection.CuttingLevel.Global);
// insert cutting section
HPS.CuttingSectionKey cutterKey = myWindowKey.InsertCuttingSection(new HPS.Plane(new HPS.Vector(1, 0, 0)));
// set gather depth
//build path to window
HPS.KeyPath path = new HPS.KeyPath();
path.Append(myWindowKey);
// put cut geometry into subsegment called "caps"
ulong cap_count = path.GatherCutGeometry(myWindowKey.Subsegment("caps"), opt);
// delete model to leave just the caps in place (optional)
myWindowKey.Subsegment("model").Delete();


%%%reference_geometry

// setting up the geometry that will be duplicated
HPS.ShellKey shellKey = isolatedSegment.InsertShell(shellKit);
// ...
// importing a copy of the geometry into 'mySegmentKey'
HPS.ReferenceKey refKey = mySegmentKey.ReferenceGeometry(shellKey);
refKey.SetModellingMatrix(matrixKit);
// remove the reference
refKey.Delete();


%%%text_extents

float out_xfrac, out_yfrac;
myKeyPath.ComputeTextExtent("My text string...", out out_xfrac, out out_yfrac);


%%%set_face_rgb_by_range

myShellKey.SetFaceRGBColorsByRange(0, 3, new HPS.RGBColor(1, 0.5f, 0));


%%%set_face_vis_by_range

myShellKey.SetFaceVisibilitiesByRange(0, 3, false);


%%%level

// set a local cutting section
mySegmentKey.GetCuttingSectionAttributeControl().SetCuttingLevel(HPS.CuttingSection.CuttingLevel.Local);
// set a global cutting section
mySegmentKey.GetCuttingSectionAttributeControl().SetCuttingLevel(HPS.CuttingSection.CuttingLevel.Global);


%%%csak


%%%optimize_shell


%%%simple

// the ShellRelationOptionsKit is setup for a surface test
srok.SetTest(HPS.Shell.RelationTest.Simple);
// perform the test
myShellKey.ComputeRelation(pointArray, srok, out srrk);
srrk.ShowRelations(out shellRelationArray);
// iterate over each result
for (int i = 0; i < shellRelationArray.size(); i++)
{
HPS.Shell.Relation relation = shellRelationArray[i];
if (relation == HPS.Shell.Relation.On)
{
// this point is on the surface of the shell
}
else if (relation == HPS.Shell.Relation.Off)
{
// this point is not on the surface of the shell
}
}


%%%enclosure

// here are the points we are testing against
HPS.Point[] pointArray = new HPS.Point[3];
pointArray[0] = new HPS.Point(0, 0, 0);
pointArray[1] = new HPS.Point(1, 0, 0);
pointArray[2] = new HPS.Point(0, 2, 0);
// the ShellRelationOptionsKit is setup for an enclosure test
srok.SetTest(HPS.Shell.RelationTest.Enclosure);
// specify an optional TreeContext
HPS.TreeContext treeContext = new HPS.TreeContext();
srok.SetTreeContext(treeContext);
// the ShellRelationResultsKit will contain the results of the computation
// this line performs the actual test
myShellKey.ComputeRelation(pointArray, srok, out srrk);
// we sent in 3 points, so our result set will have 3 results
float[] floatArray = new float[3];
HPS.Shell.Relation[] shellRelationArray = new HPS.Shell.Relation[3];
srrk.ShowRelations(out shellRelationArray);
// iterate over each result
for (int i = 0; i < shellRelationArray.size(); i++)
{
HPS.Shell.Relation relation = shellRelationArray[i];
if (relation == HPS.Shell.Relation.In)
{
// this point is inside the shell
}
else if (relation == HPS.Shell.Relation.Out)
{
// this point is outside the shell
}
else if (relation == HPS.Shell.Relation.On)
{
// this point is on the surface of the shell
}
}


%%%distance

// the ShellRelationOptionsKit is setup for a distance test
srok.SetTest(HPS.Shell.RelationTest.Distance);
// perform the test
myShellKey.ComputeRelation(pointArray, srok, out srrk);
// get results
srrk.ShowDistances(out floatArray);
// iterate over each result
for (int i = 0; i < floatArray.size(); i++)
{
// get distance for each point
float distance = floatArray[i];
}


%%%%0301_a

mySegmentKey.GetDrawingAttributeControl().SetWorldHandedness(HPS.Drawing.Handedness.Left);


%%%%030101_a

HPS.Point windowPoint = new HPS.Point(-1, -1, 0);
HPS.Point worldPoint;
windowKey.ConvertCoordinate(HPS.Coordinate.Space.Window, windowPoint, HPS.Coordinate.Space.World, out worldPoint);


%%%%030102_a

// set the segment's matrix
mySegmentKey.SetModellingMatrix(matrixKit);
// multiply the segment's matrix with another matrix
mySegmentKey.GetModellingMatrixControl().Concatenate(matrixKit);
// get the segment's matrix into a kit
mySegmentKey.ShowModellingMatrix(out matrixKit);
// perform a rotation (in degrees) on the segment's current matrix
mySegmentKey.GetModellingMatrixControl().Rotate(10, 50, 90);
// an individual element in a matrix can also be set as follows:
mySegmentKey.GetModellingMatrixControl().SetElement(1, 3, -5);
// unsetting the matrix
mySegmentKey.UnsetModellingMatrix();


%%%%0302_a

// setting the camera using the CameraControl and chaining
mySegment.GetCameraControl().SetUpVector(new HPS.Vector(0, 1, 0)).SetPosition(new HPS.Point(0, -10, 0))
.SetTarget(new HPS.Point(0, 0, 0)).SetField(4, 4)
.SetProjection(HPS.Camera.Projection.Perspective);
// alternatively, the same operation can be done with a CameraKit
HPS.CameraKit cameraKit = new HPS.CameraKit();
cameraKit.SetUpVector(new HPS.Vector(0, 1, 0));
cameraKit.SetPosition(new HPS.Point(0, -10, 0));
cameraKit.SetTarget(new HPS.Point(0, 0, 0));
cameraKit.SetField(4, 4);
cameraKit.SetProjection(HPS.Camera.Projection.Perspective);
mySegmentKey.SetCamera(cameraKit);


%%%camera_components_a

// getting all components of the camera into a kit
HPS.CameraKit cameraKit = new HPS.CameraKit();
mySegmentKey.ShowCamera(out cameraKit);
// subsequently getting one component, position, from the kit
HPS.Point position = new HPS.Point();
cameraKit.ShowPosition(out position);
// alternatively, if you only need one component, it may be more convenient to use:
mySegmentKey.GetCameraControl().ShowPosition(out position);


%%%set_field

mySegmentKey.GetCameraControl().SetField(5, 5);


%%%set_near_limit

mySegmentKey.GetCameraControl().SetNearLimit(0.1f);


%%%aspect_ratio


%%%zoom_dolly

mySegmentKey.GetCameraControl().Zoom(2.0f); // zoom
mySegmentKey.GetCameraControl().Dolly(0.5f, 0.25f, 0); // dolly


%%%orbit

mySegmentKey.GetCameraControl().Orbit(90.0f, 0);


%%%pan

mySegmentKey.GetCameraControl().Pan(0, 90.0f);


%%%roll

mySegmentKey.GetCameraControl().Roll(180.0f);


%%%transformMasks

// disable scale and translation
axisSegment.GetTransformMaskControl().SetCameraScale(true).SetCameraTranslation(true);


%%%set_orthgraphic

// 15 is the skew angle
mySegmentKey.GetCameraControl().SetProjection(HPS.Camera.Projection.Orthographic, 15, 15);


%%%oblique_perspective

// the projection is made oblique by setting the two skew parameters after the "Perspective" enum
mySegmentKey.GetCameraControl().SetProjection(HPS.Camera.Projection.Perspective, 21.8f, -21.8f);


%%%stretched_projection

cameraKit.SetProjection(HPS.Camera.Projection.Stretched);
mySegmentKey.SetCamera(cameraKit);


%%%border

HPS.SegmentKey borderKey = windowKey.Subsegment();
HPS.Point[] pointArray = new HPS.Point[5];
pointArray[0] = new HPS.Point(-1, -1, 0);
pointArray[1] = new HPS.Point(1, -1, 0);
pointArray[2] = new HPS.Point(1, 1, 0);
pointArray[3] = new HPS.Point(-1, 1, 0);
pointArray[4] = new HPS.Point(-1, -1, 0);
borderKey.InsertLine(pointArray);
borderKey.GetLineAttributeControl().SetWeight(6.0f);


%%%%030206_a

// the projection is made oblique by setting the two skew parameters after the "Perspective" enum
mySegmentKey.GetCameraControl().SetProjection(HPS.Camera.Projection.Perspective, 21.8f, -21.8f);


%%%%030206_b

cameraKit.SetProjection(HPS.Camera.Projection.Stretched);
mySegmentKey.SetCamera(cameraKit);


%%%%030206_c

HPS.SegmentKey borderKey = windowKey.Subsegment();
HPS.Point[] pointArray = new HPS.Point[5];
pointArray[0] = new HPS.Point(-1, -1, 0);
pointArray[1] = new HPS.Point(1, -1, 0);
pointArray[2] = new HPS.Point(1, 1, 0);
pointArray[3] = new HPS.Point(-1, 1, 0);
pointArray[4] = new HPS.Point(-1, -1, 0);
borderKey.InsertLine(pointArray);
borderKey.GetLineAttributeControl().SetWeight(6.0f);


%%%%0303_a

HPS.SubwindowKit subwindowKit = new HPS.SubwindowKit();
subwindowKit.SetSubwindow(new HPS.Rectangle(0.4f, 0.95f, -0.5f, 0), HPS.Subwindow.Type.Standard);
HPS.SegmentKey anotherSegmentKey = mySegmentKey.Down("subwindow", true);
anotherSegmentKey.SetSubwindow(subwindowKit);
// insert geometry and set attrubutes on 'subwindowKey' segment as you normally would


%%%%0303_b

subwindowKit.SetSubwindow(new HPS.Rectangle(0.4f, 0.95f, -0.5f, 0), HPS.Subwindow.Type.Lightweight);


%%%%0303_c

// dividing the main window into two subwindows
subwindowKit.SetSubwindow(new HPS.Rectangle(-1, 0, -1, 1), HPS.Subwindow.Type.Standard);
HPS.SegmentKey leftSubwindowSeg = mySegmentKey.Down("left", true);
leftSubwindowSeg.SetSubwindow(subwindowKit);
subwindowKit.SetSubwindow(new HPS.Rectangle(0, 1, -1, 1), HPS.Subwindow.Type.Standard);
HPS.SegmentKey rightSubwindowSeg = mySegmentKey.Down("right", true);
rightSubwindowSeg.SetSubwindow(subwindowKit);


%%%%0303_d

subwindowKit.SetBorder(HPS.Subwindow.Border.InsetBold);
subwindowKit.SetBackground(HPS.Subwindow.Background.Transparent);


%%%%0303_e

mySegmentKey.SetPriority(5);


%%%create_core_step1


%%%create_core_step2

canvas.AttachLayout(layout);
layout.AttachViewFront(view1, new HPS.Rectangle(-1, 0, -1, 1)); // left view
layout.AttachViewFront(view2, new HPS.Rectangle( 0, 1, -1, 1)); // right view
view1.AttachModel(model);
view2.AttachModel(model);


%%%create_core_step3

HPS.SegmentKey modelSegmentKey = model.GetSegmentKey();
HPS.ShellKey shellKey = modelSegmentKey.InsertShell(myShellKit);


%%%create_core_step4

HPS.SegmentKey viewSegmentKey = view.GetSegmentKey();
viewSegmentKey.GetVisibilityControl().SetText(false);
viewSegmentKey.SetCamera(cameraKit);
modelSegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.81f, 0.72f, 0.08f));
modelSegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0, 0, 0));
modelSegmentKey.GetVisibilityControl().SetEdges(true);


%%%using_canvas

canvas.AttachViewAsLayout(view);


%%%fixed_framerate

// sets the framerate, hard extents, and deferral size
canvas.SetFrameRate(20.0f);
windowKey.GetCullingControl().SetDeferralExtent(100);
windowKey.GetCullingControl().SetExtent(10);


%%%using_layout

// HPS.Rectangle constructor parameters are left, right, bottom, top
myLayout.AttachViewFront(view, new HPS.Rectangle(0, 1, -1, 0));


%%%using_view

// sets geometry to wireframe
view.SetRenderingMode(HPS.Rendering.Mode.Wireframe);
// geometry rendered with Phong lighting
view.SetRenderingMode(HPS.Rendering.Mode.Phong);
// geometry rendered with hidden lines
view.SetRenderingMode(HPS.Rendering.Mode.HiddenLine);


%%%fit_world

// adjusts the camera to the scene extents and redraws the scene
view.FitWorld();


%%%axis_navcube

// enable axis triad
myView.GetAxisTriadControl().SetVisibility(true).SetLocation(HPS.AxisTriadControl.Location.BottomRight);
// enable navigation cube
myView.GetNavigationCubeControl().SetVisibility(true).SetLocation(HPS.NavigationCubeControl.Location.BottomLeft);


%%%nav_aid_set_location

myView.GetNavigationCubeControl()
.SetLocation(HPS.NavigationCubeControl.Location.Custom,
new HPS.Rectangle(-0.5f, 0.5f, -0.5f, 0.5f));


%%%complex_clip_regions

HPS.Point[] loop1 = new HPS.Point[] { new HPS.Point(0, 0, 0),
new HPS.Point(1, 0, 0),
new HPS.Point(1, 1, 0),
new HPS.Point(0, 1, 0) };
HPS.Point[] loop2 = new HPS.Point[] { new HPS.Point(0.25f, 0.25f, 0),
new HPS.Point(-0.75f, 0.25f, 0),
new HPS.Point(-0.75f, -0.75f, 0),
new HPS.Point(0.25f, -0.75f, 0) };
HPS.Point[][] loops = new HPS.Point[][] { loop1, loop2 };
mySegmentKey.GetDrawingAttributeControl().SetClipRegion(loops, HPS.Drawing.ClipSpace.World, HPS.Drawing.ClipOperation.Remove);


%%%clip_regions

mySegmentKey.InsertSphere(new HPS.Point(0, 0, 0), 2.0f);
mySegmentKey.GetVisibilityControl().SetEdges(true);
HPS.Point[] pointArray = new Point[3];
pointArray[0] = new HPS.Point(10, 10, 0);
pointArray[1] = new HPS.Point(-10, 10, 0);
pointArray[2] = new HPS.Point(-10, -10, 0);
mySegmentKey.GetDrawingAttributeControl().SetClipRegion(
pointArray, HPS.Drawing.ClipSpace.World, HPS.Drawing.ClipOperation.Keep);


%%%portfolios_introduction

mySegmentKey.GetPortfolioControl().Push(myPortfolio);


%%%example_definitions

myPortfolio.DefineLinePattern("dashedLine", myLinePatternKit); // defines a line pattern
myPortfolio.DefineShader("superShader", myShaderKit); // defines a shader
myPortfolio.DefineNamedStyle("custom style", HPS.Database.CreateRootSegment()); // defines a style
myPortfolio.UndefineTexture("roughTexture"); // undefines a texture


%%%import_all

// imports all resources from 'otherPortfolio'
myPortfolio.ImportPortfolio(otherPortfolio);
// imports all textures from 'otherPortfolio'
myPortfolio.ImportAllTextures(otherPortfolio);
// imports a single glyph
myPortfolio.ImportGlyph(someGlyph);


%%%import_all_replace

myPortfolio.ImportAllTextures(otherPortfolio, true); // replaces existing definitions
myPortfolio.ImportAllTextures(otherPortfolio, false); // does not replace existing definitions


%%%style_segment

// setup the attributes on 'styleSegment'
styleSegment.GetVisibilityControl().SetFaces(false).SetEdges(true);
styleSegment.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0, 1, 0));
// 'anotherSegment' uses the style from 'styleSegment'
anotherSegment.GetStyleControl().PushSegment(styleSegment);


%%%unset_style

// pops a style off the stack
mySegmentKey.GetStyleControl().Pop();
// removes the style stack and replaces it with the new style
mySegmentKey.GetStyleControl().SetNamed("newStyle");
// unsets all styles on this segment
mySegmentKey.GetStyleControl().UnsetEverything();


%%%create_named_style

HPS.NamedStyleDefinition wire_style = myPortfolio.DefineNamedStyle("green wireframe", HPS.Database.CreateRootSegment());
wire_style.GetSource().GetVisibilityControl().SetFaces(false).SetEdges(true);
wire_style.GetSource().GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0.0f, 1.0f, 0.0f));
mySegmentKey.GetPortfolioControl().Push(myPortfolio);
mySegmentKey.GetStyleControl().PushNamed("green wireframe");


%%%simple_condition

// will be applied only if condition1 is satisfied
mySegmentKey.GetStyleControl().SetNamed("glossy red", condition1);
// setting the "c1" condition will enable this segment's style
mySegmentKey.SetCondition("c1");


%%%multiple_conditions

String[] conditionArray = new String[2];
conditionArray[0] = "c1";
conditionArray[1] = "c3";
mySegmentKey.SetConditions(conditionArray); // sets "c1" and "c3"


%%%complex_condition

HPS.ConditionalExpression complexOR = HPS.ConditionalExpression.OR(condition1, condition2);
HPS.ConditionalExpression complexAND = HPS.ConditionalExpression.AND(complexOR, condition3);
mySegmentKey.GetStyleControl().SetNamed("myStyle", complexAND);


%%%push_style

mySegmentKey.GetStyleControl().PushNamed("myStyle");


%%%edit_stack

String[] styleNames = new String[3];
mySegmentKey.GetStyleControl().ShowAllNamed(out styleNames, out conditions);
String[] newStyleNames = new String[2];
newStyleNames[0] = styleNames[0];
newStyleNames[1] = styleNames[2];
HPS.Style.Type[] styleTypesArray = new HPS.Style.Type[2];
styleTypesArray[0] = HPS.Style.Type.Named;
styleTypesArray[1] = HPS.Style.Type.Named;
HPS.SegmentKey[] segmentKeyArray = new HPS.SegmentKey[2];
HPS.PortfolioKey[] portfolioKeyArray = new HPS.PortfolioKey[2];
mySegmentKey.GetStyleControl().Set(styleTypesArray, segmentKeyArray, newStyleNames, conditions);


%%%define_image

try
{
HPS.ImageKit imageKit = HPS.Image.File.Import(filename, iok);
ImageDefinition imageDefinition = myPortfolio.DefineImage("my_image", imageKit);
}
catch (HPS.IOException ioe)
{
String problem = ioe.what(); // shows cause of the exception
}


%%%manual_define_image

HPS.ImageKit imageKit = new HPS.ImageKit();
imageKit.SetData(image_data);
imageKit.SetSize(512, 512); // the dimensions of the image
imageKit.SetFormat(HPS.Image.Format.RGB); // the format tells HPS how to interpret the raw data


%%%basic_glyph_usage

// CircleWithCircle is the internal name of the predefined glyph
HPS.GlyphKit myGlyphKit = HPS.GlyphKit.GetDefault(HPS.Glyph.Default.CircleWithCircle);
// you must name the glyph so it can be referenced later
myPortfolio.DefineGlyph("circle in a circle", myGlyphKit);
mySegmentKey.GetPortfolioControl().Push(myPortfolio);
mySegmentKey.GetMarkerAttributeControl().SetSymbol("circle in a circle");
mySegmentKey.InsertMarker(new HPS.Point(0, 0, 0));


%%%defining_glyphs_step1

HPS.SegmentKey mySegmentKey = parentKey.Down("glyph", true);
HPS.GlyphKit glyphKit = new HPS.GlyphKit();


%%%defining_glyphs_step2

glyphKit.SetRadius(100);
glyphKit.SetOffset(new HPS.GlyphPoint(0, 0));


%%%defining_glyphs_step3

HPS.GlyphPoint[] glyphPoints = { new HPS.GlyphPoint(-100, -100), new HPS.GlyphPoint(-100, 100),
new HPS.GlyphPoint(100, -100), new HPS.GlyphPoint(100, 100),
new HPS.GlyphPoint(-100, -100) };
HPS.LineGlyphElement lineGlyphElement = new HPS.LineGlyphElement();
lineGlyphElement.SetPoints(glyphPoints);
lineGlyphElement.SetExplicitColor(new HPS.RGBAColor(1, 0, 0)); // color will be red


%%%defining_glyphs_step4

HPS.GlyphElement[] gea = { lineGlyphElement };
glyphKit.SetElements(gea);


%%%defining_glyphs_step5

// create portfolio if one does not already exist
// glyph is named "myCustomGlyph"
myPortfolio.DefineGlyph("myCustomGlyph", glyphKit);
mySegmentKey.GetPortfolioControl().Push(myPortfolio);


%%%defining_glyphs_step6

mySegmentKey.GetMarkerAttributeControl().SetSymbol("myCustomGlyph");
mySegmentKey.InsertMarker(new HPS.Point(0, 0, 0)); // will insert "myCustomGlyph" at the origin


%%%basic_example

myPortfolio.DefineLinePattern("my_new_pattern", myLinePatternKit);
mySegmentKey.GetLineAttributeControl().SetPattern("my_new_pattern");


%%%line_patterns_step1

slpe_orange.SetSize(50, HPS.LinePattern.SizeUnits.Pixels); // each dash set to 50 pixel in length
slpe_orange.SetColor(new HPS.RGBAColor(1, 0.5f, 0)); // color set to orange
blpe.SetSize(20, HPS.LinePattern.SizeUnits.Pixels); // each space between dashes is set to 20 pixels
// this will be the blue solid line
slpe_blue.SetColor(new HPS.RGBAColor(0, 0, 1));


%%%line_patterns_step2

lpea_dashed[0] = slpe_orange; // adding the SolidLinePatternElement from step 1
lpea_dashed[1] = blpe; // adding the BlankLinePatternElement from step 1
HPS.LinePatternElement[] lpea_solid = new HPS.LinePatternElement[1]; // this will be the blue solid line
lpea_solid[0] = slpe_blue;


%%%line_patterns_step3

lppka[0].SetBody(lpea_dashed).SetOffset(4, HPS.LinePattern.SizeUnits.Pixels).SetWeight(2, HPS.LinePattern.SizeUnits.Pixels);
lppka[1].SetBody(lpea_solid);


%%%line_patterns_step4


%%%line_patterns_step5

myPortfolio.DefineLinePattern("myLinePattern", lpk);
mySegmentKey.GetPortfolioControl().Push(myPortfolio);


%%%line_patterns_step6

mySegmentKey.GetLineAttributeControl().SetPattern("myLinePattern");
mySegmentKey.InsertLine(new HPS.Point(-10, 0, 0), new HPS.Point(10, 0, 0));


%%%glyph_line_pattern

glpe.SetSource("myGlyph"); // glyph must already be defined in the current portfolio
glpe.SetInsetBehavior(HPS.LinePattern.InsetBehavior.Inline);
// ...
lpea[0] = anotherElement;
lpea[1] = glpe; // add to the LinePatternElementArray as you would any other line pattern element
lpea[2] = anotherElement;
// ...


%%%%040203_a

HPS.MaterialKit[] materialKitArray = new HPS.MaterialKit[2] { new HPS.MaterialKit(), new HPS.MaterialKit() };
materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1)); // red
materialKitArray[1].SetDiffuse(new HPS.RGBAColor(1, 1, 0, 1)); // yellow
float[] materialIndices = new float[] { 0, 0.25f, 0.5f, 0.75f, 1 };
shellKit.SetFaceIndexColorsByList(faceIndices, materialIndices);


%%%%040204_a

materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1));
materialKitArray[1].SetDiffuseTexture("my_texture"); // this material is now a texture
materialKitArray[2].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 0));


%%%%040301_a

mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.75f, 0.4f, 0.24f, 0.5f)); // setting color for all faces
mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(0, 0, 1)); // setting edges color


%%%%040303_a

ulong[] vertexIndices = new ulong[4];
vertexIndices[0] = 0;
vertexIndices[1] = 1;
vertexIndices[2] = 2;
vertexIndices[3] = 3;
HPS.RGBColor[] colorArray = new HPS.RGBColor[4];
colorArray[0] = new HPS.RGBColor(0.24f, 0.48f, 0.56f); // 1st vertex - blue
colorArray[1] = new HPS.RGBColor(0.67f, 0.07f, 0.64f); // 2nd vertex - purple
colorArray[2] = new HPS.RGBColor(1, 0.5f, 0); // 3rd vertex - orange
colorArray[3] = new HPS.RGBColor(0, 0, 0); // 4th vertex - black
shellKey.SetVertexRGBColorsByList(vertexIndices, colorArray);


%%%%040304_a

mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(1, 1, 1));


%%%%0404_a

mySegmentKey.GetMaterialMappingControl().SetEdgeColor(new HPS.RGBAColor(1, 1, 1));


%%%show_snapshot

HPS.ImageKit myImageKit = new HPS.ImageKit();
myWindowKey.ShowSnapshot(out myImageKit);
// convert the image data to PNG
myImageKit.Convert(myImageKit, HPS.Image.Format.Png);
// get the PNG image into a buffer
Byte[] imageData;
myImageKit.ShowData(out imageData);


%%%create_material_kit

HPS.MaterialKit materialKit = new HPS.MaterialKit();
materialKit.SetDiffuse(new HPS.RGBAColor(0.5f, 0.7f, 0.3f, 0.2f));
materialKit.SetDiffuseTexture("myDefinedTexture");
materialKit.SetSpecular(new HPS.RGBAColor(1, 0.8f, 0.9f, 0.5f));
materialKit.SetGloss(15.0f);


%%%material_kit_array

HPS.MaterialKit[] materialKitArray =
new HPS.MaterialKit[3] { new HPS.MaterialKit(), new HPS.MaterialKit(), new HPS.MaterialKit() };
materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1)); // opaque
materialKitArray[1].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 0.5f)); // half transparent
materialKitArray[1].SetGloss(0.5f);
materialKitArray[2].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 0)); // fully transparent


%%%material_palette_definition

myPortfolio.DefineMaterialPalette("myPalette", materialKitArray);
mySegmentKey.SetMaterialPalette("myPalette"); // the palette is made active on the segment


%%%using_material_mapping_control

// setting a color on a single segment
mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(1.0f, 0, 0, 0.5f));
// setting gloss on a single segment
mySegmentKey.GetMaterialMappingControl().SetFaceGloss(12.4f);


%%%using_material_palettes

// defining a material palette with the name of "myPalette"
// and the materials within "materialKitArray"
myPortfolio.DefineMaterialPalette("myPalette", materialKitArray);
// setting the portfolio active on the segment
mySegmentKey.GetPortfolioControl().Set(myPortfolio);
// using material '0' from "materialKitArray"
mySegmentKey.GetMaterialMappingControl().SetFaceMaterialByIndex(0);


%%%diffuse_color

mySegmentKey.GetMaterialMappingControl().SetFaceColor
(new RGBAColor(0.0f, 0.0f, 1.0f), HPS.Material.Color.Channel.DiffuseColor);


%%%specular

myMaterialKit.SetSpecular(new HPS.RGBAColor(1, 0.8f, 0.9f, 0.5f));


%%%gloss

myMaterialKit.SetGloss(15.0f);


%%%emission

mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(1, 0, 0.5f),
HPS.Material.Color.Channel.Emission);
mySegmentKey.InsertDistantLight(new HPS.Vector(x, y, z)); // IMPORTANT


%%%environment

// when loading the environment texture, use "ReflectionVector" paramaterization
textureOptionsKit.
SetParameterizationSource(HPS.Material.Texture.Parameterization.ReflectionVector);
// ... load texture
// set texture channel to environment
mySegmentKey.GetMaterialMappingControl()
.SetFaceTexture("my_texture", HPS.Material.Texture.Channel.EnvironmentTexture);


%%%basic_transparency

// opaque blue square
segmentKey1.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.24f, 0.48f, 0.56f));
// half-transparent red square
segmentKey2.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(1.0f, 0.0f, 0.0f, 0.5f));


%%%set_alpha

// adjust front face alpha value
myMaterialMappingKit.SetFaceAlpha(0.5f);
// adjust edge alpha
myMaterialMappingKit.SetEdgeAlpha(0.75f);
// adjust vertex alpha
myMaterialMappingKit.SetVertexAlpha(0.25f);


%%%depth_peeling

// setting the transparency algorithm to "depth peeling"
mySegmentKey.GetTransparencyControl().SetAlgorithm(HPS.Transparency.Algorithm.DepthPeeling);
// Visualize will "peel away" three layers when calculating transparency (only meaningful with depth peeling)
mySegmentKey.GetTransparencyControl().SetDepthPeelingLayers(3);


%%%transparency_method

// enables the "screen door" method
windowKey.GetTransparencyControl().SetMethod(HPS.Transparency.Method.ScreenDoor);
// the default transparency method is "blended"
windowKey.GetTransparencyControl().SetMethod(HPS.Transparency.Method.Blended);
// disables transparency
windowKey.GetTransparencyControl().SetMethod(HPS.Transparency.Method.None);


%%%texture_step1

HPS.ImageKit imageKit;
try
{
imageKit = HPS.Image.File.Import(filename, iok);
}
catch (HPS.IOException ioe)
{
String problem = ioe.what(); // shows cause of the exception
return Test.Result.Failure;
}


%%%texture_step1b

HPS.ImageKit imageKit = new HPS.ImageKit();
// set the data into the ImageKit
imageKit.SetData(imageData);
// the dimensions of the image
imageKit.SetSize(256, 256);
// the format tells Visualize how to interpret the raw data
imageKit.SetFormat(HPS.Image.Format.RGB);


%%%texture_step2

// import image to portfolio
HPS.ImageDefinition imageDefinition = portfolioKey.DefineImage("my_image", imageKit);


%%%texture_step3

HPS.TextureOptionsKit textureOptionsKit = new HPS.TextureOptionsKit();
// see the table below about parameterization sources
// makes the image into a texture
portfolioKey.DefineTexture("my_texture", imageDefinition, textureOptionsKit);


%%%texture_step4

mySegmentKey.GetPortfolioControl().Push(portfolioKey);


%%%texture_step5

// the vertices_map array corresponds to the vertex indices of the shell
ulong[] vertices_map = new ulong[4];
vertices_map[0] = 0;
vertices_map[1] = 1;
vertices_map[2] = 2;
vertices_map[3] = 3;
float[] vparams = new float[8];
vparams[0] = 0; vparams[1] = 0; // [0, 0]
vparams[2] = 1; vparams[3] = 0; // [1, 0]
vparams[4] = 1; vparams[5] = 1; // [1, 1]
vparams[6] = 0; vparams[7] = 1; // [0, 1]
HPS.ShellKit shellKit = new HPS.ShellKit();
shellKit.SetPoints(pointArray);
shellKit.SetFacelist(faceList);
shellKit.SetVertexParametersByList(vertices_map, vparams, 2);


%%%texture_step6

mySegmentKey.InsertShell(shellKit);
mySegmentKey.GetMaterialMappingControl().SetFaceTexture("my_texture"); // alternatively, use a material palette


%%%direct_bump

mySegmentKey.GetMaterialMappingControl().SetFaceTexture("my_texture", HPS.Material.Texture.Channel.DiffuseTexture);
mySegmentKey.GetMaterialMappingControl().SetFaceTexture("my_bump_map", HPS.Material.Texture.Channel.Bump);
mySegmentKey.InsertDistantLight(new HPS.Vector(0, 1, 0));


%%%mka_bump

materialKit[0].SetDiffuseColor(new HPS.RGBAColor(1, 0, 0, 1));
materialKit[1].SetDiffuseTexture("my_texture"); // this material is now a texture
materialKit[1].SetBump("my_bump_map"); // setting the bump component
materialKit[2].SetDiffuseColor(new HPS.RGBAColor(1, 0, 0, 0));


%%%decal

textureOptionsKit.SetDecal(true);


%%%shaders_step1

String shader_source =
"void custom_shader(const HGlobals globals, inout HColor color) { \n" +
"color.diffuse.rgb = globals.tex.coords.rgb;}\n" +
"#define H3D_COLOR_SHADER custom_shader\n";


%%%shaders_step2

HPS.ShaderKit shaderKit = new HPS.ShaderKit();
// copies the HLSL into the kit
shaderKit.SetSource(shader_source);
// create (or alternatively use an existing) portfolio
// imports the defined shader into the portfolio
portfolioKey.DefineShader("myShader", shaderKit);
// instructs the segment to use the portfolio
mySegmentKey.GetPortfolioControl().Push(portfolioKey);


%%%shaders_step3

mySegmentKey.GetMaterialMappingControl().SetFaceShader("myShader");


%%%mka_segment

HPS.MaterialKit[] myMaterialKitArray = new HPS.MaterialKit[3];
for (int i = 0; i < myMaterialKitArray.Length; i++)
myMaterialKitArray[i] = new MaterialKit();
myMaterialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1));
myMaterialKitArray[1].SetDiffuse(new HPS.RGBAColor(0, 1, 0, 1));
myMaterialKitArray[2].SetDiffuse(new HPS.RGBAColor(0, 0, 1, 1));
HPS.MaterialPaletteDefinition mpd = myPortfolio.DefineMaterialPalette
("my_palette", myMaterialKitArray);
mySegmentKey.GetPortfolioControl().Push(myPortfolio);
mySegmentKey.GetMaterialMappingControl().SetFaceMaterialByIndex(1);


%%%direct_segment

// setting color for all faces
mySegmentKey.GetMaterialMappingControl().SetFaceColor
(new HPS.RGBAColor(0.75f, 0.4f, 0.24f, 0.5f));
// setting edge color
mySegmentKey.GetMaterialMappingControl().SetEdgeColor
(new HPS.RGBAColor(0, 0, 1));


%%%material_mapping

HPS.MaterialMappingKit myMaterialMappingKit = new HPS.MaterialMappingKit();
myMaterialMappingKit.SetFaceColor(new HPS.RGBAColor(0, 0, 1));
myShellKit.SetMaterialMapping(myMaterialMappingKit);


%%%subentity_materials

ulong[] faceIndices = new ulong[3];
faceIndices[0] = 0;
faceIndices[1] = 1;
faceIndices[2] = 2;
float[] materialIndices = new float[3];
materialIndices[0] = 0;
materialIndices[1] = 1;
materialIndices[2] = 2;
myShellKit.SetFaceIndexColorsByList(faceIndices, materialIndices);


%%%%040302_a

shellKey.SetFaceRGBColorsByRange(3, 1, new HPS.RGBColor(1, 0.5f, 0)); // setting the fourth face to orange


%%%%040302_b

ulong[] faceIndices = new ulong[2];
faceIndices[0] = 3; // fourth face
faceIndices[1] = 0; // first face
HPS.RGBColor[] colorArray = new HPS.RGBColor[2];
colorArray[0] = new HPS.RGBColor(1, 0.5f, 0); // orange
colorArray[1] = new HPS.RGBColor(1, 0, 0); // red
shellKey.SetFaceRGBColorsByList(faceIndices, colorArray);


%%%%040302_c

shellKey.SetFaceRGBColorsByRange(0, 3, new HPS.RGBColor(1, 0.5f, 0));



%%%%040303_a

ulong[] vertexIndices = new ulong[4];
vertexIndices[0] = 0;
vertexIndices[1] = 1;
vertexIndices[2] = 2;
vertexIndices[3] = 3;
HPS.RGBColor[] colorArray = new HPS.RGBColor[4];
colorArray[0] = new HPS.RGBColor(0.24f, 0.48f, 0.56f); // 1st vertex - blue
colorArray[1] = new HPS.RGBColor(0.67f, 0.07f, 0.64f); // 2nd vertex - purple
colorArray[2] = new HPS.RGBColor(1, 0.5f, 0); // 3rd vertex - orange
colorArray[3] = new HPS.RGBColor(0, 0, 0); // 4th vertex - black
shellKey.SetVertexRGBColorsByList(vertexIndices, colorArray);


%%%%040204_a

materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1));
materialKitArray[1].SetDiffuseTexture("my_texture"); // this material is now a texture
materialKitArray[2].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 0));


%%%%040203_a

HPS.MaterialKit[] materialKitArray = new HPS.MaterialKit[2] { new HPS.MaterialKit(), new HPS.MaterialKit() };
materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1)); // red
materialKitArray[1].SetDiffuse(new HPS.RGBAColor(1, 1, 0, 1)); // yellow
float[] materialIndices = new float[] { 0, 0.25f, 0.5f, 0.75f, 1 };
shellKit.SetFaceIndexColorsByList(faceIndices, materialIndices);


%%%selection_algorithm

// use the visual algorithm
myWindowKey.GetSelectionOptionsControl().SetAlgorithm(HPS.Selection.Algorithm.Visual);
// use the analytic algorithm
myWindowKey.GetSelectionOptionsControl().SetAlgorithm(HPS.Selection.Algorithm.Analytic);


%%%proximity

options.SetProximity(0.05f); // the distance, in centimeters, from the selection point


%%%granularity

// will select on the object's bounding box
myWindowKey.GetSelectionOptionsControl().SetGranularity(HPS.Selection.Granularity.General);
// will select on the object's exact shape
myWindowKey.GetSelectionOptionsControl().SetGranularity(HPS.Selection.Granularity.Detailed);


%%%selection_by_point_example

myWindowKey.GetSelectionOptionsControl().SetLevel(HPS.Selection.Level.Entity); // choosing entity-level selection
myWindowKey.GetSelectionOptionsControl().SetProximity(0.01f);
myWindowKey.GetSelectionOptionsControl().SetAlgorithm(HPS.Selection.Algorithm.Analytic);
// the origin will be the selection point
HPS.Point selectionPoint = new HPS.Point(0, 0, 0);
HPS.SelectionResults selectionResults = new SelectionResults();
ulong numSelectedItems = myWindowKey.GetSelectionControl().SelectByPoint( // this is the actual selection call
selectionPoint, // the endpoint of the ray, typically the camera location
out selectionResults); // the selected geometries are returned to this object


%%%selection_by_ray_example

myWindowKey.GetSelectionOptionsControl().SetLevel(HPS.Selection.Level.Entity); // choosing entity-level selection
myWindowKey.GetSelectionOptionsControl().SetProximity(0.01f);
myWindowKey.GetSelectionOptionsControl().SetAlgorithm(HPS.Selection.Algorithm.Analytic);
HPS.Point pickStart = new HPS.Point(mouseX, mouseY, -1);
HPS.Point pickEnd = new HPS.Point(mouseX, mouseY, 0);
HPS.Point rayStart = new HPS.Point();
HPS.Point rayEnd = new HPS.Point();
myKeyPath.ConvertCoordinate(HPS.Coordinate.Space.Pixel, pickStart, HPS.Coordinate.Space.World, out rayStart);
myKeyPath.ConvertCoordinate(HPS.Coordinate.Space.Pixel, pickEnd, HPS.Coordinate.Space.World, out rayEnd);
HPS.Vector rayDir = new HPS.Vector(rayEnd - rayStart);
HPS.SelectionResults selectionResults;
ulong numSelectedItems = myWindowKey.GetSelectionControl().SelectByRay( // this is the actual selection call
rayStart, // the endpoint of the ray, typically the camera location
rayDir, // the direction of the ray
out selectionResults); // the selected geometries are returned to this object


%%%selection_results

HPS.SelectionResultsIterator srIterator = selectionResults.GetIterator();
while (srIterator.IsValid())
{
HPS.SelectionItem selectionItem = srIterator.GetItem();
HPS.Key key;
selectionItem.ShowSelectedItem(out key); // 'key' is the HPS.Key of the selected item
if (key.Type() == HPS.Type.ShellKey)
{
// do something with this key
}
srIterator.Next();
}


%%%selection_by_shell_example

selectionOptions.SetAlgorithm(HPS.Selection.Algorithm.Analytic);
selectionOptions.SetLevel(HPS.Selection.Level.Entity);
selectionOptions.SetScope(myWindowKey);
HPS.SelectionResults selectionResults;
// myShellKit contains the shell definitions that is doing the selecting
ulong numSelectedItems = HPS.Database.SelectByShell(myShellKit, selectionOptions, out selectionResults);
HPS.SelectionResultsIterator srIterator = selectionResults.GetIterator();
while (srIterator.IsValid())
{
HPS.SelectionItem selectionItem = srIterator.GetItem();
HPS.Key key;
selectionItem.ShowSelectedItem(out key); // 'key' is the HPS.Key of the selected item
if (key.Type() == HPS.Type.ShellKey)
{
// if we get here, the shell has selected at least one other body
}
srIterator.Next();
}


%%%selection_by_volume_example

HPS.SimpleCuboid boundingCuboid = new HPS.SimpleCuboid(new HPS.Point(-1, -1, -1), new HPS.Point(1, 1, 1));
ulong numSelectedItems = myWindowKey.GetSelectionControl()
.SelectByVolume(boundingCuboid, out selectionResults);


%%%selection_by_area_example

selectionOptions.SetAlgorithm(HPS.Selection.Algorithm.Analytic);
selectionOptions.SetLevel(HPS.Selection.Level.Entity);
HPS.SelectionResults selectionResults;
// specify the window-space rectangle where you want to select
ulong numSelectedItems = myWindowKey.GetSelectionControl().SelectByArea(new HPS.Rectangle(-1, 1, -1, 1), selectionOptions, out selectionResults);
HPS.SelectionResultsIterator srIterator = selectionResults.GetIterator();
while (srIterator.IsValid())
{
HPS.SelectionItem selectionItem = srIterator.GetItem();
HPS.Key key;
selectionItem.ShowSelectedItem(out key); // 'key' is the HPS.Key of the selected item
if (key.Type() == HPS.Type.ShellKey)
{
// if we get here, the shell has selected at least one sphere
}
srIterator.Next();
}


%%%limiting_enhancing

// faces are made selectable, but markers are not
myWindowKey.GetSelectabilityControl().SetEdges(HPS.Selectability.Value.On).SetMarkers(HPS.Selectability.Value.Off);
// forces selectability to on even if faces are invisible
myWindowKey.GetSelectabilityControl().SetFaces(HPS.Selectability.Value.ForcedOn);
// only the 10 closest subentites of shells and meshes will be returned as selected, even if more fell within the selection boundary
myWindowKey.GetSelectionOptionsControl().SetInternalLimit(10);
// only 2 objects will be returned
myWindowKey.GetSelectionOptionsControl().SetRelatedLimit(2);


%%%highlighting

HPS.NamedStyleDefinition orange_style = myPortfolio.DefineNamedStyle("myHighlightStyle", mySegmentKey);
mySegmentKey.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0.89f, 0.62f, 0.11f));
hok.SetStyleName("myHighlightStyle");
myWindowKey.GetPortfolioControl().Push(myPortfolio);
myWindowKey.GetHighlightControl().Highlight(keyPath, hok);


%%%overlays

mySegmentKey.GetDrawingAttributeControl().SetOverlay(HPS.Drawing.Overlay.Default);
mySegmentKey.GetDrawingAttributeControl().SetOverlay(HPS.Drawing.Overlay.WithZValues);
mySegmentKey.GetDrawingAttributeControl().SetOverlay(HPS.Drawing.Overlay.InPlace);


%%%activate_operator_1

// ... do other initialization
HPS.OrbitOperator orbitOperator = new HPS.OrbitOperator(HPS.MouseButtons.ButtonMiddle());
myView.GetOperatorControl().Push(orbitOperator); // makes 'orbitOperator' active


%%%activate_operator_2

HPS.OrbitOperator orbitOperator
// ... do other initialization


%%%activate_operator_with_priority

HPS.WalkOperator walkOperator = new HPS.WalkOperator(HPS.MouseButtons.ButtonLeft());
myView.GetOperatorControl().Push(walkOperator, Operator.Priority.Default);


%%%change_priority

// The Set command will remove all the operators in the given priority stack
// and add the operator(s) specified in the parameter list.
myView.GetOperatorControl().Set(walkOperator, Operator.Priority.High);


%%%detach_view

orbitOperator.DetachView(); // detaching operator from the view


%%%combining_operators

myView.GetOperatorControl().Push(new HPS.ZoomOperator(HPS.MouseButtons.ButtonMiddle()))
.Push(new HPS.PanOperator(HPS.MouseButtons.ButtonRight()))
.Push(new HPS.OrbitOperator(HPS.MouseButtons.ButtonLeft()));


%%%handles_operator

myView.GetOperatorControl().Push(new HPS.HandlesOperator(HPS.MouseButtons.ButtonLeft()));


%%%MyCustomOperator_step1

class MyCustomOperator : HPS.Operator
{
public override bool OnMouseDown(HPS.MouseState in_state)
{
// implementation details go here - see Step 2
return true;
}
}


%%%MyCustomOperator_step2

public override bool OnTouchDown(HPS.TouchState in_state)
{
// get the number of current touches
ulong numTouches = in_state.GetTouchCount();
// get the Touch objects themselves
HPS.Touch[] touchArray = in_state.GetTouches();
// get location in window space for first touch object
HPS.Touch touch = touchArray[0];
HPS.WindowPoint windowPoint = touch.Location;
return true;
}


%%%%0202_b

if (in_state.GetButtons().Left())
{
if (in_state.GetModifierKeys().Control())
{
// perform your logic
}
}


%%%select_operator

HPS.SelectOperator selectOperator
= new HPS.SelectOperator(HPS.MouseButtons.ButtonLeft());
myView.GetOperatorControl().Push(selectOperator); // makes 'selectOperator' active
// configure the selection options as needed
sok.SetProximity(2.0f);
selectOperator.SetSelectionOptions(sok);
// ... <user performs selection>
// get the results
HPS.SelectionResults selectionResults = selectOperator.GetActiveSelection();


%%%highlight_operator

HPS.HighlightOperator highlightOperator
= new HPS.HighlightOperator(HPS.MouseButtons.ButtonLeft());
myView.GetOperatorControl().Push(highlightOperator); // makes 'highlightOperator' active
// set the highlight style, which must be predefined
HPS.HighlightOptionsKit hok = new HPS.HighlightOptionsKit("myHighlightStyle");
highlightOperator.SetHighlightOptions(hok);
// ... <perform selection>
// ... <style is applied automatically to the selection set>


%%%selection_culling

sok.SetExtentCullingRespected(true); // extent-culled objects will not be selected
sok.SetVectorCullingRespected(false); // vector-culled objects will be selected


%%%subentity_selection

HPS.SelectionResultsIterator srIterator = selectionResults.GetIterator();
while (srIterator.IsValid())
{
HPS.SelectionItem selectionItem = srIterator.GetItem();
HPS.Key key;
// get the key of the selected item
selectionItem.ShowSelectedItem(out key);
ulong [] out_faces, out_vertices, edges1, edges2;
// out_faces is a list of faces
selectionItem.ShowFaces(out out_faces);
// out_vertices is list of vertices
selectionItem.ShowVertices(out out_vertices);
// edges1 and edges2 are parallel
selectionItem.ShowEdges(out edges1, out edges2);
srIterator.Next();
}


%%%window_update

myWindowKey.Update();


%%%window_update_progress

HPS.UpdateNotifier notifier = myWindowKey.UpdateWithNotifier();
HPS.Window.UpdateStatus status = notifier.Status();
myWindowKey.Update(); // the default
if (status == HPS.Window.UpdateStatus.InProgress)
{
// update is in progress
}
if (status == HPS.Window.UpdateStatus.Completed)
{
// update is finished
}


%%%window_update_type

myWindowKey.Update(); // simply call this if you want a default update
myWindowKey.Update(HPS.Window.UpdateType.Complete); // this might be necessary to call in a GUI toolkit's 'window expose' event


%%%fixed_framerate

myWindowKey.Update(HPS.Window.UpdateType.Default, 0.75); // max 0.75 seconds spent on rendering


%%%offscreen_window

oswok.SetDriver(HPS.Window.Driver.OpenGL2);
HPS.OffScreenWindowKey offscreenWindowKey = HPS.Database.CreateOffScreenWindow(512, 512, oswok);
offscreenWindowKey.IncludeSegment(mySegmentKey);


%%%notifier_offscreen

HPS.UpdateNotifier notifier = offscreenWindowKey.UpdateWithNotifier();
notifier.Wait();
// when you get to this point, the scene is rendered


%%%get_image_data

HPS.ImageKit imageKit;
HPS.OffScreenWindowOptionsControl oswoc = offscreenWindowKey.GetWindowOptionsControl();
// fills the ImageKit with the contents of the offscreen window
oswoc.ShowImage(HPS.Image.Format.RGB, out imageKit);
Byte[] imageData;
// gets the data out of the kit and into a buffer for writing
imageKit.ShowData(out imageData);
// at this point, you can use the data in 'imageData' any way you prefer


%%%offscreen_window_opacity

// completely transparent window background
oswok.SetOpacity(0.0f);
// 50% transparent window background
oswok.SetOpacity(0.5f);
// no explicity transparency, but preserve alpha
oswok.SetOpacity(1.0f);


%%%modify_offscreen_image_data

HPS.ImageKit imageKit;
HPS.OffScreenWindowKey offscreenWindowKey = HPS.Database.CreateOffScreenWindow(800, 600);
HPS.OffScreenWindowOptionsControl oswoc = offscreenWindowKey.GetWindowOptionsControl();
// fills the ImageKit with the contents of the offscreen window
oswoc.ShowImage(HPS.Image.Format.RGB, out imageKit);
Byte[] imageData;
// gets the data out of the kit and into a buffer for modification
imageKit.ShowData(out imageData);
// ...
// manipulate data
// ...
imageKit.SetData(imageData); // modified data reinserted into the ImageKit for display


%%%set_display_lists

// enable segment-level display lists
mySegmentKey.GetPerformanceControl().SetDisplayLists(HPS.Performance.DisplayLists.Segment);
// enable geometry-level display lists
mySegmentKey.GetPerformanceControl().SetDisplayLists(HPS.Performance.DisplayLists.Geometry);


%%%set_static_model

// enable static model
mySegmentKey.GetPerformanceControl().SetStaticModel(HPS.Performance.StaticModel.Attribute);
// allows Visualize to use static model optimizations more appropriate for very large models
mySegmentKey.GetPerformanceControl().SetStaticModel(HPS.Performance.StaticModel.AttributeSpatial);
// disable static model
mySegmentKey.GetPerformanceControl().SetStaticModel(HPS.Performance.StaticModel.None);


%%%culling_optimizations01_a

// enables back-face culling
mySegmentKey.GetCullingControl().SetBackFace(true);
// indicates front-facing polygons are those that are wound clockwise/left-handed WRT camera
mySegmentKey.GetDrawingAttributeControl().SetPolygonHandedness(HPS.Drawing.Handedness.Left);
// indicates front-facing polygons are those that are wound counter-clockwise/right-handed WRT camera
mySegmentKey.GetDrawingAttributeControl().SetPolygonHandedness(HPS.Drawing.Handedness.Right);
// ignores handedness - back-face culling does not work with this setting
mySegmentKey.GetDrawingAttributeControl().SetPolygonHandedness(HPS.Drawing.Handedness.None);


%%%distance_culling_search

SelectionOptionsKit selection_options = SelectionOptionsKit.GetDefault();
selection_options.SetDistanceCullingRespected(false);


%%%distance_culling_set_distance

myWindow.GetCullingControl().SetDistance(((float)8.2));


%%%volume_culling

// Get the culling control for the segment where your 3D model has been loaded
HPS.CullingControl cullControl = mySegKey.GetCullingControl();
// Create a volume for culling
HPS.SimpleCuboid volume;
volume.min = new Point(-1000, -1000, -1000);
volume.max = new Point(1000, 1000, 1000);
cullControl.SetVolume(volume);


%%%volume_culling_full_source

HPS.Canvas canvas = Factory.CreateCanvas(myWindowKey);
//----- Create a model and attach it to a view -----//
canvas.AttachViewAsLayout(myView);
myView.AttachModel(myModel);
HPS.SegmentKey mySegKey = myModel.GetSegmentKey();
//----- Import a Model into the Scene -----//
HPS.Stream.ImportNotifier notifier;
HPS.Stream.ImportOptionsKit in_options = new Stream.ImportOptionsKit();
in_options.SetSegment(mySegKey);
mySegKey.Flush(); // empty this segment
try
{
// Import the model
notifier = HPS.Stream.File.Import(path_to_model_file, in_options);
notifier.Wait();
}
catch (HPS.IOException)
{
// handle Exception
}
myView.FitWorld(); // Fit the view
myView.Update(); // Update the view
// Get the culling control for the segment where your 3D model has been loaded
HPS.CullingControl cullControl = mySegKey.GetCullingControl();
// Create a volume for culling
HPS.SimpleCuboid volume;
volume.min = new Point(-1000, -1000, -1000);
volume.max = new Point(1000, 1000, 1000);
cullControl.SetVolume(volume);
myView.FitWorld();


%%%culling_optimizations01_b

// for this scene, handedness is set to "Left"
mySegmentKey.GetDrawingAttributeControl().SetPolygonHandedness(HPS.Drawing.Handedness.Left);
mySegmentKey.GetCameraControl().SetPosition(new Point(0, 0, 5)); // setting the view point
// specifying a square polygon
HPS.Point[] pointArray = new HPS.Point[4];
pointArray[0] = new HPS.Point(-1.0f, -1.0f, 0);
pointArray[1] = new HPS.Point(-1.0f, 1.0f, 0);
pointArray[2] = new HPS.Point(1.0f, 1.0f, 0);
pointArray[3] = new HPS.Point(1.0f, -1.0f, 0);
// Inserting the vertices from pointArray in the order 0, 1, 2, 3 will result in the back face
// toward the camera (right-handed orientation). This face will be culled.
int[] faceList = new int[5];
faceList[0] = 4;
faceList[1] = 0;
faceList[2] = 1;
faceList[3] = 2;
faceList[4] = 3;
// merely changing the order of the vertices in the face list results in a front (left-handed) face
faceList[0] = 4;
faceList[1] = 0;
faceList[2] = 3;
faceList[3] = 2;
faceList[4] = 1;
mySegmentKey.InsertShell(pointArray, faceList);


%%%frustum_culling

mySegmentKey.GetCullingControl().SetFrustum(true); // enables frustum culling
mySegmentKey.GetCullingControl().SetFrustum(false); // disables frustum culling


%%%hardcopy

try
{
HPS.Hardcopy.File.ExportOptionsKit exportOptionsKit = new HPS.Hardcopy.File.ExportOptionsKit();
float width, height;
myWindowKey.GetWindowInfoControl().ShowPhysicalSize(out width, out height);
exportOptionsKit.SetWYSIWYG(true);
exportOptionsKit.SetSize(width, height, HPS.Hardcopy.SizeUnits.Centimeters);
exportOptionsKit.SetResolution(100, HPS.Hardcopy.ResolutionUnits.DPCM);
// export to PDF
HPS.IOResult PDFResult =
HPS.Hardcopy.File.Export("output.pdf", HPS.Hardcopy.File.Driver.PDF, myWindowKey, exportOptionsKit);
// export to Postscript
HPS.IOResult postScriptResult =
HPS.Hardcopy.File.Export("output.ps", HPS.Hardcopy.File.Driver.Postscript, myWindowKey, exportOptionsKit);
}
{
// handle Hardcopy exception
}


%%%window_update_notifier

HPS.UpdateNotifier notifier = myWindowKey.UpdateWithNotifier();
notifier.Wait();
// when you get to this point, the scene is rendered


%%%update_options_kit

uok.SetTimeLimit(0.5f);
myWindowKey.SetUpdateOptions(uok);


%%%culling_extents

// culling all geometry smaller than 10 pixels
mySegmentKey.GetCullingControl().SetExtent(10);
// deferring all geometry smaller than 100 pixels
mySegmentKey.GetCullingControl().SetDeferralExtent(100);


%%%set_soft_memory_limit

ulong memoryLimit = 132581244 / 2;


%%%MyEmergencyHandler

class MyEmergencyHandler : HPS.EmergencyHandler
{
public MyEmergencyHandler(){ notif = null;}
public override void Handle(string message, HPS.Emergency.Code code)
{
if (code == HPS.Emergency.Code.SoftMemoryLimit)
{
lock (lockObj)
{
if (notif != null)
notif.Cancel();
}
}
else if (code == HPS.Emergency.Code.HardMemoryLimit)
delete_reserve_buffer(); // free previously reserved emergency buffer
else if (code == HPS.Emergency.Code.Fatal)
abort(); // this case must not return
}
public void SetNotifier(HPS.Stream.ImportNotifier in_notif)
{
lock (lockObj)
{
notif = in_notif;
}
}
private void abort() { /* Exit app */ }
private void delete_reserve_buffer() { /* free reserve buffer*/ }
private System.Object lockObj = new System.Object();
private HPS.Stream.ImportNotifier notif;
};


%%%set_emergency_handler

MyEmergencyHandler handler = new MyEmergencyHandler();


%%%img_def_target

HPS::OffScreenWindowKey owc = HPS::Database::CreateOffScreenWindow(myImageDefinition, myOptionsKit);
// be sure to wait for the image to render before using it!
HPS::UpdateNotifier updateNotifier = owc.UpdateWithNotifier();
updateNotifier.Wait();


%%%toggle_anti_alias

awok.SetAntiAliasCapable(true, 8); // enables 8x anti-aliasing for the window
awok.SetAntiAliasCapable(false); // disables anti-aliasing altogether - cannot be enabled later
awok.SetScreenAntiAliasing(true); // turns on screen anti-aliasing for the window
awok.SetScreenAntiAliasing(false); // turns off screen anti-aliasing for the window
// ...
// create window
// ...
mySegmentKey.GetVisualEffectsControl().SetTextAntiAliasing(true); // turns on text anti-aliasing in an existing window
mySegmentKey.GetVisualEffectsControl().SetTextAntiAliasing(false); // turns off text anti-aliasing in an existing window


%%%specific_segments

segment_one.GetVisualEffectsControl().SetTextAntiAliasing(true);
segment_two.GetVisualEffectsControl().SetTextAntiAliasing(false);


%%%no_true_type

segment_one.GetTextAttributeControl().SetFont("Times New Roman")
.SetRenderer(Text.Renderer.Truetype)
.SetPreference(Text.Preference.Vector);


%%%enable_simple_shadows

// enables simple shadows
mySegmentKey.GetVisualEffectsControl().SetSimpleShadow(true);
// sets the plane where the shadows are projected
mySegmentKey.GetVisualEffectsControl().SetSimpleShadowPlane(new HPS.Plane(0, 1, 0, 0.425f));
// color of the shadow
mySegmentKey.GetVisualEffectsControl().SetSimpleShadowColor(new HPS.RGBAColor(0.2f, 0.2f, 0.2f));
// light direction
mySegmentKey.GetVisualEffectsControl().SetSimpleShadowLightDirection(new HPS.Vector(0, 1, 0));


%%%set_shadow_options

mySegmentKey.GetVisualEffectsControl().SetSimpleShadow(true, // enabling simple shadows
256, // resolution of the shadow
16, // blurring amount
false); // ignore transparency is false


%%%enable_shadow_maps

mySegmentKey.GetVisualEffectsControl().SetShadowMaps(true, // enables shadow maps
16, // samples
2048, // resolution
true, // view dependence
true); // jitter
mySegmentKey.GetVisibilityControl().SetShadows(true);


%%%cast_emit_receive

mySegmentKey.GetVisibilityControl().SetShadowCasting(true);
mySegmentKey.GetVisibilityControl().SetShadowEmitting(true);
mySegmentKey.GetVisibilityControl().SetShadowReceiving(false);


%%%shadow_direction

mySegmentKey.GetVisualEffectsControl().SetSimpleShadowLightDirection(new Vector(1, 1, 1));


%%%set_simple_reflection

mySegmentKey.GetVisualEffectsControl().SetSimpleReflection(true, 0.5f, 1U, false, 0, 0.2f);
mySegmentKey.GetVisualEffectsControl().SetSimpleReflectionPlane(new HPS.Plane(0, 1, 0, 1));


%%%enable_bloom

// to enable bloom
ppek.SetBloom(true, 10.0f); // strength can be set from 0 to 10, (default is 1)
windowKey.SetPostProcessEffects(ppek);
// to disable bloom
ppek.SetBloom(false);
windowKey.SetPostProcessEffects(ppek);


%%%star_bloom

// uses the 'star' bloom shape with a blur radius of 5
ppek.SetBloom(true, 10.0f, 5U, HPS.PostProcessEffects.Bloom.Shape.Star);


%%%algorithms

// enables Gouraud (default)
mySegmentKey.GetLightingAttributeControl().SetInterpolationAlgorithm(HPS.Lighting.InterpolationAlgorithm.Gouraud);
// enables Phong
mySegmentKey.GetLightingAttributeControl().SetInterpolationAlgorithm(HPS.Lighting.InterpolationAlgorithm.Phong);
// enables flat shading
mySegmentKey.GetLightingAttributeControl().SetInterpolationAlgorithm(HPS.Lighting.InterpolationAlgorithm.Flat);


%%%hemispheric_ambient

mySegmentKey.GetMaterialMappingControl().SetAmbientLightUpColor(new HPS.RGBAColor(1, 0, 0));
mySegmentKey.GetMaterialMappingControl().SetAmbientLightDownColor(new HPS.RGBAColor(0, 0, 1));


%%%set_hsra

myWindowKey.GetSubwindowControl().SetRenderingAlgorithm(HPS.Subwindow.RenderingAlgorithm.HiddenLine);


%%%unset_hsra

myWindowKey.GetSubwindowControl().UnsetRenderingAlgorithm();


%%%priority

mySegmentKey.GetSubwindowControl().SetRenderingAlgorithm(HPS.Subwindow.RenderingAlgorithm.Priority);
HPS.SegmentKey s1 = mySegmentKey.Subsegment();
s1.InsertCircle(new HPS.Point(0, 0, 0), 0.25f, new HPS.Vector(0, 0, 1));
HPS.SegmentKey s2 = mySegmentKey.Subsegment();
s2.InsertShell(myShellKit);


%%%hidden_line

mySegmentKey.GetVisibilityControl().SetFaces(true).SetEdges(true).SetLines(true);
mySegmentKey.GetSubwindowControl().SetRenderingAlgorithm(HPS.Subwindow.RenderingAlgorithm.HiddenLine);
mySegmentKey.GetHiddenLineAttributeControl().SetVisibility(false);


%%%dim_factor

mySegmentKey.GetHiddenLineAttributeControl().SetDimFactor(0.75f);
mySegmentKey.GetHiddenLineAttributeControl().SetVisibility(true);


%%%special_segments

// faces for this segment are rendered, even when HLR is enabled
mySegmentKey.GetHiddenLineAttributeControl().SetRenderFaces(true);
// text for this segment is rendered
mySegmentKey.GetHiddenLineAttributeControl().SetRenderText(true);


%%%depth_range

mySegmentKey.GetDrawingAttributeControl().SetDepthRange(0, 0);


%%%set_depth_of_field

ppek.SetDepthOfField(true, 5.0f, 5.0f, 30.0f);
myWindowKey.SetPostProcessEffects(ppek);


%%%enable_perimeter_edges

mySegmentKey.GetVisibilityControl().SetEdges(false); // disables non-perimeter edges
mySegmentKey.GetVisibilityControl().SetPerimeterEdges(true); // enables perimeter edges
mySegmentKey.GetVisibilityControl().SetPerimeterEdges(false); // disables perimeter edges


%%%interior_silhouette_edges

mySegmentKey.GetVisibilityControl().SetInteriorSilhouetteEdges(true);


%%%perimeter_edge_options

myWindowKey.GetPostProcessEffectsControl().SetSilhouetteEdges(true, 10, true);


%%%hard_edges

mySegmentKey.GetVisibilityControl().SetHardEdges(true);
mySegmentKey.GetEdgeAttributeControl().SetHardAngle(135);


%%%smooth

mySegmentKey.GetColorInterpolationControl().SetFaceColor(true);
ulong[] vertexIndices = { 0, 1, 2, 3 };
RGBColor[] colorArray = { new HPS.RGBColor(0.24f, 0.48f, 0.56f), // 1st vertex - blue
new HPS.RGBColor(0.67f, 0.07f, 0.64f), // 2nd vertex - purple
new HPS.RGBColor(1, 0.5f, 0), // 3rd vertex - orange
new HPS.RGBColor(0, 0, 0) // 4th vertex - black
};
myShellKey.SetVertexRGBColorsByList(vertexIndices, colorArray);


%%%hard

HPS.MaterialKit[] materialKitArray = new HPS.MaterialKit[2];
for (int i = 0; i < materialKitArray.Length; i++)
materialKitArray[i] = new HPS.MaterialKit();
materialKitArray[0].SetDiffuse(new HPS.RGBAColor(1, 0, 0, 1)); // red
materialKitArray[1].SetDiffuse(new HPS.RGBAColor(1, 1, 0, 1)); // yellow
float[] materialIndices = new float[5];
materialIndices[0] = 0;
materialIndices[1] = 0.25f;
materialIndices[2] = 0.5f;
materialIndices[3] = 0.75f;
materialIndices[4] = 1;
myShellKit.SetFaceIndexColorsByList(faceIndices, materialIndices);


%%%contour_lines

mySegmentKey.GetContourLineControl().SetVisibility(true)
.SetPositions(1.0f, 0.5f).SetWeights(2.0f).SetColors(new RGBColor(1, 0, 0));


%%%enabling_ci

// enable color interpolation for faces
mySegmentKey.GetColorInterpolationControl().SetFaceColor(true);
// enable color index interpolation for faces
mySegmentKey.GetColorInterpolationControl().SetFaceIndex(true);
// enable color interpolation for edges
mySegmentKey.GetColorInterpolationControl().SetEdgeColor(true);
// enable color index interpolation for edges
mySegmentKey.GetColorInterpolationControl().SetEdgeIndex(true);
// enable color interpolation for vertices
mySegmentKey.GetColorInterpolationControl().SetVertexColor(true);
// enable color index interpolation for vertices
mySegmentKey.GetColorInterpolationControl().SetVertexIndex(true);


%%%ambient_occlusion

myWindowKey.GetPostProcessEffectsControl().SetAmbientOcclusion(true, 2.0f,
HPS.PostProcessEffects.AmbientOcclusion.Quality.Nicest);


%%%eye_dome

windowKey.GetPostProcessEffectsControl().SetEyeDomeLighting(true, 60.0f, 1.2f);


%%%eye_dome_disable

mySegmentKey.GetVisualEffectsControl().SetPostProcessEffectsEnabled(false);


%%%read_hsf

HPS.Stream.ImportNotifier notifier = new HPS.Stream.ImportNotifier();
try
{
HPS.Stream.ImportOptionsKit importOptionsKit = new HPS.Stream.ImportOptionsKit();
importOptionsKit.SetSegment(mySegmentKey); // set destination segment
notifier = HPS.Stream.File.Import(filename, importOptionsKit);
// the notifier can be used to check the load progress
float percent_complete;
notifier.Status(out percent_complete);
// pauses this thread until the HSF is finished loading
notifier.Wait();
}
catch (HPS.IOException ioe)
{
// handle exception
}


%%%notifier

HPS.IOResult ioResult = notifier.Status();
if (ioResult == HPS.IOResult.Success)
{
// good
}
else
{
// bad
}


%%%results

HPS.Stream.ImportResultsKit importResultsKit = notifier.GetResults();
// get the default camera of the model
importResultsKit.ShowDefaultCamera(out cameraKit);
// get the segment this model was loaded into
importResultsKit.ShowSegment(out someSegment);


%%%notifier_cancel

notifier = HPS.Stream.File.Import(filename, importOptionsKit);
// cancel the import
notifier.Cancel();
// wait for the cancellation to finish
notifier.Wait();
// test for the IOResult
if (notifier.Status() != HPS.IOResult.Canceled); // if you get here, something unexpected happened


%%%stream_buffer_import

try
{
HPS.Stream.ImportOptionsKit importOptionsKit = new HPS.Stream.ImportOptionsKit();
importOptionsKit.SetSegment(mySegmentKey); // set destination segment
// read from previously exported ByteArrayArray buffers
notifier = HPS.Stream.File.Import(buffers, importOptionsKit);
// pauses this thread until the HSF is finished loading
notifier.Wait();
}
catch (HPS.IOException ioe)
{
// handle exception
throw;
}


%%%stream_buffer_export

byte[][] buffers;
try
{
HPS.Stream.ExportOptionsKit exportOptionsKit = new HPS.Stream.ExportOptionsKit();
// write to a series of buffers
HPS.Stream.ExportNotifier exportNotifier = HPS.Stream.File.Export(mySegmentKey, exportOptionsKit, out buffers);
exportNotifier.Wait();
}
catch (HPS.IOException ioe)
{
// handle exception
throw;
}


%%%exporting

try
{
HPS.Stream.ExportOptionsKit exportOptionsKit = new HPS.Stream.ExportOptionsKit();
exportOptionsKit.SetColorCompression(true, 16); // color compression ranges from 0 to 72
HPS.Stream.File.Export(filename, mySegmentKey, exportOptionsKit).Wait();
}
catch (HPS.IOException ioe)
{
// handle exception
}


%%%loading_images

HPS.ImageKit imageKit;
try
{
imageKit = HPS.Image.File.Import(filename, iok);
}
catch (HPS.IOException ioe)
{
String problem = ioe.Message; // shows cause of the exception
}


%%%save_image

HPS.Image.File.Export(filename, myImageKit);


%%%screenshot

HPS.Image.ExportOptionsKit export_options = new HPS.Image.ExportOptionsKit();
export_options.SetFormat(HPS.Image.Format.Png);
export_options.SetSize(800, 450);
HPS.Image.File.Export(filename, myWindowKey, export_options);


%%%other_formats

// importing STL file
HPS.STL.ImportOptionsKit stlOptionsKit = new HPS.STL.ImportOptionsKit();
stlOptionsKit.SetSegment(mySegmentKey);
HPS.STL.ImportNotifier stlNotifier = HPS.STL.File.Import(stlFilename, stlOptionsKit);
stlNotifier.Wait();
// importing OBJ file
HPS.OBJ.ImportOptionsKit objOptionsKit = new HPS.OBJ.ImportOptionsKit();
objOptionsKit.SetSegment(mySegmentKey);
HPS.OBJ.ImportNotifier objNotifier = HPS.OBJ.File.Import(objFilename, objOptionsKit);
objNotifier.Wait();


%%%%030102_a

try
{
notifier = HPS.Exchange.File.Import(filename, new HPS.Exchange.ImportOptionsKit());
notifier.Wait();
HPS.CADModel modelFile = notifier.GetCADModel();
// get the View and attach it to the Canvas
HPS.View myView = modelFile.ActivateDefaultCapture();
myCanvas.AttachViewAsLayout(myView);
// alternatively, if you already have a View object, you can simply
// get the Model and attach it directly:
model = modelFile.GetModel();
myView.AttachModel(model);
}
{
// handle error
}


%%%set_transform_component_path

// a user selects a wheel on the screen through a mouse
SelectionOptionsKit selection_options = new SelectionOptionsKit();
HPS.SprocketPath mySprocketPath = new SprocketPath(myCanvas);
if (myWindowKey.GetSelectionControl().SelectByPoint(new Point(0, 0, 0), selection_options, out results) > 0)
{
// we obtain a keypath from the selection results
HPS.SelectionItem item = results.GetIterator().GetItem();
HPS.KeyPath path_to_selection;
item.ShowPath(out path_to_selection);
// using the CADModel, we obtain a ComponentPath from the KeyPath
HPS.ComponentPath component_path = myCADModel.GetComponentPath(path_to_selection);
// we figure out at which level is appropriate to insert a transform, so that only the instance of the wheel I selected is affected
HPS.Component transform_target = HPS.Factory.DeInstanceComponent(component_path);
// we apply the transform
HPS.MatrixKit transform = new MatrixKit();
transform.Translate(5, 0, 0);
transform_target.SetTransform(transform);
myCanvas.Update();
}


%%%set_transform_full_source

Canvas myCanvas = Factory.CreateCanvas(myWindowKey);
HPS.Exchange.ImportNotifier importNotifier;
try
{
HPS.Exchange.ImportOptionsKit importOptionsKit = new Exchange.ImportOptionsKit();
importOptionsKit.SetBRepMode(Exchange.BRepMode.BRepAndTessellation);
importNotifier = HPS.Exchange.File.Import(modelPath, importOptionsKit);
// the notifier can be used to check the load progress
float percent_complete;
importNotifier.Status(out percent_complete);
// pauses this thread until the file is finished loading
importNotifier.Wait();
}
catch (HPS.IOException)
{
// handle exception
throw;
}
Exchange.CADModel myCADModel = importNotifier.GetCADModel();
myCanvas.AttachViewAsLayout(myCADModel.ActivateDefaultCapture());
myCanvas.Update();
// a user selects a wheel on the screen through a mouse
SelectionOptionsKit selection_options = new SelectionOptionsKit();
HPS.SprocketPath mySprocketPath = new SprocketPath(myCanvas);
if (myWindowKey.GetSelectionControl().SelectByPoint(new Point(0, 0, 0), selection_options, out results) > 0)
{
// we obtain a keypath from the selection results
HPS.SelectionItem item = results.GetIterator().GetItem();
HPS.KeyPath path_to_selection;
item.ShowPath(out path_to_selection);
// using the CADModel, we obtain a ComponentPath from the KeyPath
HPS.ComponentPath component_path = myCADModel.GetComponentPath(path_to_selection);
// we figure out at which level is appropriate to insert a transform, so that only the instance of the wheel I selected is affected
HPS.Component transform_target = HPS.Factory.DeInstanceComponent(component_path);
// we apply the transform
HPS.MatrixKit transform = new MatrixKit();
transform.Translate(5, 0, 0);
transform_target.SetTransform(transform);
myCanvas.Update();
}


%%%file_load_result

// get the status of the import
HPS.IOResult result = notifier.Status();
if (result == HPS.IOResult.Success)
{
// file loading successfully
}
// you can cancel the import by calling:
notifier.Cancel();


%%%pmi

HPS.Exchange.ImportOptionsKit importOptions = new HPS.Exchange.ImportOptionsKit();
importOptions.SetPMI(false);


%%%configurations

// get a list of all configurations in the file
HPS.Exchange.Configuration[] configArray = HPS.Exchange.File.GetConfigurations(filename);
for (int i = 0; i < configArray.Length; i++)
{
// get name of configuration
String configName = configArray[i].GetName();
// set configuration
HPS.Exchange.ImportOptionsKit importOptionsKit = new HPS.Exchange.ImportOptionsKit();
importOptionsKit.SetConfiguration(configName);
// configurations can be nested - you can get a list of subconfigurations
HPS.Exchange.Configuration[] subconfigArray = configArray[0].GetSubconfigurations();
}
// at this point, the file can be loaded using the ImportOptionsKit



%%%handling_views

HPS.Capture[] captureArray = modelFile.GetAllCaptures();
for (int i = 0; i < captureArray.Length; i++)
{
Capture capture = captureArray[i];
HPS.StringMetadata metadata = new HPS.StringMetadata(capture.GetMetadata("Name"));
String viewName = metadata.GetValue();
if (viewName == "<some interesting view>")
{
capture.Activate();
break;// exit loop
}
}


%%%handling_metadata

// get all metadata associated with a component
HPS.Metadata[] metadataArray = modelFile.GetAllMetadata();
for (int i = 0; i < metadataArray.Length; i++)
{
HPS.Metadata metadata = metadataArray[i];
// metadata can be of many different types
// you must test for type of metadata
if (metadata.Type() == HPS.Type.StringMetadata)
{
HPS.StringMetadata sm = new HPS.StringMetadata(metadata);
String metadataName = sm.GetName();
String someString = sm.GetValue();
}
else if (metadata.Type() == HPS.Type.DoubleMetadata)
{
HPS.DoubleMetadata dm = new HPS.DoubleMetadata(metadata);
String metadataName = dm.GetName();
double someDouble = dm.GetValue();
}
else if (metadata.Type() == HPS.Type.IntegerMetadata)
{
HPS.IntegerMetadata im = new HPS.IntegerMetadata(metadata);
String metadataName = im.GetName();
int someInteger = im.GetValue();
}
else if (metadata.Type() == HPS.Type.UnsignedIntegerMetadata)
{
String metadataName = uim.GetName();
uint someUnsignedInt = uim.GetValue();
}
else if (metadata.Type() == HPS.Type.TimeMetadata)
{
HPS.TimeMetadata tm = new HPS.TimeMetadata(metadata);
String metadataName = tm.GetName();
uint someUnsignedInt = tm.GetValue();
// as a convenience, TimeMetadata can also be provided as a String
String timeString = tm.GetValueAsString();
}
}


%%%activating_filters

CADModel cadModel = notifier.GetCADModel();
HPS.View myFirstView = cadModel.GetAllCaptures()[0].Activate();
// get list of filters
HPS.Filter[] filters = cadModel.GetAllFilters();
filters[0].Activate(myFirstView); // activate first filter


%%%deactivating_filters

HPS.Filter[] filterArray = modelFile.GetActiveFilters(myFirstView);
for (int i = 0; i < filterArray.Length; i++)
{
HPS.Filter filter = filterArray[i];
// deactivates this filter
filter.Deactivate(myFirstView);
}


%%%exchange_component_reload

HPS.Exchange.ImportNotifier importNotifier = HPS.Exchange.File.Import(filename, importOptionsKit);
importNotifier.Wait();
Exchange.CADModel myCADModel = importNotifier.GetCADModel();
// ... modify PRC via Exchange APIs
Exchange.ReloadNotifier reloadNotifier = exchangeComponent.Reload();
// can query notifier for status or progress
reloadNotifier.Wait(); // will block until the reload thread completes
myCADModel.ActivateDefaultCapture();


%%%exchange_simple_export

try
{
HPS.Exchange.File.ExportJT(modelFile, filename, new HPS.Exchange.ExportJTOptionsKit());
}
{
// handle error
}


%%%exchange_data_mapping

// get HPS-Exchange component interface object for corresponding HPS key
HPS.Component component = modelFile.GetComponentFromKey(hpsKey);
// test if the object type is a product occurrence
// [see table below for other Exchange types]
if (component.GetComponentType() == HPS.Component.ComponentType.ExchangeProductOccurrence)
{
// do something with this object
}
// gets the native Exchange entity that corresponds to the component
HPS.Exchange.Component myExchangeComponent = new Exchange.Component(cadModel.GetSubcomponents()[0]);
// by saving a reference to the Exchange entity, you don't have to create a new Exchange object each time you need to access it
IntPtr exchangeEntity = ((HPS.Exchange.Component) myExchangeComponent).GetExchangeEntity();
// gets the keys associated with the Component
HPS.Key[] keys = component.GetKeys();


%%%simple_export

// the SprocketPath is required to enable the exporter to locate the model
HPS.SprocketPath sprocketPath = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(), view, model);
HPS.KeyPath[] keyPathArray = new HPS.KeyPath[1];
keyPathArray[0] = sprocketPath.GetKeyPath();
// for this simple example, a default ExportOptionsKit is used
HPS.Publish.File.ExportPDF(keyPathArray, filename, new HPS.Publish.ExportOptionsKit());


%%%declarations

HPS.Publish.DocumentKit documentKit = new HPS.Publish.DocumentKit(); // corresponds to a particular view of the model
HPS.Publish.ViewKit viewKit = new HPS.Publish.ViewKit(); // container for Javascript, PMI, and views
HPS.Publish.ArtworkKit artworkKit = new HPS.Publish.ArtworkKit(); // represents the model as an object in the PDF
HPS.Publish.AnnotationKit annotationKit = new HPS.Publish.AnnotationKit(); // corresponds to a page inside the PDF
HPS.Publish.PageKit pageKit = new HPS.Publish.PageKit(); // corresponds to the document itself as a whole


%%%setup_view

HPS.CameraKit cameraKit;
cameraKit = HPS.CameraKit.GetDefault();
viewKit.SetCamera(cameraKit);
viewKit.SetExternalName("My custom view #1");
artworkKit.AddView(viewKit);
// add a second view
cameraKit.SetPosition(new HPS.Point(1, 1, 1));
viewKit.SetCamera(cameraKit);
viewKit.SetExternalName("My custom view #2");
artworkKit.AddView(viewKit);


%%%annotation_kit

HPS.SprocketPath sprocketPath = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(), view, model);
HPS.KeyPath[] keyPathArray = new HPS.KeyPath[1];
keyPathArray[0] = sprocketPath.GetKeyPath();
annotationKit.SetArtwork(artworkKit);
annotationKit.SetSource(keyPathArray);
// set B-rep ccompression to Medium
annotationKit.SetPRCBRepCompression(HPS.Publish.PRC.BRepCompression.Medium);
// use tessellation compression
annotationKit.SetPRCTessellationCompression(true);
// the IntRectangle specifies the area of the page this model will use
pageKit.SetAnnotation(annotationKit, new HPS.IntRectangle(50, 562, 50, 742));
documentKit.AddPage(pageKit);
HPS.Publish.File.ExportPDF(documentKit, filename, new HPS.Publish.ExportOptionsKit());


%%%template_kit

HPS.Publish.PageKit templateKit = new HPS.Publish.PageKit();
templateKit.SetTemplateFile("<path to template file>");
// see note below about the "_1" suffix
templateKit.SetAnnotationByField("My3DWindow_1", annotationKit);
// filling out a few of the template's text fields
templateKit.SetTextValueByField("DocumentTitle_1", "BILL OF MATERIALS");
templateKit.SetTextValueByField("Part NameRow1_1", "Turbine engine");
templateKit.SetTextValueByField("SupplierRow1_1", "Tech Soft 3D");
documentKit.AddPage(templateKit);
HPS.Publish.File.ExportPDF(documentKit, filename, new HPS.Publish.ExportOptionsKit());


%%%linkkit

HPS.Publish.LinkKit myLinkKit = new HPS.Publish.LinkKit();
myLinkKit.SetJavaScript("//activate page 2\n" +
"var a3d = this.getAnnots3D( 1 )[0];\n" +
"a3d.activated=true;\n" +
"c3d = a3d.context3D;\n" +
"c3d.runtime.setView(\"ALL\", true);\n");
myLinkKit.SetBorderWidth(1);
myLinkKit.SetBorderColor(new HPS.RGBColor(0));
myLinkKit.SetHighlighting(HPS.Publish.Highlighting.Mode.Invert);
pageKit.AddLink(myLinkKit, new HPS.IntRectangle(251, 361, 229, 255));


%%%component_mask

if (component.HasComponentType(HPS.Component.ComponentType.ExchangePMIMask))
{
// it is a piece of PMI
}
if (component.HasComponentType(HPS.Component.ComponentType.ExchangeTopologyMask))
{
// it is topology
}
if (component.HasComponentType(HPS.Component.ComponentType.ExchangeRepresentationItemMask))
{
// it is a representation item
}


%%%create_document

HPS.Publish.DocumentKey myDocumentKey = HPS.Publish.File.CreateDocument(filename);
// to create an empty in-memory document, pass a null pointer
HPS.Publish.DocumentKey myEmptyDocumentKey = HPS.Publish.File.CreateDocument(null);


%%%modify_document

// gets number of pages in this PDF document
ulong pageCount = myDocumentKey.GetPageCount();
// add an attachment to the document
myDocumentKey.AddAttachment(attachmentFilename, attachmentDescription);
// set new passwords for the document
myDocumentKey.SetPasswords(newUserPassword, newOwnerPassword);


%%%page_control

// gets the control for the first page of this document
HPS.Publish.PageControl myPageControl = myDocumentKey.GetPageControl(0);
// adds new text to this page
myPageControl.AddText(myTextKit, new HPS.IntRectangle(50, 400, 50, 200));
// adds a table to this page
// NOTE: adding tables requires the TableToPDF add-on
myPageControl.AddTable(myTableKit, new HPS.IntRectangle(200, 100, 200, 500));
// adds an annotation to this page (required for export)
myPageControl.AddAnnotation(myAnnotationKit, new HPS.IntRectangle(200, 300, 200, 500));


%%%export_document

HPS.Publish.File.ExportPDF(myDocumentKey, filename);


%%%skp_import

HPS.Sketchup.ImportOptionsKit iok = new HPS.Sketchup.ImportOptionsKit();
iok.SetTarget(myModel); // HPS.Model import location
iok.SetView(myView); // HPS.View will have the main camera - optional
HPS.Sketchup.ImportNotifier notifier = HPS.Sketchup.File.Import(filename, iok);
notifier.Wait(); // wait for this model to finish loading


%%%parasolid_add_body

/*** create a parasolid body and add it at the top level of an existing Exchange model ***/
Exchange.ImportOptionsKit import_kit = Exchange.ImportOptionsKit.GetDefault();
import_kit.SetPMI(false); // omitting PMI for better visibility of new body
Exchange.ImportNotifier notifier = Exchange.File.Import(my_cad_file, import_kit);
notifier.Wait();
HPS.CADModel cad_model = notifier.GetCADModel();
Exchange.CADModel exchange_cad_model = new Exchange.CADModel(cad_model);
View view1 = cad_model.ActivateDefaultCapture();
// create a Parasolid body (a cube)
PK.BODY_t solid_body = PK.ENTITY_t.@null;
PK.BODY.create_solid_block(0.05f, 0.05f, 0.05f, null, &solid_body); // parasolid dimensions in meters
//make the cube red
PK.ATTDEF_t system_color;
PK.ERROR.code_t error = PK.ATTDEF.find("SDL/TYSA_COLOUR_2", &system_color);
PK.ATTRIB_t color_attribute;
error = PK.ATTRIB.create_empty(solid_body, system_color, &color_attribute);
double [] color = { 1, 0, 0 };
error = PK.ATTRIB.set_doubles(color_attribute, 0, 3, color);
// apply a translation matrix to the cube we're adding
MatrixKit translation = new MatrixKit();
translation.Translate(100.0f, 0.0f, 50.0f);
// add cube to existing CAD Model
HPS.Parasolid.Component added_component = ExchangeParasolid.File.AddEntity(exchange_cad_model, solid_body, translation);
// retrieve the Parasolid entity for inspection
PK.ENTITY_t entity = added_component.GetParasolidEntity();
PK.CLASS_t entity_type;
PK.ENTITY.ask_class(entity, &entity_type);


%%%parasolid_import

iok.SetFormat(HPS.Parasolid.Format.Text);
HPS.Parasolid.ImportNotifier notifier = HPS.Parasolid.File.Import(filename, iok);
notifier.Wait(); // wait for this model to finish loading


%%%parasolid_import_options

// setting up the facet tessellation kit
ftk.SetNormals(true);
ftk.SetFacetSize(1.0, 3.0, 10);
// setting up the line tessellation kit
ltk.SetEdges(true, true);
ltk.SetIgnoreCriteria(false);
// setting the tessellation kits on the import options kit
HPS.Parasolid.ImportOptionsKit iok = Parasolid.ImportOptionsKit.GetDefault();
iok.SetCompoundBodyBehavior(HPS.Parasolid.CompoundBodyBehavior.Split);
iok.SetFacetTessellation(ftk);
iok.SetLineTessellation(ltk);
iok.SetFormat(HPS.Parasolid.Format.Text);


%%%import_default_options

// load and translate a file using the default options
try
{
ExchangeParasolid.ImportNotifier notifier = HPS.ExchangeParasolid.File.Import(
filename, //the file to import
Exchange.ImportOptionsKit.GetDefault().SetHiddenObjects(false), //options for reading the file with Exchange
Exchange.TranslationOptionsKit.GetDefault(), //options for translating the file to Parasolid
Parasolid.FacetTessellationKit.GetDefault(), //options for Parasolid facet tessellation
Parasolid.LineTessellationKit.GetDefault()); //options for Parasolid line tessellation
notifier.Wait();
HPS.CADModel modelFile = notifier.GetCADModel();
// get the View and attach it to the Canvas
HPS.View myView = modelFile.ActivateDefaultCapture();
myCanvas.AttachViewAsLayout(myView);
// alternatively, if you already have a View object, you can simply
// get the Model and attach it directly:
HPS.Model model = modelFile.GetModel();
myView.AttachModel(model);
}
{
// handle error
}


%%%query_cad_model

// Query the CADModel for its children components
HPS.Component[] subcomponents = cad_model.GetSubcomponents();
if (!subcomponents.empty())
{
// Check that the component type of the first child component is Exchange Product Occurrence
Component.ComponentType component_type = subcomponents[0].GetComponentType();
if (component_type == Component.ComponentType.ExchangeProductOccurrence)
{
// Since we know this component is an Exchange component, we can set it to
// an Exchange.Component object and access its data
Exchange.Component exchange_component = new Exchange.Component(subcomponents[0]);
IntPtr entity = exchange_component.GetExchangeEntity();
// We can now use the Exchange native API to interact with it
HPS.Component pocc_data = cad_model.GetSubcomponents()[0];
}
}
// Now let's look for all subcomponents of the CADModel which are Parasolid Topological Faces
subcomponents = cad_model.GetAllSubcomponents(Component.ComponentType.ParasolidTopoFace);
if (!subcomponents.empty())
{
// Check that the component type of the first Parasolid Topo Face we found is indeed
// a Parasolid component by checking its type mask
if (subcomponents[0].HasComponentType(Component.ComponentType.ParasolidComponentMask))
{
// Since we know this component is a Parasolid component, we can cast it to
// a Parasolid.Component object and access its data
Parasolid.Component parasolid_component = new Parasolid.Component(subcomponents[0]);
PK.ENTITY_t entity = parasolid_component.GetParasolidEntity();
// We can now use the Parasolid native API to interact with it
PK.SURF_t surface;
PK.FACE.ask_surf(entity, &surface);
}
}


%%%fillet_retessellate

//Load a model, fillet an edge using parasolid, and retessellate it to see the result
//Load a model and translate it to Parasolid
Exchange.ImportOptionsKit exchange_import = Exchange.ImportOptionsKit.GetDefault();
exchange_import.SetBRepMode(Exchange.BRepMode.BRepAndTessellation);
Exchange.TranslationOptionsKit translation_options = Exchange.TranslationOptionsKit.GetDefault();
ExchangeParasolid.ImportNotifier notifier = ExchangeParasolid.File.Import(
filename, exchange_import, translation_options,
Parasolid.FacetTessellationKit.GetDefault(), Parasolid.LineTessellationKit.GetDefault());
notifier.Wait();
if (notifier.Status() != IOResult.Success)
{
//handle error
}
View myView = notifier.GetCADModel().ActivateDefaultCapture();
myCanvas.AttachViewAsLayout(myView);
HPS.CADModel modelFile = notifier.GetCADModel();
HPS.Model model = modelFile.GetModel();
myView.AttachModel(model);
//find the edges, and pick the first one
CADModel cad_model = notifier.GetCADModel();
HPS.Component[] edge_components = cad_model.GetAllSubcomponents(Component.ComponentType.ParasolidTopoEdge);
if (edge_components.empty())
{
//handle the error
}
Parasolid.Component para_edge_component = new Parasolid.Component(edge_components[0]);
PK.EDGE_t[] edge_entity = new PK.EDGE_t[1];
edge_entity[0] = para_edge_component.GetParasolidEntity();
//find the body which owns this edge, by traversing the parents of the edge, until when we find a body
HPS.Component owner = para_edge_component.GetOwners()[0];
while (owner.GetComponentType() != HPS.Component.ComponentType.ParasolidTopoBody)
owner = owner.GetOwners()[0];
//set the blends on the edge
int number_of_edges = 0;
PK.EDGE_t* edges = null;
PK.EDGE.set_blend_constant_o_t blend_options = new PK.EDGE.set_blend_constant_o_t(true);
PK.ERROR.code_t error = PK.EDGE.set_blend_constant(1, edge_entity, 0.005, &blend_options, &number_of_edges, &edges);
if (error != PK.ERROR.code_t.no_errors)
{
//handle the error
}
//commit the blends on the body which owns this edge
int number_of_blend_faces = 0;
PK.FACE_t* created_blend_faces = null;
PK.FACE.array_t* underlying_topology = null;
int* replaced_topologies = null;
PK.blend_fault_t status = PK.blend_fault_t.no_fault_c;
PK.EDGE_t faulty_edge = PK.EDGE_t.@null;
PK.ENTITY_t topology_associated_with_fault = PK.EDGE_t.@null;
PK.BODY.fix_blends_o_v fix_blend_options = new PK.BODY.fix_blends_o_v(true);
HPS.Parasolid.Component para_component = new HPS.Parasolid.Component(owner);
error = PK.BODY.fix_blends(para_component.GetParasolidEntity(), &fix_blend_options, &number_of_blend_faces, &created_blend_faces, &underlying_topology, &replaced_topologies, &status, &faulty_edge, &topology_associated_with_fault);
if (error != PK.ERROR.code_t.no_errors || (status != PK.blend_fault_t.no_fault_c && status != PK.blend_fault_t.repaired_c))
{
//handle the error
}
//retessellate the body to update the component structure and see the result on screen
para_component.Tessellate(facet_tessellation, HPS.Parasolid.LineTessellationKit.GetDefault());
myCanvas.Update();


%%%%00760_exchange_parasolid_boolean_operator_class

class TestBooleanOperator : HPS.Operator
{
private HPS.Canvas canvas;
private HPS.CADModel cad_model;
private HPS.View attached_view;
private PK.BODY_t target;
private HPS.Component target_component;
private HPS.KeyPath target_path;
private PK.BODY_t tool;
private HPS.Component tool_component;
private HPS.KeyPath tool_path;
private HPS.WindowPoint click_location;
private HPS.SelectionOptionsKit selection_options;
private HPS.SegmentKey target_style_source;
private HPS.HighlightOptionsKit target_highlight;
private HPS.SegmentKey tool_style_source;
private HPS.HighlightOptionsKit tool_highlight;
public TestBooleanOperator(ref Canvas in_canvas, ref CADModel in_cad_model)
{
canvas = in_canvas;
cad_model = in_cad_model;
attached_view = new HPS.View();
target = PK.ENTITY_t.@null;
target_component = new HPS.Component();
target_path = new HPS.KeyPath();
tool = PK.ENTITY_t.@null;
tool_component = new HPS.Component();
tool_path = new HPS.KeyPath();
click_location = new HPS.WindowPoint();
selection_options = new HPS.SelectionOptionsKit();
target_style_source = new SegmentKey();
target_highlight = new HighlightOptionsKit();
tool_style_source = new SegmentKey();
tool_highlight = new HighlightOptionsKit();
}
public override string GetName()
{
return "TestBooleanOperator";
}
public override bool OnMouseDown(HPS.MouseState in_state)
{
if (IsMouseTriggered(in_state))
{
click_location = in_state.GetLocation();
}
return false;
}
public override bool OnMouseUp(MouseState in_state)
{
if (!IsMouseTriggered(in_state) && in_state.GetLocation() == click_location)
{
ulong count = canvas.GetWindowKey().GetSelectionControl().SelectByPoint(click_location, selection_options, out results);
if (count == 0)
return false;
HPS.SelectionResultsIterator s_it = results.GetIterator();
while (s_it.IsValid())
{
HPS.KeyPath selected_path;
s_it.GetItem().ShowPath(out selected_path);
HPS.ComponentPath component_path = cad_model.GetComponentPath(selected_path);
HPS.Component[] components = component_path.GetComponents();
foreach (HPS.Component it in components)
{
if (it.GetComponentType() == HPS.Component.ComponentType.ParasolidTopoBody)
{
HPS.Parasolid.Component para_component = new HPS.Parasolid.Component(it);
HPS.HighlightControl highlight_control = canvas.GetWindowKey().GetHighlightControl();
PK.ENTITY_t selected_parasolid_entity = para_component.GetParasolidEntity();
if (target == selected_parasolid_entity)
{
//deselect target
highlight_control.Unhighlight(selected_path, target_highlight);
canvas.Update();
target = PK.ENTITY_t.@null;
target_component.Reset();
target_path.Reset();
return true;
}
else if (tool == selected_parasolid_entity)
{
//deselect tool
highlight_control.Unhighlight(selected_path, tool_highlight);
canvas.Update();
tool = PK.ENTITY_t.@null;
tool_component.Reset();
tool_path.Reset();
return true;
}
else if (target == PK.ENTITY_t.@null)
{
target = selected_parasolid_entity;
target_component = it;
target_path = selected_path;
highlight_control.Highlight(selected_path, target_highlight);
canvas.Update();
return true;
}
else
{
tool = selected_parasolid_entity;
tool_component = it;
tool_path = selected_path;
highlight_control.Highlight(selected_path, tool_highlight);
canvas.Update();
return true;
}
}
}
s_it.Next();
}
return true;
}
return false;
}
public override void OnViewAttached(HPS.View in_attached_view)
{
attached_view = GetAttachedView();
HPS.SprocketPath sprocket_path = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(), attached_view, attached_view.GetAttachedModel());
selection_options.SetAlgorithm(HPS.Selection.Algorithm.Visual)
.SetLevel(HPS.Selection.Level.Entity)
.SetScope(sprocket_path.GetKeyPath());
//Create target style
target_style_source = HPS.Database.CreateRootSegment();
HPS.MaterialKit highlight_material = new HPS.MaterialKit();
HPS.RGBAColor color_1 = new HPS.RGBAColor(0, 0.8f, 0.0f, 0.3f);
highlight_material.SetDiffuse(color_1);
HPS.RGBAColor color_2 = new HPS.RGBAColor(1.0f, 0.847f, 0.0f);
highlight_material.SetSpecular(color_2);
HPS.RGBAColor color_3 = new HPS.RGBAColor(0, 0.8f, 0);
target_style_source.GetMaterialMappingControl()
.SetFaceMaterial(highlight_material)
.SetEdgeColor(color_3)
.SetTextColor(color_3)
.SetLineColor(color_3);
HPS.PortfolioKey portfolio = attached_view.GetPortfolioKey();
portfolio.DefineNamedStyle("BooleanOperator_TargetStyle", target_style_source);
target_highlight.SetOverlay(HPS.Drawing.Overlay.None).SetStyleName("BooleanOperator_TargetStyle");
//Create tool style
tool_style_source = HPS.Database.CreateRootSegment();
HPS.RGBAColor color_4 = new HPS.RGBAColor(1.0f, 0.647f, 0.0f, 1.0f);
highlight_material.SetDiffuse(color_4);
tool_style_source.GetMaterialMappingControl()
.SetFaceMaterial(highlight_material)
.SetEdgeColor(color_4)
.SetTextColor(color_4)
.SetLineColor(color_4);
portfolio.DefineNamedStyle("BooleanOperator_ToolStyle", tool_style_source);
tool_highlight.SetOverlay(HPS.Drawing.Overlay.None).SetStyleName("BooleanOperator_ToolStyle");
}
public override void OnViewDetached(HPS.View in_detached_view)
{
if (canvas.Type() != HPS.Type.None)
{
HPS.HighlightControl highlight_control = canvas.GetWindowKey().GetHighlightControl();
highlight_control.Unhighlight(target_highlight);
highlight_control.Unhighlight(tool_highlight);
HPS.PortfolioKey portfolio_key = attached_view.GetPortfolioKey();
portfolio_key.UndefineNamedStyle("BooleanOperator_TargetStyle");
portfolio_key.UndefineNamedStyle("BooleanOperator_ToolStyle");
target_style_source.Delete();
tool_style_source.Delete();
canvas.Update();
}
}
unsafe public bool ApplyBoolean()
{
canvas.GetWindowKey().GetHighlightControl().UnhighlightEverything();
//Now that we have all the data we need for the boolean target and tool, we move on to performing the boolean operation itself
//Step 1: Transform the tool, so that it is in the same frame of reference as the target
MatrixKit target_matrix;
target_path.ShowNetModellingMatrix(out target_matrix);
MatrixKit tool_matrix;
tool_path.ShowNetModellingMatrix(out tool_matrix);
MatrixKit transform_matrix = target_matrix.Invert();
transform_matrix.MultiplyAndAssign(tool_matrix);
MatrixKit matrix = new MatrixKit();
if (transform_matrix != matrix)
{
//The matrix has to be specified in meters.
//The imported model uses millimeters as its units, so we will need to scale the matrix accordingly
double scale = 0.001;
//Recreate the matrix into Parasolid
float[] elements;
transform_matrix.ShowElements(out elements);
PK.TRANSF_sf_t transform_data;
transform_data.matrixI0J0 = elements[0]; transform_data.matrixI1J0 = elements[1]; transform_data.matrixI2J0 = elements[2]; transform_data.matrixI3J0 = elements[3];
transform_data.matrixI0J1 = elements[4]; transform_data.matrixI1J1 = elements[5]; transform_data.matrixI2J1 = elements[6]; transform_data.matrixI3J1 = elements[7];
transform_data.matrixI0J2 = elements[8]; transform_data.matrixI1J2 = elements[9]; transform_data.matrixI2J2 = elements[10]; transform_data.matrixI3J2 = elements[11];
transform_data.matrixI0J3 = elements[12] * scale; transform_data.matrixI1J3 = elements[13] * scale; transform_data.matrixI2J3 = elements[14] * scale; transform_data.matrixI3J3 = elements[15];
PK.TRANSF_t transform;
PK.TRANSF.create(&transform_data, &transform);
//Transform the tool using it
PK.BODY.transform_o_t transform_options = new PK.BODY.transform_o_t(true);
PK.TOPOL.track_r_t tracking_1;
PK.TOPOL.local_r_t results;
PK.ERROR.code_t error_1 = PK.BODY.transform_2(tool, transform, 0.001, &transform_options, &tracking_1, &results);
//Check that the transformation completed successfully
if (error_1 != PK.ERROR.code_t.no_errors)
return false;
else if (results.status != PK.local_status_t.ok_c && results.status != PK.local_status_t.nocheck_c)
return false;
}
//Step 2: Determine whether both entities are faceted, both have b-rep data available, or if they are mixed.
//Both entities need to be either faceted or both need to have b-rep data available.
//In the case where they are not the same, we convert the entity with b-rep to a faceted entity
bool target_faceted = IsEntityFaceted(target);
bool tool_faceted = IsEntityFaceted(tool);
//Step 3: If one of the bodies is faceted and the other isn't we need to convert the non-faceted one to
//a faceted body as well.
PK.BODY_t facet_body = PK.ENTITY_t.@null;
PK.TOPOL.track_r_t tracking;
PK.ERROR.code_t error = PK.ERROR.code_t.no_errors;
if (tool_faceted != target_faceted)
{
PK.BODY_t classical_body = PK.ENTITY_t.@null;
if (!tool_faceted)
classical_body = tool;
else if (!target_faceted)
classical_body = target;
PK.BODY.make_facet_body_o_t make_facet_options = new PK.BODY.make_facet_body_o_t(true);
PK.TOPOL.track_r_t redundant_topol;
error = PK.BODY.make_facet_body(classical_body, PK.ENTITY_t.@null, &make_facet_options, &facet_body, &tracking, &redundant_topol);
if (error != PK.ERROR.code_t.no_errors)
return false;
}
//Step 4. Perform the boolean operation
PK.BODY.boolean_o_t boolean_options = new PK.BODY.boolean_o_t(true);
boolean_options.function = PK.boolean_function_t.subtract;
PK.boolean_r_t boolean_results;
PK.BODY_t tool_to_use = tool;
PK.BODY_t target_to_use = target;
if (facet_body != PK.ENTITY_t.@null && !tool_faceted)
tool_to_use = facet_body;
else if (facet_body != PK.ENTITY_t.@null && !target_faceted)
target_to_use = facet_body;
error = PK.BODY.boolean_2(target_to_use, 1, &tool_to_use, &boolean_options, &tracking, &boolean_results);
if (error == PK.ERROR.code_t.no_errors
&& boolean_results.result == PK.boolean_result_t.success_c
&& boolean_results.n_bodies > 0)
{
//Step 5. Show the result:
for (int i = 0; i < boolean_results.n_bodies; ++i)
{
//In this case there will only be a single resulting body from the boolean, the modified target entity.
//We re-tessellate it to sync the Parasolid changes with the Visualize representation of the part
if (boolean_results.bodies[i] != target)
return false;
HPS.Parasolid.Component parasolid_target_component = new HPS.Parasolid.Component(target_component);
//In the case where we have multiple bodies resulting from a boolean operation (for example if a boolean results in the
//target body being cut in half), we will need to Add the bodies which were not previously in the scene to it, using the
//ExchangeParasolid.File.AddEntity function
}
//Delete the Visualize component associated with the tool, since the boolean operation deleted its associated Parasolid body
tool_component.Delete();
return true;
}
else
return false;
}
unsafe private bool IsEntityFaceted(PK.BODY_t body)
{
int number_of_faces = 0;
PK.FACE_t* faces = null;
PK.ERROR.code_t error = PK.BODY.ask_faces(body, &number_of_faces, &faces);
if (error != PK.ERROR.code_t.no_errors || number_of_faces == 0)
{
//something went wrong
return false;
}
PK.SURF_t surface;
error = PK.FACE.ask_surf(faces[0], &surface);
if (error != PK.ERROR.code_t.no_errors)
{
//something went wrong
return false;
}
PK.GEOM.ask_geom_category_o_t geom_options = new PK.GEOM.ask_geom_category_o_t(true);
PK.GEOM.category_t category;
error = PK.GEOM.ask_geom_category(surface, &geom_options, &category);
if (error != PK.ERROR.code_t.no_errors)
{
//something went wrong
return false;
}
if (category == ((PK.GEOM.category_t)25871))
return true;
else if (category == ((PK.GEOM.category_t)25870))
return false;
return false;
}
}


%%%%00760_exchange_parasolid_boolean_setup

bool setUpScene(ref HPS.Canvas myCanvas, string importFileTarget, string importFileTool)
{
Exchange.ImportOptionsKit kit = Exchange.ImportOptionsKit.GetDefault();
kit.SetBRepMode(Exchange.BRepMode.BRepAndTessellation);
//load the first file
ExchangeParasolid.ImportNotifier notifier = ExchangeParasolid.File.Import(importFileTarget, kit,
Exchange.TranslationOptionsKit.GetDefault(),
Parasolid.FacetTessellationKit.GetDefault(),
Parasolid.LineTessellationKit.GetDefault());
notifier.Wait();
if (notifier.Status() != IOResult.Success)
return false; // something went wrong
CADModel cadmodel = notifier.GetCADModel();
//load the second file by adding it to the scene
Component[] location = { cadmodel };
ComponentPath path = new ComponentPath(location);
kit.SetLocation(path);
notifier = ExchangeParasolid.File.Import(importFileTool, kit,
Exchange.TranslationOptionsKit.GetDefault(),
Parasolid.FacetTessellationKit.GetDefault(),
Parasolid.LineTessellationKit.GetDefault());
notifier.Wait();
if (notifier.Status() != IOResult.Success)
return false; // something went wrong
//attach the view to the canvas, and setup a nice camera
View view = cadmodel.ActivateDefaultCapture();
myCanvas.AttachViewAsLayout(view);
HPS.CameraKit camera_kit = new HPS.CameraKit();
Point position = new Point(-116.158989f, -2172.083008f, 921.859985f);
Point target = new Point(-0.000153f, -89.000000f, 117.000000f);
Vector up_vector = new Vector(-0.004887f, -0.360171f, -0.932874f);
camera_kit.SetPosition(position)
.SetTarget(target)
.SetUpVector(up_vector)
.SetField(894.474365f, 894.474365f)
.SetNearLimit(0.000000f)
.SetProjection(HPS.Camera.Projection.Orthographic);
view.GetSegmentKey().SetCamera(camera_kit);
Vector distant_light = new Vector(1, 0, 0);
view.GetSegmentKey().InsertDistantLight(distant_light);
myCanvas.Update();
TestBooleanOperator boolean_operator = new TestBooleanOperator(ref myCanvas, ref cadmodel);
view.GetOperatorControl().Push(boolean_operator, HPS.Operator.Priority.Default);
return true;
}


%%%%00760_exchange_parasolid_boolean_instantiate

TestBooleanOperator boolean_operator = new TestBooleanOperator(ref myCanvas, ref cadmodel);
view.GetOperatorControl().Push(boolean_operator, HPS.Operator.Priority.Default);


%%%%00760_exchange_parasolid_boolean_execute

void executeBooleanOperation(ref HPS.Canvas myCanvas)
{
HPS.Operator myOperator = new HPS.Operator();
myCanvas.GetFrontView().GetOperatorControl().ShowTop(out myOperator);
if (myOperator.GetName() == "TestBooleanOperator")
{
TestBooleanOperator op = (TestBooleanOperator)myOperator;
op.ApplyBoolean();
myCanvas.UpdateWithNotifier().Wait();
}
}


%%%%00760_exchange_parasolid_boolean_retrieve

HPS.Operator myOperator = new HPS.Operator();
myCanvas.GetFrontView().GetOperatorControl().ShowTop(out myOperator);
if (myOperator.GetName() == "TestBooleanOperator")
{
TestBooleanOperator op = (TestBooleanOperator)myOperator;
op.ApplyBoolean();
myCanvas.UpdateWithNotifier().Wait();
}


%%%%00760_exchange_parasolid_boolean_selection_logic

public override bool OnMouseUp(MouseState in_state)
{
if (!IsMouseTriggered(in_state) && in_state.GetLocation() == click_location)
{
ulong count = canvas.GetWindowKey().GetSelectionControl().SelectByPoint(click_location, selection_options, out results);
if (count == 0)
return false;
HPS.SelectionResultsIterator s_it = results.GetIterator();
while (s_it.IsValid())
{
HPS.KeyPath selected_path;
s_it.GetItem().ShowPath(out selected_path);
HPS.ComponentPath component_path = cad_model.GetComponentPath(selected_path);
HPS.Component[] components = component_path.GetComponents();
foreach (HPS.Component it in components)
{
if (it.GetComponentType() == HPS.Component.ComponentType.ParasolidTopoBody)
{
HPS.Parasolid.Component para_component = new HPS.Parasolid.Component(it);
HPS.HighlightControl highlight_control = canvas.GetWindowKey().GetHighlightControl();
PK.ENTITY_t selected_parasolid_entity = para_component.GetParasolidEntity();
if (target == selected_parasolid_entity)
{
//deselect target
highlight_control.Unhighlight(selected_path, target_highlight);
canvas.Update();
target = PK.ENTITY_t.@null;
target_component.Reset();
target_path.Reset();
return true;
}
else if (tool == selected_parasolid_entity)
{
//deselect tool
highlight_control.Unhighlight(selected_path, tool_highlight);
canvas.Update();
tool = PK.ENTITY_t.@null;
tool_component.Reset();
tool_path.Reset();
return true;
}
else if (target == PK.ENTITY_t.@null)
{
target = selected_parasolid_entity;
target_component = it;
target_path = selected_path;
highlight_control.Highlight(selected_path, target_highlight);
canvas.Update();
return true;
}
else
{
tool = selected_parasolid_entity;
tool_component = it;
tool_path = selected_path;
highlight_control.Highlight(selected_path, tool_highlight);
canvas.Update();
return true;
}
}
}
s_it.Next();
}
return true;
}
return false;
}


%%%relative_tessellation

ftk.SetTessellationLevel(HPS.Parasolid.TessellationLevel.Medium);


%%%parasolid_subcomponent

iok.SetFormat(HPS.Parasolid.Format.Text);
HPS.Parasolid.ImportNotifier notifier = HPS.Parasolid.File.Import(filename, iok);
notifier.Wait(); // wait for this model to finish loading
// get the CAD model object
HPS.Parasolid.CADModel cadModel = notifier.GetCADModel();
// get the top-level assemblies
HPS.Component[] assemblies = cadModel.GetSubcomponents();


%%%parasolid_default_view

HPS.Canvas myCanvas = HPS.Factory.CreateCanvas(myWindowKey);
// ...
// get a reference to the model view
HPS.View view = notifier.GetCADModel().ActivateDefaultCapture();
// attach the view to the canvas
myCanvas.AttachViewAsLayout(view);


%%%parasolid_metadata

HPS.Metadata metadata = cadModel.GetMetadata("Filename");
// "Filename" is always returned as a string, so we use a StringMetadata object
HPS.StringMetadata stringMetadata = new HPS.StringMetadata(metadata);
// getting the value of the "Filename" metadata
String filename_value = stringMetadata.GetValue();


%%%parasolid_create_cad_model


%%%parasolid_entity_creation

PK.BODY_t solid_body = PK.ENTITY_t.@null;
PK.BODY.create_solid_block(0.05, 0.05, 0.05, null, &solid_body);
// add solid block to root entity
HPS.Component myNewComponent =
cadModel.AddEntity(solid_body, HPS.Parasolid.FacetTessellationKit.GetDefault(),
// check to make sure it was inserted correctly
if (myNewComponent.GetComponentType() != HPS.Component.ComponentType.ParasolidTopoBody)
{
// if you get here, something went wrong
}
// get the underlying Visualize keys which represent this component
Key[] componentKeys = myNewComponent.GetKeys();


%%%parasolid_retessellate

ftk.SetFacetPlaneTolerance(7.3, 1.0).SetChordTolerance(5.0, 5.3, 1.0);
ltk = Parasolid.LineTessellationKit.GetDefault();
ltk.SetChordTolerance(0, 0, 1.3);
component.Tessellate(ftk, ltk);
// the next update yields a retessellated model
myCanvas.Update();


%%%parasolid_export

export_options.SetFormat(HPS.Parasolid.Format.Text).SetUserFields(true);
HPS.Parasolid.File.Export(cadModel, outfile, export_options);


%%%publish_button_kit

// add button to the page
buttonKit.SetLabel("This is a page button")
.SetLabelPosition(HPS.Publish.Label.Position.OnTop)
.SetHighlighting(HPS.Publish.Highlighting.Mode.Push)
.SetVisibility(true)
.SetFont(HPS.Publish.Text.Font.Name.TimesRoman)
.SetFontSize(8)
.SetTextColor(new HPS.RGBColor(0, 0, 0))
.SetFillColor(new HPS.RGBColor(0.5f, 0.5f, 0.5f))
.SetName("execute_button"); // setting the name of the button is required!
pageKit.AddButton(buttonKit, new HPS.IntRectangle(0, 120, 400, 450));


%%%publish_button_javascript

HPS.Publish.PageKit myPageKit = new HPS.Publish.PageKit();
// ... create buttons
// specify Javascript as a string
myPageKit.SetJavaScriptActionByField("execute_button", myJavascriptSource,
HPS.Publish.Source.Type.Code);
// source the Javascript from a file - "myJavascriptSource" is a file name
myPageKit.SetJavaScriptActionByField("execute_button", myJavascriptSource,
HPS.Publish.Source.Type.Code);


%%%publish_table_source

HPS.Publish.TableKit tableKit = new HPS.Publish.TableKit();
tableKit.SetHTML(myHTML_source); // specify HTML source
tableKit.SetHTMLStyle(myCSS_source); // specify CSS source


%%%publish_table_text

HPS.Publish.TextKit textKit = new HPS.Publish.TextKit();
textKit.SetColor(new RGBColor(1, 0, 0))
.SetFont(Publish.Text.Font.Name.Courier)
.SetSize(12)
.SetText("My table text");
// set text in row 1, column 1
tableKit.SetText(1, 1, textKit);


%%%publish_table_button

buttonKit.SetLabel("button 1").
SetLabelPosition(HPS.Publish.Label.Position.OnTop).
SetVisibility(true).
SetName("b1"); // setting a name is required!
tableKit.SetButton(2, 1, buttonKit);


%%%publish_export_subtree

// get the path of the part you want to export
HPS.KeyPath[] keyPath = HPS.Component.GetKeyPath(componentModel[0]);
// set the path on the AnnotationKit
annotationKit.SetSource(keyPath);
// for this simple example, a default ExportOptionsKit is used
HPS.Publish.File.ExportPDF(annotationKit,
output_filename,


%%%MyEventHandler

class MyEventHandler : HPS.EventHandler
{
public override HandleResult Handle(HPS.Event in_event)
{
// do any processing or recovery logic here
return HandleResult.Handled; // or return NotHandled, as the case may be
}
};


%%%dispatcher

MyEventHandler myHandler = new MyEventHandler();
// adds handler to dispatcher's subscription stack
dispatcher.Subscribe(myHandler, HPS.Object.ClassID<HPS.ErrorEvent>());
// removes this handler from the subscription stack
dispatcher.UnSubscribe(myHandler, HPS.Object.ClassID<HPS.ErrorEvent>());


%%%MyEvent

class MyEvent : HPS.Event
{
public MyEvent() : base() { }
public MyEvent(IntPtr type) : base(type) { }
// called internally to copy an event. in the case your event contains pointers or dynamically
// allocated data, this function needs to be set up to handle the cloning
public override Event Clone() { return new MyEvent(GetChannel()); }
};


%%%dispatch_MyEvent

MyEvent myEvent = new MyEvent(HPS.Object.ClassID<MyEvent>());
dispatcher.InjectEvent(myEvent); // this event will be sent to the handler


%%%event_status

HPS.EventNotifier eventNotifier = dispatcher.InjectEventWithNotifier(myEvent);
if (eventNotifier.Status() == HPS.Event.Status.InProgress)
{
// the event has not yet been processed
}
if (eventNotifier.Status() == HPS.Event.Status.Completed)
{
// the event has been processed
}


%%%wait

eventNotifier.Wait();


%%%custom_event

MyEventHandler myEventHandler = new MyEventHandler();
HPS.EventDispatcher dispatcher = myCanvas.GetWindowKey().GetEventDispatcher();
// set the channel number to this object's ClassID
dispatcher.Subscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
// inject this new event into the dispatcher
MyCustomEvent myEvent = new MyCustomEvent(HPS.Object.ClassID<MyCustomEvent>());
// cleanup
dispatcher.UnSubscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());


%%%custom_event_full_source

class MyCustomEvent : HPS.Event
{
private int myRandomNumber; // this member is just for demonstration purposes
public MyCustomEvent() : base()
{
}
public MyCustomEvent(IntPtr type) : base(type)
{
}
public MyCustomEvent(IntPtr type, int randomNumber) : base(type)
{
myRandomNumber = randomNumber;
}
public override Event Clone()
{
MyCustomEvent new_event = new MyCustomEvent(GetChannel(), myRandomNumber);
return new_event;
}
public override bool Drop(Event in_that_event)
{
bool drop_status = false;
// add logic here to determine if event can be dropped
// let's drop the Event if its randomNumber member is divisible by 3
if ((myRandomNumber % 3) == 0)
drop_status = true;
return drop_status;
}
public int getMyRandomNumber()
{
return this.myRandomNumber;
}
};
public class MyEventHandler : HPS.EventHandler
{
~MyEventHandler() { Shutdown(); } // IMPORTANT
public override HandleResult Handle(HPS.Event in_event)
{
MyCustomEvent myEvent = (MyCustomEvent)in_event;
// ... do some logic
return HandleResult.Handled; // or return NotHandled, as the case may be
}
};
void injectSingleEvent(ref HPS.Canvas canvas)
{
HPS.Canvas myCanvas = canvas;
MyEventHandler myEventHandler = new MyEventHandler();
HPS.EventDispatcher dispatcher = myCanvas.GetWindowKey().GetEventDispatcher();
// set the channel number to this object's ClassID
dispatcher.Subscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
// inject this new event into the dispatcher
MyCustomEvent myEvent = new MyCustomEvent(HPS.Object.ClassID<MyCustomEvent>());
// inject this new event into the dispatcher
dispatcher.InjectEvent(myEvent);
// cleanup
dispatcher.UnSubscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
}
void injectManyEvents(ref HPS.Canvas canvas)
{
HPS.Canvas myCanvas = canvas;
MyEventHandler myEventHandler = new MyEventHandler();
HPS.EventDispatcher dispatcher = myCanvas.GetWindowKey().GetEventDispatcher();
dispatcher.Subscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
// To activate the Drop() function, let's quickly load 100 Events into the the Event pipeline.
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
int randomNumber = rand.Next();
MyCustomEvent myEvent = new MyCustomEvent(HPS.Object.ClassID<MyCustomEvent>(), randomNumber);
dispatcher.InjectEvent(myEvent); // puts this event into the event handling system
}
// cleanup
dispatcher.UnSubscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
}


%%%drop_event

MyEventHandler myEventHandler = new MyEventHandler();
HPS.EventDispatcher dispatcher = myCanvas.GetWindowKey().GetEventDispatcher();
dispatcher.Subscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());
// To activate the Drop() function, let's quickly load 100 Events into the the Event pipeline.
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
int randomNumber = rand.Next();
MyCustomEvent myEvent = new MyCustomEvent(HPS.Object.ClassID<MyCustomEvent>(), randomNumber);
dispatcher.InjectEvent(myEvent); // puts this event into the event handling system
}
// cleanup
dispatcher.UnSubscribe(myEventHandler, HPS.Object.ClassID<MyCustomEvent>());


%%%merging_events_example

class MyCustomEvent : HPS.Event
{
private int myRandomNumber; // this member is just for demonstration purposes
public MyCustomEvent() : base()
{
}
public MyCustomEvent(IntPtr type) : base(type)
{
}
public MyCustomEvent(IntPtr type, int randomNumber) : base(type)
{
myRandomNumber = randomNumber;
}
public override Event Clone()
{
MyCustomEvent new_event = new MyCustomEvent(GetChannel(), myRandomNumber);
return new_event;
}
public override bool Drop(Event in_that_event)
{
bool drop_status = false;
// add logic here to determine if event can be dropped
// let's drop the Event if its randomNumber member is divisible by 3
if ((myRandomNumber % 3) == 0)
drop_status = true;
return drop_status;
}
public int getMyRandomNumber()
{
return this.myRandomNumber;
}
};
public class MyEventHandler : HPS.EventHandler
{
~MyEventHandler() { Shutdown(); } // IMPORTANT
public override HandleResult Handle(HPS.Event in_event)
{
MyCustomEvent myEvent = (MyCustomEvent)in_event;
// ... do some logic
return HandleResult.Handled; // or return NotHandled, as the case may be
}
};


%%%handling_input

class MyEventHandler : HPS.EventHandler
{
public override HPS.EventHandler.HandleResult Handle(HPS.Event in_event)
{
HPS.MouseEvent mouseEvent = (HPS.MouseEvent)in_event;
HPS.WindowPoint location = mouseEvent.Location;
float x = location.x;
float y = location.y;
float z = location.z;
// ... do some logic
return HPS.EventHandler.HandleResult.Handled; // or return NotHandled, as the case may be
}
}


%%%subscribe

MyEventHandler myEventHandler = new MyEventHandler();
HPS.EventDispatcher dispatcher = myWindowKey.GetEventDispatcher();
dispatcher.Subscribe(myEventHandler, HPS.Object.ClassID<HPS.MouseEvent>());


%%%model_compare

subwindowKit.SetModelCompareMode(true, segment1, segment2);


%%%operator

class SphereOperator : Operator
{
private HPS.Canvas canvas;
private HPS.SegmentKey temporaryGeometry; /* segment used for drawing the sphere outline */
private HPS.Point centerPoint; /* the center of the sphere */
private HPS.LineKey radiusLine; /* a line going from the center of the sphere to its perimeter */
private HPS.CircleKey circle; /* a circle representing the outline of the sphere */
private HPS.MarkerKey centerMarker; /* marker placed on the center of the sphere*/
private bool operatorStarted;
public SphereOperator(Canvas c)
{
canvas = c;
}
/* The OnViewAttached function is executed when the CreateSphere operator is attached to the View
* It is responsible for setting up the temporary segment used for drawing the sphere outline */
public override void OnViewAttached(HPS.View in_attached_view)
{
operatorStarted = false;
HPS.Model model = canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel();
if (model.Type() == HPS.Type.None)
{
model = HPS.Factory.CreateModel();
canvas.GetAttachedLayout().GetAttachedView().AttachModel(model);
}
temporaryGeometry = model.GetSegmentKey().Subsegment();
temporaryGeometry.GetVisibilityControl().
SetLines(true).SetMarkers(true).SetFaces(false).SetEdges(true);
temporaryGeometry.GetMaterialMappingControl().
SetLineColor(new HPS.RGBAColor(0, 0, 1, 1)).
SetMarkerColor(new HPS.RGBAColor(1, 0, 0, 1));
temporaryGeometry.GetMarkerAttributeControl()
.SetSymbol("plus").SetSize(0.3f);
temporaryGeometry.GetCameraControl()
.SetProjection(HPS.Camera.Projection.Stretched)
.SetPosition(new HPS.Point(0, 0, -1)).SetTarget(new HPS.Point(0, 0, 0))
.SetUpVector(new HPS.Vector(0, 1, 0)).SetField(2, 2);
temporaryGeometry.GetDrawingAttributeControl()
.SetOverlay(HPS.Drawing.Overlay.Default);
return;
}
/* The OnMouseDown function is executed when any mouse buttons are pressed
* If the button pressed is the LEFT button, the center of the sphere is saved */
public override bool OnMouseDown(HPS.MouseState in_state)
{
if (in_state.GetActiveEvent().CurrentButton.Left())
{
operatorStarted = true;
centerPoint = in_state.GetLocation();
}
return true;
}
/* The OnMouseMove function is executed when the mouse is moved
* If the button LEFT button is pressed while the mouse is being moved, the sphere outline
* is constructed */
public override bool OnMouseMove(HPS.MouseState in_state)
{
if (IsMouseTriggered(in_state) && operatorStarted)
return ConstructSphereOutline(in_state.GetLocation());
return false;
}
/* The OnMouseUp function is executed when any mouse button goes up
* If the button that went up was the LEFT button, the temporary geometry is deleted
* and a sphere is inserted under the model, in its own segment */
public override bool OnMouseUp(MouseState in_state)
{
if (in_state.GetActiveEvent().CurrentButton.Left() && operatorStarted)
{
operatorStarted = false;
if (radiusLine != null)
radiusLine.Delete();
if (centerMarker != null)
centerMarker.Delete();
if (circle != null)
circle.Delete();
temporaryGeometry.Flush(HPS.Search.Type.Geometry, HPS.Search.Space.Subsegments);
HPS.SegmentKey sphere = GetAttachedView().GetAttachedModel().GetSegmentKey().Subsegment();
sphere.GetMaterialMappingControl().SetFaceColor(new RGBAColor(0, 1, 0, 1));
HPS.SprocketPath sprkPath = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(),
canvas.GetAttachedLayout().GetAttachedView(),
canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel());
HPS.KeyPath tpath = sprkPath.GetKeyPath();
HPS.KeyPath path = new HPS.KeyPath();
path.Append(sphere).Append(tpath);
HPS.Point drawPosition0, drawPosition1;
path.ConvertCoordinate(HPS.Coordinate.Space.Window, centerPoint, HPS.Coordinate.Space.World, out drawPosition0);
path.ConvertCoordinate(HPS.Coordinate.Space.Window, in_state.GetLocation(), HPS.Coordinate.Space.World, out drawPosition1);
sphere.InsertSphere(drawPosition0, ComputeDistance(drawPosition0, drawPosition1));
GetAttachedView().Update();
}
return true;
}
/* The ConstructSphereOutline function draws the outline of the sphere, which consists in a marker
* positioned on the center, the sphere radius, and a circle
* This geometry is drawn under the View, in Overlay */
private bool ConstructSphereOutline(Point currentPosition)
{
if (radiusLine != null)
radiusLine.Delete();
if (centerMarker != null)
centerMarker.Delete();
if (circle != null)
circle.Delete();
HPS.SprocketPath sprkPath = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(),
canvas.GetAttachedLayout().GetAttachedView(),
canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel());
HPS.KeyPath tpath = sprkPath.GetKeyPath();
HPS.KeyPath path = new HPS.KeyPath();
path.Append(temporaryGeometry).Append(tpath);
HPS.Point drawPosition0, drawPosition1;
path.ConvertCoordinate(HPS.Coordinate.Space.Window, centerPoint, HPS.Coordinate.Space.World, out drawPosition0);
path.ConvertCoordinate(HPS.Coordinate.Space.Window, currentPosition, HPS.Coordinate.Space.World, out drawPosition1);
centerMarker = temporaryGeometry.InsertMarker(new Point(drawPosition0));
radiusLine = temporaryGeometry.InsertLine(drawPosition0, drawPosition1);
circle = temporaryGeometry.InsertCircle(drawPosition0, ComputeDistance(drawPosition0, drawPosition1), new HPS.Vector(0, 0, 1));
GetAttachedView().Update();
return true;
}
/* The ComputeDistance function returns the distance between two points */
private float ComputeDistance(Point p0, Point p1)
{
return (float) Math.Sqrt((p1.x - p0.x) * (p1.x - p0.x) +
(p1.y - p0.y) * (p1.y - p0.y) +
(p1.z - p0.z) * (p1.z - p0.z));
}
}


%%%touch_operator_ex

class SphereOperator : Operator
{
private HPS.Canvas canvas;
private HPS.SegmentKey temporaryGeometry; /* segment used for drawing the sphere outline */
private HPS.Point centerPoint; /* the center of the sphere */
private HPS.LineKey radiusLine; /* a line going from the center of the sphere to its perimeter */
private HPS.CircleKey circle; /* a circle representing the outline of the sphere */
private HPS.MarkerKey centerMarker; /* marker placed on the center of the sphere*/
private bool operatorStarted;
public SphereOperator(Canvas c)
{
canvas = c;
}
/* The OnViewAttached function is executed when the CreateSphere operator is attached to the View
* It is responsible for setting up the temporary segment used for drawing the sphere outline */
public override void OnViewAttached(HPS.View in_attached_view)
{
operatorStarted = false;
HPS.Model model = canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel();
if (model.Type() == HPS.Type.None)
{
model = HPS.Factory.CreateModel();
canvas.GetAttachedLayout().GetAttachedView().AttachModel(model);
}
temporaryGeometry = model.GetSegmentKey().Subsegment();
temporaryGeometry.GetVisibilityControl().
SetLines(true).SetMarkers(true).SetFaces(false).SetEdges(true);
temporaryGeometry.GetMaterialMappingControl().
SetLineColor(new HPS.RGBAColor(0, 0, 1, 1)).
SetMarkerColor(new HPS.RGBAColor(1, 0, 0, 1));
temporaryGeometry.GetMarkerAttributeControl()
.SetSymbol("plus").SetSize(0.3f);
temporaryGeometry.GetCameraControl()
.SetProjection(HPS.Camera.Projection.Stretched)
.SetPosition(new HPS.Point(0, 0, -1))
.SetTarget(new HPS.Point(0, 0, 0))
.SetUpVector(new HPS.Vector(0, 1, 0))
.SetField(2, 2);
temporaryGeometry.GetDrawingAttributeControl()
.SetOverlay(HPS.Drawing.Overlay.Default);
return;
}
/* The OnTouchDown function is executed when any touches occur
* If we receive a one-finger touch, the center of the sphere is saved */
public override bool OnTouchDown(HPS.TouchState in_state)
{
Touch[] touches = in_state.GetActiveEvent().Touches;
if (touches.size() == 1)
{
centerPoint = touches[0].Location;
operatorStarted = true;
}
return true;
}
/* The OnTouchMove function is executed when the touch is moved
* If one finger is being used, the sphere outline is constructed */
public override bool OnTouchMove(TouchState in_state)
{
Touch[] touches = in_state.GetActiveEvent().Touches;
if (touches.size() == 1 && operatorStarted)
return ConstructSphereOutline(touches[0].Location);
return false;
}
/* The OnTouchUp function is executed when any touches go up
* If one touch goes up, the temporary geometry is deleted
* and a sphere is inserted under the model, in its own segment */
public override bool OnTouchUp(TouchState in_state)
{
Touch[] upTouches = in_state.GetActiveEvent().Touches;
if(upTouches.Length == 1 && operatorStarted)
{
operatorStarted = false;
radiusLine.Delete();
centerMarker.Delete();
circle.Delete();
temporaryGeometry.Flush(HPS.Search.Type.Geometry, HPS.Search.Space.Subsegments);
SegmentKey sphere = GetAttachedView().GetAttachedModel().GetSegmentKey().Subsegment();
sphere.GetMaterialMappingControl().SetFaceColor(new RGBAColor(0, 1, 0, 1));
SprocketPath sprkPath = new SprocketPath(canvas, canvas.GetAttachedLayout(), canvas.GetAttachedLayout().GetAttachedView(),
canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel());
KeyPath path = sprkPath.GetKeyPath();
path.Append(sphere);
Point drawPosition0, drawPosition1;
path.ConvertCoordinate(HPS.Coordinate.Space.Window, centerPoint, HPS.Coordinate.Space.World, out drawPosition0);
path.ConvertCoordinate(HPS.Coordinate.Space.Window, upTouches[0].Location, HPS.Coordinate.Space.World, out drawPosition1);
sphere.InsertSphere(drawPosition0, ComputeDistance(drawPosition0, drawPosition1));
GetAttachedView().Update();
}
return true;
}
/* The ConstructSphereOutline function draws the outline of the sphere, which consists in a marker
* positioned on the center, the sphere radius, and a circle
* This geometry is drawn under the View, in Overlay */
private bool ConstructSphereOutline(Point currentPosition)
{
if (radiusLine != null)
radiusLine.Delete();
if (centerMarker != null)
centerMarker.Delete();
if (circle != null)
circle.Delete();
HPS.SprocketPath sprkPath = new HPS.SprocketPath(canvas, canvas.GetAttachedLayout(),
canvas.GetAttachedLayout().GetAttachedView(),
canvas.GetAttachedLayout().GetAttachedView().GetAttachedModel());
HPS.KeyPath tpath = sprkPath.GetKeyPath();
HPS.KeyPath path = new HPS.KeyPath();
path.Append(temporaryGeometry).Append(tpath);
HPS.Point drawPosition0, drawPosition1;
path.ConvertCoordinate(HPS.Coordinate.Space.Window, centerPoint, HPS.Coordinate.Space.World, out drawPosition0);
path.ConvertCoordinate(HPS.Coordinate.Space.Window, currentPosition, HPS.Coordinate.Space.World, out drawPosition1);
centerMarker = temporaryGeometry.InsertMarker(new Point(drawPosition0));
radiusLine = temporaryGeometry.InsertLine(drawPosition0, drawPosition1);
circle = temporaryGeometry.InsertCircle(drawPosition0, ComputeDistance(drawPosition0, drawPosition1), new HPS.Vector(0, 0, 1));
GetAttachedView().Update();
return true;
}
/* The ComputeDistance function returns the distance between two points */
private float ComputeDistance(Point p0, Point p1)
{
return (float)Math.Sqrt((p1.x - p0.x) * (p1.x - p0.x) +
(p1.y - p0.y) * (p1.y - p0.y) +
(p1.z - p0.z) * (p1.z - p0.z));
}
}


%%%define_stream_import_handler

class NoBoldEvent : HPS.Stream.ImportEventHandler
{
public override bool Handle(HPS.Stream.ImportEvent e)
{
if (e.GetClassID() == HPS.Object.ClassID<HPS.Stream.TextImportEvent>())
{
text_event.text_kit.UnsetBold();
}
else if (e.GetClassID() == HPS.Object.ClassID<HPS.Stream.TextAttributeImportEvent>())
{
text_attribute_event.text_attribute_kit.UnsetBold();
}
return true;
}
};


%%%set_stream_import_handler

NoBoldEvent no_bold_event = new NoBoldEvent();
HPS.Stream.ImportOptionsKit import_options = new HPS.Stream.ImportOptionsKit();
import_options.SetEventHandler(no_bold_event, HPS.Object.ClassID<HPS.Stream.TextImportEvent>());
import_options.SetEventHandler(no_bold_event, HPS.Object.ClassID<HPS.Stream.TextAttributeImportEvent>());


%%%define_stream_export_handler

class SpecialExportEvent : HPS.Stream.ExportEventHandler
{
public override void Handle(HPS.Stream.ExportEvent e)
{
HPS.Stream.SegmentExportEvent seg_event = (HPS.Stream.SegmentExportEvent)e;
string name = seg_event.segment_key.Name();
if (name == "My_Special_Segment")
{
string str = "HOOPS Visualize!";
seg_event.non_db_user_data = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, seg_event.non_db_user_data, 0, seg_event.non_db_user_data.Length);
}
}
};


%%%set_stream_export_handler

SpecialExportEvent special_export_event = new SpecialExportEvent();
HPS.Stream.ExportOptionsKit export_options = new HPS.Stream.ExportOptionsKit();
export_options.SetEventHandler(special_export_event, HPS.Object.ClassID<HPS.Stream.SegmentExportEvent>());


%%%load_file_example

HPS.Stream.ImportOptionsKit importKit = new HPS.Stream.ImportOptionsKit();
importKit.SetSegment(importSeg);
HPS.Stream.ImportNotifier notif = HPS.Stream.File.Import(filename,importKit);
handler.SetNotifier(notif);
notif.Wait();
handler.SetNotifier(null); // set to null so that the handler does not try to use notif when it goes out of scope


%%%export1

HPS.Publish.File.ExportPDF(cadModel, filename, new HPS.Publish.ExportOptionsKit());


%%%export2

annotationKit.SetSource(cadModel, keyPathArray); // exporting everything


%%%export3

HPS.Exchange.File.ExportPRC(cadModel, filename, exportPRCOptionsKit);


%%%exchange_parasolid_import

HPS.Exchange.ImportOptionsKit iok = Exchange.ImportOptionsKit.GetDefault();
HPS.Exchange.TranslationOptionsKit.GetDefault(),
notifier.Wait(); // wait for this model to finish loading
// get the CAD model object
HPS.Exchange.CADModel cad_model = notifier.GetCADModel();
// get Exchange components
HPS.Component[] pmis = cad_model.GetAllSubcomponents(HPS.Component.ComponentType.ExchangePMIMask);
HPS.Exchange.Component pmi_component = new HPS.Exchange.Component(pmis[0]);
IntPtr exchange_pmi_entity = pmi_component.GetExchangeEntity();
// get Parasolid components
HPS.Component[] faces = cad_model.GetAllSubcomponents(HPS.Component.ComponentType.ParasolidTopoFace);
HPS.Parasolid.Component face_component = new HPS.Parasolid.Component(faces[0]);
int parasolid_face_entity = face_component.GetParasolidEntity();


%%%text_background

HPS.TextKit textKit = new TextKit();
textKit.SetPosition(new Point(0, 0.25f, 0));
textKit.SetText("TECH SOFT 3D");
textKit.SetSize(30, HPS.Text.SizeUnits.Pixels);
textKit.SetAlignment(HPS.Text.Alignment.Center); // relative to insertion point
textKit.SetBackground(true, "oval"); // also valid are "ellipse", "box", and "rounded box"
mySegmentKey.GetMaterialMappingControl().SetFaceColor(new RGBAColor(0.5f, 0, 0.5f));
mySegmentKey.InsertText(textKit);


%%%text_background_named_style

// first, define the style
SegmentKey styleSegment = Database.CreateRootSegment();
styleSegment.GetMaterialMappingControl().SetFaceColor(new RGBAColor(1, 1, 0)).SetEdgeColor(new RGBAColor(0, 0, 1));
styleSegment.GetEdgeAttributeControl().SetWeight(5).SetPattern("dashed_pattern");
myPortfolio.DefineNamedStyle("myShapeStyle", styleSegment);
// apply the defined style to the text segment
SegmentKey containingSegment = mySegmentKey.Subsegment();
containingSegment.GetTextAttributeControl().SetBackgroundStyle("myShapeStyle");


%%%custom_text_background

// first, build the shape points
ShapeCoordinate x = new ShapeCoordinate(1, 0);
ShapeCoordinate y = new ShapeCoordinate(0, 1);
ShapeCoordinate neg_x = new ShapeCoordinate(-1, 0);
ShapeCoordinate neg_y = new ShapeCoordinate(0, -1);
ShapeKit clippedShapeKit = new ShapeKit();
ShapePoint [] clipped_points = new ShapePoint[]
{
new ShapePoint(x.SetMargins(1), y),
new ShapePoint(x.SetMargins(0), y.SetMargins(1)),
new ShapePoint(neg_x, y),
new ShapePoint(neg_x.SetMargins(-1), y.SetMargins(0)),
new ShapePoint(neg_x, neg_y),
new ShapePoint(neg_x.SetMargins(0), neg_y.SetMargins(-1)),
new ShapePoint(x, neg_y),
new ShapePoint(x.SetMargins(1), neg_y.SetMargins(0))
};
// use the points to create a shape element
PolygonShapeElement clipped_element = new PolygonShapeElement(clipped_points);
clippedShapeKit.SetElement(clipped_element);
// define the shape in a portfolio accessible to the segment
myPortfolio.DefineShape("clipped background shape", clippedShapeKit);
// now, set the background shape on the text
TextKit textKit = new TextKit();
textKit.SetPosition(new Point(0, 0.25f, 0));
textKit.SetText("TECH SOFT 3D");
textKit.SetSize(30, HPS.Text.SizeUnits.Pixels);
textKit.SetAlignment(HPS.Text.Alignment.Center); // relative to insertion point
textKit.SetBackground(true, "clipped background shape");
mySegmentKey.InsertText(textKit);


%%%incremental1

HPS.Exchange.ImportOptionsKit importOptions = new HPS.Exchange.ImportOptionsKit();
importOptions.SetMode(HPS.Exchange.ImportMode.Incremental);
// perform an import with the incremental import mode
HPS.Exchange.ImportNotifier notifier = HPS.Exchange.File.Import(filename, importOptions);
notifier.Wait();


%%%incremental2

// get the CADModel that contains the structure of the file
HPS.Exchange.CADModel cadModel = notifier.GetCADModel();
// construct the appropriate path
HPS.Component rootProductOccurrence = cadModel.GetSubcomponents()[0];
HPS.Component componentToLoad = rootProductOccurrence.GetSubcomponents()[0];
HPS.Component [] pathComponents = { componentToLoad, rootProductOccurrence, cadModel };
HPS.ComponentPath pathToLoad = new ComponentPath(pathComponents);
// set this as the incremental component path to load
importOptions.SetIncrementalComponentPath(pathToLoad);
// set other import options as appropriate
// now options related to representation items, like Solids or Surfaces, will be respected
// perform an import with this component path - only the specified component path will be imported
notifier = HPS.Exchange.File.Import(filename, importOptions);
notifier.Wait();


%%%incremental3

// the product occurrence can only be constructed from a Component whose component type is Component.ComponentType.ExchangeProductOccurrence
HPS.Exchange.ProductOccurrence productOccurrence = new HPS.Exchange.ProductOccurrence(someComponent);
// unload data from Exchange and remove corresponding Component objects
productOccurrence.Unload(HPS.Exchange.UnloadMode.ExchangeAndVisualization);
// or, equivalently
productOccurrence.Unload();
// alternatively, to just unload Exchange data but leave components and visualization
productOccurrence.Unload(HPS.Exchange.UnloadMode.ExchangeOnly);


%%%camera_projection

mySegmentKey.GetCameraControl().SetProjection(HPS.Camera.Projection.Orthographic);


%%%shape_coordinate1

ShapeCoordinate sc1 = new ShapeCoordinate(1.15f, 0);
ShapeCoordinate sc2 = new ShapeCoordinate(0.85f, 1.5f);
ShapePoint sp = new ShapePoint(sc1, sc2);


%%%shape_coordinate2

ShapeCoordinate sc1 = new ShapeCoordinate(1, 0);
ShapeCoordinate sc2 = new ShapeCoordinate(0, 1);
ShapePoint sp = new ShapePoint(sc1, sc2);


%%%shape_coordinate3

ShapeCoordinate sc1 = new ShapeCoordinate(1, 0);
ShapeCoordinate sc2 = new ShapeCoordinate(0, 0);
ShapePoint sp = new ShapePoint(sc1, sc2);


%%%margins

// set margin size to 40% of character height
mySegmentKey.GetTextAttributeControl().SetBackgroundMargins(40);
sc1.SetMargins(1, 0, 0, 0); // 100% of margin size = 40% of char height
sc2.SetMargins(0, 3, 2, 0); // 300% of margin size + 200% of margin size * 40% = 200% of char height
sc3.SetMargins(0, 0, -1, 0); // -100% of margin size = -40% of char height
sc4.SetMargins(0, 0, 0, -2.5f); // -300% of margin size = -100% of char height


%%%non_latin_fonts

// Get the root segment
SegmentKey modelSegment = _canvas.GetFrontView().GetAttachedModel().GetSegmentKey();
// Set the visibility for text segment
modelSegment.GetVisibilityControl().SetText(true);
String font;
// Use "Microsoft YaHei" font in system font directory
modelSegment.GetTextAttributeControl().SetFont("Microsoft YaHei");
// Check whether we've set the font successfully (view result in Debugger).
modelSegment.GetTextAttributeControl().ShowFont(out font);
modelSegment.InsertText(new Point(0, 0, 0), (String)"Chinese Char 中国智造");


%%%publish_html_export_exchange

Exchange.ImportNotifier notifier;
Exchange.ImportOptionsKit importOptions = Exchange.ImportOptionsKit.GetDefault();
importOptions.SetBRepMode(Exchange.BRepMode.BRepAndTessellation);
notifier = Exchange.File.Import(myCADFilePath, importOptions);
notifier.Wait();
if (notifier.Status() != IOResult.Success)
{
// something went wrong with the file import
}
HPS.CADModel _cadModel = notifier.GetCADModel();
try
{
Publish.File.ExportHTML(_cadModel, exportedHTMLFilePath, htmlTemplateFilePath, true);
}
catch (IOException)
{
// something went wrong with the HTML export
}


%%%publish_html_export_sprocketkey

SprocketPath path = new SprocketPath(model, view, layout, canvas);
try
{
Publish.File.ExportHTML(path.GetKeyPath(), exportedHTMLFilePath, htmlTemplateFilePath);
}
catch (IOException)
{
// something went wrong with the HTML export
}


%%%sprocket_html_export

SprocketPath sPath = new SprocketPath(canvas, layout, view, model);
try
{
HTML.File.Export(sPath.GetKeyPath(), exportedHTMLFilePath, htmlTemplateFilePath);
}
catch (IOException)
{
// something went wrong with the HTML export
}


%%%ooc_import

HPS.OOC.ImportNotifier notifier;
HPS.IOResult status = HPS.IOResult.Failure;
string message;
try
{
HPS.OOC.ImportOptionsKit ioOpts = new HPS.OOC.ImportOptionsKit();
ioOpts.SetTarget(_model);
notifier = HPS.OOC.File.Import(myPointCloudFilePath, ioOpts);
notifier.Wait();
status = notifier.Status();
_view.FitWorld();
_canvas.UpdateWithNotifier(HPS.Window.UpdateType.Exhaustive).Wait();
}
catch (HPS.IOException ex)
{
status = ex.result;
message = ex.what();
}


%%%ooc_filter_class

public class CountAll : OOC.QueryFilter
{
public CountAll()
{
point_count = 0;
}
public CountAll(ulong in_point_count = 0)
{
point_count = in_point_count;
}
// determines whether or not points in memory are rejected by the filter
public override bool RejectPointsInMemory()
{
return false;
}
// determines whether or not points *not* in memory are rejected by the filter
public override bool RejectPointsOnDisk()
{
return false;
}
// determines whether or not a point cloud node is rejected by the filter
public override bool RejectNode(OOC.NodeHandle node_handle)
{
return false;
}
// determines whether or not a bounding box of points is rejected by the filter
public override bool RejectBounding(Point min_bound, Point max_bound)
{
return false;
}
// determines whether or not a single point is accepted by the filter
public override bool AcceptPoint(Point point, ulong point_index)
{
++point_count;
return true;
}
ulong point_count;
}

\htmlonly


%%%ooc_filter_half

public class AcceptHalf : OOC.QueryFilter {
public AcceptHalf()
{
point_count = 0;
}
public AcceptHalf(ulong in_point_count = 0)
{
point_count = in_point_count;
}
// determines whether or not a single point is accepted by the filter
public override bool AcceptPoint(Point point, ulong point_index)
{
if (point_index % 2 == 0)
{
++point_count;
return true;
}
else return false;
}
ulong point_count;
}

\htmlonly


%%%ooc_query_all

ulong num_points = 0;
OOC.PointCloud point_cloud = new OOC.PointCloud(_model);
if (point_cloud.Empty())
{
// the point cloud model is empty
}
CountAll filter = new CountAll();
OOC.QueryIterator it = point_cloud.QueryPoints(filter);
while (true)
{
HPS.OOC.QueryIterator.Status status = it.GetStatus();
if (status != HPS.OOC.QueryIterator.Status.Alive)
{
break; // No more points to iterate or there was a problem.
}
++num_points;
it.Next();
}


%%%ooc_query_half

ulong num_points_half = 0;
AcceptHalf filter_half = new AcceptHalf();
OOC.QueryIterator it_half = point_cloud.QueryPoints(filter_half);
while (true)
{
HPS.OOC.QueryIterator.Status status = it_half.GetStatus();
if (status != HPS.OOC.QueryIterator.Status.Alive)
{
break; // No more points to iterate or there was a problem.
}
++num_points_half;
it_half.Next();
}


%%%ooc_vertex_functions

SegmentKey mySegment = _canvas.GetFrontView().GetSegmentKey();
mySegment.GetDrawingAttributeControl().SetVertexDecimation(0.05f);
mySegment.GetDrawingAttributeControl().SetVertexRandomization(true);
_canvas.Update(HPS.Window.UpdateType.Refresh);


%%%find_highlights

//search for elements that use the Z-values overlay type
hsok.SetOverlay(Drawing.Overlay.WithZValues);
ulong numHighlights = myWindowKey.FindHighlights(hsok, out hsr);
HighlightSearchResultsIterator it = hsr.GetIterator();
while (it.IsValid())
{
string style_name = it.GetStyleName();
Drawing.Overlay overlay = it.GetOverlay();
it.Next();
}


%%%highlight_state

//optional: search for elements that use the "highlight_style" named style
hsok.SetStyleName("highlight_style");
HPS.HighlightControl myHighlightControl = new HPS.HighlightControl(myWindowKey);
HPS.HighlightState myHighlightState = new HPS.HighlightState();
myHighlightControl.ShowHighlightState(myKeyPath, hsok, out myHighlightState);
//does this segment inherit a highlight from a parent segment?
bool inheritsHighlight = myHighlightState.GetInheritsHighlight();
//does this segment contain a highlighted subentity (e.g., face or vertex)?
bool containsHighlightedSubentities = myHighlightState.GetSubentityHighlighted();
//are any of the keys on the given keypath directly highlighted?
bool isDirectlyHighlighted = myHighlightState.GetDirectlyHighlighted();
//is there a highlight in a child segment on this keypath?
bool isOnHighlightPath = myHighlightState.GetOnHighlightPath();


%%%obj_export

SprocketPath path = new SprocketPath(canvas, canvas.GetAttachedLayout(), view, model);
string output_file = my_export_directory + "/obj_export_1.obj";
OBJ.ExportNotifier export_notifier = OBJ.File.Export(output_file, path.GetKeyPath());


%%%create_views

// import the file including hidden objects and construction geometry
HPS.Exchange.ImportOptionsKit importOptions = HPS.Exchange.ImportOptionsKit.GetDefault();
importOptions.SetHiddenObjects(true);
importOptions.SetConstructionAndReferences(true);
HPS.Exchange.ImportNotifier notifier = HPS.Exchange.File.Import(filename, importOptions);
notifier.Wait();
// use the CADModel's default capture in four different views
HPS.Exchange.CADModel cadModel = notifier.GetCADModel();
View bottomLeft = cadModel.ActivateDefaultCapture();
layout.AttachViewFront(bottomLeft, new HPS.Rectangle(-1, 0, -1, 0));
View bottomRight = cadModel.ActivateDefaultCapture();
layout.AttachViewFront(bottomRight, new HPS.Rectangle(0, 1, -1, 0));
View topLeft = cadModel.ActivateDefaultCapture();
layout.AttachViewFront(topLeft, new HPS.Rectangle(-1, 0, 0, 1));
View topRight = cadModel.ActivateDefaultCapture();
layout.AttachViewFront(topRight, new HPS.Rectangle(0, 1, 0, 1));
canvas.AttachLayout(layout);


%%%change_visibility

// get the root product occurrence
HPS.Component rootPocc = cadModel.GetSubcomponents()[0];
HPS.Component firstChildPocc = rootPocc.GetSubcomponents()[0];
// in the bottom left view (layer 3) hide the first child of the root product occurrence
HPS.ComponentPath pathTofirstChildPocc = new ComponentPath();
pathTofirstChildPocc.Append(firstChildPocc);
pathTofirstChildPocc.Append(rootPocc);
pathTofirstChildPocc.Append(cadModel);
pathTofirstChildPocc.Hide(canvas, 3);
// in the bottom right view (layer 2) isolate the first child of the root product occurrence
pathTofirstChildPocc.Isolate(canvas, 2);
// in the top left view (layer 1) show some of the first child's hidden construction geometry in addition to isolating it
HPS.Component firstChildPart = firstChildPocc.GetSubcomponents()[0];
// this assumes the first 3 child components of the part contain construction geometry
HPS.Component [] partSubcomponents = firstChildPart.GetSubcomponents();
for (int i = 0; i < 3; ++i)
{
HPS.ComponentPath pathToHiddenConstruction = new HPS.ComponentPath();
pathToHiddenConstruction.Append(partSubcomponents[i]);
pathToHiddenConstruction.Append(firstChildPart);
pathToHiddenConstruction.Append(pathTofirstChildPocc);
pathToHiddenConstruction.Show(canvas, 1);
}
pathTofirstChildPocc.Isolate(canvas, 1);
// in the top right view (layer 0) isolate the first child and apply a highlight
pathTofirstChildPocc.Isolate(canvas, 0);
// this attempts to make a style with green faces and red lines
// however if the view doesn’t have lines, the lines color won’t apply
// or if the view doesn’t show faces, the face color won’t apply
SegmentKey highlightSource = topLeft.GetSegmentKey().Subsegment();
highlightSource.GetMaterialMappingControl().SetFaceColor(new HPS.RGBAColor(0, 1, 0)).SetLineColor(new HPS.RGBAColor(1, 0, 0));
canvas.GetPortfolioKey().DefineNamedStyle("my_style", highlightSource);
HighlightOptionsKit highlightOptions = new HighlightOptionsKit();
highlightOptions.SetStyleName("my_style").SetOverlay(Drawing.Overlay.InPlace);
pathTofirstChildPocc.Highlight(canvas, 0, highlightOptions);