Modeling
Math
Utilities
Onshape features
enums

The Onshape Standard Library

Modeling

geometry

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.

context

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

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 is id

EXAMPLE

id + "foo" + "bar" represents an id named "bar" whose parent equals id + "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

newId () returns 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 to 1, on the context.
ParameterTypeAdditional Info
value

Can be any value, including an array or map with many elements.

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.

libraryLanguageVersion ()

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.)

geomOperations

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.

opBoolean (context is Context, id is Id, definition is map)

Performs a boolean operation on multiple solid bodies.

ParameterTypeAdditional Info
definition map
  • tools
Query

The tool bodies.

  • targets
Query

Required if OperationType is SUBTRACTION or SUBTRACT_COMPLEMENT, or if targetsAndToolsNeedGrouping is true.

The target bodies.

  • operationType
BooleanOperationType

The boolean operation to perform.

EXAMPLE

BooleanOperationType.UNION will merge any tool bodies that intersect or abut. When several bodies merge, the identity of the tool that appears earliest in the query is preserved (in particular, part color and part name are taken from it).

EXAMPLE

BooleanOperationType.SUBTRACTION will remove the union of all tools bodies from every target body.

EXAMPLE

BooleanOperationType.INTERSECTION will create the intersection of all tool bodies.

EXAMPLE

BooleanOperationType.SUBTRACT_COMPLEMENT will remove the complement of the union of all tool bodies from every target body.
  • targetsAndToolsNeedGrouping
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 false.

  • keepTools
boolean

Optional

If true, the tools do not get consumed by the operation. Default is false.

  • matches
array

Optional

Array of topology matches between tools and targets. Each matching element is a map with fields topology1, topology2 and matchType; where topology1 and topology2 are a pair of matching edges or faces and matchType is the type of match TopologyMatchType between them.

  • recomputeMatches
boolean

Optional

If true, matches will be recomputed and specified matches will be used only for surface alignment purposes (for surface boolean). Defaults to false.

opChamfer (context is Context, id is Id, definition is map)

Adds a chamfer to given edges and faces.

ParameterTypeAdditional Info
definition map
  • entities
Query

Edges and faces to chamfer.

  • chamferType
ChamferType

Determines where the new edges of the chamfer are positioned.

EXAMPLE

ChamferType.EQUAL_OFFSETS places both new edges width away from each original edge.

EXAMPLE

ChamferType.TWO_OFFSETS places edges width1 and width2 away.

EXAMPLE

ChamferType.OFFSET_ANGLE places one edge width away, and chamfers at an angle from that edge.
  • width
ValueWithUnits

Required if chamferType is EQUAL_OFFSETS or OFFSET_ANGLE.

EXAMPLE

0.2 * inch
  • width1
ValueWithUnits

Required if chamferType is TWO_OFFSETS.

  • width2
ValueWithUnits

Required if chamferType is TWO_OFFSETS.

  • angle
ValueWithUnits

Required if chamferType is OFFSET_ANGLE.

  • oppositeDirection
boolean

Required if chamferType is OFFSET_ANGLE or TWO_OFFSETS.

true to reverse the two edges.

  • tangentPropagation
boolean

Optional

true to propagate the chamfer along edges tangent to those passed in. Defaults to false.

opDeleteBodies (context is Context, id is Id, definition is map)

Deletes bodies from the context.

ParameterTypeAdditional Info
definition map
  • entities
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.

ParameterTypeAdditional Info
definition map
  • deleteFaces
Query

Faces to delete.

  • includeFillet
boolean

true to also delete fillets adjacent to the input faces.

  • capVoid
boolean

If capVoid is true and the deleted face cannot be filled by extending the surrounding faces, will attempt to replace the face with a planar face.

  • leaveOpen
boolean

If leaveOpen is true the void from deleting faces is left open, potentially creating a surface out of a solid body.

opDraft (context is Context, id is Id, definition is map)

Applies a given draft angle to faces.

ParameterTypeAdditional Info
definition map
  • neutralPlane
Query

The face defining the neutral plane. The intersection of the drafted faces and the neutral plane remains unchanged.

  • pullVec
Vector

The 3d direction relative to which the draft is applied.

EXAMPLE

evPlane(context, {"face" : neutralPlane}).normal will draft uniformly away from the neutral plane.
  • draftFaces
Query

The faces to draft.

  • angle
ValueWithUnits

The draft angle, must be between 0 and 89 degrees.

EXAMPLE

3 * degree
  • tangentPropagation
boolean

Optional

true to propagate draft across tangent faces. Default is false.

  • reFillet
boolean

Optional

true to attempt to defillet draft faces before the draft and reapply the fillets after. Default is false.

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.

ParameterTypeAdditional Info
definition map
  • entities
Query

Edges and faces to extrude.

  • direction
Vector

The 3d direction in which to extrude.

EXAMPLE

evOwnerSketchPlane(context, {"entity" : entities}).normal to extrude perpendicular to the owner sketch

EXAMPLE

evPlane(context, {"face" : entities}).normal to extrude perpendicular to the first planar entity
  • endBound
BoundingType

The type of bound at the end of the extrusion. Cannot be SYMMETRIC.

EXAMPLE

BoundingType.BLIND
  • endDepth
ValueWithUnits

Required if endBound is BLIND.

How far from the entities to extrude.

EXAMPLE

1 * inch
  • endBoundEntity
Query

Required if endBound is UP_TO_SURFACE or UP_TO_BODY.

The face or body that provides the bound.

  • endTranslationalOffset
ValueWithUnits

Optional

The translational offset between the extrude end cap and the end bound entity. The direction vector for this is the same as direction: negative values pull the end cap away from the bound entity when endDepth is positive. endOffset will only have an effect if endBound is UP_TO_SURFACE, UP_TO_BODY, or UP_TO_NEXT.

  • startBound
BoundingType

Optional

The type of start bound. Default is for the extrude to start at entities. Cannot be SYMMETRIC.

  • isStartBoundOpposite

Required if is UP_TO_SURFACE, UP_TO_BODY, or UP_TO_NEXT.

Whether the startBound extends in the opposite direction from the profile as the endBound. Defaults to true if not supplied.

  • startDepth
ValueWithUnits

Required if startBound is BLIND.

How far from the entities to start the extrude. The direction vector for this is the negative of direction: positive values make the extrusion longer when endDepth is positive.

  • startBoundEntity
Query

Required if startBound is UP_TO_SURFACE or UP_TO_BODY.

The face or body that provides the bound.

  • startTranslationalOffset
ValueWithUnits

Optional

The translational offset between the extrude start cap and the start bound entity. The direction vector for this is the negative of direction: negative values pull the end cap away from the bound entity when startDepth is positive. startOffset will only have an effect if startBound is UP_TO_SURFACE, UP_TO_BODY, or UP_TO_NEXT.

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.

ParameterTypeAdditional Info
definition map
  • entities
Query

Edges and faces to fillet.

  • radius
ValueWithUnits

The fillet radius.

EXAMPLE

1 * inch
  • tangentPropagation
boolean

Optional

true to propagate the fillet along edges tangent to those passed in. Default is false.

  • crossSection
FilletCrossSection

Optional

Fillet cross section. One of CIRCULAR, CONIC, CURVATURE. Default is CIRCULAR.

  • rho
number

Required if crossSection is CONIC.

A number between 0 and 1, specifying the Rho value of a conic fillet

EXAMPLE

0.01 creates a flat, nearly-chamfered shape.

EXAMPLE

0.99 creates a pointed, nearly-unchanged shape.
  • magnitude
number

Required if crossSection is CURVATURE.

A number between 0 and 1, specifying the magnitude of curvature match.

  • isVariable
boolean

Optional

Fillet controls can be varied at vertices via vertexSettings. Default is false.

  • vertexSettings
array

Optional

Array of fillet settings at specified vertices.

  • createDetachedSurface
boolean

Optional

Operation does not modify the body of the selected edges, but results in surface geometry of fillet. Default is false.

opFitSpline (context is Context, id is Id, definition is map)

Creates a 3D cubic spline curve through an array of 3D points.

ParameterTypeAdditional Info
definition map
  • points
array

An array of Vectors with length units for the spline to interpolate. If the first point is the same as the last point, the spline is closed.

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
]
  • startDerivative
Vector

Optional

A Vector with length units that specifies the derivative at the start of the resulting spline (according to the arcLengthParameterization set to false). Ignored if spline is closed.

  • endDerivative
Vector

Optional

A Vector with length units that specifies the derivative at the end of the resulting spline. Ignored if spline is closed.

  • start2ndDerivative
Vector

Optional

A Vector with length units that specifies the second derivative at the start of the resulting spline. Ignored if spline is closed, or if startDerivative is not defined

  • end2ndDerivative
Vector

Optional

A Vector with length units that specifies the second derivative at the end of the resulting spline. Ignored if spline is closed, or if endDerivative is not defined

opHelix (context is Context, id is Id, definition is map)

Creates a helical and possibly spiral curve.

ParameterTypeAdditional Info
definition map
  • direction
Vector

The direction of the helix axis.

EXAMPLE

vector(0, 0, 1)
  • axisStart
Vector

A point on the helix axis.

EXAMPLE

vector(0, 0, 0) * inch
  • startPoint
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 interval is 0.

EXAMPLE

vector(1, 0, 0) * inch
  • interval
Vector

An array of two numbers denoting the interval of the helix in terms of revolution counts.

EXAMPLE

[0, 10] will create a curve with 10 revolutions.
  • clockwise
boolean

EXAMPLE

true if this is a clockwise helix when viewed along direction.
  • helicalPitch
ValueWithUnits

Distance along the axis between successive revolutions.

EXAMPLE

0.1 * inch will create a helix with 10 revolutions per inch.

EXAMPLE

0 * inch produces a planar Archimedean spiral.
  • spiralPitch
ValueWithUnits

Change in radius between successive revolutions.

EXAMPLE

0 * inch produces a helix that lies on a cylinder.

opImportForeign (context is Context, id is Id, definition is map)

Brings foreign geometry into the context. This function is used for importing uploaded parts.

ParameterTypeAdditional Info
definition map
  • foreignId
string

The foreign data id (dataId from an imported blob tab).

  • flatten
boolean

Optional

Whether to flatten assemblies; defaults to false.

  • yAxisIsUp
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.

  • isModifiable
boolean

Optional

Whether the imported data is modifiable (default) or not.

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.

ParameterTypeAdditional Info
definition map
  • profileSubqueries
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.

  • guideSubqueries
array

Optional

An array of queries for guide curves. Each guide curve should intersect each profile once.

  • vertices
Query

Optional

An array of vertices, one per profile, used in alignment of profiles.

  • makePeriodic
boolean

Optional

Defaults to false. A closed guide creates a periodic loft regardless of this option.

  • bodyType
ToolBodyType

Optional

Whether this is a solid (default) or a surface loft.

  • derivativeInfo
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

[ { "profileIndex" : 0, "vector" : vector(1, 0, 0), "magnitude" : 2., "tangentToPlane" : true}, { "profileIndex" : 1, "matchCurvature" : true, "adjacentFaces" : qFaces }] The first map would constrain the resulting loft at the start profile to be tangent to plane with normal vector(1,0,0) and magnitude 2. The second map constrains the loft at the end profile to match the curvature of faces defined by the query qFaces.

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.

ParameterTypeAdditional Info
definition map
  • coordSystem
CoordSystem

The mate connector coordinate system.

  • owner
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)

Bring all of the information from contextFrom into context. This is used, for example, for the Derived feature.

ParameterTypeAdditional Info
context Context

The target context.

definition map
  • contextFrom
Context

The source context. It is rendered unusable by this operation.

EXAMPLE

MyPartStudio::build()

opModifyFillet (context is Context, id is Id, definition is map)

This is a direct editing operation that modifies or deletes fillets.

ParameterTypeAdditional Info
definition map
  • faces
Query

The fillets to modify.

  • modifyFilletType
ModifyFilletType

Whether to change the fillet radii or remove them altogether.

  • radius
ValueWithUnits

Required if modifyFilletType is CHANGE_RADIUS.

The new radius.

  • reFillet
boolean

Required if modifyFilletType is CHANGE_RADIUS.

true to reapply adjacent fillets. Default is false.

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.

ParameterTypeAdditional Info
definition map
  • moveFaces
Query

The faces to transform.

  • transform
Transform

The transform to apply to the face.

EXAMPLE

transform(vector(0, 0, 1) * inch) will translate the face 1 inch along the world's z-axis.
  • reFillet
boolean

Optional

true to attempt to defillet moveFaces prior to the move and reapply the fillet after. Default is false.

  • mergeFaces
boolean

Optional

true to remove redundant edges from moveFaces. Default is true.

opOffsetFace (context is Context, id is Id, definition is map)

This is a direct editing operation that offsets one or more faces.

ParameterTypeAdditional Info
definition map
  • moveFaces
Query

The faces to offset.

  • offsetDistance
ValueWithUnits

The positive or negative distance by which to offset.

EXAMPLE

0.1 * inch will offset the face 0.1 inches, normal to the face.
  • reFillet
boolean

Optional

true to attempt to defillet moveFaces prior to the offset and reapply the fillet after. Default is false.

  • mergeFaces
boolean

Optional

true to remove redundant edges from moveFaces. Default is true.

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.

ParameterTypeAdditional Info
definition map
  • entities
Query

Bodies and faces to pattern.

  • transforms
array

An array of Transforms to apply to entities. The transforms do not have to be rigid.

  • instanceNames
array

An array of distinct non-empty strings the same size as transforms to identify the patterned entities.

opPlane (context is Context, id is Id, definition is map)

Creates a construction plane.

ParameterTypeAdditional Info
definition map
  • plane
Plane

The plane to create.

EXAMPLE

plane(vector(0, 0, 6) * inch, vector(0, 0, 1))
  • width
ValueWithUnits

The side length of the construction plane, as it is initially displayed.

  • height
ValueWithUnits

The side length of the construction plane, as it is initially displayed.

  • defaultType
DefaultPlaneType

Optional

For Onshape internal use.

opSphere (context is Context, id is Id, definition is map)

Creates a sphere.

ParameterTypeAdditional Info
definition map
  • radius
ValueWithUnits

The radius of the sphere.

EXAMPLE

1 * inch
  • center
Vector

The location of the center of the sphere.

EXAMPLE

vector(1, 1, 1) * inch

opPoint (context is Context, id is Id, definition is map)

Creates a construction point (a BodyType.POINT with one vertex).

ParameterTypeAdditional Info
definition map
  • point
Vector

The location of the point.

EXAMPLE

vector(0, 0, 1) * inch
  • origin
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.

ParameterTypeAdditional Info
definition map
  • replaceFaces
Query

The faces whose geometry to replace.

  • templateFace
Query

The face whose geometry to use as the replacement.

  • offset
ValueWithUnits

Optional

The positive or negative distance by which to offset the resulting face.

  • oppositeSense
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 false.

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.

ParameterTypeAdditional Info
definition map
  • entities
Query

The edges and faces to revolve.

  • axis
Line

The axis around which to revolve.

EXAMPLE

line(vector(0, 0, 0) * inch, vector(0, 0, 1))
  • angleForward
ValueWithUnits

The angle where the revolve ends relative to entities. Normalized to the range \[0, 2 PI).

EXAMPLE

30 * degree
  • angleBack
ValueWithUnits

Optional

The angle where the revolve starts relative to entities. Normalized to the range \[0, 2 PI). If angleForward == angleBack, the revolve is a full (360-degree) revolve. Defaults to 0.

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.

ParameterTypeAdditional Info
definition map
  • entities
Query

The faces to shell and solid bodies to hollow.

  • thickness
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 and sheet bodies with the given sheet body.

ParameterTypeAdditional Info
definition map
  • targets
Query

The solid and sheet bodies to split.

  • tool
Query

The sheet body or construction plane to cut with. If a planar face is passed in, the split will extend the plane infinitely.

  • keepTools
boolean

Optional

If false (default), the tool is deleted.

  • keepType
SplitOperationKeepType

Optional

Controls which pieces to keep. Default is KEEP_ALL.

opSplitFace (context is Context, id is Id, definition is map)

Split faces with the given edges or faces.

ParameterTypeAdditional Info
definition map
  • faceTargets
Query

The faces to split.

  • edgeTools
Query

Optional

The edges to cut with.

  • direction
Vector

Required if there are edge tools.

The projection direction.

  • bodyTools
Query

Optional

The bodies to cut with.

  • planeTools
Query

Optional

The planes to cut with.

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.

ParameterTypeAdditional Info
definition map
  • profiles
Query

Edges and faces to sweep.

  • path
Query

Edges that comprise the path along which to sweep. The edges can be in any order but must form a connected path.

  • keepProfileOrientation
boolean

Optional

If true, the profile maintains its original orientation as it is swept. If false (default), the profile rotates to remain normal to the path.

  • lockFaces
Query

Optional

Keep profile aligned to the normals of these faces.

opThicken (context is Context, id is Id, definition is map)

Thicken sheet bodies and faces into solid bodies.

ParameterTypeAdditional Info
definition map
  • entities
Query

The sheet bodies and faces to thicken.

  • thickness1
ValueWithUnits

The distance by which to thicken in the direction along the normal.

  • thickness2
ValueWithUnits

The distance by which to thicken in the opposite direction.

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.

ParameterTypeAdditional Info
definition map
  • bodies
Query

The bodies to transform.

  • transform
Transform

The transform to apply.

EXAMPLE

transform(vector(0, 0, 1) * inch) will translate the body 1 inch along the world's z-axis.

EXAMPLE

rotationAround(myLine, 30 * degree) will rotate around a Line object.

EXAMPLE

scaleUniformly(factor) will scale uniformly about the origin.

EXAMPLE

scaleUniformly(factor, point) will scale uniformly about a given point.

EXAMPLE

