This module makes all Onshape Standard Library features and functions available.
New Feature Studios begin with an import of this module,
import(path : "onshape/std/geometry.fs", version : "");
with current version inserted (e.g. 300.0
). This gives that Feature Studio access to all functions, types, enums, and constants defined in the Onshape Standard Library.
This module makes most common Onshape Standard Library functions available. It can be imported in place of geometry.fs
,
import(path : "onshape/std/common.fs", version : "");
into Feature Studios that do not require the full set of Onshape Standard Library features.
Context type
A Context
is a builtin
that stores modeling data, including bodies (solids, sheets, wires, and points), their constituent topological entities (faces, edges, and vertices), variables, feature error states, etc.
Every Onshape Part Studio uses a single Context
. All features, operations, and evaluation functions require a context to operate on. Different contexts do not interact, but data may be transferred from one to another using opMergeContexts
.
Each context keeps track of the version of the Onshape Standard Library at which it was created. While regenerating a feature that has been "held back" to an older version, the version reported by the context will be the older version, causing subfeatures and operations to emulate old behavior.
canBeContext (value) predicate
Typecheck for Context
isAtVersionOrLater (versionToCheck is FeatureScriptVersionNumber, versionToCompareAgainst is FeatureScriptVersionNumber) returns boolean
isAtInitialMixedModelingReleaseVersionOrLater (context is Context) returns boolean
Returns true if at or after mixed modeling release version.
Id type
An Id identifies a feature or operation in a context. Each feature, subfeature, and operation must have a unique id. Ids are used in queries, error reporting, and accessing data associated with features.
Ids are hierarchical. That is, each operation's id must have a parent id. The root id is constructed with newId()
and subIds are added with the overloaded +
operator.
EXAMPLE
id + "foo"
represents an id named"foo"
whose parent isid
EXAMPLE
id + "foo" + "bar"
represents an id named"bar"
whose parent equalsid + "foo"
Internally, an Id
is just an array whose elements are strings, representing the full path of the Id
.
EXAMPLE
newId() + "foo" + "bar"
is equivalent to["foo", "bar"] as Id
, though the expressions like the latter are not recommended in practice.
Within a feature, all operations' ids should be children of the feature's Id
(which is always passed into the feature function as the variable id
).
Subfeatures should use a similar pattern. For instance, in the snippet below, mySubfeature
is a minimal example following good practices for breaking out a set of operations into a subroutine.
annotation { "Feature Type Name" : "My Feature" } export const myFeature = defineFeature(function(context is Context, id is Id, definition is map) precondition {} { fCuboid(context, id + "startingCube", { "corner1" : vector(0, 0, 0) * inch, "corner2" : vector(1, 1, 1) * inch }); mySubfeature(context, id + "subFeature", qCreatedBy(id + "startingCube", EntityType.EDGE)); fCuboid(context, id + "endingCube", { "corner1" : vector(0, 0, 0) * inch, "corner2" : vector(-1, -1, -1) * inch }); }, {}); function mySubfeature(context is Context, id is Id, entities is Query) { opChamfer(context, id + "chamfer", { "entities" : entities, "chamferType" : ChamferType.EQUAL_OFFSETS, "width" : 0.1 * inch }); opFillet(context, id + "fillet1", { "entities" : qCreatedBy(id + "chamfer", EntityType.EDGE), "radius" : 0.05 * inch }); }
The full id hierarchy must reflect creation history. That is, each Id
(including parents) must refer to a contiguous region of operations on the context.
Thus, the following code will fail because id + "extrude"
alone refers to two non-contiguous regions of history:
for (var i in [1, 2]) { opExtrude(context, id + "extrude" + i, {...}); // Fails on second iteration. opChamfer(context, id + "chamfer" + i, {...}); }
For the above code, a pattern like id + i + "extrude"
or id + ("loop" ~ i) + "extrude"
would work as expected, as would the unnested id + ("extrude" ~ i)
.
Only the following characters are allowed in a string that makes up an Id
: a-z
, A-Z
, 0-9
, _
, +
, -
, /
. An asterisk *
is allowed at the beginning of the string to mark it an "unstable" component (see below).
canBeId (value) predicate
Typecheck for Id
Returns an empty id.
makeId (idComp is string) returns Id
Returns an id specified by the given string.
isTopLevelId (id is Id) predicate
True if the Id
represents a top-level feature or default geometry (i.e. if the Id
has length 1
)
ANY_ID const
The string literal "*"
, which matches any id inside certain queries.
EXAMPLE
qCreatedBy(id + ANY_ID + "fillet")
unstableIdComponent (addend) returns string
Marks a given id component as "unstable" causing queries to treat it as a wildcard. This is useful for when the id component is not expected to be robust, such as an index into the results of an evaluated query.
setVariable (context is Context, name is string, value)
Attach a variable to the context, which can be retrieved by another feature defined later. If a variable of the same name already exists, this function will overwrite it.
EXAMPLE
setVariable(context, "foo", 1)
attaches a variable named"foo"
, with value set to1
, on the context.
Parameter | Type | Additional Info |
---|---|---|
value |
Can be any value, including an array or map with many elements. |
setVariable (context is Context, name is string, value, description is string)
Attach a variable with a description to the context, which can be retrieved by another feature defined later. If a variable of the same name already exists, this function will overwrite it.
EXAMPLE
setVariable(context, "foo", 1, "the foo")
attaches a variable named"foo"
, with value set to1
and the description set to "the foo", on the context.
Parameter | Type | Additional Info |
---|---|---|
value |
Can be any value, including an array or map with many elements. |
|
description |
string | A string describing the use or purpose of the variable. |
getVariable (context is Context, name is string)
Retrieve a variable attached to the context by name. Throws an exception if variable by the given name is not found.
EXAMPLE
getVariable(context, "foo")
returns the value assigned to a previously-set variable named"foo"
.
Variables on a context can also be accessed within a Part Studio using #
syntax (e.g. #foo
) inside any parameter which allows an expression.
getVariable (context is Context, name is string, defaultValue)
Retrieve a variable attached to the context by name. If variable by the given name is not found, returns defaultValue
EXAMPLE
getVariable(context, "foo", {})
returns the value assigned to a previously-set variable named"foo"
. If not found returns empty map.
Returns the language version of the library. Note: this function calls @getLanguageVersion
internally, but if you call @getLanguageVersion
directly, you may get a different result. That is because @getLanguageVersion
returns the language version of the module making the call (which, for a module in std will coincide with the version of std.)
Operations are the basic modeling primitives of FeatureScript. Operations can do extrusion, filleting, transforms, etc. An operation takes a context, an id, and a definition and modifies the context in accordance with the definition. The modifications can be referenced by the passed-in id. Operations return undefined
but can fail by throwing an error or they can report warnings or infos. The status can be read with the getFeature... functions in error.fs.
When an operation parameter that requires one entity receives a query that resolves to multiple entities, it takes the first resolved entity.
The geomOperations.fs module contains wrappers around built-in Onshape operations and no actual logic.
opMoveCurveBoundary (context is Context, id is Id, definition is map)
Trims or extends a wire body to an entity or by a distance.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The wire bodies to modify. |
|
MoveCurveBoundaryType | Optional Whether to trim or extend. Default is |
|
Query | Required if Single entity to trim |
|
CurveExtensionEndCondition | Optional If |
|
ValueWithUnits | Required if Distance to extend |
|
Query | Required if Single entity to extend |
|
CurveExtensionShape | Optional Specifies how to transition into the curve extensions. Default is |
|
Query | Required if Specifies vertex used to choose a solution. If this is not provided, the closest vertex to the bounding entity will be used. |
|
boolean | Optional If |
opBodyDraft (context is Context, id is Id, definition is map)
Apply draft to a part by adding material. The material is added between reference edges and a parting object. These reference edges can be supplied directly, or they can be inferred from face or part queries.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
BodyDraftSelectionType | Optional Topology class for input. Default is |
|
Query | Required if Edges to draft above parting entity. |
|
Query | Required if Edges to draft with |
|
Query | Required if Faces to draft. This will split the face with isoclines those for the draft. Additionally, any existing edges bounding |
|
Query | Required if Parts to draft. This is equivalent to supplying all faces of the part in |
|
Query | Optional Faces of |
|
ValueWithUnits | The draft angle above the parting object. |
|
boolean | Optional If |
|
ValueWithUnits | The pull direction. |
|
boolean | Optional If true, then using the drafted part as the parting object. Default is |
|
Required if A surface from surfaceGeometry.fs or a query to a face or sheet body. |
|
|
boolean | Optional If true, then additional material will be added to make the top and bottom of the draft align. Default is |
|
BodyDraftMatchFaceType | Optional How to add material for |
|
BodyDraftCornerType | Optional The corner treatment to apply. Default is |
|
BodyDraftConcaveRepairType | Optional How to resolve intersecting draft faces. Default is |
|
ValueWithUnits | Required if The radius for intersection repair. |
|
boolean | Optional If true, an attempt will be made to keep the regions of the part protruding from the tapered faces. Default is false. |
|
boolean | Optional If true, then debug data will be generated to show the parting surface and draft edges. |
opBoolean (context is Context, id is Id, definition is map)
Performs a boolean operation on multiple solid and surface bodies.
See also
processNewBodyIfNeeded
for merging new solids.
joinSurfaceBodiesWithAutoMatching
for merging new surfaces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The tool bodies. |
|
Query | Required if The target bodies. |
|
BooleanOperationType | The boolean operation to perform. EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
|
|
boolean | Optional This option is for adjusting the behavior to be more suitable for doing the boolean as part of a body-creating feature (such as extrude). Default is |
|
boolean | Optional If true, the tools do not get consumed by the operation. Default is false. |
|
boolean | Optional In case of surface union try to join surfaces into a solid. Default is false. |
opBoundarySurface (context is Context, id is Id, definition is map)
Creates a boundary surface fitting two ordered sets of profiles.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | An ordered array of two or fewer queries for the profiles in the u direction. These can be edges or wire bodies. EXAMPLE
|
|
array | Optional An ordered array of two or fewer queries for the profiles in the v direction. These can be edges or wire bodies. EXAMPLE
|
|
array | Optional An array of maps that contain shape constraints at start and end profiles. Each map entry is required to have a profileIndex that refers to the affected profile. Optional fields include a vector to match surface tangent to, a magnitude, and booleans for matching tangents or curvature derived from faces adjacent to affected profile. EXAMPLE
|
|
array | Optional An array of maps analogous to uDerivativeInfo, but for v profiles. |
|
boolean | Optional Show graphical representation of a subset of isoparameteric curves on each face of the created boundary surface. Default |
|
number | Optional When |
opCreateBSplineCurve (context is Context, id is Id, definition is map)
Generates a wire body given a BSplineCurve
definition. The spline must have dimension of 3 and be G1-continuous.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
BSplineCurve | The definition of the spline. |
opCreateBSplineSurface (context is Context, id is Id, definition is map)
Generates a sheet body given a BSplineSurface
definition. The spline must have dimension of 3 and be G1-continuous.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
BSplineSurface | The definition of the spline surface. |
|
array | Optional An array of |
|
boolean | Optional When set to |
opCreateCompositePart (context is Context, id is Id, definition is map)
Create a composite part.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Bodies from which to create the composite part. . |
|
boolean | Optional A |
opModifyCompositePart (context is Context, id is Id, definition is map)
Modifies a composite part.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Existing composite part to modify. |
|
Query | Bodies to add to the composite part. |
|
Query | Bodies to remove from the composite part. |
opChamfer (context is Context, id is Id, definition is map)
Adds a chamfer to given edges and faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges and faces to chamfer. |
|
ChamferType | Determines where the new edges of the chamfer are positioned. EXAMPLE
EXAMPLE
EXAMPLE
|
|
ValueWithUnits | Required if EXAMPLE
|
|
ValueWithUnits | Required if |
|
ValueWithUnits | Required if |
|
ValueWithUnits | Required if |
|
boolean | Required if
|
|
boolean | Optional
|
Describes a set of isoparametric curves on a face.
Value | Type | Description |
---|---|---|
CurveOnFaceDefinition |
map | |
|
Query | Face the curves are meant to lie on. |
|
FaceCurveCreationType | Determines the type of curves. Currently supports isoparameter curves only in primary or secondary directions, either equally spaced or defined by a parameter array. |
|
array | An array of distinct non-empty strings to identify the curves created. |
|
number | Required if Number of curves. |
|
array | Required if Parameters to create curves at. |
canBeCurveOnFaceDefinition (value) predicate
Typecheck for CurveOnFaceDefinition
curveOnFaceDefinition (face is Query, creationType is FaceCurveCreationType, names is array, nCurves is number) returns CurveOnFaceDefinition
Returns a new CurveOnFaceDefinition
.
curveOnFaceDefinition (face is Query, creationType is FaceCurveCreationType, names is array, parameters is array) returns CurveOnFaceDefinition
opCreateCurvesOnFace (context is Context, id is Id, definition is map)
Generates isoparametric curves of faces. That is, for each specified surface parameter value, creates a new wire body following the curve which keeps the surface parameter at that constant value.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | An array of |
|
boolean | Optional Whether to display isoparameteric curves in color in the preview. |
|
boolean | Optional For Onshape internal use. |
opDeleteBodies (context is Context, id is Id, definition is map)
Deletes bodies from the context.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Entities to delete. Passing in entities other than bodies deletes their owning bodies. |
opDeleteFace (context is Context, id is Id, definition is map)
This is a direct editing operation that attempts to delete faces of a solid body and extend other faces to fill the hole.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Faces to delete. |
|
boolean |
|
|
boolean | If |
|
boolean | Optional If |
opDraft (context is Context, id is Id, definition is map)
Applies a given draft angle to faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
DraftType | Specifies a reference surface (e.g. a neutral plane) or reference entity draft. EXAMPLE
|
|
Query | Required if The faces to draft for a |
|
Required if A face or plane that defines the neutral surface for a |
|
|
array | Required if An array of maps of the form ("face", "references", "angle"). "face" should be a |
|
Vector | The 3d direction relative to which the draft is applied. EXAMPLE
|
|
ValueWithUnits | The draft angle, must be between 0 and 89.9 degrees. EXAMPLE
|
|
boolean | Optional For a |
|
boolean | Optional For a |
|
boolean | Optional
|
opExtractWires (context is Context, id is Id, definition is map)
Generates wire bodies from the supplied edges. If the edges are disjoint multiple wires will be returned. If the edges overlap or cross, or more than two meet at a point, the function will fail.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The edges to be extracted. |
opExtrude (context is Context, id is Id, definition is map)
Extrudes one or more edges or faces in a given direction with one or two end conditions. Faces get extruded into solid bodies and edges get extruded into sheet bodies.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges and faces to extrude. |
|
Vector | The 3d direction in which to extrude. EXAMPLE
EXAMPLE
|
|
BoundingType | The type of bound at the end of the extrusion. Cannot be EXAMPLE
|
|
ValueWithUnits | Required if How far from the EXAMPLE
|
|
Query | Required if The face or body that provides the bound. |
|
ValueWithUnits | Optional The translational offset between the extrude end cap and the end bound entity. The direction vector for this is the same as |
|
BoundingType | Optional The type of start bound. Default is for the extrude to start at |
|
Required if is Whether the |
|
|
ValueWithUnits | Required if How far from the |
|
Query | Required if The face or body that provides the bound. |
|
ValueWithUnits | Optional The translational offset between the extrude start cap and the start bound entity. The direction vector for this is the negative of |
opFaceBlend (context is Context, id is Id, definition is map)
Performs a face blend between two walls of faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | First set of faces, must belong to the same body. |
|
Query | Second set of faces, must belong to the same body. |
|
boolean | Wether to flip side 1's normal. |
|
boolean | Wether to flip side 2's normal. |
|
boolean | Optional Whether to propagate the blend. |
|
FaceBlendPropagation | Optional How to propagate the blend. FaceBlendPropagation.TANGENT will propagate over tangent faces. FaceBlendPropagation.ADJACENT will propagate over all adjacent faces. FaceBlendPropagation.CUSTOM allows specification of a maximum angle between faces for propagation. Defaults is FaceBlendPropagation.TANGENT. |
|
ValueWithUnits | Optional Maximum angle between faces for propagation. Used if propagationType is FaceBlendPropagation.CUSTOM. Default is 0 * radian. |
|
FaceBlendCrossSection | The cross section type of the blend. |
|
Query | Required if The spine of the blend. The blend's cross section will be orthogonal to the spine. |
|
BlendControlType | Whether the blend is controled by a constant radius or a constant width. |
|
FaceBlendCrossSectionShape | What shape the cross section of the blend will be. |
|
ValueWithUnits | Required if The radius of the cross section. |
|
ValueWithUnits | Required if The width of the blend. |
|
boolean | Optional Wether the radius or width is the same on each wall. |
|
ValueWithUnits | Required if The radius of the cross section from side 2. |
|
number | Required if How the blend will be divided between the walls. If widthRatio < 1, it will be wider towards side 1. If widthRatio > 1, it will be wider towards side 2. |
|
number | Required if Parameter of the conic cross section shape. |
|
number | Required if Parameter of the curvature cross section shape. |
|
boolean | Optional Whether to use the content of |
|
Query | Optional Edges to use as tangent hold lines. |
|
Query | Optional Edges to use as inverse tangent hold lines. |
|
boolean | Optional Whether to use the content of |
|
Query | Optional Edges to use as conic hold lines. |
|
Query | Optional Edges to use as inverse conic hold lines. |
|
boolean | Optional Whether to use the content of |
|
Query | Optional Edges to use as cliff edges. |
|
boolean | Optional Whether to use the content of |
|
array | Optional Entities and flip flags to use as caps. Each map should contain an |
|
boolean | Optional Whether to use the content of |
|
Query | Optional First plane to limit the blend. |
|
boolean | Whether to flip the first plane normal. Defines which side of the plane the blend will be. |
|
Query | Optional Second plane to limit the blend. |
|
boolean | Whether to flip the first plane normal. Defines which side of the plane the blend will be. |
|
Query | Optional Faces to use as limits to the blend. |
|
array | Optional Edges and adjacent faces to use as limits. Each map should contain an |
|
boolean | Optional Whether to use the content of |
|
Query | Optional Vertex or mate connector to use as help point. In case the blend parameters create several blends, only the blend closest to the help point will be kept. |
|
FaceBlendTrimType | Optional How to trim the blend. |
|
boolean | Optional Whether not to attach the blend(s) to the sides, creating new sheet bodies. |
|
boolean | Optional Show graphical representation of a subset of isoparameteric curves of the created surface. Default |
|
number | Optional When |
opFillet (context is Context, id is Id, definition is map)
For edges, performs a fillet on the edge. For faces, performs a fillet on all edges adjacent to the face.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges and faces to fillet. |
|
ValueWithUnits | The fillet radius. EXAMPLE
|
|
boolean | Optional
|
|
FilletCrossSection | Optional Fillet cross section. One of |
|
number | Required if A number between 0 and 1, specifying the Rho value of a conic fillet EXAMPLE
EXAMPLE
|
|
number | Required if A number between 0 and 1, specifying the magnitude of curvature match. |
|
array | Optional An array of maps representing the boundaries of a partial fillet. Each map should contain a EXAMPLE
|
|
boolean | Optional Fillet controls can be varied at vertices via |
|
array | Optional An array of maps representing fillet settings at specified vertices. Each map should contain a EXAMPLE
|
|
array | Optional An array of maps representing fillet settings at specified points on edges. Each map should contain an EXAMPLE
|
|
boolean | Required if Whether to create a smoother transition between each vertex. |
|
boolean | Optional Allow |
|
Query | Optional Edges you do not want |
|
boolean | Optional Allow |
|
Query | Optional Vertices you do not want |
|
boolean | Optional Operation does not modify the body of the selected edges, but results in surface geometry of fillet. Default is |
opFillSurface (context is Context, id is Id, definition is map)
Generates a surface body from supplied boundary and internal constraints. The boundaries are defined as edge queries for each continuity constraint. The internal constraints may be defined as a set of support vertices.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The edges with position constraints. |
|
Query | The edges with tangency constraints. |
|
Query | The edges with curvature constraints. |
|
Query | The vertices the resulting surface is expected to interpolate. |
|
boolean | Optional Show graphical representation of a subset of isoparameteric curves of the created surface. Default |
|
number | Optional When |
opFitSpline (context is Context, id is Id, definition is map)
Creates a 3D cubic spline curve through an array of 3D points.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | An array of EXAMPLE [ vector( 1, 1, 1) * inch, vector(-1, 1, -1) * inch, vector( 1, -1, -1) * inch, vector(-1, -1, 1) * inch, vector( 1, 1, 1) * inch ] |
|
array | Optional An array of doubles, parameters corresponding to the points. |
|
Vector | Optional A |
|
Vector | Optional A |
|
Vector | Optional A |
|
Vector | Optional A |
|
map | Optional A map of derivatives at non-end points. Entries should be |
opFlipOrientation (context is Context, id is Id, definition is map)
Reverses the orientation of sheet bodies.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Sheet bodies whose orientation should be flipped. |
opFullRoundFillet (context is Context, id is Id, definition is map)
Creates a full round fillet, replacing the center face(s) with circular profile face(s) of varying radius, joining the selected side faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | A face on one side of the blend. |
|
Query | A face on another side of the blend. |
|
Query | The face(s) to be replaced. |
|
boolean | Optional
|
opHelix (context is Context, id is Id, definition is map)
Creates a helical and possibly spiral curve.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | The direction of the helix axis. EXAMPLE
|
|
Vector | A point on the helix axis. EXAMPLE
|
|
Vector | The start point of the infinite helix. Must be off the axis. This is the point at which the created curve would actually start if the first number of EXAMPLE
|
|
Vector | An array of two numbers denoting the interval of the helix in terms of revolution counts. EXAMPLE
|
|
boolean | EXAMPLE
|
|
ValueWithUnits | Distance along the axis between successive revolutions. EXAMPLE
EXAMPLE
|
|
ValueWithUnits | Change in radius between successive revolutions. EXAMPLE
|
opHole (context is Context, id is Id, definition is map) returns array
Creates hole tools referencing a set of targets, optionally subtracting the tools from the targets. If some tools cannot be built, the operation will still succeed and indicate in its return value which holes failed to build. If no tools can be built, the operation will fail.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
HoleDefinition | The definition of the shape of the desired holes. EXAMPLE
|
|
array | An array of EXAMPLE
|
|
array | Optional An array of queries, one per axis in |
|
Query | Required if A set of bodies to target. The shape of the produced holes is dependent on the shape of these targets (as specified in the supplied |
|
boolean | Optional
|
|
Query | Optional If supplied and |
|
boolean | Optional If |
Return type | Description |
---|---|
array | An array representing target intersection information for each hole. The array is aligned with the The value of
The value of
EXAMPLE // For an opHole operation creating two holes, both going into two stacked // parts, the first of which being 1 inch thick with a slightly slanted top // and flat bottom and the second being 3 inches thick with a flat top and // bottom, and the holeDefinition referencing both TARGET_START and // LAST_TARGET_START the return value may look like: [ { // First hole (successful) "success" : true, "targetToDepthExtremes" : { (firstTargetQuery) : { "firstEntrance" : 0.1 * inch, "fullEntrance" : 0.3 * inch, "firstExit" : 1 * inch, "fullExit" : 1 * inch }, (secondTargetQuery) : { "firstEntrance" : 1 * inch, "fullEntrance" : 1 * inch, "firstExit" : 4 * inch, "fullExit" : 4 * inch } }, "positionReferenceInfo" : { HolePositionReference.TARGET_START : { "referenceRootStart" : 0.1 * inch, "referenceRootEnd" : 0.3 * inch, "target" : firstTargetQuery }, HolePositionReference.LAST_TARGET_START : { "referenceRootStart" : 1 * inch, "referenceRootEnd" : 1 * inch, "target" : secondTargetQuery }, } }, { // Second hole (successful) "success" : true, "targetToDepthExtremes" : { (firstTargetQuery) : { "firstEntrance" : 0.4 * inch, "fullEntrance" : 0.6 * inch, "firstExit" : 1 * inch, "fullExit" : 1 * inch }, (secondTargetQuery) : { "firstEntrance" : 1 * inch, "fullEntrance" : 1 * inch, "firstExit" : 4 * inch, "fullExit" : 4 * inch } }, "positionReferenceInfo" : { HolePositionReference.TARGET_START : { "referenceRootStart" : 0.4 * inch, "referenceRootEnd" : 0.6 * inch, "target" : firstTargetQuery }, HolePositionReference.LAST_TARGET_START : { "referenceRootStart" : 1 * inch, "referenceRootEnd" : 1 * inch, "target" : secondTargetQuery }, } }, { // Third hole (unsuccessful) "success" : false } ] |
opImportForeign (context is Context, id is Id, definition is map)
Brings foreign geometry into the context. This function is used for importing uploaded parts.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
CADImportData | Reference to a blob element hosting uploaded CAD data. |
|
boolean | Optional Whether to flatten assemblies; defaults to false. |
|
boolean | Optional If true, the y axis in the import maps to the z axis and z maps to -y. If false (default), the coordinates are unchanged. |
|
boolean | Optional Whether the imported data is modifiable (default) or not. |
opCreateIsocline (context is Context, id is Id, definition is map)
Creates wires corresponding to the given faces
's isocline edges. Each isocline follows a path along a face with a constant angle
in the (-90, 90) degree range (e.g., lines of latitude on a sphere). This angle
is the face tangent plane's angle with respect to the direction
with its sign determined by the dot product of direction
and the face normal, and is analogous to the angle used in draft analysis. Depending on the face geometry, there may be zero, one, or multiple isoclines on each face.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces on which to imprint isoclines. |
|
Vector | A reference direction. |
|
ValueWithUnits | The isocline angle with respect to the direction in the (-90, 90) degree range. |
opLoft (context is Context, id is Id, definition is map)
Creates a surface or solid loft fitting an ordered set of profiles, optionally constrained by guide curves.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | An ordered array of queries for the profiles. For a solid loft, these must be sheet bodies, faces, or vertices. For a surface loft, these could be wire bodies, sheet bodies, faces, edges, or vertices. EXAMPLE
|
|
array | Optional An array of queries for guide curves. Each guide curve should intersect each profile once. |
|
array | Optional An array of maps to define multiple profile alignments. Each connection map should contain: (1) connectionEntities query describing an array of vertices or edges (one per profile), (2) connectionEdges an array of individual queries for edges in connectionEntities. The order of individual edge queries should be synchronized with connectionEdgeParameters. (3) connectionEdgeParameters array - an ordered and synchronized array of parameters on edges in connectionEdgeQueries EXAMPLE
|
|
boolean | Optional Defaults to false for better performance. Controls interpretation of connectionEdgeParameters. If |
|
boolean | Optional Defaults to false. A closed guide creates a periodic loft regardless of this option. |
|
ToolBodyType | Optional Specifies a |
|
boolean | Optional If false (default) use full length of guides. If true restrict resulting surface by the first and last profile. Meaningful only for non-periodic surface loft. |
|
boolean | Optional If false (default) use full length of profiles. If true restrict resulting surface by the first and last guide or connection. Meaningful only for surface loft with open profiles. |
|
array | Optional An array of maps that contain shape constraints at start and end profiles. Each map entry is required to have a profileIndex that refers to the affected profile. Optional fields include a vector to match surface tangent to, a magnitude, and booleans for matching tangents or curvature derived from faces adjacent to affected profile. EXAMPLE
|
|
boolean | Optional Show graphical representation of a subset of isoparameteric curves on each face of the created loft. Default |
|
number | Optional When |
|
LoftTopology | Optional Specifies topology of lofted body. Default is |
opMateConnector (context is Context, id is Id, definition is map)
Creates a mate connector, which represents a coordinate system in the context. Currently it is a special type of point body.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
CoordSystem | The mate connector coordinate system. |
|
Query | The owner body of the mate connector: when the owner is brought into an assembly, owned mate connectors will be brought in and move rigidly with it. If the query resolves to multiple bodies, the first is taken as the owner. |
opMergeContexts (context is Context, id is Id, definition is map) returns array
Bring all of the information from contextFrom
into context
. This is used, for example, for the Derived feature.
Parameter | Type | Additional Info |
---|---|---|
context |
Context | The target context. |
definition |
map | |
|
Context | The source context. It is rendered unusable by this operation. EXAMPLE
|
|
array | Optional Array of queries to map evaluation result in contextFrom to context post-merge |
Return type | Description |
---|---|
array | Returns array of the same size as trackThroughMerge with evaluation results for each query(array of arrays of transient queries). |
opModifyFillet (context is Context, id is Id, definition is map)
This is a direct editing operation that modifies or deletes fillets.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The fillets to modify. |
|
ModifyFilletType | Whether to change the fillet radii or remove them altogether. |
|
ValueWithUnits | Required if The new radius. |
|
boolean | Required if
|
opMoveFace (context is Context, id is Id, definition is map)
This is a direct editing operation that applies a transform to one or more faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces to transform. |
|
Transform | The transform to apply to the face. EXAMPLE
|
|
boolean | Optional
|
|
boolean | Optional
|
opOffsetFace (context is Context, id is Id, definition is map)
This is a direct editing operation that offsets one or more faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces to offset. |
|
ValueWithUnits | The positive or negative distance by which to offset. EXAMPLE
|
|
boolean | Optional
|
|
boolean | Optional
|
opPattern (context is Context, id is Id, definition is map)
Patterns input faces and/or bodies by applying transforms to them. The original faces and bodies are preserved.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Bodies and faces to pattern. |
|
array | An array of |
|
array | An array of distinct non-empty strings the same size as |
|
boolean | Optional If true (default), copies properties and attributes to patterned entities. |
opPlane (context is Context, id is Id, definition is map)
Creates a construction plane.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Plane | The plane to create. EXAMPLE
|
|
ValueWithUnits | Optional The side length of the construction plane, as it is initially displayed. |
|
ValueWithUnits | Optional The side length of the construction plane, as it is initially displayed. |
|
DefaultPlaneType | Optional For Onshape internal use. |
opPolyline (context is Context, id is Id, definition is map)
Creates a polyline passing through an array of 3D points.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | An array of EXAMPLE [ vector( 1, 1, 1) * inch, vector(-1, 1, -1) * inch, vector( 1, -1, -1) * inch, vector(-1, -1, 1) * inch, vector( 1, 1, 1) * inch ] |
|
array | Optional An array of |
opDropCurve (context is Context, id is Id, definition is map)
Projects curves on a face.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The edges to project. |
|
Query | The faces/bodies the edges are to be projected onto. |
|
ProjectionType | Projection method. |
|
Vector | Optional The direction in which to project the curve. Required if projectionType is ProjectionType.DIRECTION. |
opIntersectFaces (context is Context, id is Id, definition is map)
Intersect two faces, creating curves appropriately.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | First array of faces to intersect. |
|
Query | Second array of faces to intersect. |
opSphere (context is Context, id is Id, definition is map)
Creates a sphere.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
ValueWithUnits | The radius of the sphere. EXAMPLE
|
|
Vector | The location of the center of the sphere. EXAMPLE
|
opSplineThroughEdges (context is Context, id is Id, definition is map)
Creates a 3D spline curve representing a sequence of edges. The edges must form a tangent-continuous chain.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges to approximate. |
opSplitEdges (context is Context, id is Id, definition is map)
Splits an array of edges with an entity or at specified parameters.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges to split. |
|
array | An array of array of parameters. Each edge gets split at the parameter values at the matching index in this array. |
|
Query | A sheet body, a construction plane or a face to cut with. Can be either a |
|
boolean | Optional If true (default), the parameter returned for edges measures distance along the edge, so |
opPoint (context is Context, id is Id, definition is map)
Creates a construction point (a BodyType.POINT
with one vertex).
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | The location of the point. EXAMPLE
|
|
boolean | Optional For Onshape internal use. |
opReplaceFace (context is Context, id is Id, definition is map)
This is a direct editing operation that replaces the geometry one or more faces with that of another face, possibly with an offset.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces whose geometry to replace. |
|
Query | The face whose geometry to use as the replacement. |
|
ValueWithUnits | Optional The positive or negative distance by which to offset the resulting face. |
|
boolean | Optional If true, flip the surface normal of the resulting face, which may be necessary to match the surface normals of surrounding faces. Default is |
opRevolve (context is Context, id is Id, definition is map)
Revolves edges and faces about an axis to produce sheet and solid bodies. The edges and faces may abut, but not strictly intersect the axis.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The edges and faces to revolve. |
|
Line | The axis around which to revolve. EXAMPLE
|
|
ValueWithUnits | The angle where the revolve ends relative to EXAMPLE
|
|
ValueWithUnits | Optional The angle where the revolve starts relative to |
opRuledSurface (context is Context, id is Id, definition is map)
Creates a ruled surface along a set of paths. Direction of ruled surface is specified with either ruledDirection
or angleFromFaces
.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The edges that form the paths for the ruled surface. |
|
RuledSurfaceCornerType | Optional How corners in the ruled surface are handled. Default is |
|
boolean | Optional Ruled surface will use a cubic interpolation if |
|
ValueWithUnits | The width of the ruled surface. |
|
RuledSurfaceType | Specifies how the ruled surface is constructed. |
|
Vector | Required if Ruled surface will be aligned with this vector. |
|
ValueWithUnits | The angle at which the ruled surface meets reference faces or |
|
Query | Required if A set of faces from which to measure |
|
map | |
|
Query | A vertex on the path where the override is applied. |
|
Vector | If specified, override will specify local direction of ruled surface along this vector. |
|
ValueWithUnits | Required if Width of ruled surface at this override. |
|
ValueWithUnits | If specified, override will specify direction as an angle to reference faces. This is only applicable if angleFromFaces is also specified at the top level. |
|
Query | If specified, override will specify that ruled surface touches upToEntity at override. |
opShell (context is Context, id is Id, definition is map)
Create a shell of a solid body with uniform thickness. The bodies that are passed in are hollowed, omitting the walls on the face
entities passed in.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces to shell and solid bodies to hollow. |
|
ValueWithUnits | The distance by which to shell. Positive means shell outward, and negative means shell inward. |
opSplitPart (context is Context, id is Id, definition is map)
Split solid, sheet, and wire bodies with the given sheet body.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The solid, sheet, and wire bodies to split. |
|
A sheet body, a construction plane or a face to cut with. Can be either a |
|
|
boolean | Optional If false, the tool is deleted. Default is |
|
SplitOperationKeepType | Optional Controls which pieces to keep. Default is |
|
boolean | Optional If true, the trimmed face boundaries are used as the tool, rather than the underlying surface. Default is |
opSplitFace (context is Context, id is Id, definition is map)
Split faces with the given edges or faces.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces to split. |
|
Query | Optional The edges to cut with. |
|
ProjectionType | Optional Edge projection method. Default is |
|
Vector | Required if The projection direction. |
|
Query | Optional The faces to cut with. |
|
Query | Optional The sheet or wire bodies to cut with. |
|
boolean | Optional If |
|
Query | Optional These planar faces are treated as infinite, rather than bounded to the face extents. |
|
boolean | Optional if |
|
boolean | Optional if |
Map containing the results of splitting faces by their isoclines. Some faces may have been split, others may have been left intact.
Value | Type | Description |
---|---|---|
SplitByIsoclineResult |
map | |
|
array | An array of steep faces. |
|
array | An array of non-steep faces. |
|
array | An array of edges at the transition from non-steep faces to steep faces. |
opSplitByIsocline (context is Context, id is Id, definition is map)
Split the given faces
by isocline edges. Each isocline follows a path along a face with a constant angle
in the (-90, 90) degree range (e.g., lines of latitude on a sphere). This angle
is the face tangent plane's angle with respect to the direction
with its sign determined by the dot product of direction
and the face normal, and is analogous to the angle used in draft analysis. Depending on the face geometry, there may be zero, one, or multiple isoclines on each face. The isocline edges are created as new edges which split the provided faces
. The resulting faces are either steep (i.e., the angle is less than the input angle
) or non-steep. To instead leave the original faces intact, you can first extract the faces with opExtractSurface(), and create isoclines on the resulting surfaces. The isocline edges can be queried for with qCreatedBy
. The split orientation is consistent such that the non-steep faces are always in "front" of the split, and can be reliably queried for with qSplitBy
:
EXAMPLE
const isoclineEdges = qCreatedBy(id + "splitByIsocline1", EntityType.EDGE); const steepFaces = qSplitBy(id + "splitByIsocline1", EntityType.FACE, true); const nonSteepFaces = qSplitBy(id + "splitByIsocline1", EntityType.FACE, false);Note that
qSplitBy
will return only those faces that were split, while the returnedSplitByIsoclineResult
will include the intact faces as well.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The faces on which to imprint isoclines. |
|
Vector | A reference direction. |
|
ValueWithUnits | The isocline angle with respect to the direction in the (-90, 90) degree range. |
Map containing the results of splitting bodies by their shadow curves. Some faces may have been split, others may have been left intact.
Value | Type | Description |
---|---|---|
SplitBySelfShadowResult |
map | |
|
array | An array of visible faces. |
|
array | An array of invisible faces. |
opSplitBySelfShadow (context is Context, id is Id, definition is map)
Splits the faces of the given bodies
into visible and invisible regions with respect to the given viewDirection
, creating shadow curves as necessary. A shadow curve represents the transition of one face from visible to invisible. Depending on the geometry, there may be zero, one, or more shadow curves per face. The shadow curve edges are created as new edges which split the faces of the provided bodies
. Each of the resulting faces is wholly visible or wholly invisible. Edge-on faces are considered invisible. The shadow curve edges can be queried for with qCreatedBy
. The split orientation is consistent such that the visible faces are always in "front" of the split, and can be reliably queried for with qSplitBy
:
EXAMPLE
const shadowEdges = qCreatedBy(id + "splitBySelfShadow1", EntityType.EDGE); const invisibleFaces = qSplitBy(id + "splitBySelfShadow1", EntityType.FACE, true); const visibleFaces = qSplitBy(id + "splitBySelfShadow1", EntityType.FACE, false);Note that
qSplitBy
will return only those faces that were split, while the returnedSplitBySelfShadowResult
will include the intact faces as well.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The bodies which cast shadows and on which to imprint shadow curves. |
|
Vector | The viewing direction. |
opSweep (context is Context, id is Id, definition is map)
Sweep the given edges and faces along a path resulting in solid and/or sheet bodies.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Edges and faces to sweep. |
|
Query | Edges that comprise the path along which to sweep. The edges can be in any order but must form a connected path. |
|
boolean | Optional If |
|
Query | Optional Keep profile aligned to the normals of these faces. |
|
Query | Optional Keep profile perpendicular to this direction. |
|
ProfileControlMode | Optional Default is NONE EXAMPLE
EXAMPLE
EXAMPLE
|
opThicken (context is Context, id is Id, definition is map)
Thicken sheet bodies and faces into solid bodies.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The sheet bodies and faces to thicken. |
|
ValueWithUnits | The distance by which to thicken in the direction along the normal. |
|
ValueWithUnits | The distance by which to thicken in the opposite direction. |
|
boolean | Optional Default is |
opTransform (context is Context, id is Id, definition is map)
Applies a given transform to one or more bodies. To make transformed copies of bodies, use opPattern
.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The bodies to transform. |
|
Transform | The transform to apply. EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
|
opWrap (context is Context, id is Id, definition is map)
Wraps or unwraps faces from one surface onto another. The location and orientation of the wrapped faces on the destination surface are controlled by the anchorPoint
and anchorDirection
of the source
and destination
WrapSurface
s. The entities
of the operation are not affected, the result of this operation is a new set of surface bodies or imprinted edges representing the wrapped or unwrapped faces. Faces that are topologically connected will remain topologically connected in the result body for WrapType.SIMPLE
and WrapType.TRIM
. This operation currently supports wrapping from a plane onto a cylinder, and unwrapping from a cylinder onto a plane.
(Formerly opRoll
)
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
WrapType | The type of wrap to execute. EXAMPLE
|
|
Query | Faces to wrap from |
|
WrapSurface | The surface to wrap from. All |
|
WrapSurface | The surface to wrap onto. Must be defined using the |
|
boolean | Optional If true (default), the normals of the resulting surface will point in the same direction as the |
cube (context is Context, id is Id, definition is map)
Create a cube of a specified size, with one corner on the origin.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
ValueWithUnits | EXAMPLE
|
sphere (context is Context, id is Id, definition is map)
Feature creating a sphere. Internally, calls opSphere
.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | A vertex query marking the sphere's center. |
|
ValueWithUnits | EXAMPLE
|
fCuboid (context is Context, id is Id, definition is map)
Create a simple rectangular prism between two specified corners.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
fCylinder (context is Context, id is Id, definition is map)
Create a simple cylindrical solid between two points, with a specified radius.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | A 3D length vector in world space. EXAMPLE
|
|
Vector | A 3D length vector in world space. EXAMPLE
|
|
ValueWithUnits | EXAMPLE
|
fCone (context is Context, id is Id, definition is map)
Create a solid cone, possibly truncated.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
|
ValueWithUnits | The radius at the top center. EXAMPLE
|
|
ValueWithUnits | The radius at the bottom center. EXAMPLE
|
fEllipsoid (context is Context, id is Id, definition is map)
Functions used to create sketches, and add entities to sketches.
A sketch used in FeatureScript generally has the following form:
var sketch1 = newSketch(context, id + "sketch1", { "sketchPlane" : qCreatedBy(makeId("Top"), EntityType.FACE) }); skRectangle(sketch1, "rectangle1", { "firstCorner" : vector(0, 0), "secondCorner" : vector(1, 1) }); skSolve(sketch1); extrude(context, id + "extrude1", { "entities" : qSketchRegion(id + "sketch1"), "endBound" : BoundingType.BLIND, "depth" : 0.5 * inch });
A Sketch
object should always be created first, with either newSketch
or newSketchOnPlane
.
Next, any number of sketch entities may be added to the sketch using the functions in this module. The inputs to sketch functions usually involve 2D Vector
s, which are positions relative to the sketch plane's origin and x-axis. To create such a point based on a projected 3D point in world space, use worldToPlane(Plane, Vector)
.
When building sketches in FeatureScript, constraints may be added, but are almost always unnecessary, since you already have the ability to place the entities precisely where you intend them to be.
Finally, the sketch is solved and added to the context by calling skSolve
. As a result of skSolve
, all edges of the sketch will become WIRE
bodies in the context. Any regions enclosed in the sketch will become SURFACE
bodies in the context. Any vertices which are not edge endpoints (such as points created by skPoint
or the center point of skCircle
) will become POINT
bodies in the context. These newly created bodies can be queried for and used in all subsequent operations and features.
Sketch type
A Sketch
object represents a Onshape sketch, to which sketch entities can be added.
Sketches can be created by calls to newSketch
or newSketchOnPlane
.
canBeSketch (value) predicate
Typecheck for builtin Sketch
isIdForSketch (context is Context, id is Id)
Check whether an Id
represents a Sketch operation.
newSketch (context is Context, id is Id, value is map) returns Sketch
Create a new sketch on an existing planar entity. The sketch coordinate system follows the canonical plane orientation and the sketch origin is the projection of the world origin onto the plane.
To make a sketch in the coordinate system of an arbitrary Plane
, use newSketchOnPlane
.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Query | A Query for a single, planar entity. EXAMPLE
|
|
boolean | Optional Prevents |
newSketchOnPlane (context is Context, id is Id, value is map) returns Sketch
Create a new sketch on a custom plane, specified by a Plane
object. The sketch coordinate system will match the coordinate system of the plane.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Plane | EXAMPLE
|
Solve any constraints in the sketch and add all sketch entities form the sketch
to its context.
Even if there are no constraints, a sketch must be solved before its entities are created.
skPoint (sketch is Sketch, pointId is string, value is map) returns map
Add a point to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
Return | Type | Description |
---|---|---|
|
map | |
|
skLineSegment (sketch is Sketch, lineId is string, value is map) returns map
Add a line segment to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
||
|
skText (sketch is Sketch, textId is string, value is map) returns map
Add a text rectangle to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
string | A string of text to write. May contain newlines (encoded as |
|
string | A font name, with extension ".ttf" or ".otf". To change font weight, replace "-Regular" with "-Bold", "-Italic", or "-BoldItalic". Must be one of the following fonts: EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
|
|
boolean | Optional
|
|
Vector | Optional One corner of the rectangle into which the text will be placed. Text will start at the left of the rectangle and extend to the right, overflowing the right if necessary. The first line of text will fill the height of the rectangle, with subsequent lines below the rectangle (or above if mirrored vertically). EXAMPLE
|
|
Vector | Optional The other corner of the rectangle into which the text will be placed. Text will start at the left of the rectangle and extend to the right, overflowing the right if necessary. The first line of text will fill the height of the rectangle, with subsequent lines below the rectangle (or above if mirrored vertically). EXAMPLE
|
|
boolean | Optional
|
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
skImage (sketch is Sketch, imageId is string, value is map) returns map
Add an image rectangle and return ids of corner points.
To use an image uploaded in your document, import the image (possibly into a namespace).
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
map | EXAMPLE
EXAMPLE
|
|
Vector | One corner of the rectangle into which the image will be placed. EXAMPLE
|
|
Vector | The other corner of the rectangle into which the image will be placed. EXAMPLE
|
Return | Type | Description |
---|---|---|
|
map | |
|
skCircle (sketch is Sketch, circleId is string, value is map) returns map
Add a circle to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
ValueWithUnits | EXAMPLE
|
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
skEllipse (sketch is Sketch, ellipseId is string, value is map) returns map
Add an ellipse to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
ValueWithUnits | EXAMPLE
|
|
ValueWithUnits | EXAMPLE
|
|
Vector | Optional A unitless 2D direction, specifying the orientation of the major axis |
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
skArc (sketch is Sketch, arcId is string, value is map) returns map
Add an arc through three points to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
||
|
skEllipticalArc (sketch is Sketch, arcId is string, value is map) returns map
Add an elliptical arc to a sketch. The ellipse has a period of 1, a parameter of 0 at the major axis and 0.25 at the minor axis. The arc is drawn counterclockwise from the start point to the end point.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
Vector | The direction, in sketch coordinates, in which the major axis of the ellipse lies. EXAMPLE
|
|
ValueWithUnits | A non-negative value with length units. EXAMPLE
|
|
ValueWithUnits | A non-negative value with length units. Does not need to be greater than the minor radius. EXAMPLE
|
|
number | The parameter of the start point. EXAMPLE
|
|
number | The parameter of the end point. EXAMPLE
|
|
boolean | Optional
|
Return | Type | Description |
---|---|---|
|
map | |
|
||
|
skFitSpline (sketch is Sketch, splineId is string, value is map)
Create an interpolated spline through the given points.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
An array of points. If the start and end points are the same, the spline is closed. EXAMPLE [ vector( 0, 0) * inch, vector( 0, -1) * inch, vector( 1, 1) * inch, vector(-1, 0) * inch, vector( 0, 0) * inch ] |
|
|
Optional An array of doubles, parameters corresponding to the points. |
|
|
boolean | Optional
|
|
Vector | Optional A 2D |
|
Vector | Optional A 2D |
skBezier (sketch is Sketch, bezierId is string, value is map)
Create a Bezier curve from the given control points.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
An array of points. EXAMPLE [ vector( 0, 0) * inch, vector( 0, 1) * inch, vector( 1, 1) * inch, vector( 1, 0) * inch ] |
|
|
boolean | Optional
|
skRectangle (sketch is Sketch, rectangleId is string, value is map)
Add a rectangle (four line segments, properly constrained) to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
Vector | EXAMPLE
|
|
boolean | Optional
|
skRegularPolygon (sketch is Sketch, polygonId is string, value is map)
Add a regular polygon to the sketch. Unconstrained.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
Vector | EXAMPLE
|
|
Vector | Distance to the center determines the radius. EXAMPLE
|
|
number | Number of polygon sides. Must be an integer 3 or greater. |
|
boolean | Optional
|
skPolyline (sketch is Sketch, polylineId is string, value is map)
Add a polyline (line segments, optionally with constrained endpoints) or a polygon to a sketch.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
array | An array of points, each a EXAMPLE [ vector( 0, 0) * inch, vector( 0, -1) * inch, vector( 1, 1) * inch, vector(-1, 0) * inch, vector( 0, 0) * inch ] |
|
boolean | Optional
|
|
boolean | Optional
|
skConstraint (sketch is Sketch, constraintId is string, value is map)
Add a constraint.
Parameter | Type | Additional Info |
---|---|---|
value |
map | |
|
ConstraintType | |
|
ValueWithUnits | Optional For constraints that require a length. Must have length units. |
|
ValueWithUnits | Optional For constraints that require a angle. Must have angle units. |
Functions for constructing queries. Features that take queries as inputs should re-export this module.
Queries are used to refer to topological entities (vertices, edges, faces, and bodies) that FeatureScript operation and evaluation functions work on. A query is a map that contains instructions for how to find entities. For example, a query for all edges in a context looks like qEverything(EntityType.EDGE)
. Many queries can take subqueries as arguments, allowing for more complex nested queries.
Queries in general do not contain a list of entities in any form. Rather, they contain criteria that specify a subset of the topological entities in a context. To get an array of the entities (if any) which match a query in a context, use evaluateQuery
. There is no need to evaluate a query before passing it into a function, including any of the Standard Library's operation and evaluation functions.
There are two general types of queries: state-based and historical. State-based queries select entities based on the model state, e.g. "All edges adjacent to a cylindrical face which touches this point." Historical queries select entities based on the model history, e.g. "the edge that was generated by feature extrude_1_id
from sketch vertex vertex_id
from sketch sketch_id
." State-based queries cannot refer to entities that have been deleted. Most automatically-generated queries are historical, while queries more commonly used in manually written code are state-based.
Query type
A Query
identifies a specific subset of a context's entities (points, lines, planes, and bodies).
The fields on a Query map depend on its QueryType
, and may include one or more subqueries.
Value | Type | Description |
---|---|---|
Query |
map | |
|
QueryType | |
|
EntityType | Optional |
canBeQuery (value) predicate
Typecheck for Query
BodyType enum
Specifies the topological type of a body.
All bodies have EntityType.BODY
, but will generally own many entities of other EntityType
s.
For example, the result of an extrude with NewBodyOperationType.NEW
is a body. This body will have BodyType.SOLID
for a solid extrude, and BodyType.SHEET
for a surface extrude. This extrude operation will create many geometric entities in the context (faces, edges, or vertices), which are owned by the body, and have the BodyType
of their owning body.
See also
Value | Description |
---|---|
SOLID |
A three-dimensional part (e.g. the result of a solid extrude) |
SHEET |
A two-dimensional sheet body (e.g. a sketch region, or the result of a surface extrude) |
WIRE |
A one-dimensional curve (e.g. a sketch line or curve, or the result of opHelix) |
POINT |
A zero-dimensional point (e.g. a sketch point, or the result of opPoint) |
MATE_CONNECTOR |
A part studio mate connector. |
COMPOSITE |
A composite part body, which can contain bodies of any other type |
EntityType enum
Specifies the topological type of a given entity. Used in several queries as a filter, or on any query explicitly with qEntityFilter
Thus, one can obtain all the vertices in a part studio with qEverything(EntityType.VERTEX)
, and can obtain all the vertices attached to solid bodies with qBodyType(qEverything(EntityType.VERTEX), BodyType.SOLID)
A query for every part in a part studio is qBodyType(qEverything(EntityType.BODY), BodyType.SOLID)
Value | Description |
---|---|
VERTEX |
A zero-dimensional point or vertex |
EDGE |
A one-dimensional line, curve, or edge |
FACE |
A two-dimensional surface, planar face, or non-planar face |
BODY |
A solid, surface, wire, or point body |
AdjacencyType enum
Specifies the adjacency type of queried entities.
See also
Value | Description |
---|---|
VERTEX |
Entities share at least a vertex |
EDGE |
Entities share at least an edge |
GeometryType enum
Specifies the geometric type of queried entities.
See also
Value | Description |
---|---|
LINE |
A straight line or edge |
CIRCLE |
A circle of constant radius |
ARC |
A segment of a circle |
OTHER_CURVE |
Any one-dimensional entity which is not described above (e.g. splines, ellipses, etc.) |
PLANE |
A construction plane or planar face |
CYLINDER |
A surface which forms the side of a right circular cylinder |
CONE |
A surface which forms the side of a right circular cone |
SPHERE |
A surface which forms the boundary of a sphere |
TORUS |
A surface which forms the boundary of a torus |
REVOLVED |
A surface constructed by revolving a curve around an axis (unless it is simplified to one of the types above) |
EXTRUDED |
A surface constructed by extruding or sweeping a curve along a line (unless it is simplified to one of the types above) |
OTHER_SURFACE |
Any two-dimensional entity which is not described above (e.g. the side of an arbitrary loft) |
ALL_MESH |
A surface or a body that is fully mesh or an edge between two mesh surfaces. |
MIXED_MESH |
A body that contains both mesh and non-mesh surfaces or an edge between a mesh and a non-mesh surfaces. |
MESH |
A surface that is mesh, a body that contains mesh surfaces or an edge bordering a mesh surface. |
CapType enum
Specifies which cap queried entities should belong to.
See also
Value | Description |
---|---|
START |
finds entities belonging to the start cap |
END |
finds entities belonging to the end cap |
EITHER |
finds entities belonging to either cap |
ConstructionObject enum
Specifies whether the entity was created for construction (e.g. a construction line or construction plane).
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Edges to use", "Filter" : EntityType.EDGE && ConstructionObject.NO } definition.edges is Query;
See also
Value | Description |
---|---|
YES |
Matches only entities which are created for construction |
NO |
Matches only entities which are not created for construction |
SMFlatType enum
Specifies whether an entity appears in the sheet metal flat view, or the main view.
See also
Value | Description |
---|---|
YES |
Matches entities which belong to a flattened sheet metal part. |
NO |
Matches entities which do not belong to a flattened sheet metal part. |
AllowMeshGeometry enum
Specifies whether we allow meshes. Default is NO
.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Bodies", "Filter" : EntityType.BODY && AllowMeshGeometry.YES } definition.body is Query;
Value | Description |
---|---|
YES |
Allow meshes |
NO |
Disallow meshes |
Specifies whether we allow flat entities. Default is NO
.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Bodies", "Filter" : EntityType.BODY && AllowFlattenedGeometry.YES } definition.body is Query;
Value | Description |
---|---|
YES |
Allow flat entities |
NO |
Disallow flat entities |
ActiveSheetMetal enum
Specifies whether the entities should belong to an active sheet metal model.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Sheet metal bodies", "Filter" : EntityType.BODY && ActiveSheetMetal.YES } definition.body is Query;
Value | Description |
---|---|
YES |
matches only entities which belong to an active sheet metal model |
NO |
matches only entities which do not belong to an active sheet metal model |
SheetMetalDefinitionEntityType enum
Specifies geometry corresponding to a certain type of topological entity in the sheet metal master body for active sheet metal models.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Sheet metal definition edges", "Filter" : SheetMetalDefinitionEntityType.EDGE } definition.entities is Query;
Value | Description |
---|---|
VERTEX |
matches entities defined by a sheet metal master body vertex. This includes vertices, edges, and faces at the corners, bend ends, fillets, and chamfers of sheet metal models. |
EDGE |
matches entities defined by a sheet metal master body edge. This includes edges and faces along the sides of sheet metal walls. |
FACE |
matches entities defined by a sheet metal master body face. This includes faces of sheet metal walls. |
ModifiableEntityOnly enum
Specifies whether we allow modifiable only entities. It is default to NO
.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Bodies", "Filter" : EntityType.BODY && ModifiableEntityOnly.YES } definition.body is Query;
See also
Value | Description |
---|---|
YES |
Only allow modifiable entities |
NO |
Allow both modifiable and unmodifiable entities |
AllowEdgePoint enum
Specifies whether we allow edge points. Default is YES
.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Corners", "Filter" : EntityType.VERTEX && AllowEdgePoint.NO } definition.body is Query;
Value | Description |
---|---|
YES |
Allow edge points |
NO |
Disallow edge points |
MeshGeometry enum
Specifies whether the entities are mesh geometries.
See also
Value | Description |
---|---|
YES |
Matches only entities (edges, faces, and bodies) which are meshes |
NO |
Matches only entities (edges, faces, and bodies) which are not meshes |
SketchObject enum
Specifies whether the entity is a part of a sketch.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Sketch curves", "Filter" : EntityType.EDGE && SketchObject.YES } definition.curves is Query;
See also
Value | Description |
---|---|
YES |
Matches only entities which are part of a sketch |
NO |
Matches only entities which are not part of a sketch |
QueryFilterCompound enum
A set of convenience filters, which are expanded during precondition processing. Can be used as a filter on query parameters, just like their corresponding expansions:
annotation { "Name" : "Axis", "Filter" : QueryFilterCompound.ALLOWS_AXIS } definition.axis is Query;
Value | Description |
---|---|
ALLOWS_AXIS |
Equivalent to |
ALLOWS_DIRECTION |
Equivalent to |
ALLOWS_PLANE |
Equivalent to |
ALLOWS_VERTEX |
Equivalent to |
CompareType enum
Specifies a method of comparing two items.
See also
Value | Description |
---|---|
EQUAL |
|
LESS |
|
LESS_EQUAL |
|
GREATER |
|
GREATER_EQUAL |
Consumed enum
Specifies whether to filter or allow bodies (and their vertices, edges, and faces) consumed by closed composite parts.
See also
Value | Description |
---|---|
YES |
Matches only bodies that are consumed |
NO |
Matches only bodies that are not consumed |
CompositePartType enum
Specifies whether to filter or allow closed or open composite parts.
See also
Value | Description |
---|---|
OPEN |
Matches only open composite parts |
CLOSED |
Matches only closed composite parts |
InContextObject enum
Specifies whether an entity is from an assembly context.
Can be used in a filter on a query parameter to only allow certain selections:
annotation { "Name" : "Edges to use", "Filter" : EntityType.EDGE && InContextObject.NO } definition.edges is Query;
Value | Description |
---|---|
YES |
Matches only entities which are from an assembly context |
NO |
Matches only entities which are not from an assembly context |
An empty query, which does not resolve to any entities.
qEverything (entityType is EntityType) returns Query
A query for all entities of a specified EntityType
in the context.
See also
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Optional |
qEverything () returns Query
A query for all entities in the context.
qAllNonMeshSolidBodies () returns Query
A query for all solid bodies that do not have mesh geometry.
qAllSolidBodies () returns Query
A query for all solid bodies.
qAllModifiableSolidBodiesNoMesh () returns Query
A query for all solid bodies that do not have mesh geometry or in context geometry, i.e. every non-mesh-containing part displayed in the Part Studio's "Parts" list.
See also
qAllModifiableSolidBodies () returns Query
A query for all modifiable solid bodies, including mesh-containing bodies.
See also
qNthElement (queryToFilter is Query, n is number) returns Query
A query for one entity in queryToFilter
at a specified index. The order of entities resolved by a query is deterministic but arbitrary.
Parameter | Type | Additional Info |
---|---|---|
queryToFilter |
Query | A query which resolves to at least n+1 entities |
n |
number | Zero-based index of entity in EXAMPLE
EXAMPLE
|
qEntityFilter (queryToFilter is Query, entityType is EntityType) returns Query
A query for entities in a queryToFilter
which match a given EntityType
.
qHasAttribute (name is string) returns Query
qHasAttribute (queryToFilter is Query, name is string) returns Query
Query for all entities in queryToFilter
marked with an attribute with name name
See also
qHasAttributeWithValue (name is string, value) returns Query
Query for all entities marked with an attribute with name name
and value exactly equal to value
See also
qHasAttributeWithValue (queryToFilter is Query, name is string, value) returns Query
Query for all entities in queryToFilter
marked with an attribute with name name
and value exactly equal to value
See also
qHasAttributeWithValueMatching (name is string, attributePattern is map) returns Query
Query for all entities marked with an attribute with name name
and a map value matching every key-value pair in the provided attributePattern
map.
See also
Parameter | Type | Additional Info |
---|---|---|
attributePattern |
map | EXAMPLE { "key1" : valueToMatch, } |
qHasAttributeWithValueMatching (queryToFilter is Query, name is string, attributePattern is map) returns Query
Query for all entities in queryToFilter
marked with an attribute with name name
and a map value matching every key-value pair in the provided attributePattern
map.
See also
Parameter | Type | Additional Info |
---|---|---|
attributePattern |
map | EXAMPLE { "key1" : valueToMatch, } |
qAttributeFilter (queryToFilter is Query, attributePattern) returns Query
Note: This query is used only for legacy unnamed attributes, which are still supported but no longer reccommended. See the Attributes module for details.
A query for entities in a queryToFilter
which have been assigned a legacy unnamed attribute matching a given attributePattern
.
Parameter | Type | Additional Info |
---|---|---|
attributePattern |
Will only resolve to queries whose legacy unnamed attributes match the type (and possibly the values) of this pattern. If attributePattern has a type tag, will only match attributes with that same type tag. EXAMPLE
If the attribute has no type tag (i.e. it is a standard type like EXAMPLE
EXAMPLE
If the attribute is a map, will only match maps which have identical values for every key-value pair in the pattern EXAMPLE
EXAMPLE
|
qAttributeQuery (attributePattern) returns Query
Note: This query is used only for legacy unnamed attributes, which are still supported but no longer reccommended. See the Attributes module for details.
A query for all entities which have been assigned a legacy unnamed attribute matching a given attributePattern
. Equivalent to qAttributeFilter(qEverything(), attributePattern)
qCreatedBy (featureId is Id, entityType is EntityType) returns Query
A query for all the entities created by a feature or operation. The feature is given by its feature id, which was passed into the the operation function in order to create the feature.
An entity is "created by" an operation if the entity was added to the context as part of that operation. Entities modified, but not created, by an operation are not returned by this query.
If an entity is split (as in a split part operation), the resulting entities are "created by" both the original entity's creator and the split part operation.
If two entities are merged (as in a union of coincident faces), that entity is "created by" the creators of each merged entity, as well as the merging operation itself.
If a sketch's feature id is specified, returns a query for all sketch regions, points, and wire bodies created by the specified sketch.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | The EXAMPLE
|
entityType |
EntityType | Optional |
qCreatedBy (featureId is Id) returns Query
qCreatedBy (features is FeatureList) returns Query
qCreatedBy (features is FeatureList, entityType is EntityType) returns Query
qCapEntity (featureId is Id, capType is CapType, entityType is EntityType) returns Query
A query for start/end cap vertex, edge, and face entities created by featureId
. Cap entities are produced by extrude, revolve, sweep, loft and thicken features
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Optional |
qCapEntity (featureId is Id, capType is CapType) returns Query
qNonCapEntity (featureId is Id, entityType is EntityType) returns Query
A query for vertex, edge, and face entities created by featureId
that are not cap entities. Cap entities are produced by extrude, revolve, sweep, loft and thicken features
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Optional |
qNonCapEntity (featureId is Id) returns Query
qOpHoleProfile (featureId is Id, filters is map) returns Query
A query for the profile edges or vertices created by an opHole
operation.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | The EXAMPLE
|
filters |
map | |
|
string | Optional Filter the query for profiles with a given name. See |
|
Query | Optional Filter the query for the hole associated with the given identity entity. See |
qOpHoleProfile (featureId is Id) returns Query
qOpHoleFace (featureId is Id, filters is map) returns Query
A query for the hole faces created by an opHole
operation.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | The EXAMPLE
|
filters |
map | |
|
string | Optional Filter the query for faces with a given name. See |
|
Query | Optional Filter the query for the hole associated with the given identity entity. See |
qOpHoleFace (featureId is Id) returns Query
qToleranceFilter (queryToFilter is Query) returns Query
qUnion (subqueries is array) returns Query
A query for entities which match any of a list of queries.
qUnion
is guaranteed to preserve order. That is, entities which match queries earlier in the subqueries
input list will also be listed earlier in the output of evaluateQuery
.
qUnion (query1 is Query, query2 is Query) returns Query
qUnion (query1 is Query, query2 is Query, query3 is Query) returns Query
qUnion (query1 is Query, query2 is Query, query3 is Query, query4 is Query) returns Query
qIntersection (subqueries is array) returns Query
A query for entities which match all of a list of queries. qIntersection preserves the order of the first subquery.
qIntersection (query1 is Query, query2 is Query) returns Query
qSubtraction (query1 is Query, query2 is Query) returns Query
A query for entities which match query1
, but do not match query2
. qSubtraction preserves the order of query1
.
qSymmetricDifference (query1 is Query, query2 is Query) returns Query
A query for entities which match either query1
or query2
, but not both.
qOwnedByBody (body is Query, entityType is EntityType) returns Query
A query for all of the entities (faces, vertices, edges, and bodies) in a context which belong to a specified body or bodies.
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Optional |
qOwnedByBody (body is Query) returns Query
qOwnedByBody (queryToFilter is Query, body is Query) returns Query
A query for all of the entities which match a queryToFilter
, and belong to the specified body or bodies.
qOwnerBody (entities is Query) returns Query
A query for each body that any of the given entities
belong to.
If a body is passed in, the result will include that body itself.
qContainedInCompositeParts (compositeParts is Query) returns Query
A query for each part contained in compositeParts
.
qCompositePartsContaining (bodies is Query) returns Query
A query for each composite part containing bodies
.
qCompositePartsContaining (bodies is Query, compositePartType is CompositePartType) returns Query
A query for each composite part of the given type containing bodies
.
qFlattenedCompositeParts (entities is Query) returns Query
A query for non-composite entities in entities
and constituents of composite parts in entities
.
qConsumed (queryToFilter is Query, consumed is Consumed) returns Query
A query for all entities in queryToFilter
which are consumed by any closed composite part, or all entities of queryToFilter
which are not consumed by any closed composite part.
qCompositePartTypeFilter (queryToFilter is Query, compositePartType is CompositePartType) returns Query
A query for all bodies in queryToFilter
which are either open or closed composite parts, depending on the second parameter.
qSourceMesh (selectedMeshVertices is Query, entityType is EntityType) returns Query
A query for each mesh element that any selectedMeshVertices
belong to. selectedMeshVertices
should be the point bodies created when a user selects a mesh vertex. Mesh vertices which have not been selected cannot be queried in FeatureScript
Parameter | Type | Additional Info |
---|---|---|
selectedMeshVertices |
Query | One or more mesh vertices whose owning elements are queried. |
entityType |
EntityType | The type of resulting entities. Can be EntityType.BODY, EntityType.FACE or EntityType.EDGE. |
qSourceMesh (selectedMeshVertices is Query) returns Query
Deprecated: Use qSourceMesh
with EntityType.BODY
qAdjacent (seed is Query, adjacencyType is AdjacencyType, entityType is EntityType) returns Query
A query for entities that are adjacent to the given seed
entities.
Parameter | Type | Additional Info |
---|---|---|
seed |
Query | One or more entities whose adjacent neighbors are queried. The result does not include the original |
adjacencyType |
AdjacencyType | EXAMPLE
EXAMPLE
|
entityType |
EntityType | Optional The type of resulting entities |
qAdjacent (seed is Query, adjacencyType is AdjacencyType) returns Query
qVertexAdjacent (query is Query, entityType is EntityType) returns Query
Deprecated: Use qAdjacent
with AdjacencyType.VERTEX
qEdgeAdjacent (query is Query, entityType is EntityType) returns Query
Deprecated: Use qAdjacent
with AdjacencyType.EDGE
qEdgeTopologyFilter (queryToFilter is Query, edgeTopologyType is EdgeTopology) returns Query
A query for edges in a queryToFilter
which match a given EdgeTopology
.
qEdgeVertex (edgeQuery is Query, atStart is boolean)
A query for the start or end vertices of edges.
qGeometry (queryToFilter is Query, geometryType is GeometryType) returns Query
A query for all entities in queryToFilter
with a specified GeometryType
.
qBodyType (queryToFilter is Query, bodyType is BodyType) returns Query
A query for all entities in queryToFilter
which are bodies of the a specified BodyType
, or are owned by bodies with the specified BodyType
qBodyType (queryToFilter is Query, bodyTypes is array) returns Query
A query for all entities in queryToFilter
with any of a list of BodyType
s.
Parameter | Type | Additional Info |
---|---|---|
bodyTypes |
array | An array of |
qConstructionFilter (queryToFilter is Query, constructionFilter is ConstructionObject) returns Query
A query for all construction entities or all non-construction entities in queryToFilter
.
See also
qActiveSheetMetalFilter (queryToFilter is Query, activeSheetMetal is ActiveSheetMetal) returns Query
A query for all entities in queryToFilter
belonging to an active sheet metal part.
See also
qSheetMetalFlatFilter (queryToFilter is Query, filterFlat is SMFlatType) returns Query
A query for all entities in queryToFilter
belonging to a flattened sheet metal part.
See also
qSMFlatFilter (subquery is Query, filterFlat is SMFlatType) returns Query
Deprecated: Use qSheetMetalFlatFilter
qPartsAttachedTo (sheetMetalEntities is Query) returns Query
A query for parts to which sheetMetalEntities
are attached (e.g. sheet metal bend line entities are attached to a flattened sheet metal part)
qCorrespondingInFlat (entitiesInFolded is Query) returns Query
A query for entities in sheet metal flattened body corresponding to any entitiesInFolded
which are part of 3D sheet metal bodies
qMeshGeometryFilter (queryToFilter is Query, meshGeometryFilter is MeshGeometry) returns Query
A query for all mesh entities or all non-mesh entities in queryToFilter
.
A body is considered a "mesh entity" if any of its faces or edges have mesh geometry.
See also
qModifiableEntityFilter (queryToFilter is Query) returns Query
A query for all modifiable entities in queryToFilter
.
An entity is considered non-modifiable if it is an in-context entity.
See also
qSketchFilter (queryToFilter is Query, sketchObjectFilter is SketchObject) returns Query
A query for all sketch entities, or all non-sketch entities in queryToFilter
.
qParallelPlanes (queryToFilter is Query, referencePlane is Plane, allowAntiparallel is boolean) returns Query
A query for all planar face entities that are parallel to the referencePlane
.
Parameter | Type | Additional Info |
---|---|---|
referencePlane |
Plane | The plane to reference when checking for parallelism. |
allowAntiparallel |
boolean | Whether to also return entities that are antiparallel. |
qParallelPlanes (queryToFilter is Query, referencePlane is Plane) returns Query
A query for all planar face entities in queryToFilter
that are parallel to the referencePlane
.
Parameter | Type | Additional Info |
---|---|---|
referencePlane |
Plane | The plane to reference when checking for parallelism. |
qParallelPlanes (queryToFilter is Query, normal is Vector, allowAntiparallel is boolean) returns Query
A query for all planar face entities in queryToFilter
that are parallel to a plane specified by the normal
vector.
Parameter | Type | Additional Info |
---|---|---|
normal |
Vector | The normal vector to reference when checking for parallelism. |
allowAntiparallel |
boolean | Whether to also return entities that are antiparallel. |
qPlanesParallelToDirection (queryToFilter is Query, direction is Vector) returns Query
A query for all planar faces in queryToFilter
that are parallel to the given direction vector (i.e., the plane normal is perpendicular to direction
).
qFacesParallelToDirection (queryToFilter is Query, direction is Vector) returns Query
A query for all faces in queryToFilter
that are parallel to the given direction vector e.g. if it is a planar face, the plane normal is perpendicular to direction
if it is a cylindrical face, the axis is parallel to direction
if it is an extruded face, the extrude direction is parallel to direction
qParallelPlanes (queryToFilter is Query, normal is Vector) returns Query
A query for all planar face entities in queryToFilter
that are parallel to a plane specified by the normal
vector.
Parameter | Type | Additional Info |
---|---|---|
normal |
Vector | The normal vector to reference when checking for parallelism. |
qConvexConnectedFaces (seed is Query) returns Query
A query for a set of faces connected to seed
via convex edges, flood-filling across any number of convex edges.
A convex edge is an edge which forms a convex angle along the full length of the edge. A convex angle is strictly less than 180 degrees for flat faces, or faces with negative curvature. If one face has positive curvature, and the other has flat or positive curvature, a convex angle is less than or equal to 180 degrees. Thus, the two bounding edges of an exterior fillet are considered convex.
qConcaveConnectedFaces (seed is Query) returns Query
A query for a set of faces connected to seed
via concave edges, flood-filling across any number of concave edges.
A concave edge is an edge which forms a concave angle along the full length of the edge. A concave angle is strictly greater than 180 degrees for flat faces, or faces with positive curvature. If one face has negative curvature, and the other has flat or negative curvature, a concave angle is less than or equal to 180 degrees. Thus, the two bounding edges of an interior fillet are considered concave.
qTangentConnectedFaces (seed is Query) returns Query
A query for a set of faces connected to seed
via tangent edges, flood-filling across any number of tangent edges.
A tangent edge is an edge joining two faces such that the surface direction is continuous across the edge, at every point along the full length of the edge.
qTangentConnectedFaces (seed is Query, angleTolerance is ValueWithUnits) returns Query
A query for a set of faces connected to seed
via tangent edges, flood-filling across any number of tangent edges.
A tangent edge is an edge joining two faces such that the surface direction is continuous across the edge, up to the given angleTolerance
, at every point along the full length of the edge.
qTangentConnectedEdges (seed is Query) returns Query
A query for a chain of tangent edges connected to seed
via tangent vertices, chaining across any number of tangent vertices.
qLoopEdges (seed is Query) returns Query
A query for a set of edges defining a loop. If the seed
has laminar edges, this query will extend to include all laminar loops that contain any seed
edges. If the seed
has faces, the result will include the loops forming the outer boundary of the joined faces.
qParallelEdges (queryToFilter is Query, direction is Vector) returns Query
A query for all linear edges in queryToFilter
which are parallel (or anti-parallel) to the given direction
.
qParallelEdges (queryToFilter is Query, edges is Query) returns Query
A query to find all linear edges in queryToFilter
which are parallel (or anti-parallel) to any linear edge in edges
.
qLoopBoundedFaces (faceAndEdge is Query) returns Query
Given a face and an edge, query for all faces bounded by the given face, on the side of the given edge.
For example, to select an entire pocket, pass in the face which surrounds the pocket, and an edge of the face which touches that pocket.
Parameter | Type | Additional Info |
---|---|---|
faceAndEdge |
Query | Should match a face and an edge. If multiple faces and edges match, used the first face and the first edge. |
qFaceOrEdgeBoundedFaces (faceAndBoundingEntities is Query) returns Query
Given a seed face and bounding entities, matches all adjacent faces inside the bounding entities, expanding from the seed face.
Parameter | Type | Additional Info |
---|---|---|
faceAndBoundingEntities |
Query | A Query for the seed face, followed by any boundary faces or edges. The seed face must be first, so a |
qHoleFaces (seed is Query) returns Query
Given a single face inside a hole or hole-like geometry, returns all faces of that hole.
Parameter | Type | Additional Info |
---|---|---|
seed |
Query | A query for a single face inside the hole. |
qSketchRegion (featureId is Id, filterInnerLoops is boolean) returns Query
A query for all fully enclosed, 2D regions created by a sketch.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | The feature id of the |
filterInnerLoops |
boolean | Optional Specifies whether to exclude sketch regions fully contained in other sketch regions. A region whose border has a vertex or edge on the outside boundary is not considered "contained." Default is false. |
qSketchRegion (featureId is Id) returns Query
qUniqueVertices (vertices is Query) returns Query
A query that filters out duplicate vertices. When duplicates are found, the vertex with the lowest deterministic ID is used.
qMateConnectorsOfParts (parts is Query) returns Query
A query for all mate connectors owned by parts
.
qFilletFaces (facesToCompareTo is Query, compareType is CompareType) returns Query
A query for fillet faces of radius equal to, less than or equal to, or greater than or equal to the input faces. If facesToCompareTo
does not match one or more fillet faces, the resulting query will not match any faces. Will find the fillet radius from each face and compare to find faces of all fillets on that body that satisfy the compareType.
If facesToCompareTo
resolves to multiple fillet faces, all are matched independently. That is, qFilletFaces(qUnion([q1, q2], compareType))
returns the same thing as qUnion([qFilletFaces(q1, compareType), qFilletFaces(q2, compareType)])
.
qMatching (referenceEntities is Query) returns Query
Matches any faces or edges within owner bodies of entities in referenceEntities
which are geometrically identical (same size and shape) to the face or edge in referenceEntities
.
If referenceEntities
resolves to multiple entities, all are matched independently. That is, qMatching(qUnion([q1, q2]))
returns the same thing as qUnion([qMatching(q1), qMatching(q2)])
.
qPatternInstances (featureId is Id, instanceNames is array, entityType is EntityType) returns Query
A query for entities created by a specific instance or instances of an opPattern
operation.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | The EXAMPLE
|
instanceNames |
array | The names of the instances to query for, a subset of the instanceNames passed into the |
qPatternInstances (featureId is Id, instanceName is string, entityType is EntityType) returns Query
qDependency (dependentEntities is Query) returns Query
A query for the true dependency of the given dependentEntities
. For instance, the true dependency of the extruded body will be the face or sketch edges of the profile from which it is extruded.
qLaminarDependency (dependentEntities is Query) returns Query
A query for the true dependency of the given dependentEntities
, specifically for use with wire edges that have been created from laminar edges. If the immediate dependency is not laminar then it will track back until it reaches a laminar dependency (if there is one).
qContainsPoint (queryToFilter is Query, point is Vector) returns Query
A query for all entities (bodies, faces, edges, or points) in queryToFilter
containing a specified point.
Parameter | Type | Additional Info |
---|---|---|
point |
Vector | A 3D point, in world space. |
qIntersectsLine (queryToFilter is Query, line is Line) returns Query
A query for all entities (bodies, faces, edges, or points) in queryToFilter
touching a specified infinite line.
qIntersectsPlane (queryToFilter is Query, plane is Plane) returns Query
A query for all entities (bodies, faces, edges, or points) in queryToFilter
touching a specified infinite plane.
Parameter | Type | Additional Info |
---|---|---|
plane |
Plane | EXAMPLE
|
qInFrontOfPlane (queryToFilter is Query, plane is Plane) returns Query
A query for all entities (bodies, faces, edges, or points) in queryToFilter
in front of a specified infinite plane. Entities intersecting the plane will not be resolved. Only entities completely on one side or coincident with the plane will be selected. Use flip(plane)
to query entities on the other side of the plane. For example, for the XY plane through the origin with the normal (0, 0, 1), qInFrontOfPlane
will resolve the vertices (1, 1, 0) and (1, 1, 1) but not the vertex (1, 1, -1).
Parameter | Type | Additional Info |
---|---|---|
plane |
Plane | EXAMPLE
|
qCoincidesWithPlane (queryToFilter is Query, plane is Plane) returns Query
A query for all entities (bodies, faces, edges, or points) in queryToFilter
coinciding with a specified infinite plane.
Parameter | Type | Additional Info |
---|---|---|
plane |
Plane | EXAMPLE
|
qWithinRadius (queryToFilter is Query, point is Vector, radius is ValueWithUnits) returns Query
A query for all entities (bodies, faces, edges or points) in queryToFilter
that are within a specified radius from a point.
Parameter | Type | Additional Info |
---|---|---|
point |
Vector | The point from which to check distance from. |
radius |
ValueWithUnits | The distance away from the point. |
qClosestTo (queryToFilter is Query, point is Vector) returns Query
A query for the entity in queryToFilter
closest to a point.
In the case of a tie, resolves to all entities within TOLERANCE.zeroLength
of being the closest.
Parameter | Type | Additional Info |
---|---|---|
point |
Vector | A position vector for the point to find entities closest to. |
qFarthestAlong (queryToFilter is Query, direction is Vector) returns Query
A query for the entity in queryToFilter
farthest along a direction
in world space. In the case of a tie, resolves to all entities within TOLERANCE.zeroLength
of being the farthest.
Parameter | Type | Additional Info |
---|---|---|
direction |
Vector | A vector for the direction to find the entity farthest away. |
qLargest (queryToFilter is Query) returns Query
A query to find the largest entity (by length, area, or volume) in queryToFilter
.
If queryToFilter
contains entities of different dimensionality (e.g. both solid bodies and faces), only entities of the highest dimension are considered. Entities are compared by length, area or volume. Multiple entities may be returned if they tie within tolerance.
qSmallest (queryToFilter is Query) returns Query
A query to find the smallest entity (by length, area, or volume) in queryToFilter
.
If queryToFilter
contains entities of different dimensionality (e.g. solid bodies and faces), only entities of the highest dimension are considered. Entities are compared by length, area or volume. Multiple entities may be returned if they tie within tolerance.
dummyQuery (operationId is Id, entityType is EntityType) returns Query
qSplitBy (featureId is Id, entityType, backBody is boolean) returns Query
Given the id of a split feature, get entities of a given EntityType
on the front or the back side of the split. For a split by face or part, the front denotes the body in the direction of the split tool's surface normal, and the back denotes the body opposite the normal. For a split by isocline, the front denotes non-steep faces and edges, and the back denotes steep entities.
Parameter | Type | Additional Info |
---|---|---|
featureId |
Id | EXAMPLE
|
backBody |
boolean | EXAMPLE
EXAMPLE
|
sketchEntityQuery (operationId is Id, entityType, sketchEntityId is string) returns Query
Gets the wire body entities created for a specific sketch entity. If the sketch id created multiple sketch entities, will return all the wire bodies.
Parameter | Type | Additional Info |
---|---|---|
operationId |
Id | Id of the sketch feature. |
entityType |
EXAMPLE
EXAMPLE
EXAMPLE
|
|
sketchEntityId |
string | Sketch id. |
evaluateQuery (context is Context, query is Query) returns array
Returns an array of queries for the individual entities in a context which match a specified query. The returned array contains exactly one transient query for each matching entity at the time of the call. If the context is modified, the returned queries may become invalid and no longer match an entity.
It is usually not necessary to evaluate queries, since operation and evaluation functions can accept non-evaluated queries. Rather, the evaluated queries can be used to count the number of entities (if any) that match a query, or to iterate through the list to process entities individually.
The order of entities returned by this function is arbitrary (and generally not predictable) except in the case of a qUnion
query. In that case, the entities matched by earlier queries in the argument to qUnion
are returned first.
areQueriesEquivalent (context is Context, first is Query, second is Query) returns boolean
Returns true
if the supplied queries evaluate to the same set of entities. This function is order-invariant, so if the two queries evaluate to the same entities, but in a different order, the function will still return true
.
isQueryEmpty (context is Context, query is Query) returns boolean
Returns true
if query
evaluates to nothing. Equivalent to evaluateQuery(context, query) == []
or size(evaluateQuery(context, query)) == 0
, but faster than either of those approaches if the query is not empty.
Evaluation functions return information about the topological entities in the context, like bounding boxes, tangent planes, projections, and collisions. Evaluation functions take a context and a map that specifies the computation to be performed and return a ValueWithUnits, a FeatureScript geometry type (like Line
or Plane
), or a special type like DistanceResult
. They may also throw errors if a query fails to evaluate or the input is otherwise invalid.
evApproximateCentroid (context is Context, arg is map) returns Vector
Find the centroid of an entity or group of entities. This is equivalent to the center of mass for a constant density object. Warning: This is an approximate value and it is not recommended to use this for modeling purposes that will be negatively affected in case the approximation changes. Consider using the center of a bounding box instead.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The entities to take the center of mass of. |
MassProperties type
The result of an evApproximateMassProperties
call.
Value | Type | Description |
---|---|---|
MassProperties |
map | |
|
ValueWithUnits | The total mass. |
|
Vector | The center of mass with respect to the given reference frame, or with respect to the origin if a reference frame is not specified. |
|
MatrixWithUnits | The 3D inertia tensor, with units of mass * length ^ 2. Evaluated with respect to the reference frame, or with respect to the centroid if a reference frame is not specified. |
|
ValueWithUnits | Total volume. Only returned for solid bodies. |
|
ValueWithUnits | Total area. Only returned for faces. |
|
ValueWithUnits | Total length. Only returned for edges. |
|
number | Total count. Only returned for vertices. |
evApproximateMassProperties (context is Context, arg is map) returns MassProperties
Calculates approximate mass properties of an entity or group of entities. Returns mass, centroid, inertia tensor, and volume/area/length/count for bodies/faces/edges/vertices, respectively. Warning: These are approximate values and it is not recommended to use them for modeling purposes that will be negatively affected in case the approximation changes.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The entities of which to compute mass properties. Only entities of the highest dimensionality will be considered. |
|
ValueWithUnits | The density of the entities, with appropriate units. EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
|
|
CoordSystem | Optional Optional coordinate system. Defaults to the centroid with world axes for the inertia tensor, and world coordinates for the centroid. |
evArea (context is Context, arg is map) returns ValueWithUnits
Return the total area of all the entities. If no matching 2D faces are found the total area will be zero.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
evAxis (context is Context, arg is map) returns Line
If the query finds one entity with an axis -- a line, circle, plane, cylinder, cone, sphere, torus, mate connector, or revolved surface -- return the axis. Otherwise throw an exception.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
evBox3d (context is Context, arg is map) returns Box3d
Find a bounding box around an entity, optionally with respect to a given coordinate system. There is also an option to use a faster but less accurate method.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The entity to find the bounding box of. |
|
CoordSystem | Optional The coordinate system to use (if not the standard coordinate system). |
|
boolean | Optional Get the tightest possible bounding box. Defaults to EXAMPLE
EXAMPLE
|
evCollision (context is Context, arg is map) returns array
Find collisions between tools and targets. Each collision is a map with field type
of type ClashType
and fields target
, targetBody
, tool
, and toolBody
of type Query
.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
Query |
evCornerType (context is Context, arg is map) returns map
Return the type of corner found at a vertex of a sheet metal model
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Return | Type | Description |
---|---|---|
|
map | |
|
SMCornerType | the type of the corner |
|
Query | the vertex that defines the corner |
|
array | array of transient queries for all definition vertices associated with the corner |
Throws | Additional info |
---|---|
GBTErrorStringEnum.BAD_GEOMETRY | The query does not evaluate to a single vertex |
evCurveDefinition (context is Context, arg is map) returns map
Given a query for a curve, return a Circle
, Ellipse
, Line
, or BSplineCurve
value for the curve. If the curve is none of these types, return a map with unspecified contents.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to evaluate. |
|
boolean | Optional If true, do not return B-spline curves (to avoid the associated time cost). Default is false. |
Throws | Additional info |
---|---|
GBTErrorStringEnum.INVALID_INPUT | The first resolved entity was not an edge. |
GBTErrorStringEnum.CANNOT_RESOLVE_ENTITIES | Input entities are invalid or there are no input entities. |
evApproximateBSplineCurve (context is Context, arg is map) returns BSplineCurve
Given a query for a curve, return its approximation (or exact representation if possible) as a B-spline. The options forceCubic
and forceNonRational
may be used to restrict the type of spline that is returned, but even if these options are false, a cubic non-rational spline may be returned.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to approximate. |
|
boolean | Optional If true, a cubic spline will be returned. Defaults to false. |
|
boolean | Optional If true, a non-rational spline will be returned. Defaults to false. |
|
number | Optional Specifies the desired approximation tolerance: the maximum distance (in meters) between the original curve and the returned spline representation. Default is 1e-6, minimum is 1e-8, and maximum is 1e-2. |
DistanceResult type
The result of an evDistance
call -- information about the extremal distance and the attaining point / line / entity.
Value | Type | Description |
---|---|---|
DistanceResult |
map | |
|
ValueWithUnits | The minimal or maximal distance. |
|
array | An array of 2 maps, containing information about where the extremum was found for each side. Each map has a:
If the If the If the If the |
evDistance (context is Context, arg is map) returns DistanceResult
Computes the minimum or maximum distance between geometry on side0
and geometry on side1
. "Geometry" means entities, points, or lines. When the minimum or the maximum is not uniquely defined, ties will be broken arbitrarily.
EXAMPLE
evDistance(context, { "side0" : vector(1, 2, 3) * meter, "side1" : query }).distance
returns the minimum distance from any entity returned byquery
to the point(1, 2, 3) meters
.
EXAMPLE
result = evDistance(context, { "side0" : qEverything(EntityType.VERTEX), "side1" : qEverything(EntityType.VERTEX), "maximum" : true })
computes the pair of vertices farthest apart.qNthElement(qEverything(EntityType.VERTEX), result.sides[0].index)
queries for one of these vertices.
See also
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
One of the following: A query, or a point (3D Length Vector), or a EXAMPLE
|
|
|
boolean | Optional If |
|
Like |
|
|
boolean | Optional Like |
|
boolean | Optional If |
|
boolean | Optional If true (default), the parameter returned for edges measures distance along the edge, so |
|
boolean | Optional For Onshape internal use. |
RaycastResult type
Map containing the results of one collision between a ray and an entity.
Value | Type | Description |
---|---|---|
RaycastResult |
map | |
|
Query | A query for the entity hit by the ray. |
|
EntityType | The type of the entity. |
|
Parameters for where the ray hit the entity. A unitless 2-vector for a face, a number for an edge, else undefined. |
|
|
Vector | Intersection point. |
|
ValueWithUnits | Distance of the intersection point from the ray origin. |
evRaycast (context is Context, arg is map) returns array
Detect intersections between a ray and the given entities.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | A query for target entities. If bodies are provided, the result will contain intersections for individual entities owned by the body. |
|
Line | The ray to intersect the entities. Because the passed-in EXAMPLE
|
|
boolean | Optional Get only the closest intersection with any of the entities. Defaults to |
|
boolean | Optional Return intersections that are behind the ray origin. Defaults to |
Return type | Description |
---|---|
array | An array of |
evEdgeConvexity (context is Context, arg is map) returns EdgeConvexityType
Return the convexity type of the given edge, CONVEX
, CONCAVE
, SMOOTH
, or VARIABLE
. If the edge is part of a body with inside and outside convex and concave have the obvious meanings.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.TOO_MANY_ENTITIES_SELECTED | The query evaluates to more than one entity |
GBTErrorStringEnum.BAD_GEOMETRY | The query does not evaluate to a single edge. |
EdgeCurvatureResult type
The result of an evEdgeCurvature
call -- a coordinate system for the Frenet frame and the curvature defined at a point
Value | Type | Description |
---|---|---|
EdgeCurvatureResult |
map | |
|
CoordSystem | The frame. The Z vector is the tangent, the X vector is the normal and the Y vector is the binormal |
|
ValueWithUnits | The curvature (inverse length units). |
evEdgeCurvature (context is Context, arg is map) returns EdgeCurvatureResult
Return a Frenet frame along an edge, with curvature. If the curve has zero curvature at an evaluated point then the returned normal and binormal are arbitrary and only the tangent is significant.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to use EXAMPLE
|
|
number | A number in the range 0..1 indicating the point along the curve to evaluate the frame at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
Query | Optional If present, the edge orientation used is such that walking along the edge with "up" being the |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_LINE | A frame could not be calculated for the specified input. |
evEdgeCurvatures (context is Context, arg is map) returns array
Return Frenet frames along an edge, with curvature. If the curve has zero curvature at an evaluated point then the returned normal and binormal are arbitrary and only the tangent is significant.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to use EXAMPLE
|
|
array | An array of numbers in the range 0..1 indicating points along the curve to evaluate frames at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
Query | Optional If present, the edge orientation used is such that walking along the edge with "up" being the |
Return type | Description |
---|---|
array | An array of |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_LINE | A frame could not be calculated for the specified input. |
curvatureFrameTangent (curvatureResult is EdgeCurvatureResult) returns Vector
Returns the tangent vector of a curvature frame
Return type | Description |
---|---|
Vector | A unit 3D vector in world space. |
curvatureFrameNormal (curvatureResult is EdgeCurvatureResult) returns Vector
Returns the normal vector of a curvature frame
Return type | Description |
---|---|
Vector | A unit 3D vector in world space. |
curvatureFrameBinormal (curvatureResult is EdgeCurvatureResult) returns Vector
Returns the binormal vector of a curvature frame
Return type | Description |
---|---|
Vector | A unit 3D vector in world space. |
evEdgeTangentLine (context is Context, arg is map) returns Line
Return one tangent Line
to an edge.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to use EXAMPLE
|
|
number | A number in the range 0..1 indicating a point along the curve to evaluate the tangent at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
Query | Optional If present, the edge orientation used is such that walking along the edge with "up" being the |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_LINE | A tangent line could not be evaluated for the given query. |
evEdgeTangentLines (context is Context, arg is map) returns array
Return tangent lines to a edge.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to use EXAMPLE
|
|
array | An array of numbers in the range 0..1 indicating points along the curve to evaluate tangents at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
Query | Optional If present, the edge orientation used is such that walking along the edge with "up" being the |
Return type | Description |
---|---|
array | An array of |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_LINE | A tangent line could not be evaluated for the given query. |
evEdgeCurvatureDerivative (context is Context, arg is map) returns Vector
Evaluate the derivative of the curvature vector with respect to arc length, that is, the third derivative of the curve with respect to arc length.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to use EXAMPLE
|
|
number | A number in the range 0..1 indicating a point along the curve to evaluate the tangent at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_LINE | The curvature derivative could not be evaluated for the given query. |
evFacePeriodicity (context is Context, arg is map) returns array
Return the periodicity in primary and secondary direction of a face, returned in an array of booleans.
A particular direction is periodic when the face's underlying surface definition is wrapped along that direction. For instance, if primary direction is periodic, the parameters [0, v]
and [1, v]
will prepresent the same point for all valid v
. If the secondary direction is periodic, the parameters [u, 0]
and [u, 1]
represent the same point for all valid u
.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The face on which to evaluate periodicity |
|
boolean | Optional If |
FaceCurvatureResult type
The result of an evFaceCurvature
call -- principal directions and curvatures at a point.
The curvature along a particular direction (in the tangent plane) is the inverse of the radius of curvature in that direction. This curvature is positive if the radius of curvature points away from the normal direction, negative if it points along the normal direction, or zero if there is no curvature in that direction. The principal curvatures at a point are the directions of minimal and maximal curvature along the surface at that point.
Value | Type | Description |
---|---|---|
FaceCurvatureResult |
map | |
|
ValueWithUnits | The smaller of the two principal curvatures (inverse length units). |
|
ValueWithUnits | The larger of the two principal curvatures (inverse length units). |
|
Vector | A 3D unit vector corresponding to |
|
Vector | A 3D unit vector corresponding to |
evFaceCurvature (context is Context, arg is map) returns FaceCurvatureResult
Given a face, calculate and return principal curvatures at a point on that face, specified by its parameter-space coordinates.
EXAMPLE
// Ellipsoid measuring 10in x 4in x 6in fEllipsoid(context, id + "ellipsoid", { "center" : vector(0, 0, 0) * inch, "radius" : vector(5 * inch, 2 * inch, 3 * inch) }); const ellipseFace = qCreatedBy(id + "ellipsoid", EntityType.FACE); const topPoint = vector(0, 0, 3) * inch; // Point on top of ellipsoid const distanceResult = evDistance(context, { // Closest position to topPoint on ellipseFace "side0" : ellipseFace, "side1" : topPoint }); var uvCoordinatesAtTopPoint = distanceResult.sides[0].parameter; var curvatureResult = evFaceCurvature(context, { "face" : ellipseFace, "parameter" : uvCoordinatesAtTopPoint }); // curvatureResult is { // minCurvature: 3 * inch / (5 * inch)^2, // maxCurvature: 3 * inch / (2 * inch)^2, // minDirection: vector(1, 0, 0), // maxDirection: vector(0, 1, 0) // }
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The face on which to evaluate the curvature. The face cannot be a mesh. EXAMPLE
|
|
Vector | a 2d unitless parameter-space vector specifying the location on the face. The coordinates are relative to the parameter-space bounding box of the face. EXAMPLE
|
evFaceCurvatures (context is Context, arg is map) returns array
Given a face, calculate and return an array of principal curvatures at points on that face, specified by its parameter-space coordinates.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | A single face on which to evaluate the curvatures. The face cannot be a mesh. EXAMPLE
|
|
array | an array of 2d unitless parameter-space vectors specifying locations on the face. The coordinates are relative to the parameter-space bounding box of the face. EXAMPLE
|
Return type | Description |
---|---|
array | An array of |
evFaceCurvatureDerivative (context is Context, arg is map) returns MatrixWithUnits
Given a face, calculate and return the derivative of the second fundamental form of the face in a given direction.
The second fundamental form is a matrix that may be computed from the principal curvatures of a surface as
const curvature = evFaceCurvature(context, { ... }); const secondFF = - curvature.minCurvature * transpose(matrix([curvature.minDirection])) * matrix([curvature.minDirection]) - curvature.maxCurvature * transpose(matrix([curvature.maxDirection])) * matrix([curvature.maxDirection]);
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The face on which to evaluate the curvature. The face cannot be a mesh. EXAMPLE
|
|
Vector | a 2d unitless parameter-space vector specifying the location on the face. The coordinates are relative to the parameter-space bounding box of the face. EXAMPLE
|
|
Vector | a 3d unitless vector specifying a direction in the tangent plane of the face. It should be a unit vector perpendicular to the face's normal at the given point. |
Return type | Description |
---|---|
MatrixWithUnits | A 3x3 matrix with units of length ^ -2. |
evFaceNormalAtEdge (context is Context, arg is map) returns Vector
Return the surface normal of a face at a position on one of its edges.
If the first result is not a face, throw an exception.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
Query | |
|
number | A number in the range 0..1 indicating a point along the edge to evaluate the tangent at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
boolean | Optional If true, the edge orientation used is such that walking along the edge with "up" being the |
evFaceTangentPlaneAtEdge (context is Context, arg is map) returns Plane
Return a Plane
tangent to face at a position on one of its edges.
If the first result is not a face, throw an exception.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
Query | |
|
number | A number in the range 0..1 indicating a point along the edge to evaluate the tangent at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
boolean | Optional If true, the edge orientation used is such that walking along the edge with "up" being the |
evFaceTangentPlanesAtEdge (context is Context, arg is map)
Return an array of Plane
s tangent to a face at an array of parameters on one of its edges. The x-direction of the plane is oriented with the tangent of the edge with respect to usingFaceOrientation
.
If the first result is not a face, throw an exception.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
Query | |
|
array | An array of numbers in the range 0..1 indicating points along the edge to evaluate the tangent at. |
|
boolean | Optional If true (default), the parameter measures distance along the edge, so |
|
boolean | Optional If true, the edge orientation used is such that walking along the edge with "up" being the |
evFaceTangentPlane (context is Context, arg is map) returns Plane
Given a face, calculate and return a Plane
tangent to that face, where the plane's origin is at the point specified by its parameter-space coordinates.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The face to evaluate. The face cannot be a mesh. EXAMPLE
|
|
Vector | 2d unitless parameter-space vector specifying the location of tangency on the face. The coordinates are relative to the parameter-space bounding box of the face. EXAMPLE
|
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_PLANE | Could not find a tangent plane or there was a problem with face parameterization. |
evFaceTangentPlanes (context is Context, arg is map) returns array
Given a face, calculate and return an array of Plane
s tangent to that face, where each plane's origin is located at the point specified by its parameter-space coordinates.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The face to evaluate. The face cannot be a mesh. EXAMPLE
|
|
array | an array of 2d unitless parameter-space vectors specifying locations of tangency on the face. The coordinates are relative to the parameter-space bounding box of the face. EXAMPLE
|
|
boolean | Optional If true, the function will only return a plane if vector is on the face, otherwise returns undefined. Default is false. |
Throws | Additional info |
---|---|
GBTErrorStringEnum.NO_TANGENT_PLANE | Could not find a tangent plane or there was a problem with face parameterization. |
evFilletRadius (context is Context, arg is map) returns ValueWithUnits
Given a face of a constant radius fillet, return the radius of fillet.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.BAD_GEOMETRY | The first resolved entity was not a filleted face. |
evLength (context is Context, arg is map) returns ValueWithUnits
Return the total length of all the entities (if they are edges) and edges belonging to entities (if they are bodies). If no edges are found the total length will be zero.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
evLine (context is Context, arg is map) returns Line
If the edge is a line, return a Line
value for the given edge.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.INVALID_INPUT | The first resolved entity was not a line. |
evMateConnector (context is Context, arg is map) returns CoordSystem
Gets the coordinate system of the given mate connector
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The mate connector to evaluate. |
evOwnerSketchPlane (context is Context, arg is map) returns Plane
Return the plane of the sketch that created the given entity.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The sketch entity. May be a vertex, edge, face, or body. |
|
boolean | Optional If true, the function will only return a plane if all entities queried under 'entity' share coplanar sketch planes. Otherwise, the plane will only be evaluated for the first entity in the query. Default is false. |
Throws | Additional info |
---|---|
GBTErrorStringEnum.CANNOT_RESOLVE_PLANE | Entities were not created by a sketch or do not share the same sketch plane. |
evPlane (context is Context, arg is map) returns Plane
If the face is a planar face or a mate connector, return the Plane
it represents.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.CANNOT_RESOLVE_PLANE | The first resolved entity was not a planar face or mate connector. |
evPlanarEdge (context is Context, arg is map) returns Plane
If the edge lies in a plane, return a Plane
it lies in.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.CANNOT_RESOLVE_PLANE | The first resolved entity was not a planar edge. |
evPlanarEdges (context is Context, arg is map) returns Plane
If all the edges in a query share the same plane, return a Plane
they lie in.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
Throws | Additional info |
---|---|
GBTErrorStringEnum.CANNOT_RESOLVE_PLANE | Edges in the query were either not planar or do not share the same plane. |
evSurfaceDefinition (context is Context, arg is map) returns map
Return a descriptive value for a face, or the first face if the query finds more than one. Return a Cone
, Cylinder
, Plane
, Sphere
, Torus
, or BSplineSurface
as appropriate for the face, or an unspecified map value if the face is none of these with surfaceType filled of type SurfaceType
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
boolean | Optional If true, do not return B-spline surfaces (to avoid the associated time cost). Default is false. |
Throws | Additional info |
---|---|
"GBTErrorStringEnum.CANNOT_RESOLVE_PLANE" | The first result is not a face. |
evApproximateBSplineSurface (context is Context, arg is map) returns map
Given a query for a face, return its approximation as a B-spline, including trim boundaries. The options forceCubic
and forceNonRational
may be used to restrict the type of spline that is returned for the surface, but even if these options are false, a cubic non-rational spline may be returned.
The returned representation includes a surface, the boundary loop as 2D splines in UV space, and any interior loops. The returned UV curves are typically degree 1 or 2 and non-rational. For periodic surfaces, outer and inner loops are not clearly defined and relying on them is not recommended.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | The curve to approximate. |
|
boolean | Optional If true, the returned surface will be a cubic spline. This does not affect the trim curves. Defaults to false. |
|
boolean | Optional If true, the returned surface will be non-rational. Defaults to false. |
|
number | Optional Specifies the desired approximation tolerance: the maximum distance (in meters) between the original face and the returned spline representation. Default is 1e-6, minimum is 1e-8, and maximum is 1e-4. The tolerance for trim curves is 10x the specified value. |
Return | Type | Description |
---|---|---|
|
map | |
|
BSplineSurface | the underlying 3D surface |
|
array | array of 2D |
|
array | array of arrays of 2D |
evVertexPoint (context is Context, arg is map) returns Vector
Return the coordinates of a point, or the origin of a mate connector.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query |
evVolume (context is Context, arg is map) returns ValueWithUnits
Return the total volume of all the entities. If no matching 3D bodies are found, the total volume will be zero.
Parameter | Type | Additional Info |
---|---|---|
arg |
map | |
|
Query | |
|
VolumeAccuracy |
This module refers to 3D bounding boxes, e.g. the result of a call to evBox3d
.
This is not to be confused with the box standard type used for references.
Box3d type
A three-dimensional bounding box.
Value | Type | Description |
---|---|---|
Box3d |
map | |
|
Vector | A 3D position representing the corner with the smallest x, y, and z coordinates. |
|
Vector | A 3D position representing the corner with the largest x, y, and z coordinates. |
canBeBox3d (value) predicate
Typecheck for Box3d
box3d (minCorner is Vector, maxCorner is Vector) returns Box3d
Construct a bounding box from two opposite corners.
box3d (pointArray is array) returns Box3d
Construct a bounding box containing all points in pointArray
transformBox3d (boxIn is Box3d, transformation is Transform) returns Box3d
Return a box aligned with transformed coordinate system containing the input box
extendBox3d (bBox is Box3d, absoluteValue is ValueWithUnits, factor is number) returns Box3d
Return an enlarged bounding box. The box is scaled by 1 + factor
around its midpoint, and then each face is moved outward by absoluteValue
(inward if absoluteValue
is negative).
Parameter | Type | Additional Info |
---|---|---|
absoluteValue |
ValueWithUnits | The absolute distance to move each face of the box. The corners move |
factor |
number | The relative amount to expand the box, with |
box3dCenter (bBox is Box3d) returns Vector
Return the center of the bounding box.
box3dDiagonalLength (bBox is Box3d) returns ValueWithUnits
Return the length of the diagonal from the minCorner
to the maxCorner
of the bounding box.
insideBox3d (point is Vector, bBox is Box3d) predicate
Whether the specified point is within the bounding box.
WORLD_ORIGIN const
Position of the world origin, equivalent to vector(0, 0, 0) * meter
X_DIRECTION const
Direction parallel to the X axis, equivalent to vector(1, 0, 0)
Y_DIRECTION const
Direction parallel to the Y axis, equivalent to vector(0, 1, 0)
Z_DIRECTION const
Direction parallel to the Z axis, equivalent to vector(0, 0, 1)
WORLD_COORD_SYSTEM const
The world coordinate system, equivalent to coordSystem(vector(0, 0, 0) * meter, vector(1, 0, 0), vector(0, 0, 1))
CoordSystem type
A right-handed Cartesian coordinate system. Used for converting points and geometry between different reference frames, or for creating planes and mate connectors.
The y-axis of a coordinate system is not stored, but it can be obtained by calling the yAxis function, which simply performs a cross product.
See also
Value | Type | Description |
---|---|---|
CoordSystem |
map | |
|
Vector | A 3D point, in world space, representing the origin of the coordinate system. |
|
Vector | A 3D unit vector, in world space, representing the x-axis of the coordinate system. |
|
Vector | A 3D unit vector, in world space, representing the z-axis of the coordinate system. Must be perpendicular to the |
coordSystem (origin is Vector, xAxis is Vector, zAxis is Vector) returns CoordSystem
Creates a Cartesian coordinate system.
See also
Parameter | Type | Additional Info |
---|---|---|
origin |
Vector | A 3D point in world space. |
xAxis |
Vector | A 3D vector in world space. Need not be normalized. |
zAxis |
Vector | A 3D vector in world space. Need not be normalized but must be orthogonal to xAxis. |
tolerantEquals (cSys1 is CoordSystem, cSys2 is CoordSystem) predicate
Check that two CoordSystem
s are the same up to tolerance.
toWorld (cSys is CoordSystem, pointInCSys is Vector) returns Vector
Convert a specified point from a specified coordinate system into world space.
EXAMPLE
toWorld(cSys, vector(0, 0, 0))
equalscSys.origin
Parameter | Type | Additional Info |
---|---|---|
pointInCSys |
Vector | A 3D vector, measured with respect to the |
Return type | Description |
---|---|
Vector | A 3D vector in world space. |
toWorld (cSys is CoordSystem) returns Transform
Returns a Transform
which will transform coordinates measured in cSys
into world coordinates.
EXAMPLE
toWorld(cSys) * vector(0, 0, 0)
equalscSys.origin
When used in operations which place or move parts (like opTransform
, opPattern
, or addInstance
), this transform will (somewhat counterintuitively) move parts from the world origin and orientation to the cSys
origin and orientation.
fromWorld (cSys is CoordSystem, worldPoint is Vector) returns Vector
Convert a specified point from world space into a specified coordinate system.
EXAMPLE
fromWorld(cSys, cSys.origin)
equalsvector(0, 0, 0)
Parameter | Type | Additional Info |
---|---|---|
worldPoint |
Vector | A 3D vector, measured in world space. |
Return type | Description |
---|---|
Vector | A 3D vector measured in |
fromWorld (cSys is CoordSystem) returns Transform
Returns a Transform
which will transform coordinates measured in world space into cSys
coordinates.
EXAMPLE
fromWorld(cSys) * cSys.origin
equalsvector(0, 0, 0)
When used in operations which place or move parts (like opTransform
, opPattern
, or addInstance
), this transform will (somewhat counterintuitively) move parts from the cSys
origin and orientation to the world origin and orientation.
scaleNonuniformly (xScale is number, yScale is number, zScale is number, cSys is CoordSystem) returns Transform
Returns a Transform
that represents 3 independent scalings along the X, Y, and Z axes of a particular cSys
, centered around cSys.origin
.
yAxis (cSys is CoordSystem) returns Vector
Returns the y-axis of a coordinate system
Return type | Description |
---|---|
Vector | A 3D vector in world space. |
toString (cSys is CoordSystem) returns string
Returns a representation of the coordinate system as a string.
X_AXIS const
The global X axis, equivalent to line(vector(0, 0, 0) * meter, vector(1, 0, 0))
Y_AXIS const
The global Y axis, equivalent to line(vector(0, 0, 0) * meter, vector(0, 1, 0))
Z_AXIS const
The global Z axis, equivalent to line(vector(0, 0, 0) * meter, vector(0, 0, 1))
Line type
Represents a parameterized line in 3D space.
Value | Type | Description |
---|---|---|
Line |
map | |
|
Vector | A point on the line, as a 3D Vector with length units. |
|
Vector | A unitless normalized 3D Vector. |
canBeLine (value) predicate
Typecheck for Line
line (origin is Vector, direction is Vector) returns Line
Creates a line from a point and a direction.
Parameter | Type | Additional Info |
---|---|---|
direction |
Vector | The direction gets normalized by this function. |
tolerantEquals (line1 is Line, line2 is Line) predicate
Check that two Line
s are the same up to tolerance, including checking that they have the same origin.
To check if two Line
s are equivalent (rather than equal), use collinearLines
.
collinearLines (line1 is Line, line2 is Line) returns boolean
Returns true
if the two lines are collinear.
transform (from is Line, to is Line) returns Transform
Returns the transformation that transforms the line from
to the line to
(including the origin) using the minimum rotation angle.
project (line is Line, point is Vector) returns Vector
Returns the projection of the point onto the line. See also other overloads of project
.
rotationAround (line is Line, angle is ValueWithUnits) returns Transform
Returns a Transform
that represents the rotation around the given line by the given angle. The rotation is counterclockwise looking against the line direction.
LineLineIntersection type
Represents an intersection between two lines. Depending on the lines, this intersection may be a point, a line, or nothing.
Value | Type | Description |
---|---|---|
LineLineIntersection |
map | |
|
number | Integer representing the dimension of the intersection. EXAMPLE
EXAMPLE
EXAMPLE
|
|
|
canBeLineLineIntersection (value) predicate
Typecheck for LineLineIntersection
intersection (line1 is Line, line2 is Line) returns LineLineIntersection
Returns a LineLineIntersection
representing the intersection between two lines. If the lines are collinear, line1
will be stored in the intersection
field of that LineLineIntersection
.
isPointOnLine (point is Vector, line is Line) returns boolean
Returns true if the point lies on the line.
toString (value is Line) returns string
Circle type
Represents a circle in 3D space.
Value | Type | Description |
---|---|---|
Circle |
map | |
|
CoordSystem | The circle lies in the xy plane of this coordinate system and the origin of its parameterization is the x axis. |
|
ValueWithUnits | The radius of the circle. |
canBeCircle (value) predicate
Typecheck for Circle
circle (cSys is CoordSystem, radius is ValueWithUnits) returns Circle
Returns a new Circle
in the given coordinate system cSys
.
circle (center is Vector, xDirection is Vector, normal is Vector, radius is ValueWithUnits) returns Circle
Returns a new Circle
with the given parameters. xDirection
and normal
must be perpendicular.
tolerantEquals (circle1 is Circle, circle2 is Circle) predicate
Check that two Circle
s are the same up to tolerance, including the coordinate system.
toString (value is Circle) returns string
Ellipse type
Represents an ellipse in 3D space.
Value | Type | Description |
---|---|---|
Ellipse |
map | |
|
CoordSystem | The ellipse lies in the xy plane of this coordinate system and the x axis corresponds to the major radius. |
|
ValueWithUnits | The larger of the two radii. |
|
ValueWithUnits | The smaller of the two radii. |
canBeEllipse (value) predicate
Typecheck for Ellipse
ellipse (cSys is CoordSystem, majorRadius is ValueWithUnits, minorRadius is ValueWithUnits) returns Ellipse
Returns a new Ellipse
with the given parameters.
ellipse (center is Vector, xDirection is Vector, normal is Vector, majorRadius is ValueWithUnits, minorRadius is ValueWithUnits) returns Ellipse
Returns a new Ellipse
with the given parameters. xDirection
and normal
must be perpendicular.
tolerantEquals (ellipse1 is Ellipse, ellipse2 is Ellipse) predicate
Check that two Ellipse
s are the same up to tolerance, including the coordinate system.
toString (value is Ellipse) returns string
KnotArray type
An array of non-decreasing numbers representing the knots of a spline
canBeKnotArray (value) predicate
Typecheck for KnotArray
knotArray (value is array) returns KnotArray
Cast an array on non-decreasing numbers to a KnotArray
knotArrayIsCorrectSize (knots is KnotArray, degree is number, nControlPoints is number) predicate
Assure that size(knotArray)
is 1 + degree + nControlPoints
BSplineCurve type
The definition of a spline in 3D or 2D world space, or unitless 2D parameter space.
See also
Value | Type | Description |
---|---|---|
BSplineCurve |
map | |
|
number | The degree of the spline. |
|
number | The dimension of the spline. Must be 2 or 3. |
|
boolean | Whether the spline is rational. |
|
boolean | Whether the spline is periodic. |
|
array | An array of control points of the required dimension. Size should be at least degree + 1. 2D spline control points can have world space units, or be unitless if they are intended to represent locations in parameter space (e.g. as a boundary input to |
|
array | Required if An array of unitless values with the same size as the control points array. |
|
KnotArray | An array of non-decreasing knots of size equal to |
canBeBSplineCurve (value) predicate
Typecheck for BSplineCurve
bSplineCurve (definition is map) returns BSplineCurve
Returns a new BSplineCurve
, adding knot padding and control point overlap as necessary.
EXAMPLE
opCreateBSplineCurve(context, id + "bSplineCurve1", { "bSplineCurve" : bSplineCurve({ "degree" : 2, "isPeriodic" : false, "controlPoints" : [ vector(0, 0, 0) * inch, vector(1, 0, 0) * inch, vector(1, 1, 0) * inch, vector(0, 1, 0) * inch], "knots" : knotArray([0, .2, 1]) // Will be padded to [0, 0, 0, .2, 1, 1, 1] }) });Creates a spline starting at the origin, moving first quickly along the x-axis (toward the second point), and finishing on the y-axis.
EXAMPLE
opCreateBSplineCurve(context, id + "bSplineCurve1", { "bSplineCurve" : bSplineCurve({ "degree" : 3, "isPeriodic" : true, "controlPoints" : [ vector(0, 0, 0) * inch, vector(1, 0, 0) * inch, vector(1, 1, 0) * inch, vector(0, 1, 0) * inch], // Will be overlapped by repeating the first 3 points "knots" : knotArray([0, .25, .5, .75, 1]) // Same as default when no knots provided. Will be padded to [-.75, -.5, -.25, 0, .25, .5, .75, 1, 1.25, 1.5, 1.75] }) });Creates a closed, curvature-continuous, symmetric curve between the four given points.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
number | The degree of the spline. |
|
boolean | Whether the spline is periodic. |
|
array | An array of control points. See EXAMPLE
|
|
array | Optional An array of weights. See |
|
KnotArray | Optional An array of knots. See |
bSplineCurve (degree is number, isPeriodic is boolean, controlPoints is array, knots is KnotArray) returns BSplineCurve
Deprecated: Use bSplineCurve(map)
bSplineCurve (degree is number, isPeriodic is boolean, controlPoints is array, weights is array, knots is KnotArray) returns BSplineCurve
Deprecated: Use bSplineCurve(map)
A module containing many elementary math functions.
Some math functions (such as sin
and cos
) accept a ValueWithUnits
, rather than a number, and are defined in the units module. There is no pow
function: exponentiation is done using the ^
operator.
When writing a FeatureScript module which uses only basic math functionality, importing mathUtils
(which imports this module along with matrix
, transform
, and vector
) is recommended.
PI const
The mathematical constant pi, to floating-point precision.
EXAMPLE
myAngle = (PI / 4) * radian
In most cases, conversions using PI
can be avoided if using ValueWithUnits
appropriately. Thus, you should never find yourself writing a statement like sin(myAngle * PI / 180)
, since myAngle
should already have correct units attached.
tolerantEquals (value1 is number, value2 is number) predicate
Returns true
if numbers are equal up to a computational tolerance. The tolerance used is a specific number defined by TOLERANCE.computational
(set to 1e-13
) that is meant to adequately handle tolerances introduced by numerical operations. However, this tolerance may be too restrictive or generous for different situations, in which case tolerantEquals(number, number, number)
should be used with the appropriate tolerance specified.
EXAMPLE
tolerantEquals(1, 1)
returnstrue
EXAMPLE
tolerantEquals(1, 1 + 1e-14)
returnstrue
EXAMPLE
tolerantEquals(1, 1 / 900 * 9e100 / 1e98)
returnstrue
EXAMPLE
tolerantEquals(1, 1 / 9 / 9 / 9 / 9 * 9 * 9 * 9 * 9)
returnstrue
See also
tolerantEquals (value1 is number, value2 is number, tolerance is number) predicate
Returns true
if numbers are equal up to a specified tolerance.
EXAMPLE
tolerantEquals(1, 1, 0)
returnstrue
EXAMPLE
tolerantEquals(1, 1.01, 0.03)
returnstrue
EXAMPLE
tolerantEquals(1, 0.99, 0.03)
returnstrue
EXAMPLE
tolerantEquals(1, 1.01, 0.01)
returnstrue
EXAMPLE
tolerantEquals(1, 1.03, 0.01)
returnsfalse
See also
abs (value)
Absolute value.
EXAMPLE
abs(-1)
returns1
EXAMPLE
abs(-1.5 * inch)
equals1.5 * inch
Square root of a number
.
EXAMPLE
sqrt(4)
returns2
EXAMPLE
sqrt(-4)
throws an error
Natural logarithm of a number
.
EXAMPLE
log(exp(3))
returns3
EXAMPLE
log(0)
returns-inf
EXAMPLE
log(-1)
throws an error
Base 10 logarithm of a number
.
EXAMPLE
log10(1000)
returns3
EXAMPLE
log10(0)
returns-inf
EXAMPLE
log10(-1)
throws an error
Hyperbolic sine.
Hyperbolic cosine.
Hyperbolic tangent.
Inverse hyperbolic sine.
Inverse hyperbolic cosine.
Inverse hyperbolic tangent.
e
to the power of value
.
EXAMPLE
exp(1)
returns2.71828...
EXAMPLE
exp(log(3))
returns3
2
to the power of value
.
EXAMPLE
exp2(10)
returns1024
hypot (a is number, b is number)
Hypotenuse function, as sqrt(a^2 + b^2)
, but without any surprising results due to finite numeric precision.
EXAMPLE
hypot(3, 4)
returns5
Round a number
down to the nearest integer.
For values with units, first divide by a value with the same units.
EXAMPLE
floor(1.9)
returns1
EXAMPLE
floor(2.0)
returns2
EXAMPLE
floor(-3.3)
returns-4
EXAMPLE
var numberOfBricks is number = floor(wallLength / brickLength);
Round a number
up to the nearest integer.
For values with units, first divide by a value with the same units.
EXAMPLE
ceil(1.1)
returns2
EXAMPLE
ceil(1.0)
returns1
EXAMPLE
ceil(-3.3)
returns-3
EXAMPLE
var numberOfBricks is number = ceil(wallLength / brickLength)
Round a number
to the nearest integer.
EXAMPLE
round(1.4)
returns1
EXAMPLE
round(1.5)
returns2
EXAMPLE
round(-1.5)
returns-1
roundToPrecision (value is number, precision is number)
Round a number
to a given number of decimal places.
EXAMPLE
roundToPrecision(0.12345, 3)
returns0.123
EXAMPLE
roundToPrecision(9.9995, 3)
returns10
EXAMPLE
roundToPrecision(123.45, -1)
returns120
For positive values of precision, this method is more accurate than round(value, multiple). For instance, print(roundToPrecision(0.45682, 4))
prints 0.4568
, but round(0.45682, 0.0001)
prints 0.45680000000000004
. This is because the floating point representation of 0.0001
is slightly imprecise, and that imprecision is compounded inside the call to round
. The floating point value of 4
, on the other hand, is precise, so the result of roundToPrecision
will be the closest possible floating-point representation of 0.4568
. Thus, print
and other functions using string conversion (~
) will not print extraneous digits.
min (value1, value2)
Return the lesser of two values, which must be comparable with <
.
EXAMPLE
min(0, 1)
returns0
EXAMPLE
min(1 * meter, 1 * inch)
equals1 * inch
max (value1, value2)
Return the greater of two values, which must be comparable with <
.
EXAMPLE
max(0, 1)
returns1
EXAMPLE
max(1 * meter, 1 * inch)
equals1 * meter
Return the least of an array of values, as determined by operator <
, or undefined if the array is empty.
EXAMPLE
min([1, 2, 3])
returns1
EXAMPLE
min([1 * inch, 2 * inch, 3 * inch])
equals1 * inch
Return the greatest of an array of values, as determined by operator <
, or undefined if the array is empty.
EXAMPLE
max([1, 2, 3])
returns3
EXAMPLE
max([1 * inch, 2 * inch, 3 * inch])
equals3 * inch
Return the index of the smallest element of an array, as determined by operator <
, or undefined if the array is empty.
EXAMPLE
argMin([1 * inch, 2 * inch, 3 * inch])
returns0
Return the index of the largest element of an array, as determined by the >
operator, or undefined if the array is empty.
EXAMPLE
argMax([1 * inch, 2 * inch, 3 * inch])
returns2
range (from is number, to is number)
Return an array of numbers in a range. Only integers are allowed.
EXAMPLE
range(0, 3)
returns[0, 1, 2, 3]
range (from, to, count)
Return an array of numbers, (of type number
or ValueWithUnits
), in a range. Note: before FeatureScript 372 this function received as input the step size instead of the number of steps
EXAMPLE
range(0, 10, 6)
returns[0, 2, 4, 6, 8, 10]
EXAMPLE
range(0, 4.5, 4)
returns[0, 1.5, 3, 4.5]
EXAMPLE
range(1 * inch, 1.4 * inch, 3)
returns[1 * inch, 1.2 * inch, 1.4 * inch]
clamp (value, lowerBound, higherBound)
Force a value into a range,
EXAMPLE
clamp(-1, 0, 20)
returns0
,
EXAMPLE
clamp(10, 0, 20)
returns10
EXAMPLE
clamp(30, 0, 20)
returns20
EXAMPLE
clamp(30 * inch, 0 * inch, 20 * inch)
equals20 * inch
isInteger (value) predicate
True if value
is a finite integer.
Note that all numbers in FeatureScript represented as floating point numbers, so an expression like isInteger(hugeInteger + 0.1)
may still return true
.
Used in feature preconditions to define an integer input.
isNonNegativeInteger (value) predicate
True if value
is a finite integer greater than or equal to zero.
isPositiveInteger (value) predicate
True if value
is a finite integer greater than zero.
This module imports the math
, matrix
, transform
, and vector
modules. It is designed to be imported instead of the geometry
module in Feature Studios where only math (not higher-level modeling functionality) is needed.
Matrix type
A Matrix
is an array of rows, all the same size, each of which is an array of numbers
canBeMatrix (val) predicate
Typecheck for Matrix
matrixSize (matrix is Matrix) returns array
Return a 2 element array containing the numbers of rows and columns of a matrix.
isSquare (matrix is Matrix) predicate
Check whether a matrix is square.
matrix (value is array) returns Matrix
Cast a two-dimensional array to a matrix.
identityMatrix (size is number) returns Matrix
Construct an identity matrix of a given dimension.
zeroMatrix (rows is number, cols is number) returns Matrix
Construct an all-zero matrix of a given dimension.
diagonalMatrix (diagonalValues is array) returns Matrix
Given an array of diagonalValues
of size n
, construct an n
xn
matrix which has those values along its main diagonal (starting in the top-left), and 0
everywhere else.
cwiseProduct (m1 is Matrix, m2 is Matrix) returns Matrix
Construct a matrix by multiplying corresponding elements of two matrices (which must be the same size).
transpose (m is Matrix) returns Matrix
Return the transpose of a matrix.
inverse (m is Matrix) returns Matrix
Compute the inverse of a matrix. Throws an exception if the matrix is not square. If the matrix is singular the resulting matrix will contain infinities.
squaredNorm (m is Matrix) returns number
Return the sum of the squares of matrix elements.
norm (m is Matrix) returns number
Return the square root of the sum of the squares of matrix elements.
Compute the singular value decomposition of a matrix, i.e. s
, u
, and v
, where m == u * s * transpose(v)
and s is a diagonal matrix of singular values.
Parameter | Type | Additional Info |
---|---|---|
m |
Matrix | an n-by-p matrix. |
Return | Type | Description |
---|---|---|
|
map | |
|
Matrix | An n-by-n unitary matrix |
|
Matrix | An n-by-p diagonal matrix |
|
Matrix | A p-by-p unitary matrix |
determinant (m is Matrix) returns number
Return the determinant of the matrix.
MatrixWithUnits type
A MatrixWithUnits
is analogous to ValueWithUnits
, but wrapping a matrix.
canBeMatrixWithUnits (value) predicate
Typecheck for MatrixWithUnits
get (matrix is MatrixWithUnits, i is number, j is number) returns ValueWithUnits
Gets an element of a MatrixWithUnits, returning a ValueWithUnits.
matrixSize (matrix is MatrixWithUnits) returns array
Return a 2-element array containing the numbers of rows and columns of a matrix.
toString (value is MatrixWithUnits) returns string
removeKnots (points is array, knots is array, curveDegree is number) returns map
Remove as many knots as possible from a NURBS defined by points, knots and curveDegree.
separatePointsAndWeights (points is array) returns map
Separates a 4d array containing weighted points into a 3d unweighted points array and a 1d weights array.
combinePointsAndWeights (points is array, weights is array) returns array
Combines a 3d unweighted points array and a 1d weights array into a 4d weighted points array
A coordinate system that can persist as part of an attribute associated with an entity. This coordinate system will be transformed along with its parent entity as that entity undergoes transformations.
As with other attributes, the coordinate system will be propagated to copied entities, such as instances in a pattern. These copied persistent coordinate systems will take on the transforms of their new parents.
When getAttribute
is used to retrieve a previously-set persistent coordinate system, the value of coordSystem will be in its transformed state for the current point in the feature execution. If a transform is applied such that the coordinate system is know longer right-handed, then the coordSystem value will be undefined. For instance, this would happen in the case of a mirrored coordinate system.
Value | Type | Description |
---|---|---|
PersistentCoordSystem |
map | |
|
CoordSystem | The coordinate system to persist |
|
string | An id to associate with the coordinate system. This id must be unique within the context of the parent entity. |
persistentCoordSystem (coordSystem is CoordSystem, coordSystemId is string) returns PersistentCoordSystem
Creates a persistent coordinate system.
See also
Parameter | Type | Additional Info |
---|---|---|
coordSystem |
CoordSystem | The coordinate system |
coordSystemId |
string | An id with which to associate the coordinate system. This id must be unique within the context of the parent entity that an becomes associated with this persistent coordinate system through |
ApproximationTarget type
A set of points and optionally derivatives to approximate by a spline.
See also
approximateSpline(Context, map)
Value | Type | Description |
---|---|---|
ApproximationTarget |
map | |
|
array | An ordered array of points for the spline to pass closely to. |
|
Vector | Required if The desired start derivative of the spline. |
|
Vector | Optional The desired start second derivative of the spline. |
|
Vector | Required if The desired end derivative of the spline. |
|
Vector | Optional The desired end second derivative of the spline. |
canBeApproximationTarget (value) predicate
Typecheck for ApproximationTarget
approximationTarget (value is map) returns ApproximationTarget
Construct an ApproximationTarget
approximateSpline (context is Context, definition is map) returns array
Compute a family of splines that approximates a family of ApproximationTarget
s to within a given tolerance. The resulting splines are consistently parameterized, so that, for example, lofting between them will match corresponding target positions. Note: If parameters
are not specified, the magnitude of start and end derivatives in targets is ignored as well as the second component parallel with the first derivative.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
number | The desired degree of the curve. The output may have a different degree, if for example there aren't enough points. |
|
ValueWithUnits | How far the output is allowed to deviate from the input. Must be at least 1e-8 meters. |
|
boolean | Whether the output spline is periodic. |
|
array | An array of |
|
array | Optional An array of numbers representing the parameters corresponding to the target points. Must be strictly increasing. If specified, the output spline at those parameters will match the target points. If specified, derivatives in approximation targets will not be rescaled. |
|
number | Optional The maximum number of control points that will be returned by this function's output. Tolerance will not be satisfied if this limit is reached. Default is 10000. |
|
array | Optional An array of indices into target positions that specifies which ones are to be interpolated exactly. This is currently supported only for non-periodic splines. |
|
boolean | Optional Don't report an info if the result is fully interpolated. Default is false. |
Return type | Description |
---|---|
array | An array of |
evaluateSpline (definition is map) returns array
Evaluate a 3D spline at several parameters, possibly with derivatives.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
BSplineCurve | The 3D spline to evaluate. |
|
array | An array of numbers in the range of the spline's knot vector. |
|
number | Optional The number of derivatives to compute, in addition to the positions. Default is 0. |
Return type | Description |
---|---|
array | An array of arrays of points. If |
elevateBezierDegree (pointsIn is array, newDegree is number) returns array
Elevate the degree of a bezier curve defined by an array of control points
Parameter | Type | Additional Info |
---|---|---|
pointsIn |
array | The control points of the curve to be elevated. Must be non-empty. |
newDegree |
number | The desired degree. If it is less than the number of control points, the control points will be returned unchanged. |
Return type | Description |
---|---|
array | The control points of the degree-elevated curve |
This module contains methods for creating and working with primitive surfaces: planes, cylinders, cones, spheres, and tori.
XY_PLANE const
The world XY plane, equivalent to plane(vector(0, 0, 0) * meter, vector(0, 0, 1), vector(1, 0, 0))
YZ_PLANE const
The world YZ plane, equivalent to plane(vector(0, 0, 0) * meter, vector(1, 0, 0), vector(0, 1, 0))
XZ_PLANE const
The world XZ plane, equivalent to plane(vector(0, 0, 0) * meter, vector(0, 1, 0), vector(0, 0, 1))
Plane type
A Plane
is a data type representing an origin, a normal vector, and an X direction, perpendicular to the normal direction.
Value | Type | Description |
---|---|---|
Plane |
map | |
|
Vector | A 3D point, in world space. |
|
Vector | A 3D unit vector in world space. |
|
Vector | A 3D unit vector in world space. Must be perpendicular to |
canBePlane (value) predicate
Typecheck for Plane
plane (cSys is CoordSystem) returns Plane
Create a Plane
on the XY plane of a specified coordinate system.
plane (origin is Vector, normal is Vector, x is Vector) returns Plane
Create a Plane
which fully specifies its orientation.
Parameter | Type | Additional Info |
---|---|---|
origin |
Vector | A 3D point in world space. |
normal |
Vector | A 3D vector in world space. Need not be normalized. |
x |
Vector | A 3D vector in world space. Need not be normalized. |
plane (origin is Vector, normal is Vector) returns Plane
Create a Plane
from a point and a normal.
The x-axis of this Plane
's coordinate system will be an arbitrary vector perpendicular to the normal
.
Parameter | Type | Additional Info |
---|---|---|
origin |
Vector | A 3D point in world space. |
normal |
Vector | A 3D vector in world space. Need not be normalized. |
alignCanonically (context is Context, plane is Plane) returns Plane
Returns the plane that would represent the coordinate system of a face coplanar with the input plane. Used in plane transformation for computing sketch patterns.
yAxis (plane is Plane) returns Vector
Returns the y-axis of the specified plane as a 3D Vector in world space.
tolerantEquals (plane1 is Plane, plane2 is Plane) predicate
Check that two Plane
s are the same up to tolerance, including checking that they have the same the origin and local coordinate system.
To check if two Plane
s are equivalent (rather than equal), use coplanarPlanes
.
coplanarPlanes (plane1 is Plane, plane2 is Plane) returns boolean
Returns true
if the two planes are coplanar.
planeToCSys (plane is Plane) returns CoordSystem
Create a coordinate system whose XY-plane is a specified plane, with its origin at the plane's origin.
coordSystem (plane is Plane) returns CoordSystem
Create a coordinate system whose XY-plane is a specified plane, with its origin at the plane's origin.
Alias for planeToCSys
.
toString (value is Plane) returns string
project (plane is Plane, point is Vector) returns Vector
Projects a 3D point
onto a Plane
, returning a 3D point on the plane.
project (plane is Plane, line is Line) returns Line
Projects a Line
onto a Plane
, returning a Line
whose origin is on the Plane
and whose direction is a normalized Vector
on the Plane
Throws an error if the Line
is in the same direction as the normal of the Plane
planeToWorld (plane is Plane, planePoint is Vector) returns Vector
Transforms a 2D point
in a Plane
's coordinates to its corresponding 3D point in world coordinates.
planeToWorld3D (plane is Plane) returns Transform
Returns a Transform
which takes 3D points measured with respect to a Plane
(such that points which lie on the plane will have a z-coordinate of approximately 0
) and transforms them into world coordinates.
worldToPlane3D (plane is Plane, worldPoint is Vector) returns Vector
Transforms a 3D point
in world coordinates into a 3D point measured in a Plane
's coordinates. If the point
lies on the Plane
, the result will have a z-coordinate of approximately 0
.
worldToPlane (plane is Plane, worldPoint is Vector) returns Vector
Transforms a 3D worldPoint
in world coordinates into a 2D point measured in a Plane
's (x,y) coordinates.
This is modified as of FeatureScript version 363.0. Older versions of FeatureScript use worldToPlane
to return 3D vectors composed of the plane coordinate system baseis. This functionality is still available in the worldToPlane
function above.
worldToPlane3D (plane is Plane) returns Transform
Returns a Transform
which takes 3D points measured in world coordinates and transforms them into 3D points measured in plane coordinates (such that points which lie on the plane will have a z-coordinate of approximately 0
).
transform (from is Plane, to is Plane) returns Transform
Returns a Transform
which maps the plane from
to the plane to
.
mirrorAcross (plane is Plane) returns Transform
Returns a Transform
which takes points on one side of a plane and transforms them to the other side. The resulting transform is non-rigid, and using this transform in an opTransform
or similar operations will invert the transformed bodies.
intersection (plane1 is Plane, plane2 is Plane)
Returns a Line
at the intersection between the two Plane
s. If the planes are parallel or coincident, returns undefined
.
Represents an intersection between a line and a plane. Depending on the line and plane, this intersection may be a point, a line, or nothing.
Value | Type | Description |
---|---|---|
LinePlaneIntersection |
map | |
|
number | Integer representing the dimension of the intersection. EXAMPLE
EXAMPLE
EXAMPLE
|
|
|
canBeLinePlaneIntersection (value) predicate
Typecheck for LinePlaneIntersection
intersection (plane is Plane, line is Line) returns LinePlaneIntersection
Returns a LinePlaneIntersection
representing the intersection between line
and plane
.
isPointOnPlane (point is Vector, plane is Plane) returns boolean
Returns true if the point lies on the plane.
flip (plane is Plane) returns Plane
Returns a Plane
with the reversed normal vector.
Cone type
Type representing a cone which extends infinitely down the positive z-axis of its coordSystem
.
Value | Type | Description |
---|---|---|
Cone |
map | |
|
CoordSystem | The position and orientation of the cone. |
|
ValueWithUnits | The angle from z-axis of |
canBeCone (value) predicate
Typecheck for Cone
cone (cSys is CoordSystem, halfAngle is ValueWithUnits) returns Cone
Constructs a Cone
from a coordinate system and a half angle.
tolerantEquals (cone1 is Cone, cone2 is Cone) predicate
Check that two Cone
s are the same up to tolerance, including the local coordinate system.
toString (value is Cone) returns string
Cylinder type
Type representing a Cylinder which extends infinitely along the z-axis of its coordSystem
.
Value | Type | Description |
---|---|---|
Cylinder |
map | |
|
CoordSystem | The position and orientation of the cylinder. |
|
ValueWithUnits | The cylinder's radius. |
canBeCylinder (value) predicate
Typecheck for Cylinder
cylinder (cSys is CoordSystem, radius is ValueWithUnits) returns Cylinder
Constructs a cylinder from a coordinate system and a radius.
tolerantEquals (cylinder1 is Cylinder, cylinder2 is Cylinder) predicate
Check that two Cylinder
s are the same up to tolerance, including the local coordinate system.
toString (value is Cylinder) returns string
Torus type
Type representing a torus, the shape of a circle revolved around a coplanar axis.
The torus represented is revolved about the z-axis of the coordSystem
and centered in its xy-plane.
Value | Type | Description |
---|---|---|
Torus |
map | |
|
CoordSystem | The position and orientation of the torus. |
|
ValueWithUnits | The major radius, i.e. the distance from the center of the torus to the center of the revolved circle. |
|
ValueWithUnits | The minor radius, i.e. the radius of the revolved circle. |
canBeTorus (value) predicate
Typecheck for Torus
torus (cSys is CoordSystem, minorRadius is ValueWithUnits, radius is ValueWithUnits) returns Torus
Constructs a torus from a coordinate system, the minor radius, and the major radius.
tolerantEquals (torus1 is Torus, torus2 is Torus) predicate
Check that two tori are the same up to tolerance, including the local coordinate system.
toString (value is Torus) returns string
Sphere type
Type representing a sphere of a given radius centered around a 3D point.
Value | Type | Description |
---|---|---|
Sphere |
map | |
|
CoordSystem | The position and orientation of the sphere. |
|
ValueWithUnits | The sphere's radius. |
canBeSphere (value) predicate
Typecheck for Sphere
sphere (cSys is CoordSystem, radius is ValueWithUnits) returns Sphere
tolerantEquals (sphere1 is Sphere, sphere2 is Sphere) predicate
Check that two Sphere
s are the same up to tolerance, including the local coordinate system.
toString (value is Sphere) returns string
ControlPointMatrix type
A two-dimensional array of 3D position vectors. Reading across a row represents a change in v, and reading down a column represents a change in u.
canBeControlPointMatrix (value) predicate
Typecheck for ControlPointMatrix
controlPointMatrix (value is array) returns ControlPointMatrix
Cast a two-dimensional array of 3D position vectors to a ControlPointMatrix
.
BSplineSurface type
The definition of a spline in 3D space. For all matrices of the spline definition, reading across a row represents a change in v, and reading down a column represents a change in u.
See also
Value | Type | Description |
---|---|---|
BSplineSurface |
map | |
|
number | The degree of the spline in u. |
|
number | The degree of the spline in v. |
|
boolean | Whether the spline is rational. |
|
boolean | Whether the spline periodic in u. |
|
boolean | Whether the spline periodic in v. |
|
ControlPointMatrix | A grid of 3d control points. Must have at least |
|
Matrix | Required if A matrix of unitless values with the same shape as the control points grid. |
|
KnotArray | An array of non-decreasing knots of size equal to 1 + |
|
KnotArray | An array of non-decreasing knots of size equal to 1 + |
canBeBSplineSurface (value) predicate
Typecheck for BSplineSurface
bSplineSurface (definition is map)
Returns a new BSplineSurface
, adding knot padding and control point overlap as necessary.
EXAMPLE
opCreateBSplineSurface(context, id + "bSplineSurface1", { "bSplineSurface" : bSplineSurface({ "uDegree" : 2, "vDegree" : 2, "isUPeriodic" : false, "isVPeriodic" : false, "controlPoints" : controlPointMatrix([ [vector(-2, 2, 0) * inch, vector(-1, 2, 0) * inch, vector(0, 2, 0) * inch, vector(1, 2, 0) * inch, vector(2, 2, 0) * inch], [vector(-2, 1, 0) * inch, vector(-1, 1, 0) * inch, vector(0, 1, 0) * inch, vector(1, 1, 0) * inch, vector(2, 1, 0) * inch], [vector(-2, 0, 0) * inch, vector(-1, 0, 0) * inch, vector(0, 0, 1) * inch, vector(1, 0, 0) * inch, vector(2, 0, 0) * inch], [vector(-2, -2, 0) * inch, vector(-1, -2, 0) * inch, vector(0, -2, 0) * inch, vector(1, -2, 0) * inch, vector(2, -2, 0) * inch] ]), "uKnots" : knotArray([0, .1, 1]), // Will be padded to [0, 0, 0, .1, 1, 1, 1] "vKnots" : knotArray([0, 1/3, 2/3, 1]) // Same as default when no knots provided. Will be padded to [0, 0, 0, 1/3, 2/3, 1, 1, 1] }) });Creates a new spline surface on the XY plane with a protrusion at the origin, falling back to the XY plane more quickly in the +Y direction.
EXAMPLE
opCreateBSplineSurface(context, id + "bSplineSurface1", { "bSplineSurface" : bSplineSurface({ "uDegree" : 2, "vDegree" : 1, "isUPeriodic" : true, "isVPeriodic" : false, "controlPoints" : controlPointMatrix([ [vector(0, 0, 1) * inch, vector(-1, 0, 0) * inch, vector(-2, 0, -1) * inch], [vector(1, 1, 1) * inch, vector( 0, 1, 0) * inch, vector(-1, 1, -1) * inch], [vector(2, 0, 1) * inch, vector( 1, 0, 0) * inch, vector( 0, 0, -1) * inch], [vector(1, -1, 1) * inch, vector( 0, -1, 0) * inch, vector(-1, -1, -1) * inch] // Will be overlapped by repeating the first two rows ]), "uKnots" : knotArray([0, .25, .5, .75, 1]), // Same as default when no knots provided. Will be padded to [-.5, -.25, 0, .25, .5, .75, 1, 1.25, 1.5] "vKnots" : knotArray([0, .5, 1]) // Same as default when no knots provided. Will be padded to [0, 0, .5, 1, 1] }) });Creates a new spline surface which is a tube surrounding the origin, sheared in the X direction.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
number | The degree of the spline in u. |
|
number | The degree of the spline in v. |
|
boolean | Whether the spline periodic in u. |
|
boolean | Whether the spline periodic in v. |
|
ControlPointMatrix | A matrix of control points. See EXAMPLE controlPointMatrix([ [vector(-1, -1, -1) * inch, vector(-1, 0, 0) * inch, vector(-1, -2, 1) * inch], [vector( 0, 1, -1) * inch, vector( 0, 2, 0) * inch, vector( 0, 0, 1) * inch], [vector( 1, -1, -1) * inch, vector( 1, 0, 0) * inch, vector( 1, -2, 1) * inch] ]) |
|
array | Optional A matrix of weights. See |
|
KnotArray | Optional An array of knots. See |
|
KnotArray | Optional See |
MeshFaceParameter type
A MeshFaceParameter
is a 2D array unitless array. It is functionnally indentical to a 2D vector but because there is no guarantee of continuity for mesh parameters, it does not make sense to expose vector math for it.
canBeMeshFaceParameter (value) predicate
Typecheck for MeshFaceParameter
meshFaceParameter (value is array) returns MeshFaceParameter
Make a MeshFaceParameter
from an array.
Transform type
A Transform
typically represents a change of position and orientation in 3D space (other affine transformations, such as scaling and shearing, can also be represented).
rotationAround
, scaleUniformly
, transform(Vector)
, toWorld(CoordSystem)
and fromWorld(CoordSystem)
return useful transforms. Transform
s are commonly used with opTransform
, whose documentation has examples of calling these functions.
Transform
s are also commonly used with their *
operator overloads to easily work with geometry in multiple coordinate systems.
EXAMPLE
transform * (vector(1, 1, 1) * inch)
yields a point which is the given point, transformed by thetransform
.
EXAMPLE
transform2 * transform1
yields a new transform which is equivalent to applyingtransform1
followed bytransform2
.
A Transform
contains a linear portion (rotation, scaling, or shearing), which is applied first, and a translation vector, which is applied second. Generally, these individual fields on this type don't need to be directly used, and everything you need can be accomplished through the operator overloads above, or other functions in this module and the coordSystem
module.
Value | Type | Description |
---|---|---|
Transform |
map | |
|
Matrix | A linear motion, which is generally a rotation, but can also be a scaling, inversion, or shearing. |
|
Vector | A 3D translation vector. |
canBeTransform (value) predicate
Typecheck for Transform
transform (linear is Matrix, translation is Vector) returns Transform
Construct a Transform
using the matrix argument for rotation and scaling and the vector argument for translation.
transform (translation is Vector) returns Transform
Construct a Transform
that translates without rotation or scaling.
transform (value is map) returns Transform
identityTransform () returns Transform
Construct a transform that does nothing (no rotation, scaling, or translation).
tolerantEquals (transform1 is Transform, transform2 is Transform) predicate
Check that two Transform
s are the same up to tolerance.
inverse (t is Transform) returns Transform
Compute the inverse of a Transform
, such that inverse(t) * t == identityTransform()
.
scaleUniformly (scale is number) returns Transform
Returns a Transform
that represents a uniform scaling around the origin.
scaleUniformly (scale is number, pointToScaleAbout is Vector) returns Transform
Returns a Transform
that represents a uniform scaling around pointToScaleAbout
.
scaleNonuniformly (xScale is number, yScale is number, zScale is number) returns Transform
Returns a Transform
that represents 3 independent scalings along the X, Y, and Z axes, centered around the origin.
scaleNonuniformly (xScale is number, yScale is number, zScale is number, pointToScaleAbout is Vector) returns Transform
Returns a Transform
that represents 3 independent scalings along the X, Y, and Z axes, centered around pointToScaleAbout
.
TransformUV type
A TransformUV
represents a change of position and orientation in unitless 2D space.
A TransformUV
contains a linear portion (rotation, scaling, or shearing), which is applied first, and a translation vector, which is applied second.
Value | Type | Description |
---|---|---|
TransformUV |
map | |
|
Matrix | A linear motion, which is generally a rotation, but can also be a scaling, inversion, or shearing. |
|
Vector | A 2D translation vector. |
isUvVector (value) predicate
True for a single 2D unitless Vector
EXAMPLE
vector(0.5, 1)
canBeTransformUV (value) predicate
Typecheck for Transform
transformUV (linear is Matrix, translation is Vector) returns TransformUV
Construct a TransformUV
using the matrix argument for rotation and scaling and the vector argument for translation.
transformUV (translation is Vector) returns TransformUV
Construct a TransformUV
that translates without rotation or scaling.
transformUV (value is map) returns TransformUV
identityTransformUV () returns TransformUV
Construct a transform that does nothing (no rotation, scaling, or translation).
tolerantEquals (transform1 is TransformUV, transform2 is TransformUV) predicate
Check that two TransformUV
s are the same up to tolerance.
inverse (t is TransformUV) returns TransformUV
Compute the inverse of a TransformUV
, such that inverse(t) * t == identityTransform()
.
scaleUniformlyUV (scale is number) returns TransformUV
Returns a TransformUV
that represents a uniform scaling around the origin.
scaleNonuniformly (xScale is number, yScale is number) returns TransformUV
Returns a TransformUV
that represents two independent scalings along the X and Y axes, centered around the origin.
rotate (angle is ValueWithUnits) returns TransformUV
Returns a TransformUV
that represents a rotation around the origin with the given angle.
ValueWithUnits type
A ValueWithUnits
is a number with dimensions, such as 1.5 inches, 90 degrees, or 9.81 meters per second per second.
const width is ValueWithUnits = 1.5 * inch; const angle is ValueWithUnits = 90 * degree; const g is ValueWithUnits = 9.81 * meter / second / second;
Values with the same dimensions can be added and subtracted, even if they were created in different unit systems.
const length = 3 * meter + 1 * inch; const longerLength = length + 0.01 * inch; const nonsense = 3 * meter + 3 * degree; // Throws an error from dimension mismatch
Multiplication (*
) will multiply both the values and the units. An expression where the units all cancel evaluates to plain number
.
var doubleLength = 2 * length; // ValueWithUnits with length units var area = (20 * foot) * (30 * foot); // ValueWithUnits with area units var numberOfBricks = (64 * foot) / (9 * inch); // number with no units
Values with units can be raised to numerical powers with the ^
operator. Base units like inch
or second
can be exponentiated in the same way.
var squareArea = (3 * meter)^2; var g = 9.81 * meter / second^2;
Functions in the standard library require a ValueWithUnits for arguments where units are needed. Thus, the depth
in opExtrude
requires a value with length units (rather than assuming meters). The argument of sin
is a value with angle units (rather than assuming radians). The argument of sqrt can be any value whose units are even powers.
var ladderHeight = ladderLength * sin(75 * degree); // Has length units var pendulumPeriod = 2 * PI * sqrt(armLength / g); // Has time units
Equality of ValueWithUnits
considers the underlying value, so 25.4 * millimeter
is equal to 1 * inch
. However, PI * radian / 5
does not equal 36 * degree
because of finite precision arithmetic. To check equality of ValueWithUnits
, you should use tolerantEquals.
if (tolerantEquals(myLength, 0 * inch)) { ...
Keeping correct units on variables is always best practice, in order to benefit from easy unit conversions and runtime unit checks. However, when printing, you may wish to divide out the units in order to display a value in a different system of units.
const length = 42 * centimeter; println(length); // prints "0.42 meter" println("length: " ~ toString(length)); // prints "length: 0.42 meter" println(length / inch ~ " inches"); // prints "16.535433070866137 inches" println(roundToPrecision(length / inch, 3) ~ " inches"); // prints "16.535 inches"
unitless const
The constant 1
, with no units.
meter const
A constant equal to 1 meter.
centimeter const
A constant equal to 1 centimeter.
millimeter const
A constant equal to 1 millimeter.
inch const
A constant equal to 1 inch.
foot const
A constant equal to 1 foot.
yard const
A constant equal to 1 yard.
squareMeter const
A constant equal to one square meter.
squareCentimeter const
A constant equal to one square centimeter.
squareMillimeter const
A constant equal to one square millimeter.
squareInch const
A constant equal to one square inch.
squareFoot const
A constant equal to one square foot.
squareYard const
A constant equal to one square yard.
cubicMeter const
A constant equal to one cubic meter.
cubicCentimeter const
A constant equal to one cubic centimeter.
cubicMillimeter const
A constant equal to one cubic millimeter.
cubicInch const
A constant equal to one cubic inch.
cubicFoot const
A constant equal to one cubic foot.
cubicYard const
A constant equal to one cubic yard.
radian const
A constant equal to 1 radian.
Formally, radians are unitless, so in certain situations you may need to multiply or divide by radian
EXAMPLE
var myAngle = PI / 6 * radian
EXAMPLE
var arcLength = radius * arcAngle / radian
degree const
A constant equal to 1 degree.
kilogram const
A constant equal to 1 kilogram.
gram const
A constant equal to 1 gram.
ounce const
A constant equal to 1 ounce.
pound const
A constant equal to 1 pound.
second const
A constant equal to 1 second
newton const
A constant equal to 1 newton.
kilonewton const
A constant equal to 1 kilonewton.
poundForce const
A constant equal to 1 pound-force.
pascal const
A constant equal to 1 pascal.
kilopascal const
A constant equal to 1 kilopascal.
megapascal const
A constant equal to 1 megapascal.
gigapascal const
A constant equal to 1 gigapascal.
poundPerSquareInch const
A constant equal to 1 pound per square inch.
kilopoundPerSquareInch const
A constant equal to 1 ksi.
newtonMeter const
A constant equal to 1 newton-meter.
newtonMillimeter const
A constant equal to 1 newton-millimeter.
inchPound const
A constant equal to 1 inch-pound.
footPound const
A constant equal to 1 foot-pound.
meterPerSecondSquared const
A constant equal to 1 meter per second squared.
millimeterPerSecondSquared const
A constant equal to 1 millimeter per second squared.
inchPerSecondSquared const
A constant equal to 1 inch per second squared.
footPerSecondSquared const
A constant equal to 1 foot per second squared.
radianPerSecond const
A constant equal to 1 radian per second.
degreePerSecond const
A constant equal to 1 degree per second.
joule const
A constant equal to 1 Joule.
footPoundForce const
A constant equal to 1 foot-pound force.
isLength (val) predicate
True for any value with length units.
isArea (val) predicate
True for any value with area units.
isVolume (val) predicate
True for any value with volume units.
isAngle (val) predicate
True for any value with angle units.
isForce (val) predicate
True for any value with force units.
isPressure (val) predicate
True for any value with pressure units.
isMoment (val) predicate
True for any value with moment units.
isAcceleration (val) predicate
True for any value with acceleration units.
isAngularVelocity (val) predicate
True for any value with angular velocity units.
isEnergy (val) predicate
True for any value with energy units.
reciprocal (val is ValueWithUnits) returns ValueWithUnits
Inverts a value, including units.
tolerantEquals (value1 is ValueWithUnits, value2 is ValueWithUnits) predicate
Returns true if angles are equal up to zeroAngle or anything else is equal up to zeroLength
tolerantGreaterThan (greater, lesser) predicate
Returns true
if greater
is greater than and not tolerantly equal to lesser
.
EXAMPLE
(1 * meter)->tolerantGreaterThan(0 * meter)
returnstrue
EXAMPLE
1->tolerantGreaterThan(0)
returnstrue
EXAMPLE
0->tolerantGreaterThan(-1e-14)
returnsfalse
EXAMPLE
0->tolerantGreaterThan(0)
returnsfalse
tolerantGreaterThanOrEqual (greater, lesser) predicate
Returns true
if greater
is greater than or tolerantly equal to lesser
.
EXAMPLE
(1 * meter)->tolerantGreaterThanOrEqual(0 * meter)
returnstrue
EXAMPLE
1->tolerantGreaterThanOrEqual(0)
returnstrue
EXAMPLE
0->tolerantGreaterThanOrEqual(0)
returnstrue
EXAMPLE
0->tolerantGreaterThanOrEqual(1e-14)
returnstrue
tolerantLessThan (lesser, greater) predicate
Returns true
if lesser
is less than and not tolerantly equal to greater
.
EXAMPLE
(0 * meter)->tolerantLessThan(1 * meter)
returnstrue
EXAMPLE
0->tolerantLessThan(1)
returnstrue
EXAMPLE
0->tolerantLessThan(1e-14)
returnsfalse
EXAMPLE
0->tolerantLessThan(0)
returnsfalse
tolerantLessThanOrEqual (lesser, greater) predicate
Returns true
if lesser
is less than or tolerantly equal to greater
.
EXAMPLE
(0 * meter)->tolerantLessThanOrEqual(1 * meter)
returnstrue
EXAMPLE
0->tolerantLessThanOrEqual(1)
returnstrue
EXAMPLE
0->tolerantLessThanOrEqual(0)
returnstrue
EXAMPLE
1e-14->tolerantLessThanOrEqual(0)
returnstrue
tolerantWithinExclusive (value, lesser, greater) predicate
Returns true
if value
is tolerantly within the interval (lesser, greater)
.
EXAMPLE
(0.5 * meter)->tolerantWithinExclusive(0 * meter, 1 * meter)
returnstrue
EXAMPLE
0.5->tolerantWithinExclusive(0, 1)
returnstrue
EXAMPLE
1->tolerantWithinExclusive(0, 1)
returnsfalse
EXAMPLE
0->tolerantWithinExclusive(0, 1)
returnsfalse
EXAMPLE
0->tolerantWithinExclusive(1e-14, 1)
returnsfalse
tolerantWithinInclusive (value, lesser, greater) predicate
Returns true
if value
is tolerantly within the interval [lesser, greater]
.
EXAMPLE
(0.5 * meter)->tolerantWithinInclusive(0 * meter, 1 * meter)
returnstrue
EXAMPLE
0.5->tolerantWithinInclusive(0, 1)
returnstrue
EXAMPLE
1->tolerantWithinInclusive(0, 1)
returnstrue
EXAMPLE
0->tolerantWithinInclusive(0, 1)
returnstrue
EXAMPLE
0->tolerantWithinInclusive(1e-14, 1)
returnstrue
tolerantEqualsZero (value) predicate
Returns true
if value
is tolerantly equal to the 0
value with the same units as value
.
EXAMPLE
tolerantEqualsZero(0)
returnstrue
EXAMPLE
tolerantEqualsZero(0 * meter)
returnstrue
EXAMPLE
tolerantEqualsZero(1e-9 * meter)
returnstrue
EXAMPLE
tolerantEqualsZero(1)
returnsfalse
EXAMPLE
tolerantEqualsZero(1 * meter)
returnsfalse
sqrt (value is ValueWithUnits) returns ValueWithUnits
Square root of a ValueWithUnits
.
EXAMPLE
sqrt(4 * meter^2)
equals2 * meter
.
EXAMPLE
2 * PI * sqrt(armLength / (9.8 * meter/second^2))
equals the period of a pendulum, in seconds.
EXAMPLE
sqrt(4 * meter)
throws an error, since FeatureScript has no concept of the square root of a meter.
hypot (a is ValueWithUnits, b is ValueWithUnits)
Hypotenuse function, as sqrt(a^2 + b^2)
, but without any surprising results due to finite numeric precision.
EXAMPLE
hypot(3 * foot, 4 * foot)
equals5 * foot
sin (value is ValueWithUnits) returns number
Sine, the ratio of the opposite side over the hypotenuse in a right triangle of the specified angle.
EXAMPLE
sin(30 * degree)
returns approximately0.5
EXAMPLE
sin(PI * radian)
returns approximately0
cos (value is ValueWithUnits) returns number
Cosine, the ratio of the adjacent side over the hypotenuse in a right triangle of the specified angle.
EXAMPLE
cos(60 * degree)
returns approximately0.5
EXAMPLE
cos(PI * radian)
returns approximately-1
tan (value is ValueWithUnits) returns number
Tangent, the ratio of the opposite side over the adjacent side in a right triangle of the specified angle.
EXAMPLE
tan(45 * degree)
returns approximately1
EXAMPLE
tan(PI * radian)
returns approximately0
asin (value is number) returns ValueWithUnits
Arcsine, i.e. inverse sine.
Returns a value between -90 * degree
and 90 * degree
.
EXAMPLE
asin(0.5)
equals approximately30 * degree
EXAMPLE
asin(1.5)
throws an error, since there is no value wheresin(value)
is1.5
acos (value is number) returns ValueWithUnits
Arccosine, i.e. inverse cosine.
Returns a value between 0 * degree
and 180 * degree
.
EXAMPLE
acos(0.5)
equals approximately60 * degree
EXAMPLE
acos(1.5)
throws an error, since there is no value wherecos(value)
is1.5
atan (value is number) returns ValueWithUnits
Arctangent, i.e. inverse tangent.
Returns a value between -90 * degree
and 90 * degree
.
EXAMPLE
atan(1)
equals approximately45 * degree
EXAMPLE
atan(inf)
equals approximately90 * degree
atan2 (y is number, x is number) returns ValueWithUnits
Returns the counterclockwise angle from the vector [0, 1]
to the vector [x, y]
. The angle is negative if y is negative. This is equivalent to atan(y/x)
except the result respects the quadrant of the input and is well-behaved near x == 0.
EXAMPLE
atan2(0, 1)
equals approximately0 * degree
EXAMPLE
atan2(1, 0)
equals approximately90 * degree
EXAMPLE
atan2(0, -1)
equals approximately180 * degree
EXAMPLE
atan2(-1, 0)
equals approximately-90 * degree
atan2 (y is ValueWithUnits, x is ValueWithUnits) returns ValueWithUnits
Returns the counterclockwise angle from the vector [0, 1]
to the vector [x, y]
, assuming the units of y
and x
match.
See also
isAngleBetween (queryAngle is ValueWithUnits, minAngle is ValueWithUnits, maxAngle is ValueWithUnits)
Returns true if the provided angle is within the given range (inclusive with tolerance), "winding" the query angle as necessary to put it within a positive full circle turn of the range. Ranges that encompass one or more full circles will return true regardless of the query angle.
Throws if range's maximum angle is less than the minimum angle.
EXAMPLE
isAngleBetween(0.5 * PI * radian, 0 * radian, PI * radian)
returnstrue
EXAMPLE
isAngleBetween(0.5 * PI * radian, 2 * PI * radian, 3 * PI * radian)
returnstrue
EXAMPLE
isAngleBetween(-1.5 * PI * radian, 0 * radian, PI * radian)
returnstrue
floor (value, multiple)
Round a value down to nearest given multiple.
EXAMPLE
floor(125, 10)
returns120
EXAMPLE
floor(-15, 10)
returns-20
EXAMPLE
floor(3.14 * inch, 0.1 * inch)
equals3.1 * inch
ceil (value, multiple)
Round a value up to nearest given multiple.
EXAMPLE
ceil(125, 10)
returns130
EXAMPLE
ceil(-15, 10)
returns-10
EXAMPLE
ceil(3.14 * inch, 0.1 * inch)
equals3.2 * inch
round (value, multiple)
Round a value to nearest given multiple.
EXAMPLE
round(125, 10)
returns130
EXAMPLE
round(-15, 10)
returns-10
EXAMPLE
round((10 / 3) * meter, centimeter)
equals3.33 * meter
EXAMPLE
round(1 * meter, .001 * inch)
equals39.37 * inch
For small values of multiple
, roundToPrecision
is preferred to reduce floating point errors.
toString (value is ValueWithUnits) returns string
General value to string conversion.
parseJsonWithUnits (s is string)
Parse a JSON string into either a map or array. Null values in the JSON are returned as undefined
. Throws if the string is not well-formed JSON. Applicable strings are parsed into a ValueWithUnits. For instance, "3 inch" will map to a ValueWithUnits
with length units that repreresents 3 inches.
Return type | Description |
---|---|
A map or an array corresponding to the JSON value. |
Vector type
A Vector
is a non-empty array. It should contain numbers or lengths.
Operators +
, -
, *
, and /
are overloaded for vectors, and other operations such as dot product are available. If a vector does not contain numbers or lengths, operations that assume number-like properties may fail.
canBeVector (value) predicate
Typecheck for Vector
vector (value is array) returns Vector
Make a Vector from an array.
Construct a 2-dimensional vector.
vector (x, y, z) returns Vector
Construct a 3-dimensional vector.
isLengthVector (value) predicate
True for a Vector
where all members are values with length units.
EXAMPLE
vector([1, 2, 3, 4, 5]) * inch
isUnitlessVector (value) predicate
True for a Vector
where all members are simple number
s.
EXAMPLE
vector([1, 2, 3, 4, 5])
is2dPoint (value) predicate
True for a single 2D length Vector
EXAMPLE
vector(0.5, 1) * inch
is2dPointVector (value) predicate
True for an array
where all members are 2D lengths.
EXAMPLE
[vector(0, 0) * inch, vector(0, 1) * inch, vector(1, 0) * inch]
is2dDirection (value) predicate
True for a unitless 2D Vector
that is normalized (i.e. has length 1
)
EXAMPLE
vector(0, 1)
is3dLengthVector (value) predicate
True for a 3D Vector
where all members are values with length units.
EXAMPLE
vector(0, 1.5, 30) * inch
is3dDirection (value) predicate
True for a unitless 3D Vector
that is normalized (i.e. has length 1
)
EXAMPLE
vector(0, 0, 1)
zeroVector (size is number) returns Vector
Make an array filled with 0.
EXAMPLE
zeroVector(3)
is equivalent tovector(0, 0, 0)
squaredNorm (vector is Vector)
Returns the squared length of a vector. This is slightly faster to calculate than the length.
Returns the length (norm) of a vector.
dot (vector1 is Vector, vector2 is Vector)
Returns the dot product of two vectors.
cross (vector1 is Vector, vector2 is Vector) returns Vector
Returns the cross product of two 3-dimensional vectors.
angleBetween (vector1 is Vector, vector2 is Vector) returns ValueWithUnits
Returns the angle between two 3-dimensional vectors. Values are within the range [0, PI] * radian
.
EXAMPLE
angleBetween(X_DIRECTION, Y_DIRECTION)
equalsPI/2 * radian
EXAMPLE
angleBetween(Y_DIRECTION, X_DIRECTION)
equalsPI/2 * radian
A plane is fitted to the two vectors and the shortest angle between them is measured on that plane.
angleBetween (vector1 is Vector, vector2 is Vector, ref is Vector) returns ValueWithUnits
Returns the counterclockwise angle between two 3-dimensional vectors as witnessed from the tip of a third 3-dimensional vector. Values are within the range (-PI, PI] * radian
with negative values indicating clockwise angles.
EXAMPLE
angleBetween(X_DIRECTION, Y_DIRECTION, Z_DIRECTION)
equalsPI/2 * radian
EXAMPLE
angleBetween(Y_DIRECTION, X_DIRECTION, Z_DIRECTION)
equals-PI/2 * radian
The first two vectors are projected onto a plane perpendicular to the reference vector and the angle is measured according to that projection.
normalize (vector is Vector) returns Vector
Returns the (unitless) result of normalizing vector. Throws if the input is zero-length.
Parameter | Type | Additional Info |
---|---|---|
vector |
Vector | A Vector with any units. |
project (target is Vector, source is Vector) returns Vector
Project the source
vector onto the target
vector. Equivalent to target * dot(source, target) / squaredNorm(target)
.
perpendicularVector (vec is Vector) returns Vector
Returns a vector perpendicular to the given vector. The choice of which perpendicular vector to return is arbitrary but consistent for the same input. The returned vector is unitless and of length 1.
rotationMatrix3d (from is Vector, to is Vector) returns Matrix
Construct a 3D rotation matrix that represents the minimum rotation that takes the normalized from
vector to the normalized to
vector. The inputs may have any units.
rotationMatrix3d (axis is Vector, angle is ValueWithUnits) returns Matrix
Construct a 3D matrix representing a counterclockwise (looking against the axis) rotation around the given axis by the given rotation angle.
scalarTripleProduct (vector1 is Vector, vector2 is Vector, vector3 is Vector)
Returns the scalar triple product, a dot (b cross c), of three 3-dimensional vectors.
toString (value is Vector) returns string
tolerantEquals (point1 is Vector, point2 is Vector) predicate
Returns true if two vectors designate the same point (within tolerance) or the same direction (within tolerance).
parallelVectors (vector1 is Vector, vector2 is Vector) returns boolean
Returns true if two vectors are parallel (within tolerance).
perpendicularVectors (vector1 is Vector, vector2 is Vector) returns boolean
Returns true if two vectors are perpendicular (within tolerance).
clusterPoints (points is array, tolerance is ValueWithUnits) returns array
Groups points into clusters. Two points farther than tolerance apart are guaranteed to be in separate clusters. A set of points all within tolerance of each other that has no other points within tolerance is guaranteed to be a single cluster.
Return type | Description |
---|---|
array | Array of arrays, where each array is a cluster of nearby points, represented as indices into points array. |
Attributes are data attached to individual entities, which can be set and retrieved by name in FeatureScript. The data can be of any type, and multiple attributes with different names can be associated with the same topological entity.
One common use case for attributes is to set attributes on an entity in one feature, and get them in another. For data not associated with entities, the same thing can be accomplished simply via setVariable
and getVariable
, but attributes allow that data to be set on specific bodies, faces, edges, or vertices.
setAttribute(context, { "entities" : somePart, "name" : "refPoint", "attribute" : vector(0, 0, 1) * inch }); // Later, possibly in another feature: const partRefPoint = getAttribute(context, { "entity" : somePart, "name" : "refPoint" }); if (partRefPoint != undefined) { // use partRefPoint... }
Attributes are also a useful way to mark important groups of entities for other features or other deriving Part Studios. You can query for entities with a specific attribute, a specific attribute value, or a value matching a given pattern with the query functions qHasAttribute
, qHasAttributeWithValue
, or qHasAttributeWithValueMatching
, respectively.
Attributes stay with the entity they are defined on, even as the Part Studio changes. An attribute on a face, edge, or body which is split in two will be set with the same name and value on both split pieces. An attribute on a patterned entity will be set on each patterned copy. If two or more entities are merged together (e.g. with a boolean union), then the attributes on both are kept on the result, though if they have attributes with the same name, the value of the primary entity (e.g. the first resolved body in the boolean tools
) will be used.
Legacy unnamed attributes: A previous use of these attribute functions involved setting unnamed attributes by calling setAttribute
without a "name"
. This workflow is still supported, but is no longer recommended. Legacy unnamed attributes can be identified and retrieved only by type, and two attributes of the same type are not allowed on the same entity. The behavior of these unnamed attributes, described in "Legacy unnamed attribute" notes like this one, can be safely ignored if all your attributes are set with a "name"
.
setAttribute (context is Context, definition is map)
Attach an attribute to one or several entities. Will overwrite any attribute previously set on the same entity with the same name.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Entities to attach attribute to. Throws an error if the query resolves to nothing. |
|
string | The name of the attribute |
|
The data to set. Can be any type. If Legacy unnamed attributes: If name is not provided, adds an unnamed attribute to the entities. If more than one unnamed attribute with the same type is set on any entity, throws an error. |
getAttributes (context is Context, definition is map) returns array
Get attributes attached to entities.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Entities to get attributes on. If query resolves to nothing, empty array is returned |
|
string | The name of the attribute to get. |
|
Optional Providing a map here will also filter out attributes which do not have entries precisely matching the keys and values of EXAMPLE
Legacy unnamed attributes: If |
Return type | Description |
---|---|
array | An array of all unique attributes on the given entities matching the pattern. |
getAttribute (context is Context, definition is map)
Get the value of a single named attribute attached to a single entity, or undefined
if no attribute of that name has been set.
EXAMPLE
setAttribute(context, { "entities" : someEntities, "name" : "importantData", "attribute" : 42}); for (const entity in evaluateQuery(entities)) { const value = getAttribute(context, { "entity" : entity, "name" : "importantData" }); println(value); // prints 42 }
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Query resolving to a single entity to get the attribute from. If multiple entities are resolved, the first resolved entity is considered. |
|
string | Name of the attribute |
getAllAttributes (context is Context, definition is map) returns map
Get the named attributes attached to a single entity, or an empty map if the entity has no attributes.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Query resolving to a single entity to get the attributes from. |
Return type | Description |
---|---|
map | A map from attribute names to attribute values for all of the attributes on the given entity. |
removeAttributes (context is Context, definition is map)
Has no effect on named attributes, instead use setAttribute
with "attribute" : undefined
.
Legacy unnamed attributes: Remove matching unnamed attributes attached to entities.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | Optional Entities to remove unnamed attributes from. Default is everything. |
|
Optional If provided, will only remove attributes with the same type, using the same behavior documented in the legacy function |
defineComputedPartProperty (propertyFunction is function) returns function
This function takes a computed part property function and wraps it to define a computed part property. It is analogous to defineFeature
, except that it is used to define computed part properties. A typical usage is something like:
annotation { "Property Function Name" : "MyProperty" } // annotation required for Onshape to recognize computed property function export const myProperty = defineComputedPartProperty(function(context is Context, part is Query, definition is map) returns ValueWithUnits // may also return string or boolean or number // definition is an empty map and reserved for future use { ... // Compute and return the property value, using the context and the parameters });
For more information on writing computed part properties, see Computed part properties
in the FeatureScript guide.
Parameter | Type | Additional Info |
---|---|---|
propertyFunction |
function | A function that takes a |
This module contains functions for working with FeatureScript arrays (e.g. [1, 2, 3]
) and maps (e.g. { "x" : 1, "y" : true }
)
makeArray (size is number, fillValue) returns array
Create a new array with given size
, filled with fillValue
. Note: this is equivalent to assigning each individual array element to fillValue
; boxes and builtins will not be deep-copied.
EXAMPLE
makeArray(3, 0)
returns[0, 0, 0]
makeArray (size is number) returns array
Create a new array with given size
, filled with undefined
.
EXAMPLE
makeArray(3)
returns[undefined, undefined, undefined]
size (container is array) returns number
Returns the size of an array. This counts only direct children; it does not recursively examine containers inside.
EXAMPLE
size([1, 2, 3])
returns3
EXAMPLE
size([1, [2, 3]])
returns2
size (container is map) returns number
Returns the size of an map. This counts only direct children; it does not recursively examine containers inside.
EXAMPLE
size({ "x" : 1, "y" : 2 })
returns2
isIn (value, container is array) returns boolean
Returns true
if value
appears in an array, using ==
for comparison.
EXAMPLE
isIn(1 * inch, [0 * inch, 1 * inch, 2 * inch])
returnstrue
indexOf (container is array, value) returns number
Return the index of the value
in container
, or -1 if the value is not found.
indexOf (container is array, value, startIndex is number) returns number
Return the index of the value
in container
starting the search at a specified start index, or -1 if the value is not found.
isValueIn (value, container is map) returns boolean
Returns true
if value
appears as the value of a map entry, using ==
for comparison.
EXAMPLE
isValueIn(true, { "a" : true, "b" : 0 })
returnstrue
EXAMPLE
isValueIn("b", { "a" : true, "b" : 0 })
returnsfalse
mapArray (arr is array, mapFunction is function) returns array
Returns a new array, with the same size as arr
, created by mapping each element of arr
through a mapFunction
.
EXAMPLE
mapArray([0, 1], function(x) { return -x; })
returns[0, -1]
Parameter | Type | Additional Info |
---|---|---|
mapFunction |
function | A function which takes in one argument (a member of the input array) and returns a value. |
resize (arr is array, newSize is number, newValue) returns array
Returns a copy of an array with size changed to newSize
. If the new size is larger than the original size, the extra values are set to newValue
.
EXAMPLE
resize([1, 2, 3], 2, 0)
returns[1, 2]
EXAMPLE
resize([1, 2, 3], 5, 0)
returns[1, 2, 3, 0, 0]
resize (arr is array, newSize is number) returns array
Returns a copy of an array with size changed to newSize
. If the new size is larger than the original size, the extra values are set to undefined
.
append (arr is array, newValue) returns array
Returns a copy of an array with a single value added to the end.
EXAMPLE
append([1, 2], 3)
returns[1, 2, 3]
concatenateArrays (arr is array) returns array
Given an array of arrays, concatenate the contents of the inner arrays.
EXAMPLE
concatenateArrays([[1, 2], [3, 4]])
returns[1, 2, 3, 4]
EXAMPLE
concatenateArrays([[1], [], [2, undefined], [[3]]])
returns[1, 2, undefined, [3]]
mergeMaps (defaults is map, m is map) returns map
Add each key-value pair in the second map to a copy of first and return the result. Since later-added entries take precedence, nothing from the second map will be lost.
In other words, any keys from defaults
which are missing from m
will be filled in with their values from defaults
.
EXAMPLE
mergeMaps({a:0}, {a:1})
returns{a:1}
EXAMPLE
mergeMaps({a:0}, {b:1})
returns{a:0, b:1}
intersectMaps (maps is array) returns map
Compute the intersection of the keysets of the input maps. In other words, returns a map whose keys are present in all input maps and whose values are taken from the last map.
EXAMPLE
intersectMaps([{a:0}, {a:1}])
returns{a:1}
EXAMPLE
intersectMaps([{a:0}, {b:1}])
returns{}
EXAMPLE
intersectMaps([{a:0, b:1}, {a:0, b:2}])
returns{a:0, b:2}
reverse (arr is array) returns array
Return a copy of an array with elements in reverse order.
EXAMPLE
reverse([1, 2, 3])
returns[3, 2, 1]
sort (entities is array, compareFunction is function)
Return a sorted copy of an array. Current implementation uses merge sort.
EXAMPLE
sort([3, 1, 2], function(a, b) { return a - b; })
returns[1, 2, 3]
Parameter | Type | Additional Info |
---|---|---|
compareFunction |
function | A function that takes two values, returns a negative value if the first is before the second, |
tolerantSort (values is array, tolerance) returns array
Returns a sorted copy of values
, where any sequence of values within tolerance
of each other is sorted in the order of the original array.
This is useful when sorting by a geometric measurement (like length, area, or volume) because it makes it much less likely that a tiny change in that computed value will change the resulting sort order.
EXAMPLE
tolerantSort([5, 1.000001, 1, 8], 0.001)
returns[1.000001, 1, 5, 8]
EXAMPLE
tolerantSort( [1 * inch, 1.00009 * inch, 0.99991 * inch], 0.0001 * inch)
returns[1 * inch, 1.00009 * inch, 0.99991 * inch]
. The order is entirely unchanged since two pairs of values are within the tolerance (even though the third pair isn't).
Parameter | Type | Additional Info |
---|---|---|
values |
array | An array of |
tolerance |
Tolerance for comparing elements of |
tolerantSort (entities is array, tolerance, mapFunction) returns array
Performs a tolerantSort of entities
, ordering by the value returned by mapFunction
. Like tolerantSort
, the original order will be preserved for values within tolerance
for stability.
Parameter | Type | Additional Info |
---|---|---|
tolerance |
EXAMPLE
|
|
mapFunction |
A function taking in a single entity and returning a sortable EXAMPLE
|
filter (arr is array, filterFunction is function)
Return the members of an array matching a predicate function, preserving element order.
Throws exception if filterFunction
throws, or if the filterFunction
does not return boolean
.
EXAMPLE
filter([1, 2, 3, 4, 5, 6], function(x) { return x % 2 == 0; })
returns[2, 4, 6]
Parameter | Type | Additional Info |
---|---|---|
filterFunction |
function | A function which takes one argument (a member of the input array) and returns a |
Return the first item in a map
keys (container is map) returns array
Returns the keys in the supplied map in map iteration order.
EXAMPLE
keys({ "a" : 1, "c" : 2, "b" : 3 })
returns["a", "b", "c"]
values (container is map) returns array
Returns the values in the supplied map ordered by the map iteration ordering of their associated keys.
EXAMPLE
values({ "a" : 1, "c" : 2, "b" : 3 })
returns[1, 3, 2]
subArray (input is array, startIndex is number) returns array
Returns the subarray beginning at startIndex
subArray (input is array, startIndex is number, endIndex is number) returns array
Returns the subarray [startIndex, endIndex)
insertIntoMapOfArrays (mapToInsertInto is map, key, value) returns map
Inserts value
into the array keyed by key
, returns the updated map
Returns last element of array.
rotateArray (elements is array, step is number) returns array
Returns a rotated array of the same elements. step
less than zero moves elements towards the front. step
greater than zero moves elements towards the back.
EXAMPLE
rotateArray([0, 1, 2], -1)
returns[1, 2, 0]
insertElementAt (arr is array, index is number, value) returns array
Returns an array with value
inserted at index
.
removeElementAt (arr is array, index is number) returns array
Returns an array with the element at index
removed.
all (arr is array, checkFunction is function) returns boolean
Returns true
if and only if all elements of an array, when passed into the checkFunction
, return true
.
EXAMPLE
all([0, 2, 4], function(e){ return e % 2 == 0; })
returnstrue
EXAMPLE
all([], function(e){ return false; })
returnstrue
See also
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of elements to be checked. |
checkFunction |
function | A unary function that returns a boolean. |
Return type | Description |
---|---|
boolean |
|
all (arr is array) returns boolean
Returns true if all elements in the passed array are true
.
EXAMPLE
all([])
returnstrue
EXAMPLE
all([false, false, true])
returnsfalse
EXAMPLE
all([true, true, true])
returnstrue
See also
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of booleans. |
Return type | Description |
---|---|
boolean |
|
allCombinations (arr is array) returns array
Creates all possible combinations from arrays of values for each element.
EXAMPLE
allCombinations([[1,2], [3,4]])
returns[[1,3], [1,4], [2,3], [2,4]]
EXAMPLE
allCombinations([[0, 1, 2, 3]])
returns[[0], [1], [2], [3]]
EXAMPLE
allCombinations([[], [0, 1, 2]])
returns[]
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of arrays, where each array represents all possible values for the given array's index in the returned arrays. |
Return type | Description |
---|---|
array | An array of all possible combinations that have exactly one element from each of the input arrays. |
any (arr is array, check is function) returns boolean
Returns true
if any element of an array, when passed into the check
function, returns true
.
EXAMPLE
any([1, 3, 4], function(e){ return e % 2 == 0; })
returnstrue
EXAMPLE
any([], function(e){ return true; })
returnsfalse
See also
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of elements. |
Return type | Description |
---|---|
boolean |
|
any (arr is array) returns boolean
Returns true if any element in the passed array is true
.
EXAMPLE
any([])
returnsfalse
EXAMPLE
any([false, false, true])
returnstrue
See also
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of booleans. |
Return type | Description |
---|---|
boolean |
|
Returns the average of an array. All array elements must be mutually addable and divisible by a number.
EXAMPLE
average([1, 2, 3, 4])
returns2.5
EXAMPLE
average([vector([1, 0, 0])*meter, vector([0, 0, 0])*meter, vector([0, 1, 0])*meter])
returnsvector(1/3, 1/3, 0) * meter
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of mutually addable and divisible elements. |
Return type | Description |
---|---|
The average of values in the passed in array. |
deduplicate (arr is array) returns array
Deduplicate an array. Maintains original array order, eliminating all but the first occurrence of a given duplicate.
EXAMPLE
deduplicate([1, 2, 1, 3, 2, 0, 0])
returns[1, 2, 3, 0]
EXAMPLE
deduplicate([])
returns[]
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of values to be deduplicated. |
Return type | Description |
---|---|
array | An array of deduplicated values. |
foldArray (arr is array, seed, foldFunction is function)
Folds an array from left to right with a foldFunction
.
EXAMPLE
foldArray([1, 2, 3], 0, function(accumulator, element) { return accumulator + element; })
returns6
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array to fold. |
seed |
The initial value of the accumulator to be passed into the |
|
foldFunction |
function | A binary function which takes in an accumulator (the seed for the first iteration, and the result of the previous call for subsequent iterations) and an element of the passed in array. |
Return type | Description |
---|---|
The accumulator after all elements of |
foldArray (arr is array, foldFunction is function)
mapArrayIndices (arr is array, mapIndexFunction is function) returns array
Returns a new array, with the same size as arr
, created by mapping each index of arr
through a mapIndexFunction
.
EXAMPLE
const myArray = [1, 3, 5]; mapArrayIndices(myArray, function(i) { return myArray[i] + myArray[ (i+1) % size(myArray)]; })
returns[4, 8, 6]
Parameter | Type | Additional Info |
---|---|---|
mapIndexFunction |
function | A function which takes in one argument (an index of the input array) and returns a value. |
Return type | Description |
---|---|
array | The results of calling |
mapValue (value, mapFunction is function)
Map a value using a mapFunction and return the result. Particularly useful when using a lambda function inline to dynamically change some value.
EXAMPLE
mapValue(4, function(n){ return n+1; })
returns5
EXAMPLE
couldBeUndefined->mapValue(function(v){ return v == undefined ? 'a great default' : v; })
Parameter | Type | Additional Info |
---|---|---|
value |
Anything that the passed in mapFunction will accept as a parameter. |
|
mapFunction |
function | A function that will be called on the passed in |
Return type | Description |
---|---|
The result of calling |
memoizeFunction (f is function) returns function
Memoize a unary (one-parameter) function. Once memoized, if the returned function is called with the same parameter twice, the second return value will be fetched from an internal cache. This can dramatically speed up calculations - particularly when f
is called with the same parameter many times. The overhead of memoizing a function is negligible. Note that memoization will not properly work with functions that have side effects, such as modifying a box.
EXAMPLE
const square = memoizeFunction(function(n){ return n^2; }); println(square(5)); // calls f internally and prints 25 println(square(5)); // retrieves cached value of 25 and returns it
Parameter | Type | Additional Info |
---|---|---|
f |
function | A unary function to be memoized. |
Return type | Description |
---|---|
function | A memoized function that will return the same thing as f. |
mergeMaps (defaults, keyList is array, newNode)
Merge maps at a particular location as specified by the keyList
. If either the destination node specified by the keyList
or the newNode
is not a map, the newNode
will replace the destination node.
EXAMPLE
mergeMaps({ a: [ { b: 2 } ] }, ['a', 0, 'b'], 4)
returns{ a : [ { b : 4 } ] }
EXAMPLE
mergeMaps(5, [], 4)
returns4
EXAMPLE
mergeMaps({ a : 5 }, ['a'], 4)
returns{a: 4 }
See also
Parameter | Type | Additional Info |
---|---|---|
defaults |
A container (array or map) that will be merged at the location specified by the |
|
keyList |
array | An array of map keys or array indices that collectively specify a location within |
newNode |
A value that will be merged into defaults at the location specified by |
Return type | Description |
---|---|
The merged or replaced value. |
Sum an array of elements that are all mutually addable. An empty array returns 0.
EXAMPLE
sum(range(0,5))
returns15
EXAMPLE
sum([vector(1, 2, 3) * meter, vector(4, 5, 6) * meter])
returnsvector(5, 7, 9) * meter
EXAMPLE
sum([])
returns0
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of mutually addable elements to be summed. |
Return type | Description |
---|---|
The sum of values in the passed in array. |
zip (arr is array) returns array
Makes an array that aggregates elements from each of the arrays. Returns an array of arrays, where the i-th array contains the i-th element from each of the argument arrays. The array stops when the shortest input array is exhausted. With a single array argument, it returns an array of single element arrays. With no arguments, it returns an empty array.
EXAMPLE
zip([range(0,3), range(10,13), range(20,26)])
returns[[0, 10, 20], [1, 11, 21], [2, 12, 22], [3, 13, 23]]
EXAMPLE
zip([])
returns[]
EXAMPLE
zip([range(0, 3)])
returns[[0],[1],[2],[3]]
See also
Parameter | Type | Additional Info |
---|---|---|
arr |
array | An array of arrays to aggregate. |
Return type | Description |
---|---|
array | An array where the i'th element contains the i'th element from each of the passed in arrays. |
zip (a is array, b is array) returns array
An alternative way to call zip(array)
that facilitates chaining arguments.
EXAMPLE
zip(range(0,3), range(1, 4))
returns[[0, 1], [1, 2], [2, 3], [3, 4]]
EXAMPLE
zip(range(0,3), [])
returns[]
See also
Parameter | Type | Additional Info |
---|---|---|
a |
array | The first array to zip. |
b |
array | The second array to zip. |
Return type | Description |
---|---|
array | An array of length-2 arrays. For the i'th array, the first element is the i'th element of |
debug (context is Context, value, color is DebugColor)
Print and, if applicable, display value
in a Part Studio, highlighting or creating entities in a chosen color, red by default.
The displayed data will ONLY be visible when the feature calling the debug
function is being edited. Entities displayed during debug are for display only, and will not appear in any queries.
Values which can be debugged are:
Query
: Highlights entities matching the Query
(bodies, faces, edges, and vertices) in red.
3D length Vector
: Displays a single point in world space.
Unitless, normalized 3D Vector
: Displays an arrow starting at the world origin, pointing in the given direction.
Line
: Displays an arrow starting at the line's origin, pointing in the line's direction.
CoordSystem
: Displays three perpendicular arrows from the coordinate system's origin, along its three axes. The arrowhead for the x-axis is largest, and the z-axis is smallest.
Plane
: Displays a large square in the positive quadrant of the plane, along with three arrows along the plane's x-axis, y-axis, and normal.
Box3d
: Displays the edges of the bounding box (in the given coordinate system, if provided)
The overloads in this module define these behaviors.
Parameter | Type | Additional Info |
---|---|---|
color |
DebugColor | Optional The color of the debug highlight |
debug (context is Context, value)
debug (context is Context, value is ValueWithUnits, color is DebugColor)
debug (context is Context, value is Vector, color is DebugColor)
debug (context is Context, value is Query, color is DebugColor)
debug (context is Context, value is Line, color is DebugColor)
debug (context is Context, value is CoordSystem)
debug (context is Context, value is CoordSystem, color is DebugColor)
debug (context is Context, value is CoordSystem, xColor is DebugColor, yColor is DebugColor, zColor is DebugColor)
debug (context is Context, value is Plane, color is DebugColor)
debug (context is Context, point1 is Vector, point2 is Vector, color is DebugColor)
Draws a line between point1
and point2
and prints the points with the distance between them.
debug (context is Context, point1 is Vector, point2 is Vector)
debug (context is Context, boundingBox is Box3d, color is DebugColor)
Displays the edges of a Box3d
in the world coordinate system with a chosen DebugColor
.
debug (context is Context, boundingBox is Box3d, cSys, color is DebugColor)
Displays the edges of a Box3d
in the given coordinate system with a chosen DebugColor
.
EXAMPLE
const myBox = evBox3d(context, { "topology" : entities, "cSys" : myCSys }); debug(context, myBox, myCSys, DebugColor.RED);
debug (context is Context, boundingBox is Box3d, cSys)
addDebugEntities (context is Context, entities is Query, color is DebugColor)
Highlights entities
in a given DebugColor
, without printing anything.
As with debug
, highlighted entities are only visible while the debugged feature's edit dialog is open.
addDebugEntities (context is Context, entities is Query)
addDebugPoint (context is Context, point is Vector, color is DebugColor)
Highlights a 3D point
in a given DebugColor
, without printing anything.
As with debug
, highlighted entities are only visible while the debugged feature's edit dialog is open.
addDebugPoint (context is Context, point is Vector)
addDebugLine (context is Context, point1 is Vector, point2 is Vector, color is DebugColor)
Draws a line in 3D space from point1
to point2
with a chosen DebugColor
.
As with debug
, highlighted entities are only visible while the debugged feature's edit dialog is open.
Parameter | Type | Additional Info |
---|---|---|
point1 |
Vector | one endpoint of the line. |
point2 |
Vector | the other endpoint of the line. |
addDebugLine (context is Context, point1 is Vector, point2 is Vector)
addDebugArrow (context is Context, from is Vector, to is Vector, radius is ValueWithUnits, color is DebugColor)
Draws an arrow in 3D space from from
to to
with a chosen DebugColor
.
As with debug
, highlighted entities are only visible while the debugged feature's edit dialog is open.
Parameter | Type | Additional Info |
---|---|---|
radius |
ValueWithUnits | Width of the four arrowhead lines EXAMPLE
|
addDebugArrow (context is Context, from is Vector, to is Vector, radius is ValueWithUnits)
startTimer (timer is string)
Starts the timer associated with the string timer
or resets it. Use with printTimer(string)
.
startTimer ()
Starts the global timer associated with the empty string or resets it. Use with printTimer()
.
printTimer (timer is string)
Prints the elapsed milliseconds for the timer associated with the string timer
. Use with startTimer(string)
.
Note that if the timer was set in a prior feature, the elapsed time may be very large because features can be regenerated at different times.
Throws an error if no such timer has been started.
printTimer ()
Prints the elapsed milliseconds for the global timer associated with the empty string. Use with startTimer()
.
Note that if the timer was set in a prior feature, the elapsed time may be very large because features can be regenerated at different times.
Throws an error if no such timer has been started.
DecalData type
Data representing a decal that is mapped onto a face.
Value | Type | Description |
---|---|---|
DecalData |
map | |
|
Id | A unique id to represent the decal in the context of the face on which it is placed. The id should correspond to the id of the creating feature, or be a sub-id of the creating feature. |
|
ImageMappingType | The type of projection mapping to use for this decal |
|
ImageData | The image that is being mapped. |
|
TransformUV | A post-projection transformation that is applied in UV space. This can be used to further translate, rotate, and scale a projected image. |
|
PersistentCoordSystem | Optional A coordinate system representing the plane for the ImageMappingType.PLANAR type. This field must be defined if the |
|
Cylinder | Optional The cylinder onto which the decal is mapped. This field must be defined if the |
|
PersistentCoordSystem | Optional A coordinate system used in projecting the image onto the given cylinder. This field must be defined if the |
createPlanarDecal (decalId is Id, image is ImageData, planeSystem is CoordSystem, uvTransform is TransformUV) returns DecalData
Creates data for a planar decal. This can be applied to a face using associateDecalAttribute
.
See also
Parameter | Type | Additional Info |
---|---|---|
decalId |
Id | The id to for the decal |
image |
ImageData | The image to use for the data |
planeSystem |
CoordSystem | The coordinate system to use for the planar projection |
uvTransform |
TransformUV | A post-projection transform to apply to the decal |
createCylindricalDecal (decalId is Id, image is ImageData, cylinder is Cylinder, uvTransform is TransformUV) returns DecalData
Creates data for a cylindrical decal. This can be applied to a face using associateDecalAttribute
.
See also
Parameter | Type | Additional Info |
---|---|---|
decalId |
Id | The id to for the decal |
image |
ImageData | The image to use for the data |
cylinder |
Cylinder | The cylinder definition to use for projection |
uvTransform |
TransformUV | A post-projection transform to apply to the decal |
associateDecalAttribute (context is Context, entities is Query, decalData is DecalData)
Associate the given decal data as an attribute on the entities provided. This will append the decal to any existing decals associated with the given entities.
Associating a decal in this way will cause the data to be transmitted to Onshape clients where they will be rendered.
createUvTransform (decalWidth is ValueWithUnits, mirrorHorizontal is boolean, decalHeight is ValueWithUnits, mirrorVertical is boolean, decalRotation is ValueWithUnits) returns TransformUV
Creates a UV transform suitable for scaling, mirroring, and rotating a decal after it's been projected.
Parameter | Type | Additional Info |
---|---|---|
decalWidth |
ValueWithUnits | The width of the decal, post-transformation |
mirrorHorizontal |
boolean | If true, the image will be mirrored about its center horizontally |
decalHeight |
ValueWithUnits | The height of the decal, post-transformation |
mirrorVertical |
boolean | If true, the image will be mirrored about its center vertically |
decalRotation |
ValueWithUnits | An amount of rotation to apply to decal about the image center. |
getWorldSpacePosition (decalData is DecalData, uv is Vector)
Unprojects the given point in UV space to its corresponding world position for the given decal data. The UV is equivalent to the texture coordinate for the UV that is ultimately used to render the decal.
See also
getDecalUvSpacePosition (decalData is DecalData, worldPosition is Vector)
Projects the given world position into UV space for the given decal data. The UV computed is equivalent to the texture coordinate for the UV that is ultimately used to render the decal.
See also
newContextWithDefaults () returns Context
Creates a Context
with default planes and an origin.
qDefaultBodies () returns Query
A query for all default created bodies in a context, that is, the top, right, front planes and the origin point.
qFrontPlane (entityType is EntityType) returns Query
A query for the front plane.
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Specify type |
qRightPlane (entityType is EntityType) returns Query
A query for the right plane.
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Specify type |
qTopPlane (entityType is EntityType) returns Query
A query for the top plane.
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Specify type |
qOrigin (entityType is EntityType) returns Query
A query for the origin point.
Parameter | Type | Additional Info |
---|---|---|
entityType |
EntityType | Specify type |
derive (context is Context, id is Id, buildFunction is function, options is map) returns map
Merges context returned by buildFunction(options.configuration) into context.
Parameter | Type | Additional Info |
---|---|---|
options |
map | |
|
Query | Queries resolving to bodies in base context to be preserved. |
|
map | The configuration of the part studio. |
|
boolean | Optional Default is |
|
boolean | Optional Default is |
|
boolean | Optional Default is |
|
ErrorStringEnum | Optional Error to be reported if options.parts resolves to empty array. If field is not specified ErrorStringEnum.IMPORT_DERIVED_NO_PARTS is used. |
|
array | Optional |
|
map | Optional Map whose keys are |
|
array | Optional Array of queries for mate connectors, to evaluate in the new context. If set, the output field |
|
array | Optional Array of creating feature ids for mate connectors. |
|
array | Optional Array of indices into mate connectors created by feature. |
|
Context | Optional Preloaded context, if available, of the reference. |
Return | Type | Description |
---|---|---|
|
map | |
|
map | Map from mate connector query to |
|
map | Map from |
addFilletControlManipulator (context is Context, id is Id, definition is map, manipulatorEntity is Query)
Create a linear manipulator for radius or width parameter
onFilletControlManipulatorChange (context is Context, definition is map, newManipulators is map, manipulatorEntity is Query, widthFieldName is string) returns map
fillet manipulator change function
regenError (customMessage is string) returns map
regenError
functions are used to construct maps for throwing to signal feature regeneration errors. Can either take a string for a custom message or an ErrorStringEnum
for a built-in message. Custom messages are limited to ASCII characters. Messages longer than 200 characters will not be displayed fully.
EXAMPLE
throw regenError("Failed to attach widget: Boolean union failed")
EXAMPLE
throw regenError("Wall is too thin for this feature", ["wallWidth"]);
EXAMPLE
throw regenError(ErrorStringEnum.POINTS_COINCIDENT, ["points"]);
regenError (customMessage is string, faultyParameters is array) returns map
Parameter | Type | Additional Info |
---|---|---|
faultyParameters |
array | An array of strings that correspond to keys in the feature definition map. Throwing a regenError with faultyParameters will highlight them in red inside the feature dialog. |
regenError (customMessage is string, entities is Query) returns map
Parameter | Type | Additional Info |
---|---|---|
entities |
Query | A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
regenError (customMessage is string, faultyParameters is array, entities is Query) returns map
Parameter | Type | Additional Info |
---|---|---|
faultyParameters |
array | An array of strings that correspond to keys in the feature definition map. Throwing a |
entities |
Query | A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
regenError (message is ErrorStringEnum) returns map
The following overloads take an ErrorStringEnum
rather than a custom message, and are using for all errors withing the Onshape Standard Library. The enum values correspond to messages which can be translated into multiple languages.
regenError (message is ErrorStringEnum, faultyParameters is array) returns map
Parameter | Type | Additional Info |
---|---|---|
faultyParameters |
array | An array of strings that correspond to keys in the feature definition map. Throwing a |
regenError (message is ErrorStringEnum, entities is Query) returns map
Parameter | Type | Additional Info |
---|---|---|
entities |
Query | A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
regenError (message is ErrorStringEnum, faultyParameters is array, entities is Query) returns map
Parameter | Type | Additional Info |
---|---|---|
faultyParameters |
array | An array of strings that correspond to keys in the feature definition map. Throwing a |
entities |
Query | A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
regenError (message is ErrorStringEnum, regenErrorOptions is map) returns map
Parameter | Type | Additional Info |
---|---|---|
regenErrorOptions |
map | |
|
An array of strings that correspond to keys in the feature definition map. Throwing a |
|
|
A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
regenError (message is string, regenErrorOptions is map) returns map
Parameter | Type | Additional Info |
---|---|---|
regenErrorOptions |
map | |
|
An array of strings that correspond to keys in the feature definition map. Throwing a |
|
|
A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the |
reportFeatureWarning (context is Context, id is Id, message is ErrorStringEnum) returns boolean
Attaches a warning-level status to the given feature id.
reportFeatureWarning (context is Context, id is Id, customMessage is string) returns boolean
Attaches a custom warning-level status to the given feature id. Will display a notification to the user containing the specified message.
reportFeatureWarning (context is Context, id is Id, message is ErrorStringEnum, associatedParameters is array) returns boolean
Attaches custom warning-level status to the given feature id. Will display a notification to the user containing the specified message.
reportFeatureInfo (context is Context, id is Id, message is ErrorStringEnum) returns boolean
Attaches an info-level status to the given feature id. Will display a notification to the user containing the specified message.
reportFeatureInfo (context is Context, id is Id, message is ErrorStringEnum, associatedParameters is array) returns boolean
Attaches an info-level status to the given feature id. Will display a notification to the user containing the specified message.
reportFeatureInfo (context is Context, id is Id, customMessage is string) returns boolean
Attaches a custom info-level status to the given feature id.
processSubfeatureStatus (context is Context, id is Id, options is map) returns boolean
Propagate the status of a subfeature to a feature.
Parameter | Type | Additional Info |
---|---|---|
options |
map | |
|
Id | The Id of the subfeature. |
|
ErrorStringEnum | Optional A status enum to use instead of the subfeature status enum if the subfeature has an info, warning, or error status. |
|
map | Optional A mapping of the field names from subfeature to feature. |
|
function | Optional A function to map field names from subfeature to feature. |
|
boolean | Optional Use subfeature error display when present. Default is false. |
|
Query | Optional Additional error entities to display if the subfeature has an info, warning, or error status. |
getFeatureStatus (context is Context, id is Id) returns FeatureStatus
Return the status of a feature as a FeatureStatus
reportFeatureStatus (context is Context, id is Id, status is FeatureStatus) returns boolean
Report the status of a feature
clearFeatureStatus (context is Context, id is Id, definition is map) returns boolean
Clear the status of a feature to StatusType.OK *
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
boolean | Optional Clear status display data attached to feature. Default true. |
getFeatureError (context is Context, id is Id)
Returns the error (as a string or an ErrorStringEnum
) associated with the given feature id or undefined
if none.
getFeatureWarning (context is Context, id is Id)
Returns the warning (as a string or an ErrorStringEnum
) associated with the given feature id or undefined
if none.
getFeatureInfo (context is Context, id is Id)
Returns the info status (as a string or an ErrorStringEnum
) associated with the given feature id or undefined
if none.
setErrorEntities (context is Context, id is Id, definition is map)
Causes the given entities to be shown in red. This display is not rolled back even if the feature fails and the entities themselves are rolled back.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The entities to display. |
featureHasError (context is Context, id is Id) returns boolean
Return type | Description |
---|---|
boolean |
|
featureHasNonTrivialStatus (context is Context, id is Id) returns boolean
Return type | Description |
---|---|
boolean |
|
faultyArrayParameterId (arrayParameter is string, itemIndex is number, innerParameter is string) returns string
Return type | Description |
---|---|
string | A string identifier for marking an error on an array parameter when using the |
FeatureStatus type
The status of a feature
Value | Type | Description |
---|---|---|
FeatureStatus |
map | |
|
StatusType | |
|
array | |
|
ErrorStringEnum | |
|
string |
canBeFeatureStatus (value) predicate
The faultyParameters cannot exist when the statusType is StatusType.OK. The statusEnum must be ErrorStringEnum.CUSTOM_ERROR if the statusMsg exists.
verify (condition is boolean, error)
If the condition check fails, this function throws the error.
Parameter | Type | Additional Info |
---|---|---|
condition |
boolean | The condition to test. |
error |
The error to throw if |
verify (condition is boolean, error, regenErrorOptions is map)
If the condition check fails, this function throws the error.
Parameter | Type | Additional Info |
---|---|---|
condition |
boolean | The condition to test. |
error |
The error to throw if |
|
regenErrorOptions |
map | The key-value pairs to pass to the thrown |
Bounding type used with SMProcessType.EXTRUDE
Value | Description |
---|---|
BLIND |
|
UP_TO_NEXT |
|
UP_TO_SURFACE |
|
UP_TO_BODY |
|
UP_TO_VERTEX |
defineFeature (feature is function, defaults is map) returns function
This function takes a regeneration function and wraps it to create a feature. It is exactly like the one-argument version of defineFeature
but the additional argument enables setting default values for feature parameters when they are not passed in.
Parameter | Type | Additional Info |
---|---|---|
defaults |
map | A map of default parameter values for when this feature is called in FeatureScript. This does NOT control the user-visible default value when creating this feature. To change the user-visible default for booleans, enums, and strings, use the "Default" annotation. To change the user-visible default for a length, angle, or number, see the EXAMPLE
EXAMPLE
|
defineFeature (feature is function) returns function
This function takes a regeneration function and wraps it to create a feature. The wrapper handles certain argument recording for the UI and error handling. A typical usage is something like:
annotation { "Feature Type Name" : "Widget" } // This annotation is required for Onshape to recognize widget as a feature. export const widget = defineFeature(function(context is Context, id is Id, definition is map) precondition { ... // Specify the parameters that this feature takes } { ... // Specify what the feature does when regenerating });
For more information on writing features, see Specifying feature UI
in the language guide.
Parameter | Type | Additional Info |
---|---|---|
feature |
function | A function that takes a |
startFeature (context is Context, id is Id)
callSubfeatureAndProcessStatus (topLevelId is Id, fn is function, context is Context, subfeatureId is Id, definition is map)
This function can be used to call a subfeature or sub-operation (such as extrude
or opExtrude
, respectively). It will properly handle any statuses as if they came from the top level feature. That is, reported INFO
will display as a blue message bubble, WARNING
will turn the feature orange with a warning tooltip on hover, and ERROR
will throw an error after status handling (aborting feature execution if it is not caught). Any error entities that the subfeature emits will also be displayed.
EXAMPLE
callSubfeatureAndProcessStatus(id, booleanBodies, context, id + "boolean", booleanDefinition);
(whereid
is the top-level feature id passed into the feature) will callbooleanBodies(context, id + "boolean", booleanDefinition)
, propagate its status onto the current feature, and show any error entities coming from the boolean.
Internally, calls the supplied function, and attaches any status it produces to the topLevelId
using processSubfeatureStatus
. If calling the function produces an error, the error is re-thrown. If the function produces a return value, that value is returned.
callSubfeatureAndProcessStatus (topLevelId is Id, fn is function, context is Context, subfeatureId is Id, definition is map, processSubfeatureStatusOptions is map)
See callSubfeatureAndProcessStatus.
Parameter | Type | Additional Info |
---|---|---|
processSubfeatureStatusOptions |
map | Passed as the |
forEachEntity (context is Context, id is Id, query is Query, operationToPerform is function)
Iterate through all entities provided by a query, calling the provided function once for each geometric entity resolved by the provided query
.
forEachEntity
behaves much like the code:
const evaluated = evaluateQuery(context, query); for (var i = 0; i < size(evaluated); i += 1) { operationToPerform(id + i, evaluated[i]); }
However, forEachEntity
has one additional benefit: The entId
this function provides to operationToPerform
is tied to the entity itself, not its index i
. This means that downstream features made in the Part Studio will hold up better across upstream changes.
For example, imagine the following scenario: A user inserts a custom feature which places a slot on every selected line. That feature calls forEachEntity(context, lineQuery ...)
. The user then makes a sketch downstream which uses geometry from e.g. the third slot. Finally, the user decides some slots are unnecessary and deletes some of the lines. Since the feature used forEachEntity
, the user's downstream sketch will still reference the same slots. If the feature instead used the code above, the user's sketch would break or jump around, since a different slot would suddenly become "slot 3".
Aside from that difference, the two are interchangable.
Like any expression function, be warned that the provided operationToPerform
can read but can NOT modify the values of variables outside the function. It can, however, modify values inside a box.
EXAMPLE
const allParts = qAllModifiableSolidBodies(); const threshold = 0.01 * inch^3; var deletedSizes is box = new box([]); // box containing an empty array forEachEntity(context, id + "deleteSmallParts", allParts, function(entity is Query, id is Id) { const size = evVolume(context, { "entities" : entity }); if (size < threshold) { opDeleteBodies(context, id + "deleteBodies1", { "entities" : entity }); deletedSizes[] = append(deletedSizes[], size); } }); println(deletedSizes[]);
Parameter | Type | Additional Info |
---|---|---|
operationToPerform |
function | EXAMPLE function(entity is Query, id is Id) { // perform operations with the entity } The first argument to this function is a query resolving to one single entity of the input The second argument to this function is a unique id tied to the |
setFeatureComputedParameter (context is Context, id is Id, definition is map)
Associates a FeatureScript value with a given string. This value can then be referenced in a feature name using the string. The provided value can be used in a feature name by including e.g. "#myValue" in the Feature Name Template.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
string | EXAMPLE
|
|
getFullPatternTransform (context is Context) returns Transform
When in feature pattern scope returns composition of all pattern transforms pushed by setFeaturePatternInstanceData
returns identity transform when out of scope
getRemainderPatternTransform (context is Context, definition is map) returns Transform
Making a feature work correctly with feature patterns is usually done with two functions: this one and transformResultIfNecessary
.
Feature patterns work by first computing a sequence of transforms, one for each instance. For each transform, the pattern pushes it onto the pattern stack (using setFeaturePatternInstanceData
), executes the patterned features, and then pops the transform off the stack (using unsetFeaturePatternInstanceData
) before pushing the next one. The stack depth corresponds to the level of nesting of feature patterns. Feature authors are responsible for reading the pattern stack and transforming themselves accordingly.
The basic principle is that inside one feature pattern (as opposed to nested feature patterns), if any entities that the feature references come from a feature that is also being patterned, then the feature ignores the pattern transform. Otherwise, the feature uses the pattern transform in a "natural" way, applying it to an input, the output, or somewhere in between.
For example, suppose the patterned feature creates a 3D line between two arbitrary vertices. If the first vertex is also patterned, but not the second, then the result should be a bunch of lines from different instances of the first vertex to the unpatterned second vertex (this is accomplished by not applying any transform to the line). If neither vertex is patterned, the line should be transformed by the pattern transform and the result will be as expected, as if a body pattern of these lines was performed. Other features may need to apply the transform differently: for example, a sweep can transform the result of opSweep
prior to the boolean, but an extrude needs to transform the profile prior to opExtrude
to accommodate up-to-next correctly.
The general case is more complicated because feature patterns may be nested, and this function is designed to handle them. This function takes references
, a query for everything the feature geometrically depends on (typically a qUnion
of the queries in the feature definition), and computes the portion of the pattern transform that is not applied to any of the references and hence should be applied to the feature. For example, if one of the references is patterned by the current feature pattern or if there is no feature pattern, it will return the identity transform. If references
evaluates to nothing, it will return the current feature pattern transform.
More precisely: Among references find topology created by pattern instance deepest in the pattern transform stack. If the transformation on the stack for that instance is S and the full transformation is F, the remainder R is such that R * S = F
A simple feature may use this function and transformResultIfNecessary
as follows:
... // Feature definition boilerplate and precondition { // Feature body // Call getRemainderPatternTransform before performing any operations var remainingTransform = getRemainderPatternTransform(context, { "references" : definition.vertexToBuildOn }); ... // Create a cube using definition.vertexToBuildOn as the reference location // Inside a feature pattern, the following will transform the cube if definition.vertexToBuildOn is not getting patterned: transformResultIfNecessary(context, id, remainingTransform); ... // Perhaps boolean the results to something in the context });
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query |
transformResultIfNecessary (context is Context, id is Id, transform is Transform)
Applies transformation to bodies created by operation with id if transform argument is non-trivial
isAnything (value) predicate
A predicate which always returns true. Used to create a generic feature parameter that can be any featurescript expression.
Note that to change the user-visible default value, the "Default" annotation must be a string containing a valid parameter expression. For example, to make the default value the string "My string"
, pass in an escaped string: annotation{ "Default": "\"My string\"" }
.
lastModifyingOperationId (context is Context, query is Query) returns Id
Returns id of operation that created or last modified the first entity to which query
resolves.
Throws if query
resolves to nothing.
startTracking (context is Context, arg is map) returns Query
Generates a tracking query, which will evaluate to entities derived from subquery in features between startTracking and when query is evaluated. If secondarySubquery is specified, the query would evaluate to entities derived from both objects. If trackPartialDependency is set to true, query would also include entities that are not exclusively derived from subquery1. Optional field lastOperationId can be used to specify the starting operation of tracking. Use example:
// "sketch1" constructs a polygon of "line0", "line1", etc. var extrudedFromLine0 = startTracking(context, id + "sketch1", "line0"); extrudeOp(context, id + "extrude1", {"entities" : qSketchRegion(id + "sketch1",....}); var fromLine0 = evaluateQuery(context, extrudedFromLine0); // fromLine0 contains a face and two edges (top and bottom) corresponding to line0 in the extrude.
startTracking (context is Context, subquery is Query) returns Query
startTracking (context is Context, sketchId is Id, sketchEntityId is string) returns Query
startTrackingIdentity (context is Context, subquery is Query) returns Query
Generates a tracking query, which will evaluate to the new entities inheriting the identity of subquery evaluation result.
makeRobustQuery (context is Context, subquery is Query) returns Query
Generates query robust to identity-preserving changes
makeRobustQueriesBatched (context is Context, subquery is Query) returns array
Generates array of robust queries for each entity of the subquery
setExternalDisambiguation (context is Context, id is Id, query is Query)
Used to set external disambiguation for operations with unstable component in id. The disambiguation will be applied to results of sub-operations which otherwise don't track dependency e.g. Sketch
, opPlane
, opPoint
Parameter | Type | Additional Info |
---|---|---|
id |
Id | ends in unstable component |
verifyNonemptyQuery (context is Context, definition is map, parameterName is string, errorToReport is string) returns array
Throws a regenError
and marks the specified Query
parameter as faulty if the specified Query
parameter is not a Query
which resolves to at least one entity. This happens when the user has not made any selection into the Query
parameter, or when upstream geometry has changed such that the Query
s of the Query
parameter no longer resolve to anything. Should be used to check all non-optional Query
parameters in a feature. By convention, errorToReport
should take the form "Select parameter display name." For example, a parameter declared as follows:
annotation { "Name" : "Entities to use", "Filter" : EntityType.FACE } definition.entitiesToUse is Query;
should verify that the input is nonempty in the following way:
EXAMPLE
verifyNonemptyQuery(context, definition, "entitiesToUse", "Select entities to use.")
Return type | Description |
---|---|
array | An array representing the result of evaluating the |
verifyNonemptyArray (context is Context, definition is map, parameterName is string, errorToReport is string)
Throws a regenError
and marks the specified array parameter as faulty if the specified array parameter does not have any entries. A parameter declared as follows:
annotation { "Name" : "Array items", "Item name" : "Array item" } definition.arrayItems is array; for (var arrayItem in definition.arrayItems) { ... }
could verify that the input is nonempty in the following way:
EXAMPLE
verifyNonemptyArray(context, definition, "arrayItems", "Add an array item.")
verifyNoMesh (context is Context, definition is map, parameterName is string)
Verifies that the definition[parameterName]
Query
does not contain mesh or mixed entities. Throws a regenError
if definition[parameterName]
references mesh topologies.
verifyNoMeshInBody (context is Context, definition is map, parameterName is string)
Verifies no body containing the specified query contains any mesh.
Parameter | Type | Additional Info |
---|---|---|
context |
Context | The application context. |
definition |
map | The feature definition. |
parameterName |
string | The key of |
adjustAngle (context is Context, angle is ValueWithUnits) returns ValueWithUnits
Adjust angle out of bounds angles to lie in [0 to 2pi]
if the feature is new, do a range check otherwise.
isButton (value) predicate
True if the value is undefined and creates a button parameter.
Support functions for feature lists (as used for featurePattern)
FeatureList type
Parameter type for inputting a list of features, stored as a map from feature Id
to feature function. For an example, see the circularPattern
module.
canBeFeatureList (value) predicate
Typecheck for FeatureList
featureList (features is map) returns FeatureList
Takes a map from id to lambda to return it as type FeatureList
valuesSortedById (context is Context, idToValue is map) returns array
Takes a context and a map whose keys are subfeature ids from that context. Returns the values from that map sorted in the order that the subfeatures were started.
FlatOperationType enum
Types of flat operations supported by SMFlatOp
Value | Description |
---|---|
ADD |
|
REMOVE |
setFormAttribute (context is Context, bodies is Query, attribute is string)
Attach the given FormAttribute to the bodies
.
qBodiesWithFormAttribute (attribute is string)
Query for all bodies marked with a FormAttribute and value exactly equal to attribute
See also
qBodiesWithFormAttribute (queryToFilter is Query, attribute is string) returns Query
Query for all bodies in queryToFilter
marked with a FormAttribute and value exactly equal to attribute
See also
qBodiesWithFormAttributes (queryToFilter is Query, attributes is array) returns Query
Query for all bodies in queryToFilter
marked with a FormAttribute and value exactly equal to one of the attributes
See also
FrameTopologyType enum
The possible types of a FrameTopologyAttribute
.
Value | Description |
---|---|
SWEPT_FACE |
The side faces of a frame, swept from the edges of the profile |
SWEPT_EDGE |
The side edges of a frame, swept from the vertices of the profile |
CAP_FACE |
The start and end cap faces of a frame |
An attribute attached to the frame profile and the constructed frame body which defines the default cutlist associated with the frame.
frameProfileAttribute (value is map) returns FrameProfileAttribute
Construct a FrameProfileAttribute
.
getFrameProfileAttributes (context is Context, frames is Query)
Get all FrameProfileAttribute
s attached to the frames
.
getFrameProfileAttribute (context is Context, frame is Query)
Get the FrameProfileAttribute
attached to the frame
. Throw if a single attribute is not found.
setFrameProfileAttribute (context is Context, frame is Query, attribute is FrameProfileAttribute)
Attach the given FrameProfileAttribute
to the frame
.
An attribute assigned to certain faces and edges of the frames to aid in tracking the frame as it changes over the series of frame-altering features.
frameTopologyAttributeForSwept (topologyType is FrameTopologyType) returns FrameTopologyAttribute
frameTopologyAttributeForCapFace (isStartFace is boolean, isFrameTerminus is boolean, isCompositeTerminus is boolean) returns FrameTopologyAttribute
getFrameTopologyAttributes (context is Context, faces is Query)
Get all FrameTopologyAttribute
s attached to the faces
.
getFrameTopologyAttribute (context is Context, face is Query)
Get the FrameTopologyAttribute
attached to the face
. Throw if a single attribute is not found.
setFrameTopologyAttribute (context is Context, entities is Query, attribute is FrameTopologyAttribute)
Attach the given FrameTopologyAttribute
to each of the entities
.
CutlistAttribute type
An attribute attached to the composite created by the Cutlist feature which contains the cutlist table for that composite.
cutlistAttribute (featureId is Id, table is Table) returns CutlistAttribute
Construct a CutlistAttribute
.
getCutlistAttributes (context is Context, composites is Query)
Get all CutlistAttribute
s attached to the composites
.
getCutlistAttribute (context is Context, composite is Query)
Get the getCutlistAttribute
attached to the composite
. Throw if a single attribute is not found.
setCutlistAttribute (context is Context, composite is Query, attribute is CutlistAttribute)
Attach the given CutlistAttribute
to the composite
.
setCustomFrameAlignmentPointAttribute (context is Context, pointsQuery is Query)
Sets an attribute on the sketch entity point queries for later discovery and use during frame creation.
getCustomFrameAlignmentPoints (context is Context, profileId is Id) returns Query
Finds the sketch points in the profileId
sketch with the custom alignment point attribute.
HoleStyle enum
Defines whether each hole should have a countersink, a counterbore, or neither.
Value | Description |
---|---|
SIMPLE |
|
C_BORE |
|
C_SINK |
HoleProfile type
Describes a single profile for a HoleDefinition
.
See also
holeProfile
for standard circular profiles.
holeProfileBeforeReference
for a circular profile meant to be used as the first profile of the hole.
matchedHoleProfile
for a profile that geometrically matches the HolePositionReference
.
Value | Type | Description |
---|---|---|
HoleProfile |
map | |
|
HolePositionReference | The reference along the hole axis to which this profile is relative. |
|
boolean | Optional Whether the |
|
HoleProfileType | How the profile should be constructed in relation to the given |
|
ValueWithUnits | Required if The position of the profile along the hole axis, relative to the given |
|
ValueWithUnits | The radius of the profile. Can be |
|
boolean | Optional If |
|
boolean | Optional If |
|
string | Optional A name for to assign to the edge created by |
canBeHoleProfile (value) predicate
Typecheck for HoleProfile
holeProfile (positionReference is HolePositionReference, position is ValueWithUnits, radius is ValueWithUnits, optionalParameters is map) returns HoleProfile
Returns a new circular HoleProfile
at a given position
in relation to the end of the range of the positionReference
. See HolePositionReference
for further detail about the range of the positionReference
.
Parameter | Type | Additional Info |
---|---|---|
optionalParameters |
map | |
|
boolean | Optional See |
|
boolean | Optional See |
|
string | Optional See |
holeProfile (positionReference is HolePositionReference, position is ValueWithUnits, radius is ValueWithUnits) returns HoleProfile
holeProfileBeforeReference (positionReference is HolePositionReference, position is ValueWithUnits, radius is ValueWithUnits, optionalParameters is map) returns HoleProfile
Returns a new circular HoleProfile
at a given position
in relation to the beginning of the range of the positionReference
. See HolePositionReference
for further detail about the range of the positionReference
. This type of profile is useful as the first profile of a hole, such that if the hole cylinder intersects the first target at a slanted or otherwise irregular face, the first profile is backed up enough such that when the hole tool is subtracted from the target, there is no undesirable overhang left behind.
Parameter | Type | Additional Info |
---|---|---|
optionalParameters |
map | |
|
boolean | Optional See |
|
boolean | Optional See |
|
string | Optional See |
holeProfileBeforeReference (positionReference is HolePositionReference, position is ValueWithUnits, radius is ValueWithUnits) returns HoleProfile
matchedHoleProfile (positionReference is HolePositionReference, radius is ValueWithUnits, optionalParameters is map) returns HoleProfile
Returns a new HoleProfile
that is geometrically matched to the positionReference
. This is useful for configurations like blind-in-last, where a transition from one radius to another must be made that matches the shape of the position reference, to avoid the hole tool intersecting incorrectly with the part(s) in question. To form a valid HoleDefinition
, MATCHED
profiles must come in pairs of different radii.
Parameter | Type | Additional Info |
---|---|---|
optionalParameters |
map | |
|
boolean | Optional See |
|
boolean | Optional See |
|
string | Optional See |
matchedHoleProfile (positionReference is HolePositionReference, radius is ValueWithUnits) returns HoleProfile
HoleDefinition type
Describes the shape of a hole using a series of HoleProfile
s.
See also
Value | Type | Description |
---|---|---|
HoleDefinition |
map | |
|
array | An array of |
|
array | Optional A list of names to assign to the faces created by |
canBeHoleDefinition (value) predicate
Typecheck for HoleDefinition
holeDefinition (profiles is array, optionalParameters is map) returns HoleDefinition
Returns a new HoleDefinition
.
Parameter | Type | Additional Info |
---|---|---|
optionalParameters |
map | |
|
string | Optional See |
holeDefinition (profiles is array) returns HoleDefinition
The instantiator makes it easy to efficiently bring in (possibly configured) bodies from other Part Studios and place them at specific positions and orientations. The usage pattern is generally as follows:
firstPartStudio::import(...); secondPartStudio::import(...); // later, in a feature const instantiator = newInstantiator(id + "myId"); var firstQuery = addInstance(instantiator, firstPartStudio::build, { "configuration" : { "configurationInput" : configurationValue }, "transform" : transform(vector(1, 2, 3) * inch) }); var secondQuery = addInstance(instantiator, secondPartStudio::build, { "configuration" : secondConfiguration, "transform" : someOtherTransform, "mateConnector" : queryForMateConnectorInSecondPartStudio // Specifies the origin }); // repeat the above as necessary instantiate(context, instantiator); // This call actually brings in the bodies // Now firstQuery and secondQuery will resolve to the instantiated geometry
Internally, the instantiator groups all added instances by Part Studio and configuration. The final call to instantiate()
is optimized so that any duplicates of the same Part Studio and the same configuration are patterned instead of re-derived, resulting in better performance and scalability for features instantiating the same bodies multiple times.
Instantiator type
Stores the data associated with using instantiator functionality.
canBeInstantiator (value) predicate
Typecheck for Instantiator
newInstantiator (id is Id) returns Instantiator
Creates a new instantiator with the specified id and default options.
newInstantiator (id is Id, options is map) returns Instantiator
Creates a new instantiator.
Parameter | Type | Additional Info |
---|---|---|
id |
Id | The root id for all instances that will be created by this instantiator. Multiple instantiators can be used simultaneously, as long as they have different ids. |
options |
map | Optional |
|
Query | Optional The query for all bodies to be brought in from the part studios. Default is all bodies except sketches. |
|
map | Optional The tolerances for variable configuration inputs. Default is 1e-8 meters for lengths, 1e-11 radians for angles, and 0 for numbers. The default tolerances for lengths, angles, and numbers can be specified using the EXAMPLE
|
addInstance (instantiator is Instantiator, build is function, definition is map) returns Query
Adds an instance to the instantiator (does not actually create it in a context) with the given build function. The definition can specify the configuration, the transform, and how the result is identified.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
map | Optional The configuration of the part studio. |
|
query | Optional A query which evaluates to bodies in new context, to be instantiated for this instance. If absent |
|
Transform | Optional The transform to be applied to the geometry. |
|
Query | Optional A query for all mate connectors from the part studio being instantiated, specifying its coordinate system. |
|
Id | Optional Creating feature Id of the mate connector used for transformation. |
|
number | Optional Index into the creating feature of the mate connector used for transformation. |
|
string | Optional The id component for this instance. Must be unique per instantiator. If it is not specified, one is automatically generated based on order. If it is specified, the query returned is |
|
Query | Optional If provided, specifies an entity whose identity controls the identity of the instance, so that queries for the instance can be robust. For example, if creating instances based on a layout sketch, one instance per line segment, the identity should be a query for the corresponding line segment. |
|
Context | If a preloaded context is provided, use this context |
Return type | Description |
---|---|
Query | a query that will resolve to the bodies instantiated once |
addInstance (instantiator is Instantiator, partStudio is PartStudioData, definition is map) returns Query
Add an instance with the buildFunction, partQuery, and configuration of a PartStudioData value.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Transform | Optional The transform to be applied to the geometry. |
|
Query | Optional A query for a mate connector in the part studio being instantiated, specifying its coordinate system. |
|
Id | Optional Creating feature Id of the mate connector used for transformation. |
|
number | Optional Index into the creating feature of the mate connector used for transformation. |
|
map | Optional If set, the values will be merged with the configuration set in |
|
string | Optional The id component for this instance. Must be unique per instantiator. If it is not specified, one is automatically generated based on order. If it is specified, the query returned is |
|
Query | Optional If provided, specifies an entity whose identity controls the identity of the instance, so that queries for the instance can be robust. For example, if creating instances based on a layout sketch, one instance per line segment, the identity should be a query for the corresponding line segment. |
|
Context | If a preloaded context is provided use this context |
Return type | Description |
---|---|
Query | a query that will resolve to the bodies instantiated once |
addInstance (instantiator is Instantiator, partStudio is PartStudioData) returns Query
Add an instance with the buildFunction, partQuery, and configuration of a PartStudioData value.
Return type | Description |
---|---|
Query | a query that will resolve to the bodies instantiated once |
instantiate (context is Context, instantiator is Instantiator)
Create the instances (in the provided context) that were added to the instantiator
LibraryValidationProblems type
A container for a list of distinct problems found when validating a part studio for use in a library
A manipulator is an alternative, graphical UI for controlling a feature's definition. For example, in Onshape's extrude
feature, the arrow which appears at the end of a blind extrusion is a manipulator controlling the depth
parameter. A manipulator can be one of a few ManipulatorTypes
, which are generally draggable arrows designed to control different degrees of freedom.
The manipulator is added inside the feature function, and will be rendered whenever that feature is being edited. Changes to a manipulator will be processed by a "Manipulator Change Function"
associated with the feature.
A small example using a manipulator to control the depth and direction of an opExtrude
is below:
annotation { "Feature Type Name" : "Fake extrude", "Manipulator Change Function" : "fakeExtrudeManipulatorChange" } export const fakeExtrude = defineFeature(function(context is Context, id is Id, definition is map) precondition { annotation { "Name" : "Faces to extrude", "Filter" : EntityType.FACE } definition.faces is Query; annotation { "Name" : "My Length" } isLength(definition.depth, LENGTH_BOUNDS); annotation { "Name" : "Opposite direction", "UIHint" : UIHint.OPPOSITE_DIRECTION } definition.shouldFlip is boolean; } { var extrudePlane is Plane = evFaceTangentPlane(context, { "face" : definition.faces, "parameter" : vector(0.5, 0.5) }); var extrudeManipulator is Manipulator = linearManipulator({ "base" : extrudePlane.origin, "direction" : extrudePlane.normal, "offset" : definition.shouldFlip ? definition.depth : -definition.depth, "primaryParameterId" : "depth" }); addManipulators(context, id, { "myManipulator" : extrudeManipulator }); opExtrude(context, id + "extrude1", { "entities" : definition.faces, "direction" : definition.shouldFlip ? extrudePlane.normal : -extrudePlane.normal, "endBound" : BoundingType.BLIND, "endDepth" : definition.depth }); }, {}); export function fakeExtrudeManipulatorChange(context is Context, definition is map, newManipulators is map) returns map { var newDepth is ValueWithUnits = newManipulators["myManipulator"].offset; definition.depth = abs(newDepth); definition.shouldFlip = newDepth > 0; return definition; }
The manipulator change function is responsible for changing the definition such that the feature will regenerate correctly. It may change the definition in any way, and need not be restricted to the pattern of one manipulator changing one parameter.
The feature function is only aware of the definition passed in; it makes no distinction about whether the definition was produced from a manipulator change, or by a change in the feature dialog, or by another custom feature.
Manipulator type
A Manipulator
is a type which can be passed into addManipulators
, containing the necessary information to position the manipulator in the context. Altered copies of these manipulators are passed into a manipulator change function as newManipulators
.
Can be constructed with triadManipulator
, linearManipulator
, and other functions below.
canBeManipulator (value) predicate
Typecheck for Manipulator
triadManipulator (definition is map) returns Manipulator
Create a manipulator represented by a triad of perpendicular arrows, aligned with the world axes, which specify a 3D position. See transformCopy
for an example.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
The position of the manipulator when the offset is |
|
|
The 3D position of the triad, relative to the |
|
|
Optional For Onshape internal use. |
fullTriadManipulator (definition is map) returns Manipulator
Create a manipulator represented by a triad of perpendicular arrows, planes, angular position handles, which specify 3D transform.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
The coordinate system the manipulator is aligned with when |
|
|
The 3D transform of the triad, relative to the |
triadManipulator (base is Vector, offset is Vector, sources) returns Manipulator
Deprecated: Use triadManipulator(map)
linearManipulator (definition is map) returns Manipulator
Create a manipulator represented by a single arrow which can move along a single axis. See extrude
for an example.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
The position of the manipulator when the offset is |
|
|
A 3D unit vector pointing on the axis on which the manipulator can be dragged. |
|
|
The positive or negative distance along |
|
|
Optional For Onshape internal use. |
|
|
ValueWithUnits | Optional The minimum offset allowed. |
|
ValueWithUnits | Optional The maximum offset allowed. |
|
ManipulatorStyleEnum | Optional |
|
string | Optional The id of the |
linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits, sources, style is ManipulatorStyleEnum) returns Manipulator
Deprecated: Use linearManipulator(map)
linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits, sources) returns Manipulator
Deprecated: Use linearManipulator(map)
linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits) returns Manipulator
Deprecated: Use linearManipulator(map)
angularManipulator (definition is map) returns Manipulator
Create a manipulator represented by a curved arrow which can move along a circumference to specify an angle, with the start and end of the rotation angle delimited by radial lines. See revolve
for an example.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | The origin of the axis to rotate around. EXAMPLE
|
|
Vector | The direction of the axis to rotate around. EXAMPLE
|
|
Vector | Point at the tip of the revolve manipulator. |
|
ValueWithUnits | Current angle value of the manipulator. |
|
Optional For Onshape internal use. |
|
|
ValueWithUnits | Optional The minimum angle allowed. |
|
ValueWithUnits | Optional The maximum angle allowed. |
|
ManipulatorStyleEnum | Optional |
|
string | Optional The id of the |
|
boolean | Optional Removes the minimum offset between the arrow and |
pointsManipulator (definition is map) returns Manipulator
A set of points which can be selected one at a time.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | Array of 3d locations for points |
|
number | The index of the currently selected point |
togglePointsManipulator (definition is map) returns Manipulator
A series of points which can each be selected individually.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
array | Array of 3d locations for points |
|
array | The indices of the currently selected points |
|
array | The indices of any non-selectable points |
flipManipulator (definition is map) returns Manipulator
Create a manipulator represented by a single arrow which flips direction when clicked.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Vector | A 3d point at the manipulator's origin EXAMPLE
|
|
Vector | A 3d vector pointing in the unflipped direction EXAMPLE
|
|
boolean | EXAMPLE
EXAMPLE
|
|
Optional For Onshape internal use. |
|
|
ManipulatorStyleEnum | Optional |
|
Vector | Optional A 3d vector for the flipped direction |
flipManipulator (base is Vector, direction is Vector, flipped is boolean, sources, style is ManipulatorStyleEnum) returns Manipulator
Deprecated: Use flipManipulator(map)
flipManipulator (base is Vector, direction is Vector, flipped is boolean, sources) returns Manipulator
Deprecated: Use flipManipulator(map)
flipManipulator (base is Vector, direction is Vector, flipped is boolean) returns Manipulator
Deprecated: Use flipManipulator(map)
addManipulators (context is Context, id is Id, manipulators is map)
Add a manipulator to this feature, which will be visible and interactable when a user edits the feature.
addManipulators
should be called within the feature function, with the offset on the added manipulator set to match the state of the definition.
Parameter | Type | Additional Info |
---|---|---|
manipulators |
map | A |
Path type
Represents a series of connected edges which form a continuous path.
Value | Type | Description |
---|---|---|
Path |
map | |
|
array | The edges that form this Path, in the order of the Path. |
|
array | An array of booleans corresponding to each edge in the path, set to |
|
boolean | Whether the Path is a closed path. |
|
Query | Optional All adjacent faces on one side of the Path. |
canBePath (value) predicate
Typecheck for Path
Distance information returned by constructPath
and evPathTangentLines
when either function is provided with referenceGeometry
Value | Type | Description |
---|---|---|
PathDistanceInformation |
map | |
|
ValueWithUnits | The distance between the the start of the |
|
boolean | Whether the start of the |
canBePathDistanceInformation (value) predicate
Typecheck for PathDistanceInformation
defaultPathDistanceInformation () returns PathDistanceInformation
Returns a PathDistanceInformation with distance
set to infinity and withinBoundingBox
set to false
reverse (path is Path) returns Path
constructPath (context is Context, edgesQuery is Query) returns Path
Construct a Path
from a Query
of edges, picking the starting point of the path based on query evaluation order for edgesQuery
Parameter | Type | Additional Info |
---|---|---|
edgesQuery |
Query | A |
constructPath (context is Context, edgesQuery is Query, options is map) returns map
Construct a Path
from a Query
of edges, optionally picking the starting point as the closest viable starting point to the supplied referenceGeometry
Parameter | Type | Additional Info |
---|---|---|
edgesQuery |
Query | |
options |
map | |
|
Optional A geometry |
|
|
ValueWithUnits | Optional Tolerance with length units indicating how close endpoints need to be to be considered part of the same path. Default is EXAMPLE
|
Return | Type | Description |
---|---|---|
|
map | |
|
Path | The resulting constructed |
|
PathDistanceInformation | A map containing the distance from the |
evPathLength (context is Context, path is Path) returns ValueWithUnits
Return type | Description |
---|---|
ValueWithUnits | The total length of the |
evPathTangentLines (context is Context, path is Path, parameters is array) returns map
Return tangent lines to a Path
using arc length parameterization.
Parameter | Type | Additional Info |
---|---|---|
path |
Path | The |
parameters |
array | An array of numbers in the range 0..1 indicating where along the |
Return | Type | Description |
---|---|---|
|
map | |
|
array | The tangent |
|
array | The indices of the edges in the |
evPathTangentLines (context is Context, path is Path, parameters is array, referenceGeometry) returns map
Return tangent lines to a Path
using arc length parameterization. By default, the 0 parameter of the Path
will be the start of the Path
. If evaluating a closed path, providing reference geometry will alter the 0 parameter to be the closest point on the Path
to the reference geometry. Providing reference geometry for a non-closed Path
will not change the parameterization of the Path
Parameter | Type | Additional Info |
---|---|---|
path |
Path | The |
parameters |
array | An array of numbers in the range 0..1 indicating where along the |
referenceGeometry |
A geometry |
Return | Type | Description |
---|---|---|
|
map | |
|
array | The tangent |
|
array | The indices of the edges in the |
|
PathDistanceInformation | A map containing the distance from the remapped 0 parameter to the center of the bounding box of |
getPathEndVertices (context is Context, path is Path) returns Query
PatternType enum
The type of pattern.
Value | Description |
---|---|
PART |
Creates copies of bodies. |
FEATURE |
Calls a feature function multiple times, first informing the |
FACE |
Creates copies of faces and attempts to merge them with existing bodies. |
MirrorType enum
applyPattern (context is Context, id is Id, definition is map, remainingTransform is Transform)
Applies the body, face, or feature pattern, given just transforms and instance names
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
PatternType | |
|
Query | Required if The faces or parts to pattern. |
|
FeatureList | Required if The features to pattern. |
|
array | An |
|
array | An |
Properties include name, appearance, material, and part number (see PropertyType
). They can be set in FeatureScript, but not read.
setProperty (context is Context, definition is map)
Sets a property on a set of bodies and/or faces. The allowed properties are listed in PropertyType
. Only APPEARANCE
and NAME
properties are supported for faces.
Note: Any properties set in this way will be overridden if they are set directly in the Part Studio (via "Rename", "Set appearance", or the properties dialog). In that case the property value provided in FeatureScript will become shadowed. For example, if a part number is set in a custom feature based on the configuration, manually editing the part number from the properties dialog will override the custom feature's part number for all configurations.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | The bodies and/or faces to apply the property to. |
|
PropertyType | The property to set. EXAMPLE
|
|
string | Required if The id of the custom property. The property id is available from your company's custom properties page. Note that this call performs no checks as to whether the custom property value is valid, so invalid property values may be recorded. |
|
A EXAMPLE
|
getProperty (context is Context, definition is map)
NOTE: This function cannot be called inside custom features. It can only be called from table functions, editing logic, and manipulator change functions. Getting properties in custom features is not possible, since features are regenerated before any user-set properties are applied.
Returns the value of a property of a single body, which can be either an Onshape property (allowed properties listed on PropertyType) or a custom property defined in company settings.
The returned value's type will correspond to the property type: A Color
if the propertyType
is APPEARANCE
, a Material
if it is MATERIAL
, a boolean if it is EXCLUDE_FROM_BOM
, and a string otherwise. CUSTOM
property's returned value will always be a string, even if the custom property is of a non-string type.
Parameter | Type | Additional Info |
---|---|---|
definition |
map | |
|
Query | A single body the property applies to. |
|
PropertyType | The property to get. EXAMPLE
|
|
string | Required if The id of the custom property. The property id is available from your company's custom properties page. |
Color type
Represents a color as red, green, blue, and alpha transparency components, each between 0 and 1 (inclusive).
canBeColor (value) predicate
Typecheck for Color
color (red is number, green is number, blue is number, alpha is number) returns Color
Create a Color
from RGBA values, each between 0 and 1 (inclusive)
color (red is number, green is number, blue is number) returns Color
Create an opaque Color
from RGB values, each between 0 and 1 (inclusive)
Material type
Represents a material.
canBeMaterial (value) predicate
Typecheck for Material
material (name is string, density is ValueWithUnits)
Constructs a material with a name and a density.
Parameter | Type | Additional Info |
---|---|---|
name |
string | The displayed name of the material. |
density |
ValueWithUnits | EXAMPLE
|
Pretty printing and toString methods
toString (value) returns string
Return a string representation of any value.
Overloads of this method are found for many standard and custom types in this and other modules. When overloaded, the toString
method will be called inside print
and println
, allowing users to change how custom types are printed.
toString (value is string) returns string
toString (value is array) returns string
toString (value is map) returns string
print (value)
Print a message to the FeatureScript notices pane.
This has no effect on model state or rendering.
println (value)
Print a message to the FeatureScript notices pane, followed by a newline.
This has no effect on model state or rendering.