toWorld(cSys) will (somewhat counterintuitively) perform a transform such that geometry on the world's origin and axes will move to the cSys origin and axes.

EXAMPLE

fromWorld(cSys) will (somewhat counterintuitively) perform a transform such that geometry on the cSys origin and axes will move to the world origin and axes.

EXAMPLE

transform2 * transform1 will perform transform1, followed by transform2.

opCreateOutline (context is Context, id is Id, definition is map)

Generates surfaces representing the outlines of parts or surfaces projected onto a surface

ParameterTypeAdditional Info
definition map
  • tools
Query

The tool parts or surfaces

  • target
Query

The face whose surface will be used to create outline. Currently only planes, cylinders or extruded surfaces are supported.

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.

ParameterTypeAdditional Info
definition map
  • bSplineCurve
BSplineCurve

The definition of the spline.

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.

ParameterTypeAdditional Info
definition map
  • edges
Query

The edges to be extracted.

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.

ParameterTypeAdditional Info
definition map
  • edgesG0
Query

The edges with position constraints.

  • edgesG1
Query

The edges with tangency constraints.

  • edgesG2
Query

The edges with curvature constraints.

  • guideVertices
Query

The vertices the resulting surface is expected to interpolate.

  • showIsocurves
boolean

Optional

Show graphical representation of a subset of isoparameteric curves of the created surface. Default false.

primitives

cube (context is Context, id is Id, definition is map)

Create a cube of a specified size, with one corner on the origin.

ParameterTypeAdditional Info
definition map
  • sideLength
ValueWithUnits

EXAMPLE

1 * inch

sphere (context is Context, id is Id, definition is map)

Feature creating a sphere. Internally, calls opSphere.

ParameterTypeAdditional Info
definition map
  • center
Query

A vertex query marking the sphere's center.

  • radius
ValueWithUnits

EXAMPLE

1 * inch

fCuboid (context is Context, id is Id, definition is map)

Create a simple rectangular prism between two specified corners.

ParameterTypeAdditional Info
definition map
  • corner1
Vector

EXAMPLE

vector(0, 0, 0) * inch
  • corner2
Vector

EXAMPLE

vector(1, 1, 1) * inch

fCylinder (context is Context, id is Id, definition is map)

Create a simple cylindrical solid between two points, with a specified radius.

ParameterTypeAdditional Info
definition map
  • topCenter
Vector

A 3D length vector in world space.

EXAMPLE

vector(0, 0, 0) * inch
  • bottomCenter
Vector

A 3D length vector in world space.

EXAMPLE

vector(1, 1, 1) * inch
  • radius
ValueWithUnits

EXAMPLE

1 * inch

fCone (context is Context, id is Id, definition is map)

Create a solid cone, possibly truncated.

ParameterTypeAdditional Info
definition map
  • topCenter
Vector

EXAMPLE

vector(1, 1, 1) * inch
  • bottomCenter
Vector

EXAMPLE

vector(0, 0, 0) * inch
  • topRadius
ValueWithUnits

The radius at the top center.

EXAMPLE

1 * inch
  • bottomRadius
ValueWithUnits

The radius at the bottom center.

EXAMPLE

0 * inch produces a standard, non-truncated cone.

fEllipsoid (context is Context, id is Id, definition is map)

Create an ellipsoid (that is, a sphere scaled independently along the three major axes).

ParameterTypeAdditional Info
definition map
  • center
Vector

EXAMPLE

vector(0, 0, 0) * inch
  • radius
Vector

The three radii, as measured along the x, y, and z axes.

EXAMPLE

vector(0.5 * inch, 1 * inch, 2 * inch)

sketch

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 Vectors, 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, which results in the new wire bodies and sketch regions being added to the context. These new entities can be queried for and used in 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.

ParameterTypeAdditional Info
value map
  • sketchPlane
Query

A Query for a single, planar entity.

EXAMPLE

qCreatedBy(makeId("Top"), EntityType.FACE) to sketch on default "Top" plane.

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.

ParameterTypeAdditional Info
value map
  • sketchPlane
Plane

EXAMPLE

plane(vector(0, 0, 0) * inch, vector(0, 0, 1)) to sketch on the world XY plane.

skSolve (sketch is Sketch)

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.

ParameterTypeAdditional Info
value map
  • position
Vector

EXAMPLE

vector(0, 1) * inch
ReturnTypeDescription
map
  • pointId

skLineSegment (sketch is Sketch, lineId is string, value is map) returns map

Add a line segment to a sketch.

ParameterTypeAdditional Info
value map
  • start
Vector

EXAMPLE

vector(0, 0) * inch
  • end
Vector

EXAMPLE

vector(1, 1) * inch
  • construction
boolean

Optional

true for a construction line

ReturnTypeDescription
map
  • startId
  • endId

skText (sketch is Sketch, textId is string, value is map) returns map

Add a text rectangle to a sketch.

ParameterTypeAdditional Info
value map
  • text
string

A string of text to write. May contain newlines.

  • fontName
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

"OpenSans-Regular.ttf" Sans-serif font. Default if no match is found.

EXAMPLE

"AllertaStencil-Regular.ttf" Stencil font. No bold/italic options.

EXAMPLE

"Arimo-Regular.ttf" Sans-serif font.

EXAMPLE

"DroidSansMono-Regular.ttf" Monospaced sans-serif font. No bold/italic options.

EXAMPLE

"NotoSans-Regular.ttf" Sans-serif font.

EXAMPLE

"NotoSansCJKjp-Regular.otf" Japanese font. No italic options.

EXAMPLE

"NotoSansCJKkr-Regular.otf" Korean font. No italic options.

EXAMPLE

"NotoSansCJKsc-Regular.otf" Chinese (simplified) font. No italic options.

EXAMPLE

"NotoSansCJKtc-Regular.otf" Chinese (traditional) font. No italic options.

EXAMPLE

"NotoSans-Regular.ttf" Serif font.

EXAMPLE

"RobotoSlab-Regular.ttf" Sans-serif font. No italic options.

EXAMPLE

"Tinos-Regular.ttf" Serif font. Metrically compatible with Times New Roman.
  • construction
boolean

Optional

true for a construction line

  • mirrorHorizontal
boolean

Optional

true for flipping text horizontally

  • mirrorVertical
boolean

Optional

true for flipping text vertically

ReturnTypeDescription
map
  • textId

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).

ParameterTypeAdditional Info
value map
  • blobInfo
map

EXAMPLE

BLOB_DATA will use the image from an image file imported into this Feature Studio.

EXAMPLE

MyImage::BLOB_DATA will use an image imported into the namespace MyImage (e.g. using MyImage::import(...))
  • firstCorner
Vector

One corner of the rectangle into which the image will be placed.

EXAMPLE

vector(0, 0) * inch
  • secondCorner
Vector

The other corner of the rectangle into which the image will be placed.

EXAMPLE

vector(1, 1) * inch
ReturnTypeDescription
map
  • imageId

skCircle (sketch is Sketch, circleId is string, value is map) returns map

Add a circle to a sketch.

ParameterTypeAdditional Info
value map
  • center
Vector

EXAMPLE

vector(0, 0) * inch
  • radius
ValueWithUnits

EXAMPLE

1 * inch
  • construction
boolean

Optional

true for a construction line

ReturnTypeDescription
map
  • centerId

skEllipse (sketch is Sketch, ellipseId is string, value is map) returns map

Add an ellipse to a sketch.

ParameterTypeAdditional Info
value map
  • center
Vector

EXAMPLE

vector(0, 0) * inch
  • majorRadius
Vector

EXAMPLE

2 * inch
  • minorRadius
Vector

EXAMPLE

1 * inch
  • construction
boolean

Optional

true for a construction line

ReturnTypeDescription
map
  • centerId

skArc (sketch is Sketch, arcId is string, value is map) returns map

Add an arc through three points to a sketch.

ParameterTypeAdditional Info
value map
  • start
Vector

EXAMPLE

vector(1, 0) * inch
  • mid
Vector

EXAMPLE

vector(0, 1) * inch
  • end
Vector

EXAMPLE

vector(-1, 0) * inch
  • construction
boolean

Optional

true for a construction line

ReturnTypeDescription
map
  • startId
  • endId

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.

ParameterTypeAdditional Info
value map
  • center
Vector

EXAMPLE

vector(0, 0) * inch
  • majorAxis
Vector

The direction, in sketch coordinates, in which the major axis of the ellipse lies.

EXAMPLE

vector(1, 0) * inch
  • minorRadius
ValueWithUnits

A non-negative value with length units.

EXAMPLE

1 * inch
  • majorRadius
ValueWithUnits

A non-negative value with length units. Does not need to be greater than the minor radius.

EXAMPLE

2 * inch
  • startParameter
number

The parameter of the start point.

EXAMPLE

0
  • endParameter
number

The parameter of the end point.

EXAMPLE

0.25
  • construction
boolean

Optional

true for a construction line

ReturnTypeDescription
map
  • startId
  • endId

skFitSpline (sketch is Sketch, splineId is string, value is map)

Create an interpolated spline through the given points.

ParameterTypeAdditional Info
value map
  • points

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
]
  • construction
boolean

Optional

true for a construction line

  • startDerivative
Vector

Optional

A 2D Vector with length units that specifies the derivative at the start of the resulting spline. Ignored if spline is closed.

  • endDerivative
Vector

Optional

A 2D Vector with length units that specifies the derivative at the end of the resulting spline. Ignored if spline is closed.

skRectangle (sketch is Sketch, rectangleId is string, value is map)

Add a rectangle (four line segments, properly constrained) to a sketch.

ParameterTypeAdditional Info
value map
  • firstCorner
Vector

EXAMPLE

vector(0, 0) * inch
  • secondCorner
Vector

EXAMPLE

vector(1, 1) * inch
  • construction
boolean

Optional

true for a construction line

skRegularPolygon (sketch is Sketch, polygonId is string, value is map)

Add a regular polygon to the sketch. Unconstrained.

ParameterTypeAdditional Info
value map
  • center
Vector

EXAMPLE

vector(0, 0) * inch
  • firstVertex
Vector

Distance to the center determines the radius.

EXAMPLE

vector(0, 1) * inch
  • sides
number

Number of polygon sides. Must be an integer 3 or greater.

  • construction
boolean

Optional

true for a construction line

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.

ParameterTypeAdditional Info
value map
  • points
array

An array of points, each a Vector of two lengths. If first and last point are the same, the polyline is closed.

EXAMPLE

[
    vector( 0,  0) * inch,
    vector( 0, -1) * inch,
    vector( 1,  1) * inch,
    vector(-1,  0) * inch,
    vector( 0,  0) * inch
]
  • construction
boolean

Optional

true for a construction line. Default false.

  • constrained
boolean

Optional

true if constraints should be created. Default false.

skConstraint (sketch is Sketch, constraintId is string, value is map)

Add a constraint.

ParameterTypeAdditional Info
value map
  • constraintType
ConstraintType
  • length
ValueWithUnits

Optional

For constraints that require a length. Must have length units.

  • angle
ValueWithUnits

Optional

For constraints that require a angle. Must have angle units.

query

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.

ValueTypeDescription
Query map
  • queryType
QueryType
  • entityType
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 EntityTypes.

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

qBodyType

ValueDescription
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. For filtering selections only.

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)

ValueDescription
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

GeometryType enum

Specifies the geometric type of queried entities.

See also

qGeometry

ValueDescription
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

OTHER_SURFACE

Any two-dimensional entity which is not described

MESH

A surface or a body that contains surface that is a mesh above (e.g. the side of an arbitrary extrude, revolve, or loft)

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

qConstructionFilter

ValueDescription
YES

Matches only entities which are created for construction

NO

Matches only entities which are not created for construction

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;
ValueDescription
YES

Allow meshes

NO

Disallow meshes

AllowFlattenedGeometry enum

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;
ValueDescription
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;
ValueDescription
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;
ValueDescription
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;
ValueDescription
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;
ValueDescription
YES

Allow edge points

NO

Disallow edge points

MeshGeometry enum

Specifies whether the entities are mesh geometries.

See also

qMeshGeometryFilter

ValueDescription
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;
ValueDescription
YES

Matches only entities which are part of a sketch

NO

Matches only entities which are not part of a sketch

EdgeTopology enum

Specifies the topology of an edge entity.

Can be used in a filter on a query parameter to only allow certain selections:

annotation { "Name" : "Surface edges", "Filter" : EntityType.EDGE && EdgeTopology.LAMINAR }
definition.edges is Query;
ValueDescription
LAMINAR

An edge adjacent to one surface (e.g. the edge of a surface extrude).

TWO_SIDED

An edge which joins two faces (e.g. the edge of a cube).

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;
ValueDescription
ALLOWS_AXIS

Equivalent to GeometryType.LINE || GeometryType.CIRCLE || GeometryType.ARC || GeometryType.CYLINDER and can be processed with evAxis

ALLOWS_DIRECTION

Equivalent to QueryFilterCompound.ALLOWS_AXIS || GeomtryType.PLANE and can be processed with extractDirection

CompareType enum

Specifies a method of comparing two items.

See also

qFilletFaces

ValueDescription
EQUAL
LESS
LESS_EQUAL
GREATER
GREATER_EQUAL

qNothing () returns Query

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.

ParameterTypeAdditional 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.

qAllModifiableSolidBodies () returns Query

A query for all solid bodies that do not have mesh geometry or in context geometry.

qNthElement (subquery is Query, n is number) returns Query

A query for an element of a subquery at a specified index

ParameterTypeAdditional Info
subquery Query

A query which resolves to at least n+1 entities

n number

Zero-based index of element in subquery.

EXAMPLE

0 indicates the first element

EXAMPLE

-1 indicates the last element

qEntityFilter (subquery is Query, entityType is EntityType) returns Query

A query for entities of a subquery which match a given EntityType.

qAttributeFilter (subquery is Query, attributePattern) returns Query

A query for entities of a subquery which have been assigned an attribute matching a given attributePattern.

See also

getAttributes

qAttributeQuery (attributePattern) returns Query

A query for all entities which have been assigned an attribute matching a given attributePattern. Equivalent to qAttributeFilter(qEverything(), attributePattern)

qCorrespondingInFlat (subquery is Query) returns Query

A query for entities in sheet metal flattened body corresponding to those in folded body defined by subquery

ParameterTypeAdditional Info
subquery Query

A query which resolves to entities in folded sheet metal body

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.

ParameterTypeAdditional Info
featureId Id

The Id of the specified feature.

EXAMPLE

id + "extrude1"
entityType EntityType

Optional

qCreatedBy (featureId is Id) returns Query

qTransient (id is TransientId) returns Query

A transient query, which refers to a single entity in the context. All transient queries are only valid until the context is modified again.

This constructor should not be used directly. To obtain a list of transient queries for specific entities, simply pass any other query into evaluateQuery.

qDependency (subquery is Query) returns Query

A query for the true dependency of the query. 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 (subquery is Query) returns Query

A query for the true dependency of the query, 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).

qCapEntity (featureId is Id, isStartCap is boolean) returns Query

A query for start/end cap entities created by featureId. Cap entities are produced by extrude, revolve, sweep and loft features

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.

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.

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.

ParameterTypeAdditional Info
entityType EntityType

Optional

qOwnedByBody (body is Query) returns Query

qOwnedByBody (subquery is Query, body is Query) returns Query

A query for all of the entities which match a subquery, and belong to the specified body or bodies.

qOwnerBody (query is Query) returns Query

A query for each part that any entities in the query belong to.

qSourceMesh (query is Query) returns Query

A query for each mesh that the mesh vertices in the query belong to.

qVertexAdjacent (query is Query, entityType is EntityType) returns Query

A query for all entities of specified EntityType that share a vertex with any entities that match the input query.

EXAMPLE

qVertexAdjacent(vertex, EntityType.EDGE) matches all edges adjacent to the given vertex.

EXAMPLE

qVertexAdjacent(face, EntityType.VERTEX) matches all vertices adjacent to the given face.
ParameterTypeAdditional Info
entityType EntityType

The type of the resulting entities.

EXAMPLE

EntityType.VERTEX

qEdgeAdjacent (query is Query, entityType is EntityType) returns Query

A query for all entities of specified EntityType that share an edge with any entities that match the input query.

EXAMPLE

qEdgeAdjacent(edge, EntityType.FACE) matches all faces adjacent to the given edge.

EXAMPLE

qEdgeAdjacent(face, EntityType.EDGE) matches all edges adjacent to the given face.

More complicated queries are also possible. For instance to match edges that bound a set faces on a solid body:

const adjacentFaces = qSubtraction(qEdgeAdjacent(faces, EntityType.FACE), faces);
const boundary = qIntersection([qEdgeAdjacent(faces, EntityType.EDGE),
                                qEdgeAdjacent(adjacentFaces, EntityType.EDGE)]);
ParameterTypeAdditional Info
entityType EntityType

The type of the resulting entities.

EXAMPLE

EntityType.EDGE

qEdgeTopologyFilter (subquery is Query, edgeTopologyType is EdgeTopology) returns Query

A query for edges of a subquery which match a given EdgeTopology.

qGeometry (subquery is Query, geometryType is GeometryType) returns Query

A query for all entities of a specified GeometryType matching a subquery.

qBodyType (subquery is Query, bodyType is BodyType) returns Query

A query for all entities of a specified BodyType matching a subquery.

qBodyType (subquery is Query, bodyTypes is array) returns Query

A query for all entities of a subquery with any of a list of BodyTypes.

ParameterTypeAdditional Info
bodyTypes array

An array of BodyTypes.

qConstructionFilter (subquery is Query, constructionFilter is ConstructionObject) returns Query

A query for all construction entities, or all non-construction entities, matching a subquery.

See also

ConstructionObject

qMeshGeometryFilter (subquery is Query, meshGeometryFilter is MeshGeometry) returns Query

Depending on meshGeometryFilter, a query for filtering out all mesh entities or allowing only mesh entities matching a subquery. A body is considered a "mesh entity" if any of its faces or edges have mesh geometry.

See also

MeshGeometry

qModifiableEntityFilter (subquery is Query) returns Query

A geometry is considered not "modifiable" if it is a in context entity.

See also

ModifiableEntityOnly

qSketchFilter (subquery is Query, sketchObjectFilter is SketchObject) returns Query

A query for all sketch entities, or all non-sketch entities, matching a subquery.

qParallelPlanes (subquery is Query, referencePlane is Plane, allowAntiparallel is boolean) returns Query

A query for all planar face entities that are parallel to the referencePlane.

ParameterTypeAdditional Info
referencePlane Plane

The plane to reference when checking for parallelism.

allowAntiparallel boolean

Whether to also return entities that are antiparallel.

qParallelPlanes (subquery is Query, referencePlane is Plane) returns Query

A query for all planar face entities that are parallel to the referencePlane.

ParameterTypeAdditional Info
referencePlane Plane

The plane to reference when checking for parallelism.

qParallelPlanes (subquery is Query, normal is Vector, allowAntiparallel is boolean) returns Query

A query for all planar face entities that are parallel to a plane specified by the normal vector.

ParameterTypeAdditional Info
normal Vector

The normal vector to reference when checking for parallelism.

allowAntiparallel boolean

Whether to also return entities that are antiparallel.

qPlanesParallelToDirection (subquery is Query, direction is Vector) returns Query

A query for all planar faces that are parallel to the given direction vector (i.e., the plane normal is perpendicular to direction).

qFacesParallelToDirection (subquery is Query, direction is Vector) returns Query

A query for all faces 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 (subquery is Query, normal is Vector) returns Query

A query for all planar face entities that are parallel to a plane specified by the normal vector.

ParameterTypeAdditional Info
normal Vector

The normal vector to reference when checking for parallelism.

qConvexConnectedFaces (subquery is Query) returns Query

A query for a set of faces connected via convex edges. subquery is used as a seed, and the query will flood-fill match any faces connected across a convex edge.

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 (subquery is Query) returns Query

A query for a set of faces connected via concave edges. subquery is used as a seed, and the query will flood-fill match any faces connected across a concave edge.

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 (subquery is Query) returns Query

A query for a set of faces connected via tangent edges. subquery is used as a seed, and the query will flood-fill match any faces connected across a tangent edge.

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.

qLoopBoundedFaces (subquery 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 a the face which surrounds the pocket, and an edge of the face which touches that pocket.

ParameterTypeAdditional Info
subquery Query

Should match a face and an edge. If multiple faces and edges match, used the first face and the first edge.

qFaceOrEdgeBoundedFaces (subquery is Query) returns Query

Given a seed face and bounding entities, matches all adjacent faces inside the bounding entities, expanding from the seed face.

ParameterTypeAdditional Info
subquery Query

A Query for the seed face, followed by any boundary faces or edges. The seed face must be first, so a qUnion should be used to guarantee the order.

qHoleFaces (subquery is Query) returns Query

Given a single face inside a hole or hole-like geometry, returns all faces of that hole.

ParameterTypeAdditional Info
subquery 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.

ParameterTypeAdditional Info
featureId Id

The feature id of the Sketch being queried.

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

qMateConnectorsOfParts (subquery is Query) returns Query

A query for all mate connectors owned by the parts of a subquery.

qFilletFaces (subquery is Query, compareType is CompareType) returns Query

A query for fillet faces of radius equal to, less than and equal to, or greater than and equal to the input faces. If subquery does not match one or more fillet faces, the resulting query will not match any faces. Will find the fillet radius from the faces and then compare to find all the faces of fillets that satisfy the compareType.

If subquery 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)]).

qMatchingFaces (subquery is Query) returns Query

Matches any faces in the context which are geometrically identical (same size and shape) to the face in subquery.

If subquery resolves to multiple faces, all are matched independently. That is, qMatchingFaces(qUnion([q1, q2])) returns the same thing as qUnion([qMatchingFaces(q1), qMatchingFaces(q2)]).

qContainsPoint (subquery is Query, point is Vector) returns Query

A query for all entities (bodies, faces, edges, or points) containing a specified point.

ParameterTypeAdditional Info
point Vector

A 3D point, in world space.

qIntersectsLine (subquery is Query, line is Line) returns Query

A query for all entities (bodies, faces, edges, or points) touching a specified infinite line.

qIntersectsPlane (subquery is Query, plane is Plane) returns Query

A query for all entities (bodies, faces, edges, or points) touching a specified infinite plane.

ParameterTypeAdditional Info
plane Plane

EXAMPLE

plane(vector(0, 0, 0), vector(0, 0, 1))

qCoincidesWithPlane (subquery is Query, plane is Plane) returns Query

A query for all entities (bodies, faces, edges, or points) coinciding with a specified infinite plane.

ParameterTypeAdditional Info
plane Plane

EXAMPLE

plane(vector(0, 0, 0), vector(0, 0, 1))

qWithinRadius (subquery is Query, point is Vector, radius is ValueWithUnits)

A query for all entities (bodies, faces, edges or points) that are within a specified radius from a point.

ParameterTypeAdditional Info
point Vector

The point from which to check distance from.

radius ValueWithUnits

The distance away from the point.

qClosestTo (subquery is Query, point is Vector) returns Query

A query for the entity closest to a point.

In the case of a tie, resolves to all entities within TOLERANCE.zeroLength of being the closest.

ParameterTypeAdditional Info
point Vector

A position vector for the point to find entities closest to.

qFarthestAlong (subquery is Query, direction is Vector)

A query for the entity farthest along a direction in world space. In the case of a tie, resolves to all entities within TOLERANCE.zeroLength of being the farthest.

ParameterTypeAdditional Info
direction Vector

A vector for the direction to find the entity farthest away.

qLargest (subquery is Query) returns Query

A query to find the largest entity (by length, area, or volume) within a subquery. If subquery 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.

qSmallest (subquery is Query) returns Query

A query to find the smallest entity (by length, area, or volume) within a subquery. If subquery 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)

Given the id of a split feature, get entities of a given EntityType on either the front body or the back body after the split.

ParameterTypeAdditional Info
featureId Id

EXAMPLE

id + "split1"
backBody boolean

EXAMPLE

false indicates the body in front (i.e. in the direction of the split tool's surface normal).

EXAMPLE

true indicates the body in back.

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.

ParameterTypeAdditional Info
operationId Id

Id of the sketch feature.

entityType

EXAMPLE

EntityType.EDGE to match the edges on the wire bodies.

EXAMPLE

EntityType.BODY to match the bodies themselves.

EXAMPLE

undefined to match both.
sketchEntityId string

Sketch id.

TransientId type

A TransientId is a deterministic id assigned to a specific topological entity.

Transient ids should generally not be used directly because they are not stable. If a user modifies an upstream feature, the transient ids of all entities can potentially change. To refer to geometry in a robust way, use non-transient queries.

canBeTransientId (value) predicate

Typecheck for TransientId

toString (value is TransientId)

evaluate

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 modelling purposes that will be negatively affected in case the approximation changes. Consider using the center of a bounding box instead.

ParameterTypeAdditional Info
arg map
  • entities

The entities to take the center of mass of.

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.

ParameterTypeAdditional Info
arg map
  • entities
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, or revolved surface -- return the axis. Otherwise throw an exception.

ParameterTypeAdditional Info
arg map
  • axis
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.

ParameterTypeAdditional Info
arg map
  • topology
Query

The entity to find the bounding box of.

  • cSys
CoordSystem

Optional

The coordinate system to use (if not the standard coordinate system).

  • tight
boolean

Optional

Get the tightest possible bounding box. Defaults to true.

EXAMPLE

true for a bounding box precisely at the extents of the given entities (and no bigger).

EXAMPLE

false for a bounding box at least as big as the given entities, using a faster algorithm.

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.

ParameterTypeAdditional Info
arg map
  • tools
Query
  • targets
Query

evCornerType (context is Context, arg is map) returns map

Return the type of corner found at a vertex of a sheet metal model

ParameterTypeAdditional Info
arg map
  • vertex
Query
ReturnTypeDescription
map
  • cornerType
SMCornerType

the type of the corner

  • primaryVertex
Query

the vertex that defines the corner

ThrowsAdditional 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, or Line value for the curve. If the curve is none of these types, return a map with unspecified contents.

ParameterTypeAdditional Info
arg map
  • edge
Query

The curve to evaluate.

ThrowsAdditional 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.

DistanceResult type

The result of an evDistance call -- information about the extremal distance and the attaining point / line / entity.

ValueTypeDescription
DistanceResult map
  • distance
ValueWithUnits

The minimal or maximal distance.

  • sides
array

An array of 2 maps, containing information about where the extremum was found for each side. Each map has a:

point (Vector of lengths) : represents the position that attains the minimum or maximum on that side.

index (integer) : the index into the line or point array or into the query results, if a query is passed in.

parameter (number or length or array of two numbers) : If the index refers to an edge, the parameter is a number between 0 and 1 (unless extend for that side was passed in). It is in the form that evEdgeTangentLine consumes (with arcLengthParameterization set to false). If the side has Line(s), the parameter is a length representing the distance along the direction. If the index refers to a face, the parameter is a 2D Vector in the form that evFaceTangentPlane consumes. If the face is a mesh, the parameter is a 2D Vector of 0.

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 by query 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

DistanceResult

ParameterTypeAdditional Info
arg map
  • side0

One of the following: A query, or a point (3D Length Vector), or a Line, or an array of points, or an array of Lines.

EXAMPLE

qNthElement(qEverything(EntityType.FACE), 0) or vector(1, 2, 3) * meter or line(vector(1, 0, 1) * meter, vector(1, 1, 1)
  • extendSide0
boolean

Optional

If true and side0 is a query, bodies will be ignored and edges and faces extended to their possibly infinite underlying surfaces. Defaults to false.

  • side1

Like side0.

  • extendSide1
boolean

Optional

Like extendSide0.

  • maximum
boolean

Optional

If true, compute the maximum instead of the minimum. Defaults to false. Not allowed to be true if a line is passed in in either side or if either extend is true.

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.

ParameterTypeAdditional Info
arg map
  • edge
Query
ThrowsAdditional 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

ValueTypeDescription
EdgeCurvatureResult map
  • frame
CoordSystem

The frame. The Z vector is the tangent, the X vector is the normal and the Y vector is the binormal

  • curvature
ValueWithUnits

The curvature.

evEdgeCurvature (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.

ParameterTypeAdditional Info
arg map
  • edge
Query

The curve to use

EXAMPLE

qNthElement(qEverything(EntityType.EDGE), 1)
  • parameters
array

An array of numbers in the range 0..1 indicating points along the curve to evaluate frames at.

  • arcLengthParameterization

Optional

If true (default), the parameter measures distance along the edge, so 0.5 is the midpoint. If false, use an arbitrary but faster-to-evaluate parameterization. For efficiency, use false if calculating the tangent only to an end point of the edge because the result will be identical. The parameterization is identical to that used by evEdgeTangentLines. Results obtained with arcLengthParameterization will have lower accuracy due to approximation.

  • face
Query

Optional

If present, the edge orientation used is such that walking along the edge with "up" being the face normal will keep face to the left. Must be adjacent to edge.

Return typeDescription
array

An array of EdgeCurvatureResults.

ThrowsAdditional 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 typeDescription
Vector

A unit 3D vector in world space.

curvatureFrameNormal (curvatureResult is EdgeCurvatureResult) returns Vector

Returns the normal vector of a curvature frame

Return typeDescription
Vector

A unit 3D vector in world space.

curvatureFrameBinormal (curvatureResult is EdgeCurvatureResult) returns Vector

Returns the binormal vector of a curvature frame

Return typeDescription
Vector

A unit 3D vector in world space.

evEdgeTangentLine (context is Context, arg is map) returns Line

Return one tangent Line to an edge.

ParameterTypeAdditional Info
arg map
  • edge
Query

The curve to use

EXAMPLE

qNthElement(qEverything(EntityType.EDGE), 1)
  • parameter
number

A number in the range 0..1 indicating a point along the curve to evaluate the tangent at.

  • arcLengthParameterization

Optional

If true (default), the parameter measures distance along the edge, so 0.5 is the midpoint. If false, use an arbitrary but faster-to-evaluate parameterization. For efficiency, use false if calculating the tangent only to an end point of the edge because the result will be identical.

  • face
Query

Optional

If present, the edge orientation used is such that walking along the edge with "up" being the face normal will keep face to the left. Must be adjacent to edge.

ThrowsAdditional 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.

ParameterTypeAdditional Info
arg map
  • edge
Query

The curve to use

EXAMPLE

qNthElement(qEverything(EntityType.EDGE), 1)
  • parameters
array

An array of numbers in the range 0..1 indicating points along the curve to evaluate tangents at.

  • arcLengthParameterization

Optional

If true (default), the parameter measures distance along the edge, so 0.5 is the midpoint. If false, use an arbitrary but faster-to-evaluate parameterization. For efficiency, use false if calculating the tangent only to an end point of the edge because the result will be identical.

  • face
Query

Optional

If present, the edge orientation used is such that walking along the edge with "up" being the face normal will keep face to the left. Must be adjacent to edge.

Return typeDescription
array

An array of Lines.

ThrowsAdditional info
GBTErrorStringEnum.NO_TANGENT_LINE

A tangent line could not be evaluated for the given query.

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.

ParameterTypeAdditional Info
arg map
  • edge
Query
  • face
Query
  • parameter
number

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.

ParameterTypeAdditional Info
arg map
  • edge
Query
  • face
Query
  • parameter
number

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.

ParameterTypeAdditional Info
arg map
  • face
Query

The face to evaluate. The face cannot be a mesh.

EXAMPLE

qNthElement(qEverything(EntityType.FACE), 1)
  • parameter
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

vector(0.5, 0.5) places the origin at the bounding box's center.
ThrowsAdditional 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 Planes tangent to that face, where each plane's origin is located at the point specified by its parameter-space coordinates.

ParameterTypeAdditional Info
arg map
  • face
Query

The face to evaluate. The face cannot be a mesh.

EXAMPLE

qNthElement(qEverything(EntityType.FACE), 1)
  • parameters
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

[ vector(0.5, 0.5), vector(0, 1) ]
ThrowsAdditional 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.

ParameterTypeAdditional Info
arg map
  • face
Query
ThrowsAdditional 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.

ParameterTypeAdditional Info
arg map
  • entities
Query

evLine (context is Context, arg is map) returns Line

If the edge is a line, return a Line value for the given edge.

ParameterTypeAdditional Info
arg map
  • edge
Query
ThrowsAdditional 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

ParameterTypeAdditional Info
arg map
  • mateConnector
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.

ParameterTypeAdditional Info
arg map
  • entity
Query

The sketch entity. May be a vertex, edge, face, or body.

ThrowsAdditional info
GBTErrorStringEnum.CANNOT_RESOLVE_PLANE

Entity was not created by a sketch.

evPlane (context is Context, arg is map) returns Plane

If the face is a plane, return a Plane value for the given face.

ParameterTypeAdditional Info
arg map
  • face
Query
ThrowsAdditional info
GBTErrorStringEnum.INVALID_INPUT

The first resolved entity was not a planar face.

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, or Torus as appropriate for the face, or an unspecified map value if the face is none of these with surfaceType filled of type SurfaceType

ParameterTypeAdditional Info
arg map
  • face
Query
ThrowsAdditional info
"GBTErrorStringEnum.CANNOT_RESOLVE_PLANE"

The first result is not a face.

evVertexPoint (context is Context, arg is map) returns Vector

Return the coordinates of a point, or the origin of a mate connector.

ParameterTypeAdditional Info
arg map
  • vertex
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.

ParameterTypeAdditional Info
arg map
  • entities
Query

Math

box

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.

ValueTypeDescription
Box3d map
  • minCorner
Vector

A 3D position representing the corner with the smallest x, y, and z coordinates.

  • maxCorner
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.

extendBox3d (bBox is Box3d, absoluteValue is ValueWithUnits, factor is number) returns Box3d

Return an enlarged bounding box.

ParameterTypeAdditional Info
absoluteValue ValueWithUnits

The absolute distance to move each face of the box. The corners move sqrt(3) times as far.

factor number

The relative amount to expand the box, with 0 leaving it unchanged.

box3dCenter (bBox is Box3d) returns Vector

Return the center of the bounding box.

insideBox3d (point is Vector, bBox is Box3d) predicate

Whether the specified point is within the bounding box.

coordSystem

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 yAxis, which simply performs a cross product.

See also

toWorld(CoordSystem)

fromWorld(CoordSystem)

coordSystem(Plane)

plane(CoordSystem)

opMateConnector

ValueTypeDescription
CoordSystem map
  • origin
Vector

A 3D point, in world space, representing the origin of the coordinate system.

  • xAxis
Vector

A 3D unit vector, in world space, representing the x-axis of the coordinate system.

  • zAxis
Vector

A 3D unit vector, in world space, representing the z-axis of the coordinate system. Must be perpendicular to the xAxis.

coordSystem (origin is Vector, xAxis is Vector, zAxis is Vector) returns CoordSystem

Creates a Cartesian coordinate system.

See also

CoordSystem

ParameterTypeAdditional 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 CoordSystems 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.

ParameterTypeAdditional Info
pointInCSys Vector

A 3D vector, measured with respect to the cSys provided.

Return typeDescription
Vector

A 3D vector in world space.

toWorld (cSys is CoordSystem) returns Transform

Returns a Transform which will move geometry from a specified coordinate system into world space.

See also

opTransform

fromWorld (cSys is CoordSystem, worldPoint is Vector) returns Vector

Convert a specified point from world space into a specified coordinate system.

ParameterTypeAdditional Info
worldPoint Vector

A 3D vector, measured in world space.

fromWorld (cSys is CoordSystem) returns Transform

Returns a Transform which will move geometry from world space into a specified coordinate system.

See also

opTransform

yAxis (cSys is CoordSystem) returns Vector

Returns the y-axis of a coordinate system

Return typeDescription
Vector

A 3D vector in world space.

toString (cSys is CoordSystem) returns string

Returns a representation of the coordinate system as a string.

curveGeometry

Line type

Represents a parameterized line in 3D space.

ValueTypeDescription
Line map
  • origin
Vector

A point on the line, as a 3D Vector with length units.

  • direction
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.

ParameterTypeAdditional Info
direction Vector

The direction gets normalized by this function.

tolerantEquals (line1 is Line, line2 is Line) predicate

Check that two Lines are the same up to tolerance, including the origin.

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.

toString (value is Line) returns string

Circle type

Represents a circle in 3D space.

ValueTypeDescription
Circle map
  • coordSystem
CoordSystem

The circle lies in the xy plane of this coordinate system and the origin of its parameterization is the x axis.

  • radius
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 Circles are the same up to tolerance, including the coordinate system.

toString (value is Circle) returns string

Ellipse type

Represents an ellipse in 3D space.

ValueTypeDescription
Ellipse map
  • coordSystem
CoordSystem

The ellipse lies in the xy plane of this coordinate system and the x axis corresponds to the major radius.

  • majorRadius
ValueWithUnits

The larger of the two radii.

  • minorRadius
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 Ellipses are the same up to tolerance, including the coordinate system.

toString (value is Ellipse) returns string

BSplineCurve type

The definition of a spline in 3D space.

ValueTypeDescription
BSplineCurve map
  • degree
number

The degree of the spline

  • dimension
number

The dimension of the spline. Must be 2 or 3.

  • isRational
boolean

Is the spline rational?

  • isPeriodic
boolean

Is the spline periodic?

  • controlPoints
array

An array of control points of the required dimension. Size should be at least degree + 1

  • weights
array

Optional

An array of unitless values of same size as the control points. Required for a rational spline

  • knots
array

An array of non-decreasing knots of size equal to 1 + degree + size(controlPoints)

canBeBSplineCurve (value) predicate

Typecheck for BSplineCurve

bSplineCurve (degree is number, isPeriodic is boolean, controlPoints is array, knots is array) returns BSplineCurve

Returns a new polynomial BSplineCurve.

ParameterTypeAdditional Info
degree number

The degree of the spline

isPeriodic boolean

Is the spline periodic?

controlPoints array

An array of control points of the required dimension. Size should be at least degree + 1

knots array

An array of non-decreasing knots of size equal to 1 + degree + size(controlPoints)

bSplineCurve (degree is number, isPeriodic is boolean, controlPoints is array, weights is array, knots is array) returns BSplineCurve

Returns a new rational BSplineCurve.

ParameterTypeAdditional Info
degree number

The degree of the spline

isPeriodic boolean

Is the spline periodic?

controlPoints array

An array of control points of the required dimension. Size should be at least degree + 1

weights array

An array of unitless values of same size as the control points.

knots array

An array of non-decreasing knots of size equal to 1 + degree + size(controlPoints)

math

A module containing many elementary math functions.

Some math functions (such sa 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.

abs (value)

Absolute value.

EXAMPLE

abs(-1) returns 1

EXAMPLE

abs(-1.5 * inch) equals 1.5 * inch

sqrt (value is number)

Square root of a number.

EXAMPLE

sqrt(4) returns 2

EXAMPLE

sqrt(-4) throws an error

log (value is number)

Natural logarithm of a number.

EXAMPLE

log(exp(3)) returns 3

EXAMPLE

log(0) returns -inf

EXAMPLE

log(-1) throws an error

log10 (value is number)

Base 10 logarithm of a number.

EXAMPLE

log10(1000) returns 3

EXAMPLE

log10(0) returns -inf

EXAMPLE

log10(-1) throws an error

sinh (value is number)

Hyperbolic sine.

cosh (value is number)

Hyperbolic cosine.

tanh (value is number)

Hyperbolic tangent.

asinh (value is number)

Inverse hyperbolic sine.

acosh (value is number)

Inverse hyperbolic cosine.

atanh (value is number)

Inverse hyperbolic tangent.

exp (value is number)

e to the power of value.

EXAMPLE

exp(1) returns 2.71828...

EXAMPLE

exp(log(3)) returns 3

exp2 (value is number)

2 to the power of value.

EXAMPLE

exp2(10) returns 1024

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) returns 5

floor (value is number)

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) returns 1

EXAMPLE

floor(2.0) returns 2

EXAMPLE

var numberOfBricks is number = floor(wallLength / brickLength);

ceil (value is number)

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) returns 2

EXAMPLE

ceil(1.0) returns 1

EXAMPLE

var numberOfBricks is number = ceil(wallLength / brickLength)

round (value is number)

Round a number to the nearest integer.

EXAMPLE

round(1.4) returns 1

EXAMPLE

round(1.5) returns 2

EXAMPLE

round(-1.5) returns -1

min (value1, value2)

Return the lesser of two values, which must be comparable with <.

EXAMPLE

min(0, 1) returns 0

EXAMPLE

min(1 * meter, 1 * inch) equals 1 * inch

max (value1, value2)

Return the greater of two values, which must be comparable with <.

EXAMPLE

max(0, 1) returns 1

EXAMPLE

max(1 * meter, 1 * inch) equals 1 * meter

min (arr is array)

Return the least of an array of values, as determined by operator <, or undefined if the array is empty.

EXAMPLE

min([1, 2, 3]) returns 1

EXAMPLE

min([1 * inch, 2 * inch, 3 * inch]) equals 1 * inch

max (arr is array)

Return the greatest of an array of values, as determined by operator <, or undefined if the array is empty.

EXAMPLE

max([1, 2, 3]) returns 3

EXAMPLE

max([1 * inch, 2 * inch, 3 * inch]) equals 3 * inch

argMin (arr is array)

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]) returns 0

argMax (arr is array)

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]) returns 2

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) returns 0,

EXAMPLE

clamp(10, 0, 20) returns 10

EXAMPLE

clamp(30, 0, 20) returns 20

EXAMPLE

clamp(30 * inch, 0 * inch, 20 * inch) equals 20 * 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.

mathUtils

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 modelling functionality) is needed.

matrix

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.

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.

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.

svd (m is Matrix) returns map

Compute the singular value decomposition of a matrix, i.e. s, u, and v, where m == u * s * v and s is a diagonal matrix of singular values.

ReturnTypeDescription
map
  • u
Matrix

A unitary matrix

  • s
Matrix

A diagonal matrix

  • v
Matrix

A unitary matrix

determinant (m is Matrix) returns number

Return the determinant of the matrix.

toString (value is Matrix) returns string

surfaceGeometry

This module contains methods for creating and working with primitive surfaces: planes, cylinders, cones, spheres, and tori.

XY_PLANE const

The default XY plane, whose normal points along the Z axis.

Plane type

A Plane is a data type representing an origin, a normal vector, and an X direction, perpendicular to the normal direction.

ValueTypeDescription
Plane map
  • origin
Vector

A 3D point, in world space.

  • normal
Vector

A 3D unit vector in world space.

  • x
Vector

A 3D unit vector in world space. Must be perpendicular to normal.

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.

ParameterTypeAdditional 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 perpindicular to the normal.

ParameterTypeAdditional 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 Planes are the same up to tolerance, including the origin and local coordinate system.

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 Planes. If the planes are parallel or coincident, returns undefined.

LinePlaneIntersection type

Represents an intersection between a line an a plane. Depending on the line and plane, this intersection may be a point, a line, or nothing.

ValueTypeDescription
LinePlaneIntersection map
  • dim
number

Integer representing the dimension of the intersection.

EXAMPLE

0 indicates that intersection is a 3D length Vector.

EXAMPLE

1 indicates that intersection is a Line.

EXAMPLE

-1 indicates that the intersection does not exist (i.e. the line and the plane are parallel).
  • intersection

undefined or Vector or Line (depending on dim) that represents the intersection.

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.

coplanarPlanes (plane1 is Plane, plane2 is Plane) returns boolean

Returns true if the two planes are coplanar.

Cone type

Type representing a cone which extends infinitely down the positive z-axis of its coordSystem.

ValueTypeDescription
Cone map
  • coordSystem
CoordSystem

The position and orientation of the cone.

  • halfAngle
ValueWithUnits

The angle from z-axis of coordSystem to the surface of the cone.

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 Cones 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.

ValueTypeDescription
Cylinder map
  • coordSystem
CoordSystem

The position and orientation of the cylinder.

  • radius
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 Cylinders 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.

ValueTypeDescription
Torus map
  • coordSystem
CoordSystem

The position and orientation of the torus.

  • radius
ValueWithUnits

The major radius, i.e. the distance from the center of the torus to the center of the revolved circle.

  • minorRadius
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.

ValueTypeDescription
Sphere map
  • coordSystem
CoordSystem

The position and orientation of the sphere.

  • radius
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 Spheres are the same up to tolerance, including the local coordinate system.

toString (value is Sphere) returns string

transform

Transform type

Type typically representing a change of position, orientation in 3D space (other affine transformations such as scaling and sheering can also be represented).

Transforms are 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 the transform.

EXAMPLE

transform2 * transform1 yields a new transform which is equivalent to applying transform1 followed by transform2.

When applying a single transform transform, the linear potion is applied first, followed by the vector translation. Generally, the individual fields on this type don't need to be directly used, and everything you need can be accomplished through the operator overloads above, and the functions in this module and the coordSystem module.

rotationAround, scaleUniformly, toWorld(CoordSystem) and fromWorld(CoordSystem) return transforms for common operations.

ValueTypeDescription
Transform map
  • linear
Matrix

A linear motion, which is generally a rotation, but can also be a scaling, inversion, or sheering.

  • translation
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 Transforms 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, point is Vector) returns Transform

Returns a Transform that represents a uniform scaling around the given point.

units

ValueWithUnits type

A ValueWithUnits is a number with dimensions, such as 1 kilogram, 90 degrees, or 9.81 meters per second per second.

Values can be multiplied and divided. The preceding values are 1 * kilogram, 90 * degree, and 9.81 * meter / second / second.

Units are always multiplied with the values, so myLength * myOtherLength evaluates to an area ValueWithUnits. An expression where the units all cancel (e.g. myLength / myOtherLength), evaluates to plain number.

Values with the same units can be added and subtracted. Square root works if the units appear as even powers, as in sqrt(4 * meter * meter).

Equality considers the underlying value, so 25.4 * millimeter is the same as 1 * inch. However, PI * radian / 5 does not equal 36 * degree because of finite precision arithmetic. To compare two ValueWithUnitss, use tolerantEquals.

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.

A constant equal to 1 foot.

yard const

A constant equal to 1 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.

isLength (val) predicate

True for any value with length units.

isAngle (val) predicate

True for any value with angle 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

sqrt (value is ValueWithUnits) returns ValueWithUnits

Square root of a ValueWithUnits.

EXAMPLE

sqrt(4 * meter^2) equals 2 * 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) equals 5 * 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 approximately 0.5

EXAMPLE

sin(PI * radian) returns approximately 0

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 approximately 0.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 approximately 1

EXAMPLE

tan(PI * radian) returns approximately 0

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 approximately 30 * degree

EXAMPLE

asin(1.5) throws an error, since there is no value where sin(value) is 1.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 approximately 60 * degree

EXAMPLE

acos(1.5) throws an error, since there is no value where cos(value) is 1.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 approximately 45 * degree

EXAMPLE

atan(inf) equals approximately 90 * 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 approximately 0 * degree

EXAMPLE

atan2(1, 0) equals approximately 90 * degree

EXAMPLE

atan2(0, -1) equals approximately 180 * 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

atan2(number, number)

toString (value is ValueWithUnits) returns string

General value to string conversion.

vector

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.

vector (x, y) returns Vector

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 numbers.

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]

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 to vector(0, 0, 0)

squaredNorm (vector is Vector)

Returns the squared length of a vector. This is slightly faster to calculate than the length.

norm (vector is Vector)

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 the angle between two 3-dimensional vectors.

normalize (vector is Vector) returns Vector

Returns the (unitless) result of normalizing vector. Throws if the input is zero-length.

ParameterTypeAdditional 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 number) 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 typeDescription
array

Array of arrays, where each array is a cluster of nearby points, represented as indices into points array.

Utilities

attributes

Attributes are data attached to entities, which can be set and retrieved in FeatureScript. The data can be of any type (except undefined), and multiple attributes can be associated with the same topological entity.

The common use case for attributes is to set attributes on an entity in one feature, and get them in another. For global data, this can be done more simply via setVariable and getVariable.

Entities can be queried by attributes with qAttributeFilter and qAttributeQuery.

setAttribute (context is Context, definition is map)

Attach an attribute to one or several entities.

ParameterTypeAdditional Info
definition map
  • entities
Query

Entities to attach attribute to. Throws an error if the query resolves to nothing.

  • attribute

The data to attach.

EXAMPLE

"myAttribute"

getAttributes (context is Context, definition is map) returns array

Get attributes attached to entities.

ParameterTypeAdditional Info
definition map
  • entities
Query

Entities to get attributes on. Throws an error if the query resolves to nothing.

EXAMPLE

qEverything()
  • attributePattern

Optional

If provided, will only return attributes of this type. If a map is provided, will also only match attributes whose fields match every field of the map provided.

EXAMPLE

"" matches all string attributes.

EXAMPLE

{} matches all map attributes.

EXAMPLE

"" as MyStringAttributeType matches all attributes of type MyStringAttributeType.

EXAMPLE

{ "odd" : true } matches all map attributes that have a field "odd" whose value is true.
Return typeDescription
array

An array of all unique attributes on the given entities matching the pattern.

removeAttributes (context is Context, definition is map)

Remove matching attributes attached to entities

ParameterTypeAdditional Info
definition map
  • entities
Query

Optional

Entities to remove attributes from. Default is everything.

  • attributePattern

Optional

If provided, will only remove attributes of this type. See getAttributes for details.

containers

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.

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]) returns 3

EXAMPLE

size([1, [2, 3]]) returns 2

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 }) returns 2

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]) returns true

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 }) returns true

EXAMPLE

isValueIn("b", { "a" : true, "b" : 0 }) returns false

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]
ParameterTypeAdditional 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}

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]
ParameterTypeAdditional Info
compareFunction function

A function that takes two values, returns a negative value if the first is before the second, 0 if the two are equal, and positive value if the second is before the first.

filter (entities 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]
ParameterTypeAdditional Info
filterFunction function

A function which takes one argument (a member of the input array) and returns a boolean.

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

keys({ "a" : 1, "c" : 2, "b" : 3 }) returns [1, 3, 2]

subArray (input is array, startIndex is number, endIndex is number) returns array

Returns the sub array [startIndex, endIndex)

debug

debug (context is Context, value)

Print and, if applicable, display value in a Part Studio, highlighting or creating entities in red.

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.

The overloads in this module define these behaviors.

debug (context is Context, value is ValueWithUnits)

debug (context is Context, value is Vector)

debug (context is Context, value is Query)

debug (context is Context, value is Line)

debug (context is Context, value is CoordSystem)

debug (context is Context, value is Plane)

debug (context is Context, point1 is Vector, point2 is Vector)

Draws a line between point1 and point2 and prints the points with the distance between them.

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.

defaultFeatures

newContextWithDefaults () returns Context

Creates a Context with default planes and an origin.

error

regenError (customMessage is string)

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)

ParameterTypeAdditional 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)

ParameterTypeAdditional Info
entities Query

A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the qUnion function. The entities are only highlighted when the feature dialog is open.

regenError (customMessage is string, faultyParameters is array, entities is Query)

ParameterTypeAdditional 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.

entities Query

A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the qUnion function. The entities are only highlighted when the feature dialog is open.

regenError (message is ErrorStringEnum)

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)

ParameterTypeAdditional 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 (message is ErrorStringEnum, entities is Query)

ParameterTypeAdditional Info
entities Query

A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the qUnion function. The entities are only highlighted when the feature dialog is open.

regenError (message is ErrorStringEnum, faultyParameters is array, entities is Query)

ParameterTypeAdditional 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.

entities Query

A query for entities to highlight in the Part Studio. Multiple queries can be combined and highlighted using the qUnion function. The entities are only highlighted when the feature dialog is open.

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.

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, definition is map) returns boolean

Propagate the status of a subfeature to a feature.

ParameterTypeAdditional Info
definition map
  • subfeatureId
Id

The Id of the subfeature.

  • featureParameterMap
map

Optional

A mapping of the field names from subfeature to feature.

  • propagateErrorDisplay
boolean

Optional

Use subfeature error display when present.

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 *

ParameterTypeAdditional Info
definition map
  • withDisplayData
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.

ParameterTypeAdditional Info
definition map
  • entities
Query

The entities to display.

featureHasError (context is Context, id is Id) returns boolean

Return typeDescription
boolean

true if the feature with the given id has an associated regeneration error.

featureHasNonTrivialStatus (context is Context, id is Id) returns boolean

Return typeDescription
boolean

true if the feature with the given id has an associated status different from OK.

faultyArrayParameterId (arrayParameter is string, itemIndex is number, innerParameter is string) returns string

Return typeDescription
string

A string identifier for marking an error on an array parameter when using the faultyParameters argument in any of the functions in this module.

FeatureStatus type

The status of a feature

ValueTypeDescription
FeatureStatus map
  • statusType
StatusType
  • faultyParameters
array
  • statusEnum
ErrorStringEnum
  • statusMsg
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.

feature

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.

ParameterTypeAdditional 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 valueBounds module.

EXAMPLE

{} will not modify the definition.

EXAMPLE

{ "shouldFillet" : false } will set the parameter "shouldFillet" to false if the feature is called from FeatureScript without the "shouldFillet" parameter.

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.

ParameterTypeAdditional Info
feature function

A function that takes a context, an id, and a definition and regenerates the feature.

startFeature (context is Context, id is Id)

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.

ParameterTypeAdditional Info
definition map
  • name
string

EXAMPLE

myValue
  • value

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
    });
ParameterTypeAdditional Info
definition map
  • references
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

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.

See also

qTransient

isAnything (value) predicate

A predicate which always returns true. Used to create a generic feature parameter that can be any featurescript expression.

Note that for non-hidden parameters, some internal validation is done to only allow this parameter to be a number or a ValueWithUnits.

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 specifiy 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

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

ParameterTypeAdditional Info
id Id

ends in unstable component

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.

featureList

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.

holeUtils

HoleStyle enum

Defines whether each hole should have a countersink, a counterbore, or neither.

ValueDescription
SIMPLE
C_BORE
C_SINK

manipulator

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" : "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(
                extrudePlane.origin,
                extrudePlane.normal,
                definition.shouldFlip ? definition.depth : -definition.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 (base is Vector, offset is Vector, sources is Query) 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.

ParameterTypeAdditional Info
base Vector

The position of the manipulator when the offset is 0.

offset Vector

The 3D position of the triad, relative to the base.

sources Query

If a query for entities is passed, creates a shadow of these entities and renders that shadow rigidly locked to the manipulator (such that the shadow will move before the feature finishes regenerating).

Can be undefined if this behavior is not needed.

linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits, sources is Query, style is ManipulatorStyleEnum) returns Manipulator

Create a manipulator represented by a single arrow which can move along a single axis. See extrude for an example.

ParameterTypeAdditional Info
base Vector

The position of the manipulator when the offset is 0.

direction Vector

A 3D unit vector pointing on the axis on which the manipulator can be dragged.

offset ValueWithUnits

The positive or negative distance along direction from the base to the manipulator.

sources Query

Optional

If a query for entities is passed, creates a shadow of these entities and renders that shadow rigidly locked to the manipulator (such that the shadow will move before the feature finishes regenerating).

linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits, sources) returns Manipulator

linearManipulator (base is Vector, direction is Vector, offset is ValueWithUnits) returns Manipulator

linearManipulator (definition is map) returns Manipulator

angularManipulator (definition is map) returns Manipulator

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.

ParameterTypeAdditional Info
definition map
  • axisOrigin
Vector

The origin of the axis to rotate around.

EXAMPLE

project(axis, rotationOrigin)
  • axisDirection
Vector

The direction of the axis to rotate around.

EXAMPLE

axis.direction
  • rotationOrigin
Vector

Point at the tip of the revolve manipulator.

  • sources
Query

Optional

If a query for entities is passed, creates a shadow of these entities and renders that shadow rigidly locked to the manipulator (such that the shadow will move before the feature finishes regenerating).

  • minValue
ValueWithUnits

Optional

The minimum angle allowed.

  • maxValue
ValueWithUnits

Optional

The maximum angle allowed.

flipManipulator (base is Vector, direction is Vector, flipped is boolean, sources is Query, style is ManipulatorStyleEnum) returns Manipulator

Create a manipulator which can invert the direction of a feature.

ParameterTypeAdditional Info
base Vector

A 3d point at the manipulator's origin

EXAMPLE

Vector(0, 0, 0) * meter
direction Vector

A 3d vector pointing in the unflipped direction

EXAMPLE

Vector(0, 0, 1) points manipulator along the z axis
flipped boolean

EXAMPLE

false points the manipulator along +direction

EXAMPLE

true points the manipulator along -direction
sources Query

Optional

style ManipulatorStyleEnum

Optional

.

flipManipulator (base is Vector, direction is Vector, flipped is boolean, sources) returns Manipulator

flipManipulator (base is Vector, direction is Vector, flipped is boolean) returns Manipulator

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.

ParameterTypeAdditional Info
manipulators map

A map whose keys will match the keys of newManipulators (passed into the Manipulator Change Function), and whose values are the Manipulators to be added.

path

Path type

Represents a series of connected edges which form a continuous path.

ValueTypeDescription
Path map
  • edges
array

The edges that form this Path, in the order of the Path.

  • flipped
array

An array of booleans corresponding to each edge in the path, set to true to traverse the edge backwards.

  • closed
boolean

Whether the Path is a closed path.

canBePath (value) predicate

Typecheck for Path

PathDistanceInformation type

Distance information returned by constructPath and evPathTangentLines when either function is provided with referenceGeometry

ValueTypeDescription
PathDistanceInformation map
  • distance
ValueWithUnits

The distance between the the start of the Path and the center of the bounding box of referenceGeometry, or infinity if referenceGeometry is empty

  • withinBoundingBox
boolean

Whether the start of the Path is within the bounding box of referenceGeometry, or false if referenceGeometry is empty

canBePathDistanceInformation (value) predicate

defaultPathDistanceInformation () returns PathDistanceInformation

Returns a PathDistanceInformation with distance set to infinity and withinBoundingBox set to false

reverse (path is Path) returns Path

Reverse the direction of a Path

ParameterTypeAdditional Info
path Path

the Path to reverse.

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

ParameterTypeAdditional Info
edgesQuery Query

A Query of edges to form into a Path. The edges are ordered with query evaluation order, so a qUnion should be used to ensure a stable ordering.

constructPath (context is Context, edgesQuery is Query, referenceGeometry) returns map

Construct a Path from a Query of edges, picking the starting point as the closest viable starting point to the supplied referenceGeometry

ParameterTypeAdditional Info
edgesQuery Query

A Query of edges to form into a Path.

referenceGeometry

A geometry Query to determine the start of the Path, or undefined. If an empty Query or undefined is specified, the starting point of the path will be based on query evaluation order for edgesQuery.

ReturnTypeDescription
map
  • path
Path

The resulting constructed Path

  • pathDistanceInformation
PathDistanceInformation

A map containing the distance from the Path start point to the center of the bounding box of referenceGeometry and whether the Path start point falls inside that bounding box.

evPathLength (context is Context, path is Path) returns ValueWithUnits

Return typeDescription
ValueWithUnits

The total length of the Path.

evPathTangentLines (context is Context, path is Path, parameters is array) returns map

Return tangent lines to a Path using arc length parameterization.

ParameterTypeAdditional Info
path Path

The Path to use.

parameters array

An array of numbers in the range 0..1 indicating where along the Path to evaluate tangents.

ReturnTypeDescription
map
  • tangentLines
array

The tangent Lines corresponding to each parameter

  • edgeIndices
array

The indices of the edges in the Path corresponding to each parameter

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

ParameterTypeAdditional Info
path Path

The Path to use.

parameters array

An array of numbers in the range 0..1 indicating where along the Path to evaluate tangents.

referenceGeometry

A geometry Query to determine the 0 parameter of the Path, or undefined. If an empty Query or undefined is specified, the tangents will be evaluated starting at the beginning of the path.

ReturnTypeDescription
map
  • tangentLines
array

The tangent Lines corresponding to each parameter

  • edgeIndices
array

The indices of the edges in the Path corresponding to each parameter

  • pathDistanceInformation
PathDistanceInformation

A map containing the distance from the remapped 0 parameter to the center of the bounding box of referenceGeometry and whether the remapped 0 parameter falls inside that bounding box. Only valid if the path is closed.

patternCommon

PatternType enum

The type of pattern.

ValueDescription
PART

Creates copies of bodies.

FEATURE

Calls a feature function multiple times, first informing the context of the transform to be applied.

FACE

Creates copies of faces and attempts to merge them with existing bodies.

MirrorType enum

The type of mirror.

See also

PatternType

ValueDescription
PART
FEATURE
FACE

patternUtils

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

ParameterTypeAdditional Info
definition map
  • patternType
PatternType
  • entities
Query

Required if patternType is not FEATURE

The faces or parts to pattern.

  • instanceFunction
FeatureList

Required if patternType is FEATURE

The features to pattern.

  • transforms
array

An array of Transforms in which to place new instances.

  • instanceNames
array

An array of the same size as transforms with a string for each transform, used in later features to identify the entities created.

string

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 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.

splitIntoCharacters (s is string) returns array

Split a string into an array of characters, each represented as a string.

REGEX_NUMBER const

Matches a number in the string, with or without decimals or exponents.

REGEX_NUMBER_CAPTURE const

Matches a number in the string, with or without decimals or exponents and captures it.

addCustomNumberMatching (regExp is string) returns string

Extends regular expression syntax by adding \f to indicate a complete number

match (s is string, regExp is string) returns map

Test if s matches regExp in its entirety.

ReturnTypeDescription
map
  • hasMatch
boolean

true if regExp matches s

  • captures
array

The first element is always the input string s. The following elements are a list of all captured groups.

replace (s is string, regExp is string, replacement is string) returns string

Returns a copy of s with every match of regExp replaced with the string replacement.

EXAMPLE

replace("a~~aa~a", "a.", "X") returns X~X~a

stringToNumber (s is string) returns number

Convert a number in string form, into a FS number. Note that this function will not accept trailing non numeric text, the entire string must be a single valid number.

EXAMPLE

stringToNumber("1") returns the number 1

EXAMPLE

stringToNumber("1.0") returns the number 1

EXAMPLE

stringToNumber("1e2") returns the number 100

length (s is string) returns number

Return the number of characters in a string.

topologyUtils

edgeIsTwoSided (context is Context, edge is Query) returns boolean

Returns true if edge has two adjacent faces, false if edge is laminar

isClosed (context is Context, edge is Query) returns boolean

Returns true if edge is closed, false if edge is open

dissolveWires (edgesAndWires is Query) returns Query

Returns the union of any edges from the input query and all the edges of any body from the input query

followWireEdgesToLaminarSource (context is Context, query is Query) returns Query

If the query contains wire edges then this function will track the wire edges back through creation history to find laminar edges that the edge was copied from (or will return the original edge if none).

extractDirection (context is Context, entity is Query)

Extract a direction from an axis or a plane

Return typeDescription

a 3D unit Vector if a direction can be extracted, otherwise undefined.

connectedComponentsOfEdges (context is Context, edges is Query)

Find connected components in the topological graph of provided edges. Each component is a chain of topologically connected edges, and each component is disjoint with (does not connect topologically with) any other component.

Returns an array of components. Each component is an array of individual queries. The queries in any group will respect the query evaluation order of the supplied edges Query. The components themselves will also be ordered by query evaluation order, sorted by the first edge in each component.

Unlike constructPath, this function operates on topological connections (underlying connections by a vertex). Distinct bodies are not topologically connected, so even if two edges on distinct bodies are geometrically related by having a vertex in the same location, the edges connected to these similar vertices will fall into different components. Notice that wire edges representing sketch curves are not topologically connected, this method cannot be used for them.

valueBounds

Value bounds are used to define minimum, maximum, and default values for numbers and values with units. These bounds are in the feature dialog UI for parameters with the given bounds.

In standard usage, a parameter can be specified with e.g. angle bounds in a feature precondition as follows:

isAngle(definition.myAngle, ANGLE_360_BOUNDS);

To change the bounds and defaults on the above declaration, a user may replace ANGLE_360_BOUNDS with another AngleBoundSpec in this module, or define their own. For instance, the following code creates a parameter whose default value is 45 degrees (if the user's settings have degrees as the default) or 1 radian (if the user's settings have radians as the default).

const MY_BOUNDS =
{
    (degree) : [0, 45, 360],
    (radian) : 1
} as AngleBoundSpec;
...
    isAngle(definition.myAngle, MY_BOUNDS);
...

isLength (value, boundSpec is LengthBoundSpec) predicate

True for a value with length units which conforms to the given bounds.

Used in feature preconditions to specify a length parameter.

ParameterTypeAdditional Info
boundSpec LengthBoundSpec

Specifies a min, a max, and a default value. These values are possibly different in different units for the sake of round numbers.

To specify a parameter with different default value or different limits, use a different or custom LengthBoundSpec.

isAngle (value, boundSpec is AngleBoundSpec) predicate

True for a value with angle units which conforms to the given bounds.

Used in feature preconditions to specify an angle parameter.

ParameterTypeAdditional Info
boundSpec AngleBoundSpec

Specifies a min, a max, and a default value. These values are possibly different in different units for the sake of round numbers.

To specify a parameter with different default value or different limits, use a different or custom AngleBoundSpec.

isInteger (value, boundSpec is IntegerBoundSpec) predicate

True for a number that is an integer and conforms to the given bounds.

Used in feature preconditions to specify an integer or count parameter.

ParameterTypeAdditional Info
boundSpec IntegerBoundSpec

Specifies a min, a max, and a default value. These values are possibly different in different units for the sake of round numbers.

To specify a parameter with different default value or different limits, use a different or custom IntegerBoundSpec.

isReal (value, boundSpec is RealBoundSpec) predicate

True for a real number which conforms to the given bounds.

Used in feature preconditions to specify a unitless numeric parameter.

ParameterTypeAdditional Info
boundSpec RealBoundSpec

Specifies a min, a max, and a default value. These values are possibly different in different units for the sake of round numbers.

To specify a parameter with different default value or different limits, use a different or custom RealBoundSpec.

LENGTH_BOUNDS const

A LengthBoundSpec for a positive or negative length.

NONNEGATIVE_LENGTH_BOUNDS const

A LengthBoundSpec for a length strictly greater than 0.

NONNEGATIVE_ZERO_INCLUSIVE_LENGTH_BOUNDS const

A LengthBoundSpec for a length greater than or equal to 0.

NONNEGATIVE_ZERO_DEFAULT_LENGTH_BOUNDS const

A LengthBoundSpec for a length greater than or equal to 0, with UI defaults of 0.0 for all units.

ZERO_DEFAULT_LENGTH_BOUNDS const

A LengthBoundSpec for a positive or negative length, with UI defaults of 0.0 for all units.

BLEND_BOUNDS const

A LengthBoundSpec for fillets and chamfers, with smaller defaults than NONNEGATIVE_LENGTH_BOUNDS (0.2 * inch, etc.).

SHELL_OFFSET_BOUNDS const

A LengthBoundSpec for a shell or offset thickness, with smaller defaults than NONNEGATIVE_LENGTH_BOUNDS. (0.1 * inch, etc.).

ZERO_INCLUSIVE_OFFSET_BOUNDS const

A LengthBoundSpec for an offset thickness, for a length greater than or equal to 0, with defaults greater than NONNEGATIVE_ZERO_INCLUSIVE_LENGTH_BOUNDS

ANGLE_360_BOUNDS const

An AngleBoundSpec for an angle between 0 and 360 degrees, defaulting to 30 degrees.

ANGLE_360_REVERSE_DEFAULT_BOUNDS const

An AngleBoundSpec for an angle between 0 and 360 degrees, defaulting to 330 degrees.

ANGLE_360_ZERO_DEFAULT_BOUNDS const

An AngleBoundSpec for an angle between 0 and 360 degrees, defaulting to 0 degrees.

ANGLE_360_FULL_DEFAULT_BOUNDS const

An AngleBoundSpec for an angle between 0 and 360 degrees, defaulting to 360 degrees.

ANGLE_STRICT_180_BOUNDS const

An AngleBoundSpec for an angle strictly less than 180 degrees.

ANGLE_STRICT_90_BOUNDS const

An AngleBoundSpec for an angle strictly less than 90 degrees.

POSITIVE_COUNT_BOUNDS const

An IntegerBoundSpec for an integer strictly greater than zero, defaulting to 2.

POSITIVE_REAL_BOUNDS const

A RealBoundSpec for a number greater than or equal to zero, defaulting to 1.

SCALE_BOUNDS const

A RealBoundSpec for the positive or negative scale factor on a transform, defaulting to 1.

LengthBoundSpec type

A spec to be used with the isLength predicate to define allowable lengths and customize UI behaviors for feature dialog parameters that take in a length.

A typical declaration looks like:

const MY_LENGTH_BOUNDS =
{
    (meter)      : [-500, 0.0025, 500],
    (centimeter) : .25,
    (millimeter) : 2.50,
    (inch)       : 0.1,
    (foot)       : 0.01,
    (yard)       : 0.0025
} as LengthBoundSpec;

The values for (meter), (inch), etc. define the bounds and default values for a feature parameter defined with MY_LENGTH_BOUNDS. The default values will be different for users who have set different default units.

Specifically, the first unit listed specified defines the minimum value, default value, and the maximum value (in terms of that unit) and the subsequent units define default values for those units, when a user with those default units first opens the dialog. The default value for a unit that is not listed is the default value of the first unit so { (inch) : [0, 1, 1e4] } as LengthBoundSpec will give a default of 2.54 cm in a Part Studio with centimeter units

canBeLengthBoundSpec (value) predicate

Typecheck for LengthBoundSpec

AngleBoundSpec type

A spec to be used with the isAngle predicate to define allowable angles and customize UI behaviors for feature dialog parameters that take in an angle.

A typical declaration looks like:

const ANGLE_360_BOUNDS =
{
    (degree) : [0, 30, 360],
    (radian) : 1
} as AngleBoundSpec;

For more information on what the various fields signify, see LengthBoundSpec.

canBeAngleBoundSpec (value) predicate

Typecheck for AngleBoundSpec

IntegerBoundSpec type

A spec to be used with the isInteger predicate to define allowable numbers and customize UI behaviors for feature dialog parameters that take in a number.

A typical declaration looks like:

const POSITIVE_COUNT_BOUNDS =
{
    (unitless) : [1, 2, 1e5]
} as IntegerBoundSpec;

For more information on what the various fields signify, see LengthBoundSpec.

canBeIntegerBoundSpec (value) predicate

Typecheck for IntegerBoundSpec

RealBoundSpec type

A spec to be used with the isReal predicate to define allowable real numbers and customize UI behaviors for feature dialog parameters that take in a real number.

A typical declaration looks like:

const POSITIVE_REAL_BOUNDS =
{
    (unitless) : [0, 1, 1e5]
} as RealBoundSpec;

For more information on what the various fields signify, see LengthBoundSpec.

canBeRealBoundSpec (value) predicate

Typecheck for RealBoundSpec

Onshape features

boolean

booleanBodies (context is Context, id is Id, definition is map)

The boolean feature. Performs an opBoolean after a possible opOffsetFace if the operation is subtraction.

convertNewBodyOpToBoolOp (operationType is NewBodyOperationType) returns BooleanOperationType

Maps a NewBodyOperationType (used in features like extrude) to its corresponding BooleanOperationType.

booleanStepTypePredicate (booleanDefinition is map) predicate

Predicate which specifies a field operationType of type NewBodyOperationType. Used by body-creating feature preconditions such as extrude, revolve, sweep or loft.

When used in a precondition, NewBodyOperationType creates UI like the extrude feature, with a horizontal list of the words "New", "Add", etc. When using this predicate in features, make sure to export an import of tool.fs so that NewBodyOperationType is visible to the Part Studios:

export import(path : "onshape/std/tool.fs", version : "");

booleanStepScopePredicate (booleanDefinition is map) predicate

Used by body-creating feature preconditions to allow post-creation booleans, specifying the merge scope (or "Merge with all") for that boolean.

Designed to be used together with booleanStepTypePredicate.

processNewBodyIfNeeded (context is Context, id is Id, definition is map, reconstructOp is function)

Performs a boolean operation (optionally). Used by body-creating features (like extrude) as the boolean step. On top of the regular boolean feature, converts the operationType and creates error bodies on failure.

ParameterTypeAdditional Info
id Id

identifier of the main feature

definition map
  • operationType
NewBodyOperationType

EXAMPLE

NewBodyOperationType.ADD performs a boolean union

EXAMPLE

NewBodyOperationType.NEW does nothing
  • defaultScope
boolean

Optional

EXAMPLE

true indicates merge scope of "everything else" (default)

EXAMPLE

false indicates merge scope is specified in booleanScope
  • booleanScope
Query

targets to use if defaultScope is false

  • seed
Query

Optional

If set, will be included in the tools section of the boolean.

reconstructOp function

A function which takes in an Id, and reconstructs the input to show to the user as error geometry in case the input is problematic or the boolean itself fails.

surfaceOperationTypePredicate (surfaceDefinition is map) predicate

Predicate which specifies a field surfaceOperationType of type NewSurfaceOperationType. Used by surface-creating feature preconditions such as revolve, sweep or loft.

When used in a precondition, NewSurfaceOperationType creates UI like the sweep feature, with a horizontal list of the words "New" and "Add". When using this predicate in features, make sure to export an import of tool.fs so that NewSurfaceOperationType is visible to the Part Studios:

export import(path : "onshape/std/tool.fs", version : "");

surfaceJoinStepScopePredicate (definition is map) predicate

Used by surface-creating feature preconditions to allow post-creation booleans, specifying the merge scope (or "Merge with all") for that boolean.

Designed to be used together with surfaceOperationTypePredicate.

joinSurfaceBodies (context is Context, id is Id, matches is array, makeSolid is boolean, reconstructOp is function)

Joins surface bodies at the matching edges.

ParameterTypeAdditional Info
id Id

identifier of the feature

matches array

Matching edges of the sheet bodies. Each matching element is a map with fields topology1, topology2 and matchType; where topology1 and topology2 are a pair of matching edges of two sheet bodies and matchType is the type of match TopologyMatchType between them. Owner body of matches[0].topology1 survives in the join operation.

makeSolid boolean

Tries to join the surfaces into a solid

reconstructOp function

A function which takes in an Id, and reconstructs the input to show to the user as error geometry in case the input is problematic or the join itself fails.

bridgingCurve

BridgingCurveMatchType enum

Specifies how the bridging curve will match the vertex or edge at each side

ValueDescription
POSITION

The bridging curve will end at the provided vertex. Direction of the curve is unspecified

TANGENCY

The bridging curve will end at the vertex and the curve will be tangent to the edge

CURVATURE

The bridging curve will end at the vertex and the curve will have same curvature as the edge at the vertex

BIAS_BOUNDS const

A RealBoundSpec for bias of a tangency/tangency bridge, defaulting to 0.5.

bridgingCurve (context is Context, id is Id, definition is map)

Creates a curve between two points, optionally with matching of tangency or curvature to other curves at that point

chamfer

chamfer (context is Context, id is Id, definition is map)

The chamfer feature directly performs an opChamfer operation.

circularPattern

circularPattern (context is Context, id is Id, definition is map)

Performs a body, face, or feature circular pattern. Internally, performs an applyPattern, which in turn performs an opPattern or, for a feature pattern, calls the feature function.

ParameterTypeAdditional Info
definition map
  • patternType
PatternType

Optional

Specifies a PART, FEATURE, or FACE pattern. Default is PART.

  • entities
Query

Required if patternType is PART

The parts to pattern.

EXAMPLE

qCreatedBy(id + "extrude1", EntityType.BODY)
  • faces
Query

Required if patternType is FACE

The faces to pattern.

  • instanceFunction
FeatureList

Required if patternType is FEATURE

The FeatureList of the features to pattern.

  • axis
Query

The axis of the pattern.

  • angle
ValueWithUnits

The angle between each pattern instance, or the total angle spanned by the pattern if equalSpace is true.

EXAMPLE

360 * degree
  • instanceCount
number

The resulting number of pattern entities, unless isCentered is true.

EXAMPLE

4 to have 4 resulting pattern entities (including the seed).
  • oppositeDirection
boolean

Optional

EXAMPLE

true to switch the direction of the pattern around the axis.
  • equalSpace
boolean

Optional

EXAMPLE

true for the entire pattern to lie within angle

EXAMPLE

false for there to be angle between each pattern instance (default)
  • isCentered
boolean

Optional

Whether to center the pattern on the seed. When set to true, instanceCount - 1 pattern entities are created in each direction around the axis. Default is false.

  • operationType
NewBodyOperationType

Optional

Specifies how the newly created body will be merged with existing bodies.

  • defaultScope
boolean

Optional

EXAMPLE

true to merge with all other bodies

EXAMPLE

false to merge with booleanScope
  • booleanScope
Query

Required if defaultScope is false

The specified bodies to merge with.

compositeCurve

compositeCurve (context is Context, id is Id, definition is map)

Creates one or more Curves that are a combination of edges from various sources, be they parts, surfaces, sketches or other Curves.

cplane

CPlaneType enum

The method of defining a construction plane.

ValueDescription
OFFSET
PLANE_POINT
LINE_ANGLE
LINE_POINT
THREE_POINT
MID_PLANE
CURVE_POINT

cPlane (context is Context, id is Id, definition is map)

Creates a construction plane feature by calling opPlane.

cPlaneLogic (context is Context, id is Id, oldDefinition is map, definition is map) returns map

Heuristics to determine the type of plane to be constructed, based on user preselection.

curvePattern

curvePattern (context is Context, id is Id, definition is map)

Performs a body, face, or feature curve pattern. Internally, performs an applyPattern, which in turn performs an opPattern or, for a feature pattern, calls the feature function.

ParameterTypeAdditional Info
definition map
  • patternType
PatternType

Optional

Specifies a PART, FEATURE, or FACE pattern. Default is PART.

  • entities
Query

Required if patternType is PART

The parts to pattern.

EXAMPLE

qCreatedBy(id + "extrude1", EntityType.BODY)
  • faces
Query

Required if patternType is FACE

The faces to pattern.

  • instanceFunction
FeatureList

Required if patternType is FEATURE

The FeatureList of the features to pattern.

  • edges
Query

A Query for a set of edges to pattern along. The edges must form a continuous path.

  • instanceCount
number

The resulting number of pattern entities.

EXAMPLE

2 to have 2 resulting pattern entities (including the seed).
  • keepOrientation
boolean

Optional

EXAMPLE

true for the pattern entities to keep the orientation of the seed

EXAMPLE

false for the pattern entities to reorient along the path (default)
  • operationType
NewBodyOperationType

Optional

Specifies how the newly created body will be merged with existing bodies.

  • defaultScope
boolean

Optional

EXAMPLE

true to merge with all other bodies

EXAMPLE

false to merge with booleanScope
  • booleanScope
Query

Required if defaultScope is false

The specified bodies to merge with.

deleteBodies

deleteBodies (context is Context, id is Id, definition is map)

Feature performing an opDeleteBodies.

deleteFace

DeleteFaceType enum

Specifies how the void resulting from delete face should be closed, if at all.

ValueDescription
HEAL

Close void by shrinking or growing adjacent faces.

CAP

Close void by a simple surface passing through all edges.

VOID

Do not close the void. Creates surface out of solids.

deleteFace (context is Context, id is Id, definition is map)

Feature performing an opDeleteFace. Has options to heal the void created by removing the selected faces, or to leave it open.

draft

draft (context is Context, id is Id, definition is map)

Feature performing an opDraft.

enclose

enclose (context is Context, id is Id, definition is map)

Feature performing an opEnclose.

extrude

SecondDirectionBoundingType enum

Similar to BoundingType, but made for the second direction of an extrude. Thus, SYMMETRIC is not an option.

ValueDescription
BLIND
UP_TO_NEXT
UP_TO_SURFACE
UP_TO_BODY
UP_TO_VERTEX
THROUGH_ALL

extrude (context is Context, id is Id, definition is map)

Create an extrude, as used in Onshape's extrude feature.

Internally, performs an opExtrude, followed by an opBoolean, possibly followed by a opDraft, possibly in two directions. If creating a simple extrusion, prefer using opExtrude alone.

ParameterTypeAdditional Info
definition map
  • bodyType
ToolBodyType

Optional

Specifies a SOLID or SURFACE extrude. Default is SOLID.

  • entities
Query

Required if bodyType is SOLID

The planar faces and/or sketch regions to extrude.

EXAMPLE

qSketchRegion(id + "sketch1") specifies all sketch regions of a given sketch.
  • surfaceEntities
Query

Required if bodyType is SURFACE

The sketch curves to extrude.

EXAMPLE

qCreatedBy(id + "sketch1", EntityType.EDGE)
  • endBound
BoundingType

Optional

The end bounding condition for the extrude. Default is BLIND.

  • oppositeDirection
boolean

Optional

EXAMPLE

true to flip the direction of the extrude to point opposite the face/sketch normal.
  • depth
ValueWithUnits

Required if endBound is BLIND or SYMMETRIC

A length specifying the extrude depth. For a symmetric extrude, specifies the full extrude depth. For a blind extrude, specifies the depth of the first extrude direction.

EXAMPLE

0.5 * inch
  • endBoundEntityFace
Query

Required if endBound is UP_TO_SURFACE

Specifies the face or surface to bound the extrude.

  • endBoundEntityBody
Query

Required if endBound is UP_TO_BODY

Specifies the surface or solid body to bound the extrude.

  • endBoundEntityVertex
Query

Required if endBound is UP_TO_VERTEX

Specifies the vertex to bound the extrude.

  • hasOffset
boolean

Optional

EXAMPLE

true to add a translational offset from the selected face, surface, solid body or vertex.
  • offsetDistance
ValueWithUnits

Required if offset is true

The translational distance between the selected face, surface, solid body or vertex and the cap of the extrude.

EXAMPLE

0.5 * inch
  • offsetOppositeDirection
boolean

Optional

EXAMPLE

false to offset away from the selected end bound (default)

EXAMPLE

true to offset into the selected end bound
  • hasDraft
boolean

Optional

EXAMPLE

true to add a draft to the extrude.
  • draftAngle
ValueWithUnits

Required if hasDraft is true

The angle, as measured from the extrude direction, at which to draft.

EXAMPLE

10 * degree
  • draftPullDirection
boolean

Optional

EXAMPLE

false to draft outwards (default)

EXAMPLE

true to draft inwards
  • hasSecondDirection
boolean

Optional

EXAMPLE

true to specify a second direction.
  • secondDirectionBound
SecondDirectionBoundingType

Optional

The bounding type of the second direction. Can be different from the bounding type of the first direction.

  • secondDirectionOppositeDirection
boolean

Optional

EXAMPLE

true will flip the second end direction to align with the plane/face's normal.
  • secondDirectionDepth
ValueWithUnits

Required if secondDirectionBound is BLIND

A length specifying the second direction's extrude depth.

  • secondDirectionBoundEntityFace
Query

Required if secondDirectionBound is UP_TO_SURFACE

specifies the face or surface to bound the extrude.

  • secondDirectionBoundEntityBody
Query

Required if secondDirectionBound is UP_TO_BODY

specifies the surface or solid body to bound the extrude.

  • secondDirectionBoundEntityVertex
Query

Required if secondDirectionBound is UP_TO_VERTEX

specifies the vertex to bound the extrude.

  • hasSecondDirectionOffset
boolean

Optional

EXAMPLE

true to add a translational offset from the selected face, surface, solid body or vertex.
  • secondDirectionOffsetDistance
ValueWithUnits

Required if offset is true

The translational distance between the selected face, surface, solid body or vertex and the cap of the extrude.

EXAMPLE

0.5 * inch
  • secondDirectionOffsetOppositeDirection
boolean

Optional

EXAMPLE

false to offset away from the selected second direction end bound (default)

EXAMPLE

true to offset into the selected second direction end bound
  • hasSecondDirectionDraft
boolean

Optional

EXAMPLE

true to add a draft to the second direction extrude.
  • secondDirectionDraftPullDirection
boolean

Optional

EXAMPLE

false to draft the second direction outwards (default)

EXAMPLE

true to draft the second direction inwards
  • operationType
NewBodyOperationType

Optional

Specifies how the newly created body will be merged with existing bodies.

  • defaultScope
boolean

Optional

EXAMPLE

true to merge with all other bodies

EXAMPLE

false to merge with booleanScope
  • booleanScope
Query

Required if defaultScope is false

The specified bodies to merge with.

fillSurface

fill (context is Context, id is Id, definition is map)

Creates a surface bounded by input edges with prescribed continuity conditions, using opFillSurface.

fillet

fillet (context is Context, id is Id, definition is map)

Feature performing an opFillet.

fitSpline

fitSpline (context is Context, id is Id, definition is map)

Feature performing an opFitSpline

helix

Direction enum

Describes the direction a helix turns while traveling along its axis.

ValueDescription
CW

Clockwise.

CCW

Counterclockwise.

HelixType enum

Specifies how the helix will be defined.

ValueDescription
TURNS

User defines the number of turns, and the helical pitch is computed based on the input entity's height.

PITCH

User defines the helical pitch, and the number of turns is computed based on the input entity's height.

HEIGHT_TURNS

User defines both the height and number of turns, and the height is computed based on these terms.

HEIGHT_PITCH

User defines both the height and helical pitch, and the number of turns is computed based on these terms.

TURNS_PITCH

User defines both the number of turns and helical pitch, and the height is computed based on these terms.

helix (context is Context, id is Id, definition is map)

Feature performing an opHelix.

helixLogic (context is Context, id is Id, oldDefinition is map, definition is map) returns map

Preselection Logic: Heuristics to determine the type of helix to be constructed, based on user preselection.

hole

HoleEndStyle enum

Defines the end bound for the hole cut.

ValueDescription
THROUGH

Cut holes with a through-all extrude.

BLIND

Cut holes to a specific depth.

BLIND_IN_LAST

Cut holes through all parts but the last, then cut to a specific depth in the last part.

hole const

Creates holes of specific dimensions and style, based either on standard hole size, or by user-defined values. Each hole's position and orientation are specified using sketch points.

CSINK_ANGLE_BOUNDS const

Angle bounds for a hole countersink.

importDerived

BuildFunction type

A special type for functions defined as the build function for a Part Studio, which return a context containing parts.

canBeBuildFunction (value) predicate

Typecheck for BuildFunction

importDerived (context is Context, id is Id, definition is map)

Feature performing an opMergeContexts, used for including parts in one Part Studio that were designed in another.

When a derived part from Part Studio 1 is created in a Part Studio 2, code is generated in Part Studio 2 which imports Part Studio 1 into a namespace. The build function from that namespace is passed into this feature, where the build function is called and run in its entirety.

If not all bodies from the derived Part Studio are included, the missing bodies are deleted after building the Part Studio, but before merging in its context.

importForeign

ForeignId type

A string representing a foreign element, such as the dataId from an imported tab.

canBeForeignId (value) predicate

Typecheck for ForeignId

importForeign (context is Context, id is Id, definition is map)

Feature performing an opImportForeign, transforming the result if necessary.

linearPattern

linearPattern (context is Context, id is Id, definition is map)

Performs a body, face, or feature linear pattern. Internally, performs an applyPattern, which in turn performs an opPattern or, for a feature pattern, calls the feature function.

ParameterTypeAdditional Info
definition map
  • patternType
PatternType

Optional

Specifies a PART, FEATURE, or FACE pattern. Default is PART.

  • entities
Query

Required if patternType is PART

The parts to pattern.

EXAMPLE

qCreatedBy(id + "extrude1", EntityType.BODY)
  • faces
Query

Required if patternType is FACE

The faces to pattern.

  • instanceFunction
FeatureList

Required if patternType is FEATURE

The FeatureList of the features to pattern.

  • directionOne
Query

The direction of the pattern.

EXAMPLE

qCreatedBy(newId() + "Right", EntityType.FACE)
  • distance
ValueWithUnits

The distance between each pattern entity.

EXAMPLE

1.0 * inch to space the pattern entities 1 inch apart.
  • instanceCount
number

The resulting number of pattern entities, unless isCentered is true.

EXAMPLE

2 to have 2 resulting pattern entities (including the seed).
  • oppositeDirection
boolean

Optional

EXAMPLE

true to switch the direction of the pattern along directionOne.
  • isCentered
boolean

Optional

Whether to center the pattern on the seed. When set to true, instanceCount - 1 pattern entities are created along each direction of directionOne. Default is false.

  • hasSecondDir
boolean

Optional

EXAMPLE

true if the pattern should extend in two directions rather than one, creating a grid of pattern entities.
  • directionTwo
Query

Required if hasSecondDir is true

The second direction of the pattern.

  • distanceTwo
ValueWithUnits

Required if hasSecondDir is true

The distance between each pattern entity in the second direction.

  • instanceCountTwo
number

Required if hasSecondDir is true

The resulting number of pattern entities in the second direction, unless isCentered is true.

  • oppositeDirectionTwo
boolean

Optional

EXAMPLE

true to switch the direction of the pattern along directionTwo.
  • isCenteredTwo
boolean

Optional

Whether to center the second direction of the pattern on the seed. When set to true, instanceCount - 1 pattern entities are created along each direction of directionTwo. Default is false.

  • operationType
NewBodyOperationType

Optional

Specifies how the newly created body will be merged with existing bodies.

  • defaultScope
boolean

Optional

EXAMPLE

true to merge with all other bodies

EXAMPLE

false to merge with booleanScope
  • booleanScope
Query

Required if defaultScope is false

The specified bodies to merge with.

loft

LoftEndDerivativeType enum

Specifies an end condition for one side of a loft.

ValueDescription
DEFAULT
NORMAL_TO_PROFILE
TANGENT_TO_PROFILE
MATCH_TANGENT
MATCH_CURVATURE

LoftGuideDerivativeType enum

Specifies derivative condition for a guide

ValueDescription
DEFAULT
MATCH_TANGENT
MATCH_CURVATURE

loft (context is Context, id is Id, definition is map)

Feature performing an opLoft.

mateConnector

mateConnector (context is Context, id is Id, definition is map)

Feature performing an opMateConnector.

mirror

mirror (context is Context, id is Id, definition is map)

Feature creating a single copy of some features, bodies, or faces, mirrored about a given entity. Internally, performs an applyPattern, which in turn performs an opPattern or, for a feature mirror, calls the feature function.

mirrorEditLogic (context is Context, id is Id, oldDefinition is map, definition is map, specifiedParameters is map, hiddenBodies is Query) returns map

implements heuristics for mirror feature

modifyFillet

ModifyFilletType enum

Defines the action of a modifyFillet feature.

ValueDescription
CHANGE_RADIUS
REMOVE_FILLET

modifyFillet (context is Context, id is Id, definition is map)

Feature performing an opModifyFillet.

moveFace

moveFace (context is Context, id is Id, definition is map)

Feature performing an opMoveFace.

moveFaceEditingLogic (context is Context, id is Id, oldDefinition is map, definition is map, specifiedParameters is map) returns map

Editing logic. Fills in translation direction. Fills in offset distance as minimal clearance.

deripEdges (context is Context, id is Id, edges is Query) returns boolean

Splits input sheet metal edges and adjusts them to lie on corresponding sheet metal part faces.

offsetSurface

offsetSurface (context is Context, id is Id, definition is map)

Feature performing an opExtractSurface. Allows creation of an offset surface from faces, surfaces, or sketch regions. Offset may be zero. Offset direction may be flipped using the oppositeDirection flag.

projectCurves

projectCurves (context is Context, id is Id, definition is map)

Performs opExtrude twice to extrude two sketches and then opBoolean to produce the intersection of the extruded surfaces

replaceFace

replaceFace (context is Context, id is Id, definition is map)

Feature performing an opReplaceFace.

revolve

RevolveType enum

Specifies how a revolve's end condition should be defined.

ValueDescription
FULL
ONE_DIRECTION
SYMMETRIC
TWO_DIRECTIONS

revolve (context is Context, id is Id, definition is map)

Feature performing an opRevolve, followed by an opBoolean. For simple revolves, prefer using opRevolve directly.

rib

RibExtrusionDirection enum

Specifies the direction of the rib extrusion starting from the profile going up to the part.

ValueDescription
PARALLEL_TO_SKETCH_PLANE

The direction of the rib extrusion goes parallel to the profile sketch plane.

NORMAL_TO_SKETCH_PLANE

The direction of the rib extrusion goes normal to the profile sketch plane.

rib (context is Context, id is Id, definition is map)

Creates ribs from selected profiles. The ribs can be either free standing or merged with their mating part. Profiles must be non-construction sketch edges.

ParameterTypeAdditional Info
definition map
  • profiles
Query

Edges which form the center lines of the ribs.

  • parts
Query

Parts which form the boundary of the ribs.

  • thickness
ValueWithUnits

Thickness of the ribs.

  • ribExtrusionDirection
RibExtrusionDirection

Whether the rib is extruded perpendicular or parallel to the plane.

  • oppositeDirection
boolean

Whether the ribs are extruded in the positive or negative direction.

  • extendProfilesUpToPart
boolean

Whether the ribs are extruded up to a boundary part.

  • mergeRibs
boolean

Whether the ribs are merged with the mating part.

sheetMetalAttribute

Modules prefixed with "sheetMetal" here and below control functionality related to working with sheet metal models in Onshape.

Sheet metal models are created with the sheetMetalStart feature. The geometry of these models is not modifiable with ordinary geometry operations, and an operation which attempts to modify a sheet metal model will always throw the error ErrorStringEnum.SHEET_METAL_PARTS_PROHIBITED

Onshape's sheet metal operations are instead encapsulated in features defined with defineSheetMetalFeature. These features directly modify the underlying sheet metal master body, a hidden surface body not accessible from other features. The master body (along with SMAttributes set on its entities) provides the information necessary for updateSheetMetalGeometry to build both sheet metal bodies: the 3D folded body and the flat pattern. The result is simultaneous sheet metal editing, where geometry and errors are always available to the end user on both the folded and the flat sheet metal models.

Most custom features will function only on bodies which are not active sheet metal, because the feature's effects are not readily translatable from the folded model back to the flattened master model. A custom feature's user will typically discover this when an operation within the custom feature throws a SHEET_METAL_PARTS_PROHIBITED error, giving the user-facing message "Active sheet metal models are not allowed."

Additionally, a custom feature's query parameter can disallow selection of entities from sheet metal bodies using the ActiveSheetMetal.NO filter. Any other query can be filtered for non-sheet-metal geometry using separateSheetMetalQueries.

SMAttribute type

Sheet metal object definition attribute type.

canBeSMAttribute (value) predicate

parameters in SMAttribute (e.g. radius in BEND, angle in JOINT, thickness in MODEL) are specified as maps

EXAMPLE

{
 value : {ValueWithUnits},
 canBeEdited : {boolean},
 controllingFeatureId : {string}, : feature to be edited when editing this parameter
 parameterIdInFeature : {string}
 }

smAttributeDefault const

Empty map as SMAttribute convenient for attribute lookup

asSMAttribute (value is map) returns SMAttribute

Attach SMAttribute type to a map. convenient for attribute lookup and queries.

makeSMJointAttribute (attributeId is string) returns SMAttribute

Start SMAttribute for joint.

makeSMWallAttribute (attributeId is string) returns SMAttribute

Start SMAttribute for wall.

makeSMCornerAttribute (attributeId is string) returns SMAttribute

Start SMAttribute for corner.

getSmObjectTypeAttributes (context is Context, topology is Query, objectType is SMObjectType) returns array

Get attributes with matching objectType.

clearSmAttributes (context is Context, entities is Query)

Clear SM attributes from entities.

hasSheetMetalAttribute (context is Context, entities is Query, objectType is SMObjectType) returns boolean

Check for presence of SMAttribute types.

replaceSMAttribute (context is Context, existingAttribute is SMAttribute, newAttribute is SMAttribute) returns Query

For all entities annotated with attribute matching existingAttribute pattern, replace it with newAttribute. Return query for entities whose attributes have been modified.

getSMDefinitionEntities (context is Context, selection is Query) returns array

Find sheet metal master body entities corresponding to feature input.

isSheetMetalModelActive (context is Context, sheetMetalModel is Query) returns boolean

Check if sheet metal model is active.

areEntitiesFromSingleSheetMetalModel (context is Context, entities is Query) returns map

Check if all entities belong to the same sheet metal model

areEntitiesFromSingleActiveSheetMetalModel (context is Context, entities is Query) returns boolean

Check if all entities belong to the same active sheet metal model

getWallAttribute (context is Context, wallFace is Query)

Get wall attribute on a single entity

getJointAttribute (context is Context, jointEdge is Query)

Get joint attribute on a single entity

getCornerAttribute (context is Context, cornerVertex is Query)

Get corner attribute on a single entity

SMAssociationAttribute type

Used by sheet metal features to maintain correspondence between master sheet body entities and solid body entities.

canBeSMAssociationAttribute (value) predicate

Association attribute stores attributeId. The association is established by assigning same attribute to associated entities. Every entity in sheet metal master sheet body has a distinct association attribute.

makeSMAssociationAttribute (attributeId is string) returns SMAssociationAttribute

create an association attribute

assignSmAssociationAttributes (context is Context, entities is Query)

Assign new association attributes to entities using their transient queries to generate attribute ids.

SMCornerBreak type

Information corresponding to a single sheet metal corner break (fillet or chamfer)

canBeSMCornerBreak (value) predicate

Corner break must hold the break style, the range (radius and distance of fillet and chamfer respectively), and the wallId of the wall that owns the corner.

makeSMCornerBreak (cornerBreakStyle is SMCornerBreakStyle, range is ValueWithUnits, wallId is string) returns SMCornerBreak

Create a corner break

addCornerBreakToSMAttribute (attribute is SMAttribute, cornerBreakMap is map) returns SMAttribute

Adds an SMCornerBreak and any additional information to an SMAttribute, initializing the cornerBreaks array if necessary.

findCornerBreak (attribute is SMAttribute, wallId is string)

Finds an SMCornerBreak in attribute corresponding to wallId, returns undefined if nothing found

updateCornerAttribute (context is Context, vertex is Query, attribute is SMAttribute)

Clears existing SMAttribute, sets new one only if non-trivial

sanitizeControllingInformation (context is Context, attribute is SMAttribute, replaceExisting is boolean) returns SMAttribute

Removes all controllingFeatureId and parameterIdInFeature information from an SMAttribute. Replaces the provided attribute with sanitized attribute if replaceExisting is true. Return the sanitized attribute

Fail if the attribute is a model attribute as a safety precaution, as removing the controllingFeatureId information from a model attribute would invalidate it from being the same model attribute as it was before

sheetMetalBendRelief

sheetMetalBendRelief const

Bend relief feature is used to override default bend relief of sheet metal model at individual bend end.

sheetMetalCorner

sheetMetalCorner const

Corner feature is used to override default sheet metal model corner relief style or dimensions for an individual corner

sheetMetalEnd

sheetMetalEnd const

Deactivate the sheet metal model of selected parts. Continued modeling on deactivated sheet metal parts will not be represented in the flat pattern or the table.

sheetMetalFlange

SMFlangeAlignment enum

Describes the position of a virtual sharp with respect to "flange face", defined as the face that corresponds to the edge selected for flange in the underlying sheet.

For Middle alignment, the virtual sharp at the intersection of the existing sheet and the sheet that corresponds to the flange wall, lies in the middle of the flange face.

For Inner alignment, the virtual sharp at the intersection of the planes defined by the faces of the solid to the interior of the bend, lies coincident with the edge of the flange face closest to the bend.

For Outer alignment, the virtual sharp at the intersection of the planes defined by the faces of the solid to the exterior of the bend, lies coincident with the edge of the flange face farthest from the bend.

ValueDescription
INNER
OUTER
MIDDLE

sheetMetalFlange const

Create sheet metal flanges on selected edges of sheet metal parts. Length of flange may be defined by distance (as measured from the virtual sharp along outer edge of wall) or limiting entity. Bend angle may be flipped using the oppositeDirection flag. When auto-miter is not selected, flange sides are rotated by miter angle.

sheetMetalJoint

sheetMetalJoint const

sheetMetalJoint feature modifies sheet metal joint by changing its attribute.

sheetMetalMakeJoint

sheetMetalMakeJoint const

Produces a sheet metal joint, currently as a rip only, by extending or trimming walls of selected edges. Rip is created as an edge joint by default.

sheetMetalStart

SMProcessType enum

Method of initializing sheet metal model

ValueDescription
CONVERT
EXTRUDE
THICKEN

SMExtrudeBoundingType enum

Bounding type used with SMProcessType.EXTRUDE

ValueDescription
BLIND
SYMMETRIC

SMCornerStrategyType enum

Default corner relief style setting

ValueDescription
SIZED_RECTANGLE
RECTANGLE
SIZED_ROUND
ROUND
CLOSED
SIMPLE

SMBendStrategyType enum

Default bend relief style setting

ValueDescription
RECTANGLE
OBROUND
TEAR

CORNER_RELIEF_SCALE_BOUNDS const

Corner relief scale bounds

BEND_RELIEF_SCALE_BOUNDS const

Bend relief scale bounds

sheetMetalStart const

Create and activate a sheet metal model by converting existing parts, extruding sketch curves or thickening. All operations on an active sheet metal model will automatically be represented in the flat pattern and the table. Sheet metal models may consist of multiple parts. Multiple sheet metal models can be active.

sheetMetalUtils

defineSheetMetalFeature (feature is function, defaults is map) returns function

Exposes sheet metal definition sheet body to the queries within feature.

updateSheetMetalGeometry (context is Context, id is Id, args is map)

Based on current state of sheet metal definition sheet body update solid bodies

ParameterTypeAdditional Info
args map
  • entities
Query

sheet metal definition entities changed (or attributes changed) in this feature

  • deletedAttributes
array

associated attributes of deleted sheet metal definition entities

  • associatedChanges
Query

sheet metal definition entities representing the change of this feature

SMThicknessDirection enum

Direction of material from definition body. For old models (before V629_SM_MODEL_FRONT_N_BACK) It is BOTH, for new models FRONT/BACK depends on oppositeDirection in sheetMetalStart

ValueDescription
BOTH
FRONT
BACK

annotateSmSurfaceBodies (context is Context, id is Id, args is map, objectCount is number) returns number

Assign SMAttributes to topology of sheet metal definition sheet body

ParameterTypeAdditional Info
args map
  • surfaceBodies
Query
  • bendEdgesAndFaces
Query
  • specialRadiiBends
array

array of pairs "(edge, bendRadius)"

  • defaultRadius
ValueWithUnits

bend radius to be applied to edges in bendEdgesAndFaces

  • controlsThickness
boolean
  • thickness
ValueWithUnits
  • defaultCornerReliefScale
number
  • defaultRoundReliefDiameter
ValueWithUnits
  • defaultSquareReliefWidth
ValueWithUnits
  • defaultBendReliefScale
number

edgeAngle (context is Context, edge is Query) returns ValueWithUnits

Compute angle between face normals at edge mid point.

K_FACTOR_BOUNDS const

A RealBoundSpec for sheet metal K-factor between 0. and 1., defaulting to .45.

ROLLED_K_FACTOR_BOUNDS const

A RealBoundSpec for rolled sheet metal K-factor between 0. and 1., defaulting to .5.

SM_MINIMAL_CLEARANCE_BOUNDS const

A LengthBoundSpec for minimal clearance of sheet metal rips

SM_BEND_RADIUS_BOUNDS const

A LengthBoundSpec for bend radius in sheet metal features

SM_THICKNESS_BOUNDS const

A LengthBoundSpec for thickness in sheet metal features. default to (1/16)" (i.e. steel)

SM_RELIEF_SIZE_BOUNDS const

A LengthBoundSpec for relief size, corners or bend relief, in sheet metal features.

partitionSheetMetalParts (context is Context, allParts is Query)

Partitions allParts into non-sheet metal parts and sheet metal parts. To preserve existing behavior of code the returned non-sm query is exactly the same as what is passed in for non-sm cases and a query is returned for them. The sheet metal results will usually be iterated through and so are returned as a map with the keys being the sheet metal ID and the values being the parts associated with that model.

getActiveSheetMetalId (context is Context, query is Query)

Get the first id of active sheet metal model the entities of query belong to.

getModelParameters (context is Context, model is Query) returns map

Extract sheet metal model parameters in a convenient form

separateSheetMetalQueries (context is Context, targets is Query) returns map

Separates queries which are part of an active sheet metal model (either in the folded model or the flat pattern).

ReturnTypeDescription
map
  • sheetMetalQueries
Query

targets which are part of an active sheet metal model

  • nonSheetMetalQueries
Query

targets which are not part of an active sheet metal model

sheetMetalExtendSheetBodyCall (context is Context, id is Id, definition is map)

Wrapper around opExtendSheetBody used in sheet metal operations to handle remapping of cornerBreak data

getSMDefinitionEntities (context is Context, selection is Query, entityType is EntityType) returns array

A function for getting associated sheet metal entities outside of a sheet metal feature.

getOwnerSMModel (context is Context, selection is Query) returns array

Returns an array of sm models associated with selection in a way that works outside of sheet metal features.

qSMCorrespondingInPart (context is Context, selection is Query, entityType is EntityType) returns Query

Returns a query for all sheet metal part entities of entityType related to the input sheet metal model entities.

shell

shell (context is Context, id is Id, definition is map)

Feature performing an opShell.

splitpart

SplitType enum

Defines whether a split should split whole parts, or just faces.

ValueDescription
PART
FACE

splitPart (context is Context, id is Id, definition is map)

Feature performing an opSplitPart.

sweep

sweep (context is Context, id is Id, definition is map)

Feature performing an opSweep, followed by an opBoolean. For simple sweeps, prefer using opSweep directly.

thicken

thicken (context is Context, id is Id, definition is map)

Feature performing an opThicken, followed by an opBoolean. For simple thickens, prefer using opThicken directly.

thickenEditLogic (context is Context, id is Id, oldDefinition is map, definition is map, specifiedParameters is map, hiddenBodies is Query) returns map

implements heuristics for thicken feature

transformCopy

TransformType enum

Defines how a the transform for a transform feature should be specified.

ValueDescription
TRANSLATION_ENTITY
TRANSLATION_DISTANCE
TRANSLATION_3D
TRANSFORM_MATE_CONNECTORS
ROTATION
COPY
SCALE_UNIFORMLY

transform (context is Context, id is Id, definition is map)

Move and/or rotate bodies or mate connectors with a single Transform, constructed with input according to the selected TransformType.

Internally, performs an opTransform when not copying, and an opPattern when copying. For simple transforms, prefer calling opTransform or opPattern directly.

ParameterTypeAdditional Info
definition map
  • entities
Query

The bodies or mate connectors to transform. An error is thrown if anything else is included.

EXAMPLE

qCreatedBy(id + "extrude1", EntityType.BODY)
  • transformType
TransformType

Defines how the transform type should be specified.

EXAMPLE

TransformType.TRANSLATION_3D
  • dx
ValueWithUnits

Required if transformType is TransformType.TRANSLATION_3D

A value with length units specifying the distance to move in the world x direction.

EXAMPLE

1 * inch
  • dy
ValueWithUnits

Required if transformType is TransformType.TRANSLATION_3D

A value with length units specifying the distance to move in the world y direction.

EXAMPLE

1 * inch
  • dz
ValueWithUnits

Required if transformType is TransformType.TRANSLATION_3D

A value with length units specifying the distance to move in the world z direction.

EXAMPLE

1 * inch
  • transformLine
Query

Required if transformType is TransformType.TRANSLATION_ENTITY

A Query for either a single line or a pair of points, specifying the direction and distance to transform.

  • oppositeDirectionEntity
boolean

Required if transformType is TransformType.TRANSLATION_ENTITY

EXAMPLE

true to flip the transform direction.
  • transformAxis
Query

Required if transformType is TransformType.ROTATION

A Query for a line, cylinder, etc. to specify the transform direction.

  • angle
ValueWithUnits

Required if transformType is TransformType.ROTATION

A value with angle units specifying the angle to rotate.

  • transformDirection
Query

Required if transformType is TransformType.TRANSLATION_DISTANCE

A Query for either a single line or a pair of points, specifying the direction to transform.

  • distance
ValueWithUnits

Required if transformType is TransformType.TRANSLATION_DISTANCE

A value with length units specifying the distance to move.

  • oppositeDirection
boolean

Required if transformType is TransformType.TRANSLATION_DISTANCE or TransformType.ROTATION

EXAMPLE

true to transform in the opposite direction.
  • scale
number

Required if transformType is TransformType.SCALE_UNIFORMLY

A positive real number specifying the scale factor.

  • scalePoint
Query

Required if transformType is TransformType.SCALE_UNIFORMLY

  • baseConnector
Query

Required if transformType is TransformType.TRANSFORM_MATE_CONNECTORS

The mate connector to transform from.

  • destinationConnector
Query

Required if transformType is TransformType.TRANSFORM_MATE_CONNECTORS

The mate connector to transform to.

  • oppositeDirectionMateAxis
boolean

Required if transformType is TransformType.TRANSFORM_MATE_CONNECTORS

  • secondaryAxisType
MateConnectorAxisType

Required if transformType is TransformType.TRANSFORM_MATE_CONNECTORS

  • makeCopy
boolean

Required if transformType is not TransformType.COPY

EXAMPLE

true to keep the original bodies.

copyPart (context is Context, id is Id, definition is map)

Deprecated: Use opPattern, or the transform feature instead.

variable

VariableType enum

Specifies the type of values assignVariable is allowed to set.

ValueDescription
LENGTH
ANGLE
NUMBER
ANY

The variable can be any immutable FeatureScript value; boxes and builtins are not allowed.

assignVariable (context is Context, id is Id, definition is map)

Feature performing a setVariable allowing a user to assign a FeatureScript value to a context variable. This variable may be retrieved within a feature by calling getVariable, or in a Part Studio using # syntax (e.g. #foo) inside any parameter which allows an expression (including the value parameter of another variable!)

ParameterTypeAdditional Info
definition map
  • variableType
VariableType

The type of variable. If it is not ANY, the value is restricted to be a length, angle, or number and is passed through the lengthValue, angleValue, or numberValue field, respectively.

  • name
string

Must be an identifier.

  • lengthValue
ValueWithUnits

Used if variableType is LENGTH.

  • angleValue
ValueWithUnits

Used if variableType is ANGLE.

  • numberValue
number

Used if variableType is NUMBER.

  • anyValue

Used if variableType is ANY. Can be any immutable FeatureScript value, including a length, an array, or a function.

verifyVariableName (name is string)

Throws an error if name is not a valid identifier.

makeLookupFunction (context is Context, id is Id) returns function

Make a function to look up variables from the given context. Used in generated part studio code.

enums

booleanoperationtype

BooleanOperationType enum

See opBoolean.

ValueDescription
UNION
SUBTRACTION
INTERSECTION
SUBTRACT_COMPLEMENT

boundingtype

BoundingType enum

Specifies how an extrude should terminate.

ValueDescription
BLIND

Extrude a specific distance.

SYMMETRIC

Like BLIND, but extrudes equally in two directions.

UP_TO_NEXT

Extrude up to the next solid body or surface body in the context.

UP_TO_SURFACE

Extrude up to the specified face, construction plane, or surface body.

UP_TO_BODY

Extrude up to the specified solid body.

UP_TO_VERTEX

Extrude up to the specified vertex.

THROUGH_ALL

Extrude an unspecified distance, guaranteed to be further in the extrude direction than any other solid or surface in the context.

UP_TO_FACE

chamfertype

ChamferType enum

See opChamfer.

ValueDescription
EQUAL_OFFSETS
TWO_OFFSETS
OFFSET_ANGLE
RAW_OFFSET

clashtype

ClashType enum

Specifies the class of intersection between two bodies. *

See also

evCollision

ValueDescription
NONE

No intersection.

INTERFERE

Bounding topologies interfere.

EXISTS

Vertex or edge intersection.

ABUT_NO_CLASS

Bounding topologies abut.

ABUT_TOOL_IN_TARGET

Bounding tool abuts bounding target on inside.

ABUT_TOOL_OUT_TARGET

Bounding tool abuts bounding target on outside.

TARGET_IN_TOOL

Target completely inside tool.

TOOL_IN_TARGET

Tool completely inside target.

constrainttype

ConstraintType enum

Specifies a type of sketch constraint.

See also

skConstraint

ValueDescription
NONE
COINCIDENT
PARALLEL
VERTICAL
HORIZONTAL
PERPENDICULAR
CONCENTRIC
MIRROR
MIDPOINT
TANGENT
EQUAL
LENGTH
DISTANCE
ANGLE
RADIUS
NORMAL
FIX
PROJECTED
OFFSET
CIRCULAR_PATTERN
PIERCE
LINEAR_PATTERN
MAJOR_DIAMETER
MINOR_DIAMETER
QUADRANT
DIAMETER
SILHOUETTED
CENTERLINE_DIMENSION
INTERSECTED
RHO

coordinatesysteminferenceselectionfilter

CoordinateSystemInferenceSelectionFilter enum

Specifies the filter type when requesting inference mate connectors.

ValueDescription
NONE
HOLE_GEOMETRY

curvetype

CurveType enum

The subset of GeometryType which applies to 1-dimensional entities.

ValueDescription
CIRCLE
LINE
OTHER
ELLIPSE

dimensionalignment

DimensionAlignment enum

Specifies how a constraint between lines or axes (such as parallel or coincident) should align the two constrained axes.

ValueDescription
UNSPECIFIED
ALIGNED
ANTI_ALIGNED

edgeconvexitytype

EdgeConvexityType enum

Specifies how two faces join at a given edge. This is a function of the interior angle between the adjoining surfaces, measured inside the owner body.

ValueDescription
CONVEX

The interior angle is less than 180 degrees along the whole edge.

CONCAVE

The interior angle is greater than 180 degrees along the whole edge.

SMOOTH

The interior angle is equal to 180 degrees along the whole edge.

VARIABLE

None of the above, i.e. the edge convexity varies along the edge.

entityinferencetype

EntityInferenceType enum

Specifies how a mate connector's coordinate system is defined with respect an entity.

ValueDescription
PART_ORIGIN
POINT
CENTROID
CENTER
MID_POINT
TOP_AXIS_POINT
MID_AXIS_POINT
BOTTOM_AXIS_POINT
ORIGIN_X
ORIGIN_Y
ORIGIN_Z

filletcrosssection

FilletCrossSection enum

Specifies the cross section for a fillet operation.

ValueDescription
CIRCULAR
CONIC
CURVATURE

geometriccontinuity

GeometricContinuity enum

Specifies the level of geometric continuity.

ValueDescription
G0
G1
G2

lookupTablePath

LookupTablePath type

A LookupTablePath identifies a map of keys into a multi-level table.

The fields on a LookupTablePath depend on its related LookupTable.

ValueTypeDescription
LookupTablePath map
  • entityType
EntityType

Optional

canBeLookupTablePath (value) predicate

Typecheck for LookupTablePath

lookupTablePath (source is map) returns LookupTablePath

Creates a lookupTablePath.

lookupTableEvaluate (expression is string) returns ValueWithUnits

Convert a table expression in string form into a ValueWithUnits.

ParameterTypeAdditional Info
expression string

Currently the following forms are supported:

EXAMPLE

{number} <*> {units}

EXAMPLE

{number}/{number} <*> {units}

EXAMPLE

{number} <+> {number}/{number} <*> {units} Where {number} is <-><.>nnn> or <->inf

EXAMPLE

{} indicate an entity, <> indicate the contents are optional spaces between entities are optional unless they are required to separate entities.

lookupTableFixExpression (expression is string) returns string

insert plus sign and parenthesis as needed to make a valid expression

getLookupTable (table is map, path is LookupTablePath)

Find a terminal/content table from a path and convert into expression/value form

lookupTableGetValue (value) returns ValueWithUnits

Extract the value portion of expression/value maps or evaluate expressions. value maybe an expression or a value with units

isLookupTableViolated (definition is map, table is map) returns boolean

Test if the current definition violates the table.

manipulatorstyleenum

ManipulatorStyleEnum enum

Specifies the style of a manipulator intended to look unique.

See also

addManipulators

ValueDescription
DEFAULT

the standard display of the manipulator. *

SECONDARY

the angular or linear manipulator has two arrow heads. *

SIMPLE

the display of the angular manipulator is simpler.

manipulatortype

ManipulatorType enum

Specifies a specific type of interactive manipulator.

ValueDescription
LINEAR_1D

A single arrow which can move along a single axis. See extrude for an example.

LINEAR_3D

A triad of perpendicular arrows which specify a 3D position. See transformCopy for an example.

ANGULAR

A curved arrow, with two radii, which can move along a circumference to specify an angle. See revolve for an example.

FLIP

A static arrow which can be clicked to toggle a flip direction. See extrude (with BoundingType.THROUGH_ALL) for an example.

mateconnectoraxistype

MateConnectorAxisType enum

Defines what direction the X-axis of a mate connector should face, relative to the reference defined. Thus, a mate connector defined with PLUS_Y will differ from the selected coordinate system by a 90-degree rotation about that coordinate system's Z-axis.

ValueDescription
PLUS_X
PLUS_Y
MINUS_X
MINUS_Y

matedoftype

MateDOFType enum

Specifies a single degree of freedom of a mate.

ValueDescription
Tx

Translation along the X axis.

Ty

Translation along the Y axis.

Tz

Translation along the Z axis.

Rz

Rotation around the Z axis.

Ryp

Rotation around the transformed Y axis from previous transform sequence.

Rzp

Rotation around the transformed z axis from previous transform sequence .

origincreationtype

OriginCreationType enum

Specifies how a mate connector origin is defined, and how many entities define it.

ValueDescription
ON_ENTITY
BETWEEN_ENTITIES

rotationtype

RotationType enum

Specifies an axis for rotation.

ValueDescription
ABOUT_X
ABOUT_Y
ABOUT_Z

sectionpart

sectionPart (context is Context, id is Id, definition is map)

Feature creating a section of a part behind a plane. Internally, performs an opSplitPart followed by an opDeleteBodies.

Not exposed in the Part Studio UI.

planeSectionPart (context is Context, id is Id, definition is map)

Split a set of parts with a plane and delete all bodies in front of the face. Unlike sectionPart, bodies which are entirely behind the split plane are retained. Any bodies not included in the target query are deleted.

ParameterTypeAdditional Info
definition map
  • target
Query

Bodies to be split.

  • plane
Plane

Plane that splits the bodies. Everything on the positive z side of the plane will be removed.

jogSectionPart (context is Context, id is Id, definition is map)

Split a part down a jogged section line and delete all back bodies. Used by drawings. Needs to be a feature so that drawings created by queries can resolve. Any bodies not included in the target query are deleted.

ParameterTypeAdditional Info
definition map
  • target
Query

Bodies to be split.

  • sketchPlane
Plane

Plane that the jog line will be drawn in and extruded normal to. Everything on the positive x side of the jog line will be removed.

  • jogPoints
array

Points that the cutting line goes through in world coordinates.

smcornertype

SMCornerType enum

Specifies the type of corner at a vertex of a sheet metal model.

ValueDescription
OPEN_CORNER

The corner has more than two bends or, when folded the edges of the metal do not meet.

CLOSED_CORNER

The corner has two bends and when folded the edge of the metal meet.

BEND_END

The 'corner' is the end of a bend and there may be bend relief.

NOT_A_CORNER

The vertex is not associated with a corner

splitoperationkeeptype

SplitOperationKeepType enum

See opSplitPart.

ValueDescription
KEEP_ALL
KEEP_FRONT
KEEP_BACK

surfacetype

SurfaceType enum

The subset of GeometryType which applies to 2-dimensional entities

ValueDescription
PLANE
CYLINDER
CONE
SPHERE
TORUS
OTHER
REVOLVED
EXTRUDED

tool

The tool.fs module contains enum types shared by multiple features.

MoveFaceType enum

Defines how face should be transformed in a moveFace feature.

Also used by boolean.

ValueDescription
OFFSET
TRANSLATE
ROTATE

ToolBodyType enum

Defines what type of body a body-creating feature (extrude, revolve, etc.) should create.

ValueDescription
SOLID
SURFACE

NewBodyOperationType enum

Defines how a new body from a body-creating feature (extrude, revolve, etc.) should be merged with other bodies in the context.

To include this enum with the same styling as the extrude dialog (and others), use booleanStepTypePredicate(definition).

ValueDescription
NEW

Creates a new body in the context with the geometry resulting from the operation.

ADD

Performs a boolean union between the new body and all bodies in the merge scope.

REMOVE

Performs a boolean subtraction of the new body from all bodies in the merge scope.

INTERSECT

Performs a boolean intersection between each new body and each body in the merge scope.

NewSurfaceOperationType enum

Defines how a new surface from a surface-creating feature (sweep, loft, revolve, etc.) should be merged with other surfaces in the context.

To include this enum with the same styling as the extrude dialog (and others), use booleanStepTypePredicate(definition).

ValueDescription
NEW

Creates a new surface in the context with the geometry resulting from the operation.

ADD

Performs a surface union between the new surface and all surfaces used as input.

topologymatchtype

TopologyMatchType enum

See opBoolean.

ValueDescription
COINCIDENT
OVERLAPING
CONTAINED_2_IN_1

uihint

UIHint enum

List of available UI Hints, which control how a parameter input is displayed in the feature dialog.

EXAMPLE

annotation { "Name" : "Flip", "UIHint" : "OPPOSITE_DIRECTION" }
definition.isFlipped is boolean;

Multiple UIHints can be specified in an array.

OPPOSITE_DIRECTION and ALWAYS_HIDDEN behaviors are considered stable. Other UIHints can be used, but their behaviors may change in future versions of Onshape.

ValueDescription
OPPOSITE_DIRECTION

For a boolean parameter, display as a toggle button with arrow next to the previous parameter.

ALWAYS_HIDDEN

Do not display this parameter or allow a user to edit it (useful for parameters changed only in editing logic or manipulator change functions).

SHOW_CREATE_SELECTION

For a query parameter, include a button to open the "Create selection" dialog.

CONTROL_VISIBILITY

For Onshape internal use.

NO_PREVIEW_PROVIDED

For a feature, hide the preview slider which controls before/after transparency, and only show the final version.

REMEMBER_PREVIOUS_VALUE

When a user makes a new instance of this feature, set this parameter's default value to the value they set the last time they used this feature.

DISPLAY_SHORT

Two consecutive boolean or quantity parameters marked as DISPLAY_SHORT may be placed on the same line.

ALLOW_FEATURE_SELECTION

For Onshape internal use.

MATE_CONNECTOR_AXIS_TYPE

For Onshape internal use.

PRIMARY_AXIS

For Onshape internal use.

SHOW_EXPRESSION

If an expression (like #foo or 1/4 in) is entered, always show the expression, and never the resulting value.

OPPOSITE_DIRECTION_CIRCULAR

Like OPPOSITE_DIRECTION, but with circular arrows.

SHOW_LABEL

Show a label above an enum parameter.

HORIZONTAL_ENUM

Display an enum as a horizontal list of clickable text, rather than the default select control

UNCONFIGURABLE

For Onshape internal use.

MATCH_LAST_ARRAY_ITEM

Inside an array parameter, set the default value on a new item to match what is set on the last item.

COLLAPSE_ARRAY_ITEMS

For an array parameter, create new items (and items in a newly opened dialog) as collapsed by default.

INITIAL_FOCUS_ON_EDIT

When an existing feature is edited, the first visible parameter with this UI hint will get focus.

INITIAL_FOCUS

When creating or editing, the first visible parameter with this UI hint will get focus (but when editing, a parameter with INITIAL_FOCUS_ON_EDIT takes precedence).