file_path
stringlengths 5
148
| content
stringlengths 150
498k
| size
int64 150
498k
|
---|---|---|
example.python_ext.python_ext.Functions.md | # example.python_ext.python_ext Functions
## Functions Summary
| Function Name |
|---------------|
| [some_public_function](example.python_ext.python_ext/example.python_ext.python_ext.some_public_function.html) | | 214 |
example.python_ext.python_ext.HelloPythonExtension.md | # HelloPythonExtension
## HelloPythonExtension
```
Bases: `omni.ext._extensions.IExt`
### Methods
| Method | Description |
|--------|-------------|
| `on_shutdown()` | |
| `on_startup(ext_id)` | |
```python
def __init__(self: omni.ext._extensions.IExt) -> None:
pass
``` | 279 |
ExampleBakery.md | # Integrating an Authoring Layer
In this article, a toy example using the Execution Framework is used to describe an online bakery. While the simplistic subject matter of the example is contrived, the concepts demonstrated in the example have real-world applications.
The article is structured such that the example starts simple, and new concepts are introduced piecemeal.
## The Authoring Layer
The Execution Framework, in particular the execution graph, is a common language to describe execution across disparate software components. It is the job of each component (or an intermediary) to populate the execution graph based on some internal description. We call this per-component, internal description the authoring layer. It is common to have multiple different authoring layers contribute to a single execution graph.
This example demonstrate a single authoring layer that describes several online bakeries. The data structures used by this authoring layer is as follows:
```c++
struct BakedGood
{
unsigned int bakeMinutes;
std::string name;
};
struct Order
{
std::string customer;
std::vector<BakedGood> bakedGoods;
};
struct Bakery
{
std::string name;
std::vector<Order> orders;
};
```
The example starts by describing two bakeries at the authoring layer:
```c++
std::vector<Bakery> bakeries {
Bakery {
"The Pie Hut", // bakery name
{
Order {
// ...
},
// ...
},
},
// ...
};
```
"Tracy", // customer
{
BakedGood { 20, "applePie" },
BakedGood { 30, "chickenPotPie" }
}
,
Order {
"Kai", // customer
{
BakedGood { 22, "peachPie" },
}
}
,
Bakery {
"Sam's Bakery", // bakery name
{
Order {
"Alex", // customer
{
BakedGood { 20, "blueberryPie" },
}
}
}
};
```
## Setting Up the Execution Graph
With the authoring layer defined, the following code is then used to populate the execution graph based on the authoring layer description:
```c++
// this example manually creates an execution graph. in most applications (e.g. kit-based applications) this will
// already be created for you
GraphPtr graph = Graph::create("exec.graph");
// as mentioned above, the builder context, pass pipeline, and builder will likely already be created for you in
// real-world scenarios.
GraphBuilderContextPtr builderContext{ GraphBuilderContext::create(graph, PassPipeline::create()) };
GraphBuilderPtr builder{ GraphBuilder::create(builderContext) };
// ef relies on the user to maintain a reference (i.e. a call omni::core::Object::acquire()) on each node in a graph
// definition. this can be done by simply holding an array of NodePtr objects in your definition. in this case,
// since we're populating the top-level graph definition, we simply store the NodePtrs here.
std::vector<NodePtr> nodes;
for (auto& bakery : bakeries) // for each bakery
{
auto node = Node::create(
graph, // this makes the node a part of the execution graph's top-level graph definition
BakeryGraphDef::create(builder, bakery), // bakery's definition (i.e. work description)
carb::fmt::format("node.bakery.{}", bakery.name)
);
// connect the bakery to the root of the execution graph's definition so that it will be executed. only nodes
// in a graph definition that can reach the definition's root node will be executed.
builder->connect(graph->getRoot(), node);
nodes.emplace_back(std::move(node));
}
```
The execution graph can be visualized as follows:
```mermaid
flowchart LR
00000261A3F90560(( ))
00000261A3F90560-->00000261A0498170
00000261A3F90560-->00000261A3FB0260
00000261A0498170(node.bakery.The Pie Hut)
00000261A0498170-.->00000261A3F8DA50
00000261A3FB0260(node.bakery.Sam's Bakery)
00000261A3FB0260-.->00000261A3F8E750
subgraph 00000261A3F8DA50[def.bakery]
direction LR
style 00000261A3F8DA50 fill:#FAFAFA,stroke:#777777
00000261A3F90CE0(( ))
00000261A3F90CE0-->00000261A3F91000
00000261A3F90CE0-->00000261A3F913C0
00000261A3F90CE0-->00000261A3F90600
00000261A3F90CE0-->00000261A3F90920
00000261A3F91000(node.bakery.The Pie Hut.preHeatOven)
00000261A3F91000-.->00000261A3DC44C0
00000261A3F91000-->00000261A3F90E20
00000261A3F91000-->00000261A3F906A0
00000261A3F91000-->00000261A3F90A60
00000261A3F913C0(node.bakedGood.prepare.applePie)
00000261A3F913C0-.->00000261A3D77160
00000261A3F913C0-->00000261A3F90E20
00000261A3F90600(node.bakedGood.prepare.chickenPotPie)
00000261A3F90600-.->00000261A3D76B60
00000261A3F90600-->00000261A3F906A0
00000261A3F90920(node.bakedGood.prepare.peachPie)
00000261A3F90920-.->00000261A3D767A0
00000261A3F90920-->00000261A3F90A60
00000261A3F90E20(node.bakedGood.bake.applePie)
00000261A3F90E20-.->00000261A3CA6BF0
00000261A3F90E20-->00000261A3F909C0
00000261A3F90E20-->00000261A3F911E0
00000261A3F906A0(node.bakedGood.bake.chickenPotPie)
00000261A3F906A0-.->00000261A3CA5210
00000261A3F906A0-->00000261A3F909C0
00000261A3F906A0-->00000261A3F911E0
00000261A3F90A60(node.bakedGood.bake.peachPie)
00000261A3F90A60-.->00000261A3CA53C0
00000261A3F90A60-->00000261A3F90EC0
00000261A3F90A60-->00000261A3F911E0
00000261A3F909C0(node.bakedGood.ship.Tracy)
00000261A3F909C0-.->00000261A3DC4510
00000261A3F911E0(node.bakery.The Pie Hut.turnOffOven)
00000261A3F911E0-.->00000261A3DC3F20
00000261A3F90EC0(node.bakedGood.ship.Kai)
00000261A3F90EC0-.->00000261A3DC45B0
end
00000261A3CA5210{{def.bakedGood.bake}}
00000261A3CA53C0{{def.bakedGood.bake}}
00000261A3CA6BF0{{def.bakedGood.bake}}
subgraph 00000261A3D767A0[def.bakedGood.prepare]
direction LR
style 00000261A3D767A0 fill:#FAFAFA,stroke:#777777
00000261A3F90F60(( ))
00000261A3F90F60-->00000261A3F90740
00000261A3F90740(node.bakedGood.gather.peachPie)
00000261A3F90740-.->00000261A3CA52A0
00000261A3F90740-->00000261A3F907E0
00000261A3F907E0(node.bakedGood.assemble.peachPie)
00000261A3F907E0-.->00000261A3CA5330
end
00000261A3CA52A0{{def.bakedGood.gatherIngredients}}
00000261A3CA5330{{def.bakedGood.assemble}}
subgraph 00000261A3D76B60[def.bakedGood.prepare]
direction LR
style 00000261A3D76B60 fill:#FAFAFA,stroke:#777777
00000261A3F91140(( ))
00000261A3F91140-->00000261A3F90BA0
00000261A3F90BA0(node.bakedGood.gather.chickenPotPie)
00000261A3F90BA0-.->00000261A3CA7100
00000261A3F90BA0-->00000261A3F904C0
00000261A3F904C0(node.bakedGood.assemble.chickenPotPie)
00000261A3F904C0-.->00000261A3CA73D0
end
00000261A3CA7100{{def.bakedGood.gatherIngredients}}
00000261A3CA73D0{{def.bakedGood.assemble}}
subgraph 00000261A3D77160[def.bakedGood.prepare]
direction LR
style 00000261A3D77160 fill:#FAFAFA,stroke:#777777
00000261A3F91320(( ))
00000261A3F91320-->00000261A3F90B00
00000261A3F90B00(node.bakedGood.gather.applePie)
00000261A3F90B00-.->00000261A3CA6B60
00000261A3F90B00-->00000261A3F90D80
00000261A3F90D80(node.bakedGood.assemble.applePie)
00000261A3F90D80-.->00000261A3CA6530
end
00000261A3CA6530{{def.bakedGood.assemble}}
00000261A3CA6B60{{def.bakedGood.gatherIngredients}}
00000261A3DC3F20{{def.oven.turnOff}}
00000261A3DC44C0{{def.oven.preHeat}}
00000261A3DC4510{{def.order.ship}}
00000261A3DC45B0{{def.order.ship}}
subgraph 00000261A3F8E750[def.bakery]
direction LR
style 00000261A3F8E750 fill:#FAFAFA,stroke:#777777
00000261A3FB0B20(( ))
00000261A3FB0B20-->00000261A3FAFFE0
00000261A3FB0B20-->00000261A3FB0940
00000261A3FAFFE0(node.bakery.Sam's Bakery.preHeatOven)
00000261A3FAFFE0-.->00000261A3DC3A20
00000261A3FAFFE0-->00000261A3FB0760
00000261A3FB0940(node.bakedGood.prepare.blueberryPie)
00000261A3FB0940-.->00000261A3D76CE0
00000261A3FB0940-->00000261A3FB0760
00000261A3FB0760(node.bakedGood.bake.blueberryPie)
00000261A3FB0760-.->00000261A3CA60B0
00000261A3FB0760-->00000261A3FAF720
00000261A3FB0760-->00000261A3FB0DA0
00000261A3FAF720(node.bakedGood.ship.Alex)
00000261A3FAF720-.->00000261A3DC3F70
00000261A3FB0DA0(node.bakery.Sam's Bakery.turnOffOven)
00000261A3FB0DA0-.->00000261A3DC4560
end
00000261A3CA60B0{{def.bakedGood.bake}}
subgraph 00000261A3D76CE0[def.bakedGood.prepare]
direction LR
style 00000261A3D76CE0 fill:#FAFAFA,stroke:#777777
00000261A3FAF680(( ))
00000261A3FAF680-->00000261A3FAFA40
00000261A3FAFA40(node.bakedGood.gather.blueberryPie)
```
00000261A3FAFA40-.->00000261A3CA59F0
00000261A3FAFA40-->00000261A3FB0120
00000261A3FB0120(node.bakedGood.assemble.blueberryPie)
00000261A3FB0120-.->00000261A3CA6020
end
00000261A3CA59F0{{def.bakedGood.gatherIngredients}}
00000261A3CA6020{{def.bakedGood.assemble}}
00000261A3DC3A20{{def.oven.preHeat}}
00000261A3DC3F70{{def.order.ship}}
00000261A3DC4560{{def.oven.turnOff}}
## Figure 20
The execution graph showing both bakeries. Arrows with solid lines represent orchestration ordering while arrows with dotted lines represent the definition a node is using.
You can see the execution graph has several types of entities:
- **Nodes** are represented by rounded boxes. Their name starts with “node.”.
- **Opaque Definitions** are represented by angled boxes. Their name starts with “def.”.
- **Graph Definitions** are represented by shaded boxes. Their name, at the top of the box, starts with “def.”.
- **Root Nodes** are represented by circles. Their name is not shown.
- **Edges**, represented by an arrow with a solid line, show the orchestration ordering between nodes.
- Each node points to a definition, either an opaque definition or a graph definition. This relationship is represented by an arrow with a dotted line. Note, definitions can be pointed to by multiple nodes, though this example does not utilize the definition sharing feature of EF.
To simplify the example, this article focuses on a single bakery. Below, you can see a visualization of only The Pie Hut’s graph definition:
```mermaid
flowchart LR
00000261A3F913C0(( ))
00000261A3F913C0-->00000261A3F91320
00000261A3F913C0-->00000261A3F90B00
00000261A3F913C0-->00000261A3F911E0
00000261A3F913C0-->00000261A3F90E20
00000261A3F91320(node.bakery.The Pie Hut.preHeatOven)
00000261A3F91320-.->00000261A3DC3930
00000261A3F91320-->00000261A3F90920
00000261A3F91320-->00000261A3F90F60
00000261A3F91320-->00000261A3F90EC0
00000261A3F90B00(node.bakedGood.prepare.applePie)
00000261A3F90B00-.->00000261A3D76CE0
00000261A3F90B00-->00000261A3F90920
00000261A3F911E0(node.bakedGood.prepare.chickenPotPie)
00000261A3F911E0-.->00000261A3D77160
00000261A3F911E0-->00000261A3F90F60
00000261A3F90E20(node.bakedGood.prepare.peachPie)
00000261A3F90E20-.->00000261A3D767A0
00000261A3F90E20-->00000261A3F90EC0
00000261A3F90920(node.bakedGood.bake.applePie)
00000261A3F90920-.->00000261A3CA6530
00000261A3F90920-->00000261A3F909C0
00000261A3F90920-->00000261A3F904C0
00000261A3F90F60(node.bakedGood.bake.chickenPotPie)
00000261A3F90F60-.->00000261A3CA7070
00000261A3F90F60-->00000261A3F909C0
00000261A3F90F60-->00000261A3F904C0
00000261A3F90EC0(node.bakedGood.bake.peachPie)
00000261A3F90EC0-.->00000261A3CA6B60
00000261A3F90EC0-->00000261A3F91000
00000261A3F90EC0-->00000261A3F904C0
00000261A3F909C0(node.bakedGood.ship.Tracy)
00000261A3F909C0-.->00000261A3DC44C0
00000261A3F904C0(node.bakery.The Pie Hut.turnOffOven)
00000261A3F904C0-.->00000261A3DC4880
00000261A3F91000(node.bakedGood.ship.Kai)
00000261A3F91000-.->00000261A3DC3D40
00000261A3CA6530{{def.bakedGood.bake}}
00000261A3CA6B60{{def.bakedGood.bake}}
00000261A3CA7070{{def.bakedGood.bake}}
subgraph 00000261A3D767A0[def.bakedGood.prepare]
direction LR
style 00000261A3D767A0 fill:#FAFAFA,stroke:#777777
00000261A3F907E0(( ))
00000261A3F907E0-->00000261A3F90880
00000261A3F90880(node.bakedGood.gather.peachPie)
00000261A3F90880-.->00000261A3CA73D0
00000261A3F90880-->00000261A3F90BA0
00000261A3F90BA0(node.bakedGood.assemble.peachPie)
00000261A3F90BA0-.->00000261A3CA6260
end
00000261A3CA6260{{def.bakedGood.assemble}}
00000261A3CA73D0{{def.bakedGood.gatherIngredients}}
subgraph 00000261A3D76CE0[def.bakedGood.prepare]
direction LR
style 00000261A3D76CE0 fill:#FAFAFA,stroke:#777777
00000261A3F90CE0(( ))
00000261A3F90CE0-->00000261A3F90560
00000261A3F90560(node.bakedGood.gather.applePie)
00000261A3F90560-.->00000261A3CA57B0
00000261A3F90560-->00000261A3F90600
00000261A3F90600(node.bakedGood.assemble.applePie)
00000261A3F90600-.->00000261A3CA6C80
end
00000261A3CA57B0{{def.bakedGood.gatherIngredients}}
00000261A3CA6C80{{def.bakedGood.assemble}}
subgraph 00000261A3D77160[def.bakedGood.prepare]
direction LR
style 00000261A3D77160 fill:#FAFAFA,stroke:#777777
00000261A3F90D80(( ))
00000261A3F90D80-->00000261A3F906A0
00000261A3F906A0(node.bakedGood.gather.chickenPotPie)
00000261A3F906A0-.->00000261A3CA5E70
00000261A3F906A0-->00000261A3F90740
00000261A3F90740(node.bakedGood.assemble.chickenPotPie)
00000261A3F90740-.->00000261A3CA6FE0
end
00000261A3CA5E70{{def.bakedGood.gatherIngredients}}
00000261A3CA6FE0{{def.bakedGood.assemble}}
00000261A3DC3930{{def.oven.preHeat}}
00000261A3DC3D40{{def.order.ship}}
00000261A3DC44C0{{def.order.ship}}
00000261A3DC4880{{def.oven.turnOff}}
```
00000261A3F90880--->00000261A3CA73D0
00000261A3F90880--->00000261A3F90BA0
00000261A3F90BA0(node.bakedGood.assemble.peachPie)
00000261A3F90BA0--->00000261A3CA6260
end
00000261A3CA6260{{def.bakedGood.assemble}}
00000261A3CA73D0{{def.bakedGood.gatherIngredients}}
subgraph 00000261A3D76CE0[def.bakedGood.prepare]
direction LR
style 00000261A3D76CE0 fill:#FAFAFA,stroke:#777777
00000261A3F90CE0(( ))
00000261A3F90CE0--->00000261A3F90560
00000261A3F90560(node.bakedGood.gather.applePie)
00000261A3F90560--->00000261A3CA57B0
00000261A3F90560--->00000261A3F90600
00000261A3F90600(node.bakedGood.assemble.applePie)
00000261A3F90600--->00000261A3CA6C80
end
00000261A3CA57B0{{def.bakedGood.gatherIngredients}}
00000261A3CA6C80{{def.bakedGood.assemble}}
subgraph 00000261A3D77160[def.bakedGood.prepare]
direction LR
style 00000261A3D77160 fill:#FAFAFA,stroke:#777777
00000261A3F90D80(( ))
00000261A3F90D80--->00000261A3F906A0
00000261A3F906A0(node.bakedGood.gather.chickenPotPie)
00000261A3F906A0--->00000261A3CA5E70
00000261A3F906A0--->00000261A3F90740
00000261A3F90740(node.bakedGood.assemble.chickenPotPie)
00000261A3F90740--->00000261A3CA6FE0
end
00000261A3CA5E70{{def.bakedGood.gatherIngredients}}
00000261A3CA6FE0{{def.bakedGood.assemble}}
00000261A3DC3930{{def.oven.preHeat}}
00000261A3DC3D40{{def.order.ship}}
00000261A3DC44C0{{def.order.ship}}
00000261A3DC4880{{def.oven.turnOff}}
## Building a Graph Definition
When creating the execution graph, most of the work is done in `BakeryGraphDef`, which is defined as follows:
```cpp
class BakeryGraphDef : public NodeGraphDef // NodeGraphDef is an ef provided implementation of INodeGraphDef
{
public:
// implementations of ef interfaces are encouraged to define a static create() method. this method returns an
// ObjectPtr which correctly manages the reference count of the returned object.
//
// when defining api methods like create(), the use of ObjectParam<>& to accept ONI object is encouraged. below,
// ObjectParam<IGraphBuilder> is a light-weight object that will accept either a raw IGraphBuilder* or a
// GraphBuilderPtr.
static omni::core::ObjectPtr<BakeryGraphDef> create(
omni::core::ObjectParam<IGraphBuilder> builder,
const Bakery& bakery) noexcept
{
// the pattern below of creating an graph definition followed by calling build() is common. in libraries like
// OmniGraph, all definitions are subclassed from a public interface that specifies a build_abi() method. since
// the build method is virtual (in OG, not here), calling build_abi() during the constructor would likely lead
// to incorrect behavior (i.e. calling a virtual method on an object that isn't fully instantiated is an
// anti-pattern). by waiting to call build() after the object is fully instantiated, as below, the proper
// build_abi() will be invoked.
auto def = omni::core::steal(new BakeryGraphDef(builder->getGraph(), bakery));
def->build(builder);
return def;
}
// build() (usually build_abi()) is a method often seen in ef definitions. it usually serves two purposes:
//
// - build the graph definition's graph
//
// - update the graph definition's graph when something has changed in the authoring layer
//
// note, this example doesn't consider updates to the authoring layer.
void build(omni::core::ObjectParam<IGraphBuilder> parentBuilder) noexcept
{
// when building a graph definition, a *dedicated* builder must be created to handle connecting nodes and
// setting the node's definitions.
//
// below, notice the use of 'auto'. use of auto is highly encouraged in ef code. in many ef methods, it is
// unclear if the return type is either a raw pointer or a smart ObjectPtr. by using auto, the caller doesn't
```
// need to care and "The Right Thing (TM)" will happen.
auto builder{ GraphBuilder::create(parentBuilder, this) };
// when using the build method to repspond to update in the authoring layer, we clear out the old nodes (if
// any). a more advanced implementation may choose to reuse nodes to avoid memory thrashing.
m_nodes.clear();
if (m_bakery.orders.empty())
{
// no orders to bake. don't turn on the oven.
return; // LCOV_EXCL_LINE
}
m_preheatOven = Node::create(
getTopology(), // each node must be a part of a single topology. getTopology() returns this defs topology.
PreHeatOvenNodeDef::create(m_bakery),
carb::fmt::format("node.bakery.{}.preHeatOven", m_bakery.name)
);
// connecting nodes in a graph must go through the GraphBuilder object created to construct this graph
// definition
builder->connect(getRoot(), m_preheatOven);
m_turnOffOven = Node::create(
getTopology(),
TurnOffOvenNodeDef::create(m_bakery),
carb::fmt::format("node.bakery.{}.turnOffOven", m_bakery.name)
);
for (auto& order : m_bakery.orders) // for each order
{
if (!order.bakedGoods.empty()) // make sure the order isn't empty
{
auto ship = Node::create(
getTopology(),
ShipOrderNodeDef::create(order),
carb::fmt::format("node.bakedGood.ship.{}", order.customer)
);
for (const BakedGood& bakedGood : order.bakedGoods) // for each item in the order
{
auto prepare = Node::create(
getTopology(),
PrepareBakedGoodGraphDef::create(builder, bakedGood),
carb::fmt::format("node.bakedGood.prepare.{}", bakedGood.name)
);
auto bake = Node::create(
getTopology(),
NodeDefLambda::create( // NodeDefLambda is an opaque def which uses a lambda to perform work
"def.bakedGood.bake",
[&bakedGood = bakedGood](ExecutionTask& info)
## Node Definitions
A `NodeDef` (e.g. `PreHeatOvenNodeDef`) is useful when:
- The developer wishes to provide additional methods on the definition.
- The opaque definition needs to store authoring data whose ownership and lifetime can’t be adequately captured in the lambda provided to `NodeDefLambda`.
## Graph Definitions
The second type of definitions seen in Figure 21 are graph definitions. Graph definitions are represented by shaded boxes. Each graph definition has a root node, represented by a circle. In Figure 21, there is one type of graph definition: `PrepareBakedGoodGraphDef`.
Here, you can see the code behind `PrepareBakedGoodGraphDef`:
### Listing 43: An example of a graph definition used to prepare a baked good.
```cpp
class PrepareBakedGoodGraphDef : public NodeGraphDefT<INodeGraphDef, INodeGraphDefDebug, IPrivateBakedGoodGetter>
{
public:
static omni::core::ObjectPtr<PrepareBakedGoodGraphDef> create(
omni::core::ObjectParam<IGraphBuilder> builder,
const BakedGood& bakedGood) noexcept
{
auto def = omni::core::steal(new PrepareBakedGoodGraphDef(builder->getGraph(), bakedGood));
def->build(builder);
return def;
}
void build(omni::core::ObjectParam<IGraphBuilder> parentBuilder) noexcept
{
auto builder = GraphBuilder::create(parentBuilder, this);
m_nodes.clear();
auto gather = Node::create(
getTopology(),
NodeDefLambda::create("def.bakedGood.gatherIngredients",
[this](ExecutionTask& info)
{
log("gather ingredients for {}", m_bakedGood.name);
return Status::eSuccess;
},
SchedulingInfo::eParallel
),
carb::fmt::format("node.bakedGood.gather.{}", m_bakedGood.name)
);
auto assemble = Node::create(
```cpp
class PopulateChickenPotPiePass : public omni::graph::exec::unstable::Implements<IPopulatePass>
```
`PrepareBakedGoodGraphDef` creates a simple graph with two opaque nodes, one which gathers all of the ingredients of the baked good and another which assembles the baked good.
## Population Passes
A powerful feature in EF are [passes](PassConcepts.html#ef-pass-concepts). Passes are user created chunks of code that transform the graph during [graph construction](PassConcepts.html#ef-pass-concepts). As an example, an oft performed transformation is one in which a generic graph definition is replaced with an optimized user defined graph definition.
[Figure 21](#ef-figure-bakery-simplified) shows `node.bakedGood.prepare.chickenPotPie` has a fairly generic graph definition. An opportunity exists to replace this definition with one which can prepare ingredients in parallel. To do this, a [population pass](api/classomni_1_1graph_1_1exec_1_1unstable_1_1IPopulatePass.html#_CPPv4N4omni5graph4exec8unstable13IPopulatePassE) is used:
```cpp
class PopulateChickenPotPiePass : public omni::graph::exec::unstable::Implements<IPopulatePass>
```
## Listing 45
The `IPrivateBakedGoodGetter` allows the bakery library to safely access private implementation details via EF.
```cpp
class IPrivateBakedGoodGetter : public omni::core::Inherits<IBase, OMNI_TYPE_ID("example.IPrivateBakedGoodGetter")>
{
public:
virtual const BakedGood& getBakedGood() const noexcept = 0;
};
```
IPrivateBakedGoodGetter is an example of a *private interface*. Private interfaces are often used in graph construction and graph execution to safely access non-public implementation details.
To understand the need of private interfaces, consider what the `run_abi()` method is doing in Listing 44. The purpose of the method is to replace the generic “prepare” graph definition with a higher-fidelity graph definition specific to the preparation of chicken pot pie. In order to build that new definition, parameters in the chicken pot pie’s `BakedGood` object are needed. Therein lies the problem: EF has no concept of a “baked good”. The population pass is only given a pointer to an `INode` EF interface. With that pointer, the pass is able to get yet another EF interface, `IDef`. Neither of these interfaces have a clue what a `BakedGood` is. So, how does one go about getting a `BakedGood` from an `INode`?
The answer lies in the type casting mechanism Omniverse Native Interfaces provides. The idea is simple, when creating a definition (e.g. PrepareBakedGoodGraphDef or `ChickenPotPieGraphDef`), do the following:
1. Store a reference to the baked good on the definition.
2. In addition to implementing the `INodeGraphDef` interface, also implement the IPrivateBakedGoodGetter private interface.
To demonstrate the latter point, consider the code used to define the `ChickenPotPieGraphDef` class used in the population pass:
```cpp
class ChickenPotPieGraphDef : public NodeGraphDefT<INodeGraphDef, INodeGraphDefDebug, IPrivateBakedGoodGetter>
```
NodeGraphDefT is an implementation of INodeGraphDef and INodeGraphDefDebug. NodeGraphDefT’s template arguments allow the developer to specify all of the interfaces the subclass will implement, including interfaces EF has no notion about (e.g. IPrivateBakedGoodGetter). Recall, much like ChickenPotPieGraphDef, PrepareBakedGoodGraphDef’s implementation also inherits from NodeGraphDefT and specifies IPrivateBakedGoodGetter as a template argument.
To access the BakedGood from the given INode, the population pass calls omni::graph::exec::unstable::cast() on the node’s definition. If the definition implements IPrivateBakedGoodGetter, a valid pointer is returned, on which getBakedGood() can be called. With the BakedGood in hand, it can be used to create the new ChickenPotPieGraphDef graph definition, which the builder attaches to the node, replacing the generic graph definition.
### Why Not Use dynamic_cast?
A valid question that may arise from the code above is, “Why not use dynamic_cast?” There are two things to note about dynamic_cast:
1. dynamic_cast is not ABI-safe. Said differently, different compilers may choose to implement its ABI differently.
2. dynamic_cast relies on runtime type information (RTTI). When compiling C++, RTTI is an optional feature that can be disabled.
In Listing 44, run_abi()’s INode pointer (and its attached IDef) may point to an object implemented by a DLL different than the DLL that implements the population pass. That means if dynamic_cast is called on the pointer, the compiler will assume the pointer utilizes its dynamic_cast ABI contract. However, since the pointer is from another DLL, possibly compiled with a different ABI and compiler settings, that assumption may be bad, leading to undefined behavior.
In contrast to dynamic_cast, omni::graph::exec::unstable::cast() is ABI-safe due to its use of Omniverse Native Interfaces.
# ONI (Open Normalized Interface)
ONI defines iron-clad, ABI-safe contracts that work across different compiler tool chains. Calling `omni::graph::exec::unstable::cast()` on an ONI object (e.g. `IDef`) has predictable behavior regardless of the compiler and compiler settings used to compile the object.
## Private vs. Public Interfaces
ONI objects are designed to be ABI-safe. However, it is clear that `IPrivateBakedGoodGetter` is not ABI-safe. `getBakedGood()` returns a reference, which is not allowed by ONI. Furthermore, the returned object, `BakedGood`, also is not ABI-safe due to its use of complex C++ objects like `std::string` and `std::vector`.
Surprisingly, since `IPrivateBakedGoodGetter` is a private interface that is defined, implemented, and only used within a single DLL, the interface can violate ONI’s ABI rules because the ABI will be consistent once `omni::graph::exec::unstable::cast()` returns a valid `IPrivateBakedGoodGetter`. If `IPrivateBakedGoodGetter` was able to be implemented by other DLLs, this scheme would not work due the ambiguities of the C++ ABI across DLL borders.
Private interfaces allow developers to safely access private implementation details (e.g. `BakedGood`) as long as the interfaces are truly private. The example above illustrates a common EF pattern, a library embedding implementation specific data in either nodes or definitions, and then defining passes which cast the generic EF `INode` and `IDef` pointers to a private interface to access the private data.
But what if the developer wants to not be limited to accessing this data in a single DLL? What if the developer wants to allow other developers, authoring their own DLLs, to access this data? In the bakery example, such a system would allow anyone to create DLLs that implement passes which can optimize the production of any baked good.
The answer to these questions are public interfaces. Unlike private interfaces, public interfaces are designed to be implemented by many DLLs. As such, public interfaces must abide by ONI’s strict ABI rules.
In the context of the example above, the following public interface can be defined to allow external developers to access baked good information:
### Listing 47
An example of replacing the private `IPrivateBakedGoodGetter` with a public interface. Such an interface allows external developers to access baked good information in novel passes to optimize the bakery.
```cpp
class IBakedGood_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("example.IBakedGood")>
{
protected:
virtual uint32_t getBakeMinutes_abi() noexcept = 0;
virtual const char* getName_abi() noexcept = 0;
};
```
To utilize the public interface, definitions simply need to inherit from it and implement its methods. For example:
### Listing 48
```markdown
This version of `PrepareBakedGoodGraphDef` is similar to the previous one, but now inherits and implements (not shown) the public interface `IBakedGood` rather than the private `IPrivateBakedGoodGetter`. `IBakedGood` is an API class generated by the *omni.bind* tool which wraps the raw `IBakedGood_abi` into a more friendly C++ class.
```c++
class PrepareBakedGoodGraphDef : public NodeGraphDefT<INodeGraphDef, INodeGraphDefDebug, IBakedGood>
```
Using public interfaces is often more work, but unlocks the ability for external developers to improve and extend a library’s execution graph. When deciding whether to use a public or private interface, consult the following flowchart.
```mermaid
flowchart TD
S[Start]
external{{Will external devs require data stored in your library to extend and improve your part of the execution graph?}}
data{{Do you need private data for graph construction or execution?}}
public[Create a public interface.]
private[Create a private interface.]
none[No interface is needed.]
S --> external
external -- Yes --> public
external -- No --> data
data -- Yes --> private
data -- No --> none
```
**Figure 22:** Flowchart of when to use public or private interfaces.
## Back to the Population Pass
After [PopulateChickenPotPiePass](#ef-listing-bakery-populatechickenpotpiepass) runs and replaces node *node.bakedGood.prepare.chickenPotPie*’s generic graph definition with a new `ChickenPotPieGraphDef`, the bakery’s definition is as follows:
```mermaid
flowchart LR
00000261A3F90D80(( ))
00000261A3F90D80-->00000261A3F90880
00000261A3F90D80-->00000261A3F91320
00000261A3F90D80-->00000261A3F913C0
00000261A3F90D80-->00000261A3F90600
00000261A3F90880(node.bakery.The Pie Hut.preHeatOven)
00000261A3F90880-.->00000261A3DC4290
00000261A3F90880-->00000261A3F90E20
00000261A3F90880-->00000261A3F90F60
00000261A3F90880-->00000261A3F90740
00000261A3F91320(node.bakedGood.prepare.applePie)
00000261A3F91320-.->00000261A3D767A0
00000261A3F91320-->00000261A3F90E20
00000261A3F913C0(node.bakedGood.prepare.chickenPotPie)
00000261A3F913C0-.->00000261A3D76CE0
00000261A3F913C0-->00000261A3F90F60
00000261A3F90600(node.bakedGood.prepare.peachPie)
00000261A3F90600-.->00000261A3D77160
00000261A3F90600-->00000261A3F90740
00000261A3F90E20(node.bakedGood.bake.applePie)
00000261A3F90E20-.->00000261A3CA6FE0
00000261A3F90E20-->00000261A3F906A0
00000261A3F90E20-->00000261A3F90CE0
00000261A3F90F60(node.bakedGood.bake.chickenPotPie)
00000261A3F90F60-.->00000261A3CA7100
00000261A3F90F60-->00000261A3F906A0
```
00000261A3F90F60-->00000261A3F90CE0
00000261A3F90740(node.bakedGood.bake.peachPie)
00000261A3F90740-.->00000261A3CA5570
00000261A3F90740-->00000261A3F91000
00000261A3F90740-->00000261A3F90CE0
00000261A3F906A0(node.bakedGood.ship.Tracy)
00000261A3F906A0-.->00000261A3DC44C0
00000261A3F90CE0(node.bakery.The Pie Hut.turnOffOven)
00000261A3F90CE0-.->00000261A3DC3610
00000261A3F91000(node.bakedGood.ship.Kai)
00000261A3F91000-.->00000261A3DC34D0
00000261A3CA5570{{def.bakedGood.bake}}
00000261A3CA6FE0{{def.bakedGood.bake}}
00000261A3CA7100{{def.bakedGood.bake}}
subgraph 00000261A3D767A0[def.bakedGood.prepare]
direction LR
style 00000261A3D767A0 fill:#FAFAFA,stroke:#777777
00000261A3F909C0(( ))
00000261A3F909C0-->00000261A3F90A60
00000261A3F90A60(node.bakedGood.gather.applePie)
00000261A3F90A60-.->00000261A3CA73D0
00000261A3F90A60-->00000261A3F91140
00000261A3F91140(node.bakedGood.assemble.applePie)
00000261A3F91140-.->00000261A3CA6260
end
00000261A3CA6260{{def.bakedGood.assemble}}
00000261A3CA73D0{{def.bakedGood.gatherIngredients}}
subgraph 00000261A3D76CE0[def.bakedGood.pie]
direction LR
style 00000261A3D76CE0 fill:#FAFAFA,stroke:#777777
00000261A3FB08A0(( ))
00000261A3FB08A0-->00000261A3FB0080
00000261A3FB08A0-->00000261A3FAF220
00000261A3FB08A0-->00000261A3FAFCC0
00000261A3FB0080(node.pie.chop.carrots)
00000261A3FB0080-.->00000261A3CA5CC0
00000261A3FB0080-->00000261A3FAFC20
00000261A3FAF220(node.pie.makeCrust.chickenPotPie)
00000261A3FAF220-.->00000261A3CA5F00
00000261A3FAF220-->00000261A3FAFC20
00000261A3FAFCC0(node.pie.cook.chicken)
00000261A3FAFCC0-.->00000261A3CA6020
00000261A3FAFCC0-->00000261A3FAFC20
00000261A3FAFC20(node.pie.assemble.chickenPotPie)
00000261A3FAFC20-.->00000261A1508650
end
00000261A1508650{{def.bakedGood.assemble}}
00000261A3CA5CC0{{def.bakedGood.chop}}
00000261A3CA5F00{{def.bakedGood.makeCrust}}
00000261A3CA6020{{def.bakedGood.cook}}
subgraph 00000261A3D77160[def.bakedGood.prepare]
direction LR
style 00000261A3D77160 fill:#FAFAFA,stroke:#777777
00000261A3F911E0(( ))
00000261A3F911E0-->00000261A3F904C0
00000261A3F904C0(node.bakedGood.gather.peachPie)
00000261A3F904C0-.->00000261A3CA6BF0
00000261A3F904C0-->00000261A3F90560
00000261A3F90560(node.bakedGood.assemble.peachPie)
00000261A3F90560-.->00000261A3CA53C0
end
00000261A3CA53C0{{def.bakedGood.assemble}}
00000261A3CA6BF0{{def.bakedGood.gatherIngredients}}
00000261A3DC34D0{{def.order.ship}}
00000261A3DC3610{{def.oven.turnOff}}
00000261A3DC4290{{def.oven.preHeat}}
00000261A3DC44C0{{def.order.ship}}
Figure 23: The execution graph after the `PopulateChickenPotPiePass` runs.
Above, you can see *node.bakedGood.prepare.chickenPotPie* now points to a new graph definition which performs task such as preparing the crust and cooking the chicken in parallel.
## Populating Graph Definitions
As mentioned earlier, population passes run on either matching node names or matching graph definition names. You are encouraged to inspect the names used in Figure 23. There, node names are fairly specific. For example, *node.bakedGood.prepare.chickenPotPie* rather than *node.bakedGood.prepare*. Definitions, on the other hand, are generic. For example, *def.bakedGood.prepare* instead of *def.bakedGood.prepare.applePie*. This naming scheme allows for a clever use of the rules for population passes.
Earlier, you saw a population pass that optimized chicken pot pie orders by matching *node* names. Here, a new pass is created: *PopulatePiePass*:
```c++
class PopulatePiePass : public omni::graph::exec::unstable::Implements<IPopulatePass>
{
public:
static omni::core::ObjectPtr<PopulatePiePass> create(omni::core::ObjectParam<IGraphBuilder> builder) noexcept
{
return omni::core::steal(new PopulatePiePass(builder.get()));
}
protected:
PopulatePiePass(IGraphBuilder*) noexcept
{
}
void run_abi(IGraphBuilder* builder, INode* node) noexcept override
{
auto bakedGoodGetter = omni::graph::exec::unstable::cast<IPrivateBakedGoodGetter>(node->getDef());
}
}
```
```c
if (!bakedGoodGetter) {
// either the node or def matches the name we're looking for, but the def doesn't implement our private
// interface to access the baked good, so this isn't a def we can populate. bail.
return; // LCOV_EXCL_LINE
}
const BakedGood& bakedGood = bakedGoodGetter->getBakedGood();
// if the baked good ends with "Pie" attach a custom def that knows how to bake pies
if (!omni::extras::endsWith(bakedGood.name, "Pie")) {
// this baked good isn't a pie. do nothing.
return; // LCOV_EXCL_LINE
}
builder->setNodeGraphDef(
node,
PieGraphDef::create(builder, bakedGood)
);
}
};
```
PopulatePiePass’s purpose is to better define the process of baking pies. This is achieved by registering
PopulatePiePass with a matching name of “def.bakedGood.prepare”. Any graph definition matching
“def.bakedGood.prepare” with be given to PopulatePiePass. Above,
PopulatePiePass’s `run_abi()` method first checks if the currently attached definition can provide the associated
`BakedGood`. If so, the name of the baked good is checked. If the name of the baked good ends with “Pie” the node’s definition is replaced with a new
`PieGraphDef`, which is a graph definition that better describes the preparation of pies. The resulting bakery graph
definition is as follows:
```mermaid
flowchart LR
00000261A3F91320(( ))
00000261A3F91320-->00000261A3F91140
00000261A3F91320-->00000261A3F90560
00000261A3F91320-->00000261A3F91000
00000261A3F91320-->00000261A3F909C0
00000261A3F91140(node.bakery.The Pie Hut.preHeatOven)
00000261A3F91140-.->00000261A3DC37F0
00000261A3F91140-->00000261A3F907E0
00000261A3F91140-->00000261A3F911E0
00000261A3F91140-->00000261A3F90B00
00000261A3F90560(node.bakedGood.prepare.applePie)
00000261A3F90560-.->00000261A3D76E60
00000261A3F90560-->00000261A3F907E0
00000261A3F91000(node.bakedGood.prepare.chickenPotPie)
00000261A3F91000-.->00000261A3D767A0
00000261A3F91000-->00000261A3F911E0
00000261A3F909C0(node.bakedGood.prepare.peachPie)
```
00000261A3F909C0-->00000261A3D76B60
00000261A3F909C0-->00000261A3F90B00
00000261A3F907E0(node.bakedGood.bake.applePie)
00000261A3F907E0-->00000261A3CA6B60
00000261A3F907E0-->00000261A3F90CE0
00000261A3F907E0-->00000261A3F913C0
00000261A3F911E0(node.bakedGood.bake.chickenPotPie)
00000261A3F911E0-->00000261A3CA5330
00000261A3F911E0-->00000261A3F90CE0
00000261A3F911E0-->00000261A3F913C0
00000261A3F90B00(node.bakedGood.bake.peachPie)
00000261A3F90B00-->00000261A3CA5600
00000261A3F90B00-->00000261A3F90600
00000261A3F90B00-->00000261A3F913C0
00000261A3F90CE0(node.bakedGood.ship.Tracy)
00000261A3F90CE0-->00000261A3DC3980
00000261A3F913C0(node.bakery.The Pie Hut.turnOffOven)
00000261A3F913C0-->00000261A3DC3930
00000261A3F90600(node.bakedGood.ship.Kai)
00000261A3F90600-->00000261A3DC3D40
00000261A3CA5330{{def.bakedGood.bake}}
00000261A3CA5600{{def.bakedGood.bake}}
00000261A3CA6B60{{def.bakedGood.bake}}
subgraph 00000261A3D767A0[def.bakedGood.pie]
direction LR
style 00000261A3D767A0 fill:#FAFAFA,stroke:#777777
00000261A3FB0A80(( ))
00000261A3FB0A80-->00000261A3FB04E0
00000261A3FB0A80-->00000261A3FB0580
00000261A3FB0A80-->00000261A3FB0C60
00000261A3FB04E0(node.pie.chop.carrots)
00000261A3FB04E0-->00000261A3CA6A40
00000261A3FB04E0-->00000261A3FB0EE0
00000261A3FB0580(node.pie.makeCrust.chickenPotPie)
00000261A3FB0580-->00000261A3CA7100
00000261A3FB0580-->00000261A3FB0EE0
00000261A3FB0C60(node.pie.cook.chicken)
00000261A3FB0C60-->00000261A1508650
00000261A3FB0C60-->00000261A3FB0EE0
00000261A3FB0EE0(node.pie.assemble.chickenPotPie)
00000261A3FB0EE0-->00000261A0496AA0
end
00000261A0496AA0{{def.bakedGood.assemble}}
00000261A1508650{{def.bakedGood.cook}}
00000261A3CA6A40{{def.bakedGood.chop}}
00000261A3CA7100{{def.bakedGood.makeCrust}}
subgraph 00000261A3D76B60[def.bakedGood.pie]
direction LR
style 00000261A3D76B60 fill:#FAFAFA,stroke:#777777
00000261A3FB0300(( ))
00000261A3FB0300-->00000261A3FAFB80
00000261A3FB0300-->00000261A3FB0620
00000261A3FAFB80(node.pie.chop.peachPie)
00000261A3FAFB80-->00000261A3CA52A0
00000261A3FAFB80-->00000261A3FB09E0
00000261A3FB0620(node.pie.makeCrust.peachPie)
00000261A3FB0620-->00000261A3CA57B0
00000261A3FB0620-->00000261A3FB09E0
00000261A3FB09E0(node.pie.assemble.peachPie)
00000261A3FB09E0-->00000261A3FB40D0
end
00000261A3CA52A0{{def.bakedGood.chop}}
00000261A3CA57B0{{def.bakedGood.makeCrust}}
00000261A3FB40D0{{def.bakedGood.assemble}}
subgraph 00000261A3D76E60[def.bakedGood.pie]
direction LR
style 00000261A3D76E60 fill:#FAFAFA,stroke:#777777
00000261A3FAF9A0(( ))
00000261A3FAF9A0-->00000261A3FAF4A0
00000261A3FAF9A0-->00000261A3FAFAE0
00000261A3FAF4A0(node.pie.chop.applePie)
00000261A3FAF4A0-->00000261A3CA5F00
00000261A3FAF4A0-->00000261A3FAF2C0
00000261A3FAFAE0(node.pie.makeCrust.applePie)
00000261A3FAFAE0-->00000261A3CA60B0
00000261A3FAFAE0-->00000261A3FAF2C0
00000261A3FAF2C0(node.pie.assemble.applePie)
00000261A3FAF2C0-->00000261A3CA6260
end
00000261A3CA5F00{{def.bakedGood.chop}}
00000261A3CA60B0{{def.bakedGood.makeCrust}}
00000261A3CA6260{{def.bakedGood.assemble}}
00000261A3DC37F0{{def.oven.preHeat}}
00000261A3DC3930{{def.oven.turnOff}}
00000261A3DC3980{{def.order.ship}}
00000261A3DC3D40{{def.order.ship}}
Figure 24
The execution graph after the `PopulatePiePass` runs.
It is important to note that EF’s default `pass pipeline` only matches population passes with either node names or graph definition names. Opaque definition names are not matched.
The example above shows that knowing the rules of the application’s `pass pipeline` can help EF developers name their nodes and definitions in such as way to make more effective use of passes.
Conclusion
The bakery example is trivial in nature, but shows several of the patterns and concepts found in the wild when using the Execution Framework. An inspection of OmniGraph’s use of EF will reveal the use of all of the patterns outlined above.
A full source listing for the example can be found at *source/extensions/omni.graph.exec/tests.cpp/TestBakeryDocs.cpp*. | 41,517 |
examples-all.md | # All Data Type Examples
This file contains example usage for all of the AutoNode data types in one place for easy reference and searching. For a view of the examples that is separated into more digestible portions see AutoNode Examples.
## Contents
- [bool](#bool)
- [bool[]](#id1)
- [double](#double)
- [double[]](#id2)
- [float](#float)
- [float[]](#id3)
- [half](#half)
- [half[]](#id4)
- [int](#int)
- [int[]](#id5)
- [int64](#int64)
- [int64[]](#id6)
- [string](#string)
- [token](#token)
- [token[]](#id7)
- [uchar](#uchar)
- [uchar[]](#id8)
- [uint](#uint)
- [uint[]](#id9)
- [uint64](#uint64)
- [uint64[]](#id10)
- [og.create_node_type(ui_name=str)](#og-create-node-type-ui-name-str)
- @og.create_node_type(unique_name=str)
- @og.create_node_type(add_execution_pins)
- @og.create_node_type(metadata=dict(str,any))
- Multiple Simple Outputs
- Multiple Tuple Outputs
- double[2]
- double[2][]
- double[3]
- double[3][]
- double[4]
- double[4][]
- float[2]
- float[2][]
- float[3]
- float[3][]
- float[4]
- float[4][]
- half[2]
- half[2][]
- half[3]
- half[3][]
- half[4]
- half[4][]
- int[2]
- int[2][]
- int[3]
- int[3][]
- int[4]
- int[4][]
- colord[3]
- colord[3][]
- colorf[3]
- colorf[3][]
- colorh[3]
- colorh[3][]
- colord[4]
- colord[4][]
- colorf[4]
- colorf[4][]
- colorh[4]
- colorh[4][]
- frame[4]
- frame[4][]
- matrixd[2]
- matrixd[2][]
- **matrixd[3]**
- **matrixd[3][]**
- **matrixd[4]**
- **matrixd[4][]**
- **normald[3]**
- **normald[3][]**
- **normalf[3]**
- **normalf[3][]**
- **normalh[3]**
- **normalh[3][]**
- **pointd[3]**
- **pointd[3][]**
- **pointf[3]**
- **pointf[3][]**
- **pointh[3]**
- **pointh[3][]**
- **quatd[4]**
- **quatd[4][]**
- **quatf[4]**
- **quatf[4][]**
- **quath[4]**
- **quath[4][]**
- **texcoordd[2]**
- **texcoordd[2][]**
- **texcoordf[2]**
- **texcoordf[2][]**
- **texcoordh[2]**
- **texcoordh[2][]**
- **texcoordd[3]**
- **texcoordd[3][]**
- **texcoordf[3]**
- **texcoordf[3][]**
- **texcoordh[3]**
- **texcoordh[3][]**
- **timecode**
- **timecode[]**
- **vectord[3]**
- **vectord[3][]**
- **vectorf[3]**
- **vectorf[3][]**
- **vectorh[3]**
- **vectorh[3][]**
- **bundle**
- **execution**
- **objectId**
- **objectId[]**
- **target**
## bool
Takes in two boolean values and outputs the logical AND of them. The types of both inputs and the return value are Python booleans. Note that the return type name is the Warp-compatible "boolean", which is just a synonym for "bool".
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_bool(first_value: ot.bool, second_value: ot.bool) -> ot.boolean:
"""Takes in two boolean values and outputs the logical AND of them.
The types of both inputs and the return value are Python booleans.
Note that the return type name is the Warp-compatible "boolean", which is just a synonym for "bool".
"""
return first_value and second_value
```
## bool[]
Takes in two arrays of boolean attributes and returns an array with the logical AND of each element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=bool) where "N" is the size of the array determined at runtime.
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_boolarray(first_value: ot.boolarray, second_value: ot.boolarray) -> ot.boolarray:
"""Takes in two arrays of boolean attributes and returns an array with the logical AND of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=bool) where "N" is the
size of the array determined at runtime.
"""
return first_value & second_value
```
## double
Takes in two double precision values and outputs the sum of them. The types of both inputs and the return value are Python floats as Python does not distinguish between different precision levels. When put into Fabric and USD the values are stored as double precision values. Note that the return type is the Warp-compatible "float64" which is a synonym for "double".
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double(first_value: ot.double, second_value: ot.double) -> ot.float64:
"""Takes in two double precision values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as double.
precision values.
Note that the return type is the Warp-compatible "float64" which is a synonym for "double".
"""
return first_value + second_value
```
## double[]
Takes in two arrays of double attributes and returns an array containing the sum of each element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float64) where "N" is the size of the array determined at runtime.
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_doublearray(first_value: ot.doublearray, second_value: ot.doublearray) -> ot.doublearray:
"""Takes in two arrays of double attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## float
Takes in two single-precision floating point values and outputs the sum of them. The types of both inputs and the return value are Python floats as Python does not distinguish between different precision levels. When put into Fabric and USD the values are stored as single-precision floating point values. Note that the return type is the Warp-compatible "float32" which is a synonym for "float".
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float(first_value: ot.float, second_value: ot.float) -> ot.float32:
"""Takes in two single-precision floating point values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as single-precision
floating point values.
Note that the return type is the Warp-compatible "float32" which is a synonym for "float".
"""
return first_value + second_value
```
## float[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_floatarray(first_value: ot.floatarray, second_value: ot.floatarray) -> ot.floatarray:
"""Takes in two arrays of float attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## half
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half(first_value: ot.half, second_value: ot.half) -> ot.float16:
"""Takes in two half-precision floating point values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as half
precision floating point values.
Note that the return type is the Warp-compatible "float16" which is a synonym for "half".
"""
return first_value + second_value
```
## half[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_halfarray(first_value: ot.halfarray, second_value: ot.halfarray) -> ot.halfarray:
"""Takes in two arrays of half attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## int
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int(first_value: ot.int, second_value: ot.int) -> ot.int32:
"""Takes in two 32-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 32-bit precision
integer values.
Note that the return type is the Warp-compatible "int32" which is a synonym for "int".
"""
return first_value + second_value
```
## int[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_intarray(first_value: ot.intarray, second_value: ot.intarray) -> ot.intarray:
"""Takes in two arrays of integer attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## int64
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int64(first_value: ot.int64, second_value: ot.int64) -> ot.int64:
"""Takes in two 64-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 64-bit precision
integer values.
Note that the return type is the Warp-compatible "int64" which is a synonym for "int64".
"""
return first_value + second_value
```
# Autonode int64
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int64(first_value: ot.int64, second_value: ot.int64) -> ot.int64:
"""Takes in two 64-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 64-bit precision
integer values.
"""
return first_value + second_value
```
# Autonode int64[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int64array(first_value: ot.int64array, second_value: ot.int64array) -> ot.int64array:
"""Takes in two arrays of 64-bit integer attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.int64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# Autonode string
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_string(first_value: ot.string, second_value: ot.string) -> ot.string:
"""Takes in two string values and outputs the concatenated string.
The types of both inputs and the return value are Python str. When put into Fabric the values are
stored as uchar arrays with a length value. USD stores it as a native string type.
"""
return first_value + second_value
```
# Autonode token
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_token(first_value: ot.token, second_value: ot.token) -> ot.token:
"""Takes in two tokenized strings and outputs the string resulting from concatenating them together.
The types of both inputs and the return value are Python strs as Python does not have the concept of a
unique tokenized string. When put into Fabric and USD the values are stored as a single
64-bit unsigned integer that is a token.
"""
return first_value + second_value
```
# Autonode token[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_tokenarray(first_value: ot.tokenarray, second_value: ot.tokenarray) -> ot.tokenarray:
"""Takes in two arrays of tokens and returns an array containing the concatenations of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype="<U") where "N" is
the size of the array determined at runtime.
"""
return np.array([x + y for x, y in zip(first_value, second_value)])
```
# Autonode uchar
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uchar(first_value: ot.uchar, second_value: ot.uchar) -> ot.uchar:
"""Takes in two unsigned character values and outputs the concatenated string.
The types of both inputs and the return value are Python str. When put into Fabric the values are
stored as uchar arrays with a length value. USD stores it as a native string type.
"""
return first_value + second_value
```
# uchar
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uchar(first_value: ot.uchar, second_value: ot.uchar) -> ot.uint8:
"""Takes in two 8-bit precision unsigned integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 8-bit
precision unsigned integer values.
Note that the return type is the Warp-compatible "uint8" which is a synonym for "uchar".
"""
return first_value + second_value
```
# uchar[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uchararray(first_value: ot.uchararray, second_value: ot.uchararray) -> ot.uchararray:
"""Takes in two arrays of 8-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uchar8) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
```
# uint
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uint(first_value: ot.uint, second_value: ot.uint) -> ot.uint:
"""Takes in two 32-bit precision unsigned integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 32-bit
precision unsigned integer values.
"""
return first_value + second_value
```
# uint[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uintarray(first_value: ot.uintarray, second_value: ot.uintarray) -> ot.uintarray:
"""Takes in two arrays of 32-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint32) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
```
# uint64
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uint64(first_value: ot.uint64, second_value: ot.uint64) -> ot.uint64:
"""Takes in two 64-bit precision unsigned integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 64-bit
precision unsigned integer values.
"""
return first_value + second_value
```
# uint64[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_uint64array(first_value: ot.uint64array, second_value: ot.uint64array) -> ot.uint64array:
"""Takes in two arrays of 64-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint64) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
```python
@og.create_node_type
def autonode_uint64array(first_value: ot.uint64array, second_value: ot.uint64array) -> ot.uint64array:
"""Takes in two arrays of 8-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint64) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
```
## @og.create_node_type(ui_name=str)
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(ui_name="Fluffy Bunny")
def autonode_decoration_ui_name() -> ot.string:
"""This node type has no inputs and returns the UI name of its node type as output. It demonstrates how the
optional ui_name argument can be used on the decorator to modify the name of the node type as it
will appear to the user.
"""
# We know the name of the node type by construction
node_type = og.get_node_type("omni.graph.autonode_decoration_ui_name")
# Get the metadata containing the UI name - will always return "Fluffy Bunny"
return node_type.get_metadata(og.MetadataKeys.UI_NAME)
```
## @og.create_node_type(unique_name=str)
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(unique_name="omni.graph.autonode_unique_name")
def autonode_decoration_unique_name() -> ot.string:
"""This node type has no inputs and returns the unique name of its node type as output. It demonstrates how the
optional unique_name argument can be used on the decorator to modify the name of the node type as it
is used for registration and identification.
"""
# Look up the node type name using the supplied unique name rather than the one that would have been
# automatically generated (omni.graph.autonode_decoration_unique_name)
node_type = og.get_node_type("omni.graph.autonode_unique_name")
return node_type.get_node_type() if node_type.is_valid() else ""
```
## @og.create_node_type(add_execution_pins)
```python
import inspect
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(add_execution_pins=True)
def autonode_decoration_add_execution_pins() -> ot.int:
"""This node type has no inputs and returns the number of attributes it has of type "execution". It
demonstrates how the optional add_execution_pins argument can be used on the decorator to automatically
include both an input and an output execution pin so that the node type can be easily included in the
Action Graph.
"""
frame = inspect.currentframe().f_back
node = frame.f_locals.get("node")
# This will return 2, counting the automatically added input and output execution attributes
return sum(1 for attr in node.get_attributes() if attr.get_resolved_type().role == og.AttributeRole.EXECUTION)
```
## @og.create_node_type(metadata=dict(str,any))
```python
import omni.graph.core as og
import omni.graph.core.types as ot
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(metadata={"Emperor": "Palpatine"})
def autonode_decoration_metadata() -> ot.string:
"""This node type has no inputs and returns a string consisting of the value of the metadata
whose name was specified in the decorator "metadata" argument. It demonstrates how the optional metadata
argument can be used on the decorator to automatically add metadata to the node type definition.
"""
# We know the name of the node type by construction
node_type = og.get_node_type("omni.graph.autonode_decoration_metadata")
# Return the metadata with the custom name we specified - will always return "Palpatine"
return node_type.get_metadata("Emperor")
```
## Multiple Simple Outputs
```python
import statistics as st
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_multi_simple(values: ot.floatarray) -> tuple[ot.float, ot.float, ot.float]:
"""Takes in a list of floating point values and returns three outputs that are the mean, median,
and mode of the values in the list. The outputs will be named "out_0", "out_1", and "out_2".
"""
return (values.mean(), np.median(values), st.mode(values))
```
## Multiple Tuple Outputs
```python
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_multi_tuple(original: ot.matrix2d) -> tuple[ot.matrix2d, ot.matrix2d]:
"""Takes in a 2x2 matrix and returns two outputs that are the inverse and transpose of the matrix.
Reports an error if the matrix is not invertible. Note that even though the data types themselves
are tuples the return values will be correctly interpreted as being separate output attributes
with each of the outputs itself being a tuple value. The outputs will be named "out_1" and "out_2".
"""
try:
return (original.transpose(), np.linalg.inv(original))
except np.linalg.LinAlgError as error:
raise og.OmniGraphError(f"Could not invert matrix {original}") from error
```
## double[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double2(first_value: ot.double2, second_value: ot.double2) -> ot.double2:
"""Takes in two double[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as two double-precision floating point values.
"""
return first_value + second_value
```
## double[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
```
```python
def autonode_double2array(first_value: ot.double2array, second_value: ot.double2array) -> ot.double2array:
"""Takes in two arrays of double2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
### double[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double3(first_value: ot.double3, second_value: ot.double3) -> ot.double3:
"""Takes in two double[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as three double-precision floating point values.
"""
return first_value + second_value
```
### double[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double3array(first_value: ot.double3array, second_value: ot.double3array) -> ot.double3array:
"""Takes in two arrays of double3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
### double[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double4(first_value: ot.double4, second_value: ot.double4) -> ot.double4:
"""Takes in two double[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as four double-precision floating point values.
"""
return first_value + second_value
```
### double[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double4array(first_value: ot.double4array, second_value: ot.double4array) -> ot.double4array:
"""Takes in two arrays of double4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
### float[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float2(first_value: ot.float2, second_value: ot.float2) -> ot.float2:
"""
(No description provided)
"""
return first_value + second_value
```
```python
"""Takes in two float[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as two single-precision floating point values.
"""
return first_value + second_value
```
## float[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float2array(first_value: ot.float2array, second_value: ot.float2array) -> ot.float2array:
"""Takes in two arrays of float2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## float[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float3(first_value: ot.float3, second_value: ot.float3) -> ot.float3:
"""Takes in two float[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as three single-precision floating point values.
"""
return first_value + second_value
```
## float[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float3array(first_value: ot.float3array, second_value: ot.float3array) -> ot.float3array:
"""Takes in two arrays of float3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## float[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float4(first_value: ot.float4, second_value: ot.float4) -> ot.float4:
"""Takes in two float[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as four single-precision floating point values.
"""
return first_value + second_value
```
## float[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float4array(first_value: ot.float4array, second_value: ot.float4array) -> ot.float4array:
"""Takes in two arrays of float4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## half[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half2(first_value: ot.half2, second_value: ot.half2) -> ot.half2:
"""Takes in two half[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as two 16-bit floating point values.
"""
return first_value + second_value
```
## half[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half2array(first_value: ot.half2array, second_value: ot.half2array) -> ot.half2array:
"""Takes in two arrays of half2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## half[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half3(first_value: ot.half3, second_value: ot.half3) -> ot.half3:
"""Takes in two half[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as three 16-bit floating point values.
"""
return first_value + second_value
```
## half[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half3array(first_value: ot.half3array, second_value: ot.half3array) -> ot.half3array:
"""Takes in two arrays of half3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## half[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half4(first_value: ot.half4, second_value: ot.half4) -> ot.half4:
"""Takes in two half[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as four 16-bit floating point values.
"""
return first_value + second_value
```
## half[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half4array(first_value: ot.half4array, second_value: ot.half4array) -> ot.half4array:
"""Takes in two arrays of half4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
```python
def autonode_half4array(first_value: ot.half4array, second_value: ot.half4array) -> ot.half4array:
"""Takes in two arrays of half4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int2(first_value: ot.int2, second_value: ot.int2) -> ot.int2:
"""Takes in two int[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.int32). When put into
Fabric and USD the values are stored as two 32-bit integer values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int2array(first_value: ot.int2array, second_value: ot.int2array) -> ot.int2array:
"""Takes in two arrays of int2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int3(first_value: ot.int3, second_value: ot.int3) -> ot.int3:
"""Takes in two int[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.int32). When put into
Fabric and USD the values are stored as three 32-bit integer values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int3array(first_value: ot.int3array, second_value: ot.int3array) -> ot.int3array:
"""Takes in two arrays of int3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int4(first_value: ot.int4, second_value: ot.int4) -> ot.int4:
"""Takes in two int[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.int32). When put into
"""
return first_value + second_value
```
## Fabric and USD the values are stored as two 32-bit integer values.
"""
return first_value + second_value
"""
## int[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int4array(first_value: ot.int4array, second_value: ot.int4array) -> ot.int4array:
"""Takes in two arrays of int4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## colord[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3d(first_value: ot.color3d, second_value: ot.color3d) -> ot.color3d:
"""Takes in two colord[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3darray(first_value: ot.color3darray, second_value: ot.color3darray) -> ot.color3darray:
"""Takes in two arrays of color3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3f(first_value: ot.color3f, second_value: ot.color3f) -> ot.color3f:
"""Takes in two colorf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3farray(first_value: ot.color3farray, second_value: ot.color3farray) -> ot.color3farray:
"""Takes in two arrays of color3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3h(first_value: ot.color3h, second_value: ot.color3h) -> ot.color3h:
"""Takes in two colorh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3harray(first_value: ot.color3harray, second_value: ot.color3harray) -> ot.color3harray:
"""Takes in two arrays of color3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4d(first_value: ot.color4d, second_value: ot.color4d) -> ot.color4d:
"""Takes in two color4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric the values are stored as 4 double-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4darray(first_value: ot.color4darray, second_value: ot.color4darray) -> ot.color4darray:
"""Takes in two arrays of color4d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4f(first_value: ot.color4f, second_value: ot.color4f) -> ot.color4f:
"""Takes in two color4f values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric the values are stored as 4 single-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4farray(first_value: ot.color4farray, second_value: ot.color4farray) -> ot.color4farray:
"""Takes in two arrays of color4f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4h(first_value: ot.color4h, second_value: ot.color4h) -> ot.color4h:
"""Takes in two color4h values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric the values are stored as 4 half-precision values. The color role is applied to USD and OmniGraph types as
an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4harray(first_value: ot.color4harray, second_value: ot.color4harray) -> ot.color4harray:
"""Takes in two arrays of color4h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## frame[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_frame4d(first_value: ot.frame4d, second_value: ot.frame4d) -> ot.frame4d:
"""Takes in two frame4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4), dtype=numpy.float64). When put
into Fabric the values are stored as a set of 16 double-precision values. USD uses the special frame4d type.
"""
return first_value + second_value
```
## frame[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_frame4darray(first_value: ot.frame4darray, second_value: ot.frame4darray) -> ot.frame4darray:
"""Takes in two frame4darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. When put into Fabric the values are stored as an array of sets
of 16 double-precision values. USD stores it as the native frame4d[] type.
"""
return first_value + second_value
```
## matrixd[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix2d(first_value: ot.matrix2d, second_value: ot.matrix2d) -> ot.matrix2d:
"""Takes in two matrix2d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(2,2), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 4 double-precision values.
"""
return first_value + second_value
```
## matrixd[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix2darray(first_value: ot.matrix2darray, second_value: ot.matrix2darray) -> ot.matrix2darray:
"""Takes in two matrix2darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(N,2,2), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 9 double-precision values. USD stores it as the native matrix2d[] type.
"""
return first_value + second_value
```
## matrixd[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix3d(first_value: ot.matrix3d, second_value: ot.matrix3d) -> ot.matrix3d:
"""Takes in two matrix3d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(3,3), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 9 double-precision values.
"""
return first_value + second_value
```
## matrixd[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix3darray(first_value: ot.matrix3darray, second_value: ot.matrix3darray) -> ot.matrix3darray:
"""Takes in two matrix3darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(3,3,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 9 double-precision values. USD stores it as the native matrix3d[] type.
"""
return first_value + second_value
```
## matrixd[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix4d(first_value: ot.matrix4d, second_value: ot.matrix4d) -> ot.matrix4d:
"""Takes in two matrix4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 9 double-precision values.
"""
return first_value + second_value
```
## matrixd[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix4darray(first_value: ot.matrix4darray, second_value: ot.matrix4darray) -> ot.matrix4darray:
"""Takes in two matrix4darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 9 double-precision values. USD stores it as the native matrix4d[] type.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix4darray(first_value: ot.matrix4darray, second_value: ot.matrix4darray) -> ot.matrix4darray:
"""Takes in two matrix4darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 16 double-precision values. USD stores it as the native matrix4d[] type.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3d(first_value: ot.normal3d, second_value: ot.normal3d) -> ot.normal3d:
"""Takes in two normald[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3darray(first_value: ot.normal3darray, second_value: ot.normal3darray) -> ot.normal3darray:
"""Takes in two arrays of normal3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3f(first_value: ot.normal3f, second_value: ot.normal3f) -> ot.normal3f:
"""Takes in two normalf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3farray(first_value: ot.normal3farray, second_value: ot.normal3farray) -> ot.normal3farray:
"""Takes in two arrays of normal3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
# Python Code Snippets
## autonode_normal3h
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3h(first_value: ot.normal3h, second_value: ot.normal3h) -> ot.normal3h:
"""Takes in two normalh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## autonode_normal3harray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3harray(first_value: ot.normal3harray, second_value: ot.normal3harray) -> ot.normal3harray:
"""Takes in two arrays of normal3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## autonode_point3d
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3d(first_value: ot.point3d, second_value: ot.point3d) -> ot.point3d:
"""Takes in two pointd[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## autonode_point3darray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3darray(first_value: ot.point3darray, second_value: ot.point3darray) -> ot.point3darray:
"""Takes in two arrays of point3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## autonode_point3f
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3f(first_value: ot.point3f, second_value: ot.point3f) -> ot.point3f:
"""Takes in two pointf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## autonode_point3farray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3farray(first_value: ot.point3farray, second_value: ot.point3farray) -> ot.point3farray:
"""Takes in two arrays of point3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3farray(first_value: ot.point3farray, second_value: ot.point3farray) -> ot.point3farray:
"""Takes in two arrays of point3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3h(first_value: ot.point3h, second_value: ot.point3h) -> ot.point3h:
"""Takes in two pointh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3harray(first_value: ot.point3harray, second_value: ot.point3harray) -> ot.point3harray:
"""Takes in two arrays of point3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatd(first_value: ot.quatd, second_value: ot.quatd) -> ot.quatd:
"""Takes in two quatd[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric the values are stored as 4 double-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatdarray(first_value: ot.quatdarray, second_value: ot.quatdarray) -> ot.quatdarray:
"""Takes in two arrays of quatd attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatf(first_value: ot.quatf, second_value: ot.quatf) -> ot.quatf:
"""Takes in two quatf[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric the values are stored as 4 single-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatf(first_value: ot.quatf, second_value: ot.quatf) -> ot.quatf:
"""Takes in two quatf[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric the values are stored as 4 single-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatfarray(first_value: ot.quatfarray, second_value: ot.quatfarray) -> ot.quatfarray:
"""Takes in two arrays of quatf attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quath(first_value: ot.quath, second_value: ot.quath) -> ot.quath:
"""Takes in two quath[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric the values are stored as 4 half-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatharray(first_value: ot.quatharray, second_value: ot.quatharray) -> ot.quatharray:
"""Takes in two arrays of quath attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2d(first_value: ot.texcoord2d, second_value: ot.texcoord2d) -> ot.texcoord2d:
"""Takes in two texcoordd[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float64). When put into
Fabric the values are stored as 2 double-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2darray(first_value: ot.texcoord2darray, second_value: ot.texcoord2darray) -> ot.texcoord2darray:
"""Takes in two arrays of texcoordd attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2darray(
first_value: ot.texcoord2darray, second_value: ot.texcoord2darray
) -> ot.texcoord2darray:
"""Takes in two arrays of texcoord2d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### texcoordf[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2f(first_value: ot.texcoord2f, second_value: ot.texcoord2f) -> ot.texcoord2f:
"""Takes in two texcoordf[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float32). When put into
Fabric the values are stored as 2 single-precision values. The texcoord role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
### texcoordf[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2farray(
first_value: ot.texcoord2farray, second_value: ot.texcoord2farray
) -> ot.texcoord2farray:
"""Takes in two arrays of texcoord2f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### texcoordh[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2h(first_value: ot.texcoord2h, second_value: ot.texcoord2h) -> ot.texcoord2h:
"""Takes in two texcoordh[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float16). When put into
Fabric the values are stored as 2 half-precision values. The texcoord role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
### texcoordh[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2harray(
first_value: ot.texcoord2harray, second_value: ot.texcoord2harray
) -> ot.texcoord2harray:
"""Takes in two arrays of texcoord2h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### texcoordd[3]
```python
import omni.graph.core as og
```
```python
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3d(first_value: ot.texcoord3d, second_value: ot.texcoord3d) -> ot.texcoord3d:
"""Takes in two texcoordd[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3darray(first_value: ot.texcoord3darray, second_value: ot.texcoord3darray) -> ot.texcoord3darray:
"""Takes in two arrays of texcoord3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3f(first_value: ot.texcoord3f, second_value: ot.texcoord3f) -> ot.texcoord3f:
"""Takes in two texcoordf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3farray(first_value: ot.texcoord3farray, second_value: ot.texcoord3farray) -> ot.texcoord3farray:
"""Takes in two arrays of texcoord3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3h(first_value: ot.texcoord3h, second_value: ot.texcoord3h) -> ot.texcoord3h:
"""Takes in two texcoordh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3harray(first_value: ot.texcoord3harray, second_value: ot.texcoord3harray) -> ot.texcoord3harray:
"""Takes in two arrays of texcoord3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3harray(
first_value: ot.texcoord3harray, second_value: ot.texcoord3harray
) -> ot.texcoord3harray:
"""Takes in two arrays of texcoord3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### timecode
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_timecode(first_value: ot.timecode, second_value: ot.timecode) -> ot.timecode:
"""Takes in two timecodes outputs the sum of them.
The types of both inputs and the return value are Python floats with the full precision required in order
to represent the range of legal timecodes. When put into Fabric and USD the values are stored as a
double-precision floating point value.
"""
return first_value + second_value
```
### timecode[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_timecodearray(first_value: ot.timecodearray, second_value: ot.timecodearray) -> ot.timecodearray:
"""Takes in two arrays of timecodes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
### vectord[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3d(first_value: ot.vector3d, second_value: ot.vector3d) -> ot.vector3d:
"""Takes in two vectord[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### vectord[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3darray(first_value: ot.vector3darray, second_value: ot.vector3darray) -> ot.vector3darray:
"""Takes in two arrays of vector3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### vectorf[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3d(first_value: ot.vector3d, second_value: ot.vector3d) -> ot.vector3d:
"""Takes in two vectorf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3f(first_value: ot.vector3f, second_value: ot.vector3f) -> ot.vector3f:
"""Takes in two vectorf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3farray(first_value: ot.vector3farray, second_value: ot.vector3farray) -> ot.vector3farray:
"""Takes in two arrays of vector3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3h(first_value: ot.vector3h, second_value: ot.vector3h) -> ot.vector3h:
"""Takes in two vectorh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3harray(first_value: ot.vector3harray, second_value: ot.vector3harray) -> ot.vector3harray:
"""Takes in two arrays of vector3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import inspect
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_bundle(bundle: ot.bundle, added: ot.int) -> ot.bundle:
"""Takes in a bundle value and outputs a bundle containing everything in the input bundle plus a count
of "added" extra integer members named "added_0", "added_1", etc. Use the special value "added = 0" to
indicate that the bundle should be cleared.
The types of both inputs and the return value are og.BundleContents. When put into Fabric the bundle is
stored as a data bucket and in USD it is represented as a target or reference to a prim when connected.
Note how, since AutoNode definitions do not have direct access to the node, the inspect module must be
used to get at it in order to construct an output bundle.
"""
frame = inspect.currentframe().f_back
node = frame.f_locals.get("node")
```
```python
context = frame.f_locals.get("context")
result = og.BundleContents(context, node, "outputs_out_0", read_only=False, gpu_by_default=False)
result.clear()
if bundle.valid:
result.bundle = bundle
if added > 0:
first_index = result.size
for index in range(added):
result.bundle.create_attribute(f"added_{index + first_index}", og.Type(og.BaseDataType.INT))
return result
```
### execution
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_execution(first_trigger: ot.execution, second_trigger: ot.execution) -> ot.execution:
"""Takes two execution pins and triggers the output only when both of them are enabled.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 32-bit precision
integer values.
"""
if first_trigger == og.ExecutionAttributeState.ENABLED and second_trigger == og.ExecutionAttributeState.ENABLED:
return og.ExecutionAttributeState.ENABLED
return og.ExecutionAttributeState.DISABLED
```
### objectId
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_objectid(first_value: ot.objectid, second_value: ot.objectid) -> ot.objectid:
"""Takes in two objectId values and outputs the larger of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 64-bit
unsigned integer values.
"""
return first_value if first_value > second_value else second_value
```
### objectId[]
```python
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_objectidarray(first_value: ot.objectidarray, second_value: ot.objectidarray) -> ot.objectidarray:
"""Takes in two arrays of object IDs and returns an array containing the largest of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint64) where
"N" is the size of the array determined at runtime.
"""
return np.maximum(first_value, second_value)
```
### target
```python
import omni.graph.core as og
import omni.graph.core.types as ot
```
```python
from usdrt import Sdf
@og.create_node_type
def autonode_target(target_values: ot.target) -> ot.target:
"""Takes in target values and outputs the targets resulting from appending "TestChild" to the target.
The types of both inputs and the return value are list[usdrt.Sdf.Path]. Unlike most other array types this
is represented as a list rather than a numpy array since the value type is not one supported by numpy.
When put into Fabric the value is stored as an SdfPath token, while USD uses the native rel type.
"""
return [target.AppendPath("Child") for target in target_values]
```
---
| 77,441 |
examples-decoration.md | # Examples Using Custom Decoration
This file contains example usage of AutoNode decoration that use the extra decorator parameters. For access to the other types of examples see AutoNode Examples.
## Contents
- [@og.create_node_type(ui_name=str)](#og-create-node-type-ui-name-str)
- [@og.create_node_type(unique_name=str)](#og-create-node-type-unique-name-str)
- [@og.create_node_type(add_execution_pins)](#og-create-node-type-add-execution-pins)
- [@og.create_node_type(metadata=dict(str,any))](#og-create-node-type-metadata-dict-str-any)
The `@og.create_node_type` decorator takes a number of optional arguments that helps provide the extra information to the node type that is normally part of the .ogn definition.
```python
def create_node_type(
func: callable = None,
*,
unique_name: str = None,
ui_name: str = None,
add_execution_pins: bool = False,
metadata: dict[str, str] = None,
) -> callable:
"""Decorator to transform a Python function into an OmniGraph node type definition.
The decorator is configured to allow use with and without parameters. When used without parameters all of the
default values for the parameters are assumed.
If the function is called from the __main__ context, as it would if it were executed from the script editor or
from a file, then the decorator is assumed to be creating a short-lived node type definition and the default
module name "__autonode__" is applied to indicate this. Any attempts to save a scene containing these short-term
node types will be flagged as a warning.
Examples:
>>> import omni.graph.core as og
>>> @og.create_node_type
>>> def double_float(a: ogdt.Float) -> ogdt.Float:
>>> return a * 2.0
>>>
>>> @og.create_node_type(add_execution_pins=True)
>>> def double_float(a: ogdt.Float) -> ogdt.Float:
>>> return a * 2.0
Args:
func: the function object being wrapped. Should be a pure python function object or any other callable which
has an `__annotations__` property. If "None" then the decorator was called using the parameterized form
"@create_node_type(...)" instead of "@create_node_type" and the function will be inferred in other ways.
"""
```
unique_name: Override the default unique name, which is the function name in the module namespace
ui_name: Name that appears in the node type's menu and node display.
add_execution_pins: Include both input and output execution pins so that this can be used as a trigger node
type in an action graph.
metadata: Dictionary of extra metadata to apply to the node type
Returns:
Decorated version of the function that will create the node type definition
"""
These examples show how the definition of the node type is affected by each of them.
## @og.create_node_type(ui_name=str)
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(ui_name="Fluffy Bunny")
def autonode_decoration_ui_name() -> ot.string:
"""This node type has no inputs and returns the UI name of its node type as output. It demonstrates how the
optional ui_name argument can be used on the decorator to modify the name of the node type as it
will appear to the user.
"""
# We know the name of the node type by construction
node_type = og.get_node_type("omni.graph.autonode_decoration_ui_name")
# Get the metadata containing the UI name - will always return "Fluffy Bunny"
return node_type.get_metadata(og.MetadataKeys.UI_NAME)
```
## @og.create_node_type(unique_name=str)
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(unique_name="omni.graph.autonode_unique_name")
def autonode_decoration_unique_name() -> ot.string:
"""This node type has no inputs and returns the unique name of its node type as output. It demonstrates how the
optional unique_name argument can be used on the decorator to modify the name of the node type as it
is used for registration and identification.
"""
# Look up the node type name using the supplied unique name rather than the one that would have been
# automatically generated (omni.graph.autonode_decoration_unique_name)
node_type = og.get_node_type("omni.graph.autonode_unique_name")
return node_type.get_node_type() if node_type.is_valid() else ""
```
## @og.create_node_type(add_execution_pins)
```python
import inspect
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(add_execution_pins=True)
def autonode_decoration_add_execution_pins() -> ot.int:
"""This node type has no inputs and returns the number of attributes it has of type "execution". It
demonstrates how the optional add_execution_pins argument can be used on the decorator to automatically
include both an input and an output execution pin so that the node type can be easily included in the
Action Graph.
"""
frame = inspect.currentframe().f_back
node = frame.f_locals.get("node")
# This will return 2, counting the automatically added input and output execution attributes
return sum(1 for attr in node.get_attributes() if attr.get_resolved_type().role == og.AttributeRole.EXECUTION)
```
## @og.create_node_type(metadata=dict(str,any))
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type(metadata={"Emperor": "Palpatine"})
def autonode_decoration_metadata() -> ot.string:
pass
```
"""This node type has no inputs and returns a string consisting of the value of the metadata
whose name was specified in the decorator "metadata" argument. It demonstrates how the optional metadata
argument can be used on the decorator to automatically add metadata to the node type definition."""
# We know the name of the node type by construction
node_type = og.get_node_type("omni.graph.autonode_decoration_metadata")
# Return the metadata with the custom name we specified - will always return "Palpatine"
return node_type.get_metadata("Emperor") | 6,063 |
examples-multi-outputs.md | # Multiple-Output Examples
This file contains example usage for AutoNode functions that have more than one output. For access to the other types of examples see AutoNode Examples.
## Contents
* [Multiple Simple Outputs](#multiple-simple-outputs)
* [Multiple Tuple Outputs](#multiple-tuple-outputs)
## Multiple Simple Outputs
```python
import statistics as st
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_multi_simple(values: ot.floatarray) -> tuple[ot.float, ot.float, ot.float]:
"""Takes in a list of floating point values and returns three outputs that are the mean, median,
and mode of the values in the list. The outputs will be named "out_0", "out_1", and "out_2".
"""
return (values.mean(), np.median(values), st.mode(values))
```
## Multiple Tuple Outputs
```python
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_multi_tuple(original: ot.matrix2d) -> tuple[ot.matrix2d, ot.matrix2d]:
"""Takes in a 2x2 matrix and returns two outputs that are the inverse and transpose of the matrix.
Reports an error if the matrix is not invertible. Note that even though the data types themselves
```
are tuples the return values will be correctly interpreted as being separate output attributes
with each of the outputs itself being a tuple value. The outputs will be named "out_1" and "out_2".
"""
try:
return (original.transpose(), np.linalg.inv(original))
except np.linalg.LinAlgError as error:
raise og.OmniGraphError(f"Could not invert matrix {original}") from error | 1,645 |
examples-roles.md | # Role-Based Data Type Examples
This file contains example usage for all of the AutoNode role-based data types. For access to the other types of examples see AutoNode Examples.
## Contents
- [colord[3]](#colord-3)
- [colord[3][]](#id1)
- [colorf[3]](#colorf-3)
- [colorf[3][]](#id2)
- [colorh[3]](#colorh-3)
- [colorh[3][]](#id3)
- [colord[4]](#colord-4)
- [colord[4][]](#id4)
- [colorf[4]](#colorf-4)
- [colorf[4][]](#id5)
- [colorh[4]](#colorh-4)
- [colorh[4][]](#id6)
- [frame[4]](#frame-4)
- [frame[4][]](#id7)
- [matrixd[2]](#matrixd-2)
- [matrixd[2][]](#id8)
- [matrixd[3]](#matrixd-3)
- [matrixd[3][]](#id9)
- [matrixd[4]](#matrixd-4)
- [matrixd[4][]](#id10)
- [normald[3]](#normald-3)
- [normald[3][]](#id11)
- **`normald[3][]`**
- **`normalf[3]`**
- **`normalf[3][]`**
- **`normalh[3]`**
- **`normalh[3][]`**
- **`pointd[3]`**
- **`pointd[3][]`**
- **`pointf[3]`**
- **`pointf[3][]`**
- **`pointh[3]`**
- **`pointh[3][]`**
- **`quatd[4]`**
- **`quatd[4][]`**
- **`quatf[4]`**
- **`quatf[4][]`**
- **`quath[4]`**
- **`quath[4][]`**
- **`texcoordd[2]`**
- **`texcoordd[2][]`**
- **`texcoordf[2]`**
- **`texcoordf[2][]`**
- **`texcoordh[2]`**
- **`texcoordh[2][]`**
- **`texcoordd[3]`**
- **`texcoordd[3][]`**
- **`texcoordf[3]`**
- **`texcoordf[3][]`**
- **`texcoordh[3]`**
- **`texcoordh[3][]`**
- **`timecode`**
- **`timecode[]`**
- **`vectord[3]`**
- **`vectord[3][]`**
- **`vectorf[3]`**
- **`vectorf[3][]`**
- **`vectorh[3]`**
- **`vectorh[3][]`**
### colord[3]
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3d(first_value: ot.color3d, second_value: ot.color3d) -> ot.color3d:
"""Takes in two colord[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3darray(first_value: ot.color3darray, second_value: ot.color3darray) -> ot.color3darray:
"""Takes in two arrays of color3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3f(first_value: ot.color3f, second_value: ot.color3f) -> ot.color3f:
"""Takes in two colorf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3farray(first_value: ot.color3farray, second_value: ot.color3farray) -> ot.color3farray:
"""Takes in two arrays of color3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3h(first_value: ot.color3h, second_value: ot.color3h) -> ot.color3h:
"""Takes in two colorh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color3harray(first_value: ot.color3harray, second_value: ot.color3harray) -> ot.color3harray:
"""Takes in two arrays of color3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4d(first_value: ot.color4d, second_value: ot.color4d) -> ot.color4d:
"""Takes in two color4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric the values are stored as 4 double-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colord[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4darray(first_value: ot.color4darray, second_value: ot.color4darray) -> ot.color4darray:
"""Takes in two arrays of color4d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4f(first_value: ot.color4f, second_value: ot.color4f) -> ot.color4f:
"""Takes in two color4f values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric the values are stored as 4 single-precision values. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorf[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4farray(first_value: ot.color4farray, second_value: ot.color4farray) -> ot.color4farray:
"""Takes in two arrays of color4f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
## colorh[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4h(first_value: ot.color4h, second_value: ot.color4h) -> ot.color4h:
"""Takes in two color4h values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric the values are stored as 4 half-precision values. The color role is applied to USD and OmniGraph types as
an aid to interpreting the values.
"""
return first_value + second_value
```
### colorh[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_color4harray(first_value: ot.color4harray, second_value: ot.color4harray) -> ot.color4harray:
"""Takes in two arrays of color4h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The color role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### frame[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_frame4d(first_value: ot.frame4d, second_value: ot.frame4d) -> ot.frame4d:
"""Takes in two frame4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4), dtype=numpy.float64). When put
into Fabric the values are stored as a set of 16 double-precision values. USD uses the special frame4d type.
"""
return first_value + second_value
```
### frame[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_frame4darray(first_value: ot.frame4darray, second_value: ot.frame4darray) -> ot.frame4darray:
"""Takes in two frame4darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. When put into Fabric the values are stored as an array of sets
of 16 double-precision values. USD stores it as the native frame4d[] type.
"""
return first_value + second_value
```
### matrixd[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix2d(first_value: ot.matrix2d, second_value: ot.matrix2d) -> ot.matrix2d:
"""Takes in two matrix2d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(2,2), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 4 double-precision values.
"""
return first_value + second_value
```
### matrixd[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix2darray(first_value: ot.matrix2darray, second_value: ot.matrix2darray) -> ot.matrix2darray:
"""Takes in two matrix2darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(N,2,2), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 9 double-precision values. USD stores it as the native matrix2d[] type.
"""
return first_value + second_value
```
### matrixd[3]
```
# matrix3d
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix3d(first_value: ot.matrix3d, second_value: ot.matrix3d) -> ot.matrix3d:
"""Takes in two matrix3d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(3,3), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 9 double-precision values.
"""
return first_value + second_value
```
# matrix3darray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix3darray(first_value: ot.matrix3darray, second_value: ot.matrix3darray) -> ot.matrix3darray:
"""Takes in two matrix3darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(3,3,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 9 double-precision values. USD stores it as the native matrix3d[] type.
"""
return first_value + second_value
```
# matrix4d
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix4d(first_value: ot.matrix4d, second_value: ot.matrix4d) -> ot.matrix4d:
"""Takes in two matrix4d values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4), dtype=numpy.float64). When put
into Fabric and USD the values are stored as a list of 9 double-precision values.
"""
return first_value + second_value
```
# matrix4darray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_matrix4darray(first_value: ot.matrix4darray, second_value: ot.matrix4darray) -> ot.matrix4darray:
"""Takes in two matrix4darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(4,4,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 16 double-precision values. USD stores it as the native matrix4d[] type.
"""
return first_value + second_value
```
# normal3d
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3d(first_value: ot.normal3d, second_value: ot.normal3d) -> ot.normal3d:
"""Takes in two normald[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
# normal3darray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3darray(first_value: ot.normal3darray, second_value: ot.normal3darray) -> ot.normal3darray:
"""Takes in two normal3darray values and outputs the sum of them.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.. When put into Fabric the values are stored as an array of sets
of 3 double-precision values. USD stores it as the native normal3d[] type.
"""
return first_value + second_value
```python
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3darray(first_value: ot.normal3darray, second_value: ot.normal3darray) -> ot.normal3darray:
"""Takes in two arrays of normal3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### normalf[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3f(first_value: ot.normal3f, second_value: ot.normal3f) -> ot.normal3f:
"""Takes in two normalf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### normalf[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3farray(first_value: ot.normal3farray, second_value: ot.normal3farray) -> ot.normal3farray:
"""Takes in two arrays of normal3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### normalh[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3h(first_value: ot.normal3h, second_value: ot.normal3h) -> ot.normal3h:
"""Takes in two normalh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### normalh[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_normal3harray(first_value: ot.normal3harray, second_value: ot.normal3harray) -> ot.normal3harray:
"""Takes in two arrays of normal3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The normal role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### pointd[3]
```python
import omni.graph.core as og
```
```python
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3d(first_value: ot.point3d, second_value: ot.point3d) -> ot.point3d:
"""Takes in two pointd[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3darray(first_value: ot.point3darray, second_value: ot.point3darray) -> ot.point3darray:
"""Takes in two arrays of point3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3f(first_value: ot.point3f, second_value: ot.point3f) -> ot.point3f:
"""Takes in two pointf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3farray(first_value: ot.point3farray, second_value: ot.point3farray) -> ot.point3farray:
"""Takes in two arrays of point3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3h(first_value: ot.point3h, second_value: ot.point3h) -> ot.point3h:
"""Takes in two pointh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3harray(first_value: ot.point3harray, second_value: ot.point3harray) -> ot.point3harray:
"""Takes in two arrays of pointh attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_point3harray(first_value: ot.point3harray, second_value: ot.point3harray) -> ot.point3harray:
"""Takes in two arrays of point3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The point role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### quatd[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatd(first_value: ot.quatd, second_value: ot.quatd) -> ot.quatd:
"""Takes in two quatd[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric the values are stored as 4 double-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
### quatd[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatdarray(first_value: ot.quatdarray, second_value: ot.quatdarray) -> ot.quatdarray:
"""Takes in two arrays of quatd attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### quatf[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatf(first_value: ot.quatf, second_value: ot.quatf) -> ot.quatf:
"""Takes in two quatf[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric the values are stored as 4 single-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
### quatf[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatfarray(first_value: ot.quatfarray, second_value: ot.quatfarray) -> ot.quatfarray:
"""Takes in two arrays of quatf attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
### quath[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quath(first_value: ot.quath, second_value: ot.quath) -> ot.quath:
"""Takes in two quath[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float128). When put into
Fabric the values are stored as 4 quadruple-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
def autonode_quath(first_value: ot.quath, second_value: ot.quath) -> ot.quath:
"""Takes in two quath[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric the values are stored as 4 half-precision values. The quaternion role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_quatharray(first_value: ot.quatharray, second_value: ot.quatharray) -> ot.quatharray:
"""Takes in two arrays of quath attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The quaternion role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2d(first_value: ot.texcoord2d, second_value: ot.texcoord2d) -> ot.texcoord2d:
"""Takes in two texcoordd[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float64). When put into
Fabric the values are stored as 2 double-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2darray(first_value: ot.texcoord2darray, second_value: ot.texcoord2darray) -> ot.texcoord2darray:
"""Takes in two arrays of texcoord2d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2f(first_value: ot.texcoord2f, second_value: ot.texcoord2f) -> ot.texcoord2f:
"""Takes in two texcoordf[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float32). When put into
Fabric the values are stored as 2 single-precision values. The texcoord role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2farray(first_value: ot.texcoord2farray, second_value: ot.texcoord2farray) -> ot.texcoord2farray:
"""Takes in two arrays of texcoord2f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
def autonode_texcoord2farray(
first_value: ot.texcoord2farray, second_value: ot.texcoord2farray
) -> ot.texcoord2farray:
"""Takes in two arrays of texcoord2f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2h(first_value: ot.texcoord2h, second_value: ot.texcoord2h) -> ot.texcoord2h:
"""Takes in two texcoordh[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float16). When put into
Fabric the values are stored as 2 half-precision values. The texcoord role is applied to USD and OmniGraph
types as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord2harray(
first_value: ot.texcoord2harray, second_value: ot.texcoord2harray
) -> ot.texcoord2harray:
"""Takes in two arrays of texcoord2h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3d(first_value: ot.texcoord3d, second_value: ot.texcoord3d) -> ot.texcoord3d:
"""Takes in two texcoordd[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3darray(
first_value: ot.texcoord3darray, second_value: ot.texcoord3darray
) -> ot.texcoord3darray:
"""Takes in two arrays of texcoord3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3f(first_value: ot.texcoord3f, second_value: ot.texcoord3f) -> ot.texcoord3f:
"""Takes in two texcoordf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3f(first_value: ot.texcoord3f, second_value: ot.texcoord3f) -> ot.texcoord3f:
"""Takes in two texcoordf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3farray(
first_value: ot.texcoord3farray, second_value: ot.texcoord3farray
) -> ot.texcoord3farray:
"""Takes in two arrays of texcoord3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3h(first_value: ot.texcoord3h, second_value: ot.texcoord3h) -> ot.texcoord3h:
"""Takes in two texcoordh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_texcoord3harray(
first_value: ot.texcoord3harray, second_value: ot.texcoord3harray
) -> ot.texcoord3harray:
"""Takes in two arrays of texcoord3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The texcoord role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_timecode(first_value: ot.timecode, second_value: ot.timecode) -> ot.timecode:
"""Takes in two timecodes outputs the sum of them.
The types of both inputs and the return value are Python floats with the full precision required in order
to represent the range of legal timecodes. When put into Fabric and USD the values are stored as a
double-precision floating point value.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_timecodearray(first_value: ot.timecodearray, second_value: ot.timecodearray) -> ot.timecodearray:
"""Takes in two arrays of timecodes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3d(first_value: ot.vector3d, second_value: ot.vector3d) -> ot.vector3d:
"""Takes in two vectord[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric the values are stored as 3 double-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3darray(first_value: ot.vector3darray, second_value: ot.vector3darray) -> ot.vector3darray:
"""Takes in two arrays of vector3d attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3f(first_value: ot.vector3f, second_value: ot.vector3f) -> ot.vector3f:
"""Takes in two vectorf[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric the values are stored as 3 single-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3farray(first_value: ot.vector3farray, second_value: ot.vector3farray) -> ot.vector3farray:
"""Takes in two arrays of vector3f attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3h(first_value: ot.vector3h, second_value: ot.vector3h) -> ot.vector3h:
"""Takes in two vectorh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
def autonode_vector3h(first_value: ot.vector3h, second_value: ot.vector3h) -> ot.vector3h:
"""Takes in two vectorh[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric the values are stored as 3 half-precision values. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
```
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_vector3harray(first_value: ot.vector3harray, second_value: ot.vector3harray) -> ot.vector3harray:
"""Takes in two arrays of vector3h attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime. The vector role is applied to USD and OmniGraph types
as an aid to interpreting the values.
"""
return first_value + second_value
``` | 39,804 |
examples-simple.md | # Simple Data Type Examples
This file contains example usage for all of the AutoNode simple data types. For access to the other types of examples see AutoNode Examples.
## Contents
- [bool](#bool)
- [bool[]](#bool-array)
- [double](#double)
- [double[]](#double-array)
- [float](#float)
- [float[]](#float-array)
- [half](#half)
- [half[]](#half-array)
- [int](#int)
- [int[]](#int-array)
- [int64](#int64)
- [int64[]](#int64-array)
- [string](#string)
- [token](#token)
- [token[]](#token-array)
- [uchar](#uchar)
- [uchar[]](#uchar-array)
- [uint](#uint)
- [uint[]](#uint-array)
- [uint64](#uint64)
- [uint64[]](#uint64-array)
## bool
# 自动节点类型
## 布尔类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_bool(first_value: ot.bool, second_value: ot.bool) -> ot.boolean:
"""Takes in two boolean values and outputs the logical AND of them.
The types of both inputs and the return value are Python booleans.
Note that the return type name is the Warp-compatible "boolean", which is just a synonym for "bool".
"""
return first_value and second_value
```
## 布尔数组类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_boolarray(first_value: ot.boolarray, second_value: ot.boolarray) -> ot.boolarray:
"""Takes in two arrays of boolean attributes and returns an array with the logical AND of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=bool) where "N" is the
size of the array determined at runtime.
"""
return first_value & second_value
```
## 双精度类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double(first_value: ot.double, second_value: ot.double) -> ot.float64:
"""Takes in two double precision values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as double.
precision values.
Note that the return type is the Warp-compatible "float64" which is a synonym for "double".
"""
return first_value + second_value
```
## 双精度数组类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_doublearray(first_value: ot.doublearray, second_value: ot.doublearray) -> ot.doublearray:
"""Takes in two arrays of double attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## 浮点类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float(first_value: ot.float, second_value: ot.float) -> ot.float32:
"""Takes in two single-precision floating point values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as single-precision
floating point values.
Note that the return type is the Warp-compatible "float32" which is a synonym for "float".
"""
return first_value + second_value
```
## 浮点数组类型
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_floatarray(first_value: ot.floatarray, second_value: ot.floatarray) -> ot.floatarray:
"""Takes in two arrays of float attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# autonode_floatarray
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_floatarray(first_value: ot.floatarray, second_value: ot.floatarray) -> ot.floatarray:
"""Takes in two arrays of float attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# half
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half(first_value: ot.half, second_value: ot.half) -> ot.float16:
"""Takes in two half-precision floating point values and outputs the sum of them.
The types of both inputs and the return value are Python floats as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as half
precision floating point values.
Note that the return type is the Warp-compatible "float16" which is a synonym for "half".
"""
return first_value + second_value
```
# half[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_halfarray(first_value: ot.halfarray, second_value: ot.halfarray) -> ot.halfarray:
"""Takes in two arrays of half attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# int
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int(first_value: ot.int, second_value: ot.int) -> ot.int32:
"""Takes in two 32-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 32-bit precision
integer values.
Note that the return type is the Warp-compatible "int32" which is a synonym for "int".
"""
return first_value + second_value
```
# int[]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_intarray(first_value: ot.intarray, second_value: ot.intarray) -> ot.intarray:
"""Takes in two arrays of integer attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# int64
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int64(first_value: ot.int64, second_value: ot.int64) -> ot.int64:
"""Takes in two 64-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 64-bit precision
integer values.
Note that the return type is the Warp-compatible "int64" which is a synonym for "int64".
"""
return first_value + second_value
```
"""Takes in two 64-bit precision integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 64-bit precision
integer values.
"""
return first_value + second_value
## int64[]
"""Takes in two arrays of 64-bit integer attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.int64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
## string
"""Takes in two string values and outputs the concatenated string.
The types of both inputs and the return value are Python str. When put into Fabric the values are
stored as uchar arrays with a length value. USD stores it as a native string type.
"""
return first_value + second_value
## token
"""Takes in two tokenized strings and outputs the string resulting from concatenating them together.
The types of both inputs and the return value are Python strs as Python does not have the concept of a
unique tokenized string. When put into Fabric and USD the values are stored as a single
64-bit unsigned integer that is a token.
"""
return first_value + second_value
## token[]
"""Takes in two arrays of tokens and returns an array containing the concatenations of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype="<U") where "N" is
the size of the array determined at runtime.
"""
return np.array([x + y for x, y in zip(first_value, second_value)])
## uchar
"""Takes in two 8-bit precision unsigned integer values and outputs the sum of them.
"""
return first_value + second_value
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 8-bit
precision unsigned integer values.
Note that the return type is the Warp-compatible "uint8" which is a synonym for "uchar".
"""
return first_value + second_value
## uchar[]
Takes in two arrays of 8-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uchar8) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
## uint
Takes in two 32-bit precision unsigned integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 32-bit
precision unsigned integer values.
"""
return first_value + second_value
## uint[]
Takes in two arrays of 32-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint32) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
## uint64
Takes in two 64-bit precision unsigned integer values and outputs the sum of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 64-bit
precision unsigned integer values.
"""
return first_value + second_value
## uint64[]
Takes in two arrays of 8-bit unsigned integer attributes and returns an array containing the sum of each
element. The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint64) where
"N" is the size of the array determined at runtime.
"""
return first_value + second_value
# 标题1
## 子标题1
这是一个段落,包含了一些文本和一些链接,比如[这是一个链接](#)。
## 子标题2
```python
def add_values(first_value, second_value):
"""
return first_value + second_value
"""
``` | 11,534 |
examples-special.md | # Special Data Type Examples
This file contains example usage for all of the AutoNode special data types. For access to the other types of examples see AutoNode Examples.
## Contents
- [bundle](#bundle)
- [execution](#execution)
- [objectId](#objectid)
- [objectId[]](#id1)
- [target](#target)
## bundle
### Takes in a bundle value and outputs a bundle containing everything in the input bundle plus a count of "added" extra integer members named "added_0", "added_1", etc. Use the special value "added = 0" to indicate that the bundle should be cleared.
The types of both inputs and the return value are og.BundleContents. When put into Fabric the bundle is stored as a data bucket and in USD it is represented as a target or reference to a prim when connected.
Note how, since AutoNode definitions do not have direct access to the node, the inspect module must be used to get at it in order to construct an output bundle.
```python
import inspect
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_bundle(bundle: ot.bundle, added: ot.int) -> ot.bundle:
"""Takes in a bundle value and outputs a bundle containing everything in the input bundle plus a count
of "added" extra integer members named "added_0", "added_1", etc. Use the special value "added = 0" to
indicate that the bundle should be cleared.
The types of both inputs and the return value are og.BundleContents. When put into Fabric the bundle is
stored as a data bucket and in USD it is represented as a target or reference to a prim when connected.
Note how, since AutoNode definitions do not have direct access to the node, the inspect module must be
used to get at it in order to construct an output bundle.
"""
frame = inspect.currentframe().f_back
node = frame.f_locals.get("node")
context = frame.f_locals.get("context")
result = og.BundleContents(context, node, "outputs_out_0", read_only=False, gpu_by_default=False)
result.clear()
```
```python
if bundle.valid:
result.bundle = bundle
if added > 0:
first_index = result.size
for index in range(added):
result.bundle.create_attribute(f"added_{index + first_index}", og.Type(og.BaseDataType.INT))
return result
```
## execution
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_execution(first_trigger: ot.execution, second_trigger: ot.execution) -> ot.execution:
"""Takes two execution pins and triggers the output only when both of them are enabled.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels. When put into Fabric and USD the values are stored as 32-bit precision
integer values.
"""
if first_trigger == og.ExecutionAttributeState.ENABLED and second_trigger == og.ExecutionAttributeState.ENABLED:
return og.ExecutionAttributeState.ENABLED
return og.ExecutionAttributeState.DISABLED
```
## objectId
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_objectid(first_value: ot.objectid, second_value: ot.objectid) -> ot.objectid:
"""Takes in two objectId values and outputs the larger of them.
The types of both inputs and the return value are Python ints as Python does not distinguish between
different precision levels or signs. When put into Fabric and USD the values are stored as 64-bit
unsigned integer values.
"""
return first_value if first_value > second_value else second_value
```
## objectId[]
```python
import numpy as np
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_objectidarray(first_value: ot.objectidarray, second_value: ot.objectidarray) -> ot.objectidarray:
"""Takes in two arrays of object IDs and returns an array containing the largest of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(N,), dtype=numpy.uint64) where
"N" is the size of the array determined at runtime.
"""
return np.maximum(first_value, second_value)
```
## target
```python
import omni.graph.core as og
import omni.graph.core.types as ot
from usdrt import Sdf
@og.create_node_type
def autonode_target(target_values: ot.target) -> ot.target:
"""Takes in target values and outputs the targets resulting from appending "TestChild" to the target.
The types of both inputs and the return value are list[usdrt.Sdf.Path]. Unlike most other array types this
```
is represented as a list rather than a numpy array since the value type is not one supported by numpy.
When put into Fabric the value is stored as an SdfPath token, while USD uses the native rel type.
"""
return [target.AppendPath("Child") for target in target_values] | 4,852 |
examples-tuple.md | # Tuple Data Type Examples
This file contains example usage for all of the AutoNode tuple data types. For access to the other types of examples see AutoNode Examples.
## Contents
- [double[2]](#double-2)
- [double[2][]](#id1)
- [double[3]](#double-3)
- [double[3][]](#id2)
- [double[4]](#double-4)
- [double[4][]](#id3)
- [float[2]](#float-2)
- [float[2][]](#id4)
- [float[3]](#float-3)
- [float[3][]](#id5)
- [float[4]](#float-4)
- [float[4][]](#id6)
- [half[2]](#half-2)
- [half[2][]](#id7)
- [half[3]](#half-3)
- [half[3][]](#id8)
- [half[4]](#half-4)
- [half[4][]](#id9)
- [int[2]](#int-2)
- [int[2][]](#id10)
- [int[3]](#int-3)
- [int[3][]](#id11)
- **int[4]**
- **int[4][]**
## double[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double2(first_value: ot.double2, second_value: ot.double2) -> ot.double2:
"""Takes in two double[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as two double-precision floating point values.
"""
return first_value + second_value
```
## double[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double2array(first_value: ot.double2array, second_value: ot.double2array) -> ot.double2array:
"""Takes in two arrays of double2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## double[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double3(first_value: ot.double3, second_value: ot.double3) -> ot.double3:
"""Takes in two double[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as three double-precision floating point values.
"""
return first_value + second_value
```
## double[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double3array(first_value: ot.double3array, second_value: ot.double3array) -> ot.double3array:
"""Takes in two arrays of double3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## double[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double4(first_value: ot.double4, second_value: ot.double4) -> ot.double4:
"""Takes in two double[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float64). When put into
Fabric and USD the values are stored as four double-precision floating point values.
"""
return first_value + second_value
```
## double[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double4array(first_value: ot.double4array, second_value: ot.double4array) -> ot.double4array:
"""Takes in two arrays of double4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# double[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_double4array(first_value: ot.double4array, second_value: ot.double4array) -> ot.double4array:
"""Takes in two arrays of double4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float64) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# float[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float2(first_value: ot.float2, second_value: ot.float2) -> ot.float2:
"""Takes in two float[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as two single-precision floating point values.
"""
return first_value + second_value
```
# float[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float2array(first_value: ot.float2array, second_value: ot.float2array) -> ot.float2array:
"""Takes in two arrays of float2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# float[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float3(first_value: ot.float3, second_value: ot.float3) -> ot.float3:
"""Takes in two float[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as three single-precision floating point values.
"""
return first_value + second_value
```
# float[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float3array(first_value: ot.float3array, second_value: ot.float3array) -> ot.float3array:
"""Takes in two arrays of float3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# float[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float4(first_value: ot.float4, second_value: ot.float4) -> ot.float4:
"""Takes in two float[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as four single-precision floating point values.
"""
return first_value + second_value
```
# autonode_float4
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float4(first_value: ot.float4, second_value: ot.float4) -> ot.float4:
"""Takes in two float[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float32). When put into
Fabric and USD the values are stored as four single-precision floating point values.
"""
return first_value + second_value
```
# float[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_float4array(first_value: ot.float4array, second_value: ot.float4array) -> ot.float4array:
"""Takes in two arrays of float4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# half[2]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half2(first_value: ot.half2, second_value: ot.half2) -> ot.half2:
"""Takes in two half[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as two 16-bit floating point values.
"""
return first_value + second_value
```
# half[2][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half2array(first_value: ot.half2array, second_value: ot.half2array) -> ot.half2array:
"""Takes in two arrays of half2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
# half[3]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half3(first_value: ot.half3, second_value: ot.half3) -> ot.half3:
"""Takes in two half[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as three 16-bit floating point values.
"""
return first_value + second_value
```
# half[3][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_half3array(first_value: ot.half3array, second_value: ot.half3array) -> ot.half3array:
"""Takes in two arrays of half3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
"""Takes in two arrays of half3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
## half[4]
"""Takes in two half[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.float16). When put into
Fabric and USD the values are stored as four 16-bit floating point values.
"""
return first_value + second_value
## half[4][]
"""Takes in two arrays of half4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.float16) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
## int[2]
"""Takes in two int[2] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(2,), dtype=numpy.int32). When put into
Fabric and USD the values are stored as two 32-bit integer values.
"""
return first_value + second_value
## int[2][]
"""Takes in two arrays of int2 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(2,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
## int[3]
"""Takes in two int[3] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(3,), dtype=numpy.int32). When put into
Fabric and USD the values are stored as three 32-bit integer values.
"""
return first_value + second_value
## int[3][]
"""Takes in two arrays of int3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
## int3array
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int3array(first_value: ot.int3array, second_value: ot.int3array) -> ot.int3array:
"""Takes in two arrays of int3 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(3,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
```
## int[4]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int4(first_value: ot.int4, second_value: ot.int4) -> ot.int4:
"""Takes in two int[4] values and outputs the sum of them.
The types of both inputs and the return value are numpy.array(shape=(4,), dtype=numpy.int32). When put into
Fabric and USD the values are stored as two 32-bit integer values.
"""
return first_value + second_value
```
## int[4][]
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.create_node_type
def autonode_int4array(first_value: ot.int4array, second_value: ot.int4array) -> ot.int4array:
"""Takes in two arrays of int4 attributes and returns an array containing the sum of each element.
The types of both inputs and the return value are numpy.ndarray(shape=(4,N,), dtype=numpy.int32) where "N" is
the size of the array determined at runtime.
"""
return first_value + second_value
``` | 13,755 |
examples.md | # AutoNode Examples
For simplicity the set of examples is broken out into subsections so that you more easily navigate to the types that are of use to you. In addition, if you wish to easily peruse the set of all available examples they have been aggregated into a single file.
## Types of Data Handled
- [Simple Data Type Examples](examples-simple.html)
- [Tuple Data Type Examples](examples-tuple.html)
- [Role-Based Data Type Examples](examples-roles.html)
- [Special Data Type Examples](examples-special.html)
To see the full list of data types available for use look at the Data Types document.
## Special Examples
- [Multiple-Output Examples](examples-multi-outputs.html)
- [Examples Using Custom Decoration](examples-decoration.html)
- [All Data Type Examples](examples-all.html) | 792 |
example_Overview.md | # Overview
This document will cover the basic concepts and give examples of how to build a graph extension. It mainly focuses on:
- how to build a simple graph model which manages the data for the graph
- how to create a custom graph delegate which controls the look of the graph
- how to create a graph example based on our generic base widget of GraphEditorCoreWidget.
## Example
`omni.kit.graph.editor.example` is an extension we built up as an example for developers to start their journey on building up their own graph extension.
To have a preview of how the graph looks and how it works, you can find the extension `omni.kit.graph.editor.example` and enable it in your app (e.g. Code, enabled by default)
There is a start panel on the right hand graph editor where you can start to Open or Create your graph. You can drag and drop nodes from the left catalog widget, which contains a list of available nodes, to the graph editor area. There is also a simple toolbar on the top where you can open or save, or go back to the start frame. Once you start editing the graph, there will be a dropdown widget where you can switch between different delegate styles for your graph.
In summary, the simple example demonstrates:
- save and import graph
- node creation and deletion
- ports connection and disconnection
- switch between different graph delegates with the same graph model
- Use backdrop and subgraph nodes to organize the graph visually and hierarchically
## Make your own extension
You are welcome to fork the code as your extension start point and build your own from there.
This example is not USD based to simplify the demonstration of the graph model. It is using json for serialization. All the Nodes and Ports and their properties are string based. If you are looking for a Usd-based graph extension example, please refer to `omni.kit.window.material_graph`, which has more complications, however. | 1,927 |
execution.md | # Running the service
The Scene Optimizer can either be executed via the docker container, on bare metal via the kit CLI or as a Task on Omniverse Farm (recommended).
## Docker
Sign up to NGC Log in via docker:
First, pull the `services` docker container from NGC’s docker repository:
```docker
docker pull YOUR_DOCKERHUB_USERNAME/my-service-image:v1
```
```docker
docker run -it --rm \
-p 8000:8000 \
-e USER=my_username \
-e TOKEN=my_token \
my-service-image --config_json_url=https://example.com/path/to/config.json
```
You can now access the services’ swagger UI to learn about it’s API, send requests and get Curl example commands.
## Bare Metal + Omniverse Kit CLI
Example command line when using it with Omniverse Kit:
```bash
```
Once the service is running, you can evoke the /request endpoint to process files.
## Omniverse Farm TaaS (Task as a Service)
When using it as a Task on Omniverse Farm, a job definition needs to be provided. The job definition informs the farm task about which service endpoint should be executed by the farm as well as the json configuration for defining Scene Optimizer processes to be completed. | 1,166 |
ExecutorCreation.md | # Executor Creation
This is a practitioner’s guide to using the Execution Framework. Before continuing, it is recommended you first review the [Execution Framework Overview](#ef-framework) along with basic topics such as [Graphs Concepts](#ef-graph-concepts), [Pass Concepts](#ef-pass-concepts), and [Execution Concepts](#ef-execution-concepts).
Customizing execution can happen at many levels, let’s have a look at different examples.
## Customizing Visit Strategy
The default `ExecutorFallback`’s visit strategy and execution order is matching traversal over the entire graph, where each node gets computed only once when all upstream nodes complete computation. Without changing the traversal order, we can change the visit strategy to only compute when the underlying node requests to compute.
### Listing 31: A custom visit strategy for visiting only nodes that requested compute.
```cpp
struct ExecutionVisitWithCacheCheck
{
//! Called when the traversal wants to visit a node. This method determines what to do with the node (e.g. schedule
//! it, defer it, etc).
template <typename ExecutorInfo>
static Status tryVisit(ExecutorInfo info) noexcept
{
auto& nodeData = info.getNodeData();
auto triggeringTaskStatus = info.currentTask.getExecutionStatus();
if (triggeringTaskStatus == Status::eSuccess)
nodeData.hasComputedUpstream = true; // we only set to true...doesn't matter which thread does it first
else if (triggeringTaskStatus == Status::eDeferred)
nodeData.hasDeferredUpstream = true; // we only set to true...doesn't matter which thread does it first
}
}
```
```cpp
std::size_t requiredCount = info.nextNode->getParents().size() - info.nextNode->getCycleParentCount();
if ((requiredCount == 0) || (++nodeData.visitCount == requiredCount))
{
if (nodeData.hasDeferredUpstream)
return Status::eDeferred;
else
{
// spawning a task within executor doesn't change the upstream path. just reference the same one.
ExecutionTask newTask(info.getContext(), info.nextNode, info.getUpstreamPath());
if (nodeData.hasComputedUpstream ||
info.getContext()->getStateInfo(newTask)->needsCompute(info.getExecutionStamp()))
return info.schedule(std::move(newTask));
else // continue downstream...there may be something dirty. Bypass scheduler to avoid unnecessary
// overhead
return info.continueExecute(newTask);
}
}
return Status::eUnknown;
}
};
```
In this modified version, we will only compute a node and propagate this to the downstream when compute was requested.
## Customizing Preallocated Per-node Data
Sometimes visit strategy must store more data per node to achieve the desired execution behavior.
We will use an example from a pipeline graph that dynamically generates more work based on data and a static graph.
```cpp
struct TestPipelineExecutionNodeData : public ExecutionNodeData
{
DynamicNode* getNode(ExecutionTaskTag tag)
{
if (tag == ExecutionTask::kEmptyTag)
return nullptr;
auto findIt = generatedNodes.find(tag);
return findIt != generatedNodes.end() ? &findIt->second : nullptr;
}
DynamicNode* createNode(ExecutionTask&& task)
{
if (!task.hasValidTag())
return nullptr; // LCOV_EXCL_LINE
auto findIt = generatedNodes.find(task.getTag());
// ... rest of the code ...
}
};
```
```cpp
if (findIt != generatedNodes.end())
return &findIt->second; // LCOV_EXCL_LINE
auto added = generatedNodes.emplace(task.getTag(), std::move(task));
return &added.first->second;
}
using DynamicNodes = std::map<ExecutionTaskTag, DynamicNode>;
DynamicNodes generatedNodes;
std::atomic<std::size_t> dynamicUpstreamCount{ 0 };
std::atomic<std::size_t> dynamicVisitCount{ 0 };
};
```
```cpp
template <typename ExecutorInfo>
Status TestPipelineExecutionVisit::tryVisit(ExecutorInfo info) noexcept
{
OMNI_GRAPH_EXEC_ASSERT(info.nextNode->getCycleParentCount() == 0);
auto pipelineNodeDef = omni::graph::exec::unstable::cast<TestPipelineNodeDef>(info.nextNode->getNodeDef());
if (!pipelineNodeDef)
return Status::eFailure; // LCOV_EXCL_LINE
auto executor = omni::graph::exec::unstable::cast<TestPipelineExecutor>(info.getExecutor());
REQUIRE(executor);
const ExecutionTask& currentTask = info.currentTask;
auto& predData = info.getExecutor()->getNodeData(currentTask.getNode());
auto& nodeData = info.getNodeData();
std::size_t dynamicVisit = 0;
if (!currentTask.hasValidTag()) // we enter a pre-visit that can statically generate work
{
nodeData.dynamicUpstreamCount += predData.generatedNodes.size();
nodeData.visitCount++;
dynamicVisit = nodeData.dynamicVisitCount;
Status status = pipelineNodeDef->generate(
```
currentTask, info.nextNode, TestPipelineNodeDef::VisitStep::ePreExecute, executor->getDynamicGraph());
if (status == Status::eSuccess /*STATIC*/ && nodeData.visitCount >= info.nextNode->getParents().size())
{
ExecutionTask newTask(info.getContext(), info.nextNode, info.getUpstreamPath());
(void)executor->continueExecute(newTask);
}
else
{
dynamicVisit = ++nodeData.dynamicVisitCount;
DynamicNode* predDynamicNode = predData.getNode(currentTask.getTag());
predDynamicNode->done();
pipelineNodeDef->generate(
currentTask, info.nextNode, TestPipelineNodeDef::VisitStep::eExecute, executor->getDynamicGraph());
}
// this was the last dynamic call into the node
if (nodeData.visitCount >= info.nextNode->getParents().size() && nodeData.dynamicUpstreamCount == dynamicVisit)
{
Status status = pipelineNodeDef->generate(
currentTask, info.nextNode, TestPipelineNodeDef::VisitStep::ePostExecute, executor->getDynamicGraph());
if (status == Status::eSuccess /*DYNAMIC*/)
{
ExecutionTask newTask(info.getContext(), info.nextNode, info.getUpstreamPath());
(void)executor->continueExecute(newTask);
}
}
// Kick dynamic work
for (auto& pair : nodeData.generatedNodes)
{
DynamicNode& dynNode = pair.second;
if (dynNode.trySchedule())
{
ExecutionTask newTask = dynNode.task();
info.schedule(std::move(newTask));
}
}
return Status::eUnknown;
## Customizing Scheduler
The default `ExecutorFallback`'s scheduler will run all the generated tasks serially on a calling thread. We can easily change that and request task dispatch from a custom scheduler.
### Listing 34
A custom scheduler dispatch implementation to run all generated tasks concurrently.
```cpp
struct TestTbbScheduler
{
tbb::task_group g;
TestTbbScheduler(IExecutionContext* context)
{
}
~TestTbbScheduler() noexcept
{
}
template<typename Fn>
Status schedule(Fn&& task, SchedulingInfo)
{
g.run(
[task = captureScheduleFunction(task), this]() mutable
{
Status ret = invokeScheduleFunction(task);
Status current, newValue = Status::eUnknown;
do // LCOV_EXCL_LINE
{
current = this->m_status.load();
newValue = ret | current;
} while (!this->m_status.compare_exchange_weak(current, newValue));
});
return Status::eSuccess;
}
Status getStatus()
{
g.wait();
return m_status;
}
private:
std::atomic<Status> m_status{ Status::eUnknown };
};
```
## Customizing Traversal
In all examples above, the executor was iterating over all children of a node and was able to stop dispatching the node to compute. We can further customize the continuation loop over children of a node by overriding the `Executor::continueExecute(const ExecutionTask&)` method. This ultimately allows us to change entire traversal behavior. In this final example, we will push this to the end by also customizing `IExecutor::execute()` and delegating the entire execution to the implementation of `NodeDef`.
```
We will use Behavior Tree to illustrate it all. Make sure to follow examples from Definition Creation to learn how NodeGraphDef were implemented.
```cpp
// Listing 35: A custom executor for behavior tree.
using BaseExecutorClass = Executor<Node, BtVisit, BtNodeData, SerialScheduler, DefaultSchedulingStrategy>;
class BtExecutor : public BaseExecutorClass
{
public:
//! Factory method
static omni::core::ObjectPtr<BtExecutor> create(omni::core::ObjectParam<ITopology> toExecute, const ExecutionTask& thisTask)
{
return omni::core::steal(new BtExecutor(toExecute.get(), thisTask));
}
//! Custom execute method to bypass continuation and start visitation directly.
//! Propagate the behavior tree status to node instantiating NodeGraphDef this executor operate on. This enables
//! composability of behavior trees.
Status execute_abi() noexcept override
{
auto& instantiatingNodeState = BtNodeState::forceGet(m_task.getContext()->getStateInfo(m_path));
instantiatingNodeState.computeStatus = BtNodeState::Status::eSuccess;
for (auto child : m_task.getNode()->getChildren())
{
if (BtVisit::tryVisit(Info(this, m_task, child)) == Status::eFailure)
{
instantiatingNodeState.computeStatus = BtNodeState::Status::eFailure;
break;
}
}
return Status::eSuccess;
}
//! We don't leverage continuation called from within executed task. Entire traversal logic is handled before
//! from within NodeDef execution method. See nodes implementing @p BtNodeDefBase.
Status continueExecute_abi(ExecutionTask* currentTask) noexcept override
{
return currentTask->getExecutionStatus();
}
protected:
BtExecutor(ITopology* toExecute, const ExecutionTask& currentTask) noexcept
}
```
```cpp
class BaseExecutorClass(toExecute, currentTask)
{
}
;
```
```cpp
struct BtVisit
{
template <typename ExecutorInfo>
static Status tryVisit(ExecutorInfo info) noexcept
{
// Illustrate that we can still leverage pre-allocated data to avoid potential cycles.
// FWIW. They can as well be detected earlier in the pipeline.
auto& nodeData = info.getNodeData();
if (std::exchange(nodeData.executed, true))
{
return Status::eFailure; // LCOV_EXCL_LINE
}
// We don't engage the scheduler because there should be only single node under root...if not but we could get
// all the independent branches executed concurrently when going via scheduler.
ExecutionTask newTask(info.getContext(), info.nextNode, info.getUpstreamPath());
if (newTask.execute(info.getExecutor()) == Status::eSuccess)
{
auto& nodeState = BtNodeState::forceGet(&newTask);
return (nodeState.computeStatus == BtNodeState::Status::eSuccess) ? Status::eSuccess : Status::eFailure;
}
return Status::eFailure; // LCOV_EXCL_LINE
}
};
```
```cpp
class BtSequenceNodeDef : public BtNodeDefBase
{
public:
//! Factory method
static omni::core::ObjectPtr<BtSequenceNodeDef> create()
{
return omni::core::steal(new BtSequenceNodeDef());
}
protected:
//! Specialized composition method for sequence behavior. We don't engage scheduler since all work needs to happen
//! during the call and scheduler would only add overhead in here.
Status execute_abi(ExecutionTask* info) noexcept override
{
auto& nodeState = BtNodeState::forceGet(info);
}
};
```
nodeState.computeStatus = BtNodeState::Status::eSuccess;
for (auto child : info->getNode()->getChildren())
{
ExecutionTask newTask(info->getContext(), child, info->getUpstreamPath());
newTask.execute(getCurrentExecutor()); // bypass scheduler
if (BtNodeState::forceGet(&newTask).computeStatus == BtNodeState::Status::eFailure)
{
nodeState.computeStatus = BtNodeState::Status::eFailure;
break;
}
}
return Status::eSuccess;
}
//! Constructor
BtSequenceNodeDef() noexcept : BtNodeDefBase("tests.def.BtSequenceNodeDef")
{
}
}; | 12,375 |
explore-community-extensions_app_from_scratch.md | # Develop a Simple App
This section provides an introduction to Application development and presents important foundational knowledge:
- How Applications and Extensions are defined in `.kit` and `.toml` files.
- How to explore existing Extensions and adding them to your Application.
- How user settings can override Application configurations.
- Controlling Application window layout.
## Kit and Toml Files
If you have developed solutions before you are likely to have used configuration files. Configuration files present developers with a “low-code” approach to changing behaviors. With Kit SDK you will use configuration files to declare:
- Package metadata
- Dependencies
- Settings
Kit allows Applications and Services to be configured via `.kit` files and Extensions via `.toml` files. Both files present the same ease of readability and purpose of defining a configuration - they simply have different file Extensions.
Let’s create a `.kit` file and register it with the build system:
1. Create a Kit file:
1. Create a file named `my_company.my_app.kit` in `.\source\apps`.
2. Add this content to the file:
```toml
[package]
title = "My App"
description = "An Application created from a tutorial."
version = "2023.0.0"
[dependencies]
"omni.kit.uiapp" = {}
[settings]
app.window.title = "My App"
[[test]]
args = [
"--/app/window/title=My Test App",
]
```
2. Configure the build tool to recognize the new Application:
1. Open `.\premake5.lua`.
2. Find the section `-- Apps:`.
3. Add an entry for the new app:
- Define the application:
```plaintext
define_app("my_company.my_app")
```
- Run the `build` command.
- Start the app:
- Windows:
```plaintext
.\_build\windows-x86_64\release\my_company.my_app.bat
```
- Linux:
```plaintext
./_build/linux-x86_64/release/my_company.my_app.sh
```
- Congratulations, you have created an Application!
- Let’s review the sections of `.kit` and `.toml` files:
### Package
This section provides information used for publishing and displaying information about the Application/Extension. For example, `version = "2023.0.0"` is used both in publishing and UI: a publishing process can alert a developer that the given version has already been published and the version can be shown in an “About Window” and the Extension Manager.
### Dependencies
Dependencies section is a list of Extensions used by the Application/Extension. The above reference `"omni.kit.uiapp" = {}` points to the most recent version available but can be configured to use specific versions. Example of an Extension referenced by a specific version:
```toml
"omni.kit.converter.cad" = {version = "200.1", exact = true}
```
The dependencies can be hosted in Extension Registries for on-demand download or in various locations on the local workstation - including inside a project like kit-app-template.
### Settings
Settings provide a low-code mechanism to customize Application/Extension behavior. Some settings modify UI and others modify functionality - it all depends on how an Application/Extension makes use of the setting. An Omniverse developer should consider exposing settings to developers - and end users - to make Extensions as modular as possible.
#### Experiment
Change the title to `My Company App` - `app.window.title = "My Company App"` - and run the app again - still, no build required. Note the Application title bar shows the new name.
### Test
The test section can be thought of as a combined dependencies and settings section. It allows adding dependencies and settings for when running an Application and Extension in test mode.
```toml
[[test]]
args = [
"--/app/window/title=My Test App",
]
```
We will cover this in greater detail later.
Note:
- Reference: Testing Extensions with Python.
- Reference: .kit and .toml configurations.
```
## Extension Manager
The Extension Manager window is a tool for developers to explore Extensions created on the Omniverse platform. It lists Extensions created by NVIDIA, the Omniverse community, and can be configured to list Extensions that exist on a local workstation. Let’s add the Extension Manager to the app so we can look for dependencies to add.
1. Add Extension Manager.
- Open `.\source\apps\my_company.my_app.kit`.
- Add dependency `omni.kit.window.extensions`. Dependencies section should read:
```toml
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.window.extensions" = {}
```
- In order to point the Extension Manager to the right Extension Registry we need to add the following settings:
```toml
# Extension Registries
[settings.exts."omni.kit.registry.nucleus"]
registries = [
{ name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" },
{ name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" },
]
```
- Observe that - once you save the source kit file - the corresponding kit file in the build directory was updated as well. This is due to the use of symlinks. A build is not necessary when editing .kit files. See:
- Windows: `.\_build\windows-x86_64\release\apps\my_company.my_app.kit`
- Linux: `./_build/linux-x86_64/release/apps/my_company.my_app.kit`
2. Explore Extensions in Extension Manager.
- Start the app:
- Windows: `.\_build\windows-x86_64\release\my_company.my_app.bat`
- Linux: `./_build/linux-x86_64/release/my_company.my_app.sh`
- Open Extension Manager: Window > Extensions.
- Please allow Extension Manager to sync with the Extension Registry. The listing might not load instantly.
- Search for `graph editor example`. The Extension Manager should list `omni.kit.graph.editor.example` in the NVIDIA tab.
- Click `INSTALL`.
- Click the toggle `DISABLED` to enable Extension.
- Check `AUTOLOAD`.
- Close the app and start again.
- Observe that the *Graph Editor Example* Extension is enabled. Look at the `[dependencies]` section in `.\source\apps\my_company.my_app.kit`. The `omni.kit.graph.editor.example` Extension is not listed. The point here is to make it clear that when an Extension is enabled by a user in the Extension Manager, the dependency is **NOT** added to the Application `.kit`.
{ name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" },
{ name = "kit/community", url = "https://dw290v42wisod.cloudfront.net/exts/kit/community" },
]
### Restart the app and allow Extension Manager to sync with the Extension Registry. The listing might not load instantly.
You can now experiment by adding community Extensions such as
"heavyai.ui.component" = {}
```
to the
```
[dependencies]
```
section.
### Add Extensions
#### Let’s assume we found a few Extensions we want to use. Add the below
```
[dependencies]
"omni.kit.uiapp" = {}
# Viewport
"omni.kit.viewport.bundle" = {}
# Render Settings
"omni.rtx.window.settings" = {}
# Content Browser
"omni.kit.window.content_browser" = {}
# Stage Inspector
"omni.kit.window.stage" = {}
# Layer Inspector
"omni.kit.widget.layers" = {}
# Toolbar. Setting load order so that it loads last.
"omni.kit.window.toolbar" = { order = 1000 }
# Properties Inspector
"omni.kit.property.bundle" = {}
# DX shader caches (windows only)
[dependencies."filter:platform"."windows-x86_64"]
"omni.rtx.shadercache.d3d12" = {}
```
#### Add this setting:
```
app.content.emptyStageOnStart = true
```
#### Run the app again. It’ll look something like this:
### Application Layout
The Application window layout is fairly organized already but let’s take care of the floating Content Browser by docking it below the viewport window.
#### Add a Resource Extension
Extensions do not need to provide code. We use so-called “resource Extensions” to provide assets, data, and anything else that can be considered a resource. In this example we create it to provide a layout file.
1. Create a new Extension using
```
repo template new
```
command (command cheat-sheet).
1. For `What do you want to add` choose `extension`.
2. For `Choose a template` choose `python-extension-simple`.
3. Enter an all new name: `my_company.my_app.resources`. Do
1. Do not use the default name.
2. Leave version as `0.1.0`.
3. The new Extension is created in `.\source\extensions\my_company.my_app.resources`.
4. Add a `layouts` directory inside `my_company.my_app.resources`. We’ll be adding a resource file here momentarily.
5. Configure the build to pick up the `layouts` directory by adding a `{ "layouts", ext.target_dir.."/layouts" },` in the Extension’s `.\my_company.my_app.resources\premake5.lua` file:
```lua
-- Use folder name to build Extension name and tag. Version is specified explicitly.
local ext = get_current_extension_info()
-- That will also link whole current "target" folder into as extension target folder:
project_ext(ext)
repo_build.prebuild_link {
{ "data", ext.target_dir.."/data" },
{ "docs", ext.target_dir.."/docs" },
{ "layouts", ext.target_dir.."/layouts" },
{ "my_company", ext.target_dir.."/my_company" },
}
```
## Configure App to Recognize Extensions
By default, Extensions that are part of the Kit SDK will be recognized by Applications. When we add Extensions like the one above we need to add paths to the Application’s .kit file. The below adds the paths for these additional Extensions. Note the use of `${app}` as a token. This will be replaced with the path to the app at runtime.
Add this to the `my_company_my_app.kit`:
```toml
[settings.app.exts]
# Add additional search paths for dependencies.
folders.'++' = [ "${app}/../exts", "${app}/../extscache/" ]
```
**Note**
Reference: [Tokens](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/tokens.html)
## Configure App to Provide Layout Capabilities
Add these Extensions to the `my_company_my_app.kit` `[dependencies]` section. `omni.app.setup` provides layout capabilities.
```toml
# Layout capabilities
"omni.app.setup" = {}
# App resources
"my_company.my_app.resources" = {}
```
## Create a Layout File
1. Run a build to propagate the new Extension to the built solution and start the app.
2. Drag and drop the `Content Browser` on top of the lower docker manipulator within the `Viewport` window.
3. Save the layout:
- Use menu `Window` > `Layout` > `Save Layout...` command.
- Save the layout as `.\source\extensions\my_company.my_app.resources\layouts\layout.json`.
## Use Layout
1. Add this to the `my_company.my_app.kit` files `[settings]` section. Again, here we are using a token: `${my_company.my_app.resources}`. That token is replaced with the path to the Extension at runtime:
```toml
app.kit.editor.setup = true
app.layout.default = "${my_company.my_app.resources}/layouts/layout.json"
```
2. Run a build so the `layouts` directory with its `layout.json` file is created in the `_build` directory structure.
3. Run the Application again and see the `Content Browser` being docked.
A developer can provide end users with different layouts - or `workflows`. This topic can be further explored in the omni.app.setup reference.
You now have an Application and could skip ahead to the [Package App](#) and [Publish App](#) sections; however, this tutorial now continues with a more advanced example: [Develop a USD Explorer App](#). | 11,511 |
export-handler_Overview.md | # Overview — Omniverse Kit 1.0.30 documentation
## Overview
The file_exporter extension provides a standardized dialog for exporting files. It is a wrapper around the `FilePickerDialog`, but with reasonable defaults for common settings, so it’s a higher-level entry point to that interface. Nevertheless, users will still have the ability to customize some parts but we’ve boiled them down to just the essential ones.
Why you should use this extension:
- Present a consistent file export experience across the app.
- Customize only the essential parts while inheriting sensible defaults elsewhere.
- Reduce boilerplate code.
- Inherit future improvements.
- Checkpoints fully supported if available on the server.
## Quickstart
You can pop-up a dialog in just 2 steps. First, retrieve the extension.
```python
# Get the singleton extension object, but as weakref to guard against the extension being removed.
file_exporter = get_file_exporter()
if not file_exporter:
return
```
Then, invoke its show_window method.
```python
file_exporter.show_window(
title="Export As ...",
export_button_label="Save",
export_handler=self.export_handler,
filename_url="omniverse://ov-rc/NVIDIA/Samples/Marbles/foo",
show_only_folders=True,
enable_filename_input=False,
)
```
Note that the extension is a singleton, meaning there’s only one instance of it throughout the app. Basically, we are assuming that you’d never open more than one instance of the dialog at any one time. The advantage is that we can channel any development through this single extension and all users will inherit the same changes.
## Customizing the Dialog
You can customize these parts of the dialog.
- Title - The title of the dialog.
- Collections - Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
- Filename Url - Url to open the dialog with.
- Postfix options - List of content labels appended to the filename.
- Extension options - List of filename extensions.
- Export options - Options to apply during the export process.
- Export label - Label for the export button.
- Export handler - User provided callback to handle the export process.
Note that these settings are applied when you show the window. Therefore, each time it’s displayed, the dialog can be tailored
## Filename postfix options
Users might want to set up data libraries of just animations, materials, etc. However, one challenge of working in Omniverse is that everything is a USD file. To facilitate this workflow, we suggest adding a postfix to the filename, e.g. “file.animation.usd”. The file bar contains a dropdown that lists the postfix labels. A default list is provided but you can also provide your own.
```python
DEFAULT_FILE_POSTFIX_OPTIONS = [
None,
"anim",
"cache",
"curveanim",
"geo",
"material",
"project",
"seq",
"skel",
"skelanim",
]
```
A list of file extensions, furthermore, allows the user to specify what flavor of USD to export.
```python
DEFAULT_FILE_EXTENSION_TYPES = [
("*.usd", "Can be Binary or Ascii"),
("*.usda", "Human-readable text format"),
("*.usdc", "Binary format"),
]
```
When the user selects a combination of postfix and extension types, the file view will filter out all other file types, leaving only the matching ones.
## Export options
A common need is to provide user options for the export process. You create the widget for accepting those inputs, then add it to the details pane of the dialog. Do this by subclassing from `ExportOptionsDelegate` and overriding the methods, :meth:`ExportOptionsDelegate._build_ui_impl` and (optionally) :meth:`ExportOptionsDelegate._destroy_impl`.
```python
class MyExportOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl)
self._widget = None
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(style={"background_color": 0xFF23211F}):
ui.Label("Checkpoint Description", alignment=ui.Alignment.CENTER)
ui.Separator(height=5)
model = ui.StringField(multiline=True, height=80).model
model.set_value("This is my new checkpoint.")
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
```
Then provide the controller to the file picker for display.
```python
self._export_options = MyExportOptionsDelegate()
file_exporter.add_export_options_frame("Export Options", self._export_options)
```
## Export handler
Provide a handler for when the Export button is clicked. In addition to :attr:`filename` and :attr:`dirname`, the handler should expect a list of :attr:`selections` made from the UI.
```python
def export_handler(self, filename: str, dirname: str, extension: str = "", selections: List[str] = []):
```
# NOTE: Get user inputs from self._export_options, if needed.
```
```python
print(f"> Export As '{filename}{extension}' to '{dirname}' with additional selections '{selections}'")
```
## Demo app
A complete demo, that includes the code snippets above, is included with this extension.
```
--- | 5,255 |
ext-omni-graph-action_Overview.md | # Overview
## Extension
: omni.graph.action-1.101.1
## Documentation Generated
: Apr 26, 2024
## Changelog
# Overview
This extension is a bundle of **omni.graph.action_core** and **omni.graph.action_nodes**, which is the core functionality of OmniGraph Action Graph. | 271 |
ext-omni-graph-template-cpp_Overview.md | # Overview
This is the gold standard template for creating a Kit extension that contains only C++ OmniGraph nodes.
## The Files
To use this template first copy the entire directory into a location that is visible to your build, such as `source/extensions`. The copy will have this directory structure. The highlighted lines should be renamed to match your extension, or removed if you do not want to use them.
```text
omni.graph.template.cpp/
config/
extension.toml
data/
icon.svg
preview.png
docs/
CHANGELOG.md
directory.txt
Overview.md
README.md
nodes/
OgnTemplateNodeCpp.cpp
OgnTemplateNodeCpp.ogn
plugins/
Module.cpp
premake5.lua
```
## The Build File
Kit normally uses premake for building so this example shows how to use the template `premake5.lua` file to customize your build. By default the build file is set up to correspond to the directory structure shown above. By using this standard layout the utility functions can do most of the work for you.
```lua
-- --------------------------------------------------------------------------------------------------------------------
-- Build file for the build tools used by the OmniGraph C++ extension. These are tools required in order to
-- run the build on that extension, and all extensions dependent on it.
-- --------------------------------------------------------------------------------------------------------------------
-- This sets up a shared extension configuration, used by most Kit extensions.
local ext = get_current_extension_info()
-- --------------------------------------------------------------------------------------------------------------------
-- Set up a variable containing standard configuration information for projects containing OGN files
local ogn = get_ogn_project_information(ext, "omni/graph/template/cpp")
-- --------------------------------------------------------------------------------------------------------------------
-- Put this project into the "omnigraph" IDE group
ext.group = "omnigraph"
-- --------------------------------------------------------------------------------------------------------------------
-- Set up the basic shared project information first
project_ext( ext )
-- --------------------------------------------------------------------------------------------------------------------
-- Define a build project to process the ogn files to create the generated code that will be used by the node
23 -- implementations. The (optional) "toc" value points to the directory where the table of contents with the OmniGraph
24 -- nodes in this extension will be generated. Omit it if you will be generating your own table of contents.
25 project_ext_ogn( ext, ogn, { toc="docs/Overview.md" } )
26
27 -- --------------------------------------------------------------------------------------------------------------------
28 -- The main plugin project is what implements the nodes and extension interface
29 project_ext_plugin( ext, ogn.plugin_project )
30 -- These lines add the files in the project to the IDE where the first argument is the group and the second
31 -- is the set of files in the source tree that are populated into that group.
32 add_files("impl", ogn.plugin_path)
33 add_files("nodes", ogn.nodes_path)
34 add_files("config", "config")
35 add_files("docs", ogn.docs_path)
36 add_files("data", "data")
37
38 -- Add the standard dependencies all OGN projects have. The second parameter is normally omitted for C++ nodes
39 -- as hot reload of C++ definitions is not yet supported.
40 add_ogn_dependencies(ogn)
41
42 -- Link the directories required to make the extension definition complete
43 repo_build.prebuild_link {
44 { "docs", ext.target_dir.."/docs" },
45 { "data", ext.target_dir.."/data" },
46 }
47
48 -- This optional line adds support for CUDA (.cu) files in your project. Only include it if you are building nodes
49 -- that will run on the GPU and implement CUDA code to do so. Your deps/ directory should contain a file with a
50 -- cuda dependency that looks like the following to access the cuda library:
51 -- <dependency name="cuda" linkPath="../_build/target-deps/cuda">
52 -- <package name="cuda" version="11.8.0_520.61-d8963068-${platform}" platforms="linux-x86_64"/>
53 -- <package name="cuda" version="11.8.0_520.61-abe3d9d7-${platform}" platforms="linux-aarch64"/>
54 -- <package name="cuda" version="11.8.0_522.06-abe3d9d7-${platform}" platforms="windows-x86_64"/>
55 -- </dependency>
56 -- add_cuda_build_support()
57
58 -- --------------------------------------------------------------------------------------------------------------------
59 -- With the above copy/link operations this is what the source and build trees will look like
60 --
61 -- SOURCE BUILD
62 -- omni.graph.template.cpp/ omni.graph.template.cpp/
63 -- config/ config@ -> SOURCE/config
64 -- data/ data@ -> SOURCE/data
65 -- docs/ docs@ -> SOURCE/docs
66 -- nodes/ ogn/ (generated by build)
67 -- plugins/
```
Normally your nodes will have tests automatically generated for them, which will be in Python even though the nodes are in C++. By convention the installed Python files are structured in a directory tree that matches a namespace corresponding to the extension name, in this case `omni/graph/template/cpp/`, which corresponds to the extension name *omni.graph.template.cpp*. You’ll want to modify this to match your own extension’s name. Changing the first highlighted line is all you have to do to make that happen.
### The Configuration
Every extension requires a `config/extension.toml` file with metadata describing the extension to the extension management system. Below is the annotated version of this file, where the highlighted lines are the ones you should change to match your own extension.
```toml
# Main extension description values
[package]
# The current extension version number - uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
version = "2.3.1"
# The title of the extension that will appear in the extension window
title = "OmniGraph C++ Template"
# Longer description of the extension
description = "Templates for setting up an extension containing only C++ OmniGraph nodes."
# Authors/owners of the extension - usually an email by convention
authors = ["NVIDIA <no-reply@nvidia.com>"]
```
# Category under which the extension will be organized
category = "Graph"
# Location of the main README file describing the extension for extension developers
readme = "docs/README.md"
# Location of the main CHANGELOG file describing the modifications made to the extension during development
changelog = "docs/CHANGELOG.md"
# Location of the repository in which the extension's source can be found
repository = "kit-omnigraph"
# Keywords to help identify the extension when searching
keywords = ["kit", "omnigraph", "nodes", "cpp", "c++"]
# Image that shows up in the preview pane of the extension window
preview_image = "data/preview.png"
# Image that shows up in the navigation pane of the extension window - can be a .png, .jpg, or .svg
icon = "data/icon.svg"
# Specifying this ensures that the extension is always published for the matching version of the Kit SDK
writeTarget.kit = true
# Specify the minimum level for support
support_level = "Enterprise"
# Other extensions that need to load in order for this one to work
[dependencies]
"omni.graph.core" = {} # For basic functionality
"omni.graph.tools" = {} # For node generation
# This extension has a compiled C++ project and so requires this declaration that it exists
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
# Main pages published as part of documentation. (Only if you build and publish your documentation.)
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
# Contained in this file are references to the icon file in
# data/icon.svg
# and the preview image in
# data/preview.png
# which control how your extension appears in the extension manager. You will want to customize those.
# The Plugin Module
## The Plugin Module
Every C++ extension requires some standard code setup to register and deregister the node types at the proper time. The minimum requirements for the Carbonite wrappers that implement this are contained in the file plugins/Module.cpp.
```cpp
// Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// ==============================================================================================================
//
// This file contains mostly boilerplate code required to register the extension and the nodes in it.
//
// See the full documentation for OmniGraph Native Interfaces online at
// https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/docs/OmniverseNativeInterfaces.html
//
// ==============================================================================================================
#include <omni/core/ModuleInfo.h>
#include <omni/core/Omni.h>
#include <omni/graph/core/ogn/Registration.h>
// These are the most common interfaces that will be used by nodes. Others that are used within the extension but
```
```c++
// not registered here will issue a warning and can be added.
OMNI_PLUGIN_IMPL_DEPS(omni::graph::core::IGraphRegistry, omni::fabric::IToken)
// OMNI_MODULE_GLOBALS("omni.graph.template.cpp.plugin", "OmniGraph Template With C++ Nodes");
// This declaration is required in order for registration of C++ OmniGraph nodes to work
// DECLARE_OGN_NODES();
namespace
{
void onStarted()
{
// Macro required to register all of the C++ OmniGraph nodes in the extension
// INITIALIZE_OGN_NODES();
}
bool onCanUnload()
{
return true;
}
void onUnload()
{
// Macro required to deregister all of the C++ OmniGraph nodes in the extension
// RELEASE_OGN_NODES();
}
} // end of anonymous namespace
// Hook up the above functions to the module to be called at the right times
OMNI_MODULE_API omni::Result omniModuleGetExports(omni::ModuleExports* exports)
{
OMNI_MODULE_SET_EXPORTS(exports);
OMNI_MODULE_ON_MODULE_STARTED(exports, onStarted);
OMNI_MODULE_ON_MODULE_CAN_UNLOAD(exports, onCanUnload);
OMNI_MODULE_ON_MODULE_UNLOAD(exports, onUnload);
OMNI_MODULE_GET_MODULE_DEPENDENCIES(exports, omniGetDependencies);
return omni::core::kResultSuccess;
}
```
The first highlighted line shows where you customize the extension plugin name to match your own. The others indicate standard macros that set up the OmniGraph node type registration and deregistration process. Without these lines your node types will not be known to OmniGraph and will not be available in any of the editors.
## Documentation
Everything in the `docs/` subdirectory is considered documentation for the extension.
- **README.md**
The contents of this file appear in the extension manager window so you will want to customize it. The location of this file is configured in the `extension.toml` file as the **readme** value.
- **CHANGELOG.md**
It is good practice to keep track of changes to your extension so that users know what is available. The location of this file is configured in the `extension.toml` file as the **changelog** value, and as an entry in the [documentation] pages.
- **Overview.md**
This contains the main documentation page for the extension. It can stand alone or reference an arbitrarily complex set of files, images, and videos that document use of the extension. The **toctree** reference at the bottom of the file contains at least `GeneratedNodeDocumentation/`, which creates links to all of the documentation that is automatically generated for your nodes. The location of this file is configured in the `extension.toml` file in the [documentation] pages section.
- **directory.txt**
This file can be deleted as it is specific to these instructions.
## The Node Type Definitions
You define a new node type using two files, examples of which are in the `nodes/` directory.
subdirectory. Tailor the
definition of your node types for your computations. Start with the OmniGraph User Guide for information on how
to configure your own definitions.
That’s all there is to creating a simple C++ node type! You can now open your app, enable the new extension, and your
sample node type will be available to use within OmniGraph.
OmniGraph Nodes In This Extension
* C++ Template Node | 13,206 |
ext-omni-graph-template-python_Overview.md | # Overview
## Extension
: omni.graph.template.python-1.3.1
## Documentation Generated
: Apr 26, 2024
## Changelog
This is the gold standard template for creating a Kit extension that contains only Python OmniGraph nodes.
## The Files
To use this template first copy the entire directory into a location that is visible to your build, such as `source/extensions`. The copy will have this directory structure. The highlighted lines should be renamed to match your extension, or removed if you do not want to use them.
```text
omni.graph.template.python/
config/
extension.toml
data/
icon.svg
preview.png
docs/
CHANGELOG.md
directory.txt
Overview.md
README.md
premake5.lua
python/
__init__.py
_impl/
__init__.py
extension.py
nodes/
OgnTemplateNodePy.ogn
OgnTemplateNodePy.py
tests/
__init__.py
test_api.py
test_omni_graph_template_python.py
```
The convention of having implementation details of a module in the `_impl/` subdirectory is to make it clear to the user that they should not be directly accessing anything in that directory, only what is exposed in the `__init__.py`.
## The Build File
Kit normally uses premake for building so this example shows how to use the template `premake5.lua` file to customize your build. By default the build file is set up to correspond to the directory structure shown above. By using this standard layout the utility functions can do most of the work for you.
```lua
-- --------------------------------------------------------------------------------------------------------------------
-- Build file for the build tools used by the OmniGraph Python template extension. These are tools required in order to
-- run the build on that extension, and all extensions dependent on it.
-- --------------------------------------------------------------------------------------------------------------------
-- This sets up a shared extension configuration, used by most Kit extensions.
local ext = get_current_extension_info()
-- --------------------------------------------------------------------------------------------------------------------
-- Set up a variable containing standard configuration information for projects containing OGN files.
-- The string corresponds to the Python module name, in this case omni.graph.template.python.
local ogn = get_ogn_project_information(ext, "omni/graph/template/python")
-- --------------------------------------------------------------------------------------------------------------------
```
15 -- Put this project into the "omnigraph" IDE group. You might choose a different name for convenience.
16 ext.group = "omnigraph"
17
18 -- --------------------------------------------------------------------------------------------------------------------
19 -- Define a build project to process the ogn files to create the generated code that will be used by the node
20 -- implementations. The (optional) "toc" value points to the directory where the table of contents with the OmniGraph
21 -- nodes in this extension will be generated. Omit it if you will be generating your own table of contents.
22 project_ext_ogn( ext, ogn, { toc="docs/Overview.md" })
23
24 -- --------------------------------------------------------------------------------------------------------------------
25 -- Build project responsible for generating the Python nodes and installing them and any scripts into the build tree.
26 project_ext( ext, { generate_ext_project=true })
27
28 -- These lines add the files in the project to the IDE where the first argument is the group and the second
29 -- is the set of files in the source tree that are populated into that group.
30 add_files("python", "*.py")
31 add_files("python/_impl", "python/_impl/**.py")
32 add_files("python/nodes", "python/nodes")
33 add_files("python/tests", "python/tests")
34 add_files("docs", "docs")
35 add_files("data", "data")
36
37 -- Add the standard dependencies all OGN projects have. The second parameter is a table of all directories
38 -- containing Python nodes. Here there is only one.
39 add_ogn_dependencies(ogn, { "python/nodes" })
40
41 -- Copy the init script directly into the build tree. This is required because the build will create an ogn/
42 -- subdirectory in the Python module so only the subdirectories can be linked.
43 repo_build.prebuild_copy {
44 { "python/__init__.py", ogn.python_target_path },
45 }
46
47 -- Linking directories allows them to hot reload when files are modified in the source tree.
48 -- Docs are linked to get the README into the extension window.
49 -- Data contains the images used by the extension configuration preview.
50 -- The "nodes/" directory does not have to be mentioned here as it will be handled by add_ogn_dependencies() above.
51 repo_build.prebuild_link {
52 { "docs", ext.target_dir.."/docs" },
53 { "data", ext.target_dir.."/data" },
54 { "python/tests", ogn.python_tests_target_path },
55 { "python/_impl", ogn.python_target_path.."/_impl" },
56 }
57
58 -- With the above copy/link operations this is what the source and build trees will look like
59 --
60 -- SOURCE BUILD
61 -- omni.graph.template.python/ omni.graph.template.python/
62 -- config/ config@ -> SOURCE/config
63 -- data/ data@ -> SOURCE/data
64 -- docs/ docs@ -> SOURCE/docs
65 -- python/ ogn/ (generated by the build)
66 -- __init__.py omni/
67 -- _impl/ graph/
68 -- nodes/ template/
69 -- python/
70 -- __init__.py (copied from SOURCE/python)
71 -- _impl@ -> SOURCE/python/_impl
72 -- nodes@ -> SOURCE/python/nodes
73 -- tests@ -> SOURCE/python/tests
74 -- ogn/ (Generated by the build)
```
By convention the installed Python files are structured in a directory tree that matches a namespace corresponding to
the extension name, in this case
```
omni/graph/template/python/
```
, which corresponds to the extension name
**omni.graph.template.python**. You’ll want to modify this to match your own extension’s name. Changing the first
highlighted line is all you have to do to make that happen.
## The Configuration
Every extension requires a
```toml
# Main extension description values
[package]
# The current extension version number - uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
version = "1.3.1"
# The title of the extension that will appear in the extension window
title = "OmniGraph Python Template"
# Longer description of the extension
description = "Templates for setting up an extension containing OmniGraph Python nodes only (no C++)."
# Authors/owners of the extension - usually an email by convention
authors = ["NVIDIA <no-reply@nvidia.com>"]
# Category under which the extension will be organized
category = "Graph"
# Location of the main README file describing the extension for extension developers
readme = "docs/README.md"
# Location of the main CHANGELOG file describing the modifications made to the extension during development
changelog = "docs/CHANGELOG.md"
# Location of the repository in which the extension's source can be found
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-omnigraph"
# Keywords to help identify the extension when searching
keywords = ["kit", "omnigraph", "nodes", "python"]
# Image that shows up in the preview pane of the extension window
preview_image = "data/preview.png"
# Image that shows up in the navigation pane of the extension window - can be a .png, .jpg, or .svg
icon = "data/icon.svg"
# Specifying this ensures that the extension is always published for the matching version of the Kit SDK
writeTarget.kit = true
# Specify the minimum level for support
support_level = "Enterprise"
# Main module for the Python interface. This is how the module will be imported.
[[python.module]]
name = "omni.graph.template.python"
# Watch the .ogn files for hot reloading. Only useful during development as after delivery files cannot be changed.
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions that need to load in order for this one to work
[dependencies]
"omni.graph" = {} # For basic functionality
"omni.graph.tools" = {} # For node generation
# Main pages published as part of documentation. (Only if you build and publish your documentation.)
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
# Some extensions are only needed when writing tests, including those automatically generated from a .ogn file.
# Having special test-only dependencies lets you avoid introducing a dependency on the test environment when only
# using the functionality.
[[test]]
dependencies = [
"omni.kit.test" # Brings in the Kit testing framework
]
```
This is a file with metadata describing the extension to the extension management system. Below is the annotated version of this file, where the highlighted lines are the ones you should change to match your own extension.
# Documentation
Everything in the `docs/` subdirectory is considered documentation for the extension.
- **README.md**
The contents of this file appear in the extension manager window so you will want to customize it. The location of this file is configured in the `extension.toml` file as the **readme** value.
- **CHANGELOG.md**
It is good practice to keep track of changes to your extension so that users know what is available. The location of this file is configured in the `extension.toml` file as the **changelog** value, and as an entry in the `[documentation]` pages.
- **Overview.md**
This contains the main documentation page for the extension. It can stand alone or reference an arbitrarily complex set of files, images, and videos that document use of the extension. The **toctree** reference at the bottom of the file contains at least `GeneratedNodeDocumentation/`, which creates links to all of the documentation that is automatically generated for your nodes. The location of this file is configured in the `extension.toml` file in the `[documentation]` pages section.
- **directory.txt**
This file can be deleted as it is specific to these instructions.
# The Node Type Definitions
You define a new node type using two files, examples of which are in the `nodes/` subdirectory. Tailor the definition of your node types for your computations. Start with the OmniGraph User Guide for information on how to configure your own definitions.
# Tests
While completely optional it’s always a good idea to add a few tests for your node to ensure that it works as you intend it and continues to work when you make changes to it. Automated tests will be generated for each of your node type definitions to exercise basic functionality. What you want to write here are more complex tests that use your node types in more complex graphs.
The sample tests in the `tests/` subdirectory show you how you can integrate with the Kit testing framework to easily run tests on nodes built from your node type definition.
That’s all there is to creating a simple Python node type! You can now open your app, enable the new extension, and your sample node type will be available to use within OmniGraph.
## OmniGraph Nodes In This Extension
- Python Template Node | 11,856 |
ext-omni-graph-ui-nodes_Overview.md | # Overview
This extension provides a set of standard ui-related nodes for general use in OmniGraph.
## OmniGraph Nodes In This Extension
- Button (BETA)
- Draw Debug Curve
- Get Active Camera
- Get Camera Position
- Get Camera Target
- Get Viewport Renderer
- Get Viewport Resolution
- Lock Viewport Render
- On New Frame
- On Picked (BETA)
- On Viewport Clicked (BETA)
- On Viewport Dragged (BETA)
- On Viewport Hovered (BETA)
- On Viewport Pressed (BETA)
- On Viewport Scrolled (BETA)
- On Widget Clicked (BETA)
- On Widget Value Changed (BETA)
- Print Text
- Read Mouse State
- Read Pick State (BETA)
- Read Viewport Click State (BETA)
- Read Viewport Drag State (BETA)
- Read Viewport Hover State (BETA)
- Read Viewport PressState (BETA)
- Read Viewport Press State (BETA)
- Read Viewport Scroll State (BETA)
- Set Active Camera
- Set Camera Position
- Set Camera Target
- Set Viewport Fullscreen
- Set Viewport Mode (BETA)
- Set Viewport Renderer
- Set Viewport Resolution
- Slider (BETA) | 996 |
ext-omni-graph-ui_Overview.md | # Overview
## Extension
: omni.graph.ui-1.67.1
## Documentation Generated
: Apr 26, 2024
## Changelog
## Overview
This extension provides basic user interface elements for OmniGraph. | 186 |
ext-omni-graph_Overview.md | # Overview
This extension contains the Python bindings and scripts used by `omni.graph.core`.
## Python API
Automatically generated Python API documentation can be found at `omni.graph.core`.
## Python ABI
ABI bindings are available through these links:
- `omni.graph.core._omni_graph_core.Attribute`
- `omni.graph.core._omni_graph_core.AttributeData`
- `omni.graph.core._omni_graph_core.AttributePortType`
- `omni.graph.core._omni_graph_core.AttributeRole`
- `omni.graph.core._omni_graph_core.AttributeType`
- `omni.graph.core._omni_graph_core.BaseDataType`
- `omni.graph.core._omni_graph_core.BucketId`
- `omni.graph.core._omni_graph_core.ComputeGraph`
- omni.graph.core._omni_graph_core.ConnectionInfo
- omni.graph.core._omni_graph_core.ConnectionType
- omni.graph.core._omni_graph_core.ExecutionAttributeState
- omni.graph.core._omni_graph_core.ExtendedAttributeType
- omni.graph.core._omni_graph_core.FileFormatVersion
- omni.graph.core._omni_graph_core.Graph
- omni.graph.core._omni_graph_core.GraphBackingType
- omni.graph.core._omni_graph_core.GraphContext
- omni.graph.core._omni_graph_core.GraphEvaluationMode
- omni.graph.core._omni_graph_core.GraphEvent
- omni.graph.core._omni_graph_core.GraphPipelineStage
- omni.graph.core._omni_graph_core.GraphRegistry
- omni.graph.core._omni_graph_core.GraphRegistryEvent
- omni.graph.core._omni_graph_core.IBundle2
- omni.graph.core._omni_graph_core.IBundleFactory
- omni.graph.core._omni_graph_core.IBundleFactory2
- omni.graph.core._omni_graph_core.IConstBundle2
- omni.graph.core._omni_graph_core.INodeCategories
- omni.graph.core._omni_graph_core.ISchedulingHints
- omni.graph.core._omni_graph_core.IVariable
- omni.graph.core._omni_graph_core.MemoryType
- **omni.graph.core._omni_graph_core.MemoryType**
- **omni.graph.core._omni_graph_core.Node**
- **omni.graph.core._omni_graph_core.NodeEvent**
- **omni.graph.core._omni_graph_core.NodeType**
- **omni.graph.core._omni_graph_core.OmniGraphBindingError**
- **omni.graph.core._omni_graph_core.PtrToPtrKind**
- **omni.graph.core._omni_graph_core.Severity**
- **omni.graph.core._omni_graph_core.Type**
- **omni.graph.core._omni_graph_core.eAccessLocation**
- **omni.graph.core._omni_graph_core.eAccessType**
- **omni.graph.core._omni_graph_core.eComputeRule**
- **omni.graph.core._omni_graph_core.ePurityStatus**
- **omni.graph.core._omni_graph_core.eThreadSafety**
- **omni.graph.core._omni_graph_core.eVariableScope**
- **AutoNode**
- **Data Types** | 2,463 |
ExtendingOniInterfaces.md | # Extending an Omniverse Native Interface
## Overview
Once released, an Omniverse Native Interface’s ABI may not be changed. This guarantees that any library or plugin that was dependent on a previous version of the interface will always be able to access it even if newer versions of the interface become available later. The implementation of an interface may change, but the interface’s ABI layer itself may not change. A change to an ABI may for instance mean adding a new function, changing the prototype of an existing function, or removing an existing function. None of these may occur on a released version of the interface since that would break released apps that make use of the interface.
If additional functionality is needed in an ONI interface, a new version of the interface can still be added. The new interface may either inherit from the previous version(s) or may be entirely standalone if needed. In cases where it is possible, it is always preferrable to have the new version of the interface inherit from the previous version.
Note that it is possible to add new enum or flag values to an existing interface’s header without breaking the ABI. However, care must still be taken when doing that to ensure that the behavior added by the new flags or enums is both backward and forward compatible and safe. For example, if an older version of the plugin is loaded, will it either fail gracefully or safely ignore any new flag/enum values passed in. Similarly, if a newer version of the plugin is loaded in an app expecting an older version, will the expected behavior still be supported without the new enums or flags being passed in. In general though, adding new flags or enums without adding a new interface version as well should be avoided unless it can be absolutely guaranteed to be safe in all cases.
The process for adding a new version of an ONI interface will be described below. This will extend the example interfaces used in Creating a New Omniverse Native Interface and assumes that document has already been read. This assumes the reader’s familiarity with and extends the examples presented there. More information on ONI can be found in Omniverse Native Interfaces.
If further examples of extending a real ONI interface are needed, `omni::platforminfo::IOsInfo2_abi` (in `include/omni/platforminfo/IOsInfo2.h`) or `omni::structuredlog::IStructuredLogSettings2_abi` (in `include/omni/structuredlog/IStructuredLogSettings2.h`) may be used for reference. In both these cases, the new interface inherits from the previous one.
## Defining the New Interface Version
The main difference between the previous version of an interface and its new version are that should inherit from the previous ABI interface class instead of `omni::core::IObject`. The new interface version must also be declared in its own new C++ header file. The new interface version must also have a different name than the previous version. Adding a version number to the new interface version’s name is generally suggested.
It is always suggested that the implementation of the new version(s) of the interface be added to the same C++ plugin as the previous version(s). This reduces code duplication, internal dependencies, and allows all versions of an interface to be present in a single location.
To extend our `ILunch` interface to be able to ask if the user would like salad with lunch, a new version of the interface would be needed.
the interface could be added to the C++ header
```cpp
include/omni/meals/ILunch2.h
```
as follows:
```cpp
// file 'include/omni/meals/ILunch2.h'
#pragma once
#include "ILunch.h"
namespace omni
{
namespace meals
{
enum class OMNI_ATTR("prefix=e") Dressing
{
eNone,
eRaspberryVinaigrette,
eBalsamicVinaigrette,
eCaesar,
eRanch,
eFrench,
eRussian,
eThousandIsland,
};
// we must always forward declare each interface that will be referenced here.
class ILunch2;
// the interface's name must end in '_abi'.
class ILunch2_abi : public omni::core::Inherits<omni::meals::ILunch, OMNI_TYPE_ID("omni.meals.lunch2")>
{
protected: // all ABI functions must always be 'protected' and must end in '_abi'.
virtual void addGardenSalad_abi(Dressing dressing) noexcept = 0;
virtual void addWedgeSalad_abi(Dressing dressing) noexcept = 0;
virtual void addColeSlaw_abi() noexcept = 0;
};
} // namespace meals
} // namespace omni
// include the generated header and declare the API interface. Note that this must be
// done at the global scope.
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "ILunch2.gen.h"
// this is the API version of the interface that code will call into. Custom members and
// helpers may also be added to this interface API as needed, but this API object may not
// hold any additional data members.
class omni::meals::ILunch2 : public omni::core::Generated<omni::meals::ILunch2_abi>
{
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "ILunch2.gen.h"
```
Once created, this new header also needs to be added to the
```
omnibind
```
call in the premake script. This should be
added to the same interface generator project that previous versions used:
```lua
project "omni.meals.interfaces"
location (workspaceDir.."/%{prj.name}")
omnibind {
{ file="include/omni/meals/IBreakfast.h", api="include/omni/meals/IBreakfast.gen.h", py="source/bindings/python/omni.meals/PyIBreakfast.gen.h" },
{ file="include/omni/meals/ILunch.h", api="include/omni/meals/ILunch.gen.h", py="source/bindings/python/omni.meals/PyILunch.gen.h" },
{ file="include/omni/meals/IDinner.h", api="include/omni/meals/IDinner.gen.h", py="source/bindings/python/omni.meals/PyIDinner.gen.h" },
-- new header(s) added here:
{ file="include/omni/meals/ILunch2.h", api="include/omni/meals/ILunch2.gen.h", py="source/bindings/python/omni.meals/PyILunch2.gen.h" },
}
dependson { "omni.core.interfaces" }
```
Building the interface generator project should then result in the new header files being generated.
## The New Interface’s Python Bindings
The new interface’s python bindings would be added to the python binding project just as they were before. This would simply require including the new generated header and calling the new generated inlined helper function. Note that the above header file will now generate two inlined helper functions in the bindings header. One helper function will add python bindings for the new version of the interface and one will add python bindings for the `Dressing` enum.
### Code Example
```cpp
#include <omni/python/PyBind.h>
#include <omni/meals/IBreakfast.h>
#include <omni/meals/ILunch.h>
#include <omni/meals/ILunch2.h> // <-- include the new API header file.
#include <omni/meals/IDinner.h>
#include "PyIBreakfast.gen.h"
#include "PyILunch.gen.h"
#include "PyILunch2.gen.h" // <-- include the new generated bindings header file.
#include "PyIDinner.gen.h"
OMNI_PYTHON_GLOBALS("omni.meals-pyd", "Python bindings for omni.meals.")
PYBIND11_MODULE(_meals, m)
{
bindIBreakfast(m);
bindILunch(m);
bindIDinner(m);
// call the new generated inlined helper functions.
bindILunch2(m);
bindDressing(m);
}
```
## Implementing the New Interface
In most cases, implementing the new version of the interface is as simple as changing the implementation object from inheriting from the previous version API (ie: `omni::meals::ILunch` in this case) to inheriting from the new version (`omni::meals::ILunch2`) instead, then adding the implementations of the new methods. If the new interface version does not inherit from the previous version, this can still be handled through inheritence in the implementation, but appropriate casting must occur when returning the new version’s object from the creator function.
Once the new version’s implementation is complete, a new entry needs to be added to the plugin’s interface implementation listing object. This object is retrieved by the type factory from the plugin’s `onLoad()` function. To add the new interface, the following simple changes would need to be made:
### Code Example
```cpp
omni::core::Result onLoad(const omni::core::InterfaceImplementation** out, uint32_t* outCount)
{
// clang-format off
static const char* breakfastInterfaces[] = { "omni.meals.IBreakfast" };
static const char* lunchInterfaces[] = { "omni.meals.ILunch", "omni.meals.ILunch2" }; // <-- add new interface name.
static const char* dinnerInterfaces[] = { "omni.meals.IDinner" };
static omni::core::InterfaceImplementation impls[] =
{
{
"omni.meals.breakfast",
[]() { return static_cast<omni::core::IObject*>(new Breakfast); },
1, // version
breakfastInterfaces, CARB_COUNTOF32(breakfastInterfaces)
},
{
"omni.meals.lunch",
// switch this to create the new interface version's object instead. Callers can then
// ...
},
// ...
};
// ...
}
```
// cast between the new and old interface versions as needed.
```cpp
[]() {
return static_cast<omni::core::IObject*>(new Lunch2);
},
1, // version
lunchInterfaces, CARB_COUNTOF32(lunchInterfaces)
{
"omni.meals.dinner",
[]() {
return static_cast<omni::core::IObject*>(new Dinner);
},
1, // version
dinnerInterfaces, CARB_COUNTOF32(dinnerInterfaces)
};
```
Note that the structure of this interface implementation listing object can differ depending on how the implementation
class is structured. For example, if all interfaces in the plugin are implemented as a single class internally where
the class inherits from all interfaces in its
invocation, only a single entry
would be needed for the
listing. This case would look similar to
this:
```cpp
omni::core::Result onLoad(const omni::core::InterfaceImplementation** out, uint32_t* outCount)
{
// clang-format off
static const char* interfacesImplemented[] = {
"omni.meals.ITable",
"omni.meals.IWaiter",
"omni.meals.IKitchenStaff"
};
static omni::core::InterfaceImplementation impls[] =
{
{
"omni.meals.IRestaurant",
[]() -> omni::core::IObject* {
omni::meals::Restaurant* obj = new omni::meals::Restaurant::getInstance();
// cast to `omni::core::IObject` before return to ensure a good base object is given.
return static_cast<omni::core::IObject*>(obj->cast(omni::core::IObject::kTypeId));
},
1, // version
interfacesImplemented, CARB_COUNTOF32(interfacesImplemented)
},
};
// clang-format on
*out = impls;
*outCount = CARB_COUNTOF32(impls);
return omni::core::kResultSuccess;
}
```
```cpp
return omni::core::kResultSuccess;
}
```
When the caller receives this object from `omni::core::createType()`, it will then be able to use `omni::core::IObject::cast()` to convert the returned object to the interface it needs instead of having to explicitly create each interface object provided through the plugin using multiple calls to `omni::core::createType()`. This typically ends up being a better user experience for developers. | 11,285 |
extension-architecture_kit_sdk_overview.md | # Kit SDK Overview
Omniverse is a developer platform. It provides Nucleus for collaboration and data storage. Connector API provides USD conversion capabilities. The Omniverse developer platform provides the Kit SDK for developing Applications, Extensions, and Services.
This tutorial is focused on creating Applications and Extensions on top of Kit SDK.
## Kit Apps & Extensions
The Kit SDK Extension Architecture allow developers to define Extensions and Applications. An Extension is defined by a `.toml` file and most commonly has a set of directories with Python or C++ code. Extensions can also bundle resources such as images. An Application is a single `.kit` file. These modules can state each other as dependencies to combine small capabilities into a greater whole providing complex solutions.
Throughout this document you will encounter many Extensions and Applications. You will start to think of Extensions as “pieces of capabilities” and of Applications as “the collection of Extensions”.
### Extension
- Defined by an `extension.toml` file
- Contains code (Python or C++) and/or resource files.
- Provides a user interface and/or runtime capability.
### App
- Defined by a `.kit` file.
- Combines dependencies into an end user workflow.
## Extension Architecture
At the foundation of Kit SDK, the Kit Kernel provides the ability to bootstrap Applications and execute code. All capability on top of the Kernel is provided by Extensions. Kit SDK contains hundreds of Extensions providing runtime functionality such as USD, rendering, and physics - and other Extensions providing workflow solutions such as USD Stage inspectors, viewport, and content browsers. By combining the Kit SDK Extensions with one or more custom Extensions, new workflow and service based solutions can be created. The Extension Architecture of Kit has been designed for extreme modularity - enabling rapid development of reusable modules:
- Extensions are lego pieces of functionality.
- One Extension can state any number of other Extensions as dependencies.
- Applications provide a complete solution by combining many Extensions.
- Any Omniverse developer can create more Extensions.
Here’s another way to conceptualize the stack of an Application. At the foundation level of an app we have the Kit Kernel. There are runtime Extensions such as USD, RTX, and PhysX. Also behind the scene, there are framework Extensions that enable interfaces to be created, Extension management, and so on. Finally, we have the Extensions that provide end users with interfaces - such as the Viewport, Content Browser, and Stage inspector.
Applications you create will have the same stack - the only difference is what Extensions the Application makes use of and how they are configured.
We will explore the Extensions available in Kit SDK, how to create Applications, and how to get started with Extension development.
# Getting Started
## Introduction
Welcome to the tutorial on getting started with our platform. In this tutorial, we will guide you through the process of setting up your developer environment.
## Prerequisites
Before you begin, ensure you have met the following requirements:
* You have installed the latest version of Python.
* You have installed the latest version of Node.js.
* You have a Windows/Linux/Mac machine.
## Installing Dependencies
To install the necessary dependencies, follow these steps:
1. Install Python:
```bash
sudo apt-get install python3
```
2. Install Node.js:
```bash
sudo apt-get install nodejs
```
## Setting Up the Developer Environment
In this tutorial, let's get the developer environment setup. | 3,664 |
extension-config_Overview.md | # Overview — Omniverse Kit 107.0.0 documentation
## Overview
### Overview
Module to enable usage of `pip install` in Omniverse Kit environment. It wraps `pip install` calls and reroutes package installation into user specified environment folder.
It also extends Kit Extension System by enabling extensions to depend on python packages and providing pip archive folders for offline pip install (prebundling).
## Important Notes
### Important Notes
**This extension is not recommended for production. Installing packages at runtime relies on network availability, slow and security risk. Use this extension for prototyping and local development only.**
More information on pip packages in Kit can be found in [Using Python pip Packages](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/using_pip_packages.html).
## Usage
### Usage
Simples example is to just call `omni.kit.pipapi.install()` before importing a package:
```python
import omni.kit.pipapi
omni.kit.pipapi.install("semver==2.13.0")
# use
import semver
ver = semver.VersionInfo.parse('1.2.3-pre.2+build.4')
print(ver)
```
It can also be used to call pip with custom arguments, e.g.:
```python
omni.kit.pipapi.call_pip(["--help"])
```
## Extension Config
### Extension Config
All extensions that loaded after **omni.kit.pipapi** can specify those additional configuration settings in their extension.toml file:
### extension.toml
```toml
[python.pipapi]
# List of additional directories with pip achives to be passed into pip using ``--find-links`` arg.
# Relative paths are relative to extension root. Tokens can be used.
archiveDirs = ["path/to/pip_archive"]
# Commands passed to pip install before extension gets enabled. Can also contain flags, like `--upgrade`, `--no--index`, etc.
# Refer to: https://pip.pypa.io/en/stable/reference/requirements-file-format/
requirements = [
"simplejson==6.1",
]
```
"numpy"
# Optional list of modules to import before (check) and after pip install if different from packages in requirements.
modules = [
"simplejson",
"numpy"
]
# Allow going to online index. Required to be set to true for pip install call.
use_online_index = true
# Ignore import check for modules.
ignore_import_check = false
# Use this to specify a list of additional repositories if your pip package is hosted somewhere other
# than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument
repositories = [
"https://my.additional.pip_repo.com/"
]
# Other arguments to pass to pip install. For example, to disable caching:
extra_args = [
"--no-cache-dir"
]
This is equivalent to just calling
```python
omni.kit.pipapi.install()
```
in your extension’s startup. | 2,724 |
extension-toml-important-keys_Overview.md | # Overview
## A simple extension demonstrating how to bundle an external renderer into a Kit extension.
### extension.toml: Important keys
- **order = -100**
_# Load the extension early in startup (before Open USD libraries)_
- **writeTarget.usd = true**
_# Publish the extension with the version of Open USD built against_
### extension.py: Important methods
- **on_startup**
_# Handle registration of the renderer for Open USD and the Viewport menu_
- **on_shutdown**
_# Handle the removal of the renderer from the Viewport menu_
### settings.py:
- **register_sample_settings**
_# Register UI for communication via HdRenderSettings API via RenderSettings Window_
- **deregister_sample_settings**
_# Remove renderer specific UI from RenderSettings Window_ | 784 |
extension-types_index.md | # kit-rtp-texture: Omniverse Kit Extension & App Template
## Kit Extensions & Apps Example :package:
This repo is a gold standard for building Kit extensions and applications.
The idea is that you fork it, trim down parts you don’t need and use it to develop your extensions and applications. Which then can be packaged, shared, reused.
This README file provides a quick overview. In-depth documentation can be found at:
📖 [omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-rtp-texture](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-rtp-texture)
Teamcity Project
## Extension Types
```mermaid
graph TD
subgraph "python"
A3(__init__.py + python code)
end
subgraph cpp
A1(omni.ext-example_cpp_ext.plugin.dll)
end
subgraph "mixed"
A2(__init__.py + python code)
A2 --import _mixed_ext--> B2(example.mixed_ext.python)
B2 -- carb::Framework --> C2(example.mixed_ext.plugin.dll)
end
Kit[Kit] --> A1
Kit[Kit] --> A2
Kit[Kit] --> A3
```
## Getting Started
1. build:
```
build.bat -r
```
2. run:
```
_build\windows-x86_64\release\omni.app.new_exts_demo_mini.bat
```
3. notice enabled extensions in “Extension Manager Window” of Kit. One of them brought its own test in “Test Runner” window.
To run tests:
```
repo.bat test
```
To run from python:
```
_build\windows-x86_64\release\example.pythonapp.bat
```
## Using a Local Build of Kit SDK
By default packman downloads Kit SDK (from `deps/kit-sdk.packman.xml`). For developing purposes local build of Kit SDK can be used.
To use your local build of Kit SDK, assuming it is located say at `C:/projects/kit`.
Use `repo_source` tool to link:
```
repo source link C:/projects/kit
## Using a Local Build of another Extension
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g. `omni.app.my_app.kit` example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using `deps/user.toml`. You can use that file to override any setting.
Create `deps/user.toml` file in this repo with the search to path to your repo added to `app/exts/folders` setting, e.g.:
```toml
[app.exts]
folders."++" = ["c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts"]
```
`repo source` tool can also be used to create and edit `user.toml`. Provide a path to a repo or a direct path to an extension(s):
```
repo source link [repo_path]
- If repo produces kit extensions add them to `deps/user.toml` file.
repo source link [ext_path]
- If the path is a kit extension or folder with kit extensions add to `deps/user.toml` file.
```
Other options:
- Pass CLI arg to any app like this: `--ext-folder c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts`.
- Use *Extension Manager UI (Gear button)*.
- Use other `user.toml` (or other) configuration files, refer to [Kit Documentation: Configuration](https://docs.omniverse.nvidia.com/kit/docs/kit-sdk/104.0/docs/guide/configuration.html#user-settings).
You can always find out where an extension is coming from in *Extension Manager* by selecting an extension and hovering over the open button.
You can also find it in the log, by looking either for `registered` message for each extension or `About to startup:` when it starts.
## Other Useful Links
- See [Kit Manual](https://docs.omniverse.nvidia.com/kit/docs/kit-manual)
- See [Kit Documentation](https://docs.omniverse.nvidia.com/kit/docs)
# Kit Developer Documentation Index
- **Build Systems**
- See Anton’s Video Tutorials for Anton’s videos about the build systems. | 3,783 |
extension-types_overview.md | # Kit Extensions & Apps Example :package:
This repo is a gold standard for building Kit extensions and applications.
The idea is that you fork it, trim down parts you don’t need and use it to develop your extensions and applications. Which then can be packaged, shared, reused.
This README file provides a quick overview. In-depth documentation can be found at:
📖 http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-template
Teamcity Project
## Extension Types
graph TD
subgraph "python"
A3(__init__.py + python code)
end
subgraph cpp
A1(omni.ext-example_cpp_ext.plugin.dll)
end
subgraph "mixed"
A2(__init__.py + python code)
A2 --import _mixed_ext--> B2(example.mixed_ext.python)
B2 -- carb::Framework --> C2(example.mixed_ext.plugin.dll)
end
Kit[Kit] --> A1
Kit[Kit] --> A2
Kit[Kit] --> A3
## Getting Started
1. build:
```
build.bat -r
```
2. run:
```
_build\windows-x86_64\release\omni.app.new_exts_demo_mini.bat
```
3. notice enabled extensions in “Extension Manager Window” of Kit. One of them brought its own test in “Test Runner” window.
To run tests:
```
repo.bat test
```
To run from python:
```
_build\windows-x86_64\release\example.pythonapp.bat
```
## Using a Local Build of Kit SDK
By default packman downloads Kit SDK (from
```
deps/kit-sdk.packman.xml
```
). For developing purposes local build of Kit SDK can be used.
To use your local build of Kit SDK, assuming it is located say at
```
C:/projects/kit
```
.
Use
```
repo_source
```
tool to link:
```
repo source link c:/projects/kit/kit
```
Or you can also do it manually: create a file:
```
deps/kit-sdk.packman.xml.user
```
containing the following lines:
```
<div class="highlight-xml notranslate">
<div class="highlight">
<pre><span>
<span class="nt"><dependency
<span class="nt"><source
<span class="nt"></dependency>
<span class="nt"></project>
<p>
To see current source links:
<blockquote>
<div>
<p>
<code>
repo
source
list
<p>
To remove source link:
<blockquote>
<div>
<p>
<code>
repo
source
unlink
kit-sdk
<p>
To remove all source links:
<blockquote>
<div>
<p>
<code>
repo
source
clear
<section id="using-a-local-build-of-another-extension">
<h2>
Using a Local Build of another Extension
<p>
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g.
<code>
omni.app.my_app.kit
example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
<p>
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using
<code>
deps/user.toml
. You can use that file to override any setting.
<p>
Create
<code>
deps/user.toml
file in this repo with the search to path to your repo added to
<code>
app/exts/folders
setting, e.g.:
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span>
<span class="n">folders
<p>
<code>
repo
source
tool can also be used to create and edit
<code>
user.toml
. Provide a path to a repo or a direct path to an extension(s):
<blockquote>
<div>
<p>
<code>
repo
source
link
[repo_path]
- If repo produces kit extensions add them to
<code>
deps/user.toml
file.
<blockquote>
<div>
<p>
<code>
repo
source
link
[ext_path]
- If the path is a kit extension or folder with kit extensions add to
<code>
deps/user.toml
file.
<p>
Other options:
<ul>
<li>
<p>
Pass CLI arg to any app like this:
<code>
--ext-folder
c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts
.
<li>
<p>
Use
<em>
Extension Manager UI (Gear button)
<li>
<p>
Use other
<code>
user.toml
(or other) configuration files, refer to
<em>
Kit Documentation: Configuration
.
<p>
You can always find out where an extension is coming from in
<em>
Extension Manager
by selecting an extension and hovering over the open button.
<p>
You can also find it in the log, by looking either for
<code>
registered
message for each extension or
<code>
About
to
startup:
when it starts.
<section id="other-useful-links">
<h2>
Other Useful Links
<ul>
<li>
<p>
See
<em>
Kit Manual
<li>
<p>
See
<em>
Kit Developer Documentation Index
<li>
<p>
See
<em>
Anton’s Video Tutorials
for Anton’s videos about the build systems.
| 4,878 |
extensions-loaded_Overview.md | # Overview — kit-omnigraph 2.3.1 documentation
## Overview
This extension is an aggregator of the set of extensions required for basic Action Graph use. Action Graphs are a subset of OmniGraph that control execution flow through event triggers. Loading this bundle extension is a convenient way to load all of the extensions required to use the OmniGraph Action Graphs. There is no new functionality added by this bundle over and above what is provided by loading each of the extensions individually.
### Extensions Loaded
- [omni.graph](https://docs.omniverse.nvidia.com/kit/docs/omni.graph/latest/Overview.html#ext-omni-graph) (in Omniverse Kit)
- [omni.graph.action](../../omni.graph.action/1.101.1/Overview.html#ext-omni-graph-action) (in kit-omnigraph)
- [omni.graph.nodes](../../omni.graph.nodes/1.141.2/Overview.html#ext-omni-graph-nodes) (in kit-omnigraph)
- [omni.graph.ui](../../omni.graph.ui/1.67.1/Overview.html#ext-omni-graph-ui) (in kit-omnigraph)
- [omni.graph.ui_nodes](../../omni.graph.ui_nodes/1.24.1/Overview.html#ext-omni-graph-ui-nodes) (in kit-omnigraph) | 1,078 |
extensions.md | # Related Extensions
## Related Extensions
- **omni.graph**
- Python access to OmniGraph functionality
- **omni.graph.action**
- Support and nodes best suited for using in an [Action Graph](Glossary.html#term-Action-Graph)
- **omni.graph.bundle.action**
- Aggregator of the extensions required to use all Action Graph features
- **omni.graph.core**
- Core extension with all of the basic OmniGraph functionality
- **omni.graph.examples.cpp**
- Example nodes written in C++
- **omni.graph.examples.python**
- Example nodes written in Python
- **omni.graph.nodes**
- Library of simple nodes for common use
- **omni.graph.scriptnode**
- Implementation of an OmniGraph node that lets you implement your own node computation without needing to add all of the extension support required for a regular node
- **omni.graph.telemetry**
- Omniverse Kit telemetry integration for OmniGraph
- **omni.graph.template.cpp**
- Template extension to copy when building an extension with only C++ OmniGraph nodes
- **omni.graph.template.mixed**
- Template extension to copy when building an extension with both C++ and Python OmniGraph nodes
<span class="xref std std-ref">
omni.graph.template.mixed
Template extension to copy when building an extension with a mix of C++ and Python OmniGraph nodes
<span class="xref std std-ref">
omni.graph.template.no_build
Template extension to copy when creating an extension with only Python nodes without a premake build process
<span class="xref std std-ref">
omni.graph.template.python
Template extension to copy when building an extension with only Python OmniGraph nodes
<span class="xref std std-ref">
omni.graph.tools
Tools for build and runtime operations, such as the node generator
<span class="xref std std-ref">
omni.graph.tutorials
Nodes that walk through use of various facets of the node description format
<span class="xref std std-ref">
omni.graph.ui
User interface elements for interacting with the elements of an OmniGraph
<span class="xref std std-ref">
omni.graph.ui_nodes
OmniGraph nodes that facilitate dynamic creation of user interface elements | 2,127 |
extensions_advanced.md | # Extensions in-depth
## What is an Extension?
An extension is, in its simplest form, just a folder with a config file (`extension.toml`). The Extension system will find that extension and if it’s enabled it will do whatever the config file tells it to do, which may include loading python modules, **Carbonite** plugins, shared libraries, applying settings etc.
There are many variations, you can have an extension whose sole purpose is just to enable 10 other extensions for example, or just apply some settings.
## Extension in a single folder
Everything that an extension has should be contained or nested within its root folder. This is a convention we are trying to adhere to. Looking at other package managers, like those in the Linux ecosystem, the content of packages can be spread across the filesystem, which makes some things easier (like loading shared libraries), but also creates many other problems.
Following this convention makes the installation step very simple - we just have to unpack a single folder.
A typical extension might look like this:
```
[extensions-folder]
└── omni.appwindow
│──bin
│ └───windows-x86_64
│ └───debug
│ └─── omni.appwindow.plugin.dll
│───config
│ └─── extension.toml
└───omni
└───appwindow
│─── _appwindow.cp37-win_amd64.pyd
└─── __init__.py
```
This example contains a **Carbonite** plugin and a python module (which contains the bindings to this plugin).
## Extension Id
Extension id consists of 3 parts: `[ext_name]-[ext_tag]-[ext_version]`:
- `[ext_name]`: Extension name. Extension folder or kit file name.
- `[ext_tag]`: Extension tag. Optional. Used to have different implementations of the same extension. Also part of folder or kit file name.
- `[ext_version]`: Extension version. Defined in `extension.toml`. Can also be part of folder name, but ignored there.
Extension id example: `omni.kit.commands-1.2.3-beta.1`. Extension name is `omni.kit.commands`. Version is `1.2.3-beta.1`. Tag is empty.
## Extension Version
Version is defined in `[package.version]` config field.
Semantic Versioning is used. A good example of valid and invalid versions: [link](https://regex101.com/r/Ly7O1x/3/)
In short, it is `[major].[minor].[patch]-[prerelease].[build]`.
# Versioning
Versioning follows semantic versioning:
```markdown
[major].[minor].[patch]-[prerelease]
```
. Express compatibility with version change:
- For breaking change increment major version
- For backwards compatible change increment minor version
- For bugfixes increment patch version
Use
```markdown
[prerelease]
```
part to test a new version e.g.
```markdown
1.2.3-beta.1
```
# Extension Package Id
Extension package id is extension id plus build metadata.
```markdown
[ext_id]+[build_meta]
```
.
One extension id can have 1 or multiple packages in order to support different targets. It is common for binary extensions to have packages like:
- ```markdown
[ext_id]+wx64.r
```
- windows-x86_64, release config.
- ```markdown
[ext_id]+lx64.r
```
- linux-x86_64, release config.
- ```markdown
[ext_id]+lx64.d
```
- linux-x86_64, debug config.
- …
Python version or kit version can also denote different target. Refer to
```markdown
[package.target]
```
section of extension config.
# Single File Extensions
Single file Extensions are supported - i.e. Extensions consisting only of a config file, without any code. In this case the name of the config will be used as the extension ID. This is used to make a top-level extension which we call an **app**. They are used as an application entry point, to unroll the whole extension tree.
The file extension can be anything (
```markdown
.toml
```
for instance), but the recommendation is to name them with the
```markdown
.kit
```
file extension, so that it can be associated with the
```markdown
kit.exe
```
executable and launched with a single click.
```markdown
[extensions-folder]
└── omni.exp.hello.kit
```
# App Extensions
When
```markdown
.kit
```
files are passed to
```markdown
kit.exe
```
they are treated specially:
This:
```markdown
>
kit.exe
C:/abc/omni.exp.hello.kit
```
Is the same as:
```markdown
>
kit.exe
--ext-path
C:/abc/omni.exp.hello.kit
--enable
omni.exp.hello
```
It adds this
```markdown
.kit
```
file as an extension and enables it, ignoring any default app configs, and effectively starting an app.
Single file (
```markdown
.kit
```
file) extensions are considered apps, and a “launch” button is added to it in the UI of the extension browser. For regular extensions, specify the keyword:
```markdown
package.app
=
true
```
in the config file to mark your extension as an app that users can launch.
App extensions can be published, versioned, etc. just like normal extensions. So for instance if the
```markdown
omni.exp.hello
```
example from above is published, we can just run Kit as:
```markdown
>
kit.exe
omni.exp.hello.kit
```
Kit will pull it from the registry and start.
# Extension Search Paths
Extensions are automatically searched for in specified folders.
Core **Kit** config
```markdown
kit-core.json
```
specifies default search folders in
```markdown
/app/exts/foldersCore
```
setting. This way **Kit** can find core extensions, it also looks for extensions in system-specific documents folders for user convenience.
To add more folders to search paths there are a few ways:
1. Pass
```markdown
--ext-folder
[PATH]
```
CLI argument to kit.
2. Add to array in settings:
```markdown
/app/exts/folders
```
3. Use the
```markdown
omni::ext::ExtensionManager::addPath
```
API to add more folders (also available in python).
1. To specify direct path to a specific extension use the
```
/app/exts/paths
```
setting or the
```
--ext-path [PATH]
```
CLI argument.
2. Folders added last are searched first. This way they will be prioritized over others, allowing the user to override existing extensions.
3. Example of adding an extension seach path in a kit file:
```toml
[settings.app.exts]
folders.'++' = [
"C:/hello/my_extensions"
]
```
4. Custom Search Paths Protocols
Both folders and direct paths can be extended to support other url schemes. If no scheme is specified, they are assumed to be local filesystem. The extension system provides APIs to implement custom protocols. This way an extension can be written to enable searching for extensions in different locations, for example: git repos.
E.g.
```
--ext-folder foo://abc/def
```
– The extension manager will redirect this search path to the implementor of the
```
foo
```
scheme, if it was registered.
5. Git URL as Extension Search Paths
Extension
```
omni.kit.extpath.git
```
implements following extension search path schemes:
```
git
```
,
```
git+http
```
,
```
git+https
```
,
```
git+ssh
```
.
Optional URL query params are supported:
- ```
dir
```
subdirectory of a git repo to use as a search path (or direct path).
- ```
branch
```
git branch to checkout
- ```
tag
```
git tag to checkout
- ```
sha
```
git sha to checkout
Example of usage with cmd arg:
```
--ext-folder git://github.com/bob/somerepo.git?branch=main&dir=exts
```
– Add
```
exts
```
subfolder and
```
main
```
branch of this git repo as extension search paths.
Example of usage in kit file:
```toml
[settings.app.exts]
folders.'++' = [
"git+https://gitlab-master.nvidia.com/bob/some-repo.git?dir=exts&branch=feature"
]
```
After the first checkout, the git path is cached into global cache. To pull updates:
- use extension manager properties pages
- setting:
```
--/exts/omni.kit.extpath.git/autoUpdate=1
```
- API call
```
omni.kit.extpath.git.update_all_git_paths()
```
The Extension system automatically enables this extension if a path with a scheme is added. It enables extensions specified in a setting:
```
app/extensions/pathProtocolExtensions
```
, which by default is
```
["omni.kit.extpath.git"]
```
.
Note
Git installation is required for this functionality. It expects the
```
git
```
executable to be available in system shell.
6. Extension Discovery
The Extension system monitors any specified extension search folders (or direct paths) for changes. It automatically syncs all changed/added/removed extensions. Any subfolder which contains an
```
extension.toml
```
in the root or
```
config
```
folder is considered to be an extension.
The subfolder name uniquely identifies the extension and is used to extract the extension name and tag:
```
[ext_name]-[ext_tag]
```
[extensions-folder]
└── omni.kit.example-gpu-2.0.1-stable.3+cp37
# Extension Overview
This folder contains the following files:
- `extension.toml`
- ...
## Example Extension
In this example, we have an extension `omni.kit.example-gpu-2.0.1-stable.3+cp37`, where:
- **name:** `omni.kit.example`
- **tag:** `gpu` (optional, default is "")
The version and other information (like supported platforms) are queried in the extension config file. They may also be included in the folder name, which is what the system does with packages downloaded from a remote registry. In this example, anything could have been after the "gpu" tag, e.g., `omni.kit.example-gpu-whatever`.
## Extension Dependencies
When a Kit-based application starts, it discovers all extensions and does nothing with them until some of them are enabled, whether via config file or API. Each extension can depend on other extensions, and this is where the whole application tree can unroll. The user may enable a high-level extension like **omni.usd_viewer**, which will bring in dozens of others.
An extension can express dependencies on other extensions using **name**, **version**, and optionally **tag**. It is important to keep extensions versioned properly and express breaking changes using [Semantic Versioning](https://semver.org/).
This is a good place to grasp what **tag** is for. If extension `foo` depends on `bar`, you might implement other versions of `bar`, like `bar-light`, `bar-prototype`. If they still fulfill the same API contract and expected behavior, you can safely substitute `bar` without `foo` noticing. In other words, if the extension is an interface, **tag** is the implementation.
The effect is that just enabling some high-level extensions like omni.kit.window.script_editor will expand the whole dependency tree in the correct order without the user having to specify all of them or worry about initialization order.
One can also substitute extensions in a tree with a different version or tag, towards the same end-user experience, but having swapped in-place a different low-level building block.
When an extension is enabled, the manager tries to satisfy all of its dependencies by recursively solving the dependency graph. This is a difficult problem - If dependency resolution succeeds, the whole dependency tree is enabled in order so that all dependents are enabled first. The opposite is true for disabling extensions. All extensions which depend on the target extension are disabled first. More details on the dependency system can be found in the C++ unit tests: `source/tests/test.unit/ext/TestExtensions.cpp`.
A Dependency graph defines the order in which extensions are loaded - it is sorted topologically. There are however, many ways to sort the same graph (think of independent branches). To give finer control over startup order, the `order` parameters can be used. Each extension can use `core.order` config parameter to define its order and the order of dependencies can also be overridden with `order` param in `[[dependencies]]` section. Those with lower order will start sooner. If there are multiple extensions that depend on one extension and are trying to override this order then the one that is loaded last will be used (according to dependency tree). In summary - the dependency order is always satisfied (or extensions won’t be started at all, if the graph contains cycles) and soft ordering is applied on top using config params.
## Extension Configuration File (extension.toml)
An Extension config file can specify:
1. Dependencies to import
2. Settings
3. A variety of metadata/information which are used by the Extension Registry browser
TOML is the format used. See this short [toml tutorial](https://learnxinyminutes.com/docs/toml/).
Note in particular the `[[]]` TOML syntax for arrays of objects and quotes around keys which contain special symbols (e.g., `"omni.physx"`).
The config file should be placed in the root of the extension folder or in a `config` subfolder.
### Note
All relative paths in configs are relative to the extension folder. All paths accept tokens (like `${platform}`, `${config}`, `${kit}` etc). More info: [Tokens](tokens.html#list-tokens).
There are no mandatory fields in a config, so even with an empty config, the extension will be considered valid and can be enabled - without any effect.
Next we will list all the config fields the extension system uses, though a config file may contain more. The Extension system provides a mechanism to query config files and hook into itself. That allows us to extend the extension system itself and add new config sections. For instance `omni.kit.pipapi` allows extensions to specify pip packages to be installed before enabling them. More info on that: Hooks. That also means that **typos or unknown config settings will be left as-is and no warning will be issued**.
### Config Fields
#### [core] section
For generic extension properties. Used directly by the Extension Manager core system.
##### [core.reloadable] (default: true)
Is the extension **reloadable**? The Extension system will monitor the extension’s files for changes and try to reload the extension when any of them change. If the extension is marked as **non-reloadable**, all other extensions that depend on it are also non-reloadable.
##### [core.order] (default: 0)
When extensions are independent of each other they are enabled in an undefined order. An extension can be ordered to be before (negative) or after (positive) other extensions
#### [package] section
Contains information used for publishing extensions and displaying user-facing details about the package.
##### [package.version] (default: "0.0.0")
Extension version. This setting is required in order to publish extensions to the remote registry. The Semantic Versioning concept is baked into the extension system, so make sure to follow the basic rules:
- Before you reach `1.0.0`, anything goes, but if you make breaking changes, increment the minor version.
- After `1.0.0`, only make breaking changes when you increment the major version.
- Incrementing the minor version implies a backward-compatible change. Let’s say extension `bar` depends on `foo-1.2.0`. That means that `foo-1.3.0`, `foo-1.4.5`, etc.. are also suitable and can be enabled by extension system.
- Use version numbers with three numeric parts such as `1.0.0` rather than `1.0`.
- Prerelease labels can also be used like so: `1.3.4-beta`, `1.3.4-rc1.test.1`, or `1.3.4-stable`.
##### [package.title] default: ""
User-facing package name, used for UI.
##### [package.description] default: ""
User facing package description, used for UI.
##### [package.category] (default: "")
## Package Category Default
Extension category, used for UI. One of:
- animation
- graph
- rendering
- audio
- simulation
- example
- internal
- other
## Package App Default False
Whether the extension is an App. Used to mark extension as an app in the UI. Adds a “Launch” button to run kit with only this extension (and its dependents) enabled. For single-file extensions (.kit files), it defaults to true.
## Package Feature Default False
Extension is a Feature. Used to show user-facing extensions, suitable to be enabled by the user from the UI. By default, the app can choose to show only those feature extensions.
## Package Toggleable Default True
Indicates whether an extension can be toggled (i.e enabled/disabled) by the user from the UI. There is another related setting: [core.reloadable], which can prevent the user from disabling an extension in the UI.
## Package Authors Default
Lists people or organizations that are considered the “authors” of the package. Optionally include email addresses within angled brackets after each author.
## Package Repository Default
URL of the extension source repository, used for display in the UI.
## Package Keywords Default
Array of strings that describe this extension. Helpful when searching for it in an Extension registry.
## Package Changelog Default
Location of a CHANGELOG.MD file in the target (final) folder of the Extension, relative to the root. The UI will load and show it. We can also insert the content of that file inline instead of specifying a filepath. It is important to keep the changelog updated when new versions of an extension are released and published.
For more info on writing changelogs refer to Keep a Changelog
## Package Readme Default
Location of README file in the target (final) folder of an extension, relative to the root. The UI will load and show it. We can also insert the content of that file inline instead of specifying a filepath.
### [package.preview_image] (default: "")
Location of a preview image in the target (final) folder of extension, relative to the root. The preview image is shown in the “Overview” of the extension in the Extensions window. A screenshot of your extension might make a good preview image.
### [package.icon] (default: "")
Location of the icon in the target (final) folder of extension, relative to the root. Icon is shown in Extensions window. Recommended icon size is 256x256 pixels.
### [package.target]
This section is used to describe the target platform this extension runs on - this is fairly arbitrary, but can include:
- Operating system
- CPU architecture
- Python version
- Build configuration
The Extension system will filter out extensions that doesn’t match the current environment/platform. This is particularly important for extensions published and downloaded from a remote Extension registry.
Normally you don’t need to fill this section in manually. When extensions are published, this will be automatically filled in with defaults, more in [Publishing Extensions](#kit-ext-publishing). But it can be overriden by setting:
```toml
package.target.kit = ["*"] – Kit version (major.minor), e.g. "101.0", "102.3".
package.target.kitHash = ["*"] – Kit git hash (8 symbols), e.g. "abcdabcd".
package.target.config = ["*"] – Build config, e.g. "debug", "release".
package.target.platform = ["*"] – Build platform, e.g. "windows-x86_64", "linux-aarch64".
package.target.python = ["*"] – Python version, e.g. "cp37" (cpython 3.7). Refer to [PEP 0425](https://peps.python.org/pep-0425/).
```
A full example:
```toml
[package.target]
config = ["debug"]
platform = ["linux-*", "windows"]
python = ["*"]
```
### [package.writeTarget]
This section can be used to explicitly control if [package.target] should be written. By default it is written based on rules described in [Extension Publishing](#kit-ext-publishing). But if for some [target] a field is set, such as `package.writeTarget.[target] = true/false`, that tells explicitly whether it should automatically be filled in.
For example if you want to target a specific kit version to make the extension
**only**
work with that version, set:
```toml
[package]
writeTarget.kit = true
```
Or if you want your extension to work for all python versions, write:
```toml
[package]
writeTarget.python = false
```
The list of known targets is the same as in the
```
[package.target]
```
section:
```
kit
```
,
```
config
```
,
```
platform
```
,
```
python
```
.
## [dependencies] section
This section is used to describe which extensions this extension depends on. The extension system will guarantee they are enabled before it loads your extension (assuming that it doesn’t fail to enable any component). One can optionally specify a version and tag per dependency, as well as make a dependency optional.
Each entry is a **name** of other extension. It may or may not additionally specify: **tag**, **version**, **optional**, **exact**:
```toml
"omni.physx" = { version="1.0", "tag"="gpu" }
"omni.foo" = { version="3.2" }
"omni.cool" = { optional = true }
```
**Note that it is highly recommended to use versions**, as it will help maintain stability for extensions (and the whole application) - i.e if a breaking change happens in a dependency and dependents have not yet been updated, an older version can still be used instead. (only the **major** and **minor** parts are needed for this according to semver).
```
optional
```
(default:
```
false
```
) – will mean that if the extension system can’t resolve this dependency the extension will still be enabled. So it is expected that the extension can handle the absence of this dependency. Optional dependencies are not enabled unless they are a non-optional dependency of some other extension which is enabled, or if they are enabled explicitly (using API, settings, CLI etc).
```
exact
```
(default:
```
false
```
) – only an exact version match of extension will be used. This flag is experimental and may change.
```
order
```
(default:
```
None
```
) – override the
```
core.order
```
parameter of an extension that it depends on. Only applied if set.
## [python] section
If an extension contains python modules or scripts this is where to specify them.
### [[python.module]]
Specifies python module(s) that are part of this extension. Multiple can be specified. Take notice the
```
[[]]
```
syntax.
When an extension is enabled, modules are imported in order. Here we specify 2 python modules to be imported (
```
import omni.hello
```
and
```
import omni.calculator
```
).
When modules are scheduled for import this way, they will be reloaded if the module is already present.
Example:
```toml
[[python.module]]
name = "omni.hello"
[[python.module]]
name = "omni.calculator"
path = "."
```
```python
public = True
```
```
name
```
(required) – Python module name, can be empty. Think of it as what will be imported by other extensions that depend on you:
```python
import omni.calculator
```
```
public
```
(default:
```
true
```
) – If public, a module will be available to be imported by other extensions (extension folder is added to sys.path). Non-public modules have limited support and their use is not recommended.
```
path
```
(default:
```
"."
```
) – Path to the root folder where the python module is located. If written as relative, it is relative to extension root. Think of it as what gets added to
```
sys.path
```
. By default the extension root folder is added if any
```
[[python.module]]
```
directive is specified.
```
searchExt
```
(default:
```
true
```
) – If true, imports said module and launches the extensions search routine within the module. If false, only the module is imported.
By default the extension system uses a custom fast importer. Fast importer only looks for python modules in extension root subfolders that correspond to the module namespace. In the example above it would only look in
```
[ext root]/omni/**
```
. If you have other subfolders that contain python modules you at least need to specify top level namespace. E.g. if you have also
```
foo.bar
```
in
```
[ext root]/foo/bar.py
```
:
```toml
[[python.module]]
name = "foo"
```
Would make it discoverable by fast importer. You can also just specify empty name to make importer search all subfolders:
```toml
[[python.module]]
path = "."
```
Example of that is in
```
omni.kit.pip_archive
```
which brings a lot of different modules, which would be tedious to list.
### [[python.scriptFolder]]
Script folders can be added to
```
IAppScripting
```
, and they will be searched for when a script file path is specified to executed (with –exec or via API).
Example:
```toml
[[python.scriptFolder]]
path = "scripts"
```
```
path
```
(required) – Path to the script folder to be added. If the path is relative it is relative to the extension root.
### [native] section
Used to specify Carbonite plugins to be loaded.
### [[native.plugin]]
When an Extension is enabled, the Extension system will search for Carbonite plugins using
```
path
```
pattern and load all of them. It will also try to acquire the
```
omni::ext::IExt
```
interface if any of the plugins implements it. That provides an optional entry point in C++ code where your extension can be loaded.
When an extension is disabled it releases any acquired interfaces which may lead to plugins being unloaded.
Example:
```toml
[[native.plugin]]
path = "bin/${platform}/${config}/*.plugin"
recursive = false
```
```
path
```
(required) – Path to search for Carbonite plugins, may contain wildcards and Tokens.
## recursive
(default: false) – Search recursively in folders.
## [[native.library]] section
Used to specify shared libraries to load when an Extension is enabled.
When an Extension is enabled the Extension system will search for native shared libraries using `path` and load them. This mechanism is useful to “preload” libraries needed later, avoid OS specific calls in your code, and the use of `PATH`/`LD_LIBRARY_PATH` etc to locate and load DSOs/DLLs. With this approach we just load the libraries needed directly.
When an extension is disabled it tries to unload those shared libraries.
Example:
```toml
[[native.library]]
path = "bin/${platform}/${config}/foo.dll"
```
`path` (required) – Path to search for shared libraries, may contain wildcards and Tokens.
## [settings] section
Everything under this section is applied to the root of the global Carbonite settings (`carb.settings.plugin`). In case of conflict, the original setting is kept.
It is good practice to namespace your settings with your extension name and put them all under the `exts` root key, e.g.:
```toml
[settings]
exts."omni.kit.renderer.core".compatibilityMode = true
```
> Note
> Quotes are used here to distinguish between the `.` of a toml file and the `.` in the name of extension.
An important detail is that settings are applied in reverse order of extension startup (before any extensions start) and they don’t override each other. Therefore a parent extension can specify settings for child extensions to use.
## [[env]] section
This section is used to specify one or more environment variables to set when an extension is enabled. Just like settings, env vars are applied in reverse order of startup. They don’t by default override if already set, but override behavior does allow parent extensions to override env vars of extensions they depend on.
Example:
```toml
[[env]]
name = "HELLO"
value = "123"
isPath = false
append = false
override = false
platform = "windows-x86_64"
```
`name` (required) – Environment variable name.
`value` (required) – Environment variable value to set.
`isPath` (default: false) – Treat value as path. If relative it is relative to the extension root folder. Tokens can also be used as within any path.
`append` (default: false) – Append value to already set env var if any. Platform-specific separators will be used.
`override` (default: false) – Override value of already set env var if any.
`platform` (default: "") – Set only if platform matches pattern. Wildcards can be used.
### [fswatcher] section
Used to specify file system watcher used by the Extension system to monitor for changes in extensions and auto reload.
#### [fswatcher.patterns]
Specify files that are monitored.
- include (default: ["*.toml", "*.py"]) – File patterns to include.
- exclude (default: []) – File patterns to exclude.
Example:
```toml
[fswatcher.patterns]
include = ["*.toml", "*.py", "*.txt"]
exclude = ["*.cache"]
```
#### [fswatcher.paths]
Specify folders that are monitored. FS watcher will use OS specific API to listen for changes on those folders. You can use that setting that limit amount of subscriptions if your extensions has too many folders inside.
- include (default: ["*/config/*", "*/./*"] and python modules) – Folder path patterns to include.
- exclude (default: ["*/__pycache__/*", "*/.git/*"]) – Folder path patterns to exclude.
Example:
```toml
[fswatcher.paths]
include = ["*/config"]
exclude = ["*/data*"]
```
### [[test]] section
This section is read only by the testing system (omni.kit.test extension) when running per-extension tests. Extension tests are run as a separate process where only the tested extension is enabled and runs all the tests that it has. Usually this section can be left empty, but extensions can specify additional extensions (which are not a part of their regular dependencies, or when the dependency is optional), additional cmd arguments, or filter out (or in) any additional stdout messages.
Each [[test]] entry will run a separate extension test process.
Extension tests run in the context of an app. An app can be empty, which makes extension test isolated and only its dependencies are enabled. Testing in an empty app is the minimal recommended test coverage. Extension developers can then opt-in to be tested in other apps and fine-tune their test settings per app.
Example:
```toml
[[test]]
name = "default"
enabled = true
apps = [""]
args = ["-v"]
dependencies = ["omni.kit.capture"]
pythonTests.include = ["omni.foo.*"]
pythonTests.exclude = []
cppTests.libraries = ["bin/${lib_prefix}omni.appwindow.tests${lib_ext}"]
timeout = 180
```
parallelizable = true
unreliable = false
profiling = false
pyCoverageEnabled = false
waiver = ""
stdoutFailPatterns.include = ["*[error]*", "[fatal]*"]
stdoutFailPatterns.exclude = [
"*Leaking graphics objects*", # Exclude graphics leaks until fixed
]
### Test Configuration
- **name** – Test process name. If there are multiple `[[test]]` entries, this name must be unique.
- **enabled** – If tests are enabled. By default it is true. Useful to disable tests per platform.
- **apps** – List of apps to use this test configuration for. Used in case there are multiple `[[test]]` entries. Wildcards are supported. Defaults to `[""]` which is an empty app.
- **args** – Additional cmd arguments to pass into the extension test process.
- **dependencies** – List of additional extensions to enable when running the extension tests.
- **pythonTests.include** – List of tests to run. If empty, python modules are used instead (`[[python.module]]`), since all tests names start with module they are defined in. Can contain wildcards.
- **pythonTests.exclude** – List of tests to exclude from running. Can contain wildcards.
- **cppTests.libraries** – List of shared libraries with C++ doctests to load.
- **timeout** (default: 180) – Test process timeout (in seconds).
- **parallelizable** (default: true) – Whether the test processes can run in parallel relative to other test processes.
- **unreliable** (default: false) – If marked as unreliable, test failures won’t fail a whole test run.
- **profiling** (default: true) – Collects and outputs Chrome trace data via carb profiling for CPU events for the test process.
- **pyCoverageEnabled** (default: false) – Collects python code coverage using Coverage.py.
- **waiver** – String explaining why an extension contains no tests.
- **stdoutFailPatterns.include** – List of additional patterns to search stdout for and mark as a failure. Can contain wildcards.
- **stdoutFailPatterns.exclude** – List of additional patterns to search stdout for and exclude as a test failure. Can contain wildcards.
### [documentation] section
This section is read by the `omni.kit.documenation.builder` extension, and is used to specify a list of markdown files for in-app API documentation and offline sphinx generation.
Example:
```toml
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
```
- **pages** – List of .md file paths, relative to the extension root.
- **menu** – Menu item path to add to the popup in-app documentation window.
## Config Filters
Any part of a config can be filtered based on the current platform or build configuration. Use
```
```toml
"filter:platform"."[platform_name]"
```
or
```
```toml
"filter:config"."[build_config]"
```
pair of keys. Anything under those keys will be merged on top of the tree they are located in (or filtered out if it doesn’t apply).
| filter | values |
| --- | --- |
| platform | `windows-x86_64`, `linux-x86_64` |
| config | `debug`, `release` |
To understand, here are some examples:
```toml
[dependencies]
"omni.foo" = {}
"filter:platform"."windows-x86_64"."omni.fox" = {}
"filter:platform"."linux-x86_64"."omni.owl" = {}
"filter:config"."debug"."omni.cat" = {}
```
After loading that extension on a Windows debug build, it would resolve to:
```toml
[dependencies]
"omni.foo" = {}
"omni.fox" = {}
"omni.cat" = {}
```
**Note**
You can debug this behavior by running in debug mode, with
```
--/app/extensions/debugMode=1
```
setting and looking into the log file.
## Example
Here is a full example of an
```
extension.toml
```
file:
```toml
[core]
reloadable = true
order = 0
[package]
version = "0.1.0"
category = "Example"
feature = false
app = false
title = "The Best Package"
description = "long and boring text.."
authors = ["John Smith <jsmith@email.com>"]
repository = "https://gitlab-master.nvidia.com/omniverse/kit"
keywords = ["banana", "apple"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
# writeTarget.kit = true
# writeTarget.kitHash = true
# writeTarget.platform = true
# writeTarget.config = true
# writeTarget.python = true
[dependencies]
"omni.physx" = { version="1.0", "tag"="gpu" }
"omni.foo" = {}
# Modules are loaded in order. Here we specify 2 python modules to be imported (``import hello`` and ``import omni.physx``).
[[python.module]]
```
name = "hello"
path = "."
public = false
[[python.module]]
name = "omni.physx"
[[python.scriptFolder]]
path = "scripts"
# Native section, used if extension contains any Carbonite plugins to be loaded
[[native.plugin]]
path = "bin/${platform}/${config}/*.plugin"
recursive = false # false is default, hence it is optional
# Library section. Shared libraries will be loaded when the extension is enabled, note [[]] toml syntax for array of objects.
[[native.library]]
path = "bin/${platform}/${config}/foo.dll"
# Settings. They are applied on the root of global settings. In case of conflict original settings are kept.
[settings]
exts."omni.kit.renderer.core".compatibilityMode = true
# Environment variables. Example of adding "data" folder in extension root to PATH on Windows:
[[env]]
name = "PATH"
value = "data"
isPath = true
append = true
platform = "windows-x86_64"
# Fs Watcher patterns and folders. Specify which files are monitored for changes to reload an extension. Use wildcard for string matching.
[fswatcher]
patterns.include = ["*.toml", "*.py"]
patterns.exclude = []
paths.include = ["*"]
paths.exclude = ["*/__pycache__*", "*/.git*"]
# Documentation
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
```
# Extension Enabling/Disabling
Extensions can be enabled and disabled at runtime using the provided API. The default **Create** application comes with an Extension Manager UI which shows all the available extensions and allows a user to toggle them. An App configuration file can also be used to control which extensions are to be enabled.
You may also use command-line arguments to the Kit executable (or any Omniverse App based on Kit) to enable specific extensions:
Example:
```
> kit.exe --enable omni.kit.window.console --enable omni.kit.window.extensions
```
`--enable` adds the chosen extension to the “enabled list”. The command above will start only extensions needed to show those 2 windows.
## Python Modules
Enabling an extension loads the python modules specified and searches for children of :class: `omni.ext.IExt` class. They are instantiated and the `on_startup` method is called, e.g.:
`hello.py`
```python
import omni.ext
class MyExt(omni.ext.IExt):
def on_startup(self, ext_id):
pass
def on_shutdown(self):
pass
```
When an extension is disabled, `on_shutdown` is called and all references to the extension object are released.
## Native Plugins
Enabling an extension loads all Carbonite plugins specified by search masks in the `native.plugin` section. If one or more plugins implement the `omni.ext.IExt` interface, they are loaded and initialized.
# IExt Interface
When an extension is enabled, if it implements the `omni::ext::IExt` interface, it is acquired and the `onStartup` method is called.
When an extension is disabled, `onShutdown` is called and the interface is released.
# Settings
Settings to be applied when an extension is enabled can be specified in the `settings` section. They are applied on the root of global settings. In case of any conflicts, the original settings are kept. It is recommended to use the path `exts/[extension_name]` for extension settings, but in general any path can be used.
It is also good practice to document each setting in the `extension.toml` file, for greater discoverability of which settings a particular extension supports.
# Tokens
When extension is enabled it sets tokens into the Carbonite `ITokens` interface with a path to the extension root folder. E.g. for the extension `omni.foo-bar`, the tokens `${omni.foo}` and `${omni.foo-bar}` are set.
# Extensions Manager
## Reloading
Extensions can be hot reloaded. The Extension system monitors the file system for changes to enabled extensions. If it finds any, the extensions are disabled and enabled again (which can involve reloading large parts of the dependency tree). This allows live editing of python code and recompilation of C++ plugins.
Use the `fswatcher.patterns` and `fswatcher.paths` config settings (see above) to control which files change triggers reloading.
Use the `reloadable` config setting to disable reloading. This will also block the reloading of all extensions this extension depends on. The extension can still be unloaded directly using the API.
New extensions can also be added and removed at runtime.
## Extension interfaces
The Extension manager is implemented in `omni.ext.plugin`, with an interface: `omni::ext::IExtensions` (for C++), and `omni.ext` module (for python)
It is loaded by `omni.kit.app` and you can get an extension manager instance using its interface: `omni::kit::IApp` (for C++) and `omni.kit.app` (for python)
## Runtime Information
At runtime, a user can query various pieces of information about each extension. Use `omni::ext::IExtensions::getExtensionDict()` to get a dictionary for each extension with all the relevant information.
For python use `omni.ext.ExtensionManager.get_extension_dict()`.
This dictionary contains:
- Everything the extension.toml contains under the same path
- An additional `state` section which contains:
- `state/enabled` (bool): Indicates if the extension is currently enabled.
- `state/reloadable` (bool): Indicates if the extension can be reloaded (used in the UI to disable extension unloading/reloading)
## Hooks
Both the C++ and python APIs for the Extension system provide a way to hook into certain actions/phases of the Extension System to enable extending it. If you register a hook like this:
```python
def on_before_ext_enabled(self, ext_id: str, *_):
pass
manager = omni.kit.app.get_app_interface().get_extension_manager()
```
```python
# Extensions/Enable Extension
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
# enable immediately
manager.set_extension_enabled_immediate("omni.kit.window.about", True)
print(manager.is_extension_enabled("omni.kit.window.about"))
# or next update (frame), multiple commands are be batched
manager.set_extension_enabled("omni.kit.window.about", True)
manager.set_extension_enabled("omni.kit.window.console", True)
```
```python
# Extensions/Get All Extensions
import omni.kit.app
# there are a lot of extensions, print only first N entries in each loop
PRINT_ONLY_N = 10
# get all registered local extensions (enabled and disabled)
manager = omni.kit.app.get_app().get_extension_manager()
for ext in manager.get_extensions()[:PRINT_ONLY_N]:
print(ext["id"], ext["package_id"], ext["name"], ext["version"], ext["path"], ext["enabled"])
# get all registered non-local extensions (from the registry)
# this call blocks to download registry (slow). You need to call it at least once, or use refresh_registry() for non-blocking.
manager.sync_registry()
for ext in manager.get_registry_extensions()[:PRINT_ONLY_N]:
print(ext["id"], ext["package_id"], ext["name"], ext["version"], ext["path"], ext["enabled"])
# functions above print all versions of each extension. There is other API to get them grouped by name (like in ext manager UI).
# "enabled_version" and "latest_version" contains the same dict as returned by functions above, e.g. with "id", "name", etc.
for summary in manager.fetch_extension_summaries()[:PRINT_ONLY_N]:
print(summary["fullname"], summary["flags"], summary["enabled_version"]["id"], summary["latest_version"]["id"])
# get all versions for particular extension
for ext in manager.fetch_extension_versions("omni.kit.window.script_editor"):
print(ext["id"])
```
```python
# Extensions/Get Extension Config
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
# There could be multiple extensions with same name, but different version
# Extension id is: [ext name]-[ext version].
# Many functions accept extension id:
```
# Extension dict contains whole extension.toml as well as some runtime data:
## package section
```python
print(data["package"])
```
## is enabled?
```python
print(data["state/enabled"])
```
## resolved runtime dependencies
```python
print(data["state/dependencies"])
```
## time it took to start it (ms)
```python
print(data["state/startupTime"])
```
## can be converted to python dict for convenience and to prolong lifetime
```python
data = data.get_dict()
print(type(data))
```
# Get Extension Path
## Extensions/Get Extension Path
```python
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
# There could be multiple extensions with same name, but different version
# Extension id is: [ext name]-[ext version].
# Many functions accept extension id.
# You can get extension of enabled extension by name or by python module name:
ext_id = manager.get_enabled_extension_id("omni.kit.window.script_editor")
print(ext_id)
ext_id = manager.get_extension_id_by_module("omni.kit.window.script_editor")
print(ext_id)
# There are few ways to get fs path to extension:
print(manager.get_extension_path(ext_id))
print(manager.get_extension_dict(ext_id)["path"])
print(manager.get_extension_path_by_module("omni.kit.window.script_editor"))
```
# Other Settings
## /app/extensions/disableStartup (default: false)
Special mode where extensions are not started (the python and C++ startup functions are not called). Everything else will work as usual. One use-case might be to warm-up everything and get extensions downloaded. Another use case is getting python environment setup without starting anything.
## /app/extensions/precacheMode (default: false)
Special mode where all dependencies are solved and extensions downloaded, then the app exits. It is useful for precaching all extensions before running an app to get everything downloaded and check that all dependencies are correct.
## /app/extensions/debugMode (default: false)
Output more debug information into the info logging channel.
## /app/extensions/detailedSolverExplanation (default: false)
Output more information after the solver finishes explaining why certain versions were chosen and what the available versions were (more costly).
## /app/extensions/registryEnabled (default: true)
Disable falling back to the extension registry when the application couldn’t resolve all its dependencies, and fail immediately.
## /app/extensions/skipPublishVerification (default: false)
Skip the verification of the publish status of extensions and assume they are all published.
### Skip extension verification before publishing. Use wisely.
### /app/extensions/excluded (default: [])
List of extensions to exclude from startup. Can be used with or without a version. Before solving the startup order, all of those extensions are removed from all dependencies.
### /app/extensions/preferLocalVersions (default: true)
If true, prefer local extension versions over remote ones during dependency solving. Otherwise all are treated equally, so it can become likely that newer versions are selected and downloaded.
### /app/extensions/syncRegistryOnStartup (default: false)
Force sync with the registry on startup. Otherwise the registry is only enabled if dependency solving fails (i.e. something is missing). The --update-exts command line switch enables this behavior.
### /app/extensions/publishExtraDict (default: {})
Extra data to write into the extension index root when published.
### /app/extensions/fsWatcherEnabled (default: true)
Globally disable all filesystem watchers that the extension system creates.
### /app/extensions/mkdirExtFolders (default: true)
Create non-existing extension folders when adding extension search path.
### /app/extensions/installUntrustedExtensions (default: false)
Skip untrusted-extensions check when automatically installing dependencies and install anyway.
### /app/extensions/profileImportTime (default: false)
Replace global import function with the one that sends events to carb.profiler. It makes all imported modules show up in a profiler. Similar to PYTHONPROFILEIMPORTTIME.
### /app/extensions/fastImporter/enabled (default: true)
Enable faster python importer, which doesn’t rely on sys.path and manually scan extensions instead.
### /app/extensions/fastImporter/searchInTopNamespaceOnly (default: true)
If true, fast importer will skip search for python files in subfolders of the extension root that doesn’t match module names defined in [[python.module]]. E.g. it won’t usually look in any folder other than [ext.
# Extension Registries
## Publishing Extensions
### Cache file existence checks in the fast importer. This speeds up startup time, but extensions python code can’t be modified without cleaning the cache.
### Enable parallel pulling of extensions from the registry.
The Extension system supports adding external registry providers for publishing extensions to, and pulling extensions from. By default Kit comes with the omni.kit.registry.nucleus extension which adds support for Nucleus as an extension registry.
When an extension is enabled, the dependency solver resolves all dependencies. If a dependency is missing in the local cache, it will ask the registry for a particular extension and it will be downloaded/installed at runtime. Installation is just unpacking of a zip archive into the cache folder (app/extensions/registryCache setting).
The Extension system will only enable the Extension registry when it can’t find all extensions locally. At that moment, it will try to enable any extensions specified in the setting: app/extensions/registryExtension, which by default is omni.kit.registry.nucleus.
The Registry system can be completely disabled with the app/extensions/registryEnabled setting.
The Extension manager provides an API to add other extension registries and query any existing ones (omni::ext::IExtensions::addRegistryProvider, omni::ext::IExtensions::getRegistryProviderCount etc).
Multiple registries can be configured to be used at the same time. They are uniquely identified with a name. Setting app/extensions/registryPublishDefault sets which one to use by default when publishing and unpublishing extensions. The API provides a way to explicitly pass the registry to use.
To properly publish your extension to the registry use publishing tool, refer to: Publishing Extensions Guide
Alternatively, kit.exe --publish CLI command can be used during development:
Example:
```
> kit.exe --publish omni.my.ext-tag
```
If there is more than one version of this extension available, it will produce an error saying that you need to specify which one to publish.
Example:
```
> kit.exe --publish omni.my.ext-tag-1.2.0
```
To specify the registry to publish to, override the default registry name:
Example:
```
> kit.exe --publish omni.my.ext-tag-1.2.0 --/app/extensions/registryPublishDefault="kit/mr"
```
If the extension already exists in the registry, it will fail. To force overwriting, use the additional --publish-overwrite argument:
Example:
```
> kit.exe --publish omni.my.ext --publish-overwrite
```
The version must be specified in a config file for publishing to succeed.
All [package.target] config subfields are filled in automatically if unspecified:
- If the extension config has the [native] field [package.target.platform] or [package.target.config], they are filled with the current platform information.
If the extension config has the
[native]
and
[python]
fields, the field
[package.target.python]
is filled with the current python version.
If the
/app/extensions/writeTarget/kitHash
setting is true, the field
[package.target.kitHash]
is filled with the current kit githash.
An Extension package name will look like this:
[ext_name]-[ext_tag]-[major].[minor].[patch]-[prerelease]+[build]
. Where:
[ext_name]-[ext_tag]
is the extension name (initially coming from the extension folder).
[ext_tag]-[major].[minor].[patch]-[prerelease]
if
[package.version]
field of a config specifies.
[build]
is composed from the
[package.target]
field.
Pulling Extensions
There are multiple ways to get Extensions (both new Extensions and updated versions of existing Extensions) from a registry:
Use the UI provided by this extension:
omni.kit.window.extensions
If any extensions are specified in the app config file - or required through dependencies - are missing from the local cache, the system will attempt to sync with the registry and pull them. That means, if you have version “1.2.0” of an Extension locally, it won’t be updated to “1.2.1” automatically, because “1.2.0” satisfies the dependencies. To force an update run Kit with
--update-exts
Example:
> kit.exe --update-exts
Pre-downloading Extensions
You can also run Kit without starting any extensions. The benefit of doing this is that they will be downloaded and cached for the next run. To do that run Kit with
--ext-precache-mode
Example:
> kit.exe --ext-precache-mode
Authentication and Users
The Omniverse Client library is used to perform all operations with the nucleus registry. Syncing, downloading, and publishing extensions requires signing in. For automation, 2 separate accounts can be explicitly provided, for read and write operations.
User account read/write permissions can be set for the
omni.kit.registry.nucleus
extension. The “read” user account is used for syncing with registry and downloading extensions. The “write” user account is used for publishing or unpublishing extensions. If no user is set, it defaults to a regular sign-in using a browser.
By default, kit comes with a default read and write accounts set for the default registry.
Accounts setting example:
```
```toml
[exts."omni.kit.registry.nucleus".accounts]
[
{ url = "omniverse://kit-extensions.ov.nvidia.com", read = "[user]:[password]", write = "[user]:[password]" }
]
Where
read
- is read user account,
write
- is write user account. Both are optional. Format is: “user:password”.
Building Extensions
Extensions are a runtime concept. This guide doesn’t describe how to build them or how to build other extensions which might depend on another specific extension at build-time. One can use a variety of different tools and setups for that. We do however have some best-practice recommendations. The best sources of information on that topic are currently:
The example
omni.example.hello
extension (and many other extensions). Copy and rename it to create a new extension.
We also strive to use folder linking as much as possible. Meaning we don’t copy python files and configs from the source folder to the target (build) folder, but link them. This permits live changes to those files under version control to be immediately reflected, even at runtime. Unfortunately we can’t link files, because of Windows limitations, so folder linking is used. This adds some verbosity to the way the folder structure is organized.
For example, for a simple python-only extension, we link the whole python namespace subfolder:
```
source/extensions/omni.example.hello/omni
```
– [linked to] –>
```
_build/windows-x86_64/debug/exts/omni.example.hello/omni
```
For an extension with binary components we link python code parts and copy binary parts.
We specify other parts to link in the premake file:
```
repo_build.prebuild_link
{
"folder",
ext.target_dir.."/folder"
}
```
When working with the build system it is always a good idea to look at what the final
```
_build/windows-x86_64/debug/exts
```
folder looks like, which folder links exist, where they point to, which files were copied, etc. Remember that the goal is to produce
**one extension folder**
which will potentially be zipped and published. Folder links are just zipped as-is, as if they were actual folders. | 53,853 |
extensions_basic.md | # Getting Started with Extensions
This guide will help you get started creating new extensions for **Kit** based apps and sharing them with other people.
While this guide can be followed from any **Kit** based app with a UI, it was written for and tested in [Create](https://docs.omniverse.nvidia.com/app_create/app_create/overview.html).
### Note
For more comprehensive documentation on what an extension is and how it works, refer to :doc: `Extensions (Advanced) <extensions_advanced>`.
### Note
We recommend installing and using [Visual Studio Code](https://code.visualstudio.com/) as the main developer environment for the best experience.
## 1. Open Extension Manager UI: Window -> Extensions
This window shows all found extensions, regardless of whether they are enabled or disabled, local or remote.
## 2. Create New Extension Project: Press “Plus” button on the top left
It will ask you to select an empty folder to create a project in. You can create a new folder right in this dialog with a right-click.
It will then ask you to pick an extension name. It is good practice to match it with a python module that the extension will contain. Save the extension folder to your own convenient location for development work.
A few things will happen next:
- The selected folder will be prepopulated with a new extension.
- `exts` subfolder will be automatically added to extension search paths.
- `app` subfolder will be linked (symlink) to the location of your **Kit** based app.
- The folder gets opened in **Visual Studio Code**, configured and ready to hack!
- The new extension is enabled and a new UI window pops up.
The small “Gear” icon (on the right from the search bar) opens the extension preferences. There you can see and edit extension search paths. Notice your extension added at the end.
Have a look at the `README.md` file of created folder for more information on its content.
Try changing some python files in the new extension and observe changes immediately after saving. You can create new extensions by just cloning an existing one and renaming. You should be able to find it in the list of extensions immediately.
## 3. Push to git
When you are ready to share it with the world, push it to some public git repository host, for instance: [GitHub](https://github.com/).
A link to your extension might look like:
## Git URL as Extension Search Paths
The repository link can be added right into the extension search paths in UI.
To get new changes pulled in from the repository, click on the little sync button.
### Note
Git must already be installed (`git` command available in the shell) for this feature to work.
## More Advanced Things To Try
### Explore kit.exe
From Visual Studio Code terminal in a newly created project you have easy access to **Kit** executable.
Try a few commands in the terminal:
- `app\kit\kit.exe -h` to get started
- `app\kit\kit.exe --ext-folder exts --enable company.hello.world` to only start newly added extension. It has one dependency which will automatically start few more extensions.
- `app\kit\omni.app.mini.bat` to run another **Kit** based app. More developer oriented, minimalistic and fast to start.
### Explore other extensions
**Kit** comes with a lot of bundled extensions. Look inside `app/kit/exts`, `app/kit/extscore`, and `app/exts`. Most of them are written in python. All of the source to these extensions is available and can serve as an excellent reference to learn from. | 3,473 |
extensions_usd_schema.md | # USD Schema Extensions
USD libraries are part of omni.usd.libs extension and are loaded as one of the first extensions to ensure that USD dlls are available to other extensions.
USD schemas itself are each an individual extension that can be a part of any repository. USD schema extensions are loaded after omni.usd.libs and ideally before omni.usd.
Example of a schema extension config.toml file:
```toml
[core]
reloadable = false
# Load at the start, load all schemas with order -100 (with order -1000 the USD libs are loaded)
order = -100
[package]
category = "Simulation"
keywords = ["physics", "usd"]
# pxr modules to load
[[python.module]]
name = "pxr.UsdPhysics"
# python loader module
[[python.module]]
name = "usd.physics.schema"
# pxr libraries to be preloaded
[[native.library]]
path = "bin/${lib_prefix}usdPhysics${lib_ext}"
```
Schema extensions contain pxr::Schema, its plugin registry and config.toml definition file. Additionally it contains a loading module omni/schema/_schema_name that does have python init.py file containing the plugin registry code.
Example:
```python
import os
from pxr import Plug
pluginsRoot = os.path.join(os.path.dirname(__file__), '../../../plugins')
physicsSchemaPath = pluginsRoot + '/UsdPhysics/resources'
Plug.Registry().RegisterPlugins(physicsSchemaPath)
``` | 1,320 |
ext_blast.md | # Blast Destruction
## Overview
The Omniverse™ Blast Destruction (omni.blast) extension integrates the NVIDIA Omniverse™ Blast SDK into NVIDIA Omniverse™ Kit applications. It supports authoring of destructible content, and also implements destruction in PhysX SDK-driven simulation.
## Introductory Video
## User Guide
### Interface
The Blast window is divided into panels described in the following subsections.
#### Fracture Controls
These settings are used to author destructibles from mesh prims.
| Control | Effect |
|---------|--------|
| Combine Selected | Combines the selected mesh prims and/or destructible instances into a “multi-root” destructible. |
| Fracture Selected | Fracture the selected mesh prim. |
| Num Voronoi Sites | The number of pieces in which to fracture the selected meshes. |
| Random Seed | Seed value of pseudorandom number generator used during fracture operations. |
| Auto Increment | If checked, the Random Seed will automatically increment after each fracture operation. |
| Select Parent | |
### Select Parent
Select the parent(s) of the currently selected chunk(s). Removes children from selection set.
### Select Children
Select the children(s) of the currently selected chunk(s). Removes parents from selection set.
### Select Source
Select the source prim associated with any part of the destructible.
### Contact Threshold
The minimum contact impulse to trigger a contact event with a destructible.
### Max Contact Impulse
Applied to kinematic destructibles, limits the force applied to an impacting object.
### Reset to Default
Set Max Contact Impulse back to ‘inf’ for the selection.
### Interior Material
The material applied to faces generated through fracture. Can be set before or after fracture and will be applied to all descendants of the selected chunk(s).
### Interior UV Scale
Stretch to apply to material textures on newly-created interior faces.
### Apply Interior UV Scale
Apply the stretch value Interior UV Scale to selected chunks.
### Recalculate Bond Areas
Recalculate the bond area of selected instances. Use this after scaling an instance to ensure correct areas. Bond areas are used in stress pressure calculations.
### Recalculate Attachment
Search for nearby static or dynamic geometry and form bonds with that geometry.
### Make External Bonds Unbreakable
Bonds created between a blast destructible and external geometry will never break.
### Remove External Bonds
Remove all bonds to external geometry.
### Create Instance
Creates an instance based on the selected destructible base or instance. On instances, this is equivalent to using Kit’s duplicate command on the instance prim.
### Reset Blast Data
Destroys fracture information, depending on the type of prim(s) selected:
- Base selected - destroy all destruction info (including combine) and restores the orig mesh.
- Instance selected - destroy the selected instance.
- Anything else - search for chunks under selection and reset all fracture information for them.
### Important
Fracturing operations can increase geometry counts exponentially and have the potential to overwhelm computer resources. Use caution when increasing Number of Voronoi Sites.
### Instance Stress Settings
Beginning with omni.blast-0.11, damage in Blast has been unified into a stress model simulated for each destructible instance. External accelerations applied to support-level chunks are used as input, and the solver determines the internal bond forces which are required to keep the bonded chunks from moving relative to one another. Given each bond’s area, these forces are translated into pressures. The material strength of the destructible is described in terms of pressure limits which it can withstand before breaking.
The pressure is decomposed into components: the pressure in the bond-normal direction, and pressure perpendicular to the bond normal. Furthermore, the normal component can either be compressive (if the chunks are being pushed together) or tensile (if the chunks are being pulled apart). The pressure component perpendicular to the bond normal is called shear. For each component (compressive, tensile, or shear), we allow the user to specify an “elastic limit” and a “fatal limit.” These are described in the table below.
Damage has units of acceleration, which is applied to the support-level chunk at the damage application point. If “Stress Gravity Enabled” is checked (see the table below), then gravitational acceleration is applied to each support chunk, every frame in the stress simulation. If “Stress Rotation Enabled” is checked, then centrifugal acceleration is calculated and applied to each support chunk as well.
The stress solver replaces damage shaders in older versions of Blast. Using the stress model, damage spreads naturally through the system and fracture occurs because of physically modeled limits. Impact damage is applied by translating the contact impulse into an acceleration applied to the contacting support chunk. When fractured chunk islands (actors) break free, the excess force (that which exceeded the bonds’ limits) is applied to the separating islands, which leads naturally to pieces flying off with higher speeds when the system is hit harder. The excess force and contact impulse effects are adjustable with a multiplier for each (see Residual Force Multiplier and Impact Damage Scale).
<figure class="align-center" id="id1">
<figcaption>
<p>
<span class="caption-text">
This wall has fractured under its own weight due to the pressure of the overhang jutting out to the right.
<p>
These settings are applied to the selected destructible instance(s). They control how stress is processed during simulation.
<table class="docutils align-left">
<colgroup>
<col style="width: 18%"/>
<col style="width: 82%"/>
<thead>
<tr class="row-odd">
<th class="head">
<p>
Control
<th class="head">
<p>
Effect
<tbody>
<tr class="row-even">
<td>
<p>
Stress Gravity Enabled
<td>
<div class="line-block">
<div class="line">
Whether or not the stress solver includes gravitational acceleration.
<tr class="row-odd">
<td>
<p>
Stress Rotation Enabled
<td>
<div class="line-block">
<div class="line">
Whether or not the stress solver includes rotational acceleration.
<tr class="row-even">
<td>
<p>
Maximum Solver Iterations Per Frame
<td>
<div class="line-block">
<div class="line">
Controls how many passes the solver can do per frame. Higher numbers here will result in converging on a stable solution faster.
<tr class="row-odd">
<td>
<p>
Residual Force Multiplier
<td>
<div class="line-block">
<div class="line">
Multiplies the residual forces on bodies after connecting bonds break.
<tr class="row-even">
<td>
<p>
Stress Limit Presets
<td>
<div class="line-block">
<div class="line">
Set stress limits based on various physical substances. Can be used as a rough starting point, then tweaked for a specific use case.
<tr class="row-odd">
<td>
<p>
Compression Elastic Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for being compressed where bonds starts taking damage.
<tr class="row-even">
<td>
<p>
Compression Fatal Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for being compressed where bonds break instantly.
<tr class="row-odd">
<td>
<p>
Tension Elastic Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for being pulled apart where bonds starts taking damage. Use a negative value to fall back on compression limit.
<tr class="row-even">
<td>
<p>
Tension Fatal Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for being pulled apart where bonds break instantly. Use a negative value to fall back on compression limit.
<tr class="row-odd">
<td>
<p>
Shear Elastic Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for linear stress perpendicular to bond directions where bonds starts taking damage. Use a negative value to fall back on compression limit.
<tr class="row-even">
<td>
<p>
Shear Fatal Limit
<td>
<div class="line-block">
<div class="line">
Stress limit (in megapascals) for linear stress perpendicular to bond directions where bonds break instantly. Use a negative value to fall back on compression limit.
<tr class="row-odd">
<td>
<p>
Reset All to Default
<td>
<div class="line-block">
<div class="line">
Reset values in this panel to their defaults.
<section id="instance-damage-settings">
<h4>
Instance Damage Settings
<p>
These settings are applied to the selected destructible instance(s). They control how damage is processed during simulation.
<table class="docutils align-left">
<colgroup>
<col style="width: 20%"/>
<col style="width: 80%"/>
<thead>
<tr class="row-odd">
<th class="head">
<p>
Control
<th class="head">
<p>
Effect
<tbody>
<tr class="row-even">
<td>
<p>
Impact Damage Scale
<td>
<div class="line-block">
<div class="line">
A multiplier, contact impulses are multiplied by this amount before being used as stress solver inputs. If not positive, impact damage is disabled.
<tr class="row-odd">
<td>
<p>
Allow Self Damage
<td>
<div class="line-block">
<div class="line">
If On, chunks may damage other chunks which belong to the same destructible.
<section id="global-simulation-settings">
<h4>
Global Simulation Settings
<p>
These settings are general simulation settings.
<table class="docutils align-left">
<colgroup>
<col style="width: 25%"/>
<col style="width: 75%"/>
## Debug Visualization
These settings are used to visualize various aspects of a destructible.
### Controls
| Control | Effect |
|------------------------|---------------------------------------------------------------------------------------------|
| Max New Actors Per Frame | Only this many Blast actors may be created per frame. Additional actors will be delayed to subsequent frames. |
| Explode View Radius | When Not simulating, separates the chunks for inspection and/or selection. |
| View Chunk Depth | Which chunk hierarchy depth to render while in exploded view. |
| Visualization Mode | Controls what to render debug data for (see Visualization Mode table below). |
| Visualization Type | Controls what debug data is to be rendered (see Visualization Type table below). |
### Visualization Mode
| Visualization Mode | Description |
|---------------------|--------------------------------------------------------------------------------------------|
| Off | Disable Blast debug visualization system. |
| Selected | Only render debug visualization for the selected actor/instance. |
| On | Render debug visualization for all instances. |
### Visualization Type
| Visualization Type | Description |
|---------------------|--------------------------------------------------------------------------------------------|
| Support Graph | This shows representations of chunk centroids and bonds (drawn between the centroids). External bonds have a brown square around the bond centroid to distinguish them. The bond colors have meaning: |
| | Green - the bond’s health is at or near its full value. |
| | Red - the bond’s health is near zero. (Zero-health bonds are “broken” and not displayed.) |
| | In Green -> Yellow -> Red continuum - the bond’s health is somewhere between zero and full value. |
| | Light blue - the bond is an unbreakable external bond. |
| Max Stress Graph | This shows the maximum of the stress components for each bond, by coloring the bond lines drawn between the centroids. The colors have meaning: |
| | Green -> Yellow -> Red continuum - the stress is between 0 (green) and the bond’s elastic limit (red). |
| | Blue -> Magenta continuum - the stress is between the bond’s elastic limit (blue) and fatal limit (magenta). |
| Compression Graph | If the bond is under compression, this shows the compression component of stress for each bond. Colors have the same meaning as described for the Max Stress Graph. |
| Tension Graph | If the bond is under tension, this shows the tension component of stress for each bond. Colors have the same meaning as described for the Max Stress Graph. |
| Shear Graph | This shows the shear component of stress for each bond. Colors have the same meaning as described for the Max Stress Graph. |
| Bond Patches | Render bonded faces between chunks with matching colors. |
## Debug Damage Tool Settings
These settings control damage applied using Shift+B+(Left Mouse Button) during simulation. This is only intended for testing the behavior of a destructible.
| Control | Effect |
|---------|--------|
| Damage Amount | The base damage amount (acceleration in m/s^2) applied to the nearest support chunk in a destructible instance. |
| Damage Impulse | The outward impulse applied to rigid bodies which lie within the damage radius after fracture. This is in addition to the excess forces applied by the stress solver to chunks when they break free. |
| Damage Radius | The distance from the damage center (where the cursor is over scene geometry) to search for destructibles to damage. |
## Reset Button
This button resets all controls in the Blast window to their default settings.
## Push to USD Button
This will push the current runtime destruction data to USD, allowing the scene to be saved and later restored in the same destroyed state.
## OmniGraph Blast Node Documentation
This section describes the Blast nodes for use in the OmniGraph system. You can find them under “omni.blast” in the “Add node” right click menu or the pop out side bar.
NOTE: The nodes automatically update the USD stage. It is possible for them to get out of sync. If that happens just save and reload the scene. That will cause the Blast data to regenerate and should get things back in sync.
### Authoring: Combine
The Combine node takes two mesh or destructible prims and combines them into a single destructible. These can be chained together to create complex destructibles built out of many parts.
The output of this can also be sent to Fracture nodes to break them down. Note that fracturing after combine will apply to all parts that are touched by the point cloud. If you want points to only apply to a specific part, run it through Fracture first, then combine it to simplify the process.
| Input | Description |
|-------|-------------|
| prim1 | Prim to use as input to fracture. Connect to “destructible” output from another Blast node or “output” from an “import USD prim data” node. The import node should be connected to a mesh or xform/scope containing meshes. |
| prim2 | Prim to use as input to fracture. Connect to “destructible” output from another Blast node or “output” from an “import USD prim data” node. The import node should be connected to a mesh or xform/scope containing meshes. |
| contactThreshold | Force from impact must be larger than this value to be used to apply damage. Set higher to prevent small movements from breaking bonds. |
| bondStrength | Base value to use for bond strength. How it is applied depends on the mode used. Bond strength is automatically recalculated when this changes. |
| bondStrengthMode | Controls how the Default Bond Strength is used. Bond strength is automatically recalculated when this changes. |
| maxContactImpulse | Force that PhysX can use to prevent objects from penetrating. It is only used for kinematic destructibles that are attached to the world. This can approximate brittle materials by setting the value low, giving the bonds a chance to break before the objects are pushed apart. |
| damageMinRadius | Full damage from user generated fracture event is applied inside this radius. |
| damageMaxRadius | No damage from user generated fracture event is applied outside this radius. |
| impactDamageScale | Scale physical impacts by this amount when applying damage from collisions. |
|------------------|------------------------------------------------------------------------------------|
| impactClusterRadius | If positive, contact reports will be aggregated into clusters of approximately the given radius, and damage accumulated for that cluster. The cluster will be reported as one damage event. |
| allowSelfDamage | If on, chunks from a destructible actor may cause damage to sibling actors. Default behavior for legacy assets is to disable self-damage, which changes the legacy behavior. |
| destructible | Result of the combine operation. Can be used as the input prim to another Blast authoring node. |
## Authoring: Fracture
The Fracture node takes a mesh or destructible and fractures it based on a point cloud input. For best results, the mesh should be closed and not contain degenerate triangles. Input points that are inside of the mesh will be used to generate Voronoi sites, points outside of the mesh are ignored.
Sending in an already fractured mesh to another fracture node will create layers of fracture. The newly generated chunks from the first fracture will be fractured again using another set of points. This allows you to sculpt the detail and density in areas that you want it without requiring the entire mesh to be broken up at that fidelity.
During simulation if all children of a given parent chunk are still intact, then the parent will be rendered instead.
| Input | Description |
|-------|-------------|
| prim | Prim to use as input to fracture. Connect to “destructible” output from another Blast node or “output” from an “import USD prim data” node. The import node should be connected to a mesh prim. |
| points | Point cloud to use for fracture. Points inside will be used as Voronoi sites, points outside will be ignored. |
| contactThreshold | Force from impact must be larger than this value to be used to apply damage. Set higher to prevent small movements from breaking bonds. |
| bondStrength | Base value to use for bond strength. How it is applied depends on the mode used. Bond strength is automatically recalculated when this changes. |
| bondStrengthMode | Controls how the Default Bond Strength is used. Bond strength is automatically recalculated when this changes. |
| | “areaInstance”: (Default) Multiply the default value by the area of the bond using destructible instance scale. |
| | “areaBase”: Multiply the default value by the area of the bond using destructible base scale. |
| | “absolute”: Use the default value directly. |
| interiorMaterial | Path to material to use for interior faces created through fracture. |
| maxContactImpulse | Force that PhysX can use to prevent objects from penetrating. It is only used for kinematic destructibles that are attached to the world. This can approximate brittle materials by setting the value low, giving the bonds a chance to break before the objects are pushed apart. |
| interiorUvScale | UV scale to use on interior faces generated through fracture. |
| damageMinRadius | Full damage from user generated fracture event is applied inside this radius. |
| damageMaxRadius | No damage from user generated fracture event is applied outside this radius. |
| impactDamageScale | Scale physical impacts by this amount when applying damage from collisions. |
| impactClusterRadius | If positive, contact reports will be aggregated into clusters of approximately the given radius, and damage accumulated for that cluster. The cluster will be reported as one damage event. |
| allowSelfDamage | If on, chunks from a destructible actor may cause damage to sibling actors. Default behavior for legacy assets is to disable self-damage, which changes the legacy behavior. |
## Events: Flow Adapter
The Events Flow Adapter node takes a bundle of active events and translates it into outputs that can drive Flow emitter prim attributes.
Currently only one layer is supported for all events. Work is ongoing to support visible materials mapping to Flow data via a new schema, and for Flow emitters to be able to emit on multiple layers from a single input stream of data. Then events will use material data to drive emission specific to that material.
### Input
| Input | Description |
|-------|-------------|
| events | Bundle of events that can be processed by adapter nodes. |
### Output
| Output | Description |
|--------|-------------|
| positions | Unique world space vectors. |
| faceVertexIndices | Indices into “positions” used to build faces. |
| faceVertexCounts | Defines how many indices make up each face. |
| velocities | Per vertex velocity. |
| coupleRateSmokes | Per vertex emission rate. |
### Warning
The outputs prefixed with “subset” are not intended to be used yet. They will support multiple layers in the event bundle being passed to Flow when materials can be mapped to Flow layer IDs and Flow emitters support multiple layers.
### Experimental Output
| Experimental Output | Description |
|---------------------|-------------|
| subsetLayers | Flow layer IDs referenced by faces. It is possible for their to be duplicates. |
| subsetFaceCounts | Number of faces each layer ID slot represents. Faces are grouped by layer ID. |
| subsetEnabledStatus | Tells Flow emitter if each block of faces is enabled. Allows other data to be cached. |
## Events: Gather
The Events Gather node takes no inputs and produces a bundle of active events. These can come from bonds breaking and contacts between objects.
- Destruction events are generated for all Blast based prims when bonds break.
- Collision events are reported for all prims that have the rigid body and report contacts APIs applied.
The output of this can be sent to adapter nodes to generate responses to the events.
Visual materials should have the **Rigid Body Material** applied. This can be added by selecting the material and doing **Add -> Physics -> Rigid Body Material**. It is needed to report the correct materials for collision events. This is not strictly required yet, but will be when multiple materials are fully supported by this system.
# Demo Scenes
## Demo Scenes
Several demo scenes can be accessed through the physics demo scenes menu option (
```plaintext
Window > Simulation > Physics / Demo Scenes
```
).
This will enable a Physics Demo Scenes window, which has a Blast Samples section.
# Tutorials
## Tutorials
### Getting Started
This tutorial shows initial setup.
First enable the Blast extension (if it isn’t already):
```plaintext
Navigate to Window > Extensions
Enable the Blast Destruction extension
```
You can check `Autoload` if you will be working with Blast frequently and don’t want to have to enable it by hand each time you load the application.
Make sure it says `UP TO DATE` at the top of the extension details, if not, update to the latest release of the extension.
Make sure there something for the mesh to interact with:
```plaintext
Navigate to Create > Physics > Physics Scene
And Create > Physics > Ground Plane
```
Next, create a mesh:
```plaintext
Navigate to Create > Mesh and pick a mesh primitive type to create (Cube, Sphere, etc)
```
Be sure not to select `Create > Shape`, those do not support fracture, it must be a “Mesh” type prim.
Alternatively, you can load a mesh from another Usd source, just make sure it is a closed mesh.
Set up any physics properties you want on the mesh:
```plaintext
Right click on the mesh and navigate to Add > Physics
```
- **Make the object dynamic and collidable:**
- Set the Rigid Body with Colliders Preset to make it dynamic and collidable.
- **Change physics properties:**
- You can then change physics properties in the Properties > Physics panel.
Now fracture it:
- **Select the mesh to fracture:**
- Make sure the mesh to fracture is selected.
- **Locate the Blast pane:**
- Locate the Blast pane (by default it docs in the same area as Console).
- **Adjust Blast settings:**
- Adjust Blast settings as desired (see above for what the settings control).
- **Fracture the selected mesh:**
- Click the Fracture Selected button to fracture it.
- This will deactivate the original mesh and select the new Blast instance container (prim named after source mesh with __blastInst in the name).
- The original mesh is not altered and can be easily restored later if desired.
- **Review the fracture:**
- Scrub/adjust the Debug Visualization > Explode View Radius in the Blast panel to review the fracture.
- **Create additional instances:**
- Additional copies of the destructible can be made by clicking the “Create Instance” button in the Blast panel or running the duplicate command (Ctrl + D or Right Click > Duplicate).
Running the simulation (by pressing Play), the destructible falls to the ground and fractures due to impact damage.
## Reset Fracture
Here we see how to undo a fracture operation:
- **Select the original mesh or Blast base container:**
- Select the original mesh with Blast applied or the Blast base container (prim named after source mesh with __blastBase in the name).
- **Reset Fracture Data:**
- Click the Reset Fracture Data button in the Fracture Controls section.
- **Confirm deletion:**
- Dialogue will warn of deletion permanency; agree to delete.
- **Re-activate the source mesh prim:**
- This will remove all Blast data generated and re-activate the source mesh prim.
In the video we change the Num Voronoi Sites number and re-fracture.
## Multilevel Fracture
Here we see how to recursively fracture. This allows for higher overall detail with lower rendering and simulation cost by using a parent chunk for rendering and simulation until at least one child breaks off. It also allows for non-uniform fracture density throughout the mesh. Chunks of a fractured mesh may be broken down further.
> ### Fracturing a Mesh with Blast
> 1. Select a mesh with Blast applied
> 2. Adjust the explode view radius to make chunk selection easy
> 3. Select the desired chunk(s) to fracture further
> > You can also select them directly from Stage view under `<Blast base container>` while in explode view
> 4. Adjust the `Num Voronoi Sites` in the Blast panel to the desired number
> > Each chunk will be split into that many pieces
> 5. Click the `Fracture Selected` button to fracture the selected chunks
> 6. Changing the `View Chunk Depth` value selects different hierarchy depths to display
> 7. You may use the `Select Parent` and `Select Children` buttons to select up and down the hierarchy
> 8. Repeat as needed to get the desired level of granularity and fracture density throughout the mesh
> ### Static Attachment
> This tutorial shows the preferred way of creating a “static” destructible, by emulating an attachment to the static world:
> 1. Create a static collision mesh
> > - Create/load a mesh
> > - Right click on it
> > - Navigate to `Add > Physics > Colliders Preset`
> 2. Create a destructible prim in the usual way (see Getting Started above)
> > Leave the source prim as dynamic, do not set to kinematic or static
> 3. Place the destructible prim adjacent to (or slightly overlapping) a static collision mesh
> 4. Select the Blast instance container prim
> 5. Set the state of `Make External Bonds Unbreakable` based on how you want the base to behave
> > - When checked, the base pieces will remain kinematic no matter how much damage they take
> > - This is a good idea if the Blast instance container is deeply penetrating the static geometry, otherwise physics will force them apart when the pieces become dynamic
> > - When unchecked, the chunks can take damage and break free, becoming new dynamic rigid bodies
> 6. Press the `Recalculate Attachment` button to form bonds between the destructible and nearby static geometry (“external” bonds)
> 7. Debug Visualization >
Visualization
Type
>
Support
Graph
```
shows where external bonds have been formed when
```markdown
Debug
Visualization
>
Visualization
Mode
```
is set to
```markdown
Selected
```
or
```markdown
All
```
When simulating, the bonds formed keep the destructible “static” (kinematic). When bonds are damaged, chunk islands that are not connected via bonds to static geometry become separate dynamic bodies. The chunks that remain connected to static geometry via bonds remain kinematic.
# Dynamic Attachment
Here we see how to turn a part of a rigid body into a destructible. If the rigid body consists of multiple meshes, we may select one and make it destructible:
1. Create an Xform prim to contain the meshes with
```markdown
Create
>
Xform
```
2. Create/load meshes and add them to the Xform container
3. Set the hierarchy as dynamic and collidable
- Right click on the Xform prim
- Navigate to
```markdown
Add
>
Physics
>
Rigid
Body
with
Colliders
Preset
```
- This will automatically set the contained meshes as colliders
4. Select one or more of the meshes in the container to make destructible
5. Click the
```markdown
Fracture
Selected
```
button to fracture the mesh as usual
6. Set the state of
```markdown
Make
External
Bonds
Unbreakable
```
based on how you want the base to behave
- The same rules apply as for Static Attachment above
7. Press the
```markdown
Recalculate
Attachment
```
button
- Bonds will be formed with any adjacent or overlapping collision geometry from the same rigid Body
When simulating, the destructible mesh will move with its parent physics as a single rigid body. When bonds are damaged, chunk islands that are not connected via bonds to the parent physics geometry become separate dynamic bodies. The chunks that remain connected to the parent physics geometry via bonds remain rigidly connected to the physics body.
Note, if no bonds were formed (because there was no adjacent or overlapping collision geometry from the parent rigid body), then all chunk islands become dynamic when the destructible is fractured.
# Stress Damage
This tutorial covers the basics of the new stress damage system in Blast destruction, which is available in omni.blast-0.11. The viewer will learn how it relates to the previous damage system, how various sorts of damage are integrated within the stress framework, and how to adjust stress settings in a destructible.
> - Create a “wall” by first creating a mesh cube
> > - Create menu -> Mesh -> Cube
> > - With the new cube selected, in the property window set the Transform > Scale (x, y, z) to 5.0, 2.0, 0.2, and Translate y = 100.0
> > - Right click on the `cube` (wall)
> > - Navigate to `Add > Physics > Rigid Body with Colliders Preset`
> - Create the destructible wall
> > - Select the wall in the viewport
> > - In the Blast window, under the `Fracture Controls` panel, set `Num Voronoi Sites` to 1000
> > - Click the `Fracture Selected` button. There will be a long pause until the controls become responsive and the Cube__blastBase and Cube__blastInst prims appear in the Stage view
> > - With Cube_blastInst selected, press the `Recalculate Attachment` button to form permanent bonds between the destructible and the ground
> - Set stress limits and debug damage amount
> > - With Cube_blastInst selected, in the `Instance Stress Settings` panel, set `Compression Elastic Limit` to 0.05 and `Compression Fatal Limit` to 0.1
> > - In the `Debug Damage Tool Settings` panel, Set `Damage Amount` to 25000.0
> - Checking `non-stress` behavior
> > - With Cube_blastInst selected, in the `Instance Stress Settings` panel, uncheck both `Stress Gravity Enabled` and `Stress Rotation Enabled`
> > - Deselect the wall (you can deselect all by hitting the Esc key). Otherwise outline drawing of the 1000-piece wall causes a large hitch
- **Using the Cube_blastInst**
- **Applying damage to the wall**
- Shift+B+(Left Click) with the mouse cursor on the wall to apply damage
- You can damage along the bottom of the wall, and the top will only break off when you’ve completely cut through to the other simulated
- **Using the full stress solver**
- With Cube_blastInst selected, in the `Instance Stress Settings` panel, ensure both `Stress Gravity Enabled` and `Stress Rotation Enabled` are checked
- Deselect the wall (you can deselect all by hitting the Esc key)
- Shift+B+(Left Click) with the mouse cursor on the wall to apply damage
- You can damage along the bottom of the wall, but before you cut all the way across, the stress of the overhanging piece should cause it to snap off on its own
- **Repeating with a weaker wall (lower pressure limits)**
- With Cube_blastInst selected, in the `Instance Stress Settings` panel, set `Compression Elastic Limit` to 0.025 and `Compression Fatal Limit` to 0.05
- Deselect the wall (you can deselect all by hitting the Esc key)
- In the `Debug Damage Tool Settings` panel, Set `Damage Amount` to 10000.0
- Shift+B+(Left Click) with the mouse cursor on the wall to apply damage
- Now as you damage along the bottom of the wall, it doesn’t take as large of an overhang for the stress to cause it to snap off
**Note**
- If Shift+B+(Left Mouse Button) does not fracture a destructible, try increasing Damage Amount or Damage Radius.
- Changing Material(s) requires re-fracturing.
- Physics Properties of the Source Asset propagate to the fractured elements during authoring. | 35,031 |
ext_boom.md | # Boom Collision Audio
## Overview
The NVIDIA Omniverse™ Boom (omni.audio.boom) Extension adds audio material support to Kit Apps. With it, you can author audio materials on top of physics materials. These audio materials are used to play sounds based on simulation events, such as an impact, a roll, or a slide, or custom, script-based events with user-defined event names.
## Interface
The Boom window is divided into panels described in the following subsections.
### Debug Settings
With *Debug Settings*, you control the debug rendering features of the system.
#### Control
- **Debug Display**: Toggles debug rendering on/off. Colored spheres are drawn based on the type and magnitude of the event.
- **Red**: Impact
- **Green**: Rolling
- **Blue**: Sliding
- **Yellow**: Custom
- **Grey**: Suppressed
- **Show Suppressed Events**: Controls if events that were filtered out by containing events are rendered in black. This is off, by default, to prevent cluttering, but it can be useful to see how many events are attempting to play.
### Audio Material Definitions
With *Audio Material Definitions*, you define the audio material and its associated events.
#### Control
- **Add Event Type**: Defines a new event type for the audio material.
- **Simulation Events**: Created for both bodies involved.
- **Impact**: (One-shot) based on linear velocity in the normal direction when 2 bodies collide.
## Demo Scenes
Example demo scenes can be accessed through the physics demo scenes menu option (Window > Simulation > Demo Scenes). This will enable a Physics Demo Scenes window, which has a Boom Samples section.
## Tutorials
### Basic Setup Tutorial
### Step-by-step Walkthrough
In this tutorial, you learn how to set up a simple scene with collision-based audio.
First, enable the Boom extension (if it isn’t enabled already):
- Navigate to Window > Extensions.
- Enable the Boom extension.
You can check *Autoload* if you’ll be working with Boom frequently and don’t want to enable it every time you load the application.
Make sure it says “UP TO DATE” at the top of the extension details. If it doesn’t, update to the latest release of the extension.
Make sure there is something for the object to interact with:
> Navigate to *Create > Physics > Physics Scene*.
> And *Create > Physics > Ground Plane*.
Next, create a prim to interact with:
> Navigate to *Create > Mesh* or *Create > Shape*, and pick a primitive type to create (Cube, Sphere, etc).
> Alternatively, you can load a mesh from another USD source.
> Position the mesh above the plane.
Set up the mesh’s physics properties.
> Right-click the mesh, and navigate to *Add > Physics > Rigid Body with Colliders Preset* to make it dynamic and collidable.
> Right-click the mesh again, and navigate to *Add > Physics > Contact Reporter* if you want the system to auto-generate the simulation-based events.
> Make sure the *Contact Report Threshold* is low enough to generate contact events for the body. The default of 100 should be fine unless the mesh is very small.
> Only one object in a collision event needs to have the Contact Reporter set for sounds to play for both sides, but both having it won’t cause any problems.
The simulation events depend on the physics material. That can be applied in one of two ways:
> Assign a render material that has a physics material with it under *Materials on selected models* in the *Property* panel.
> Right click on a render material and select *Add > Physics > Rigid Body Material* to create add physics properties to it.
> Set the physics material directly under *Physics > Physics materials on selected models* in the Property panel, this one takes priority if both are set.
Now set up the audio material:
> The audio material needs to live on the same prim as the physics material.
> Select the prim that the physics material is defined on, and add the desired event type(s) to it via the *Boom* panel to define the audio material.
> Or, create the audio material in another scene and reference it (this method is useful if you want to create a library of audio materials in a single file).
> Create a *Scope* prim in another file, and add the event type(s) you want to it.
> Use *Add > Reference* on the physics material in the original file to point at it.
> Use the *Prim Path* field of the reference to target a single prim in the reference file.
Define as many threshold groups as you want.
> We recommend that you have the minimum attenuation for the lowest threshold group start at 0 so bodies settling don’t spam sounds.
> If you only have one set of sounds that you want to play, creating two threshold groups and adding the same sounds to both is useful in allowing the sounds to ramp in over the first range and play at full volume above the second threshold.
> If multiple audio assets are added to a threshold group, one will be picked at random to play when triggered by contact.
Repeat for all event types that you want to have play audio clips.
> It is not required to fill out all event types for an audio material to be valid.
> Creating complex sounds from interactions of multiple materials:
>
> - Unique material pair sounds are created by combining audio materials from both sides of a contact event.
> - Audio assets should be authored with as little audio contribution from external materials as possible.
> - Try the “Simple Example” demo to hear how sounds are combined based on materials involved in the contact.
> > - You can change the material on the box to hear how the sounds change when interacting with the two ground tiles.
>
> **Note**
>
> Run the simulation (by pressing *Play*), the rigid body falls to the ground and generates sounds from contact events. Use Shift + Left Mouse Button to toss the body to generate impact events or drag the body to generate sliding and rolling events. | 5,932 |
ext_omnigraph.md | # OmniGraph
OmniGraph is the visual scripting language of Omniverse. It allows the worlds in Omniverse to come alive with behavior and interactivity. OmniGraph addresses all sorts of computations, from deformers to particles to event-based graphs and more. OmniGraph is not a single type of graph, but a composition of many different types of graph systems under a single framework.
There are two types of graph types you can create in OmniGraph: **Action Graphs**, which allow event driven behaviors and **Push Graphs** which evaluate nodes continuously.
Additionally, there are node libraries for Particle System creation, Skeletal Animation and more.
## Getting Started
New to OmniGraph? These pages bring you up to speed with the concepts of OmniGraph and how to get up and running quickly.
- [Core Concepts](ext_omnigraph/getting-started/core_concepts.html)
- [Intro to OmniGraph](ext_omnigraph/tutorials/gentle_intro.html)
## OmniGraph Interface
Familiarize yourself with the OmniGraph Editor interface and view all available OmniGraph nodes.
- [The OmniGraph Interface](ext_omnigraph/interface.html)
- [Node Library](ext_omnigraph/node-library/node-library.html)
## OmniGraph Tutorials
To help you get started with OmniGraph, we’ve created a handful of hands-on tutorials:
- [Using Event Nodes](ext_omnigraph/tutorials/using_event_nodes.html)
- [Using Flow Control Nodes](ext_omnigraph/tutorials/using_flow_control_nodes.html)
- [Using Variant Nodes](ext_omnigraph/tutorials/using_variant_nodes.html)
- [Using Maneuver Nodes](ext_omnigraph/tutorials/using_maneuver_nodes.html)
## OmniGraph Developer Documentation
Interested in learning about OmniGraph development?
Open the OmniGraph developer portal | 1,723 |
ext_scene-optimizer.md | # Scene Optimizer
The Scene Optimizer is a Kit Extension that performs scene optimization at the USD level. This allows complex scenes to be converted into more lightweight representations which can be displayed and evaluated more quickly.
The tool provides various processes which can be used individually or in combination stack to optimize a scene.
## Topics
- [Using The Scene Optimizer](ext_scene-optimizer/user-manual.html)
- [Operations](ext_scene-optimizer/operations.html)
- [Scene Optimizer: What Options Should I Choose?](ext_scene-optimizer/howto.html)
- [White Papers](ext_scene-optimizer/white-papers.html)
- [Release Notes](ext_scene-optimizer/release-notes.html) | 682 |
ext_shaders.md | # Damage Shaders (NvBlastExtShaders)
The Blast damage shader extension provides basic implementations of programs generating fracture commands, the first step in breaking a Blast Actor, see [Damage and Fracturing](#splitting). These programs come as two shader functions (callbacks): one for Actors with a support graph, and one for Actors with just one chunk, respectively. The NvBlastDamageProgram containing both shaders can be used for low-level directly (NvBlastActorGenerateFracture) or for TkActor’s damage and fracture functions.
For example, one may construct a damage program using the “shear” damage shaders declared in NvBlastExtDamageShaders.h:
```
```c
NvBlastDamageProgram damageProgram = { NvBlastExtShearGraphShader, NvBlastExtShearSubgraphShader };
```
The appropriate shader (“graph” or “subgraph”) will be called for an Actor being processed, along with the Actor’s necessary geometry and program parameters. The parameters (NvBlastProgramParams) are set to contain:
1. Material, something that describes an Actor properties (e.g. mass, stiffness, fragility) which are not expected to be changed often.
2. Damage description, something that describes a particular damage event (e.g. position, radius and force of explosion).
For example:
```c
NvBlastExtMaterial material = { health, minDamageThreshold, maxDamageThreshold };
NvBlastExtRadialDamageDesc damageDesc = { compressive, posX, posY, posZ, minR, maxR };
```
When used with TkActor::damage() functions, TkActor will cache the necessary data for deferred processing through TkGroup. This includes accumulating damage requests for the same material and program parameter combination. A default material can be set for a TkFamily that all its Actors uses.
A Tk layer example follows.
```c
tkGroup->addActor(*tkActor);
tkActor->damage(damageProgram, damageDesc0, sizeof(NvBlastExtRadialDamageDesc), &material);
tkActor->damage(damageProgram, damageDesc1, sizeof(NvBlastExtRadialDamageDesc), &material);
tkGroup->process();
```
In contrast, the user is responsible for providing all the damage descriptions persisting through the low-level NvBlastActorGenerateFracture call when not using the Tk layer:
```c
NvBlastProgramParams programParams = { damageDescs, 2, &material };
NvBlastActorGenerateFracture(commandBuffers, actor, damageProgram, &programParams, nullptr, nullptr);
``` | 2,360 |
ext_stress.md | # Stress Solver (NvBlastExtStress)
The Blast stress solver extension provides an implementation of a fast and easy to use stress solver which works directly with the bond graph. It simulates iteratively spreading forces across bonds that connect nodes of the support graph (where nodes typically represent chunks) and allows bond limits to be specified for tension, compression, and shear independently.
The most common usage is applying gravity force on a static structure so that it will fall apart at some point when it cannot hold anymore. For gravity to work correctly there must be at least one node in the graph with 0 mass. That causes the system to treat the node as being fixed and having infinite mass so it can’t move to reach a converged state. You can use part of the destructible itself, or add a dummy node and bonds connecting it to the nodes that should support the structure. The other option is to add a supporting force to all nodes at the “base” of the graph (where the graph connects to the thing supporting it, normally the bottom, but could be the top for a hanging structure). Without this, the algorithm will stabilize with no internal force due to gravity, effectively treating it like the entire structure is in freefall.
It also can be used as another way to apply impact damage, which can give the visually pleasant result of an actor breaking in a weak place instead of the place of contact. This is accomplished by adding the impulse of collisions to the nearest node in the graph.
Dynamic actors are also supported, you could for example add centrifugal force so that rotating an object fast enough will break bonds. Keep in mind that for gravity to work with dynamic actors, an opposing force or static node(s) must be added to the system to provide resistance to the force.
## Features
- Requires only core a NvBlast
- Supports both static and dynamic actors
- Propagates both linear and angular momentum
- Graph complexity selection (reduces support graph to smaller size to trade-off speed for quality)
- Apply stress damage on Blast actor
- Debug Render
## Settings Tuning
Computation time is linearly proportional to the a maxSolverIterationsPerFrame setting. Higher values will converge to a solution sooner, but at processing cost. a graphReductionLevel should be considered experimental at this point, it has not been heavily tested.
Debug render can help a lot for tuning, consider using a stressSolver->fillDebugRender(…) for that.
## Usage
In order to use the stress solver, create an instance with a ExtStressSolver::create(…).
```cpp
ExtStressSolver* stressSolver = ExtStressSolver::create(family, settings);
```
a ExtStressSolverSettings are passed in create function, but also can be changed at any time with a stressSolver->setSettings(…).
It fully utilizes the fact that it knows the initial support graph structure and does a maximum of processing in the a create(…) method call. After that, all actor split calls are synchronized internally and efficiently so only the actual stress propagation takes most of computational time.
You need to provide physics specific information (mass, volume, position) for every node in support graph since Blast itself is physics agnostic. There are two ways to do it. One way is to call a stressSolver->setNodeInfo(…) for every graph node. The other way is to call stressSolver->setAllNodesInfoFromLL() once: all the data will be populated using NvBlastAsset chunk’s data, in particular a volume and a centroid. All ‘world’ nodes are considered static.
```cpp
stressSolver->setAllNodesInfoFromLL(density);
```
The stress solver needs to keep track for actor create/destroy events in order to update its internal stress graph accordingly. So you need to call a stressSolver->notifyActorCreated(actor) and a stressSolver->notifyActorDestroyed(actor) every time an actor is created or destroyed, including the initial actor the family had when the stress solver was created. There is no need to track actors which contain only one or less graph nodes. In that case a notifyActorCreated(actor) returns ‘false’ as a hint. It means that the stress solver will ignore them, as for those actors applying forces does not make any sense.
A typical update loop looks like this:
- Apply all forces, use a stressSolver->addForce(…), stressSolver->addGravity(…), a stressSolver->addCentrifugalAcceleration(…)
- Call a stressSolver->update(). This is where all expensive computation takes place.
- If a stressSolver->getOverstressedBondCount() > 0, use one of a stressSolver->generateFractureCommands() methods to get bond fracture commands and apply them on actors.
- If split happened, call relevant stressSolver->notifyActorCreated(actor) and stressSolver->notifyActorDestroyed(actor) | 4,780 |
ext_tkserialization.md | # BlastTk Serialization (NvBlastExtTkSerialization)
This extension contains serializers which can be loaded into the ExtSerialization manager defined in [Serialization (NvBlastExtSerialization)](ext_serialization.html#pageextserialization).
To use this extension, you must also load the ExtSerialization extension and create a serialization manager as described in [Serialization (NvBlastExtSerialization)](ext_serialization.html#pageextserialization).
We repeat this here (again, assuming we are in the Nv::Blast namespace):
```cpp
ExtSerialization* ser = NvBlastExtSerializationCreate();
```
Then, call the function NvBlastExtTkSerializerLoadSet, declared in **NvBlastExtTkSerialization.h**, passing in your TkFramework:
```cpp
TkFramework* framework = ... // We must have created a TkFramework
NvBlastExtTkSerializerLoadSet(*framework, *ser);
```
Now your serialization manager will have the serializers provided by this extension. Currently only TkAsset serializers exist, with object type ID given by
**TkObjectTypeID::Asset**
As with low-level assets, you can serialize using the serialization manager directly:
```cpp
const TkAsset* asset = ... // Given pointer to an Nv::Blast::TkAsset
void* buffer;
uint64_t size = ser->serializeIntoBuffer(buffer, asset, TkObjectTypeID::Asset);
```
or use the wrapper function defined in **NvBlastExtTkSerialization.h**:
```cpp
void* buffer;
uint64_t size = NvBlastExtSerializationSerializeTkAssetIntoBuffer(buffer, *ser, asset);
``` | 1,486 |
ext_viewport.md | # Viewport — Omniverse Extensions latest documentation
## Viewport
### Overview
The Viewport extension is the primary way you view 3D worlds in Omniverse Kit-based Apps. It’s the window through which you see and navigate your creative work.
### Viewport Tools
There are several tools that make up the functionality of the Viewport:
- Viewport Controls
- Viewport Settings
- Render Mode
- Interface Visibility
- Camera
- Persistent Menus
- Viewport Transform Manipulators
- Viewport Transform Context Menu
- Viewport Navigation
- Viewport Visor
- Viewport Turntable | 574 |
fabric_hierarchy.md | # Fabric Transforms with Fabric Scene Delegate and IFabricHierarchy
## About
The Fabric Scene Delegate is the next-generation Omniverse scene delegate for Hydra. It leverages the power and performance of Fabric for a faster, more flexible, streamlined rendering pipeline.
Fabric Scene Delegate uses Fabric as its data source for all rendering operations. Starting in Kit 106, Fabric Scene Delegate also leverages the new Connectivity API in Fabric to store and query information about the scenegraph transform hierarchy via the new IFabricHierarchy interface. This adds the following functionality to Fabric Scene Delegate:
- All Boundable prims in Fabric now participate in the transform hierarchy - changes to the local transform of a Fabric prim will affect the world transform of all descendants of that prim in Fabric.
- Prims authored exclusively in Fabric now participate in the transform hierarchy for the scene - previously, participating in the transform hierarchy (to the extent that OmniHydra supported it) required a corresponding prim on the USD stage.
This document reviews the IFabricHierarchy interface and how the transform hierarchy is maintained in Fabric.
## Fabric Transforms Previously
Earlier iterations of the Omniverse rendering pipeline supported limited Fabric-based transforms in the Hydra scene delegate. These required Fabric prims to express their world transform on Fabric prims using these attributes:
- `_worldPosition`
- `_worldOrientation`
- `_worldScale`
You can read more about this here: Working with OmniHydra Transforms
Prims with these transform attributes authored in Fabric no longer participate in any transform hierarchy. This often causes unexpected behavior when manipulating transforms on ancestors or descendants of these prims.
OmniHydra also supports a `_localMatrix` attribute, which if it exists in Fabric is substituted in the world transform calculation for a given prim in place of the backing USD prim’s computed local-to-parent transform. However, this requires a valid backing USD hierarchy, and is superseded by the existence of any of the `_world*` attributes.
Earlier versions of Fabric Scene Delegate also leveraged the `_world*` attributes to drive rendered prim transforms. These attribute values could be updated directly in Fabric, and transform attribute changes to the underlying USD stage are reflected in Fabric by the Fabric population interface USD notice handler. Like with OmniHydra, these values in Fabric represent an absolute world-space transform for the prim, and any changes to these values in Fabric does not represent a hierarchical transform change. There is no transform change that can be made in Fabric that will affect transform descendants of that prim in a Fabric Scene Delegate powered render.
In summary, support for hierarchical transform changes in Fabric has been somewhat incomplete. IFabricHierarchy was created to add complete, Fabric-native transform hierarchy support with Fabric Scene Delegate.
## Fabric Transforms with Fabric Scene Delegate and IFabricHierarchy
Kit 106 adds a new interface for use with Fabric Scene Delegate called IFabricHierarchy. This interface is not supported with OmniHydra.
### New transform attributes
When Fabric is populated from the USD Stage while Fabric Scene Delegate is enabled, every Boundable prim has two new attributes created in Fabric:
- `omni:fabric:localMatrix` - the local-to-parent transform of the prim, as a `GfMatrix4d`
- `omni:fabric:worldMatrix` - the world transform of the prim, as a `GfMatrix4d`
- `omni:fabric:worldMatrix` - the local-to-world transform of the prim, as a `GfMatrix4d`
`omni:fabric:localMatrix` is the editable local transform of any prim in Fabric. `omni:fabric:worldMatrix` is the computed, cached, read-only ( * ) world transform of any prim in Fabric. Changes to the value of the `omni:fabric:localMatrix` attribute will cause the `omni:fabric:worldMatrix` attribute of that prim and all of its descendants to be recomputed before the next rendered frame. Fabric Scene Delegate uses the `omni:fabric:worldMatrix` attribute to set prim transform values in the Hydra rendering pipeline.
(*) All attributes in Fabric are writeable, but as a computed value, `omni:fabric:worldMatrix` is intended as a read-only attribute outside of updates from the IFabricHierarchy implementation.
## The IFabricHierarchy interface
IFabricHierarchy is a new interface defined in `includes/usdrt/hierarchy/IFabricHierarchy.h`
`usdrt::hierarchy::IFabricHierarchy`
IFabricHierarchy has a few simple APIs:
- `getFabricHierarchy(fabricId, stageId)` - Get the Fabric Hierarchy instance for a given FabricId and StageId
- `getLocalXform(path)` - Get the local-to-parent transform of a given prim - this just returns the value of the `omni:fabric:localMatrix` attribute in Fabric.
- `getWorldXform(path)` - Get the local-to-world transform of a given prim - note that this value will be computed, so the value returned will always be correct. To query the cached value, `omni:fabric:worldMatrix` can be read from Fabric directly.
- `setLocalXform(path, matrix)` - Update the `omni:fabric:localMatrix` attribute value in Fabric with the new matrix value.
- `setWorldXform(path, matrix)` - Compute a new local-to-parent transform value such that the resulting computed local-to-world transform matches the given transform matrix, and set that value on `omni:fabric:localMatrix`.
- `updateWorldXforms()` - Using Fabric change tracking, update all `omni:fabric:worldMatrix` values for any prim whose `omni:fabric:localMatrix` value has changed, as well as all transform hierarchy descendants of those prims, since the last time `updateWorldXforms()` was called.
These APIs assume a few things about the data stored in Fabric.
- All Boundable prims have an `omni:fabric:localMatrix` and `omni:fabric:worldMatrix` attribute authored. This is enforced for prims that originate from USD by the Fabric population interface that ships with Fabric Scene Delegate. For prims that are created and only exist in Fabric, these attributes may need to be created directly or by using the RtXformable API:
- `usdrt::RtXformable::CreateFabricHierarchyLocalMatrixAttr()`
- `usdrt::RtXformable::CreateFabricHierarchyWorldMatrixAttr()`
- All prims in Fabric have been registered with the Fabric Connectivity API. This happens automatically for prims originating from USD and prims created with `usdrt::UsdStage::DefinePrim()`. The Connectivity API enables Fabric to establish a transform hierarchy for prims that only exist in Fabric.
<span class="pre">
omni:fabric:localMatrix
always represents the correct and most recent local transform for the prim. This is enforced for changes on the USD stage by the Fabric Scene Delegate USD Notice handler - any transform change on any prim in USD is immediately reflected as an update in Fabric on the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
attribute for the corresponding Fabric prim.
<p>
With IFabricHierarchy, the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
attribute represents a cached value of the world transform of the prim. That value is only updated when
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
is called on the interface - this allows changes to
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
to happen quickly and at scale without the cost of recomputing potentially thousands of
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
values that might otherwise be incurred in order to reflect changes inherited through the transform hierarchy every time a single prim transform is modified. Because of this, it is possible that the value for any
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
attribute is stale or out of date unless
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
has been called recently. Within the Kit application,
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
is called immediately prior to rendering every frame, so that Fabric Scene Delegate and the RTX renderer pull the latest and correct world transform values directly from Fabric.
<p>
In order to discover the world transform of any prim at any time, regardless of when
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
was last called,
<code class="docutils literal notranslate">
<span class="pre">
getWorldXform()
will calculate the correct value using the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
values of the prim and its ancestors.
<p>
While
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
is always called just before rendering, this method may be called any time that it is desirable to have the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
attribute values in Fabric reflect hierarchical transform changes from modifications to
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
since the last time
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
was called, such as at the start of a simulation step. If there have been no changes since the last call to
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
, this call does nothing.
<section id="code-examples">
<h2>
Code Examples
<section id="getting-and-changing-the-local-transform-of-a-prim">
<h3>
Getting and changing the local transform of a prim
<p>
The local transform of a prim can be modified by directly changing the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
attribute in Fabric, using USDRT APIs to change the value, or using the IFabricHierarchy interface.
<section id="using-usdprim-and-usdattribute-apis-in-usdrt">
<h4>
Using UsdPrim and UsdAttribute APIs in USDRT
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="n">stage
<span class="n">prim
<span class="n">attr
<span class="n">current_xform
<span class="n">new_xform
<span class="n">new_xform
<span class="n">attr
<section id="using-rtxformable-api-in-usdrt">
<h4>
Using RtXformable API in USDRT
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="n">stage
<span class="n">prim
<span class="n">xformable
<span class="n">attr
<span class="n">current_xform
<span class="n">new_xform
<span class="n">new_xform
## Using IFabricHierarchy Interface
```python
from usdrt import Gf, Sdf, Usd, hierarchy
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
current_xform = hier.get_local_xform(prim_path)
new_xform = Gf.Matrix4d(1)
new_xform.SetTranslateOnly((10, -15, 200))
hier.set_local_xform(prim_path, new_xform)
```
## Getting the last computed world transform value
The last computed world transform value for a prim can be retrieved directly from Fabric using Fabric or USDRT APIs.
### Using UsdPrim and UsdAttribute APIs in USDRT
```python
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(scene_path)
prim = stage.GetPrimAtPath(prim_path)
attr = prim.GetAttribute("omni:fabric:worldMatrix")
cached_world_xform = attr.Get()
```
### Using RtXformable API in USDRT
```python
from usdrt import Gf, Sdf, Usd, Rt
stage = Usd.Stage.Open(scene_path)
prim = stage.GetPrimAtPath(prim_path)
xformable = Rt.Xformable(prim)
attr = xformable.GetFabricHierarchyWorldMatrixAttr()
cached_world_xform = attr.Get()
```
## Getting the computed world transform of a prim
The IFabricHierarchy interface can compute the correct world transform of any prim, regardless of when the last call to `updateWorldXforms()` was made.
```python
from usdrt import Gf, Sdf, Usd, hierarchy
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
current_world_xform = hier.get_world_xform(prim_path)
```
## Set a computed local transform from a world transform value
The IFabricHierarchy interface can compute a local transform for a prim using the transforms of the ancestors of that prim, such that the new value transforms the prim to the desired transform in world space.
```python
from usdrt import Gf, Sdf, Usd, hierarchy
# Code block for setting computed local transform
```
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
result = hier.get_world_xform(path)
expected = Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 90, 0, 0, 1)
self.assertEqual(result, expected)
hier.set_world_xform(path, Gf.Matrix4d(1))
hier.update_world_xforms()
local_result = hier.get_local_xform(path)
local_expected = Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, -90, 0, 0, 1)
self.assertEqual(local_result, local_expected)
```
### Timesampled Transforms
Fabric does not have native support for USD timesamples - the StageReaderWriter is a snapshot of composed data on the stage at a single point in time.
Fabric Scene Delegate builds on top of Fabric by adding limited timesample support. Fabric Scene Delegate’s population utilities will listen for changes to the timeline in Kit, and populate timesampled attributes into Fabric at the time selected in the playback timeline, overwriting any previously existing value in Fabric. This is the case for timesampled transforms as well.
IFabricHierarchy will update calculate and update `omni:fabric:worldMatrix` for transform hierarchy descendants of any prims with timesampled transforms whose values are updated by Fabric Scene Delegate population when `updateWorldXforms()` is called.
### Backward Compatibility Layer
In order to support existing OmniHydra applications, a degree of backwards compatibility has been added to help developers bridge the gap to the new interface and transform attributes.
If these attributes exist and have been modified since the last call to `updateWorldXforms()` …
- `_worldPosition`
- `_worldOrientation`
- `_worldScale`
…then their values will be used to calculate and set the corresponding `omni:fabric:localMatrix` value for the prim at the beginning of the next `updateWorldXforms()` call.
Similarly, if a `_localMatrix` attribute exists and was modified since the last call to `updateWorldXforms()`, then its value will be copied directly to `omni:fabric:localMatrix` for the prim.
This fallback behavior adds calculation overhead and will be more expensive than writing `omni:fabric:localMatrix` directly. It is recommended that developers update to the new interface for the best performance with transforms in Fabric.
### Behavior when writing `omni:fabric:worldMatrix`
While `omni:fabric:worldMatrix` is not intended to be modified outside the IFabricHierarchy implementation, Fabric does not provide attribute permissions or other concepts, so it is possible to write the `omni:fabric:worldMatrix` value at any time using USDRT or Fabric APIs. In the event that this happens, it will
be inferred that this is a new target world transform for the prim,
and IFabricHierarchy will compute a new
```code
omni:fabric:localMatrix
```
value at the start of the next
```code
updateWorldXforms()
```
call. In
addition to being expensive to compute, it is also potentially
incorrect in the event that several of these attributes were
modified in a hierarchically dependent way - there is no way to
unravel an intended order of operations for calculating the new
```code
omni:fabric:localMatrix
```
attributes. | 16,076 |
faq.md | # Frequently Asked Questions
## What’s the difference between a Python node and a C++ node?
From the user’s point of view there isn’t really a difference. They both behave the same way, have the same types of attributes, store their data in Fabric, and are backed by USD. The real difference is on the node writing side. C++ is generally more difficult to write as it has strong typing requirements and less flexible data structures. On the other hand it is much more performant. A C++ node will often be an order of magnitude faster than an equivalent Python node.
## Once I choose Python or C++ for my node am I stuck with it?
No indeed! The architecture is set up so that the definition of the authoring graph, described in the .ogn file, is independent of its implementation. You can quickly prototype a node using Python so that you can try out your ideas, and then later if you want to speed it up you can rewrite the node implementation in C++ without touching the .ogn file and anyone that uses that node will invisibly benefit from the faster performance. | 1,066 |
fat-package_packaging_app.md | # Package App
## Production Build
### Set Application Version
The Application version can be set in `.\tools\VERSION.md`. This version will be used in for example the Application title bar but also in places such as the Omniverse Launcher’s `description.toml` file where a launcher package created as detailed below.
### Cleaning up
Packages are created from the contents of the `_build` directory. The kit-app-template repo comes with some Application and Extension examples, and we have created a couple of new ones along the way. This is a tutorial so it’s okay if we have some extra files; however, for production development the project should only contain elements that are intended to be released. The following instructions are intended to help with creating a clean build - but not critical for the tutorial.
1. Assuming we want to package just the `my_company.usd_explorer` app, make sure the `.\premake5.lua` only has the `define_app("my_company.usd_explorer")` entry in the `-- Apps` section.
2. Make sure these dependencies are not part of the Application kit file:
- `omni.kit.window.extensions`
- `omni.kit.debug.vscode`
3. For any Extension that should NOT be included - such as `omni.hello.world` - the Extension specific `premake5.lua` file can be either deleted or fully commented out:
```c++
-- Use folder name to build Extension name and tag.
-- local ext = get_current_extension_info()
-- project_ext(ext)
-- Link only those files and folders into the Extension target directory
```
-- repo_build.prebuild_link {"docs", ext.target_dir.."/docs"}
-- repo_build.prebuild_link {"data", ext.target_dir.."/data"}
-- repo_build.prebuild_link {"omni", ext.target_dir.."/omni"}
4.
- Delete the `_build` directory - either manually or by running `build -c`.
- Run `build`.
Note that the build directory only has `.bat` and `.sh` files for the Application we’re wanting to package - with the addition of a few created by default.
Locking Extension Versions
=========================
The build command is used throughout this tutorial. Before creating a package for distribution of the app, it is recommended to lock the Extension versions. There’s no harm in doing this with iterative builds during development as well - but more important prior to releasing an app.
1. Open the `.\repo.toml` file.
2. Edit the kit file(s) that should have locked Extension versions in the `[repo_precache_exts]` section. For the `my_company.usd_explorer` app, change the `apps` setting to the below:
```c++
[repo_precache_exts]
# Apps to run and precache
apps = [
"${root}/source/apps/my_company.usd_explorer.kit"
]
```
3. Add Extension versions by running the command `repo precache_exts -u`.
4. Note the section labeled `BEGIN GENERATED PART` in `my_company.usd_explorer.kit` - this is where Extension versions are locked down.
We now have a clean version locked build ready to be packaged.
Note
====
Reference: [Building an App](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html)
Warmup Script
=============
When an end user installs an Application we can provide a `warmup procedure` that caches shaders and does a few other things to improve the Application startup performance. This is an optional step and is most relevant to packages published via an Omniverse Launcher.
1. Open `.\kit-app-template\premake5.lua`.
2. Note this section:
```lua
-- App warmup script for the Launcher
create_app_warmup_script("omni.usd_explorer", {
args = "--exec \"open_stage.py ${SCRIPT_DIR}exts/omni.usd_explorer.setup/data/BuiltInMaterials.usda\" --/app/warmupMode=1 --no-window --/app/extensions/excluded/0='omni.kit.splash' --/app/extensions/excluded/1='omni.kit.splash.carousel' --/app/extensions/excluded/2='omni.kit.window.splash' --/app/settings/persistent=0 --/app/settings/loadUserConfig=0 --/structuredLog/enable=0 --/app/hangDetector/enabled=0 --/crashreporter/skipOldDumpUpload=1 --/app/content/emptyStageOnStart=1 --/app/window/showStartup=false --/rtx/materialDb/syncLoads=1 --/omni.kit.plugin/syncUsdLoads=1 --/rtx/hydra/materialSyncLoads=1 --/app/asyncRendering=0 --/app/file/ignoreUnsavedOnExit=1 --/renderer/multiGpu/enabled=0 --/app/quitAfter=10"
})
```
3. By including this section for the app, an additional
```
[app name].warmup.bat\.sh
```
is added in the build. Go ahead and change
```
omni.usd_explorer
```
to
```
my_company.usd_explorer
```
(there’s two places):
```c++
-- App warmup script for the Launcher
create_app_warmup_script("my_company.usd_explorer", {
args = "--exec \"open_stage.py ${SCRIPT_DIR}exts/my_company.usd_explorer.setup/data/BuiltInMaterials.usda\" --/app/warmupMode=1 --no-window --/app/extensions/excluded/0='omni.kit.splash' --/app/extensions/excluded/1='omni.kit.splash.carousel' --/app/extensions/excluded/2='omni.kit.window.splash' --/app/settings/persistent=0 --/app/settings/loadUserConfig=0 --/structuredLog/enable=0 --/app/hangDetector/enabled=0 --/crashreporter/skipOldDumpUpload=1 --/app/content/emptyStageOnStart=1 --/app/window/showStartup=false --/rtx/materialDb/syncLoads=1 --/omni.kit.plugin/syncUsdLoads=1 --/rtx/hydra/materialSyncLoads=1 --/app/asyncRendering=0 --/app/file/ignoreUnsavedOnExit=1 --/renderer/multiGpu/enabled=0 --/app/quitAfter=10"
})
```
4. Run a build.
5. A
```
my_company.usd_explorer.warmup.bat\.sh
```
file was created in the build directory.
6. To prepare for a Launcher package, open
```
.kit-app-template\source\launcher\launcher.toml
```
.
7. Note the per platform
```
post-install = ""
```
entries. Edit these settings to provide the warmup script (the default has them commented out):
```toml
[defaults.windows-x86_64.install]
...
post-install = "${productRoot}/my_company.usd_explorer.warmup.bat"
...
[defaults.linux-x86_64.install]
...
post-install = "${productRoot}/my_company.usd_explorer.warmup.sh"
...
```
## Fat Package
A “fat” package includes **everything** to run the app: Kit Kernel and all Extensions. This package type should be used when the goal is to not require an end user to have to download anything at time of installation. This type of package is suitable for environments that do not have access to public repositories - such as air gapped organizations.
1. Create a production build.
2. Run `repo package` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
## Thin Package
A “thin” package contains the **bare minimum** required for an installation to be possible - but requires the ability to download Kit Kernel and Extensions when the app is installed.
Installed thin packaged apps make use of shared storage of Kit Kernel and Extensions. This approach optimizes the use of local storage - only downloading components that have not already been downloaded by other thin packaged apps. This package type is not suitable for air gapped environments.
1. Create a production build.
2. Run `repo package --thin` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
installation if they are not already installed from some prior installation.
The package can be renamed - nothing inside the package depends on the package name- and be
published.
## Launcher Package
Omniverse Launcher is an Application for distributing solutions to Omniverse users. This project has tools to create
an Application package that can be installed via the IT Managed Launcher. The package can be “fat” or “thin” as mentioned above -
but will also contain additional metadata so that end users can see it within the Launcher.
There are source files within this project that are used for this kind of a package - you’ll find them in `.\source\launcher`.
### Launcher Data
File: `.\source\launcher\launcher.toml`.
This file provides settings for the Launcher used at installation. Be sure to set the `entrypoint` and `command` fields
for Windows and/or for Linux to the `.bat` and `.sh` files launching your Application.
Example for `my_company.usd_explorer` app:
```toml
## install and launch instructions by environment
[defaults.windows-x86_64]
...
entrypoint = "${productRoot}/my_company.usd_explorer.bat"
...
[defaults.windows-x86_64.open]
command = "${productRoot}/my_company.usd_explorer.bat"
...
[defaults.windows-x86_64.install]
...
[defaults.linux-x86_64]
url = ""
entrypoint = "${productRoot}/my_company.usd_explorer.sh"
...
```
### Images
The following images inside `.\source\launcher` should be updated according to the intended branding:
- `background.png`
- `card.png`
- `icon.png`
- `icon_ovc.png`
- `image.png`
Do NOT change the resolution of these images.
### Metadata
File: `.\source\launcher\description.toml`.
#### Version
If you leave `version = "${version}"` then the version label will be injected automatically using
version mentioned in `.\tools\VERSION.md`. It could also be written “manually” here if that is desirable.
#### Slug
A critical entry in this file is the `slug`. The `slug` is an identifier that is not used by the UI.
Keep this the same for all versions of the app so that users can see updates and versions in a single place:
```toml
#unique identifier for component, all lower case, persists between versions
slug = "my_company.usd_explorer"
```
#### URL
Another critical entry is the `[url]`: only define the platform(s) supported by the package you are creating.
For example, remove the `windows-x86_64` entry if only Linux is supported by the given package.
```toml
[url]
```
windows-x86_64 = 'windows-x86_64/package.zip'
linux-x86_64 = 'linux-x86_64/package.zip'
```
## Launcher UI Data
Here are other metadata fields to use in
```toml
description.toml
```
which are used in the Launcher UI:
- The `Publisher` and `Developer` metadata are *sections* in the toml file; for example:
```toml
[developer]
#name of developer
name = 'My Company'
# hyperlink on developer name (can be left as empty string)
url = 'https://www.my-company.com/'
[publisher]
#name of publisher
name = 'My Company'
# hyperlink on publisher name (can be left as empty string)
url = 'https://www.my-company.com/'
```
- You can add as many `[[links]]` as you’d like.
```toml
[[links]]
title = "My Page"
url = "https://www.my-page.com/"
```
File:
```toml
.\source\launcher\requirements.toml
```
This defines the system requirements for your Application to be used. This metadata is shown
in the `EXCHANGE` section underneath the metadata provided by `description.toml`; for example:
## Command to Package
1. Create a production build.
2. Run `repo package --launcher` or `repo package --launcher --thin` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
The top level package structure is the same whether the `--thin` argument was used or not:
```
linux-x86_64
package.zip
windows-x86_64
package.zip
background.png
description.toml
icon.png
icon_ovc.png
image.png
requirements.toml
```
What varies is what is inside the `package.zip`. This is where the “thin” or “fat” packaged Application ends up.
The Linux and/or Windows version can be included in the same package. A workstation build can of course only
generate one or the other so if both are to be delivered together you’ll have to manually construct one archive from
two packages.
The package can be renamed - nothing inside the package depends on the package name- and be published.
## Preview in Launcher
Omniverse Launcher (both the *Workstation* and *IT Managed Launcher*) supports installing Applications via commands.
Here’s how to install the package to preview and make sure it is displayed correctly:
1. Make sure an Omniverse launcher is installed.
2. Open up a shell and execute the following (with the appropriate absolute filepath for the zip file):
- **Windows**: `start omniverse-launcher://install?path="C:\my_company.usd_explorer.zip"` command cheat-sheet
- **Linux**: `xdg-open omniverse-launcher://install?path="/home/my_username/my_company.usd_explorer.zip"` command cheat-sheet
3. The Launcher shows an installation progress bar.
4. Once installation is complete, the Application is listed in the `Library` tab’s `Apps` section.
**Note**
Reference: Workstation Launcher
Reference: IT Managed Launcher
## Omniverse Cloud
If you are not familiar with Omniverse Cloud (OVC) then you can read more here.
To package an Application for OVC, use the `repo package --launcher` command mentioned above. This will create the necessary “fat launcher” package. | 12,538 |
fat-package_publish_app.md | # Publish App
## Fat Package
1. Extract the package.
2. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Thin Package
1. Extract the package.
2. Run `pull_kit_sdk.bat` / `pull_kit_sdk.sh` in the root directory of the extracted package (requires Internet access). **This only has to be done once** - not every time a user wants to start the app.
3. Run the optional Application warmup script `[app name].warmup.bat` / `[app name].warmup.sh` if it was created.
4. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Launcher Package
Launcher packages can be installed via the Omniverse Launcher. The archive should NOT be unzipped prior to installation.
1. Make sure an Omniverse launcher is installed.
2. Open up a shell and execute the following (with the appropriate absolute filepath for the zip file):
- **Windows**: `start omniverse-launcher://install?path="C:\my_company.usd_explorer.zip"` [command cheat-sheet](commands.html#omniverse-launcher-installation)
- **Linux**: `xdg-open omniverse-launcher://install?path="/home/my_username/my_company.usd_explorer.zip"`
- **command cheat-sheet**
- The Launcher shows an installation progress bar.
- Once installation is complete, the Application is listed in the `Library` tab’s `Apps` section.
::: note
**Note**
Reference: IT Managed Launcher (installation instructions applies also to Workstation Launcher)
::: | 1,481 |
files.md | # Files
- [8fa04669143f4cb0/_build/target-deps/hoops_exchange_cad_converter_release/hoops_exchange_cad_converter/include/hoops_reader/CADConverterSpec.h](file_8fa04669143f4cb0__build_target-deps_hoops_exchange_cad_converter_release_hoops_exchange_cad_converter_include_hoops_reader_CADConverterSpec.h.html#c-a-d-converter-spec-8h) | 331 |
file_omni_avreality_rain_IPuddleBaker.h.md | # omni/avreality/rain/IPuddleBaker.h
In directory:
omni/avreality/rain
Source file:
omni/avreality/rain/IPuddleBaker.h
## Classes
- **omni::avreality::rain::IPuddleBaker**: Bakes puddle into dynamic textures.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** | 287 |
file_omni_avreality_rain_IWetnessController.h.md | # omni/avreality/rain/IWetnessController.h
In directory:
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/IWetnessController.h
```
## Classes
- **omni::avreality::rain::IWetnessController**: Controller scene level wetness parameters.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** | 326 |
file_omni_avreality_rain_PuddleBaker.h.md | # omni/avreality/rain/PuddleBaker.h
In directory:
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/PuddleBaker.h
```
## Classes
- **omni::avreality::rain::PuddleBaker**: Bake puddles into dynamic textures.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain**
``` | 302 |
file_omni_avreality_rain_WetnessController.h.md | # omni/avreality/rain/WetnessController.h
In directory:
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/WetnessController.h
```
## Classes
- **omni::avreality::rain::WetnessController**: Controller for scene level wetness parameters.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** | 327 |
flow-omniverse-fluid-dynamics_index.md | # flow: Omniverse Fluid Dynamics
## FlowUsd :package:
Repository created: 2022-06-24 by jcarius
This is the repository home for building FlowUSD and its USD schema in the same repository.
The `master` branch remains unchanged from the kit-extension template repository to allow for occasional merging.
This README file provides a quick overview. In-depth documentation can be found at:
📖 [FlowUSD Documentation](#)
Teamcity Project
## Building
To build everything run `.\build.bat` or `.\build.bat --rebuild`
To build the FlowUsd kit extensions run `.\buildExtensions.bat`
## Run
`.\_build\windows-x86_64\release\omni.app.flowusd.bat`
## Testing
`repo.bat test`
## Packaging and publishing
### Kit Extension Registry
To publish extension to the extension registry `.\repo.bat publish_exts`.
This will publish all extensions as configured in the repo.toml.
Note that existing versions should not be overridden, so increment the version in the respective `extension.toml` first before publishing.
More fine-grained control/manual publishing is possible with `.\_build\windows-x86_64\release\omni.app.flowusd.bat --publish omni.usd.schema.flow`.
Note that publishing needs to be run both from windows and linux.
The packages in the registry are automatically named with version and platform information, e.g., publishing `omni.flowusd` version `0.3.0` on windows yields `omni.flowusd-0.3.0+wx64.r.cp37`.
To list published packages execute `.`
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--list-registry-exts
```
<p>
To un-publish (dangerous!) extensions:
<code class="docutils literal notranslate">
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--unpublish
```
```pre
omni.usd.schema.flow
```
<section id="packman-packaging">
<h4>
Packman packaging
<p>
<em>
Note: This is currently not used
<p>
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.usd.schema.flow
```
,
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.flowusd
```
<p>
This will place the packages in
<code class="docutils literal notranslate">
```pre
_build/packages
```
. Then
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
publish
```
will upload them to packman. This allows other kit projects to include flowusd in their target dependencies with
<div class="highlight-c++ notranslate">
<div class="highlight">
<pre><span>
<span class="w">
<span class="o"></
<section id="updating">
<h3>
Updating
<p>
This repo carries a number dependencies with fixed versions.
To update them proceed as follows:
<ul>
<li>
<p>
Packman.xml files in
<code class="docutils literal notranslate">
```pre
deps
```
: These should be updated by merging the newest version from
kit-template
.
Thanks to automatic repo mirroring the
<code class="docutils literal notranslate">
```pre
master
```
branch of this repository is synced with the kit-template repo. The commands for updating are hence
<div class="highlight-none notranslate">
<div class="highlight">
<pre><span>
git fetch origin master:master
git pull origin master:master
<p>
If there are conflicts due to changes to files that have been deleted in
<code class="docutils literal notranslate">
```pre
flowusd-master
```
, e.g., example packages, just accept the deleted version.
<li>
<p>
Don’t forget to update the changelog!
<section id="using-a-local-build-of-kit-sdk">
<h3>
Using a Local Build of Kit SDK
<p>
By default packman downloads Kit SDK (from
<code class="docutils literal notranslate">
```pre
deps/kit-sdk.packman.xml
```
). For developing purposes local build of Kit SDK can be used.
<p>
To use your local build of Kit SDK, assuming it is located say at
<code class="docutils literal notranslate">
```pre
C:/projects/kit
```
.
<p>
Use
<code class="docutils literal notranslate">
```pre
repo_source
```
tool to link:
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
link
```
```pre
c:/projects/kit/kit
```
<p>
Or you can also do it manually: create a file:
<code class="docutils literal notranslate">
```pre
deps/kit-sdk.packman.xml.user
```
containing the following lines:
<div class="highlight-xml notranslate">
<div class="highlight">
<pre><span>
<span class="nt"><dependency
<span class="nt"><source
<span class="nt"></dependency>
<span class="nt"></project>
<p>
To see current source links:
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
list
```
<p>
To remove source link:
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
unlink
```
```pre
kit-sdk
```
<p>
To remove all source links:
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
clear
```
<section id="using-a-local-build-of-another-extension">
### Using a Local Build of another Extension
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g.
```
\`\`\`
omni.app.my_app.kit
\`\`\`
example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using
```
\`\`\`
deps/user.toml
\`\`\`
. You can use that file to override any setting.
Create
```
\`\`\`
deps/user.toml
\`\`\`
file in this repo with the search to path to your repo added to
```
\`\`\`
app/exts/folders
\`\`\`
setting, e.g.:
```
\`\`\`toml
[app.exts]
folders."++" = [ "c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts" ]
\`\`\`
\`\`\`
repo source tool can also be used to create and edit
\`\`\`
user.toml
\`\`\`
. Provide a path to a repo or a direct path to an extension(s):
> \`\`\`
> repo source link [repo_path]
> \`\`\`
> - If repo produces kit extensions add them to
> \`\`\`
> deps/user.toml
> \`\`\`
> file.
> \`\`\`
> repo source link [ext_path]
> \`\`\`
> - If the path is a kit extension or folder with kit extensions add to
> \`\`\`
> deps/user.toml
> \`\`\`
> file.
Other options:
- Pass CLI arg to any app like this:
\`\`\`
--ext-folder c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts
\`\`\`
.
- Use *Extension Manager UI (Gear button)*.
- Use other
\`\`\`
user.toml
\`\`\`
(or other) configuration files, refer to Kit Documentation: Configuration.
You can always find out where an extension is coming from in *Extension Manager* by selecting an extension and hovering over the open button.
You can also find it in the log, by looking either for
\`\`\`
registered
\`\`\`
message for each extension or
\`\`\`
About to startup:
\`\`\`
when it starts.
### Other Useful Links
- See Kit Manual.
- See Kit Developer Documentation Index.
- See Anton’s Video Tutorials for Anton’s videos about the build systems. | 7,858 |
fonts.md | # Fonts
## Font style
It’s possible to set different font types with the style. The style key ‘font’ should point to the font file, which allows packaging of the font to the extension. We support both TTF and OTF formats. All text-based widgets support custom fonts.
```python
with ui.VStack():
ui.Label("Omniverse", style={"font":"${fonts}/OpenSans-SemiBold.ttf", "font_size": 40.0})
ui.Label("Omniverse", style={"font":"${fonts}/roboto_medium.ttf", "font_size": 40.0})
```
## Font size
It’s possible to set the font size with the style.
Drag the following slider to change the size of the text.
```python
def value_changed(label, value):
label.style = {"color": ui.color(0), "font_size": value.as_float}
slider = ui.FloatSlider(min=1.0, max=150.0)
slider.model.as_float = 10.0
label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0})
slider.model.add_value_changed_fn(partial(value_changed, label))
``` | 943 |
Framework.md | # Carbonite Framework
## Carbonite Framework
The key ingredient of Carbonite is what we call the Carbonite `carb::Framework`. It is the core entity which manages plugins and their interfaces. This guide describes the plugin management functionality of the Carbonite Framework. The Framework itself is versioned and when a plugin is loaded, the Framework ensures that its version is compatible with the Framework version that the plugin expects.
## Plugins
Plugins are dynamic libraries that provide one or more interfaces. An Interface is an API (with a versioned, stable ABI) that applications can use to access functionality in a plugin.
## About Interfaces and Authoring a Plugin
See the Guide for a walkthrough of authoring a plugin, and information about interfaces and versioning.
## Starting Carbonite
The Carbonite Framework is found in `carb.dll` (Windows), `libcarb.so` (Linux) or `libcarb.dylib` (Mac). You can either use the package-provided import library to import the functions from the Framework, or dynamically load and request the functions by name (rare).
### Declaration of Globals
The `OMNI_APP_GLOBALS` macro specifies the Carbonite application globals:
```c++
OMNI_APP_GLOBALS("example.windowing.native.app", "Native (C++) example app using example.windowing.");
```
This macro ensures that `g_carbClientName` is set to the Client name, and that the default logging channel is set up (the description provided is used as the description for the default logging channel).
Historically, this macro instantiated global variables such as `g_carbFramework` and `g_carbLogging`, but this was changed with Carbonite release v117.0 so that these variables are weakly-linked and need not be instantiated.
For backwards compatibility, older names of this macro exist: `CARB_GLOBALS_EX` (equivalent to `OMNI_APP_GLOBALS`).
## Starting the Framework
Starting the Framework is as easy as using the `OMNI_CORE_INIT` macro.
```cpp
int main(int argc, char** argv)
{
// Startup the Framework
OMNI_CORE_INIT(argc, argv);
carb::Framework* framework = carb::getFramework();
if (!framework)
return EXIT_FAILURE;
return runApp(framework);
}
```
Typically, command-line arguments are passed to the `OMNI_CORE_INIT` macro, but other options are available (see documentation).
This macro ensures that the Framework is acquired (calling `carb::acquireFramework()`), the Omniverse Native Interfaces subsystem is started (calling `omniCoreStart()`), and finally calls `carb::startupFramework()` to initialize the Framework.
The `carb::startupFramework()` function can potentially do a large amount of work. Based on parameters it can load the settings plugin, parse command-line options and environment variables, and register plugins indicated in the configuration file. Check the documentation for `carb::startupFramework()` for more information.
## Clients and Naming
Any entity which uses `carb::Framework` or is a plugin is a *Client*. This generally includes the Carbonite Application itself, as well as any plugins and other libraries (such as script bindings) that interact with the Carbonite Framework. All Clients must have **unique** Client Names as the Framework tracks usages and dependencies by these names. Carbonite Applications declare their Client Name in their Globals declaration. Plugins declare their Client Name in the `carb::PluginImplDesc` struct passed to the `CARB_PLUGIN_IMPL` macro. Script bindings declare their Client Name in their `CARB_BINDINGS` declaration.
If there are multiple definitions of the same interface, the general rule is to uniquely name each plugin by adding a qualifier after the interface name (e.g. *carb.profiler-cpu.plugin*, *carb.profiler-tracy.plugin*, etc.). This approach also means that you cannot have multiple implementations of the same interface in the same plugin (by design).
## 插件注册流程
插件在使用前必须先进行注册。当插件被注册时,会发生以下步骤:
- 使用 `carb::extras::loadLibrary()` 加载插件动态库。
- 如果动态库未被加载,这可能会导致静态初始化器的执行。
- 定位 `omniModuleGetExports()` 函数。如果找到此函数,该库是一个 Omniverse Native Interfaces 模块。插件加载停止,ONI 类型工厂接管。
- 定位并调用 `carbGetFrameworkVersion()` 函数(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)。这用于检查插件与框架之间的兼容性。
- 定位插件注册函数,按以下顺序检查:
1. `carbOnPluginRegisterEx2()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
2. `carbOnPluginRegisterEx()`(已弃用)
3. `carbOnPluginRegister()`(已弃用)
- 定位可选的 `carbGetPluginDeps` 函数(由 `CARB_PLUGIN_IMPL_DEPS` 或 `CARB_PLUGIN_IMPL_NO_DEPS` 宏在插件中实现)。
- 如果注册库将保持库加载(典型情况),则定位以下可选函数:
- `carbOnPluginPreStartup()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- `carbOnPluginPostShutdown()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- `carbOnPluginStartupEx()` 或 `carbOnPluginStartup()`(必要时手动实现)
- `carbOnPluginShutdown()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- **Shutdown Functions**
- `carbOnPluginShutdown()` (Manually implemented if necessary)
- `carbOnPluginQuickShutdown()` (Manually implemented if necessary)
- `carbOnReloadDependency()` (Manually implemented if necessary)
- **Plugin Registration**
- The plugin registration function found above (e.g. `carbOnPluginRegisterEx2`) is called, which gives the plugin information about the Framework and receives information about the plugin.
- The `carbGetPluginDeps` function is called if provided, informing the Framework about the Plugin’s dependencies.
- **Plugin Registration Methods**
- **Registered when starting the Framework**
- Plugins can be registered by `carb::startupFramework()`, typically called from `OMNI_CORE_INIT`.
- Parameters to `carb::startupFramework()` are passed in `carb::StartupFrameworkDesc` via `OMNI_CORE_INIT`.
- If a configuration file or string is passed to `carb::startupFramework()`, the function will attempt to register the specified plugins. See `carb::detail::loadPluginsFromConfig()` for a list of the settings keys and how they’re used.
- **Searching for Plugins Programmatically**
- The `carb::Framework::loadPlugins()` function uses `carb::PluginLoadingDesc` to describe how to search directories to locate and load plugins.
- This is the most common means of finding and loading plugins after startup.
- **Explicitly Registering a Plugin**
- The `carb::Framework::loadPlugin` function allows loading a specific plugin, given the path. This option is rarely used.
- **Registering a Static Plugin**
- In rare cases, an application can register a plugin that actually exists in the application or a plugin. This is accomplished through the `carb::Framework::registerPlugin` function. Plugins registered via this method are never unloaded when their interfaces are released; instead they must be explicitly unloaded with `carb::Framework::unregisterPlugin`.
## Loading Plugins
Typically when a plugin is found, it is loaded immediately. This means the dynamic library is loaded and static initializers within the library will run, and the Framework will locate and call functions exported by the plugin that the Framework uses to discover information about the plugin as described above.
However, if carb::PluginLoadingDesc::unloadPlugins is true, the plugin will be loaded to gather information, but immediately unloaded until an interface is requested. This is rare as it is not the default option. In some cases, the OS loader could choose to keep the library loaded, in which case a warning is logged.
## Acquiring Interfaces
Acquiring an interface gives you an ABI-stable API that you can use to access plugin functionality. Once a plugin is registered and loaded, the Framework will be able to provide interfaces from it.
The first time an interface is acquired from a registered plugin, the plugin is started. To do this, the Framework calls carbOnPluginStartupEx() (or carbOnPluginStartup()). If startup succeeds, the Framework will provide interfaces from the plugin back to the caller.
### getCachedInterface
This is the preferred means of acquiring an interface. Since carb::Framework::tryAcquireInterface does a lot of checking, it can be expensive when repeatedly called (plus, it produces log messages). In order to provide a very cheap way to cache an interface, carb::getCachedInterface() is provided. This is conceptually similar to:
```cpp
// NOTE: Do not actually do this; use carb::getCachedInterface<carb::dictionary::IDictionary>() instead.
static auto dictionary = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>();
```
However, unlike static, getCachedInterface() will reset its internal pointer to nullptr when the interface (or the Framework) has been released; calling getCachedInterface() after this point will attempt to re-acquire the interface.
The interface acquired will be from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats). Given the template nature of carb::getCachedInterface(), specifying a plugin requires some special handling in the form of a global char array:
```cpp
const char sGamma[] = "carb.frameworktest.gamma.plugin";
FrameworkScoped f;
f.loadPlugins({"carb.frameworktest.*.plugin"});
auto iface = carb::getCachedInterface<carb::frameworktest::FrameworkTest, sGamma>();
REQUIRE(iface);
CHECK_EQ(iface->getName(), "gamma");
```
## tryAcquireInterface
### tryAcquireInterface
The most common method of acquiring an interface (and the method used by `carb::getCachedInterface()`) is `carb::Framework::tryAcquireInterface`:
```cpp
// Acquire the IDictionary interface (typically this would be carb::getCachedInterface() instead):
carb::dictionary::IDictionary* dict = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>();
```
If the interface is not available `nullptr` is returned. To debug why an interface cannot be acquired, use verbose logging.
The Framework provides the interface from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats):
```cpp
auto profiler = carb::getFramework()->tryAcquireInterface<carb::profiler::IProfiler>("carb.profiler-cpu.plugin");
```
**Warning**
As `carb::Framework::tryAcquireInterface` does some level of work for each call with potential logging, it is highly recommended to instead use `carb::getCachedInterface()` instead.
## acquireInterface
### acquireInterface
**Warning**
This function should only be used within plugins and only for interfaces which are declared as dependencies (with `CARB_PLUGIN_IMPL_DEPS`). If it fails to acquire an interface, an error log is issued; this cannot happen for declared dependencies within a plugin as the plugin will fail to load if the dependencies cannot be acquired.
`carb::Framework::acquireInterface` is similar to `carb::Framework::tryAcquireInterface`, but will issue an error log message if the interface cannot be acquired. It will also warn if a Client requests an interface that is not declared as a dependency with `CARB_PLUGIN_IMPL_DEPS`.
Interfaces provided by the same plugin that is acquiring it will not result in any log or warning messages, and need not (nor can be) specified as a dependency.
Generally this method should be avoided unless it is guaranteed that the interface would be available, either by declared dependency or by also being provided by the same plugin.
The Framework provides the interface from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats):
```cpp
auto profiler = carb::getFramework()->acquireInterface<carb::profiler::IProfiler>("carb.profiler-cpu.plugin");
```
## Acquiring an Interface
To acquire an interface, you can use either `carb::Framework::tryAcquireInterface` or `carb::getCachedInterface()`.
## Acquiring an Interface from a Specific Plugin
### Acquiring an Interface from a Specific Plugin
, `carb::Framework::tryAcquireInterface` and `carb::Framework::acquireInterface` all allow specifying the client name of a plugin (e.g. “carb.profiler-cpu.plugin”) to acquire the interface from a specific plugin.
In most cases, while multiple plugins may provide the same interface, there is nuance to usage. The Profiler example stands here as the profilers require external tools (carb.profiler-tracy.plugin or carb.profiler-nvtx.plugin), or in the case of the serializers (carb.dictionary.serializer-toml.plugin or carb.dictionary.serializer-json.plugin) read and write completely different file types. So while the contract specified by the interface definition is consistent, additional care and programming is generally necessary in using them.
The load order may be non-deterministic and seemingly random. It is generally considered good practice if multiple plugins provide a given interface to set a default plugin.
It is also possible to acquire an interface from the path to the dynamic library file itself. If the dynamic library is not a known plugin, it is registered as a new plugin and loaded. This is accomplished with the `carb::Framework::tryAcquireInterfaceFromLibrary()` function.
## Acquiring an Interface from the Same Plugin as Another Interface
### Acquiring an Interface from the Same Plugin as Another Interface
As a very rare case, it may be desirable to acquire an interface exported by the same plugin as a different interface. To accomplish this, alternate versions of `carb::Framework::acquireInterface` and `carb::Framework::tryAcquireInterface` exist that take any interface pointer.
## Client Spoofing
### Client Spoofing
This is very rarely needed.
Using internal functions, it is possible to “spoof” a plugin. That is, your plugin or application can instruct the Framework to acquire an interface as if it were a different plugin requesting. This is useful for modifying unload order by notifying the Framework of a dependency between two plugins:
```c++
// acquire beta as if we are alpha
auto beta2AsAlpha = static_cast<FrameworkTestSecond*>(f->acquireInterfaceWithClient(
"carb.frameworktest.alpha.plugin", interfaceDesc2, "carb.frameworktest.beta.plugin"));
CARB_UNUSED(beta2AsAlpha);
// acquire gamma2 as if we are beta
auto gamma2AsBeta = static_cast<FrameworkTestSecond*>(f->acquireInterfaceWithClient(
"carb.frameworktest.beta.plugin", interfaceDesc2, "carb.frameworktest.gamma.plugin"));
CARB_UNUSED(gamma2AsBeta);
// acquire gamma as if we are alpha
auto gammaAsAlpha = static_cast<FrameworkTest*>(f->acquireInterfaceWithClient(
"carb.frameworktest.alpha.plugin", interfaceDesc, "carb.frameworktest.gamma.plugin"));
CARB_UNUSED(gammaAsAlpha);
```
## Try Acquiring an Interface Without Loading
This is very rarely needed. It may be needed in circumstances where a circular dependency exists between interfaces and the Framework chooses to shut down a dependent interface prior to plugin shutdown (carbOnPluginShutdown()).
All of the above options will make an attempt to load the plugin in order to acquire the interface. Sometimes this is undesirable–the interface should only be acquired if its plugin is already loaded and the interface acquired elsewhere. This can be accomplished via the carb::Framework::tryAcquireExistingInterface() function.
This is the case in the Profiler system where Settings is used only if it is already available. This is necessary because the Profiler could be loading and it is dangerous to try to load Settings recursively.
```cpp
// Don't try to load settings, but if it's already available we will load settings from it.
auto settings = g_carbFramework->tryAcquireExistingInterface<settings::ISettings>();
```
## Default Plugins
In some cases, it is reasonable to have multiple options for interfaces. A typical example is carb::profiler::IProfiler which is provided by multiple Carbonite plugins: *carb.profiler-cpu.plugin*, *carb.profiler-tracy.plugin*, and *carb.profiler-nvtx.plugin*.
There are multiple ways of declaring the default plugin.
### Version
The *implicit* default plugin is the Framework’s earliest registered match for the highest compatible version for the requested interface. In order to be a compatible version, the *major* version of the plugin’s interface must match the major version of the requested interface, and the *minor* version of the plugin’s interface must be greater-than-or-equal to the minor version of the requested interface.
### Configuration
The configuration file may have a `/defaultPlugins` key that specifies plugin names. See carb::detail::setDefaultPluginsFromConfig() for more information. Note that a listed plugin will become the default for *all* interfaces that it provides.
### Programmatically
An application or plugin may specify a plugin to use as default with the carb::Framework::setDefaultPlugin() function.
For this function to be useful, it must be called to register a default plugin before the interface in question is acquired by *any* clients. This should be done as close to Framework startup as possible.
### Overriding
As mentioned above, the carb::Framework::tryAcquireInterface and carb::Framework::acquireInterface functions allow explicitly providing a plugin name to acquire the interface from that plugin. This will ignore any default plugin.
## Releasing Interfaces
When you acquired a particular interface, carb::Framework tracks this using client name. Usually you don’t need to explicitly release an interface you use. When the plugin is unloaded, all interfaces it acquired are released.
That being said, you can explicitly release with the carb::Framework::releaseInterface function.
When an interface is no longer needed, it can be released using the `releaseInterface` function.
When an interface was acquired by a client, this information is stored in `carb::Framework`. Multiple acquire calls do **not** add up. This means that:
```cpp
IFoo* foo = framework->acquireInterface<IFoo>();
IFoo* foo2 = framework->acquireInterface<IFoo>();
IFoo* foo3 = framework->acquireInterface<IFoo>();
framework->releaseInterface(foo);
```
will release all `foo`, `foo2`, `foo3`, which actually all contain the same pointer value.
Remember that a plugin can implement multiple interfaces. Every interface can be used by multiple clients. Once all interfaces are released by all clients (explicitly or automatically) the plugin is unloaded.
## Unloading Plugins
Once all interfaces to a plugin are released, the plugin is automatically unloaded. However, if a plugin never had any interfaces acquired from it, it remains loaded. It can be explicitly unloaded by plugin name with `carb::Framework::unregisterPlugin` or by library path with `carb::Framework::unloadPlugin`, but given the automatic unloading, this is typically not necessary for dynamic plugins.
Both of these functions also unregister the plugin, so attempting to acquire an interface from it again will not work without re-registering.
It is also possible to unload all plugins with `carb::Framework::unloadAllPlugins`. This is typically done automatically when the Framework is released.
## Plugin Dependencies
Plugins may declare dependencies on interfaces that are required to be available before the plugin. An example of this is *carb.settings.plugin* which is dependent upon *carb.dictionary.plugin*. These are specified with `CARB_PLUGIN_IMPL_DEPS` generally immediately following the `CARB_PLUGIN_IMPL` use:
```cpp
const struct carb::PluginImplDesc kPluginImpl = {"carb.settings.plugin", "Settings storage", "NVIDIA", carb::PluginHotReload::eDisabled, "dev" };
CARB_PLUGIN_IMPL(kPluginImpl, carb::settings::ISettings)
CARB_PLUGIN_IMPL_DEPS(carb::dictionary::IDictionary)
```
In this case, when `carb::getCachedInterface<carb::settings::ISettings>()` executes for the first time, before initializing *carb.settings.plugin*, the Framework will first try to acquire `carb::dictionary::IDictionary` from an available plugin (typically *carb.dictionary.plugin*). Missing dependencies will cause a plugin load to fail, and `nullptr` will be returned as the requested interface could not be acquired.
Carbonite provides a command-line tool, *plugin.inspector* which, given a particular plugin library, can list which interfaces it depends on. Example:
```bash
plugin.inspector.exe carb.assets.plugin.dll
```
Its output:
```json
{
}
```
Listing an interface as a dependency allows your plugin to use `carb::Framework::acquireInterface` (as opposed to `carb::Framework::tryAcquireInterface`) without any fear of error logging or `nullptr` returns.
A best practice is to only list interfaces as dependencies if your plugin cannot function without them. Other interfaces can be considered optional and your plugin can handle the case where the interface is not available. An example of this is `carb.settings.plugin` which requires `carb::dictionary::IDictionary` (and lists it as a dependency as seen above), but `carb.profiler-cpu.plugin` can function just fine without `carb::settings::ISettings`; it merely applies default settings. In this case, `carb::settings::ISettings` is not listed as a dependency in `CARB_PLUGIN_IMPL_DEPS` but the plugin uses `carb::Framework::tryAcquireInterface` and handles the case where `nullptr` is returned.
It’s important to note that dependencies are per plugin and set by the plugin author. Different plugins might implement the same interface, but have different dependencies.
Circular explicit dependencies are not allowed. Having two plugins that are dependent on interfaces from each other will result in an error log message and `nullptr` return from `carb::Framework::acquireInterface`. However, it is perfectly reasonable to allow circular use of interfaces that are acquired optionally upon first use. In this case, do not list the interface in `CARB_PLUGIN_IMPL_DEPS` and use `carb::Framework::tryAcquireInterface` when needed, sometime after startup (i.e. when `carbOnPluginStartup()` is called).
CARB_PLUGIN_IMPL_DEPS specifies explicit dependencies, but any use of carb::Framework::acquireInterface or carb::Framework::tryAcquireInterface (or any of the variations) notifies the Framework of an implicit dependency. The Framework uses this information to determine the order in which plugins should be unloaded.
In general, the Framework will try to unload dependencies after the plugin in which they’re required. In other words, given our example of carb.settings.plugin dependent on carb::dictionary::IDictionary (typically from carb.dictionary.plugin), the Framework would attempt to unload carb.settings.plugin before the plugin providing IDictionary. This allows carb.settings.plugin to continue using IDictionary until it is fully shut down, at which point IDictionary can be shut down.
Since circular usage is allowed (and therefore, circular implicit dependencies), the Framework may not be able to satisfy the above rule. In this case, the Framework will unload in reverse of load order (unload most recently loaded first).
Unload ordering is very complicated and requires that the Framework have an understanding of the explicit and implicit dependencies of all loading plugins. Because acquiring an interface is an implicit dependency, whenever an interface is acquired the Framework will re-evaluate the unload order and log it out (Verbose log level). Turning on Verbose logging can help diagnose unload ordering issues.
## Versioning
The Carbonite Framework uses the concept of semantic versioning to determine a plugin’s compatibility with the Framework, and whether an interface provided by a plugin is compatible with an interface request. Carbonite uses major and minor version numbers to do this:
- The major version number of the candidate must match the major version of the request.
- The minor version number of the candidate must be greater-than-or-equal to the minor version of the request.
Carbonite expresses its concept of a version with the carb::Version struct and checking with comparison operators and the carb::isVersionSemanticallyCompatible() function.
### Framework Compatibility
When a plugin is registered with the Framework, the Framework will find and execute the carbGetFrameworkVersion() function exported by the plugin. This is the version of the Framework that the plugin was built against. In this case, the plugin is considered the requestor and the Framework is considered the candidate. Therefore, the Framework minor version must be greater-than-or-equal the minor version returned by carbGetFrameworkVersion() (and the major versions must match exactly).
If the Framework determines that the plugin is not compatible with it, it will refuse to load.
In order to support plugins compiled at different times, the Carbonite dynamic library will honor multiple versions of the Carbonite Framework. The latest Carbonite version is available as carb::kFrameworkVersion.
### Interface Compatibility
For the many variations on acquiring an interface, a version check is also performed. The Client that calls carb::Framework::tryAcquireInterface (for example) is considered the requestor. The plugins that have been registered with the Framework provide interfaces that are considered the candidates. Every interface has a
InterfaceType::getInterfaceDesc()
function that is generated by the
CARB_PLUGIN_INTERFACE
or
CARB_PLUGIN_INTERFACE_EX
macros (example function:
carb::tasking::ITasking::getInterfaceDesc()
).
The
carb::Framework::tryAcquireInterface
(for example) is a templated inline function that takes the interface type as its template parameter
T
and will call
InterfaceType::getInterfaceDesc()
to provide the interface name and semantic version to the Framework at interface acquire time.
When a plugin or application is built, this inline function is written into a compilation unit and captures the name and version
that the plugin or application knew about when it was built. This information forms the
*request*.
At runtime, the plugin or application passes the interface name and version information that it was built with. If a specific
plugin was given, the Framework checks only that plugin; otherwise the
default plugin
is used (if
no default plugin has been specified or identified, the Framework will select the first registered plugin — in registration
order — with a greater-than-or-equal version to the interface version requested). From this plugin, the Framework will
check to see if an interface candidate is exported whose
*major*
version matches exactly and whose
*minor*
version is
greater-than-or-equal to the requested minor version.
If the version of the candidate has a higher
*major*
version, the Framework will ask the plugin if it can create an interface
for the requested version. This only happens if the plugin supports multiple interface versions.
If no matches are found,
nullptr
is returned to the caller. | 26,671 |
Function.md | # Omni Function
## Omni Function
The `omni::function` is an ABI safe, DLL boundary safe polymorphic function intended to be used in [Omniverse Native Interfaces](../OmniverseNativeInterfaces.html) that provides the functionality of `std::function`. An `omni::function` satisfies `std::is_standard_layout`.
Standard usage is identical to `std::function`:
```cpp
// Basic usage of binding to a lambda expression:
omni::function<int(int)> f = [](int x) { return x + 1; };
assert(f(1) == 2);
// Or bind to a free function:
int double_it(int x)
{
return x * 2;
};
f = double_it;
assert(f(5) == 10);
// Closures are automatically captured:
auto& output = std::cout;
omni::function<void(omni::string)> print =
[&output](omni::string s)
{
output << s << std::endl;
};
print("A message");
void (*printfn)(char const*) =
[](char const* msg)
```
{
output << msg << std::endl;
};
// use of std::bind will also work:
print = std::bind(printfn, "Hello again!");
print();
## omni::function Features
### Relocatable
An `omni::function` is trivially relocatable. This is similar to trivially move constructible, in that `std::memcpy` is an acceptable substitute for actual move-construction, but with the qualification that the moved-from location does not get the destructor called.
> Note
> The examples in this section are demonstration only. You should prefer using the language-specific bindings for working with `omni::function`, like `operator()`, the copy and move constructors and assignment operators, and the destructor in C++.
```cpp
using function_type = omni::function<void()>;
using function_buf = alignas(function_type) char[sizeof(function_type)];
function_buf buf1, buf2;
new static_cast<void*>(buf1) function_type([] { std::println("Hello world\n"); });
// Relocate through memcpy is safe
std::memcpy(buf2, buf1, sizeof buf2);
// buf2 now acts as a function_type
(*reinterpret_cast<function_type*>(buf2))();
// Destroy through the relocated-to position, not the relocated-from
reinterpret_cast<function_type*>(buf2)->~function_type();
```
This concept is useful when interacting with C, where concepts like copy and move construction do not exist. When shared with C, an `omni::function` can be used with a byte-for-byte copy; no wrapper indirection is needed. This allows for natural usage.
```c
/* signature: omni_function omni_foo(void); */
omni_function fn = omni_foo();
/* signature: void my_own_code(omni_function f);
The backing structure is copied into the target, which is safe. */
my_own_code(fn);
omni_function_free(fn);
```
### Interaction with `std::function` and `std::bind`
Despite the lack of ABI safety for `std::function` and `std::bind`, `omni::function`s created using these facilities are...
ABI
safe.
Because
the
Standard
Library
implementations
are
inlined,
the
`omni::function`
will call code which is compatible with the compilation parameters of the binding site.
Function binding requires that certain targets create an unbound function wrappers.
For example, a function pointer which is null (`omni::function<void()>{static_cast<void(*)()>(nullptr)}`) or a function wrapper which is unbound (`omni::function<void()>{omni::function<void()>{nullptr}}`) both yield unbound `omni::function`s.
The implementation also understands `std::function`s, so binding an `omni::function` to an unbound `std::function` works as you would expect.
```cpp
std::function<void()> std_fn; // <- unbound
// The omni::function will be created unbound
omni::function<void()> omni_fn = std_fn;
if (!omni_fn)
printf("It works!\n");
```
This property is not commutative.
Since `std::function` does not understand `omni::function`, an `std::function` binding to an unbound `omni::function` will successfully bind to a target that can never be successfully called.
```cpp
omni::function<void()> omni_fn; // <- unbound
// The std::function will be bound to call the unbound omni::function
std::function<void()> std_fn = omni_fn;
if (std_fn)
std_fn(); // <- calls the unbound omni_fn
```
If conversion from `omni::function` to `std::function` is required, the `omni::function` should be checked to see if it is bound first.
> Note
> This conversion can not be done implicitly because of the `std::function` constructor which accepts a universal reference to bind to (C++ Standard 2020, §22.10.17.3.2/8).
> Conversion operators on `omni::function` which target a `std::function<UReturn(UArgs...)>` will be ambiguous with the candidate constructor accepting `template F&&`.
### Missing Features from `std::function`
While `omni::function` is generally compatible with `std::function`, there are a few features that are not supported.
#### Allocators
The constructors for `std::function` support `std::allocator_arg_t`-accepting overloads which allows for a user-supplied allocator to be used when the binding needs to allocate.
This was inconsistently implemented and removed from the C++ Standard in the 2017 edition.
Because of this, `omni::function` does not support these allocator-accepting overloads. It will always use the `carbReallocate()` function for allocation on bindings.
## Target Access
The member functions `target_type()` and `target()` allow a caller to access the type information and value of the functor the `omni::function` is bound to. These are problematic because they require run-time type information, which Carbonite does not require and many builds disable. Even when RTTI is enabled, the `std::type_info` is not ABI safe, so attempting to use the types returned from these functions would not be safe, either.
These facilities are unhelpful in Omniverse at large, since the target of an `omni::function` might be implemented in another language; getting `PythonFunctionWrapper` or `RustTrampoline` is not all that useful. Developers are encouraged to find a safer facility instead of attempting to access the target function through the polymorphic wrapper. For example, you can keep the part you need to access in a `shared_ptr` and bind the function to access that:
```cpp
struct Foo
{
int value{};
int operator()(int x) const
{
return x + value;
}
};
int main()
{
// An std::function supports accessing the bound target:
std::function<int(int)> with_target{Foo{}};
with_target.target<Foo>()->value = 5;
assert(with_target(4) == 9);
// Instead, you can track Foo through a shared_ptr
auto foo_ptr = std::make_shared<Foo>();
omni::function<int(int)> omni_style = std::bind(&Foo::operator(), foo_ptr);
foo_ptr->value = 5;
assert(omni_style(4) == 9);
}
```
## Why not `std::function`?
There are two major reasons to have `omni::function` instead of relying on `std::function`. The primary reason is `std::function` is not guaranteed to be ABI stable, even across different compilation flags with the same compiler. Even if `std::function` guaranteed ABI stability, some binding targets require allocations, which need to go through the Omniverse `carbReallocate()` to support construction in one module and destruction in another.
## Details
### Data Layout
The core functionality of `omni::function` lives in `omni::detail::FunctionData`, a non-templated structure. An `omni::function` consists only of this `FunctionData`, the templated type only providing structural sugar for function calls and lifetime management in C++. Core data is designed to be used from other languages, with lifetime management and call syntax being left to language specific facilities.
```cpp
struct FunctionCharacteristics;
constexpr std::size_t kFUNCTION_BUFFER_SIZE = 16U;
constexpr std::size_t kFUNCTION_BUFFER_ALIGN = alignof(std::max_align_t);
union alignas(kFUNCTION_BUFFER_ALIGN) FunctionBuffer
{
char raw[kFUNCTION_BUFFER_SIZE];
void* pointer;
// other alternatives excluded
};
struct FunctionData
{
FunctionBuffer buffer;
void* trampoline;
FunctionCharacteristics const* characteristics;
};
```
The `trampoline` value is a pointer to a function with the signature `TReturn (*)(FunctionBuffer const*, TArgs...)`. It exists to restore context from the `FunctionBuffer`, which are user-defined additional details needed to perform the function call, covered in the next paragraph. If `trampoline` is `nullptr`, then the function is not active, regardless of any other value.
> **Note**
> Care must be taken to ensure the `FunctionData` for a function with one signature is not mixed with the signature of another. Type safety for this is maintained by language specific bindings (e.g.: in C++, a `omni::function<TReturn(TArgs...)>` cannot be mixed with a `omni::function<UReturn(UArgs...)>`).
The `buffer` field stores extra information for actually performing a function call. Exact structure is determined by the type `omni::function` is bound to. In the simplest case, a `omni::function<TReturn(TArgs...)>` might be bound to a `TReturn(*)(TArgs...)`, so the buffer would contain only this pointer. A more complex binding might be to a class type with an `operator()` overload, in which case the buffer will contain an object instance or pointer to a heap-allocated one.
The `characteristics` is meant for the management level operations of copying and destroying the function `buffer`. If this value is `nullptr`, then the function buffer is assumed to be trivially copyable and trivially destructible. It is discussed in detail in the [Function Characteristics](#function-characteristics) section.
Bringing this all together, the actual function call is performed by (error handling removed for brevity):
```cpp
template <typename TReturn, typename... TArgs>
TReturn function<TReturn(TArgs...)>::operator()(TArgs... args) const
```
{
auto real = reinterpret_cast<TReturn(*)(FunctionBuffer const*, TArgs...)>(this->trampoline);
return omni::invoke_r<TReturn>(&this->buffer, std::forward<TArgs>(args)...);
}
```
## Function Characteristics
```cpp
struct FunctionCharacteristics
{
size_t size;
void (*destroy)(FunctionBuffer* self);
omni::Result (*clone)(FunctionBuffer* target, FunctionBuffer const* source);
};
```
The `FunctionCharacteristics` structure is responsible for performing the special operations of destruction and copying of binding targets through the `destroy` and `clone` member functions. Either of these functions can be `nullptr`, which indicates the operation is trivial. A trivial `destroy` does nothing; a trivial `clone` means that `memcpy` is a valid replacement for copy. If both of these are trivial operations, then `FunctionData::characteristics` can be left as `nullptr`.
The instance must exist for the lifetime of the `omni::function`, but these live in the library-static space of where the function was created. A `function` instance does not make guarantees that the DLL/SO will remain loaded while it is callable. | 10,941 |
Garch.md | # Garch module
Summary: GL Architecture
## Module: pxr.Garch
garch
### Classes:
| Class | Description |
|-------|-------------|
| [GLPlatformDebugContext](#pxr.Garch.GLPlatformDebugContext) | Platform specific context (e.g. X11/GLX) which supports debug output. |
### Class: pxr.Garch.GLPlatformDebugContext
Platform specific context (e.g. X11/GLX) which supports debug output.
#### Methods:
| Method | Description |
|--------|-------------|
| [makeCurrent](#pxr.Garch.GLPlatformDebugContext.makeCurrent)() | |
#### Attributes:
| Attribute | Description |
|-----------|-------------|
| [expired](#pxr.Garch.GLPlatformDebugContext.expired) | True if this object has expired, False otherwise. |
#### Method: pxr.Garch.GLPlatformDebugContext.makeCurrent()
#### Attribute: pxr.Garch.GLPlatformDebugContext.expired
True if this object has expired, False otherwise.
---
title: 文章标题
author: 作者名
date: 2023-04-01
---
# 一级标题
## 二级标题
这是一段普通的文本。
### 三级标题
这里是代码块:
```python
print("Hello, World!")
```
这里是引用块:
> 引用内容
这里是列表:
- 列表项1
- 列表项2
这里是表格:
| 列1 | 列2 |
| --- | --- |
| 数据1 | 数据2 |
这里是链接文本,但没有实际链接:[链接文本]
这里是图片描述,但没有实际图片:![图片描述]
---
这里是页脚。 | 1,160 |
geforce-now-runtime-sdk-integration_Overview.md | # GeForce NOW Runtime SDK Integration
omni.kit.gfn links Omniverse Kit with the GFN runtime SDK.
It allows startup and shutdown of the SDK, retrieving GFN partner secure data,
and communicating with the client website containing the embedded GFN stream.
## Startup
Acquire the interface and call `startup` to initialize the GFN SDK.
```python
from omni.kit.gfn import get_geforcenow_interface
gfn = get_geforcenow_interface()
gfn.startup()
```
## Sending messages
Send messages to the GFN client by using the Kit application message bus.
Use `omni.kit.livestream.send_message` for the event type, and a `message` item for the event payload.
```python
import carb.events
import omni.kit.app
event_type = carb.events.type_from_string("omni.kit.livestream.send_message")
payload = {"message": "Hello GFN!"}
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(event_type, payload=payload)
```
## Receiving messages
Receive messages from the GFN client by using the Kit application message bus.
Use `omni.kit.livestream.receive_message` for the event type, and the message will be in the `message` item of the event payload.
```python
import carb.events
import omni.kit.app
def on_event(event: carb.events.IEvent):
message = event.payload["message"]
print("received", message)
event_type = carb.events.type_from_string("omni.kit.livestream.receive_message")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_pop_by_type(event_type, on_event)
```
We also support generic messages, if it doesn’t parse as json with those keys, use
omni.kit.gfn.receive_message
```
for the event type, and the raw message will be in the
```
message
```
item of the event payload. | 1,767 |
general-use-case_Overview.md | # Overview — Omniverse Kit 1.1.5 documentation
## Overview
This extension provides a collection of commands for managing and manipulating primitives within a Fabric stage using USDRT API. It includes commands for creating, copying, moving, deleting, and transforming primitives, as well as grouping, ungrouping, and changing properties and attributes of these primitives. They are designed to work with Fabric, a framework within NVIDIA Omniverse for real-time graphics and simulation.
### Important API List
- DeleteFabricPrimsCommand: Deletes specified primitives from a Fabric stage.
- MoveFabricPrimCommand: Moves a single Fabric prim to a new path within the same stage.
- MoveFabricPrimsCommand: Moves multiple Fabric prims to new locations within the stage.
- ToggleVisibilitySelectedFabricPrimsCommand: Toggles the visibility of selected Fabric primitives.
- CreateFabricPrimWithDefaultXformCommand: Creates a Fabric primitive with a default transform.
- CreateFabricPrimCommand: Creates a Fabric primitive.
- CopyFabricPrimsCommand: Creates multiple Fabric primitives.
- CreateDefaultXformOnFabricPrimCommand: Applies a default transform to a Fabric primitive.
- CopyFabricPrimCommand: Copies a Fabric primitive to a new location in the stage.
- CopyFabricPrimsCommand: Copies multiple Fabric primitives to new locations in the stage.
- GroupFabricPrimsCommand: Groups multiple Fabric primitives under a new Xform primitive.
- UngroupFabricPrimsCommand: Ungroups Fabric primitives from their common parent Xform primitive.
## Commands
- **TransformFabricPrimCommand**: Transforms a Fabric primitive with a given transformation matrix.
- **ChangeFabricPropertyCommand**: Changes a specified property on a Fabric primitive.
- **ChangeFabricAttributeCommand**: Changes a specified attribute on a Fabric primitive.
## General Use Case
Users can use this extension to perform various operations on primitives within a Fabric stage, such as creating, deleting, moving, grouping, and transforming primitives, as well as managing their properties and visibility. These commands facilitate the manipulation of scene elements in a programmatic and undoable manner, allowing for efficient scene management in the Omniverse Kit. For examples of how to use the APIs, please consult the Python usage pages.
## User Guide
- Settings
- Usage Examples
- Changelog | 2,359 |
GeomUtil.md | # GeomUtil module
Summary: The GeomUtil module contains utilities to help image common geometry.
## Classes:
| Class | Description |
| --- | --- |
| `CapsuleMeshGenerator` | This class provides an implementation for generating topology and point positions on a capsule. |
| `ConeMeshGenerator` | This class provides an implementation for generating topology and point positions on a cone of a given radius and height. |
| `CuboidMeshGenerator` | This class provides an implementation for generating topology and point positions on a rectangular cuboid given the dimensions along the X, Y and Z axes. |
| `CylinderMeshGenerator` | This class provides an implementation for generating topology and point positions on a cylinder with a given radius and height. |
| `SphereMeshGenerator` | This class provides an implementation for generating topology and point positions on a sphere with a given radius. |
### CapsuleMeshGenerator
This class provides an implementation for generating topology and point positions on a capsule.
- The simplest form takes a radius and height and is a cylinder capped by two hemispheres that is centered at the origin.
- The generated capsule is made up of circular cross-sections in the XY plane.
- Each cross-section has numRadial segments.
- Successive cross-sections for each of the hemispheres are generated at numCapAxial locations along the Z and -Z axes respectively.
- The height is aligned with the Z axis and represents the height of just the cylindrical portion.
- An optional transform may be provided to GeneratePoints to orient the capsule as necessary (e.g., whose height is along the Y axis).
- An additional overload of GeneratePoints is provided to specify different radii and heights for the bottom and top caps, as well as the sweep angle for the capsule about the +Z axis.
- When the sweep is less than 360 degrees, the generated geometry is not closed.
Usage:
```
```markdown
```cpp
const size_t numRadial = 4, numCapAxial = 4;
const size_t numPoints =
GeomUtilCapsuleMeshGenerator::ComputeNumPoints(numRadial, numCapAxial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCapsuleMeshGenerator::GeneratePoints(
points.begin(), numRadial, numCapAxial, radius, height);
```markdown
**Methods:**
```
```markdown
| Method | Description |
| --- | --- |
| ComputeNumPoints | classmethod ComputeNumPoints(numRadial, numCapAxial, closedSweep) -> int |
| GeneratePoints | classmethod GeneratePoints(iter, numRadial, numCapAxial, radius, height, framePtr) -> None |
| GenerateTopology | classmethod GenerateTopology(numRadial, numCapAxial, closedSweep) -> MeshTopology |
```
```markdown
**Attributes:**
```
```markdown
| Attribute | Description |
| --- | --- |
| minNumCapAxial | |
| minNumRadial | |
```
```markdown
**ComputeNumPoints**
```
```markdown
classmethod ComputeNumPoints(numRadial, numCapAxial, closedSweep) -> int
```
```markdown
Parameters:
- numRadial (int) –
- numCapAxial (int) –
- closedSweep (bool) –
```
```markdown
**GeneratePoints**
```
```markdown
classmethod GeneratePoints(iter, numRadial, numCapAxial, radius, height, framePtr) -> None
```
```markdown
Parameters:
- iter (PointIterType) –
- numRadial (int) –
- numCapAxial (int) –
- radius (ScalarType) –
- height (ScalarType) –
- framePtr (Matrix4d) –
```
```markdown
<p>
GeneratePoints(iter, numRadial, numCapAxial, bottomRadius, topRadius, height, bottomCapHeight, topCapHeight, sweepDegrees, framePtr) -> None
<dl>
<dt>Parameters
<dd>
<ul>
<li>
<p><strong>iter
<li>
<p><strong>numRadial
<li>
<p><strong>numCapAxial
<li>
<p><strong>bottomRadius
<li>
<p><strong>topRadius
<li>
<p><strong>height
<li>
<p><strong>bottomCapHeight
<li>
<p><strong>topCapHeight
<li>
<p><strong>sweepDegrees
<li>
<p><strong>framePtr
<hr>
<p>
GeneratePoints(iter, arg2) -> None
<dl>
<dt>Parameters
<dd>
<ul>
<li>
<p><strong>iter
<li>
<p><strong>arg2
<dl>
<dt>classmethod GenerateTopology(numRadial, numCapAxial, closedSweep) -> MeshTopology
<dd>
<dl>
<dt>Parameters
<dd>
<ul>
<li>
<p><strong>numRadial
<li>
<p><strong>numCapAxial
<li>
<p><strong>closedSweep
<dl>
<dt>minNumCapAxial = 1
<dl>
<dt>minNumRadial = 3
<dl>
<dt>class pxr.GeomUtil.ConeMeshGenerator
<dd>
<p>This class provides an implementation for generating topology and point positions on a cone of a given radius and height.
<p>The cone is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. The height is aligned with the Z axis, with the base of the object at Z = -h/2 and apex at Z = h/2.
<p>An optional transform may be provided to GeneratePoints to orient the cone as necessary (e.g., whose height is along the Y axis).
<p>An additional overload of GeneratePoints is provided to specify the sweep angle for the cone about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.
<p>Usage:
<div class="highlight-text notranslate">
<div class="highlight">
```pre
const size_t numRadial = 8;
const size_t numPoints =
GeomUtilConeMeshGenerator::ComputeNumPoints(numRadial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilConeMeshGenerator::GeneratePoints(
points.begin(), numRadial, radius, height);
## Methods:
| Method | Description |
| --- | --- |
| `ComputeNumPoints` | `classmethod ComputeNumPoints(numRadial, closedSweep) -> int` |
| `GeneratePoints` | `classmethod GeneratePoints(iter, numRadial, radius, height, framePtr) -> None` |
| `GenerateTopology` | `classmethod GenerateTopology(numRadial, closedSweep) -> MeshTopology` |
## Attributes:
| Attribute | Description |
| --- | --- |
| `minNumRadial` | |
### ComputeNumPoints
```
classmethod ComputeNumPoints(numRadial, closedSweep) -> int
```
Parameters:
- `numRadial` (int) –
- `closedSweep` (bool) –
### GeneratePoints
```
classmethod GeneratePoints(iter, numRadial, radius, height, framePtr) -> None
```
Parameters:
- `iter` (PointIterType) –
- `numRadial` (int) –
- `radius` (ScalarType) –
- `height` (ScalarType) –
- `framePtr` (Matrix4d) –
GeneratePoints(iter, numRadial, radius, height, sweepDegrees, framePtr) -> None
Parameters:
- `iter` (PointIterType) –
- `numRadial` (int) –
- `radius` (ScalarType) –
- `height` (ScalarType) –
```
- **sweepDegrees** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
---
GeneratePoints(iter, arg2) -> None
- **Parameters**
- **iter** (`PointIterType`) –
- **arg2** –
---
- **classmethod** GenerateTopology(numRadial, closedSweep) -> MeshTopology
- **Parameters**
- **numRadial** (`int`) –
- **closedSweep** (`bool`) –
---
- **minNumRadial** = 3
---
- **class** pxr.GeomUtil.CuboidMeshGenerator
- This class provides an implementation for generating topology and point positions on a rectangular cuboid given the dimensions along the X, Y and Z axes.
- The generated cuboid is centered at the origin.
- An optional transform may be provided to GeneratePoints to orient the cuboid as necessary.
- Usage:
```cpp
const size_t numPoints = GeomUtilCuboidMeshGenerator::ComputeNumPoints();
const float l = 5, b = 4, h = 3;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCuboidMeshGenerator::GeneratePoints(points.begin(), l, b, h);
```
- **Methods:**
- **classmethod** ComputeNumPoints() -> int
- **classmethod** GeneratePoints(iter, xLength, yLength, zLength, framePtr) -> None
- **classmethod** GenerateTopology() -> MeshTopology
- **classmethod** ComputeNumPoints() -> int
### GeneratePoints
**classmethod** GeneratePoints(iter, xLength, yLength, zLength, framePtr) -> None
#### Parameters
- **iter** (`PointIterType`) –
- **xLength** (`ScalarType`) –
- **yLength** (`ScalarType`) –
- **zLength** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
---
GeneratePoints(iter, arg2) -> None
#### Parameters
- **iter** (`PointIterType`) –
- **arg2** –
### GenerateTopology
**classmethod** GenerateTopology() -> MeshTopology
### CylinderMeshGenerator
This class provides an implementation for generating topology and point positions on a cylinder with a given radius and height.
The cylinder is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. The height is aligned with the Z axis, with the base at Z = -h/2.
An optional transform may be provided to GeneratePoints to orient the cone as necessary (e.g., whose height is along the Y axis).
An additional overload of GeneratePoints is provided to specify different radii for the bottom and top discs of the cylinder and a sweep angle for cylinder about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.
Setting one radius to 0 in order to get a cone is inefficient and could result in artifacts. Clients should use GeomUtilConeMeshGenerator instead. Usage:
```cpp
const size_t numRadial = 8;
const size_t numPoints = GeomUtilCylinderMeshGenerator::ComputeNumPoints(numRadial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCylinderMeshGenerator::GeneratePoints(
points.begin(), numRadial, radius, height);
```
**Methods:**
- **ComputeNumPoints** (`classmethod` ComputeNumPoints(numRadial, closedSweep) -> int)
- **GeneratePoints** (`classmethod` GeneratePoints(iter, numRadial, radius, height, framePtr) -> None)
- **GenerateTopology** (`classmethod` GenerateTopology(numRadial, closedSweep) -> MeshTopology)
**Attributes:**
- **minNumRadial**
## ComputeNumPoints
**classmethod** ComputeNumPoints(numRadial, closedSweep) -> int
### Parameters
- **numRadial** (int) –
- **closedSweep** (bool) –
## GeneratePoints
**classmethod** GeneratePoints(iter, numRadial, radius, height, framePtr) -> None
### Parameters
- **iter** (PointIterType) –
- **numRadial** (int) –
- **radius** (ScalarType) –
- **height** (ScalarType) –
- **framePtr** (Matrix4d) –
**classmethod** GeneratePoints(iter, numRadial, bottomRadius, topRadius, height, sweepDegrees, framePtr) -> None
### Parameters
- **iter** (PointIterType) –
- **numRadial** (int) –
- **bottomRadius** (ScalarType) –
- **topRadius** (ScalarType) –
- **height** (ScalarType) –
- **sweepDegrees** (ScalarType) –
- **framePtr** (Matrix4d) –
**classmethod** GeneratePoints(iter, arg2) -> None
### Parameters
- **iter** (PointIterType) –
- **arg2** –
## GenerateTopology
**classmethod** GenerateTopology(numRadial, closedSweep) -> MeshTopology
### Parameters
- **numRadial** (int) –
- **closedSweep** (bool) –
This class provides an implementation for generating topology and point positions on a sphere with a given radius.
The sphere is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. Successive cross-sections are generated at numAxial locations along the Z axis, with the bottom of the sphere at Z = -r and top at Z = r.
An optional transform may be provided to GeneratePoints to orient the sphere as necessary (e.g., cross-sections in the YZ plane).
An additional overload of GeneratePoints is provided to specify a sweep angle for the sphere about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.
Usage:
```cpp
const size_t numRadial = 4, numAxial = 4;
const size_t numPoints = GeomUtilSphereMeshGenerator::ComputeNumPoints(numRadial, numAxial);
const float radius = 5;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilSphereMeshGenerator::GeneratePoints(points.begin(), numRadial, numAxial, radius);
```
**Methods:**
| Method | Description |
|--------|-------------|
| `ComputeNumPoints` | **classmethod** ComputeNumPoints(numRadial, numAxial, closedSweep) -> int |
| `GeneratePoints` | **classmethod** GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None |
| `GenerateTopology` | **classmethod** GenerateTopology(numRadial, numAxial, closedSweep) -> MeshTopology |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `minNumAxial` | |
| `minNumRadial` | |
**ComputeNumPoints**
**classmethod** ComputeNumPoints(numRadial, numAxial, closedSweep) -> int
Parameters:
- **numRadial** (int) –
- **numAxial** (int) –
- **closedSweep** (bool) –
**GeneratePoints**
**static** GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None
### GeneratePoints
```python
classmethod GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **radius** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
```python
classmethod GeneratePoints(iter, numRadial, numAxial, radius, sweepDegrees, framePtr) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **radius** (`ScalarType`) –
- **sweepDegrees** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
```python
classmethod GeneratePoints(iter, arg2) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **arg2** –
### GenerateTopology
```python
classmethod GenerateTopology(numRadial, numAxial, closedSweep) -> MeshTopology
```
**Parameters**
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **closedSweep** (`bool`) –
### minNumAxial
```python
minNumAxial = 2
```
### minNumRadial
```python
minNumRadial = 3
``` | 13,410 |
Gestures.md | # Gestures
Gestures handle all of the logic needed to process user-input events such as click and drag and recognize when those events happen on the shape. When recognizing it, SceneUI runs a callback to update the state of a view or perform an action.
## Add Gesture Callback
Each gesture applies to a specific shape in the scene hierarchy. To recognize a gesture event on a particular shape, it’s necessary to create and configure the gesture object. SceneUI provides the full state of the gesture to the callback using the `gesture_payload` object. The `gesture_payload` object contains the coordinates of the intersection of mouse pointer and the shape in world and shape spaces, the distance between last intersection and parametric coordinates. It’s effortless to modify the state of the shape using this data.
```python
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Line(
[-1, 0, 0],
[1, 0, 0],
color=cl.blue,
thickness=5,
gesture=sc.DragGesture(
on_changed_fn=partial(move, transform)
)
)
```
## Reimplementing Gesture
Some gestures can receive the update in a different state. For example, DragGesture offers the update when the user presses the mouse, moves the mouse, and releases the mouse: `on_began`, `on_changed`, `on_ended`. It’s also possible to extend the gesture by reimplementing its class.
```python
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform):
# Implementation details here
```
```python
super().__init__()
self.__transform = transform
def on_began(self):
self.sender.color = cl.red
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def on_ended(self):
self.sender.color = cl.blue
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(color=cl.blue, gesture=Move(transform))
```
## Gesture Manager
Gestures track incoming input events separately, but it’s normally necessary to let only one gesture be executed because it prevents user input from triggering more than one action at a time. For example, if multiple shapes are under the mouse pointer, normally, the only gesture of the closest shape should be processed. However, this default behavior can introduce unintended side effects. To solve those problems, it’s necessary to use the gesture manager.
GestureManager controls the priority of gestures if they are processed at the same time. It prioritizes the desired gestures and prevents unintended gestures from being executed.
In the following example, the gesture of the red rectangle always wins even if both rectangles overlap.
```python
class Manager(sc.GestureManager):
def __init__(self):
super().__init__()
def should_prevent(self, gesture, preventer):
# prime gesture always wins
if preventer.name == "prime":
return True
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
mgr = Manager()
with scene_view.scene:
transform1 = sc.Transform()
with transform1:
sc.Rectangle(
color=cl.red,
gesture=sc.DragGesture(
name="prime",
manager=mgr,
on_changed_fn=partial(move, transform1)
)
)
transform2 = sc.Transform(
transform=sc.Matrix44.get_translation_matrix(2, 0, 0)
)
with transform2:
sc.Rectangle(
color=cl.blue,
gesture=sc.DragGesture(
manager=mgr,
on_changed_fn=partial(move, transform2)
)
)
``` | 4,271 |
Gf.md | # Gf module
Summary: The Gf (Graphics Foundations) library contains classes and functions for working with basic mathematical aspects of graphics.
## Graphics Foundation
This package defines classes for fundamental graphics types and operations.
### Classes:
| Class | Description |
|-------|-------------|
| `BBox3d` | Arbitrarily oriented 3D bounding box |
| `Camera` | |
| `DualQuatd` | |
| `DualQuatf` | |
| `DualQuath` | |
| `Frustum` | Basic view frustum |
| `Interval` | Basic mathematical interval class |
| `Line` | Line class |
| `LineSeg` | Line segment class |
| `Matrix2d` | |
| `Matrix2f` | |
- Matrix2f
- Matrix3d
- Matrix3f
- Matrix4d
- Matrix4f
- MultiInterval
- Plane
- Quatd
- Quaternion
- Quaternion class
- Quatf
- Quath
- Range1d
- Range1f
- Range2d
- Range2f
- Range3d
- Range3f
- Ray
- Rect2i
- Rotation
- 3-space rotation
- Size2
- A 2D size class
Size3
A 3D size class
Transform
Vec2d
Vec2f
Vec2h
Vec2i
Vec3d
Vec3f
Vec3h
Vec3i
Vec4d
Vec4f
Vec4h
Vec4i
class pxr.Gf.BBox3d
Arbitrarily oriented 3D bounding box
**Methods:**
Combine(b1, b2) -> BBox3d
classmethod
ComputeAlignedBox()
Returns the axis-aligned range (as a GfRange3d) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
ComputeAlignedRange()
Returns the axis-aligned range (as a GfRange3d)
| Method | Description |
| --- | --- |
| `ComputeCentroid()` | Returns the centroid of the bounding box. |
| `GetBox()` | Returns the range of the axis-aligned untransformed box. |
| `GetInverseMatrix()` | Returns the inverse of the transformation matrix. |
| `GetMatrix()` | Returns the transformation matrix. |
| `GetRange()` | Returns the range of the axis-aligned untransformed box. |
| `GetVolume()` | Returns the volume of the box (0 for an empty box). |
| `HasZeroAreaPrimitives()` | Returns the current state of the zero-area primitives flag. |
| `Set(box, matrix)` | Sets the axis-aligned box and transformation matrix. |
| `SetHasZeroAreaPrimitives(hasThem)` | Sets the zero-area primitives flag to the given value. |
| `SetMatrix(matrix)` | Sets the transformation matrix only. |
| `SetRange(box)` | Sets the range of the axis-aligned box only. |
| `Transform(matrix)` | Transforms the bounding box by the given matrix, which is assumed to be a global transformation to apply to the box. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `box` | |
| `hasZeroAreaPrimitives` | |
| `matrix` | |
### Combine
```python
classmethod Combine(b1, b2) -> BBox3d
```
Combines two bboxes, returning a new bbox that contains both.
This uses the coordinate space of one of the two original boxes as the space of the result; it uses the one that produces the smaller of the two resulting boxes.
#### Parameters
- **b1** (`BBox3d`) –
- **b2** (`BBox3d`) –
### ComputeAlignedBox
```python
ComputeAlignedBox() -> Range3d
```
Returns the axis-aligned range (as a `GfRange3d`) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
This synonym for `ComputeAlignedRange` exists for compatibility purposes.
### ComputeAlignedRange
```python
ComputeAlignedRange() -> Range3d
```
Returns the axis-aligned range (as a `GfRange3d`) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
### ComputeCentroid
```python
ComputeCentroid() -> Vec3d
```
Returns the centroid of the bounding box.
The centroid is computed as the transformed centroid of the range.
### GetBox
```python
GetBox() -> Range3d
```
Returns the range of the axis-aligned untransformed box.
This synonym of `GetRange` exists for compatibility purposes.
### GetInverseMatrix
```python
GetInverseMatrix() -> Matrix4d
```
Returns the inverse of the transformation matrix.
This will be the identity matrix if the transformation matrix is not invertible.
### GetMatrix
```python
GetMatrix() -> Matrix4d
```
Returns the transformation matrix.
Returns the transformation matrix.
Returns the range of the axis-aligned untransformed box.
Returns the volume of the box (0 for an empty box).
Returns the current state of the zero-area primitives flag.
Sets the axis-aligned box and transformation matrix.
Parameters:
- box (Range3d) –
- matrix (Matrix4d) –
Sets the zero-area primitives flag to the given value.
Parameters:
- hasThem (bool) –
Sets the transformation matrix only.
The axis-aligned box is not modified.
Parameters:
- matrix (Matrix4d) –
### pxr.Gf.BBox3d.SetRange
- **Description:** Sets the range of the axis-aligned box only. The transformation matrix is not modified.
- **Parameters:**
- **box** (Range3d) –
### pxr.Gf.BBox3d.Transform
- **Description:** Transforms the bounding box by the given matrix, which is assumed to be a global transformation to apply to the box. Therefore, this just post-multiplies the box’s matrix by matrix.
- **Parameters:**
- **matrix** (Matrix4d) –
### pxr.Gf.BBox3d.box
- **Description:** (property)
### pxr.Gf.BBox3d.hasZeroAreaPrimitives
- **Description:** (property)
### pxr.Gf.BBox3d.matrix
- **Description:** (property)
### pxr.Gf.Camera
- **Classes:**
- **FOVDirection:** Direction used for Field of View or orthographic size.
- **Projection:** Projection type.
- **Methods:**
- **GetFieldOfView(direction):** Returns the horizontal or vertical field of view in degrees.
- **SetFromViewAndProjectionMatrix(viewMatrix, ...):** Sets the camera from a view and projection matrix.
- **SetOrthographicFromAspectRatioAndSize:**
```code
SetOrthographicFromAspectRatioAndSize
```
(...)
```
Sets the frustum to be orthographic such that it has the given
```code
aspectRatio
```
and such that the orthographic width, respectively, orthographic height (in cm) is equal to
```code
orthographicSize
```
(depending on direction).
```
<a title="pxr.Gf.Camera.SetPerspectiveFromAspectRatioAndFieldOfView">
```code
SetPerspectiveFromAspectRatioAndFieldOfView
```
(...)
```
Sets the frustum to be projective with the given
```code
aspectRatio
```
and horizontal, respectively, vertical field of view
```code
fieldOfView
```
(similar to gluPerspective when direction = FOVVertical).
```
**Attributes:**
```
```
<a title="pxr.Gf.Camera.APERTURE_UNIT">
```code
APERTURE_UNIT
```
```
<a title="pxr.Gf.Camera.DEFAULT_HORIZONTAL_APERTURE">
```code
DEFAULT_HORIZONTAL_APERTURE
```
```
<a title="pxr.Gf.Camera.DEFAULT_VERTICAL_APERTURE">
```code
DEFAULT_VERTICAL_APERTURE
```
```
<a title="pxr.Gf.Camera.FOCAL_LENGTH_UNIT">
```code
FOCAL_LENGTH_UNIT
```
```
<a title="pxr.Gf.Camera.FOVHorizontal">
```code
FOVHorizontal
```
```
<a title="pxr.Gf.Camera.FOVVertical">
```code
FOVVertical
```
```
<a title="pxr.Gf.Camera.Orthographic">
```code
Orthographic
```
```
<a title="pxr.Gf.Camera.Perspective">
```code
Perspective
```
```
<a title="pxr.Gf.Camera.aspectRatio">
```code
aspectRatio
```
```
float
```
```
<a title="pxr.Gf.Camera.clippingPlanes">
```code
clippingPlanes
```
```
list[Vec4f]
```
```
<a title="pxr.Gf.Camera.clippingRange">
```code
clippingRange
```
```
Range1f
```
```
<a title="pxr.Gf.Camera.fStop">
```code
fStop
```
```
float
```
```
<a title="pxr.Gf.Camera.focalLength">
```code
focalLength
```
```
float
```
```
<a title="pxr.Gf.Camera.focusDistance">
```
| Property | Type |
|-------------------------|------------|
| focusDistance | float |
| frustum | Frustum |
| horizontalAperture | float |
| horizontalApertureOffset| float |
| horizontalFieldOfView | |
| projection | Projection |
| transform | Matrix4d |
| verticalAperture | float |
| verticalApertureOffset | float |
| verticalFieldOfView | |
### FOVDirection
**Description:** Direction used for Field of View or orthographic size.
**Methods:**
- GetValueFromName
**Attributes:**
- allValues
#### GetValueFromName
#### allValues
Projection type.
**Methods:**
- GetValueFromName
- allValues
**Attributes:**
- allValues
**GetValueFromName**
**allValues** = (Gf.Camera.Perspective, Gf.Camera.Orthographic)
**GetFieldOfView**
Returns the horizontal or vertical field of view in degrees.
Parameters:
- **direction** (FOVDirection) –
**SetFromViewAndProjectionMatrix**
Sets the camera from a view and projection matrix.
Note that the projection matrix does only determine the ratio of aperture to focal length, so there is a choice which defaults to 50mm (or more accurately, 50 tenths of a world unit).
Parameters:
- **viewMatrix** (Matrix4d) –
- **projMatix** (Matrix4d) –
- **focalLength** (float) –
### SetOrthographicFromAspectRatioAndSize
```python
SetOrthographicFromAspectRatioAndSize(aspectRatio, orthographicSize, direction) → None
```
Sets the frustum to be orthographic such that it has the given `aspectRatio` and such that the orthographic width, respectively, orthographic height (in cm) is equal to `orthographicSize` (depending on direction).
#### Parameters
- **aspectRatio** (float) –
- **orthographicSize** (float) –
- **direction** (FOVDirection) –
### SetPerspectiveFromAspectRatioAndFieldOfView
```python
SetPerspectiveFromAspectRatioAndFieldOfView(aspectRatio, fieldOfView, direction, horizontalAperture) → None
```
Sets the frustum to be projective with the given `aspectRatio` and horizontal, respectively, vertical field of view `fieldOfView` (similar to gluPerspective when direction = FOVVertical).
Do not pass values for `horionztalAperture` unless you care about DepthOfField.
#### Parameters
- **aspectRatio** (float) –
- **fieldOfView** (float) –
- **direction** (FOVDirection) –
- **horizontalAperture** (float) –
### APERTURE_UNIT
```python
APERTURE_UNIT = 0.1
```
### DEFAULT_HORIZONTAL_APERTURE
```python
DEFAULT_HORIZONTAL_APERTURE = 20.955
```
### DEFAULT_VERTICAL_APERTURE
```python
DEFAULT_VERTICAL_APERTURE =
```
=
15.290799999999999
FOCAL_LENGTH_UNIT = 0.1
FOVHorizontal = Gf.Camera.FOVHorizontal
FOVVertical = Gf.Camera.FOVVertical
Orthographic = Gf.Camera.Orthographic
Perspective = Gf.Camera.Perspective
property aspectRatio
- float
- Returns the projector aperture aspect ratio.
- Type: type
property clippingPlanes
- list[Vec4f]
- Returns additional clipping planes.
- type : None
- Sets additional arbitrarily oriented clipping planes.
- A vector (a,b,c,d) encodes a clipping plane that clips off points (x,y,z) with a * x + b * y + c * z + d * 1<0
- where (x,y,z) are the coordinates in the camera’s space.
- Type: type
property clippingRange
- Range1f
- Returns the clipping range in world units.
- type : None
- Sets the clipping range in world units.
- Type: type
property fStop
- float
- Returns the lens aperture.
- type : None
- Sets the lens aperture, unitless.
- Type: type
property focalLength
### focalLength
- **Type**: float
- **Description**: Returns the focal length in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- Together with the clipping range, they determine the camera frustum.
- Sets the focal length in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### focusDistance
- **Type**: float
- **Description**: Returns the focus distance in world units.
- **Details**:
- Sets the focus distance in world units.
### frustum
- **Type**: Frustum
- **Description**: Returns the computed, world-space camera frustum.
- **Details**:
- The frustum will always be that of a Y-up, -Z-looking camera.
### horizontalAperture
- **Type**: float
- **Description**: Returns the width of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- Sets the width of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### horizontalApertureOffset
- **Type**: float
- **Description**: Returns the horizontal offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- In particular, an offset is necessary when writing out a stereo camera with finite convergence distance as two cameras.
- Sets the horizontal offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### horizontalFieldOfView
- **Type**: float
- **Description**: Returns the horizontal field of view.
### projection
- **Type**: Projection
- **Description**: Returns the projection type.
- **Details**:
- Sets the projection type.
### transform
- **Type**: Matrix4d
- **Description**: Returns the transform of the filmback in world space.
- **Details**:
- This is exactly the transform specified via SetTransform().
- Sets the transform of the filmback in world space to `val`.
Type
: type
property verticalAperture
: float
Returns the height of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
type : None
Sets the height of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
Type
: type
property verticalApertureOffset
: float
Returns the vertical offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
type : None
Sets the vertical offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
Type
: type
property verticalFieldOfView
:
class pxr.Gf.DualQuatd
: Methods:
- GetConjugate()
Returns the conjugate of this dual quaternion.
- GetDual()
Returns the dual part of the dual quaternion.
- classmethod GetIdentity() -> DualQuatd
GetIdentity() -> DualQuatd
- GetInverse()
Returns the inverse of this dual quaternion.
- GetLength()
Returns geometric length of this dual quaternion.
- GetNormalized(eps)
Returns a normalized (unit-length) version of this dual quaternion.
- GetReal()
Returns the real part of the dual quaternion.
- GetTranslation()
Get the translation component of this dual quaternion.
| Method | Description |
| ------ | ----------- |
| `GetZero` | classmethod GetZero() -> DualQuatd |
| `Normalize(eps)` | Normalizes this dual quaternion in place. |
| `SetDual(dual)` | Sets the dual part of the dual quaternion. |
| `SetReal(real)` | Sets the real part of the dual quaternion. |
| `SetTranslation(translation)` | Set the translation component of this dual quaternion. |
| `Transform(vec)` | Transforms the row vector `vec` by the dual quaternion. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| `dual` | |
| `real` | |
**Methods:**
- `GetConjugate()` -> DualQuatd
- Returns the conjugate of this dual quaternion.
- `GetDual()` -> Quatd
- Returns the dual part of the dual quaternion.
- `GetIdentity()` -> DualQuatd
- Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
- `GetInverse()` -> DualQuatd
- Returns the inverse of this dual quaternion.
### GetLength
Returns geometric length of this dual quaternion.
### GetNormalized
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
**Parameters**
- **eps** (float) –
### GetReal
Returns the real part of the dual quaternion.
### GetTranslation
Get the translation component of this dual quaternion.
### GetZero
**classmethod** GetZero() -> DualQuatd
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (float) –
### SetDual
)
→ None
Sets the dual part of the dual quaternion.
Parameters
----------
dual (Quatd) –
SetReal(real)
→ None
Sets the real part of the dual quaternion.
Parameters
----------
real (Quatd) –
SetTranslation(translation)
→ None
Set the translation component of this dual quaternion.
Parameters
----------
translation (Vec3d) –
Transform(vec)
→ Vec3d
Transforms the row vector `vec` by the dual quaternion.
Parameters
----------
vec (Vec3d) –
property dual
property real
class pxr.Gf.DualQuatf
Methods:
----------
GetConjugate()
Returns the conjugate of this dual quaternion.
- `GetDual()`
- Returns the dual part of the dual quaternion.
- `GetIdentity()`
- `classmethod GetIdentity() -> DualQuatf`
- `GetInverse()`
- Returns the inverse of this dual quaternion.
- `GetLength()`
- Returns geometric length of this dual quaternion.
- `GetNormalized(eps)`
- Returns a normalized (unit-length) version of this dual quaternion.
- `GetReal()`
- Returns the real part of the dual quaternion.
- `GetTranslation()`
- Get the translation component of this dual quaternion.
- `GetZero()`
- `classmethod GetZero() -> DualQuatf`
- `Normalize(eps)`
- Normalizes this dual quaternion in place.
- `SetDual(dual)`
- Sets the dual part of the dual quaternion.
- `SetReal(real)`
- Sets the real part of the dual quaternion.
- `SetTranslation(translation)`
- Set the translation component of this dual quaternion.
- `Transform(vec)`
- Transforms the row vector `vec` by the dual quaternion.
**Attributes:**
- `dual`
- `real`
( ) → DualQuatf
Returns the conjugate of this dual quaternion.
( ) → Quatf
Returns the dual part of the dual quaternion.
static GetIdentity() → DualQuatf
Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
( ) → DualQuatf
Returns the inverse of this dual quaternion.
( ) → tuple[float, float]
Returns geometric length of this dual quaternion.
( eps ) → DualQuatf
Returns a normalized (unit-length) version of this dual quaternion. If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
Parameters:
- eps (float) –
( ) → Quatf
Returns the real part of the dual quaternion.
( ) → Vec3f
Returns the translation part of the dual quaternion.
### Get the translation component of this dual quaternion.
### GetZero
```markdown
classmethod GetZero() -> DualQuatf
```
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
```markdown
Normalize(eps) -> tuple[float, float]
```
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (float) –
### SetDual
```markdown
SetDual(dual) -> None
```
Sets the dual part of the dual quaternion.
**Parameters**
- **dual** (Quatf) –
### SetReal
```markdown
SetReal(real) -> None
```
Sets the real part of the dual quaternion.
**Parameters**
- **real** (Quatf) –
### SetTranslation
```markdown
SetTranslation(translation) -> None
```
Set the translation component of this dual quaternion.
**Parameters**
- **translation** (Vec3f) –
### pxr.Gf.DualQuatf.Transform
Transforms the row vector `vec` by the dual quaternion.
#### Parameters
- **vec** (`Vec3f`) –
### pxr.Gf.DualQuatf.dual
property dual
### pxr.Gf.DualQuatf.real
property real
### pxr.Gf.DualQuath
Methods:
| Method | Description |
|--------|-------------|
| `GetConjugate()` | Returns the conjugate of this dual quaternion. |
| `GetDual()` | Returns the dual part of the dual quaternion. |
| `GetIdentity()` | **classmethod** GetIdentity() -> DualQuath |
| `GetInverse()` | Returns the inverse of this dual quaternion. |
| `GetLength()` | Returns geometric length of this dual quaternion. |
| `GetNormalized(eps)` | Returns a normalized (unit-length) version of this dual quaternion. |
| `GetReal()` | Returns the real part of the dual quaternion. |
| `GetTranslation()` | Get the translation component of this dual quaternion. |
| `GetZero()` | **classmethod** GetZero() -> DualQuath |
| `Normalize(eps)` | |
Normalizes this dual quaternion in place.
SetDual (dual)
: Sets the dual part of the dual quaternion.
SetReal (real)
: Sets the real part of the dual quaternion.
SetTranslation (translation)
: Set the translation component of this dual quaternion.
Transform (vec)
: Transforms the row vector `vec` by the dual quaternion.
**Attributes:**
dual
:
real
:
GetConjugate()
: Returns the conjugate of this dual quaternion.
GetDual()
: Returns the dual part of the dual quaternion.
GetIdentity()
: **classmethod** GetIdentity() -> DualQuath
Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
GetInverse()
: Returns the inverse of this dual quaternion.
GetLength()
: Returns the length of this dual quaternion.
### Returns geometric length of this dual quaternion.
### GetNormalized
```python
GetNormalized(eps)
```
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
**Parameters**
- **eps** (`GfHalf`) –
### GetReal
```python
GetReal()
```
Returns the real part of the dual quaternion.
### GetTranslation
```python
GetTranslation()
```
Get the translation component of this dual quaternion.
### GetZero
```python
classmethod GetZero() -> DualQuath
```
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
```python
Normalize(eps)
```
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (`GfHalf`) –
### SetDual
```python
SetDual(dual)
```
Sets the dual part of the dual quaternion.
**Parameters**
- **dual** (`Quath`) –
### SetReal
Sets the real part of the dual quaternion.
**Parameters**
- **real** (`Quath`) –
### SetTranslation
Set the translation component of this dual quaternion.
**Parameters**
- **translation** (`Vec3h`) –
### Transform
Transforms the row vector `vec` by the dual quaternion.
**Parameters**
- **vec** (`Vec3h`) –
### dual
### real
### Frustum
Basic view frustum
**Classes:**
- **ProjectionType**
This enum is used to determine the type of projection represented by a frustum.
**Methods:**
- **ComputeAspectRatio** ()
Returns the aspect ratio of the frustum, defined as the width of the window divided by the height.
- **ComputeCorners** ()
- `ComputeCorners()`
- Returns the world-space corners of the frustum as a vector of 8 points, ordered as:
- `ComputeCornersAtDistance(d)`
- Returns the world-space corners of the intersection of the frustum with a plane parallel to the near/far plane at distance d from the apex, ordered as:
- `ComputeLookAtPoint()`
- Computes and returns the world-space look-at point from the eye point (position), view direction (rotation), and view distance.
- `ComputeNarrowedFrustum(windowPos, size)`
- Returns a frustum that is a narrowed-down version of this frustum.
- `ComputePickRay(windowPos)`
- Builds and returns a `GfRay` that can be used for picking at the given normalized (-1 to +1 in both dimensions) window position.
- `ComputeProjectionMatrix()`
- Returns a GL-style projection matrix corresponding to the frustum's projection.
- `ComputeUpVector()`
- Returns the normalized world-space up vector, which is computed by rotating the y axis by the frustum's rotation.
- `ComputeViewDirection()`
- Returns the normalized world-space view direction vector, which is computed by rotating the -z axis by the frustum's rotation.
- `ComputeViewFrame(side, up, view)`
- Computes the view frame defined by this frustum.
- `ComputeViewInverse()`
- Returns a matrix that represents the inverse viewing transformation for this frustum.
- `ComputeViewMatrix()`
- Returns a matrix that represents the viewing transformation for this frustum.
- `FitToSphere(center, radius, slack)`
- Modifies the frustum to tightly enclose a sphere with the given center and radius, using the current view direction.
- `GetFOV()`
- Returns the horizontal fov of the frustum.
- `GetNearFar()`
- Returns the near/far interval.
- `GetOrthographic()`
- Returns whether the frustum is orthographic.
- `GetOrthographic(left, right, bottom, top, ...)`
- Returns the current frustum in the format used by `SetOrthographic()`.
- `GetPerspective`
- Returns the current perspective frustum values suitable for use by SetPerspective.
- `GetPosition()`
- Returns the position of the frustum in world space.
- `GetProjectionType()`
- Returns the projection type.
- `GetReferencePlaneDepth()`
- `classmethod` GetReferencePlaneDepth() -> float
- `GetRotation()`
- Returns the orientation of the frustum in world space as a rotation to apply to the -z axis.
- `GetViewDistance()`
- Returns the view distance.
- `GetWindow()`
- Returns the window rectangle in the reference plane.
- `Intersects(bbox)`
- Returns true if the given axis-aligned bbox is inside or intersecting the frustum.
- `IntersectsViewVolume(bbox, vpMat)`
- `classmethod` IntersectsViewVolume(bbox, vpMat) -> bool
- `SetNearFar(nearFar)`
- Sets the near/far interval.
- `SetOrthographic(left, right, bottom, top, ...)`
- Sets up the frustum in a manner similar to `glOrtho()`.
- `SetPerspective(fieldOfViewHeight, ...)`
- Sets up the frustum in a manner similar to `gluPerspective()`.
- `SetPosition(position)`
- Sets the position of the frustum in world space.
- `SetPositionAndRotationFromMatrix(camToWorldXf)`
- Sets the position and rotation of the frustum from a camera matrix (always from a y-Up camera).
| Method | Description |
| --- | --- |
| `SetProjectionType(projectionType)` | Sets the projection type. |
| `SetRotation(rotation)` | Sets the orientation of the frustum in world space as a rotation to apply to the default frame: looking along the -z axis with the +y axis as "up". |
| `SetViewDistance(viewDistance)` | Sets the view distance. |
| `SetWindow(window)` | Sets the window rectangle in the reference plane that defines the left, right, top, and bottom planes of the frustum. |
| `Transform(matrix)` | Transforms the frustum by the given matrix. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `Orthographic` | |
| `Perspective` | |
| `nearFar` | |
| `position` | |
| `projectionType` | |
| `rotation` | |
| `viewDistance` | |
| `window` | |
**pxr.Gf.Frustum.ProjectionType**
This enum is used to determine the type of projection represented by a frustum.
**Methods:**
| Method | Description |
| --- | --- |
| `GetValueFromName` | |
**Attributes:**
| allValues |
|-----------|
| allValues |
### GetValueFromName
- **Type**: static
- **Name**: GetValueFromName
### allValues
- **Type**: static
- **Value**: (Gf.Frustum.Orthographic, Gf.Frustum.Perspective)
### ComputeAspectRatio
- **Name**: ComputeAspectRatio
- **Returns**: float
- **Description**: Returns the aspect ratio of the frustum, defined as the width of the window divided by the height. If the height is zero or negative, this returns 0.
### ComputeCorners
- **Name**: ComputeCorners
- **Returns**: list[Vec3d]
- **Description**: Returns the world-space corners of the frustum as a vector of 8 points, ordered as:
- Left bottom near
- Right bottom near
- Left top near
- Right top near
- Left bottom far
- Right bottom far
- Left top far
- Right top far
### ComputeCornersAtDistance
- **Name**: ComputeCornersAtDistance
- **Parameters**:
- d (float)
- **Returns**: list[Vec3d]
- **Description**: Returns the world-space corners of the intersection of the frustum with a plane parallel to the near/far plane at distance d from the apex, ordered as:
- Left bottom
- Right bottom
- Left top
- Right top
- In particular, it gives the partial result of ComputeCorners when given near or far distance.
### ComputeLookAtPoint
- **Name**: ComputeLookAtPoint
- **Returns**: float
## pxr.Gf.Frustum.ComputeLookAtPoint
- **Description**: Computes and returns the world-space look-at point from the eye point (position), view direction (rotation), and view distance.
## pxr.Gf.Frustum.ComputeNarrowedFrustum
- **Description**: Returns a frustum that is a narrowed-down version of this frustum.
- **Parameters**:
- `windowPos` (Vec2d)
- `size` (Vec2d)
- **Details**:
- The new frustum has the same near and far planes, but the other planes are adjusted to be centered on `windowPos` with the new width and height obtained from the existing width and height by multiplying by `size` [0] and `size` [1], respectively.
- `windowPos` is given in normalized coords (-1 to +1 in both dimensions).
- `size` is given as a scalar (0 to 1 in both dimensions).
- If the `windowPos` or `size` given is outside these ranges, it may result in returning a collapsed frustum.
- This method is useful for computing a volume to use for interactive picking.
## pxr.Gf.Frustum.ComputePickRay
- **Description**: Builds and returns a Ray.
- **Parameters**:
- `windowPos`
- **Return**: Ray
<code class="docutils literal notranslate">
<span class="pre">
GfRay
that can be used for picking at the
given normalized (-1 to +1 in both dimensions) window position.
Contrasted with ComputeRay() , that method returns a ray whose origin
is the eyepoint, while this method returns a ray whose origin is on
the near plane.
Parameters
----------
windowPos
(Vec2d) –
ComputePickRay(worldSpacePos) -> Ray
Builds and returns a
<code class="docutils literal notranslate">
<span class="pre">
GfRay
that can be used for picking that
connects the viewpoint to the given 3d point in worldspace.
Parameters
----------
worldSpacePos
(Vec3d) –
ComputeProjectionMatrix() -> Matrix4d
-----------------------------
Returns a GL-style projection matrix corresponding to the frustum’s
projection.
ComputeUpVector() -> Vec3d
--------------------------
Returns the normalized world-space up vector, which is computed by
rotating the y axis by the frustum’s rotation.
ComputeViewDirection() -> Vec3d
-------------------------------
Returns the normalized world-space view direction vector, which is
computed by rotating the -z axis by the frustum’s rotation.
ComputeViewFrame(side, up, view) -> None
-----------------------------------------
Computes the view frame defined by this frustum.
The frame consists of the view direction, up vector and side vector,
as shown in this diagram.
up
^ ^
| /
| / view
|/
+- - - - > side
Parameters
----------
side
(Vec3d) –
up
(Vec3d) –
view
(Vec3d) –
ComputeViewInverse() -> Matrix4d
--------------------------------
Returns the inverse of the view matrix.
### ComputeViewInverse
Returns a matrix that represents the inverse viewing transformation for this frustum.
That is, it returns the matrix that converts points from eye (frustum) space to world space.
### ComputeViewMatrix
Returns a matrix that represents the viewing transformation for this frustum.
That is, it returns the matrix that converts points from world space to eye (frustum) space.
### FitToSphere
Modifies the frustum to tightly enclose a sphere with the given center and radius, using the current view direction.
The planes of the frustum are adjusted as necessary. The given amount of slack is added to the sphere’s radius is used around the sphere to avoid boundary problems.
**Parameters**
- **center** (Vec3d) –
- **radius** (float) –
- **slack** (float) –
### GetFOV
Returns the horizontal fov of the frustum. The fov of the frustum is not necessarily the same value as displayed in the viewer. The displayed fov is a function of the focal length or FOV avar. The frustum’s fov may be different due to things like lens breathing.
If the frustum is not of type GfFrustum::Perspective, the returned FOV will be 0.0.
### GetNearFar
Returns the near/far interval.
### GetOrthographic
Returns the current frustum in the format used by SetOrthographic().
If the current frustum is not an orthographic projection, this returns false and leaves the parameters untouched.
Parameters
----------
- **left** (`float`) –
- **right** (`float`) –
- **bottom** (`float`) –
- **top** (`float`) –
- **nearPlane** (`float`) –
- **farPlane** (`float`) –
GetPerspective
---------------
Returns the current perspective frustum values suitable for use by SetPerspective. If the current frustum is a perspective projection, the return value is a tuple of (fieldOfView, aspectRatio, nearDistance, farDistance). If the current frustum is not perspective, the return value is None.
GetPosition
-----------
Returns the position of the frustum in world space.
GetProjectionType
------------------
Returns the projection type.
GetReferencePlaneDepth
-----------------------
**classmethod** GetReferencePlaneDepth() -> float
Returns the depth of the reference plane.
GetRotation
-----------
Returns the orientation of the frustum in world space as a rotation to apply to the -z axis.
GetViewDistance
----------------
Returns the view distance.
GetWindow
---------
Returns the window rectangle in the reference plane.
Returns true if the given axis-aligned bbox is inside or intersecting the frustum.
Otherwise, it returns false. Useful when doing picking or frustum culling.
Parameters
----------
bbox
(BBox3d) –
Intersects(point) -> bool
--------------------------
Returns true if the given point is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
point
(Vec3d) –
Intersects(p0, p1) -> bool
---------------------------
Returns true if the line segment formed by the given points is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0
(Vec3d) –
p1
(Vec3d) –
Intersects(p0, p1, p2) -> bool
-------------------------------
Returns true if the triangle formed by the given points is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0
(Vec3d) –
p1
(Vec3d) –
p2
(Vec3d) –
classmethod IntersectsViewVolume(bbox, vpMat) -> bool
-------------------------------------------------------
Returns true if the bbox volume intersects the view volume given by the view-projection matrix, erring on the side of false positives for efficiency.
This method is intended for cases where a GfFrustum is not available or when the view-projection matrix yields a view volume that is not expressable as a GfFrustum.
Because it errs on the side of false positives, it is suitable for early-out tests such as draw or intersection culling.
Parameters
----------
bbox
(BBox3d) –
vpMat
(Matrix4d) –
SetNearFar(nearFar) -> None
----------------------------
Sets the near/far interval.
### Parameters
- **nearFar** (Range1d) –
### SetOrthographic
```python
SetOrthographic(left, right, bottom, top, nearPlane, farPlane) -> None
```
Sets up the frustum in a manner similar to `glOrtho()`.
Sets the projection to `GfFrustum::Orthographic` and sets the window and near/far specifications based on the given values.
#### Parameters
- **left** (float) –
- **right** (float) –
- **bottom** (float) –
- **top** (float) –
- **nearPlane** (float) –
- **farPlane** (float) –
### SetPerspective
```python
SetPerspective(fieldOfViewHeight, aspectRatio, nearDistance, farDistance) -> None
```
Sets up the frustum in a manner similar to `gluPerspective()`.
It sets the projection type to `GfFrustum::Perspective` and sets the window specification so that the resulting symmetric frustum encloses an angle of `fieldOfViewHeight` degrees in the vertical direction, with `aspectRatio` used to figure the angle in the horizontal direction. The near and far distances are specified as well. The window coordinates are computed as:
```
top = tan(fieldOfViewHeight / 2)
bottom = -top
right = top \* aspectRatio
left = -right
near = nearDistance
far = farDistance
```
#### Parameters
- **fieldOfViewHeight** (float) –
- **aspectRatio** (float) –
- **nearDistance** (float) –
- **farDistance** (float) –
SetPerspective(fieldOfView, isFovVertical, aspectRatio, nearDistance, farDistance) -> None
Sets up the frustum in a manner similar to gluPerspective().
It sets the projection type to `GfFrustum::Perspective` and sets the window specification so that:
If *isFovVertical* is true, the resulting symmetric frustum encloses an angle of `fieldOfView` degrees in the vertical direction, with `aspectRatio` used to figure the angle in the horizontal direction.
If *isFovVertical* is false, the resulting symmetric frustum encloses an angle of `fieldOfView` degrees in the horizontal direction, with `aspectRatio` used to figure the angle in the vertical direction.
The near and far distances are specified as well. The window coordinates are computed as follows:
> - if isFovVertical:
> - top = tan(fieldOfView / 2)
> - right = top * aspectRatio
> - if NOT isFovVertical:
> - right = tan(fieldOfView / 2)
> - top = right / aspectRatio
> - bottom = -top
> - left = -right
> - near = nearDistance
> - far = farDistance
Parameters:
- **fieldOfView** (float) –
- **isFovVertical** (bool) –
- **aspectRatio** (float) –
- **nearDistance** (float) –
- **farDistance** (float) –
SetPosition(position) -> None
Sets the position of the frustum in world space.
Parameters:
- **position** (Vec3d) –
SetPositionAndRotationFromMatrix(camToWorldXf) -> None
Sets the position and rotation of the frustum from a camera matrix (always from a y-Up camera).
The resulting frustum’s transform will always represent a right-handed and orthonormal coordinate system (scale, shear, and projection are removed from the given `camToWorldXf`).
Parameters:
- **camToWorldXf** (Matrix4d) –
SetProjectionType(projectionType) -> None
Sets the projection type of the frustum.
Parameters:
- **projectionType** (GfFrustum::ProjectionType) –
### SetProjectionType
Sets the projection type.
**Parameters**
- **projectionType** (`Frustum.ProjectionType`) –
### SetRotation
Sets the orientation of the frustum in world space as a rotation to apply to the default frame: looking along the -z axis with the +y axis as "up".
**Parameters**
- **rotation** (`Rotation`) –
### SetViewDistance
Sets the view distance.
**Parameters**
- **viewDistance** (`float`) –
### SetWindow
Sets the window rectangle in the reference plane that defines the left, right, top, and bottom planes of the frustum.
**Parameters**
- **window** (`Range2d`) –
### Transform
Transforms the frustum by the given matrix.
The transformation matrix is applied as follows: the position and the direction vector are transformed with the given matrix. Then the length of the new direction vector is used to rescale the near and far plane and the view distance. Finally, the points that define the reference plane are transformed by the matrix. This method assures that the frustum will not be sheared or perspective-projected.
Note that this definition means that the transformed frustum does not preserve scales very well. Do **not** use this function to transform a frustum that is to be used for precise operations such as intersection testing.
**Parameters**
- **matrix** (`Matrix4d`) –
### Orthographic
```
```markdown
### Perspective
```
```markdown
### property nearFar
```
```markdown
### property position
```
```markdown
### property projectionType
```
```markdown
### property rotation
```
```markdown
### property viewDistance
```
```markdown
### property window
```
```markdown
### class Interval
Basic mathematical interval class
**Methods:**
- **Contains**
Returns true if x is inside the interval.
- **GetFullInterval**
`classmethod GetFullInterval() -> Interval`
- **GetMax**
Get the maximum value.
- **GetMin**
Get the minimum value.
- **GetSize**
The width of the interval
- **In**
(Description not provided in the HTML snippet)
```
Returns true if x is inside the interval.
Intersects(i)
Return true iff the given interval i intersects this interval.
IsEmpty
True if the interval is empty.
IsFinite()
Returns true if both the maximum and minimum value are finite.
IsMaxClosed()
Maximum boundary condition.
IsMaxFinite()
Returns true if the maximum value is finite.
IsMaxOpen()
Maximum boundary condition.
IsMinClosed()
Minimum boundary condition.
IsMinFinite()
Returns true if the minimum value is finite.
IsMinOpen()
Minimum boundary condition.
SetMax
Set the maximum value.
SetMin
Set the minimum value.
Attributes:
finite
isEmpty
True if the interval is empty.
max
The maximum value.
maxClosed
maxFinite
maxOpen
| Property | Description |
|----------|-------------|
| `maxOpen` | |
| `min` | The minimum value. |
| `minClosed` | |
| `minFinite` | |
| `minOpen` | |
| `size` | The width of the interval. |
### Contains()
Returns true if x is inside the interval.
### GetFullInterval()
**classmethod** GetFullInterval() -> Interval
Returns the full interval (-inf, inf).
### GetMax()
Get the maximum value.
### GetMin()
Get the minimum value.
### GetSize()
The width of the interval
### In()
Returns true if x is inside the interval.
### Intersects(i)
Return true iff the given interval i intersects this interval.
**Parameters**
- **i** (Interval) –
### IsEmpty()
- True if the interval is empty.
- **IsFinite**()
- Returns true if both the maximum and minimum value are finite.
- **IsMaxClosed**()
- Maximum boundary condition.
- **IsMaxFinite**()
- Returns true if the maximum value is finite.
- **IsMaxOpen**()
- Maximum boundary condition.
- **IsMinClosed**()
- Minimum boundary condition.
- **IsMinFinite**()
- Returns true if the minimum value is finite.
- **IsMinOpen**()
- Minimum boundary condition.
- **SetMax**()
- Set the maximum value.
- Set the maximum value and boundary condition.
- **SetMin**()
- Set the minimum value.
- Set the minimum value and boundary condition.
- **property finite**
- **property isEmpty**
- True if the interval is empty.
### pxr.Gf.Interval.max
**property**
**max**
The maximum value.
### pxr.Gf.Interval.maxClosed
**property**
**maxClosed**
### pxr.Gf.Interval.maxFinite
**property**
**maxFinite**
### pxr.Gf.Interval.maxOpen
**property**
**maxOpen**
### pxr.Gf.Interval.min
**property**
**min**
The minimum value.
### pxr.Gf.Interval.minClosed
**property**
**minClosed**
### pxr.Gf.Interval.minFinite
**property**
**minFinite**
### pxr.Gf.Interval.minOpen
**property**
**minOpen**
### pxr.Gf.Interval.size
**property**
**size**
The width of the interval.
### pxr.Gf.Line
**class**
**pxr.Gf.Line**
Line class
**Methods:**
- **FindClosestPoint(point, t)**
Returns the point on the line that is closest to `point`.
- **GetDirection()**
Return the normalized direction of the line.
- **GetPoint(t)**
Return the point on the line at `( p0 + t * dir)`.
- **Set(p0, dir)**
param p0
<dd class="field-odd">
<p>
<p>
<strong>
Attributes:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
direction
<td>
<p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.FindClosestPoint">
<span class="sig-name descname">
<span class="pre">
FindClosestPoint
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
point
,
<em class="sig-param">
<span class="n">
<span class="pre">
t
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Vec3d
<a class="headerlink" href="#pxr.Gf.Line.FindClosestPoint" title="Permalink to this definition">
<dd>
<p>
Returns the point on the line that is closest to
<code class="docutils literal notranslate">
<span class="pre">
point
.
<p>
If
<code class="docutils literal notranslate">
<span class="pre">
t
is not
<code class="docutils literal notranslate">
<span class="pre">
None
, it will be set to the parametric distance along the line of the returned point.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
point
(
Vec3d
) –
<li>
<p>
<strong>
t
(
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.GetDirection">
<span class="sig-name descname">
<span class="pre">
GetDirection
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Vec3d
<a class="headerlink" href="#pxr.Gf.Line.GetDirection" title="Permalink to this definition">
<dd>
<p>
Return the normalized direction of the line.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.GetPoint">
<span class="sig-name descname">
<span class="pre">
GetPoint
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
t
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Vec3d
<a class="headerlink" href="#pxr.Gf.Line.GetPoint" title="Permalink to this definition">
<dd>
<p>
Return the point on the line at `` ( p0 + t * dir).
<p>
Remember dir has been normalized so t represents a unit distance.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
t
(
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.Set">
<span class="sig-name descname">
<span class="pre">
Set
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
p0
,
<em class="sig-param">
<span class="n">
<span class="pre">
dir
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
float
<a class="headerlink" href="#pxr.Gf.Line.Set" title="Permalink to this definition">
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
p0
(
Vec3d
) –
<li>
<p>
<strong>
dir
(
Vec3d
) –
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Line.direction">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
## pxr.Gf.LineSeg
Line segment class
### Methods:
| Method | Description |
| --- | --- |
| `FindClosestPoint(point, t)` | Returns the point on the line that is closest to `point`. |
| `GetDirection()` | Return the normalized direction of the line. |
| `GetLength()` | Return the length of the line. |
| `GetPoint(t)` | Return the point on the segment specified by the parameter t. |
### Attributes:
| Attribute | Description |
| --- | --- |
| `direction` | |
| `length` | |
#### FindClosestPoint(point, t)
Returns the point on the line that is closest to `point`.
If `t` is not `None`, it will be set to the parametric distance along the line of the closest point.
**Parameters:**
- **point** (`Vec3d`) –
- **t** (`float`) –
#### GetDirection()
Return the normalized direction of the line.
#### GetLength()
Return the length of the line.
(float)
Return the length of the line.
GetPoint(t) → Vec3d
Return the point on the segment specified by the parameter t.
p = p0 + t * (p1 - p0)
Parameters:
- t (float) –
property direction
property length
class pxr.Gf.Matrix2d
Methods:
- GetColumn(i) - Gets a column of the matrix as a Vec2.
- GetDeterminant() - Returns the determinant of the matrix.
- GetInverse(det, eps) - Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- GetRow(i) - Gets a row of the matrix as a Vec2.
- GetTranspose() - Returns the transpose of the matrix.
- Set(m00, m01, m10, m11) - Sets the matrix from 4 independent double values, specified in row-major order.
- SetColumn(i, v) - Sets a column of the matrix from a Vec2.
- SetDiagonal(s) - Sets the matrix to
<em>s
```python
SetIdentity()
```
Sets the matrix to the identity matrix.
```python
SetRow(i, v)
```
Sets a row of the matrix from a Vec2.
```python
SetZero()
```
Sets the matrix to zero.
**Attributes:**
```python
dimension
```
```python
GetColumn(i) → Vec2d
```
Gets a column of the matrix as a Vec2.
Parameters:
- **i** (int) –
```python
GetDeterminant() → float
```
Returns the determinant of the matrix.
```python
GetInverse(det, eps) → Matrix2d
```
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a `float` can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `*det` is set to the determinant.
Parameters:
- **det** (float) –
- **eps** (float) –
```python
GetRow(i) → Vec2d
```
Gets a row of the matrix as a Vec2.
Parameters:
- **i** (int) –
```
### Parameters
- **i** (`int`) –
### GetTranspose
```
GetTranspose() -> Matrix2d
```
Returns the transpose of the matrix.
### Set
```
Set(m00, m01, m10, m11) -> Matrix2d
```
Sets the matrix from 4 independent `double` values, specified in row-major order.
For example, parameter *m10* specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
### SetColumn
```
SetColumn(i, v) -> None
```
Sets a column of the matrix from a Vec2.
#### Parameters
- **i** (`int`) –
- **v** (`Vec2d`) –
### SetDiagonal
```
SetDiagonal(s) -> Matrix2d
```
Sets the matrix to *s* times the identity matrix.
#### Parameters
- **s** (`float`) –
### Matrix2d Methods
#### SetDiagonal(arg1) -> Matrix2d
Sets the matrix to have diagonal `v[0], v[1]`.
**Parameters:**
- **arg1** (`Vec2d`) –
#### SetIdentity() -> Matrix2d
Sets the matrix to the identity matrix.
#### SetRow(i, v) -> None
Sets a row of the matrix from a Vec2.
**Parameters:**
- **i** (`int`) –
- **v** (`Vec2d`) –
#### SetZero() -> Matrix2d
Sets the matrix to zero.
### Matrix2d Attribute
#### dimension = (2, 2)
### Matrix2f Methods
- **GetColumn(i)** – Gets a column of the matrix as a Vec2.
- **GetDeterminant()** – Returns the determinant of the matrix.
- **GetInverse(det, eps)** – Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **GetRow(i)** – Gets a row of the matrix as a Vec2.
| Method | Description |
|--------|-------------|
| GetRow (i) | Gets a row of the matrix as a Vec2. |
| GetTranspose () | Returns the transpose of the matrix. |
| Set (m00, m01, m10, m11) | Sets the matrix from 4 independent float values, specified in row-major order. |
| SetColumn (i, v) | Sets a column of the matrix from a Vec2. |
| SetDiagonal (s) | Sets the matrix to s times the identity matrix. |
| SetIdentity () | Sets the matrix to the identity matrix. |
| SetRow (i, v) | Sets a row of the matrix from a Vec2. |
| SetZero () | Sets the matrix to zero. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| dimension | |
**Methods:**
- **GetColumn (i) → Vec2f**
- Gets a column of the matrix as a Vec2.
- Parameters:
- **i** (int) –
- **GetDeterminant () → float**
- Returns the determinant of the matrix.
- **GetInverse (det, eps) → Matrix2f**
- Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the
matrix is singular.
The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `\*det` is set to the determinant.
### Parameters
- **det** (`float`) –
- **eps** (`float`) –
### GetRow
```python
GetRow(i) -> Vec2f
```
Gets a row of the matrix as a Vec2.
#### Parameters
- **i** (`int`) –
### GetTranspose
```python
GetTranspose() -> Matrix2f
```
Returns the transpose of the matrix.
### Set
```python
Set(m00, m01, m10, m11) -> Matrix2f
```
Sets the matrix from 4 independent `float` values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
Set(m) -> Matrix2f
Sets the matrix from a 2x2 array of `float` values, specified in row-major order.
#### Parameters
- **m** (`float`) –
### SetColumn
```python
SetColumn(i, v) -> Matrix2f
```
Sets a column of the matrix.
#### Parameters
- **i** (`int`) –
- **v** (`float`) –
### SetColumn
Sets a column of the matrix from a Vec2.
**Parameters**
- **i** (int) –
- **v** (Vec2f) –
### SetDiagonal
Sets the matrix to `s` times the identity matrix.
**Parameters**
- **s** (float) –
SetDiagonal(arg1) -> Matrix2f
Sets the matrix to have diagonal (`v[0]`, `v[1]`).
**Parameters**
- **arg1** (Vec2f) –
### SetIdentity
Sets the matrix to the identity matrix.
### SetRow
Sets a row of the matrix from a Vec2.
**Parameters**
- **i** (int) –
- **v** (Vec2f) –
### SetZero
Sets the matrix to zero.
### dimension
dimension = (2, 2)
## pxr.Gf.Matrix3d
### Methods:
| Method | Description |
|--------|-------------|
| `ExtractRotation()` | Returns the rotation corresponding to this matrix. |
| `GetColumn(i)` | Gets a column of the matrix as a Vec3. |
| `GetDeterminant()` | Returns the determinant of the matrix. |
| `GetHandedness()` | Returns the sign of the determinant of the matrix, i.e. |
| `GetInverse(det, eps)` | Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular. |
| `GetOrthonormalized(issueWarning)` | Returns an orthonormalized copy of the matrix. |
| `GetRow(i)` | Gets a row of the matrix as a Vec3. |
| `GetTranspose()` | Returns the transpose of the matrix. |
| `IsLeftHanded()` | Returns true if the vectors in matrix form a left-handed coordinate system. |
| `IsRightHanded()` | Returns true if the vectors in the matrix form a right-handed coordinate system. |
| `Orthonormalize(issueWarning)` | Makes the matrix orthonormal in place. |
| `Set(m00, m01, m02, m10, m11, m12, m20, m21, m22)` | Sets the matrix from 9 independent double values, specified in row-major order. |
| `SetColumn(i, v)` | Sets a column of the matrix from a Vec3. |
| `SetDiagonal(s)` | Sets the matrix to s times the identity matrix. |
| Method | Description |
|--------|-------------|
| `SetIdentity()` | Sets the matrix to the identity matrix. |
| `SetRotate(rot)` | Sets the matrix to specify a rotation equivalent to `rot`. |
| `SetRow(i, v)` | Sets a row of the matrix from a Vec3. |
| `SetScale(scaleFactors)` | Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`. |
| `SetZero()` | Sets the matrix to zero. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**Methods:**
- **ExtractRotation()** → `Rotation`
- Returns the rotation corresponding to this matrix. This works well only if the matrix represents a rotation. For good results, consider calling Orthonormalize() before calling this method.
- **GetColumn(i)** → `Vec3d`
- Gets a column of the matrix as a Vec3.
- Parameters:
- **i** (int) –
- **GetDeterminant()** → float
- Returns the determinant of the matrix.
- **GetHandedness()** → float
- Returns the sign of the determinant of the matrix, i.e., 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
- **GetInverse(det)** → `Matrix3d`
- Returns the inverse of the matrix.
- Parameters:
- **det** (float) – The determinant of the matrix.
### GetInverse
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a `float` can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `\*det` is set to the determinant.
#### Parameters
- **det** (`float`) –
- **eps** (`float`) –
### GetOrthonormalized
Returns an orthonormalized copy of the matrix.
#### Parameters
- **issueWarning** (`bool`) –
### GetRow
Gets a row of the matrix as a Vec3.
#### Parameters
- **i** (`int`) –
### GetTranspose
Returns the transpose of the matrix.
### IsLeftHanded
Returns true if the vectors in matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the matrix form a right-handed coordinate system.
### Orthonormalize
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If `issueWarning` is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
#### Parameters
- **issueWarning** (`bool`) –
### Set
Sets the matrix from 9 independent `double` values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m02** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
- **m12** (`float`) –
- **m20** (`float`) –
- **m21** (`float`) –
- **m22** (`float`) –
Set(m) -> Matrix3d
Sets the matrix from a 3x3 array of `double` values, specified in row-major order.
#### Parameters
- **m** (`float`) –
### SetColumn
Sets a column of the matrix from a Vec3.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3`) –
### SetDiagonal
```SetDiagonal```
Sets the matrix to `s` times the identity matrix.
**Parameters**
- **s** (`float`) –
SetDiagonal(arg1) -> Matrix3d
Sets the matrix to have diagonal (`v[0], v[1], v[2]`).
**Parameters**
- **arg1** (`Vec3d`) –
### SetIdentity
```SetIdentity```
Sets the matrix to the identity matrix.
### SetRotate
```SetRotate```
Sets the matrix to specify a rotation equivalent to `rot`.
**Parameters**
- **rot** (`Quatd`) –
SetRotate(rot) -> Matrix3d
Sets the matrix to specify a rotation equivalent to `rot`.
**Parameters**
- **rot** (`Rotation`) –
### SetRow
```SetRow```
Sets a row of the matrix from a Vec3.
**Parameters**
- **i** (`int`) –
- **v** (`Vec3d`) –
### SetScale
(scaleFactors) → Matrix3d
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
**Parameters**
- **scaleFactors** (`Vec3d`) –
---
SetScale(scaleFactor) -> Matrix3d
Sets matrix to specify a uniform scaling by `scaleFactor`.
**Parameters**
- **scaleFactor** (`float`) –
---
### SetZero
() → Matrix3d
Sets the matrix to zero.
---
### dimension
= (3, 3)
---
### class pxr.Gf.Matrix3f
**Methods:**
- **ExtractRotation**() - Returns the rotation corresponding to this matrix.
- **GetColumn**(i) - Gets a column of the matrix as a Vec3.
- **GetDeterminant**() - Returns the determinant of the matrix.
- **GetHandedness**() - Returns the sign of the determinant of the matrix, i.e.
- **GetInverse**(det, eps) - Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **GetOrthonormalized**(issueWarning) - Returns an orthonormalized copy of the matrix.
- **GetRow**(i) - Gets a row of the matrix as a Vec3.
<p>
GetTranspose()
<p>
Returns the transpose of the matrix.
<p>
IsLeftHanded()
<p>
Returns true if the vectors in matrix form a left-handed coordinate system.
<p>
IsRightHanded()
<p>
Returns true if the vectors in the matrix form a right-handed coordinate system.
<p>
Orthonormalize(issueWarning)
<p>
Makes the matrix orthonormal in place.
<p>
Set(m00, m01, m02, m10, m11, m12, m20, m21, m22)
<p>
Sets the matrix from 9 independent float values, specified in row-major order.
<p>
SetColumn(i, v)
<p>
Sets a column of the matrix from a Vec3.
<p>
SetDiagonal(s)
<p>
Sets the matrix to s times the identity matrix.
<p>
SetIdentity()
<p>
Sets the matrix to the identity matrix.
<p>
SetRotate(rot)
<p>
Sets the matrix to specify a rotation equivalent to rot.
<p>
SetRow(i, v)
<p>
Sets a row of the matrix from a Vec3.
<p>
SetScale(scaleFactors)
<p>
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
<p>
SetZero()
<p>
Sets the matrix to zero.
<p>
<strong>
Attributes:
<p>
dimension
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Matrix3f.ExtractRotation">
<span class="sig-name descname">
<span class="pre">
ExtractRotation
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Rotation" title="pxr.Gf.Rotation">
<span class="pre">
Rotation
<a class="headerlink" href="#pxr.Gf.Matrix3f.ExtractRotation" title="Permalink to this definition">
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
GetColumn
(
i
)
→ Vec3f
Gets a column of the matrix as a Vec3.
Parameters
----------
i (int) –
GetDeterminant
(
)
→ float
Returns the determinant of the matrix.
GetHandedness
(
)
→ float
Returns the sign of the determinant of the matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
GetInverse
(
det,
eps
)
→ Matrix3f
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a float can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter eps. If det is non-null, *det is set to the determinant.
Parameters
----------
det (float) –
eps (float) –
GetOrthonormalized
(
issueWarning
)
→ Matrix3f
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning (bool) –
GetRow
(
i
)
→ Vec3f
Gets a row of the matrix as a Vec3.
### GetRow
Gets a row of the matrix as a Vec3.
#### Parameters
- **i** (int) –
### GetTranspose
Returns the transpose of the matrix.
### IsLeftHanded
Returns true if the vectors in matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the matrix form a right-handed coordinate system.
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If `issueWarning` is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
#### Parameters
- **issueWarning** (bool) –
### Set
Sets the matrix from 9 independent float values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (float) –
- **m01** (float) –
- **m02** (float) –
- **m10** (float) –
- **m11** (float) –
- **m12** (float) –
- **m20** (float) –
- **m21** (float) –
- **m22** (float) –
**m01** (**float**) –
**m02** (**float**) –
**m10** (**float**) –
**m11** (**float**) –
**m12** (**float**) –
**m20** (**float**) –
**m21** (**float**) –
**m22** (**float**) –
Set(m) -> Matrix3f
Sets the matrix from a 3x3 array of `float` values, specified in row-major order.
**Parameters**
- **m** (**float**) –
**SetColumn** (i, v) -> None
Sets a column of the matrix from a Vec3.
**Parameters**
- **i** (**int**) –
- **v** (**Vec3f**) –
**SetDiagonal** (s) -> Matrix3f
Sets the matrix to s times the identity matrix.
**Parameters**
- **s** (**float**) –
SetDiagonal(arg1) -> Matrix3f
Sets the matrix to have diagonal (`v[0], v[1], v[2]`).
**Parameters**
- **arg1** (**Vec3f**) –
**SetIdentity** () -> Matrix3f
Sets the matrix to the identity matrix.
**SetRotate** (rot) -> None
Sets the matrix to represent a rotation.
**Parameters**
- **rot** (**Gf.Rotation**) –
### SetRotate Method
Sets the matrix to specify a rotation equivalent to `rot`.
#### Parameters
- **rot** (`Quatf`) –
---
SetRotate(rot) -> Matrix3f
Sets the matrix to specify a rotation equivalent to `rot`.
#### Parameters
- **rot** (`Rotation`) –
### SetRow Method
Sets a row of the matrix from a Vec3.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetScale Method
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
#### Parameters
- **scaleFactors** (`Vec3f`) –
---
SetScale(scaleFactor) -> Matrix3f
Sets matrix to specify a uniform scaling by `scaleFactor`.
#### Parameters
- **scaleFactor** (`float`) –
### SetZero Method
Sets the matrix to zero.
### dimension Attribute
dimension = (3, 3)
## Methods:
| Method | Description |
| --- | --- |
| `ExtractRotation()` | Returns the rotation corresponding to this matrix. |
| `ExtractRotationMatrix()` | Returns the rotation corresponding to this matrix. |
| `ExtractRotationQuat()` | Return the rotation corresponding to this matrix as a quaternion. |
| `ExtractTranslation()` | Returns the translation part of the matrix, defined as the first three elements of the last row. |
| `Factor(r, s, u, t, p, eps)` | Factors the matrix into 5 components: |
| `GetColumn(i)` | Gets a column of the matrix as a Vec4. |
| `GetDeterminant()` | Returns the determinant of the matrix. |
| `GetDeterminant3()` | Returns the determinant of the upper 3x3 matrix. |
| `GetHandedness()` | Returns the sign of the determinant of the upper 3x3 matrix, i.e. |
| `GetInverse(det, eps)` | Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular. |
| `GetOrthonormalized(issueWarning)` | Returns an orthonormalized copy of the matrix. |
| `GetRow(i)` | Gets a row of the matrix as a Vec4. |
| `GetRow3(i)` | Gets a row of the matrix as a Vec3. |
| `GetTranspose()` | Returns the transpose of the matrix. |
| `HasOrthogonalRows3()` | Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis. |
IsLeftHanded()
Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
IsRightHanded()
Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
Orthonormalize(issueWarning)
Makes the matrix orthonormal in place.
RemoveScaleShear()
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
Set(m00, m01, m02, m03, m10, m11, m12, m13, ...)
Sets the matrix from 16 independent double values, specified in row-major order.
SetColumn(i, v)
Sets a column of the matrix from a Vec4.
SetDiagonal(s)
Sets the matrix to s times the identity matrix.
SetIdentity()
Sets the matrix to the identity matrix.
SetLookAt(eyePoint, centerPoint, upDirection)
Sets the matrix to specify a viewing matrix from parameters similar to those used by gluLookAt(3G).
SetRotate(rot)
Sets the matrix to specify a rotation equivalent to rot, and clears the translation.
SetRotateOnly(rot)
Sets the matrix to specify a rotation equivalent to rot, without clearing the translation.
SetRow(i, v)
Sets a row of the matrix from a Vec4.
SetRow3(i, v)
Sets a row of the matrix from a Vec3.
SetScale(scaleFactors)
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
SetTransform()
| Method | Description |
|--------|-------------|
| `SetTransform(rotate, translate)` | Sets matrix to specify a rotation by `rotate` and a translation by `translate`. |
| `SetTranslate(trans)` | Sets matrix to specify a translation by the vector `trans`, and clears the rotation. |
| `SetTranslateOnly(t)` | Sets matrix to specify a translation by the vector `trans`, without clearing the rotation. |
| `SetZero()` | Sets the matrix to zero. |
| `Transform(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformAffine(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformDir(vec)` | Transforms row vector `vec` by the matrix, returning the result. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**Methods:**
- **ExtractRotation()**
- Returns the rotation corresponding to this matrix.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
- **ExtractRotationMatrix()**
- Returns the rotation corresponding to this matrix.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
- **ExtractRotationQuat()**
- Return the rotation corresponding to this matrix as a quaternion.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
### ExtractTranslation
Returns the translation part of the matrix, defined as the first three elements of the last row.
### Factor
Factors the matrix into 5 components:
- *M* = r \* s \* -r \* u \* t where
- t is a translation.
- u and r are rotations, and -r is the transpose (inverse) of r. The u matrix may contain shear information.
- s is a scale. Any projection information could be returned in matrix p, but currently p is never modified.
Returns `false` if the matrix is singular (as determined by eps).
In that case, any zero scales in s are clamped to eps to allow computation of u.
#### Parameters
- **r** (Matrix4d) –
- **s** (Vec3d) –
- **u** (Matrix4d) –
- **t** (Vec3d) –
- **p** (Matrix4d) –
- **eps** (float) –
### GetColumn
## pxr.Gf.Matrix4d.GetColumn
- **Description**: Gets a column of the matrix as a Vec4.
- **Parameters**:
- **i** (int) –
## pxr.Gf.Matrix4d.GetDeterminant
- **Description**: Returns the determinant of the matrix.
## pxr.Gf.Matrix4d.GetDeterminant3
- **Description**: Returns the determinant of the upper 3x3 matrix.
- **Additional Info**: This method is useful when the matrix describes a linear transformation such as a rotation or scale because the other values in the 4x4 matrix are not important.
## pxr.Gf.Matrix4d.GetHandedness
- **Description**: Returns the sign of the determinant of the upper 3x3 matrix, i.e. 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
## pxr.Gf.Matrix4d.GetInverse
- **Description**: Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **Additional Info**: The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `*det` is set to the determinant.
- **Parameters**:
- **det** (float) –
- **eps** (float) –
## pxr.Gf.Matrix4d.GetOrthonormalized
- **Description**: Returns an orthonormalized copy of the matrix.
- **Parameters**:
- **issueWarning** (bool) –
## pxr.Gf.Matrix4d.GetRow
- **Description**: Gets a row of the matrix as a Vec4.
- **Parameters**:
- **i** (int) –
### GetRow
Gets a row of the matrix as a Vec4.
**Parameters**
- **i** (int) –
### GetRow3
Gets a row of the matrix as a Vec3.
**Parameters**
- **i** (int) –
### GetTranspose
Returns the transpose of the matrix.
### HasOrthogonalRows3
Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.
Note they do not have to be unit length for this test to return true.
### IsLeftHanded
Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If issueWarning is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
**Parameters**
- **issueWarning** (bool) –
### RemoveScaleShear
Returns a matrix with scale and shear removed.
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
If the matrix cannot be decomposed, returns the original matrix.
Set
(
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33
) -> Matrix4d
Sets the matrix from 16 independent double values, specified in row-major order.
For example, parameter m10 specifies the value in row 1 and column 0.
Parameters:
- m00 (float) –
- m01 (float) –
- m02 (float) –
- m03 (float) –
- m10 (float) –
- m11 (float) –
- m12 (float) –
- m13 (float) –
- m20 (float) –
- m21 (float) –
- m22 (float) –
- m23 (float) –
- m30 (float) –
- m31 (float) –
- m32 (float) –
- m33 (float) –
Set(m) -> Matrix4d
Sets the matrix from a 4x4 array of double
values, specified in row-major order.
### Parameters
**m** (*float*) –
### Parameters
- **i** (*int*) –
- **v** (*Vec4d*) –
Sets a column of the matrix from a Vec4.
### Parameters
**s** (*float*) –
Sets the matrix to *s* times the identity matrix.
SetDiagonal(arg1) -> Matrix4d
Sets the matrix to have diagonal (*v*[0], *v*[1], *v*[2], *v*[3]).
### Parameters
**arg1** (*Vec4d*) –
### Parameters
- **eyePoint** (*Vec3d*) –
- **centerPoint** (*Vec3d*) –
- **upDirection** (*Vec3d*) –
Sets the matrix to specify a viewing matrix from parameters similar to those used by `gluLookAt(3G)`.
*eyePoint* represents the eye point in world space.
*centerPoint* represents the world-space center of attention.
*upDirection* is a vector indicating which way is up.
- **centerPoint** (Vec3d) –
- **upDirection** (Vec3d) –
SetLookAt(eyePoint, orientation) -> Matrix4d
Sets the matrix to specify a viewing matrix from a world-space `eyePoint` and a world-space rotation that rigidly rotates the orientation from its canonical frame, which is defined to be looking along the `-z` axis with the `+y` axis as the up direction.
- **Parameters**
- **eyePoint** (Vec3d) –
- **orientation** (Rotation) –
- **SetRotate**
- **Parameters**
- **rot** (Quatd) –
SetRotate(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `rot`, and clears the translation.
- **Parameters**
- **rot** (Rotation) –
- **SetRotate**
- **Parameters**
- **mx** (Matrix3d) –
SetRotate(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `mx`, and clears the translation.
- **SetRotateOnly**
- **Parameters**
- **rot** (Quatd) –
SetRotateOnly(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `rot`, without clearing the translation.
- **Parameters**
- **rot** (Rotation) –
- **SetRotateOnly**
- **Parameters**
- **mx** (Matrix3d) –
SetRotateOnly(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `mx`, without clearing the translation.
### SetRow
Sets a row of the matrix from a Vec4.
**Parameters**
- **i** (int) –
- **v** (Vec4d) –
### SetRow3
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
**Parameters**
- **i** (int) –
- **v** (Vec3d) –
### SetScale
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
**Parameters**
- **scaleFactors** (Vec3d) –
SetScale(scaleFactor) -> Matrix4d
Sets matrix to specify a uniform scaling by scaleFactor.
**Parameters**
- **scaleFactor** (float) –
### SetTransform
Sets matrix to specify a rotation by rotate and a translation by translate.
**Parameters**
- **rotate** (Rotation) –
- **translate** (Vec3d) –
- **rotate** (**Vec3d**) –
- **translate** (**Vec3d**) –
---
SetTransform(rotmx, translate) -> Matrix4d
Sets matrix to specify a rotation by **rotmx** and a translation by **translate**.
- **rotmx** (**Matrix3d**) –
- **translate** (**Vec3d**) –
---
SetTranslate(trans) -> Matrix4d
Sets matrix to specify a translation by the vector **trans**, and clears the rotation.
- **trans** (**Vec3d**) –
---
SetTranslateOnly(t) -> Matrix4d
Sets matrix to specify a translation by the vector **trans**, without clearing the rotation.
- **t** (**Vec3d**) –
---
SetZero() -> Matrix4d
Sets the matrix to zero.
---
Transform(vec) -> Vec3d
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1.
- **vec** (**Vec3d**) –
---
Transform(vec) -> Vec3f
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1. This is an overloaded method; it differs from the other version in that it returns a different value type.
- **vec** (**Vec3f**) –
### TransformAffine Method
```python
TransformAffine(vec)
```
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters:**
- **vec** (Vec3d) –
---
```python
TransformAffine(vec) -> Vec3f
```
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters:**
- **vec** (Vec3f) –
### TransformDir Method
```python
TransformDir(vec)
```
Transforms row vector `vec` by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0.
**Parameters:**
- **vec** (Vec3d) –
---
```python
TransformDir(vec) -> Vec3f
```
Transforms row vector `vec` by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0. This is an overloaded method; it differs from the other version in that it returns a different value type.
**Parameters:**
- **vec** (Vec3f) –
### dimension Attribute
```python
dimension = (4, 4)
```
### Matrix4f Class
**Methods:**
- `ExtractRotation()` - Returns the rotation corresponding to this matrix.
- `ExtractRotationMatrix()` - Returns the rotation corresponding to this matrix.
```
- `ExtractRotationQuat()`
- Return the rotation corresponding to this matrix as a quaternion.
- `ExtractTranslation()`
- Returns the translation part of the matrix, defined as the first three elements of the last row.
- `Factor(r, s, u, t, p, eps)`
- Factors the matrix into 5 components:
- `GetColumn(i)`
- Gets a column of the matrix as a Vec4.
- `GetDeterminant()`
- Returns the determinant of the matrix.
- `GetDeterminant3()`
- Returns the determinant of the upper 3x3 matrix.
- `GetHandedness()`
- Returns the sign of the determinant of the upper 3x3 matrix, i.e.
- `GetInverse(det, eps)`
- Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- `GetOrthonormalized(issueWarning)`
- Returns an orthonormalized copy of the matrix.
- `GetRow(i)`
- Gets a row of the matrix as a Vec4.
- `GetRow3(i)`
- Gets a row of the matrix as a Vec3.
- `GetTranspose()`
- Returns the transpose of the matrix.
- `HasOrthogonalRows3()`
- Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.
- `IsLeftHanded()`
- Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
- `IsRightHanded()`
- Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
- `Orthonormalize(issueWarning)`
- Orthonormalizes the matrix.
Makes the matrix orthonormal in place.
RemoveScaleShear()
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
Set(m00, m01, m02, m03, m10, m11, m12, m13, ...)
Sets the matrix from 16 independent float values, specified in row-major order.
SetColumn(i, v)
Sets a column of the matrix from a Vec4.
SetDiagonal(s)
Sets the matrix to s times the identity matrix.
SetIdentity()
Sets the matrix to the identity matrix.
SetLookAt(eyePoint, centerPoint, upDirection)
Sets the matrix to specify a viewing matrix from parameters similar to those used by gluLookAt(3G).
SetRotate(rot)
Sets the matrix to specify a rotation equivalent to rot, and clears the translation.
SetRotateOnly(rot)
Sets the matrix to specify a rotation equivalent to rot, without clearing the translation.
SetRow(i, v)
Sets a row of the matrix from a Vec4.
SetRow3(i, v)
Sets a row of the matrix from a Vec3.
SetScale(scaleFactors)
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
SetTransform(rotate, translate)
Sets matrix to specify a rotation by rotate and a translation by translate.
SetTranslate(trans)
Sets matrix to specify a translation by the vector trans, and clears the rotation.
SetTranslateOnly(t)
| Method | Description |
|--------|-------------|
| `SetZero()` | Sets the matrix to zero. |
| `Transform(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformAffine(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformDir(vec)` | Transforms row vector `vec` by the matrix, returning the result. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
### ExtractRotation()
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractRotationMatrix()
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractRotationQuat()
Return the rotation corresponding to this matrix as a quaternion.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractTranslation()
Returns the translation part of the matrix, defined as the first three elements of the last row.
### Factor Method
Factors the matrix into 5 components:
> - *M* = r \* s \* -r \* u \* t where
> - t is a translation.
> - u and r are rotations, and -r is the transpose (inverse) of r. The u matrix may contain shear information.
> - s is a scale. Any projection information could be returned in matrix p, but currently p is never modified.
> - Returns `false` if the matrix is singular (as determined by eps). In that case, any zero scales in s are clamped to eps to allow computation of u.
#### Parameters
- **r** (Matrix4f) –
- **s** (Vec3f) –
- **u** (Matrix4f) –
- **t** (Vec3f) –
- **p** (Matrix4f) –
- **eps** (float) –
### GetColumn Method
Gets a column of the matrix as a Vec4.
#### Parameters
- **i** (int) –
### GetDeterminant Method
Returns the determinant of the matrix.
### GetDeterminant3
Returns the determinant of the upper 3x3 matrix.
This method is useful when the matrix describes a linear transformation such as a rotation or scale because the other values in the 4x4 matrix are not important.
### GetHandedness
Returns the sign of the determinant of the upper 3x3 matrix, i.e. 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
### GetInverse
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a float can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter eps. If det is non-null, *det is set to the determinant.
**Parameters**
- **det** (float) –
- **eps** (float) –
### GetOrthonormalized
Returns an orthonormalized copy of the matrix.
**Parameters**
- **issueWarning** (bool) –
### GetRow
Gets a row of the matrix as a Vec4.
**Parameters**
- **i** (int) –
### GetRow3
Gets a row of the matrix as a Vec3.
**Parameters**
- **i** (int) –
<p>Gets a row of the matrix as a Vec3.
<dl class="field-list simple">
<dt class="field-odd">Parameters
<dd class="field-odd">
<p><strong>i
<p>Returns the transpose of the matrix.
<p>Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.
<p>Note they do not have to be unit length for this test to return true.
<p>Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
<p>Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
<p>Makes the matrix orthonormal in place.
<p>This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
<p>Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If <em>issueWarning
<dl class="field-list simple">
<dt class="field-odd">Parameters
<dd class="field-odd">
<p><strong>issueWarning
<p>Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
<p>If the matrix cannot be decomposed, returns the original matrix.
<p>Set
<p>Sets the matrix to the specified values.
Sets the matrix from 16 independent `float` values, specified in row-major order.
For example, parameter *m10* specifies the value in row1 and column 0.
**Parameters**
- **m00** (*float*) –
- **m01** (*float*) –
- **m02** (*float*) –
- **m03** (*float*) –
- **m10** (*float*) –
- **m11** (*float*) –
- **m12** (*float*) –
- **m13** (*float*) –
- **m20** (*float*) –
- **m21** (*float*) –
- **m22** (*float*) –
- **m23** (*float*) –
- **m30** (*float*) –
- **m31** (*float*) –
- **m32** (*float*) –
- **m33** (*float*) –
Set(m) -> Matrix4f
Sets the matrix from a 4x4 array of `float` values, specified in row-major order.
**Parameters**
- **m** (*float*) –
SetColumn(i, v) -> None
### Sets a column of the matrix from a Vec4.
#### Parameters
- **i** (`int`) –
- **v** (`Vec4f`) –
### SetDiagonal(s) -> Matrix4f
Sets the matrix to `s` times the identity matrix.
#### Parameters
- **s** (`float`) –
---
SetDiagonal(arg1) -> Matrix4f
Sets the matrix to have diagonal (`v[0], v[1], v[2], v[3]`).
#### Parameters
- **arg1** (`Vec4f`) –
### SetIdentity() -> Matrix4f
Sets the matrix to the identity matrix.
### SetLookAt(eyePoint, centerPoint, upDirection) -> Matrix4f
Sets the matrix to specify a viewing matrix from parameters similar to those used by `gluLookAt(3G)`.
#### Parameters
- **eyePoint** (`Vec3f`) –
- **centerPoint** (`Vec3f`) –
- **upDirection** (`Vec3f`) –
---
SetLookAt(eyePoint, orientation) -> Matrix4f
Sets the matrix to specify a viewing matrix from a world-space `eyePoint` and a world-space rotation that rigidly rotates the orientation from its canonical frame, which is defined to be looking along the `-z` axis with the `+y` axis as the up direction.
- **eyePoint** (**Vec3f**) –
- **orientation** (**Rotation**) –
### SetRotate
SetRotate(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, and clears the translation.
#### Parameters
- **rot** (**Quatf**) –
SetRotate(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, and clears the translation.
#### Parameters
- **rot** (**Rotation**) –
SetRotate(mx) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **mx**, and clears the translation.
#### Parameters
- **mx** (**Matrix3f**) –
### SetRotateOnly
SetRotateOnly(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, without clearing the translation.
#### Parameters
- **rot** (**Quatf**) –
SetRotateOnly(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, without clearing the translation.
#### Parameters
- **rot** (**Rotation**) –
SetRotateOnly(mx) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **mx**, without clearing the translation.
#### Parameters
- **mx** (**Matrix3f**) –
### SetRow
SetRow(i, v) → **None**
Sets a row of the matrix from a Vec4.
#### Parameters
- **i**
- **v**
- **i** (`int`) –
- **v** (`Vec4f`) –
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetRow3
```python
SetRow3(i, v) -> None
```
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetScale
```python
SetScale(scaleFactors) -> Matrix4f
```
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
#### Parameters
- **scaleFactors** (`Vec3f`) –
```python
SetScale(scaleFactor) -> Matrix4f
```
Sets matrix to specify a uniform scaling by `scaleFactor`.
#### Parameters
- **scaleFactor** (`float`) –
### SetTransform
```python
SetTransform(rotate, translate) -> Matrix4f
```
Sets matrix to specify a rotation by `rotate` and a translation by `translate`.
#### Parameters
- **rotate** (`Rotation`) –
- **translate** (`Vec3f`) –
```python
SetTransform(rotmx, translate) -> Matrix4f
```
Sets matrix to specify a rotation by `rotmx` and a translation by `translate`.
#### Parameters
- **rotmx** (`Matrix3f`) –
- **translate** (`Vec3f`) –
### SetTranslate
```python
SetTranslate(trans)
```
- **Parameters**:
- **trans** (Vec3f) –
Sets matrix to specify a translation by the vector `trans`, and clears the rotation.
### SetTranslateOnly
```python
SetTranslateOnly(t)
```
- **Parameters**:
- **t** (Vec3f) –
Sets matrix to specify a translation by the vector `trans`, without clearing the rotation.
### SetZero
```python
SetZero()
```
Sets the matrix to zero.
### Transform
```python
Transform(vec)
```
- **Parameters**:
- **vec** (Vec3d) –
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1.
### TransformAffine
```python
TransformAffine(vec)
```
- **Parameters**:
- **vec** (Vec3d) –
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**vec** (**Vec3d**) –
TransformAffine(vec) -> Vec3f
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters**
- **vec** (**Vec3f**) –
**TransformDir**(vec) -> Vec3d
Transforms row vector **vec** by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0.
**Parameters**
- **vec** (**Vec3d**) –
TransformDir(vec) -> Vec3f
Transforms row vector **vec** by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0. This is an overloaded method; it differs from the other version in that it returns a different value type.
**Parameters**
- **vec** (**Vec3f**) –
**dimension** = (4, 4)
**class** pxr.Gf.**MultiInterval**
**Methods:**
- **Add**(i)
- Add the given interval to the multi-interval.
- **ArithmeticAdd**(i)
- Uses the given interval to extend the multi-interval in the interval arithmetic sense.
- **Clear**()
- Clear the multi-interval.
- **Contains**
- Returns true if x is inside the multi-interval.
- **GetBounds**()
- Returns an interval bounding the entire multi-interval.
- **GetComplement**()
- Returns an interval that is the complement of the multi-interval.
### Methods
- **GetComplement()**
- Return the complement of this set.
- **GetFullInterval()**
- `classmethod` GetFullInterval() -> MultiInterval
- **GetSize()**
- Returns the number of intervals in the set.
- **Intersect(i)**
- param i
- **IsEmpty()**
- Returns true if the multi-interval is empty.
- **Remove(i)**
- Remove the given interval from this multi-interval.
### Attributes
- **bounds**
- **isEmpty**
- **size**
### Methods
- **Add(i)**
- Add the given interval to the multi-interval.
- Parameters:
- **i** (Interval) –
- Add(s) -> None
- Add the given multi-interval to the multi-interval.
- Sets this object to the union of the two sets.
- Parameters:
- **s** (MultiInterval) –
- **ArithmeticAdd(i)**
- Uses the given interval to extend the multi-interval in the interval arithmetic sense.
- Parameters:
- **i** (Interval) –
<strong>i
### Clear
```python
Clear() -> None
```
Clear the multi-interval.
### Contains
```python
Contains() -> bool
```
Returns true if x is inside the multi-interval.
Returns true if x is inside the multi-interval.
Returns true if x is inside the multi-interval.
### GetBounds
```python
GetBounds() -> Interval
```
Returns an interval bounding the entire multi-interval.
Returns an empty interval if the multi-interval is empty.
### GetComplement
```python
GetComplement() -> MultiInterval
```
Return the complement of this set.
### GetFullInterval
```python
@classmethod
GetFullInterval() -> MultiInterval
```
Returns the full interval (-inf, inf).
### GetSize
```python
GetSize() -> int
```
Returns the number of intervals in the set.
### Intersect
```python
Intersect(i: Interval) -> None
```
Parameters:
- **i** (**Interval**) –
```python
Intersect(s: MultiInterval) -> None
```
Parameters:
- **s** (**MultiInterval**) –
### IsEmpty
```python
IsEmpty() -> bool
### pxr.Gf.MultiInterval.IsEmpty
- **Description:** Returns true if the multi-interval is empty.
### pxr.Gf.MultiInterval.Remove
- **Function:** Remove(i) -> None
- **Description:** Remove the given interval from this multi-interval.
- **Parameters:**
- **i** (Interval) –
- **Description:** Remove(s) -> None
- **Description:** Remove the given multi-interval from this multi-interval.
- **Parameters:**
- **s** (MultiInterval) –
### pxr.Gf.MultiInterval.bounds
- **Property:** bounds
### pxr.Gf.MultiInterval.isEmpty
- **Property:** isEmpty
### pxr.Gf.MultiInterval.size
- **Property:** size
### pxr.Gf.Plane
- **Methods:**
- **GetDistance(p):** Returns the distance of point from the plane.
- **GetDistanceFromOrigin():** Returns the distance of the plane from the origin.
- **GetEquation():** Give the coefficients of the equation of the plane.
- **GetNormal():** Returns the unit-length normal vector of the plane.
- **IntersectsPositiveHalfSpace(box):** Returns true if the given aligned bounding box is at least partially on the positive side (the one the normal points into) of the plane.
| Method | Description |
| --- | --- |
| `GetDistance(p)` | Returns the distance of point `p` from the plane. This distance will be positive if the point is on the side of the plane containing the normal. |
| `GetDistanceFromOrigin()` | Returns the distance of the plane from the origin. |
| `GetEquation()` | Give the coefficients of the equation of the plane. Suitable to OpenGL calls to set the clipping plane. |
| `GetNormal()` | Returns the unit-length normal vector of the plane. |
| `IntersectsPositiveHalfSpace()` | |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `distanceFromOrigin` | |
| `normal` | |
### IntersectsPositiveHalfSpace
Returns `true` if the given aligned bounding box is at least partially on the positive side (the one the normal points into) of the plane.
**Parameters**
- **box** (`Range3d`) –
---
IntersectsPositiveHalfSpace(pt) -> bool
Returns true if the given point is on the plane or within its positive half space.
**Parameters**
- **pt** (`Vec3d`) –
### Project
Return the projection of `p` onto the plane.
**Parameters**
- **p** (`Vec3d`) –
### Reorient
Flip the plane normal (if necessary) so that `p` is in the positive halfspace.
**Parameters**
- **p** (`Vec3d`) –
### Set
Sets this to the plane perpendicular to `normal` and at `distance` units from the origin. The passed-in normal is normalized to unit length first.
**Parameters**
- **normal** (`Vec3d`) –
- **distanceToOrigin** (`float`) –
---
Set(normal, point) -> None
This constructor sets this to the plane perpendicular to `normal` and that passes through `point`.
The passed-in normal is normalized to unit length first.
Parameters
----------
- **normal** (`Vec3d`) –
- **point** (`Vec3d`) –
Set(p0, p1, p2) -> None
-----------------------
This constructor sets this to the plane that contains the three given points.
The normal is constructed from the cross product of (p1 - p0) and (p2 - p0). Results are undefined if the points are collinear.
Parameters
----------
- **p0** (`Vec3d`) –
- **p1** (`Vec3d`) –
- **p2** (`Vec3d`) –
Set(eqn) -> None
----------------
This method sets this to the plane given by the equation eqn[0] * x + eqn[1] * y + eqn[2] * z + eqn[3] = 0.
Parameters
----------
- **eqn** (`Vec4d`) –
Transform(matrix) -> Plane
--------------------------
Transforms the plane by the given matrix.
Parameters
----------
- **matrix** (`Matrix4d`) –
property distanceFromOrigin
---------------------------
property normal
---------------
class pxr.Gf.Quatd
------------------
Methods:
- **GetConjugate** ()
| Method | Description |
| --- | --- |
| `GetConjugate()` | Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients. |
| `GetIdentity` | classmethod GetIdentity() -> Quatd |
| `GetImaginary()` | Return the imaginary coefficient. |
| `GetInverse()` | Return this quaternion's inverse, or reciprocal. |
| `GetLength()` | Return geometric length of this quaternion. |
| `GetNormalized(eps)` | If length of this quaternion is smaller than `eps`, return the identity quaternion. |
| `GetReal()` | Return the real coefficient. |
| `GetZero` | classmethod GetZero() -> Quatd |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
| `SetImaginary(imaginary)` | Set the imaginary coefficients. |
| `SetReal(real)` | Set the real coefficient. |
| `Transform(point)` | Transform the GfVec3d point. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `imaginary` | |
| `real` | |
### GetConjugate()
Return this quaternion’s conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients.
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetIdentity
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Quatd.GetIdentity" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetIdentity() -> Quatd
<p>
Return the identity quaternion, with real coefficient 1 and an imaginary coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3d" title="pxr.Gf.Vec3d">
<span class="pre">
Vec3d
<a class="headerlink" href="#pxr.Gf.Quatd.GetImaginary" title="Permalink to this definition">
<dd>
<p>
Return the imaginary coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatd" title="pxr.Gf.Quatd">
<span class="pre">
Quatd
<a class="headerlink" href="#pxr.Gf.Quatd.GetInverse" title="Permalink to this definition">
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
<p>
This is the quaternion’s conjugate divided by it’s squared length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatd.GetLength" title="Permalink to this definition">
<dd>
<p>
Return geometric length of this quaternion.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatd" title="pxr.Gf.Quatd">
<span class="pre">
Quatd
<a class="headerlink" href="#pxr.Gf.Quatd.GetNormalized" title="Permalink to this definition">
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, return the identity quaternion.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatd.GetReal" title="Permalink to this definition">
<dd>
<p>
Return the real coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetZero">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetZero
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Quatd.GetZero" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetZero() -> Quatd
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatd.Normalize" title="Permalink to this definition">
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the length before normalization.
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, this sets the quaternion to identity.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
### eps (float) –
### SetImaginary
Set the imaginary coefficients.
**Parameters**
- **imaginary** (Vec3d) –
SetImaginary(i, j, k) -> None
Set the imaginary coefficients.
**Parameters**
- **i** (float) –
- **j** (float) –
- **k** (float) –
### SetReal
Set the real coefficient.
**Parameters**
- **real** (float) –
### Transform
Transform the GfVec3d point.
If the quaternion is normalized, the transformation is a rotation. Given a GfQuatd q, q.Transform(point) is equivalent to: (q * GfQuatd(0, point) * q.GetInverse()).GetImaginary() but is more efficient.
**Parameters**
- **point** (Vec3d) –
### property imaginary
### property real
### class pxr.Gf.Quaternion
Quaternion class
**Methods:**
- **GetIdentity**
| Method | Description |
| --- | --- |
| `classmethod GetIdentity()` | Returns the identity quaternion, which has a real part of 1 and an imaginary part of (0,0,0). |
| `GetImaginary()` | Returns the imaginary part of the quaternion. |
| `GetInverse()` | Returns the inverse of this quaternion. |
| `GetLength()` | Returns geometric length of this quaternion. |
| `GetNormalized(eps)` | Returns a normalized (unit-length) version of this quaternion. |
| `GetReal()` | Returns the real part of the quaternion. |
| `classmethod GetZero()` | Returns the zero quaternion. |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `imaginary` | None |
| `real` | None |
**Methods:**
**GetIdentity**
```python
classmethod GetIdentity() -> Quaternion
```
Returns the identity quaternion, which has a real part of 1 and an imaginary part of (0,0,0).
**GetImaginary**
```python
GetImaginary() -> Vec3d
```
Returns the imaginary part of the quaternion.
**GetInverse**
```python
GetInverse() -> Quaternion
```
Returns the inverse of this quaternion.
**GetLength**
```python
GetLength()
```
Returns geometric length of this quaternion.
### pxr.Gf.Quaternion.GetLength
- **Returns**: geometric length of this quaternion.
### pxr.Gf.Quaternion.GetNormalized
- **Returns**: a normalized (unit-length) version of this quaternion.
- **Parameters**:
- **eps** (float) –
### pxr.Gf.Quaternion.GetReal
- **Returns**: the real part of the quaternion.
### pxr.Gf.Quaternion.GetZero
- **Returns**: the zero quaternion, which has a real part of 0 and an imaginary part of (0,0,0).
### pxr.Gf.Quaternion.Normalize
- **Returns**: the length before normalization.
- **Parameters**:
- **eps** (float) –
### pxr.Gf.Quaternion.imaginary
- **Type**: type
### pxr.Gf.Quaternion.real
- **Type**: type
| Method | Description |
|--------|-------------|
| `GetConjugate()` | Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients. |
| `GetIdentity` | `classmethod GetIdentity() -> Quatf` |
| `GetImaginary()` | Return the imaginary coefficient. |
| `GetInverse()` | Return this quaternion's inverse, or reciprocal. |
| `GetLength()` | Return geometric length of this quaternion. |
| `GetNormalized(eps)` | If the length of this quaternion is smaller than `eps`, return the identity quaternion. |
| `GetReal()` | Return the real coefficient. |
| `GetZero` | `classmethod GetZero() -> Quatf` |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
| `SetImaginary(imaginary)` | Set the imaginary coefficients. |
| `SetReal(real)` | Set the real coefficient. |
| `Transform(point)` | Transform the GfVec3f point. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `imaginary` | |
| `real` | |
<p>
Return this quaternion’s conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetIdentity">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetIdentity
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Quatf.GetIdentity" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetIdentity() -> Quatf
<p>
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3f" title="pxr.Gf.Vec3f">
<span class="pre">
Vec3f
<a class="headerlink" href="#pxr.Gf.Quatf.GetImaginary" title="Permalink to this definition">
<dd>
<p>
Return the imaginary coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatf" title="pxr.Gf.Quatf">
<span class="pre">
Quatf
<a class="headerlink" href="#pxr.Gf.Quatf.GetInverse" title="Permalink to this definition">
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
<p>
This is the quaternion’s conjugate divided by it’s squared length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatf.GetLength" title="Permalink to this definition">
<dd>
<p>
Return geometric length of this quaternion.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatf" title="pxr.Gf.Quatf">
<span class="pre">
Quatf
<a class="headerlink" href="#pxr.Gf.Quatf.GetNormalized" title="Permalink to this definition">
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, return the
identity quaternion.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatf.GetReal" title="Permalink to this definition">
<dd>
<p>
Return the real coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetZero">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetZero
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Quatf.GetZero" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetZero() -> Quatf
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Quatf.Normalize" title="Permalink to this definition">
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the
length before normalization.
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
<p>
<code>
<span>
, this sets
the quaternion to identity.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.SetImaginary">
<span class="sig-name descname">
<span class="pre">
SetImaginary
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
imaginary
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Set the imaginary coefficients.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
imaginary
(
<em>
Vec3f
) –
<hr />
<p>
SetImaginary(i, j, k) -> None
<p>
Set the imaginary coefficients.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
i
(
<em>
float
) –
<li>
<p>
<strong>
j
(
<em>
float
) –
<li>
<p>
<strong>
k
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.SetReal">
<span class="sig-name descname">
<span class="pre">
SetReal
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
real
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Set the real coefficient.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
real
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.Transform">
<span class="sig-name descname">
<span class="pre">
Transform
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
point
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec3f
<dd>
<p>
Transform the GfVec3f point.
<p>
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuatf q, q.Transform(point) is equivalent to: (q *
GfQuatf(0, point) * q.GetInverse()).GetImaginary()
<p>
but is more efficient.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
point
(
<em>
Vec3f
) –
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.imaginary">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
imaginary
<dd>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.real">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
real
<dd>
<dl class="py class">
<dt class="sig sig-object py" id="pxr.Gf.Quath">
<em class="property">
<span class="pre">
class
<span class="w">
<span class="sig-prename descclassname">
<span class="pre">
pxr.Gf.
<span class="sig-name descname">
<span class="pre">
Quath
<dd>
<p>
<strong>
Methods:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetConjugate
()
<p>
Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetIdentity" title="pxr.Gf.Quath.GetIdentity">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetIdentity
<p>
<strong>
classmethod
GetIdentity() -> Quath
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetImaginary" title="pxr.Gf.Quath.GetImaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetImaginary
()
<p>
Return the imaginary coefficient.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetInverse" title="pxr.Gf.Quath.GetInverse">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetInverse
()
<p>
Return this quaternion's inverse, or reciprocal.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetLength" title="pxr.Gf.Quath.GetLength">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetLength
()
<p>
Return geometric length of this quaternion.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetNormalized" title="pxr.Gf.Quath.GetNormalized">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetNormalized
(eps)
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, return the identity quaternion.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetReal" title="pxr.Gf.Quath.GetReal">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetReal
()
<p>
Return the real coefficient.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetZero" title="pxr.Gf.Quath.GetZero">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetZero
<p>
<strong>
classmethod
GetZero() -> Quath
<p>
<a class="reference internal" href="#pxr.Gf.Quath.Normalize" title="pxr.Gf.Quath.Normalize">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Normalize
(eps)
<p>
Normalizes this quaternion in place to unit length, returning the length before normalization.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.SetImaginary" title="pxr.Gf.Quath.SetImaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
SetImaginary
(imaginary)
<p>
Set the imaginary coefficients.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.SetReal" title="pxr.Gf.Quath.SetReal">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
SetReal
(real)
<p>
Set the real coefficient.
<p>
<a class="reference internal" href="#pxr.Gf.Quath.Transform" title="pxr.Gf.Quath.Transform">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Transform
(point)
<p>
Transform the GfVec3h point.
<p>
<strong>
Attributes:
<p>
<a class="reference internal" href="#pxr.Gf.Quath.imaginary" title="pxr.Gf.Quath.imaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
imaginary
<p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.real" title="pxr.Gf.Quath.real">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
real
<p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetConjugate">
<span class="sig-name descname">
<span class="pre">
GetConjugate
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quath" title="pxr.Gf.Quath">
<span class="pre">
Quath
<a class="headerlink" href="#pxr.Gf.Quath.GetConjugate" title="Permalink to this definition">
<dd>
<p>
Return this quaternion’s conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetIdentity">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetIdentity
<span class="sig-paren">
()
<a class="headerlink" href="#pxr.Gf.Quath.GetIdentity" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetIdentity() -> Quath
<p>
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
<span class="sig-paren">
()
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Vec3h
<a class="headerlink" href="#pxr.Gf.Quath.GetImaginary" title="Permalink to this definition">
<dd>
<p>
Return the imaginary coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
<span class="sig-paren">
()
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Quath
<a class="headerlink" href="#pxr.Gf.Quath.GetInverse" title="Permalink to this definition">
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
<p>
This is the quaternion’s conjugate divided by it’s squared length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
()
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
GfHalf
<a class="headerlink" href="#pxr.Gf.Quath.GetLength" title="Permalink to this definition">
<dd>
<p>
Return geometric length of this quaternion.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(eps)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Quath
<a class="headerlink" href="#pxr.Gf.Quath.GetNormalized" title="Permalink to this definition">
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, return the
identity quaternion.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
GfHalf
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
<span class="sig-paren">
()
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
GfHalf
<a class="headerlink" href="#pxr.Gf.Quath.GetReal" title="Permalink to this definition">
<dd>
<p>
Return the real coefficient.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetZero">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetZero
<span class="sig-paren">
()
<a class="headerlink" href="#pxr.Gf.Quath.GetZero" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetZero() -> Quath
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
<span class="sig-paren">
(eps)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
GfHalf
<a class="headerlink" href="#pxr.Gf.Quath.Normalize" title="Permalink to this definition">
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the
length before normalization.
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
<p>
<code>
<span>
SetIdentity
, this sets
the quaternion to identity.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
GfHalf
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.SetImaginary">
<span class="sig-name descname">
<span class="pre">
SetImaginary
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
imaginary
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
None
<dd>
<p>
Set the imaginary coefficients.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
imaginary
(
<em>
Vec3h
) –
<hr />
<p>
SetImaginary(i, j, k) -> None
<p>
Set the imaginary coefficients.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
i
(
<em>
GfHalf
) –
<li>
<p>
<strong>
j
(
<em>
GfHalf
) –
<li>
<p>
<strong>
k
(
<em>
GfHalf
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.SetReal">
<span class="sig-name descname">
<span class="pre">
SetReal
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
real
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
None
<dd>
<p>
Set the real coefficient.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
real
(
<em>
GfHalf
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.Transform">
<span class="sig-name descname">
<span class="pre">
Transform
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
point
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
Vec3h
<dd>
<p>
Transform the GfVec3h point.
<p>
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuath q, q.Transform(point) is equivalent to: (q *
GfQuath(0, point) * q.GetInverse()).GetImaginary()
<p>
but is more efficient.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
point
(
<em>
Vec3h
) –
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quath.imaginary">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
imaginary
<dd>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quath.real">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
real
<dd>
<dl class="py class">
<dt class="sig sig-object py" id="pxr.Gf.Range1d">
<em class="property">
<span class="pre">
class
<span class="w">
<span class="sig-prename descclassname">
<span class="pre">
pxr.Gf.
<span class="sig-name descname">
<span class="pre">
Range1d
<dd>
<p>
<strong>
Methods:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
| Method | Description |
| ------ | ----------- |
| Contains(point) | Returns true if the point is located inside the range. |
| GetDistanceSquared(p) | Compute the squared distance from a point to the range. |
| GetIntersection(a, b) -> Range1d | classmethod GetIntersection(a, b) -> Range1d |
| GetMax() | Returns the maximum value of the range. |
| GetMidpoint() | Returns the midpoint of the range, that is, 0.5*(min+max). |
| GetMin() | Returns the minimum value of the range. |
| GetSize() | Returns the size of the range. |
| GetUnion(a, b) -> Range1d | classmethod GetUnion(a, b) -> Range1d |
| IntersectWith(b) | Modifies this range to hold its intersection with b and returns the result. |
| IsEmpty() | Returns whether the range is empty (max<min). |
| SetEmpty() | Sets the range to an empty interval. |
| SetMax(max) | Sets the maximum value of the range. |
| SetMin(min) | Sets the minimum value of the range. |
| UnionWith(b) | Extend this to include b. |
**Attributes:**
- dimension
| max |
| --- |
| min |
### Contains
`Contains(point)` -> bool
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
**Parameters**
- **point** (float) –
---
Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
**Parameters**
- **range** (Range1d) –
### GetDistanceSquared
`GetDistanceSquared(p)` -> float
Compute the squared distance from a point to the range.
**Parameters**
- **p** (float) –
### GetIntersection
`classmethod GetIntersection(a, b)` -> Range1d
Returns a `GfRange1d` that describes the intersection of `a` and `b`.
**Parameters**
- **a** (Range1d) –
- **b** (Range1d) –
### GetMax
`GetMax()` -> float
Returns the maximum value of the range.
### GetMidpoint
`GetMidpoint()` -> float
### GetMidpoint
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
Returns the minimum value of the range.
### GetSize
Returns the size of the range.
### GetUnion
**classmethod** GetUnion(a, b) -> Range1d
Returns the smallest `GfRange1d` which contains both `a` and `b`.
Parameters:
- **a** (`Range1d`) –
- **b** (`Range1d`) –
### IntersectWith
Modifies this range to hold its intersection with `b` and returns the result.
Parameters:
- **b** (`Range1d`) –
### IsEmpty
Returns whether the range is empty (max<min).
### SetEmpty
Sets the range to an empty interval.
### SetMax
→ None
Sets the maximum value of the range.
Parameters
----------
max (float) –
SetMin(min)
→ None
Sets the minimum value of the range.
Parameters
----------
min (float) –
UnionWith(b)
→ Range1d
Extend `this` to include `b`.
Parameters
----------
b (Range1d) –
UnionWith(b) -> Range1d
Extend `this` to include `b`.
Parameters
----------
b (float) –
dimension = 1
property max
property min
class pxr.Gf.Range1f
Methods:
---------
Contains(point)
Returns true if the `point` is located inside the range.
| Method | Description |
|--------|-------------|
| `GetDistanceSquared()` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range1f` | classmethod GetIntersection(a, b) -> Range1f |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range1f` | classmethod GetUnion(a, b) -> Range1f |
| `IntersectWith(b)` | Modifies this range to hold its intersection with b and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend this to include b. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
| `max` | |
| `min` | |
```code
min
```
```code
Contains
(
point
)
→
bool
```
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
Parameters
----------
point (float) –
```code
Contains(range) -> bool
```
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
Parameters
----------
range (Range1f) –
```code
GetDistanceSquared
(
p
)
→
float
```
Compute the squared distance from a point to the range.
Parameters
----------
p (float) –
```code
static
GetIntersection
(
)
```
```code
classmethod
GetIntersection(a, b) -> Range1f
```
Returns a `GfRange1f` that describes the intersection of `a` and `b`.
Parameters
----------
a (Range1f) –
b (Range1f) –
```code
GetMax
(
)
→
float
```
Returns the maximum value of the range.
```code
GetMidpoint
(
)
→
float
```
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
```code
GetMin
```
### GetMin
Returns the minimum value of the range.
### GetSize
Returns the size of the range.
### GetUnion
**classmethod** GetUnion(a, b) -> Range1f
Returns the smallest `GfRange1f` which contains both `a` and `b`.
Parameters:
- **a** (`Range1f`) –
- **b** (`Range1f`) –
### IntersectWith
Modifies this range to hold its intersection with `b` and returns the result.
Parameters:
- **b** (`Range1f`) –
### IsEmpty
Returns whether the range is empty (max<min).
### SetEmpty
Sets the range to an empty interval.
### SetMax
Sets the maximum value of the range.
Parameters:
- **max** –
**max** (**float**) –
**SetMin**(min) → None
Sets the minimum value of the range.
**Parameters**
- **min** (**float**) –
**UnionWith**(b) → Range1f
Extend `this` to include `b`.
**Parameters**
- **b** (**Range1f**) –
UnionWith(b) -> Range1f
Extend `this` to include `b`.
**Parameters**
- **b** (**float**) –
**dimension** = 1
**property max**
**property min**
**class pxr.Gf.Range2d**
**Methods:**
- **Contains**(point)
Returns true if the `point` is located inside the range.
- **GetCorner**(i)
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
| Method | Description |
|--------|-------------|
| `GetDistanceSquared()` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range2d` | classmethod GetIntersection(a, b) -> Range2d |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetQuadrant(i)` | Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range2d` | classmethod GetUnion(a, b) -> Range2d |
| `IntersectWith(b)` | Modifies this range to hold its intersection with b and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend this to include b. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
| `max` | |
### max
### min
### unitSquare
### Contains
```
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
**Parameters**
- **point** (`Vec2d`) –
Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
**Parameters**
- **range** (`Range2d`) –
### GetCorner
```
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
**Parameters**
- **i** (`int`) –
```
### GetDistanceSquared
```
Compute the squared distance from a point to the range.
**Parameters**
- **p** (`Vec2d`) –
```
### GetIntersection
```
classmethod GetIntersection(a, b) -> Range2d
Returns a `GfRange2d` that describes the intersection of `a` and `b`.
**Parameters**
- **a** (`Range2d`) –
- **b** (`Range2d`) –
```
**Range2d**
- **b** (Range2d) –
### GetMax()
Returns the maximum value of the range.
### GetMidpoint()
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin()
Returns the minimum value of the range.
### GetQuadrant(i)
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
Parameters:
- **i** (int) –
### GetSize()
Returns the size of the range.
### GetUnion(a, b)
Returns the smallest GfRange2d which contains both a and b.
Parameters:
- **a** (Range2d) –
- **b** (Range2d) –
### pxr.Gf.Range2d.IntersectWith
- **Description**: Modifies this range to hold its intersection with `b` and returns the result.
- **Parameters**:
- **b** (Range2d) –
### pxr.Gf.Range2d.IsEmpty
- **Description**: Returns whether the range is empty (max<min).
### pxr.Gf.Range2d.SetEmpty
- **Description**: Sets the range to an empty interval.
### pxr.Gf.Range2d.SetMax
- **Description**: Sets the maximum value of the range.
- **Parameters**:
- **max** (Vec2d) –
### pxr.Gf.Range2d.SetMin
- **Description**: Sets the minimum value of the range.
- **Parameters**:
- **min** (Vec2d) –
### pxr.Gf.Range2d.UnionWith
- **Description**: Extend `this` to include `b`.
- **Parameters**:
- **b** (Range2d) –
- **Example**: UnionWith(b) -> Range2d
### Parameters
**b** (Vec2d) –
### Attributes
- **dimension** = 2
- **max** property
- **min** property
- **unitSquare** = Gf.Range2d(Gf.Vec2d(0.0, 0.0), Gf.Vec2d(1.0, 1.0))
### Class: pxr.Gf.Range2f
**Methods:**
- **Contains**(point) - Returns true if the point is located inside the range.
- **GetCorner**(i) - Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
- **GetDistanceSquared**(p) - Compute the squared distance from a point to the range.
- **GetIntersection**(a, b) -> Range2f - **classmethod**
- **GetMax**() - Returns the maximum value of the range.
- **GetMidpoint**() - Returns the midpoint of the range, that is, 0.5*(min+max).
- **GetMin**() - Returns the minimum value of the range.
- **GetQuadrant**(i) - Returns the ith quadrant of the range.
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
GetSize()
Returns the size of the range.
GetUnion
classmethod GetUnion(a, b) -> Range2f
IntersectWith(b)
Modifies this range to hold its intersection with b and returns the result.
IsEmpty()
Returns whether the range is empty (max<min).
SetEmpty()
Sets the range to an empty interval.
SetMax(max)
Sets the maximum value of the range.
SetMin(min)
Sets the minimum value of the range.
UnionWith(b)
Extend this to include b.
Attributes:
dimension
max
min
unitSquare
Contains(point) -> bool
Returns true if the point is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
Parameters:
point (Vec2f)
### Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
#### Parameters
- **range** (Range2f) –
### GetCorner(i) -> Vec2f
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
#### Parameters
- **i** (int) –
### GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
#### Parameters
- **p** (Vec2f) –
### GetIntersection(a, b) -> Range2f
Returns a `GfRange2f` that describes the intersection of `a` and `b`.
#### Parameters
- **a** (Range2f) –
- **b** (Range2f) –
### GetMax() -> Vec2f
Returns the maximum value of the range.
### GetMidpoint() -> Vec2f
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin() -> Vec2f
Returns the minimum value of the range.
(→ Vec2f)
Returns the minimum value of the range.
(i→ Range2f)
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
Parameters
----------
i (int) –
()→ Vec2f
Returns the size of the range.
classmethod GetUnion(a, b) -> Range2f
Returns the smallest GfRange2f which contains both a and b.
Parameters
----------
a (Range2f) –
b (Range2f) –
IntersectWith(b) -> Range2f
Modifies this range to hold its intersection with b and returns the result.
Parameters
----------
b (Range2f) –
IsEmpty() -> bool
Returns whether the range is empty (max<min).
SetEmpty() -> None
### SetEmpty
Sets the range to an empty interval.
### SetMax
Sets the maximum value of the range.
- **Parameters**
- **max** (Vec2f) –
### SetMin
Sets the minimum value of the range.
- **Parameters**
- **min** (Vec2f) –
### UnionWith
Extend `this` to include `b`.
- **Parameters**
- **b** (Range2f) –
UnionWith(b) -> Range2f
Extend `this` to include `b`.
- **Parameters**
- **b** (Vec2f) –
### dimension
= 2
### max
property max
### min
property min
### unitSquare
= Gf.Range2f(Gf.Vec2f(0.0,
### pxr.Gf.Range3d
**Methods:**
- **Contains**(point)
- Returns true if the `point` is located inside the range.
- **GetCorner**(i)
- Returns the ith corner of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- **GetDistanceSquared**(p)
- Compute the squared distance from a point to the range.
- **GetIntersection**(a, b) -> Range3d
- **classmethod** GetIntersection(a, b) -> Range3d
- **GetMax**()
- Returns the maximum value of the range.
- **GetMidpoint**()
- Returns the midpoint of the range, that is, 0.5*(min+max).
- **GetMin**()
- Returns the minimum value of the range.
- **GetOctant**(i)
- Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- **GetSize**()
- Returns the size of the range.
- **GetUnion**(a, b) -> Range3d
- **classmethod** GetUnion(a, b) -> Range3d
- **IntersectWith**(b)
- Modifies this range to hold its intersection with `b` and returns the result.
- **IsEmpty**()
- Returns whether the range is empty (max<min).
- **SetEmpty**()
- Sets the range to be empty.
| | |
|---|---|
| Sets the range to an empty interval. | |
| `SetMax` (max) | Sets the maximum value of the range. |
| `SetMin` (min) | Sets the minimum value of the range. |
| `UnionWith` (b) | Extend `this` to include `b`. |
**Attributes:**
| | |
|---|---|
| `dimension` | |
| `max` | |
| `min` | |
| `unitCube` | |
**Contains**
(point) → bool
- Returns true if the `point` is located inside the range.
- As with all operations of this type, the range is assumed to include its extrema.
- **Parameters**
- **point** (Vec3d) –
- Contains(range) -> bool
- Returns true if the `range` is located entirely inside the range.
- As with all operations of this type, the ranges are assumed to include their extrema.
- **Parameters**
- **range** (Range3d) –
**GetCorner**
(i) → Vec3d
- Returns the ith corner of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- Where L/R is left/right, D/U is down/up, and B/F is back/front.
- **Parameters**
- **i** (int) –
### GetDistanceSquared
Compute the squared distance from a point to the range.
#### Parameters
- **p** (Vec3d) –
### GetIntersection
classmethod GetIntersection(a, b) -> Range3d
Returns a `GfRange3d` that describes the intersection of `a` and `b`.
#### Parameters
- **a** (Range3d) –
- **b** (Range3d) –
### GetMax
Returns the maximum value of the range.
### GetMidpoint
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
Returns the minimum value of the range.
### GetOctant
Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
#### Parameters
- **i** (int) –
### pxr.Gf.Range3d.GetSize
- **Returns the size of the range.**
### pxr.Gf.Range3d.GetUnion
- **classmethod** GetUnion(a, b) -> Range3d
- Returns the smallest `GfRange3d` which contains both `a` and `b`.
- **Parameters**
- **a** (`Range3d`) –
- **b** (`Range3d`) –
### pxr.Gf.Range3d.IntersectWith
- Modifies this range to hold its intersection with `b` and returns the result.
- **Parameters**
- **b** (`Range3d`) –
### pxr.Gf.Range3d.IsEmpty
- Returns whether the range is empty (max<min).
### pxr.Gf.Range3d.SetEmpty
- Sets the range to an empty interval.
### pxr.Gf.Range3d.SetMax
- Sets the maximum value of the range.
- **Parameters**
- **max** (`Vec3d`) –
### pxr.Gf.Range3d.SetMin
- Sets the minimum value of the range.
- **Parameters**
- **min** (`Vec3d`) –
### pxr.Gf.Range3d.SetMin
- **Description:** Sets the minimum value of the range.
- **Parameters:**
- **min** (Vec3d) –
### pxr.Gf.Range3d.UnionWith
- **Description:** Extend `this` to include `b`.
- **Parameters:**
- **b** (Range3d) –
- **Function Signature:** UnionWith(b) -> Range3d
- **Description:** Extend `this` to include `b`.
- **Parameters:**
- **b** (Vec3d) –
### pxr.Gf.Range3d.dimension
- **Description:** (Property) dimension = 3
### pxr.Gf.Range3d.max
- **Description:** (Property) max
### pxr.Gf.Range3d.min
- **Description:** (Property) min
### pxr.Gf.Range3d.unitCube
- **Description:** (Property) unitCube = Gf.Range3d(Gf.Vec3d(0.0, 0.0, 0.0), Gf.Vec3d(1.0, 1.0, 1.0))
### pxr.Gf.Range3f
- **Methods:**
- **Contains** (point) - Returns true if the `point` is located inside the range.
- **GetCorner** (i) -
| Method | Description |
|--------|-------------|
| `GetDistanceSquared(p)` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range3f` | classmethod GetIntersection(a, b) -> Range3f |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetOctant(i)` | Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range3f` | classmethod GetUnion(a, b) -> Range3f |
| `IntersectWith(b)` | Modifies this range to hold its intersection with `b` and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend `this` to include `b`. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
<td>
<p>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.max" title="pxr.Gf.Range3f.max">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
max
<td>
<p>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.min" title="pxr.Gf.Range3f.min">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
min
<td>
<p>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.unitCube" title="pxr.Gf.Range3f.unitCube">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
unitCube
<td>
<p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.Contains">
<span class="sig-name descname">
<span class="pre">
Contains
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
point
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
bool
<a class="headerlink" href="#pxr.Gf.Range3f.Contains" title="Permalink to this definition">
<dd>
<p>
Returns true if the
<code class="docutils literal notranslate">
<span class="pre">
point
is located inside the range.
<p>
As with all operations of this type, the range is assumed to include
its extrema.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
point
(
<em>
Vec3f
) –
<hr class="docutils"/>
<p>
Contains(range) -> bool
<p>
Returns true if the
<code class="docutils literal notranslate">
<span class="pre">
range
is located entirely inside the range.
<p>
As with all operations of this type, the ranges are assumed to include
their extrema.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
range
(
<em>
Range3f
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetCorner">
<span class="sig-name descname">
<span class="pre">
GetCorner
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
i
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3f" title="pxr.Gf.Vec3f">
<span class="pre">
Vec3f
<a class="headerlink" href="#pxr.Gf.Range3f.GetCorner" title="Permalink to this definition">
<dd>
<p>
Returns the ith corner of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
<p>
Where L/R is left/right, D/U is down/up, and B/F is back/front.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
i
(
<em>
int
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetDistanceSquared">
<span class="sig-name descname">
<span class="pre">
GetDistanceSquared
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
p
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Range3f.GetDistanceSquared" title="Permalink to this definition">
<dd>
<p>
Compute the squared distance from a point to the range.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
p
(
<em>
Vec3f
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetIntersection">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetIntersection
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Range3f.GetIntersection" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetIntersection(a, b) -> Range3f
<p>
Returns a
<code class="docutils literal notranslate">
<span class="pre">
GfRange3f
that describes the intersection of
<code class="docutils literal notranslate">
<span class="pre">
a
and
```
```
b
```
.
### Parameters
- **a** (Range3f) –
- **b** (Range3f) –
### GetMax
```
GetMax() → Vec3f
```
Returns the maximum value of the range.
### GetMidpoint
```
GetMidpoint() → Vec3f
```
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
```
GetMin() → Vec3f
```
Returns the minimum value of the range.
### GetOctant
```
GetOctant(i) → Range3f
```
Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
#### Parameters
- **i** (int) –
### GetSize
```
GetSize() → Vec3f
```
Returns the size of the range.
### GetUnion
```
classmethod GetUnion(a, b) → Range3f
```
Returns the smallest GfRange3f which contains both a and b.
#### Parameters
- **a** (Range3f) –
- **b** (Range3f) –
(
**Range3f**
) –
### IntersectWith
```python
IntersectWith(b)
```
Returns: **Range3f**
Modifies this range to hold its intersection with `b` and returns the result.
**Parameters**
- **b** (**Range3f**) –
### IsEmpty
```python
IsEmpty()
```
Returns: **bool**
Returns whether the range is empty (max<min).
### SetEmpty
```python
SetEmpty()
```
Returns: **None**
Sets the range to an empty interval.
### SetMax
```python
SetMax(max)
```
Returns: **None**
Sets the maximum value of the range.
**Parameters**
- **max** (**Vec3f**) –
### SetMin
```python
SetMin(min)
```
Returns: **None**
Sets the minimum value of the range.
**Parameters**
- **min** (**Vec3f**) –
### UnionWith
```python
UnionWith(b)
```
Returns: **Range3f**
Extend `this` to include `b`.
**Parameters**
- **b** –
**b** (**Range3f**) –
---
UnionWith(b) -> Range3f
Extend `this` to include `b`.
---
**Parameters**
**b** (**Vec3f**) –
---
**dimension** = 3
**max** property
**min** property
**unitCube** = Gf.Range3f(Gf.Vec3f(0.0, 0.0, 0.0), Gf.Vec3f(1.0, 1.0, 1.0))
---
**class** **pxr.Gf.Ray**
**Methods:**
- **FindClosestPoint**(point, rayDistance)
- Returns the point on the ray that is closest to `point`.
- **GetPoint**(distance)
- Returns the point that is `distance` units from the starting point along the direction vector, expressed in parametric distance.
- **Intersect**(p0, p1, p2)
- float, barycentric = GfVec3d, frontFacing = bool
- **SetEnds**(startPoint, endPoint)
- Sets the ray by specifying a starting point and an ending point.
- **SetPointAndDirection**(startPoint, direction)
- Sets the ray by specifying a starting point and a direction.
- **Transform**(matrix)
- Transforms the ray by the given matrix.
## Attributes:
| Attribute | Description |
|-----------|-------------|
| `direction` | Vec3d |
| `startPoint` | Vec3d |
## Methods
### FindClosestPoint(point, rayDistance) → Vec3d
Returns the point on the ray that is closest to `point`.
If `rayDistance` is not `None`, it will be set to the parametric distance along the ray of the closest point.
**Parameters:**
- **point** (Vec3d) –
- **rayDistance** (float) –
### GetPoint(distance) → Vec3d
Returns the point that is `distance` units from the starting point along the direction vector, expressed in parametric distance.
**Parameters:**
- **distance** (float) –
### Intersect(p0, p1, p2) → tuple<intersects=bool, dist=float, barycentric=GfVec3d, frontFacing=bool>
Intersects the ray with the triangle formed by points p0, p1, and p2. The first item in the tuple is true if the ray intersects the triangle. dist is the parametric distance to the intersection point, the barycentric coordinates of the intersection point, and the front-facing flag. The barycentric coordinates are defined with respect to the three vertices taken in order. The front-facing flag is True if the intersection hit the side of the triangle that is formed when the vertices are ordered counter-clockwise (right-hand rule).
**Barycentric coordinates are defined to sum to 1 and satisfy this relationship:**
```
intersectionPoint = (barycentricCoords[0] * p0 +
barycentricCoords[1] * p1 +
barycentricCoords[2] * p2);
```
**Intersect( plane ) → tuple<intersects = bool, dist = float, frontFacing = bool>**
Intersects the ray with the Gf.Plane. The first item in the returned tuple is true if the ray intersects the plane. dist is the parametric distance to the intersection point.
and frontfacing is true if the intersection is on the side
of the plane toward which the plane’s normal points.
Intersect( range3d ) -> tuple<intersects = bool, enterDist
= float, exitDist = float>
Intersects the plane with an axis-aligned box in a
Gf.Range3d. intersects is true if the ray intersects it at
all within bounds. If there is an intersection then enterDist
and exitDist will be the parametric distances to the two
intersection points.
Intersect( bbox3d ) -> tuple<intersects = bool, enterDist
= float, exitDist = float>
Intersects the plane with an oriented box in a Gf.BBox3d.
intersects is true if the ray intersects it at all within
bounds. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
Intersect( center, radius ) -> tuple<intersects = bool,
enterDist = float, exitDist = float>
Intersects the plane with an sphere. intersects is true if
the ray intersects it at all within the sphere. If there is
an intersection then enterDist and exitDist will be the
parametric distances to the two intersection points.
Intersect( origin, axis, radius ) -> tuple<intersects = bool,
enterDist = float, exitDist = float>
Intersects the plane with an infinite cylinder. intersects
is true if the ray intersects it at all within the
sphere. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
Intersect( origin, axis, radius, height ) ->
tuple<intersects = bool, enterDist = float, exitDist = float>
Intersects the plane with an cylinder. intersects
is true if the ray intersects it at all within the
sphere. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
SetEnds( startPoint, endPoint ) -> None
Sets the ray by specifying a starting point and an ending point.
Parameters:
- startPoint (Vec3d) –
- endPoint (Vec3d) –
SetPointAndDirection( startPoint, direction ) -> None
Sets the ray by specifying a starting point and a direction.
Parameters:
- startPoint (Vec3d) –
- direction (Vec3d) –
Transform( matrix ) -> Ray
Transforms the ray by the given matrix.
Parameters:
- matrix (Matrix4d) –
## Vec3d
Returns the direction vector of the segment.
This is not guaranteed to be unit length.
### Type
type
## startPoint
Returns the starting point of the segment.
### Type
type
## pxr.Gf.Rect2i
### Methods:
- **Contains(p)** - Returns true if the specified point is in the rectangle.
- **GetArea()** - Return the area of the rectangle.
- **GetCenter()** - Returns the center point of the rectangle.
- **GetHeight()** - Returns the height of the rectangle.
- **GetIntersection(that)** - Computes the intersection of two rectangles.
- **GetMax()** - Returns the max corner of the rectangle.
- **GetMaxX()** - Return the X value of the max corner.
- **GetMaxY()** - Return the Y value of the max corner.
- **GetMin()** - Returns the min corner of the rectangle.
- **GetMinX()** - Return the X value of min corner.
- **GetMinY()** - Return the Y value of the min corner.
- **GetNormalized()** - Returns a normalized rectangle, i.e.
- `GetSize()`
- Returns the size of the rectangle as a vector (width,height).
- `GetUnion(that)`
- Computes the union of two rectangles.
- `GetWidth()`
- Returns the width of the rectangle.
- `IsEmpty()`
- Returns true if the rectangle is empty.
- `IsNull()`
- Returns true if the rectangle is a null rectangle.
- `IsValid()`
- Return true if the rectangle is valid (equivalently, not empty).
- `SetMax(max)`
- Sets the max corner of the rectangle.
- `SetMaxX(x)`
- Set the X value of the max corner.
- `SetMaxY(y)`
- Set the Y value of the max corner.
- `SetMin(min)`
- Sets the min corner of the rectangle.
- `SetMinX(x)`
- Set the X value of the min corner.
- `SetMinY(y)`
- Set the Y value of the min corner.
- `Translate(displacement)`
- Move the rectangle by `displ`.
**Attributes:**
- `max`
- `maxX`
- `maxY`
<p>
min
<p>
minX
<p>
minY
<dl>
<dt>
Contains (p) → bool
<a href="#pxr.Gf.Rect2i.Contains" title="Permalink to this definition">
<dd>
<p>Returns true if the specified point in the rectangle.
<dl>
<dt>Parameters
<dd>
<p><strong>p
<dl>
<dt>
GetArea () → int
<a href="#pxr.Gf.Rect2i.GetArea" title="Permalink to this definition">
<dd>
<p>Return the area of the rectangle.
<dl>
<dt>
GetCenter () → Vec2i
<a href="#pxr.Gf.Rect2i.GetCenter" title="Permalink to this definition">
<dd>
<p>Returns the center point of the rectangle.
<dl>
<dt>
GetHeight () → int
<a href="#pxr.Gf.Rect2i.GetHeight" title="Permalink to this definition">
<dd>
<p>Returns the height of the rectangle.
<p>If the min and max y-coordinates are coincident, the height is one.
<dl>
<dt>
GetIntersection (that) → Rect2i
<a href="#pxr.Gf.Rect2i.GetIntersection" title="Permalink to this definition">
<dd>
<p>Computes the intersection of two rectangles.
<dl>
<dt>Parameters
<dd>
<p><strong>that
<dl>
<dt>
GetMax () → Vec2i
<a href="#pxr.Gf.Rect2i.GetMax" title="Permalink to this definition">
<dd>
<p>Returns the max corner of the rectangle.
<dl>
<dt>
GetMaxX () → int
<a href="#pxr.Gf.Rect2i.GetMaxX" title="Permalink to this definition">
<dd>
<p>Returns the max x-coordinate of the rectangle.
### GetMaxX
Return the X value of the max corner.
### GetMaxY
Return the Y value of the max corner.
### GetMin
Returns the min corner of the rectangle.
### GetMinX
Return the X value of min corner.
### GetMinY
Return the Y value of the min corner.
### GetNormalized
Returns a normalized rectangle, i.e. one that has a non-negative width and height.
```
```markdown
GetNormalized() swaps the min and max x-coordinates to ensure a non-negative width, and similarly for the y-coordinates.
```
### GetSize
Returns the size of the rectangle as a vector (width,height).
### GetUnion
Computes the union of two rectangles.
#### Parameters
- **that** (Rect2i) –
### GetWidth
Returns the width of the rectangle. If the min and max x-coordinates are coincident, the width is one.
### IsEmpty
```python
IsEmpty() -> bool
```
Returns true if the rectangle is empty.
An empty rectangle has one or both of its min coordinates strictly greater than the corresponding max coordinate.
An empty rectangle is not valid.
### IsNull
```python
IsNull() -> bool
```
Returns true if the rectangle is a null rectangle.
A null rectangle has both the width and the height set to 0, that is
```python
GetMaxX() == GetMinX() - 1
and
GetMaxY() == GetMinY() - 1
```
Remember that if `GetMinX()` and `GetMaxX()` return the same value then the rectangle has width 1, and similarly for the height.
A null rectangle is both empty, and not valid.
### IsValid
```python
IsValid() -> bool
```
Return true if the rectangle is valid (equivalently, not empty).
### SetMax
```python
SetMax(max) -> None
```
Sets the max corner of the rectangle.
**Parameters**
- **max** (`Vec2i`) –
### SetMaxX
```python
SetMaxX(x) -> None
```
Set the X value of the max corner.
**Parameters**
- **x** (`int`) –
### SetMaxY
```python
SetMaxY(y) -> None
```
Set the Y value of the max corner.
**Parameters**
- **y** (`int`) –
### SetMin
```python
SetMin(min) -> None
```
Sets the min corner of the rectangle.
**Parameters**
- **min** (`Vec2i`) –
### SetMin
Sets the min corner of the rectangle.
**Parameters**
- **min** (Vec2i) –
### SetMinX
Set the X value of the min corner.
**Parameters**
- **x** (int) –
### SetMinY
Set the Y value of the min corner.
**Parameters**
- **y** (int) –
### Translate
Move the rectangle by `displ`.
**Parameters**
- **displacement** (Vec2i) –
### max
### maxX
### maxY
### min
### minX
### minY
## pxr.Gf.Rotation
class
3-space rotation
### Methods:
- **Decompose(axis0, axis1, axis2)**
Decompose rotation about 3 orthogonal axes.
- **DecomposeRotation**
classmethod DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
- **DecomposeRotation3**
- **GetAngle()**
Returns the rotation angle in degrees.
- **GetAxis()**
Returns the axis of rotation.
- **GetInverse()**
Returns the inverse of this rotation.
- **GetQuat()**
Returns the rotation expressed as a quaternion.
- **GetQuaternion()**
Returns the rotation expressed as a quaternion.
- **MatchClosestEulerRotation**
classmethod MatchClosestEulerRotation(targetTw, targetFB, targetLR, targetSw, thetaTw, thetaFB, thetaLR, thetaSw) -> None
- **RotateOntoProjected(v1, v2, axis)**
classmethod RotateOntoProjected(v1, v2, axis) -> Rotation
- **SetAxisAngle(axis, angle)**
Sets the rotation to be `angle` degrees about `axis`.
- **SetIdentity()**
Sets the rotation to an identity rotation.
- **SetQuat()**
Sets the rotation to a quaternion.
| Method | Description |
| ------ | ----------- |
| `SetQuat(quat)` | Sets the rotation from a quaternion. |
| `SetQuaternion(quat)` | Sets the rotation from a quaternion. |
| `SetRotateInto(rotateFrom, rotateTo)` | Sets the rotation to one that brings the `rotateFrom` vector to align with `rotateTo`. |
| `TransformDir(vec)` | Transforms row vector `vec` by the rotation, returning the result. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| `angle` | |
| `axis` | |
### Decompose
```python
Decompose(axis0, axis1, axis2) -> Vec3d
```
Decompose rotation about 3 orthogonal axes. If the axes are not orthogonal, warnings will be spewed.
**Parameters:**
- **axis0** (Vec3d) –
- **axis1** (Vec3d) –
- **axis2** (Vec3d) –
### DecomposeRotation
```python
@staticmethod
DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
```
**classmethod** DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
**Parameters:**
- **rot** (Matrix4d) –
- **TwAxis** (Vec3d) –
- **FBAxis** (Vec3d) –
- **LRAxis** (Vec3d) –
- **handedness** (int) –
- **thetaTw** (float) –
- **thetaFB** (float) –
- **thetaLR** (float) –
- **thetaSw** (float) –
- **useHint** (bool) –
- **swShift** (float) –
**LRAxis** (**Vec3d**) –
**handedness** (**float**) –
**thetaTw** (**float**) –
**thetaFB** (**float**) –
**thetaLR** (**float**) –
**thetaSw** (**float**) –
**useHint** (**bool**) –
**swShift** (**float**) –
**DecomposeRotation3**()
**GetAngle**() → float
- Returns the rotation angle in degrees.
**GetAxis**() → Vec3d
- Returns the axis of rotation.
**GetInverse**() → Rotation
- Returns the inverse of this rotation.
**GetQuat**() → Quatd
- Returns the rotation expressed as a quaternion.
**GetQuaternion**() → Quaternion
- Returns the rotation expressed as a quaternion.
**MatchClosestEulerRotation**(targetTw, targetFB, targetLR, targetSw, thetaTw, thetaFB, thetaLR, thetaSw) -> None
- Replace the hint angles with the closest rotation of the given rotation to the hint.
- Each angle in the rotation will be within Pi of the corresponding hint
angle and the sum of the differences with the hint will be minimized.
If a given rotation value is null then that angle will be treated as
0.0 and ignored in the calculations.
All angles are in radians. The rotation order is Tw/FB/LR/Sw.
### Parameters
- **targetTw** (`float`) –
- **targetFB** (`float`) –
- **targetLR** (`float`) –
- **targetSw** (`float`) –
- **thetaTw** (`float`) –
- **thetaFB** (`float`) –
- **thetaLR** (`float`) –
- **thetaSw** (`float`) –
### classmethod RotateOntoProjected(v1, v2, axis) -> Rotation
#### Parameters
- **v1** (`Vec3d`) –
- **v2** (`Vec3d`) –
- **axis** (`Vec3d`) –
### SetAxisAngle(axis, angle) -> Rotation
Sets the rotation to be `angle` degrees about `axis`.
#### Parameters
- **axis** (`Vec3d`) –
- **angle** (`float`) –
### SetIdentity() -> Rotation
Sets the rotation to an identity rotation.
(This is chosen to be 0 degrees around the positive X axis.)
### SetQuat(quat) -> Rotation
### SetQuat
Sets the rotation from a quaternion.
Note that this method accepts GfQuatf and GfQuath since they implicitly convert to GfQuatd.
**Parameters**
- **quat** (Quatd) –
### SetQuaternion
Sets the rotation from a quaternion.
**Parameters**
- **quat** (Quaternion) –
### SetRotateInto
Sets the rotation to one that brings the `rotateFrom` vector to align with `rotateTo`.
The passed vectors need not be unit length.
**Parameters**
- **rotateFrom** (Vec3d) –
- **rotateTo** (Vec3d) –
### TransformDir
Transforms row vector `vec` by the rotation, returning the result.
**Parameters**
- **vec** (Vec3f) –
TransformDir(vec) -> Vec3d
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
**Parameters**
- **vec** (Vec3d) –
### angle
### axis
### pxr.Gf.Size2
**A 2D size class**
**Methods:**
| Method | Description |
|--------|-------------|
| `Set(v)` | Set to the values in a given array. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
#### pxr.Gf.Size2.Set
**Set to the values in a given array.**
**Parameters:**
- **v** (int) –
**Set(v0, v1) -> Size2**
Set to values passed directly.
**Parameters:**
- **v0** (int) –
- **v1** (int) –
#### pxr.Gf.Size2.dimension
**dimension = 2**
### pxr.Gf.Size3
**A 3D size class**
**Methods:**
| Method | Description |
|--------|-------------|
| `Set(v)` | Set to the values in `v`. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
#### pxr.Gf.Size3.Set
**Set to the values in `v`.**
**Parameters:**
- **v** (int) –
#### pxr.Gf.Size3.dimension
### Size3
Set to the values in `v`.
#### Parameters
- **v** (`int`) –
---
Set(v0, v1, v2) -> Size3
Set to values passed directly.
#### Parameters
- **v0** (`int`) –
- **v1** (`int`) –
- **v2** (`int`) –
### Size3.dimension
= 3
### pxr.Gf.Transform
**Methods:**
- **GetMatrix**()
Returns a `GfMatrix4d` that implements the cumulative transformation.
- **GetPivotOrientation**()
Returns the pivot orientation component.
- **GetPivotPosition**()
Returns the pivot position component.
- **GetRotation**()
Returns the rotation component.
- **GetScale**()
Returns the scale component.
- **GetTranslation**()
Returns the translation component.
- **Set**()
Set method used by old 2x code.
- **SetIdentity**()
Sets the transformation to the identity transformation.
- **SetMatrix**(m)
Sets the transform components to implement the transformation represented by matrix `m`.
| Method | Description |
| ------ | ----------- |
| SetPivotOrientation(pivotOrient) | Sets the pivot orientation component, leaving all others untouched. |
| SetPivotPosition(pivPos) | Sets the pivot position component, leaving all others untouched. |
| SetRotation(rotation) | Sets the rotation component, leaving all others untouched. |
| SetScale(scale) | Sets the scale component, leaving all others untouched. |
| SetTranslation(translation) | Sets the translation component, leaving all others untouched. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| pivotOrientation | |
| pivotPosition | |
| rotation | |
| scale | |
| translation | |
**Methods:**
- **GetMatrix() -> Matrix4d**
- Returns a `GfMatrix4d` that implements the cumulative transformation.
- **GetPivotOrientation() -> Rotation**
- Returns the pivot orientation component.
- **GetPivotPosition() -> Vec3d**
- Returns the pivot position component.
Returns the pivot position component.
```
```markdown
GetRotation
()
→ Rotation
Returns the rotation component.
```
```markdown
GetScale
()
→ Vec3d
Returns the scale component.
```
```markdown
GetTranslation
()
→ Vec3d
Returns the translation component.
```
```markdown
Set
()
Set method used by old 2x code. (Deprecated)
```
```markdown
SetIdentity
()
→ Transform
Sets the transformation to the identity transformation.
```
```markdown
SetMatrix
(m)
→ Transform
Sets the transform components to implement the transformation represented by matrix m, ignoring any projection.
This tries to leave the current center unchanged.
Parameters
----------
m (Matrix4d) –
```
```markdown
SetPivotOrientation
(pivotOrient)
→ None
Sets the pivot orientation component, leaving all others untouched.
Parameters
----------
pivotOrient (Rotation) –
```
```markdown
SetPivotPosition
(pivPos)
Sets the pivot position component.
```
### SetPivotPosition
Sets the pivot position component, leaving all others untouched.
**Parameters**
- **pivPos** (Vec3d) –
### SetRotation
Sets the rotation component, leaving all others untouched.
**Parameters**
- **rotation** (Rotation) –
### SetScale
Sets the scale component, leaving all others untouched.
**Parameters**
- **scale** (Vec3d) –
### SetTranslation
Sets the translation component, leaving all others untouched.
**Parameters**
- **translation** (Vec3d) –
### pivotOrientation
### pivotPosition
### rotation
### scale
### translation
## pxr.Gf.Vec2d
### Methods:
| Method | Description |
|--------|-------------|
| Axis(i) -> Vec2d | classmethod Axis(i) -> Vec2d |
| GetComplement(b) | Returns the orthogonal complement of this->GetProjection(b). |
| GetDot | |
| GetLength() | Length. |
| GetNormalized(eps) | param eps |
| GetProjection(v) | Returns the projection of this onto v. |
| Normalize(eps) | Normalizes the vector in place to unit length, returning the length before normalization. |
| XAxis() -> Vec2d | classmethod XAxis() -> Vec2d |
| YAxis() -> Vec2d | classmethod YAxis() -> Vec2d |
### Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension | |
### static Axis
classmethod Axis(i) -> Vec2d
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if i is greater than or equal to 2.
Parameters
- i: |
<p>
<strong>
i
(
<em>
int
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
b
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec2d
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
.
<p>
That is:
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
b
(
<em>
Vec2d
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<dd>
<p>
Length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec2d
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
v
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec2d
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
onto
<code class="docutils literal notranslate">
<span class="pre">
v
.
<p>
That is:
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
v
(
<em>
Vec2d
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<dd>
<p>
Normalizes the vector in place to unit length, returning the length
before normalization.
<p>
If the length of the vector is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
, then the vector
is set to vector/
<code class="docutils literal notranslate">
<span class="pre">
eps
. The original length of the vector is
returned. See also GfNormalize() .
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
### eps (float) –
### classmethod XAxis() -> Vec2d
Create a unit vector along the X-axis.
### classmethod YAxis() -> Vec2d
Create a unit vector along the Y-axis.
### dimension = 2
### class Vec2f
Methods:
- **classmethod Axis(i) -> Vec2f**
- **GetComplement(b)**
Returns the orthogonal complement of this->GetProjection(b).
- **GetDot**
- **GetLength()**
Length.
- **GetNormalized(eps)**
param eps
- **GetProjection(v)**
Returns the projection of this onto v.
- **Normalize(eps)**
Normalizes the vector in place to unit length, returning the length before normalization.
- **classmethod XAxis() -> Vec2f**
```html
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
YAxis
<td>
<p>
<strong>
classmethod
YAxis() -> Vec2f
<p>
<strong>
Attributes:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec2f.dimension" title="pxr.Gf.Vec2f.dimension">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
<td>
<p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.Axis">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
Axis
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Vec2f.Axis" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
Axis(i) -> Vec2f
<p>
Create a unit vector along the i-th axis, zero-based.
<p>
Return the zero vector if
<code class="docutils literal notranslate">
<span class="pre">
i
is greater than or equal to 2.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
i
(
<em>
int
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
b
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
<a class="headerlink" href="#pxr.Gf.Vec2f.GetComplement" title="Permalink to this definition">
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
.
<p>
That is:
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
b
(
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<em>
Vec2f
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Vec2f.GetDot" title="Permalink to this definition">
<dd>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<a class="headerlink" href="#pxr.Gf.Vec2f.GetLength" title="Permalink to this definition">
<dd>
<p>
Length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
<a class="headerlink" href="#pxr.Gf.Vec2f.GetNormalized" title="Permalink to this definition">
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
v
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
<a class="headerlink" href="#pxr.Gf.Vec2f.GetProjection" title="Permalink to this definition">
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
onto
<code class="docutils literal notranslate">
.
That is:
v \* (\*this \* v)
```
Parameters
----------
v (Vec2f) –
Normalize
---------
(eps) → float
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
Parameters
----------
eps (float) –
XAxis
-----
() → Vec2f
Create a unit vector along the X-axis.
YAxis
-----
() → Vec2f
Create a unit vector along the Y-axis.
dimension
---------
= 2
Vec2h
-----
Methods:
- Axis(i) → Vec2h
- GetComplement(b)
- GetDot()
- GetLength()
- GetNormalized(eps)
| 方法 | 描述 |
| --- | --- |
| `GetProjection(v)` | Returns the projection of `this` onto `v`. |
| `Normalize(eps)` | Normalizes the vector in place to unit length, returning the length before normalization. |
| `XAxis()` | `classmethod` XAxis() -> Vec2h |
| `YAxis()` | `classmethod` YAxis() -> Vec2h |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `dimension` | |
**classmethod Axis(i) -> Vec2h**
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if `i` is greater than or equal to 2.
**Parameters**
- **i** (int) –
**GetComplement(b) -> Vec2h**
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
**Parameters**
- **b** (Vec2h) –
**GetLength() -> GfHalf**
Length.
### GetNormalized
- **Parameters**
- **eps** (GfHalf) –
### GetProjection
- Returns the projection of `this` onto `v`.
- **Parameters**
- **v** (Vec2h) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- **Parameters**
- **eps** (GfHalf) –
### XAxis
- **classmethod** XAxis() -> Vec2h
- Create a unit vector along the X-axis.
### YAxis
- **classmethod** YAxis() -> Vec2h
- Create a unit vector along the Y-axis.
### dimension
- **dimension** = 2
### Methods:
| Description | Method |
|-------------|--------|
| classmethod Axis(i) -> Vec2i | Axis |
| classmethod XAxis() -> Vec2i | XAxis |
| classmethod YAxis() -> Vec2i | YAxis |
| classmethod GetDot() -> Vec2i | GetDot |
### Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension (int) = 2 | dimension |
### Details:
#### Axis
- **classmethod** Axis(i) -> Vec2i
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 2.
- **Parameters:**
- **i** (int) –
#### XAxis
- **classmethod** XAxis() -> Vec2i
- Create a unit vector along the X-axis.
#### YAxis
- **classmethod** YAxis() -> Vec2i
- Create a unit vector along the Y-axis.
#### GetDot
- **classmethod** GetDot() -> Vec2i
#### dimension
- **attribute** dimension = 2
| Row | Content |
| --- | --- |
| Even | `BuildOrthonormalFrame(v1, v2, eps)` - Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal. |
| Odd | `GetComplement(b)` - Returns the orthogonal complement of `this->GetProjection(b)`. |
| Even | `GetCross` |
| Odd | `GetDot` |
| Even | `GetLength()` - Length. |
| Odd | `GetNormalized(eps)` - param eps |
| Even | `GetProjection(v)` - Returns the projection of `this` onto `v`. |
| Odd | `Normalize(eps)` - Normalizes the vector in place to unit length, returning the length before normalization. |
| Even | `OrthogonalizeBasis` - `classmethod` OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool |
| Odd | `XAxis` - `classmethod` XAxis() -> Vec3d |
| Even | `YAxis` - `classmethod` YAxis() -> Vec3d |
| Odd | `ZAxis` - `classmethod` ZAxis() -> Vec3d |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `dimension` | |
### Axis(i) -> Vec3d
- **classmethod**
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 3.
- **Parameters**
- **i** (`int`) –
### BuildOrthonormalFrame(v1, v2, eps) -> None
- Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
- If the length L of *this is smaller than `eps`, then v1 and v2 will have magnitude L/eps.
- **Parameters**
- **v1** (`Vec3d`) –
- **v2** (`Vec3d`) –
- **eps** (`float`) –
### GetComplement(b) -> Vec3d
- Returns the orthogonal complement of `this->GetProjection(b)`.
- That is: \*this - this->GetProjection(b)
- **Parameters**
- **b** (`Vec3d`) –
### GetCross()
### GetDot()
### GetLength() -> float
- Length.
### GetNormalized(eps)
### GetNormalized
- Parameters
- **eps** (float) –
### GetProjection
- Returns the projection of `this` onto `v`.
- That is:
```
v * (this * v)
```
- Parameters
- **v** (Vec3d) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
- Parameters
- **eps** (float) –
### OrthogonalizeBasis
- **classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
- Orthogonalize and optionally normalize a set of basis vectors.
- This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
- Parameters
- **tx** (Vec3d) –
- **ty** (Vec3d) –
- **tz** (Vec3d) –
- **normalize** (bool) –
- **eps** (float) –
### XAxis
## XAxis
```python
classmethod XAxis() -> Vec3d
```
Create a unit vector along the X-axis.
## YAxis
```python
classmethod YAxis() -> Vec3d
```
Create a unit vector along the Y-axis.
## ZAxis
```python
classmethod ZAxis() -> Vec3d
```
Create a unit vector along the Z-axis.
## dimension
```python
dimension = 3
```
## Vec3f
### Methods:
- `Axis(i) -> Vec3f`
- `BuildOrthonormalFrame(v1, v2, eps)`
Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
- `GetComplement(b)`
Returns the orthogonal complement of `this->GetProjection(b)`.
- `GetCross()`
- `GetDot()`
- `GetLength()`
Length.
- `GetNormalized(eps)`
- param eps
- `GetProjection(v)`
Returns the projection of `this`.
onto
```
```markdown
v
```
```markdown
Normalize (eps)
```
```markdown
Normalizes the vector in place to unit length, returning the length before normalization.
```
```markdown
OrthogonalizeBasis
```
```markdown
classmethod
OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
```
```markdown
XAxis
```
```markdown
classmethod
XAxis() -> Vec3f
```
```markdown
YAxis
```
```markdown
classmethod
YAxis() -> Vec3f
```
```markdown
ZAxis
```
```markdown
classmethod
ZAxis() -> Vec3f
```
```markdown
Attributes:
```
```markdown
dimension
```
```markdown
static
Axis
```
```markdown
classmethod
Axis(i) -> Vec3f
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if i is greater than or equal to 3.
Parameters
----------
i (int) –
```
```markdown
BuildOrthonormalFrame
```
```markdown
BuildOrthonormalFrame(v1, v2, eps)
Sets v1 and v2 to unit vectors such that v1, v2 and *this are mutually orthogonal.
If the length L of *this is smaller than eps, then v1 and v2 will have magnitude L/eps. As a result, the function delivers a continuous result as *this shrinks in length.
Parameters
----------
v1 (Vec3f) –
v2 (Vec3f) –
eps (float) –
```
### GetComplement
```python
GetComplement(b)
```
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```python
*this - this->GetProjection(b)
```
#### Parameters
- **b** (`Vec3f`) –
### GetCross
```python
GetCross()
```
### GetDot
```python
GetDot()
```
### GetLength
```python
GetLength()
```
Returns: `float`
Length.
### GetNormalized
```python
GetNormalized(eps)
```
Returns: `Vec3f`
#### Parameters
- **eps** (`float`) –
### GetProjection
```python
GetProjection(v)
```
Returns the projection of `this` onto `v`.
That is:
```python
v * (*this * v)
```
#### Parameters
- **v** (`Vec3f`) –
### Normalize
```python
Normalize(eps)
```
Returns: `float`
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/
```
`eps`. The original length of the vector is returned. See also GfNormalize().
### Parameters
- **eps** (`float`) –
## OrthogonalizeBasis
```python
classmethod OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
```
Orthogonalize and optionally normalize a set of basis vectors.
This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
### Parameters
- **tx** (`Vec3f`) –
- **ty** (`Vec3f`) –
- **tz** (`Vec3f`) –
- **normalize** (`bool`) –
- **eps** (`float`) –
## XAxis
```python
classmethod XAxis() -> Vec3f
```
Create a unit vector along the X-axis.
## YAxis
```python
classmethod YAxis() -> Vec3f
```
Create a unit vector along the Y-axis.
## ZAxis
```python
classmethod ZAxis() -> Vec3f
```
Create a unit vector along the Z-axis.
## dimension
```python
dimension = 3
```
## Vec3h
### Methods:
- **Axis**
```python
classmethod Axis(i) -> Vec3h
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
BuildOrthonormalFrame
(v1, v2, eps)
<td>
<p>
Sets
<code class="docutils literal notranslate">
<span class="pre">
v1
and
<code class="docutils literal notranslate">
<span class="pre">
v2
to unit vectors such that v1, v2 and *this are mutually orthogonal.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetComplement" title="pxr.Gf.Vec3h.GetComplement">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetComplement
(b)
<td>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
.
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetCross" title="pxr.Gf.Vec3h.GetCross">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetCross
<td>
<p>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetDot" title="pxr.Gf.Vec3h.GetDot">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetDot
<td>
<p>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetLength" title="pxr.Gf.Vec3h.GetLength">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetLength
()
<td>
<p>
Length.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetNormalized" title="pxr.Gf.Vec3h.GetNormalized">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetNormalized
(eps)
<td>
<p>
<dl class="field-list simple">
<dt class="field-odd">
param eps
<dd class="field-odd">
<p>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetProjection" title="pxr.Gf.Vec3h.GetProjection">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetProjection
(v)
<td>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
onto
<code class="docutils literal notranslate">
<span class="pre">
v
.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.Normalize" title="pxr.Gf.Vec3h.Normalize">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Normalize
(eps)
<td>
<p>
Normalizes the vector in place to unit length, returning the length before normalization.
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.OrthogonalizeBasis" title="pxr.Gf.Vec3h.OrthogonalizeBasis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
OrthogonalizeBasis
<td>
<p>
<strong>
classmethod
OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.XAxis" title="pxr.Gf.Vec3h.XAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
XAxis
<td>
<p>
<strong>
classmethod
XAxis() -> Vec3h
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.YAxis" title="pxr.Gf.Vec3h.YAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
YAxis
<td>
<p>
<strong>
classmethod
YAxis() -> Vec3h
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.ZAxis" title="pxr.Gf.Vec3h.ZAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
ZAxis
<td>
<p>
<strong>
classmethod
ZAxis() -> Vec3h
<p>
<strong>
Attributes:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.dimension" title="pxr.Gf.Vec3h.dimension">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
<td>
<p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec3h.Axis">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
Axis
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Gf.Vec3h.Axis" title="Permalink to this definition">
## classmethod Axis(i) -> Vec3h
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if `i` is greater than or equal to 3.
### Parameters
- **i** (int) –
## BuildOrthonormalFrame(v1, v2, eps) -> None
Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
If the length L of *this is smaller than `eps`, then v1 and v2 will have magnitude L/eps. As a result, the function delivers a continuous result as *this shrinks in length.
### Parameters
- **v1** (Vec3h) –
- **v2** (Vec3h) –
- **eps** (GfHalf) –
## GetComplement(b) -> Vec3h
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
### Parameters
- **b** (Vec3h) –
## GetLength() -> GfHalf
Length.
### GetNormalized
- **Parameters**
- **eps** (GfHalf) –
### GetProjection
- Returns the projection of `this` onto `v`.
- That is:
```
v * (this * v)
```
- **Parameters**
- **v** (Vec3h) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
- **Parameters**
- **eps** (GfHalf) –
### OrthogonalizeBasis
- **classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
- Orthogonalize and optionally normalize a set of basis vectors.
- This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
- **Parameters**
- **tx** (Vec3h) –
- **ty** (Vec3h) –
- **tz** (Vec3h) –
- **normalize** (bool) –
- **eps** (float) –
### XAxis
- **static** XAxis()
### XAxis
```python
classmethod
XAxis() -> Vec3h
```
Create a unit vector along the X-axis.
### YAxis
```python
classmethod
YAxis() -> Vec3h
```
Create a unit vector along the Y-axis.
### ZAxis
```python
classmethod
ZAxis() -> Vec3h
```
Create a unit vector along the Z-axis.
### dimension
```python
dimension = 3
```
### Vec3i
```
class pxr.Gf.Vec3i
```
Methods:
| Method | Description |
|--------|-------------|
| Axis(i) -> Vec3i | Create a unit vector along the i-th axis, zero-based. Return the zero vector if i is greater than or equal to 3. |
| GetDot | |
| XAxis() -> Vec3i | |
| YAxis() -> Vec3i | |
| ZAxis() -> Vec3i | |
Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension | |
## pxr.Gf.Vec3i Methods
### XAxis
**classmethod** XAxis() -> Vec3i
Create a unit vector along the X-axis.
### YAxis
**classmethod** YAxis() -> Vec3i
Create a unit vector along the Y-axis.
### ZAxis
**classmethod** ZAxis() -> Vec3i
Create a unit vector along the Z-axis.
### dimension
dimension = 3
## pxr.Gf.Vec4d Methods
### Axis
**classmethod** Axis(i) -> Vec4d
### GetComplement
Returns the orthogonal complement of this->GetProjection(b).
### GetDot
### GetLength
Length.
### GetNormalized
param eps
### GetProjection
Returns the projection of this onto v.
### Normalize
| Method | Description |
|--------|-------------|
| `WAxis()` | classmethod WAxis() -> Vec4d |
| `XAxis()` | classmethod XAxis() -> Vec4d |
| `YAxis()` | classmethod YAxis() -> Vec4d |
| `ZAxis()` | classmethod ZAxis() -> Vec4d |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**static** `Axis()`
- **classmethod** Axis(i) -> Vec4d
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 4.
- **Parameters**
- **i** (int) –
`GetComplement(b)`
- Returns the orthogonal complement of `this->GetProjection(b)`.
- That is: `*this - this->GetProjection(b)`
- **Parameters**
- **b** (Vec4d) –
`GetDot()`
`GetLength()`
- Length.
`GetNormalized(eps)`
### Vec4d.GetNormalized
- **Parameters**
- **eps** (float) –
### Vec4d.GetProjection
- **Parameters**
- **v** (Vec4d) –
### Vec4d.Normalize
- **Parameters**
- **eps** (float) –
### Vec4d.WAxis
- **classmethod** WAxis() -> Vec4d
- Create a unit vector along the W-axis.
### Vec4d.XAxis
- **classmethod** XAxis() -> Vec4d
- Create a unit vector along the X-axis.
### Vec4d.YAxis
- **classmethod** YAxis() -> Vec4d
- Create a unit vector along the Y-axis.
### Vec4d.ZAxis
- **classmethod** ZAxis() -> Vec4d
- Create a unit vector along the Z-axis.
### Vec4d.dimension
- **property** dimension
## pxr.Gf.Vec4f
### Methods:
| Method | Description |
| ------ | ----------- |
| Axis(i) -> Vec4f | classmethod |
| GetComplement(b) | Returns the orthogonal complement of this->GetProjection(b). |
| GetDot | |
| GetLength() | Length. |
| GetNormalized(eps) | param eps |
| GetProjection(v) | Returns the projection of this onto v. |
| Normalize(eps) | Normalizes the vector in place to unit length, returning the length before normalization. |
| WAxis() -> Vec4f | classmethod |
| XAxis() -> Vec4f | classmethod |
| YAxis() -> Vec4f | classmethod |
| ZAxis() -> Vec4f | classmethod |
### Attributes:
| Attribute | Description |
| --------- | ----------- |
| dimension | |
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
Axis
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
<strong>
classmethod
Axis(i) -> Vec4f
<p>
Create a unit vector along the i-th axis, zero-based.
<p>
Return the zero vector if
<code class="docutils literal notranslate">
<span class="pre">
i
is greater than or equal to 4.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
i
(
<em>
int
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
b
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec4f
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
.
<p>
That is:
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
b
(
<em>
Vec4f
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
float
<dd>
<p>
Length.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec4f
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
eps
(
<em>
float
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
v
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
Vec4f
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
onto
<code class="docutils literal notranslate">
<span class="pre">
v
.
<p>
That is:
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
v
(
<em>
Vec4f
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
eps
)
→ float
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
**Parameters**
**eps** (**float**) –
classmethod WAxis() -> Vec4f
Create a unit vector along the W-axis.
classmethod XAxis() -> Vec4f
Create a unit vector along the X-axis.
classmethod YAxis() -> Vec4f
Create a unit vector along the Y-axis.
classmethod ZAxis() -> Vec4f
Create a unit vector along the Z-axis.
dimension = 4
class pxr.Gf.Vec4h
Methods:
- Axis(i) -> Vec4h
- GetComplement(b)
Returns the orthogonal complement of this->GetProjection(b).
- GetDot()
- GetLength()
Length.
```
```
GetNormalized (eps)
```
```
param eps
```
```
GetProjection (v)
```
Returns the projection of `this` onto `v`.
```
Normalize (eps)
```
Normalizes the vector in place to unit length, returning the length before normalization.
```
WAxis
```
```
classmethod WAxis() -> Vec4h
```
```
XAxis
```
```
classmethod XAxis() -> Vec4h
```
```
YAxis
```
```
classmethod YAxis() -> Vec4h
```
```
ZAxis
```
```
classmethod ZAxis() -> Vec4h
```
```
dimension
```
```
static classmethod Axis(i) -> Vec4h
```
Create a unit vector along the i-th axis, zero-based. Return the zero vector if `i` is greater than or equal to 4.
Parameters:
- **i** (int) –
```
GetComplement (b) -> Vec4h
```
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
Parameters:
- **b** (Vec4h) –
```
### GetDot
```
### GetLength
```
Length.
```
### GetNormalized
```
Parameters
----------
eps (GfHalf) –
```
### GetProjection
```
Returns the projection of `this` onto `v`.
That is:
```
v * (*this * v)
```
Parameters
----------
v (Vec4h) –
```
### Normalize
```
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
```
Parameters
----------
eps (GfHalf) –
```
### WAxis
```
classmethod WAxis() -> Vec4h
Create a unit vector along the W-axis.
```
### XAxis
```
classmethod XAxis() -> Vec4h
Create a unit vector along the X-axis.
```
### YAxis
### YAxis
- **classmethod** YAxis() -> Vec4h
- Create a unit vector along the Y-axis.
### ZAxis
- **classmethod** ZAxis() -> Vec4h
- Create a unit vector along the Z-axis.
### dimension
- **Attribute** dimension = 4
### Vec4i
- **Methods:**
- **classmethod** Axis(i) -> Vec4i
- **classmethod** WAxis() -> Vec4i
- **classmethod** XAxis() -> Vec4i
- **classmethod** YAxis() -> Vec4i
- **classmethod** ZAxis() -> Vec4i
- **Attributes:**
- **Attribute** dimension
### Axis
- **classmethod** Axis(i) -> Vec4i
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 4.
- **Parameters**
- **i** (int) –
### GetDot
```
```markdown
### WAxis
```
```markdown
### XAxis
```
```markdown
### YAxis
```
```markdown
### ZAxis
```
```markdown
### dimension
``` | 211,668 |
Glf.md | # Glf module
Summary: The Glf module contains Utility classes for OpenGL output.
## Classes:
- **DrawTarget**
- A class representing a GL render target with multiple image attachments.
- **GLQueryObject**
- Represents a GL query object in Glf.
- **SimpleLight**
- (No description provided)
- **SimpleMaterial**
- (No description provided)
- **Texture**
- Represents a texture object in Glf.
### DrawTarget
- **Methods:**
- **AddAttachment(name, format, type, internalFormat)**
- Add an attachment to the DrawTarget.
| Method | Description |
| --- | --- |
| Bind() | Binds the framebuffer. |
| Unbind() | Unbinds the framebuffer. |
| WriteToFile(name, filename, viewMatrix, ...) | Write the Attachment buffer to an image file (debugging). |
**Attributes:**
| Attribute | Description |
| --- | --- |
| expired | True if this object has expired, False otherwise. |
**AddAttachment(name, format, type, internalFormat)**
- **Parameters**
- **name** (str)
- **format** (GLenum)
- **type** (GLenum)
- **internalFormat** (GLenum)
**Bind()**
- Binds the framebuffer.
**Unbind()**
- Unbinds the framebuffer.
**WriteToFile(name, filename, viewMatrix, projectionMatrix)**
- Write the Attachment buffer to an image file (debugging).
### Parameters
- **name** (`str`) –
- **filename** (`str`) –
- **viewMatrix** (`Matrix4d`) –
- **projectionMatrix** (`Matrix4d`) –
### Property: expired
- True if this object has expired, False otherwise.
### Class: pxr.Glf.GLQueryObject
Represents a GL query object in Glf
#### Methods:
| Method | Description |
|--------|-------------|
| `Begin` (target) | Begin query for the given target. Target has to be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED, GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TIME_ELAPSED, GL_TIMESTAMP. |
| `BeginPrimitivesGenerated` () | Equivalent to Begin(GL_PRIMITIVES_GENERATED). |
| `BeginSamplesPassed` () | Equivalent to Begin(GL_SAMPLES_PASSED). |
| `BeginTimeElapsed` () | Equivalent to Begin(GL_TIME_ELAPSED). |
| `End` () | End query. |
| `GetResult` () | Return the query result (synchronous) stalls CPU until the result becomes available. |
| `GetResultNoWait` () | Return the query result (asynchronous) returns 0 if the result hasn't been available. |
#### Method: Begin
- Begin query for the given target. Target has to be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED, GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TIME_ELAPSED, GL_TIMESTAMP. Returns None.
GL_TRANSFORM_FEITBACK_PRIMITIVES_WRITTEN GL_TIME_ELAPSED,
GL_TIMESTAMP.
### Parameters
**target** (GLenum) –
### BeginPrimitivesGenerated
equivalent to Begin(GL_PRIMITIVES_GENERATED).
The number of primitives sent to the rasterizer by the scoped drawing command will be returned.
### BeginSamplesPassed
equivalent to Begin(GL_SAMPLES_PASSED).
The number of samples that pass the depth test for all drawing commands within the scope of the query will be returned.
### BeginTimeElapsed
equivalent to Begin(GL_TIME_ELAPSED).
The time that it takes for the GPU to execute all of the scoped commands will be returned in nanoseconds.
### End
End query.
### GetResult
Return the query result (synchronous) stalls CPU until the result becomes available.
### GetResultNoWait
Return the query result (asynchronous) returns 0 if the result hasn’t been available.
### SimpleLight
**Attributes:**
- ambient
- attenuation
| 属性 | 描述 |
| --- | --- |
| `diffuse` | None |
| `hasShadow` | None |
| `id` | |
| `isCameraSpaceLight` | None |
| `isDomeLight` | None |
| `position` | None |
| `shadowBias` | None |
| `shadowBlur` | None |
| `shadowIndexEnd` | None |
| `shadowIndexStart` | None |
| `shadowMatrices` | None |
| `shadowResolution` | None |
| `specular` | None |
| `spotCutoff` | None |
| `spotDirection` | None |
| `spotFalloff` | None |
| `transform` | None |
## Properties
### ambient
- **Type**: Vec4f
### attenuation
- **Type**: Vec3f
### diffuse
- **Type**: Vec4f
### hasShadow
- **Type**: type
### id
### isCameraSpaceLight
- **Type**: bool
### isDomeLight
- **Type**: bool
### position
- **Type**: Vec4f
### shadowBias
- **Type**: float
### shadowBlur
- **Type**: float
### shadowIndexEnd
- **Type**: int
### shadowIndexStart
- **Type**: int
### shadowMatrices
- **Type**: list[Matrix4d]
### shadowResolution
- **Type**: int
### specular
- **Type**: Vec4f
### spotCutoff
- **Type**: float
### spotDirection
- **Type**: Vec3f
### spotFalloff
- **Type**: float
### transform
- **Type**: Matrix4d
### SimpleMaterial
- **Type**: class
## SimpleMaterial
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `ambient` | None |
| `diffuse` | None |
| `emission` | None |
| `shininess` | None |
| `specular` | None |
### ambient
**Type:** Vec4f
### diffuse
**Type:** Vec4f
### emission
**Type:** Vec4f
### shininess
**Type:** float
### specular
**Type:** Vec4f
## Texture
Represents a texture object in Glf.
A texture is typically defined by reading texture image data from an image file but a texture might also represent an attachment of a draw target.
**Methods:**
| 属性 | 描述 |
| --- | --- |
| `GetTextureMemoryAllocated` | `classmethod GetTextureMemoryAllocated() -> int` |
| `magFilterSupported` | bool |
| `memoryRequested` | None |
| `memoryUsed` | int |
| `minFilterSupported` | bool |
**Attributes:**
```python
classmethod GetTextureMemoryAllocated() -> int
```
static reporting function
```python
property magFilterSupported
```
bool
Type: type
```python
property memoryRequested
```
None
Specify the amount of memory the user wishes to allocate to the texture.
type: int
Amount of memory the user wishes to allocate to the texture.
Type: type
```python
property memoryUsed
```
int
Amount of memory used to store the texture.
Type: type
```python
property minFilterSupported
```
bool
Type: type | 5,956 |
global-simulation-commands_structcarb_1_1blast_1_1_blast.md | # carb::blast::Blast
Defined in [Blast.h](file_Blast.h)
## Destructible Authoring Commands
Plugin interface for the omni.blast extension.
### combinePrims
### DamageParameters
* damageParameters,
* float defaultMaxContactImpulse)
Main entry point to combine a existing prims into a single destructible.
#### Parameters
- **Param paths**
- [in] Full USD paths to prims that should be combined.
- **Param numPaths**
- [in] How many prims are in the paths array.
- **Param defaultContactThreshold**
- [in] How hard the prim needs to be hit to register damage during simulation.
- **Param damageParameters**
- [in] See DamageParameters description.
- **Param defaultMaxContactImpulse**
- [in] How much force can be used to push other prims away during a collision For kinematic prims only, used to allow heavy objects to continue moving through brittle destructible prims.
#### Return
- true iff the prims were combined successfully.
### fracturePrims
- const char * (const char ** paths, size_t numPaths, const char * defaultInteriorMaterial, uint32_t numVoronoiSites, float defaultContactThreshold, const DamageParameters * damageParameters)
Main entry point to fracture an existing prim.
### Parameters
- **Param paths [in]**
Full USD path(s) to prim(s) that should be fractured. They need to all be part of the same destructible if there are more than one.
- **Param numPaths [in]**
How many prims are in the paths array.
- **Param defaultInteriorMaterial [in]**
Material to set on newly created interior faces. (Ignored when re-fracturing and existing interior material is found.)
- **Param numVoronoiSites [in]**
How many pieces to split the prim into.
- **Param defaultContactThreshold [in]**
How hard the prim needs to be hit to register damage during simulation.
- **Param damageParameters [in]**
See [DamageParameters](structcarb_1_1blast_1_1_damage_parameters.html#structcarb_1_1blast_1_1_damage_parameters) description.
- **Param defaultMaxContactImpulse [in]**
How much force can be used to push other prims away during a collision. For kinematic prims only, used to allow heavy objects to continue moving through brittle destroyable prims.
- **Param interiorUvScale [in]**
Scale to apply to UV frame when mapping to interior face vertices.
### Return
path to the new prim if the source prim was fractured successfully, nullptr otherwise.
### Function: setRandomSeed
Set the random number generator seed for fracture operations.
#### Parameters
- **Param seed [in]**
the new seed.
### Function: resetBlastData
Reset the [Blast](#structcarb_1_1blast_1_1_blast) data (partial or full hierarchy) starting at the given path.
#### Parameters
- **Param path [in]**
the path to reset.
The destructible will be rebuilt with only appropriate data remaining.
- **Param path**
- **[in]** The path to a chunk, instance, or base destructible prim.
- **Return**
- true iff the operation could be performed on the prim at the given path.
- **Param path**
- **[in]** The USD path of the blast container.
- **Param defaultMaxContactImpulse**
- **[in]** Controls how much force physics can use to stop bodies from penetrating.
- **Param relativePadding**
- **[in]** A relative amount to grow chunk bounds in order when calculating world attachment.
- **Return**
- true if the destructible’s NvBlastAsset was modified (or if path == NULL).
- **Param path**
- **[in]** The USD path of the blast container.
- **Return**
- true if the destructible’s NvBlastAsset was modified (or if path == NULL).
Recalculates the areas of bonds.
This may be used when a destructible is scaled.
**Param path**
- **[in]** Path to the chunk, instance, or base destructible prim.
**Return**
- true iff the operation was successful.
Finds all children of the chunks in the given paths, and sets kit’s selection set to the paths of those children.
**Param paths**
- **[in]** Full USD path(s) to chunks.
**Param numPaths**
- **[in]** How many paths are in the paths array.
**Return**
- true iff the operation was successful.
### Function: selectParent
Finds all parents of the chunks in the given paths, and sets kit’s selection set to the paths of those parents.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
#### Return
true iff the operation was successful.
### Function: selectSource
Finds all source meshes for chunks in the given paths, and sets kit’s selection set to the paths of those meshes.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
#### Return
true iff the operation was successful.
### Function: setInteriorMaterial
Sets the material for the interior facets of the chunks at the given paths.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
- **interiorMaterial** [in]: The material to set for the interior facets.
### Description
#### Param paths
- **[in]** Full USD path(s) to chunks.
#### Param numPaths
- **[in]** How many paths are in the paths array.
#### Return
- the material path if all meshes found at the given paths have the same interior materials. If more than one interior material is found among the meshes found, the empty string (“”) is returned. If no interior material is found, nullptr is returned.
### Description
#### Param path
- **[in]** Path to the chunk, instance, or base destructible prim.
#### Param interiorUvScale
- **[in]** the scale to use to calculate UV coordinates. A value of 1 will cause the texture to map to a region in space roughly the size of the whole destructible’s largest width.
#### Return
- true iff the operation was successful.
### Function: createDestructibleInstance
```cpp
void createDestructibleInstance(
const char *path,
DamageParameters *damageParameters,
float defaultContactThreshold,
float defaultMaxContactImpulse
)
```
Creates a destructible instance with default values from the given destructible base.
**Parameters:**
- **path** [in] Path to the destructible base to instance.
- **damageParameters** [in] The damage characteristics to assign to the instance (see DamageParameters).
- **defaultContactThreshold** [in] Rigid body parameter to apply to actors generated by the instance. The minimum impulse required for a rigid body to generate a contact event, needed for impact damage.
- **defaultMaxContactImpulse** [in] Rigid body parameter to apply to actors generated by the instance. The maximum impulse that a contact constraint on a kinematic rigid body can impart on a colliding body.
### Function: setSimulationParams
```cpp
void setSimulationParams(int32_t maxNewActorsPerFrame)
```
Sets the maximum number of actors which will be generated by destruction each simulation frame.
**Parameters:**
- **maxNewActorsPerFrame** [in] The maximum number of actors generated per frame.
### Damage Application
```cpp
void createDamageEvent(const char *hitPrimPath, DamageEvent *damageEvents, size_t numDamageEvents);
```
Create a destruction event during simulation.
**Parameters:**
- **hitPrimPath [in]** - The full path to the prim to be damaged (may be a blast actor prim or its collision shape).
- **damageEvents [in]** - An array of DamageEvent structs describing the damage to be applied.
- **numDamageEvents [in]** - The size of the damageEvents array.
---
```cpp
void setExplodeViewRadius(const char *path, float radius);
```
Set the cached explode view radius for the destructible prim associated with the given path.
**Parameters:**
- **path [in]** - Full USD path to a destructible instance.
- **radius [in]** - The distance to move apart the instance’s rendered chunks.
```
Gives the cached explode view radius for the destructible instances associated with the given paths, if the cached value for all instances is the same.
**Param paths**
- **[in]** Array of USD paths to destructible instances.
**Param numPaths**
- **[in]** The length of the paths array.
**Return**
- The cached explode view radius for all valid destructible instances at the given paths, if that value is the same for all instances. If there is more than one radius found, this function returns -1.0f. If no valid instances are found, this function returns 0.0f.
Calculate the maximum depth for all chunks in the destructible prim associated with the given paths.
**Param paths**
- **[in]** Array of USD paths to destructible prims.
**Param numPaths**
- **[in]** The length of the paths array.
**Return**
- the maximum chunk depth for all destructibles associated with the given paths. Returns 0 if no destructibles are found.
### getViewDepth
Calculates what the view depth should be, factoring in internal override if set.
/return return what the view depth should be.
#### Parameters
- **Param paths [in]** Array of USD paths to destructible prims.
- **Param numPaths [in]** The length of the paths array.
### setViewDepth
Set the view depth for explode view functionality.
#### Parameters
- **Param paths [in]** Array of USD paths to destructible prims.
- **Param numPaths [in]** The length of the paths array.
- **Param depth [in]** Either a string representation of the numerical depth value, or “Leaves” to view leaf chunks.
### setDebugVisualizationInfo
Set the debug visualization info.
#### Parameters
- **Param mode [in]** The mode for debug visualization.
- **Param value [in]** The value for the debug visualization mode.
Set the debug visualization mode & type.
If mode != debugVisNone, an anonymous USD layer is created which overrides the render meshes for blast objects which are being visualized.
- **Param mode [in]**
- Supported modes: “debugVisNone”, “debugVisSelected”, “debugVisAll”
- **Param type [in]**
- Supported modes: “debugVisSupportGraph”, “debugVisMaxStressGraph”, “debugVisCompressionGraph”, “debugVisTensionGraph”, “debugVisShearGraph”, “debugVisBondPatches”
- **Return**
- true iff a valid mode is selected.
Debug Damage Functions
Set parameters for the debug damage tool in kit.
This is applied using Shift + B + (Left Mouse). A ray is cast from the camera position through the screen point of the mouse cursor, and intersected with scene geometry. The intersection point is used to find nearby destructibles using to damage.
- **Param amount [in]**
- The base damage to be applied to each destructible, as an acceleration in m/s^2.
- **Param impulse [in]**
- An impulse to apply to rigid bodies within the given radius, in kg*m/s. (This applies to non-destructible rigid bodies too.)
- **Param radius [in]**
- The distance in meters from the ray hit point to search for rigid bodies to affect with this function.
### Apply Debug Damage
Apply debug damage at the position given, in the direction given.
The damage parameters set by setDebugDamageParams will be used.
#### Parameters
- **Param worldPosition [in]**
The world position at which to apply debug damage.
- **Param worldDirection [in]**
The world direction of the applied damage.
### Notice Handler Functions
These can be called at any time to enable or disable notice handler monitoring.
When enabled, use BlastUsdMonitorNoticeEvents to catch unbuffered Usd/Sdf commands. It will be automatically cleaned up on system shutdown if enabled.
- **blastUsdEnableNoticeHandlerMonitor()**
- **blastUsdDisableNoticeHandlerMonitor()**
### Destructible Path Utilities
These functions find destructible base or instance prims from any associated prim path.
- **getDestructibleBasePath(const char* path)**
- **Param path [in]**
Any path associated with a destructible base prim.
- **Return**
the destructible prim’s path if found, or nullptr otherwise.
## getDestructibleInstancePath
```
```markdown
## blastCachePushBinaryDataToUSD
```
```markdown
## Blast SDK Cache
```
```markdown
This function pushes the Blast SDK data that is used during simulation back to USD so it can be saved and then later restored in the same state.
This is also the state that will be restored to when sim stops.
```
```markdown
## Blast Stress
```
```markdown
This function modifies settings used to drive stress calculations during simulation.
```
```markdown
Param path
```
```markdown
[in] Any path associated with a destructible instance prim.
```
```markdown
Param gravityEnabled
```
```markdown
[in] Controls if gravity should be applied to stress simulation of the destructible instance.
```
```markdown
Param rotationEnabled
```
```markdown
[in] Controls if rotational acceleration should be applied to stress simulation of the destructible instance.
```
```markdown
Param residualForceMultiplier
```
```markdown
[in] Multiplies the residual forces on bodies after connecting bonds break.
```
```markdown
Param settings
```
```markdown
[in] Values used to control the stress solver.
```
```markdown
Return
```
```markdown
true if stress settings were updated, false otherwise.
```
```markdown
char * path, bool gravityEnabled, bool rotationEnabled, float residualForceMultiplier, const StressSolverSettings & settings) | 13,133 |
Glossary.md | # Glossary
## “Any” Attribute Type
An [Extended Attribute](#term-Extended-Attribute) that can accept values or connections with any legal attribute type, with a few exceptions.
## Action Graph
An [OmniGraph](#term-OmniGraph) that triggers actions in response to a particular event.
## Attribute
A property of a node or node type that consists of a name, a data type, and a set of metadata that defines further properties.
## Attribute Data
The actual value an attribute has been given for a specific node and [Graph Context](#term-Graph-Context).
## Attribute Type
A description of the data type an attribute can hold. In many cases it is a simple piece of data such as float, int, or double, but it can also be more complicated data like a [“Union” Attribute Type](#term-Union-Attribute-Type) or a [Bundle](#term-Bundle).
## Authoring Graph
Refers to the definition of an [OmniGraph](#term-OmniGraph) structure, including nodes, attributes, and connections.
## Bundle
A Bundle is an attribute comprising of a set of named attributes, including other bundles.
## C++ ABI
The backwards-compatible interface surface defined by an extension. It consists of a set of interface classes, each of which comprise a set of static functions that are defined by an interface implementation.
## C++ API
A layer on top of the [C++ ABI](#term-C-ABI) that provides a higher level interface on top of the low level ABI interface functions to make it easier to interact with the C++ code.
## Compound Node
A compound node is a [Node](#term-Node) whose execution is defined by the evaluation of a [Graph](#term-Graph).
## Compound Graph
A compound graph is a [Graph](#term-Graph) that defines the execution of a [Graph](#term-Graph).
## Compound Node
## Compute Graph
“Compute graph” is a synonym for OmniGraph, an engine for programmatically manipulating scenes with a graph-based visual scripting interface.
## Connection
An edge in the Graph that joins two Nodes, indicating a relationship between the two Nodes, usually that the downstream Node cannot evaluate until the upstream Node has completed evaluation. Generally speaking the connections are formed between two Attributes on the Nodes, not between the Nodes directly.
## Dynamic Attribute
A Dynamic Attribute is an Attribute that is added to a node at runtime, as opposed to the ones that are predefined as part of the node’s ogn definition.
## Execution Graph
The intermediate representation of an OmniGraph that has been optimized for fast evaluation, and which follows the business logic needs of a specifically defined Authoring Graph.
## Extended Attribute
A type of attribute that is allowed to accept or produce more than one type of data.
## Fabric
The underlying data model that houses the data used by the Execution Graph during evaluation. It also provides the synchronizing of data between the CPU, GPU, USD, and external processes.
## Generic Graph
The term Generic Graph is also referred to as a Push Graph, which evaluates every node at every system update, or “tick”.
## Graph
The abstract concept that comprises nodes and connections which could be referring to either the Authoring Graph, the Execution Graph, or the combination of both.
## Graph Context
Each time a Graph is evaluated it is done so using specific evaluation context, represented concretely by the graph context. Different contexts maintain their own separate data models with unique values for every node and attribute evaluated in their context.
## Instance
An instance is a virtual copy of a Graph that can be replicated multiple times without actual replication of the Nodes within the Graph. Used for optimization of computation for duplicate subsections of a Graph by avoiding having multiple copies of the Authoring Graph and Execution Graph.
## Lazy Graph
A Lazy Graph is an OmniGraph that only evaluates nodes whose inputs have changed since the last evaluation.
## Metadata
Metadata is named general data that describes traits of either attributes or node types. It is a more flexible representation of object traits as it can have any data type and any name so that it can be attached to these objects at runtime.
### Node
A node is the basic vertex type in a Graph. It implements a single unit of computation and provides a location for attribute data storage and endpoints for graph edges, or Connections.
### ogn
### .ogn
### OGN
### OmniGraph
An engine for programmatically manipulating scenes with a graph-based visual scripting interface. It provides a platform for building graph types that potentially have very different types of authoring and evaluation representations. OmniGraph can represent such diverse graph types as state machines, AI training, and extension updates within Kit. It can be thought of more concretely as a graph of graphs that comprise the entirety of the graph authoring and evaluation system. Also used as the Prim schema type used for the USD representation of a graph.
### OmniGraphNode
The Prim schema type used for the USD representation of a node in a graph.
### Prim
### USD Prim
### Property
A USD term indicating a namespace object in USD, like a Prim, but with real data. Roughly equivalent to the OmniGraph node Attribute.
### Push Graph
A Push Graph is an OmniGraph that evaluates every node at every system update, or “tick”. It is convenient to use, but potentially inefficient as values are recomputed even when they are not changing.
### Python API
The Python modules that are officially supported as the interface between OmniGraph and the rest of the development environment. Generally speaking if a Python symbol can be imported and its name does not begin with an underscore (_) or dunder (__), then it is part of the supported Python API. Otherwise it is unsupported and subject to change without backward compatibility.
### Python Bindings
A subset of the Python API that is a Python wrapper on top of the C++ ABI. For the most part the functions that appear in it will be similar, other than following Python naming conventions, with a few extra additions that make a function more “Pythonic”, e.g. by supporting a generator.
### “Union” Attribute Type
An Attribute Type that can assume a fixed set of types, as opposed to the “Any” Attribute Type, which can assume any type at all.
### USD
Universal Scene Description (USD) is the fundamental representation for assets in Omniverse, and the persistent backing for OmniGraph nodes.
### Variable
A variable in this context is a value that is globally available at any location in a Graph without requiring an explicit Connection.
### Connection
### Vectorization
The process of evaluating an algorithm in parallel on multiple data sets of the same type. In a
**Node** you can see the difference between regular evaluation and vectorized evaluation as the difference between implementing
the `compute` function versus implementing the `computeVectorized` function. | 6,948 |
goal_Overview.md | # Introduction — Omniverse Kit 1.0.12 documentation
## Introduction
**Extension** : omni.kit.collaboration.channel_manager-1.0.12
**Documentation Generated** : May 08, 2024
### Introduction
Extension `omni.kit.collaboration.channel_manager` provides interfaces for creating/managing the Nucleus Channel easily and defines standard protocol for multiple users to do communication in the same channel. At the same time, users can be aware of each other.
### Goal
The Nucleus Channel only provides a way to pub/sub messages from the channel. It does not provide APIs to manage user states, nor complete application protocol for all clients to understand each other. It’s transient and stateless, so that messages that were sent before user has joined will not be sent again. It does not support P2P message, so that messages sent to the channel are broadcasted to all users. Therefore, we made the following extensions:
- It’s able to query user states from the API, and gets notified when users joined/left.
- It defines application protocol for all clients that support it to communicate with each other.
Currently, no P2P communication is supported still.
### Programming Guide
Here is an async function that joins a channel and sends a string message `hello, world` to the channel.
```python
import omni.kit.collaboration.channel_manager as cm
async def join_channel_async(channel_url, on_message: Callable[[cm.Message], None]):
# Joins the channel, and adds subscriber to subsribe messages.
channel = await cm.join_channel_async(channel_url)
if channel:
channel.add_subscriber(on_message)
# Sends message in dict
await channel.send_message_async({"test": "hello world"})
```
As you can see, the first step is to join a channel with `omni.kit.collaboration.channel_manager.join_channel_async()`, which will return a handle of the channel, through which you can query its connection states, other users that joined the same channel, and send messages (see `omni.kit.collaboration.channel_manager.Channel.send_message_async()`) specific to your application in the format of Python dict.
Also, it supports adding subscribers through
```python
omni.kit.collaboration.channel_manager.Channel.add_subscriber()
```
to subscribe to messages received from the channel. Messages received from other users are in type
```python
omni.kit.collaboration.channel_manager.Message
```
, and depends on the value of its
```python
message_type
```
property, message can be categorized into the following types (see
```python
omni.kit.collaboration.channel_manager.MessageType
```
for details):
- ```python
JOIN
```
: New user joined this channel.
- ```python
HELLO
```
: Someone said hello to me. Normally, it’s received when a new user joined the channel, and other users exist in the channel will reply HELLO so new user could be aware of them.
- ```python
LEFT
```
: Someone left the channel.
- ```python
GET_USERS
```
: Ping message to find out who joined this channel. Clients received this message should reply HELLO.
- ```python
MESSAGE
```
: Application specific message sent through API
```python
omni.kit.collaboration.channel_manager.Channel.send_message_async()
```
. | 3,249 |
Graph%20Core.md | # Graph Core
## Graph View
Following the model-view-delegate pattern, we’ve introduced the model and delegate. Now we are looking at the `GraphView`. It’s the visualisation layer of omni.kit.widget.graph. It behaves like a regular widget and displays nodes and their connections.
Since we mostly just want to use the defined GraphView for all the graphs, we define a core graph widget where you can just focus on building the model and delegate for your customized graph, while reusing the common graph stuff as much as possible.
## Omni.kit.graph.editor.core
We design Omni.kit.graph.editor.core to be the common framework for graph editor in Kit. It is a generic graph widget platform with a standard tree-view panel on the left to show all the available nodes in a list view, with a search bar on the top left. There is the graph editor on the right where we can view and edit the graph. There is also a breadcrumb in the graph view as the navigation of the graph.
We use it as the kit graph core to ensure all standard UI/UX widgets and windows for all our graph nodes are standardized with a common framework.
An example of material graph using omni.kit.graph.editor.core
## Create a graph widget
When you want to create your own graph widget, you can build your GraphWidget (`MyGraphWidget`) based on GraphEditorCoreWidget, define your graph (`self.__graph_model`) and catalog model (`self.__catalog_model`) to manage the graph data, customize graph (`self.__graph_delegate`) and catalog delegate (`self.__catalog_delegate`) look to suit your application.
![Code Result](Graph Core_0.png)
```python
class MyGraphWidget(GraphEditorCoreWidget):
def __init__(self, **kwargs):
self.__graph_model = None
self.__graph_delegate = None
self.__catalog_model = None
self.__catalog_delegate = None
toolbar_items = []
super().__init__(
model=self.__graph_model,
delegate=self.__graph_delegate,
view_type=GraphView,
style=None,
catalog_model=self.__catalog_model,
catalog_delegate=self.__catalog_delegate,
toolbar_items=toolbar_items,
has_catalog=True,
**kwargs,
)
```
# Navigation
To navigate between different subgraphs, we use `set_current_compound` which changes the current view to show the subgraph of the input item.
# Add right click menu on canvas
To add a right click context menu on the graph canvas, we should call `on_right_mouse_button_pressed` to override the function in the base class.
Use `ui.Menu` to create the menu and `ui.MenuItem` to add menu items. `ui.Separator()` is useful to create a separator between categories of menus.
An example of `on_right_mouse_button_pressed` is as below:
```python
def on_right_mouse_button_pressed(self, items):
self.__context_menu = ui.Menu("Context menu")
with self.__context_menu:
ui.MenuItem("Delete Selection", triggered_fn=lambda: self._graph_model.delete_selection())
ui.Separator()
ui.MenuItem("Open All", triggered_fn=lambda: self._graph_view.set_expansion(GraphModel.ExpansionState.OPEN))
ui.MenuItem(
"Minimize All", triggered_fn=lambda: self._graph_view.set_expansion(GraphModel.ExpansionState.MINIMIZED)
)
```
# Add button to the ToolBar
To add a toolbar on the top of the graph, one way is to define the `toolbar_items` as the code above before calling GraphEditorCoreWidget’s constructor. `toolbar_items` is a list of dictionaries containing the button name, icon and `on_clicked` callback.
An example of `toolbar_items` is as below:
```python
toolbar_items = [
{"name": "open", "icon": "open.svg", "on_clicked": open, "tooltip": "Open a graph"},
{"name": "-"},
{"name": "save", "icon": "save.svg", "on_clicked": save},
{"name": "new", "icon": "new.svg", "on_clicked": new},
]
```
`{"name": "open", "icon": "open.svg", "on_clicked": open(), "tooltip": "Open a graph"}` create a button named open with the icon as “open.svg”. When you hover over the button, it will show the tooltip of “Open a graph”, and when you click on the button, it will call the callable `open` function. `{"name": "-"}` is to create a separator.
Another way to define the toolbar, is to call `set_toolbar_items` to override the function from `GraphEditorCoreWidget`. This is useful if you want to change the toolbar items when you have already created your
```
GraphEditorCoreWidget
```
. The input attribute is the same type as the above example.
--- | 4,554 |
Graph%20Delegate.md | # Graph Delegate
Graph delegate describes how the graph looks, including the nodes, ports, connections and the editor itself. We have three different delegates available at the moment: omni.kit.delegate.default, omni.kit.delegate.modern and omni.kit.delegate.neo.
The delegate looks are shown below:
**Modern delegate:**
**Default delegate:**
**Neo delegate:**
The modern delegate will be the new standard look for our tools going forward. But please feel free to modify or build your own from any of those examples.
The omni.kit.graph.editor.example provides the example of switching between different delegates from the top right dropdown list. Each delegate is an extension, you can create your customized delegate by forking one of them and starting from there.
## GraphNodeDelegateRouter
From the above images, we can tell that the backdrop node looks quite different from other nodes. Also when the expansion states of nodes are closed (Render Mesh nodes on the right), it also looks very different from when the nodes are open (FullNode on the left) or minimized (Noise Deformer in the middle). Therefore, we need more than one look for the nodes for just one style of delegate. We use `GraphNodeDelegateRouter` to manage that. It is the base class of graph node delegate. It keeps multiple delegates and picks them depending on the routing conditions, e.g. expansion state of Closed or Open, node type of backdrop or compound.
We use `add_route` to add routing conditions. And the conditions could be a type or a lambda expression. The latest added routing is stronger than previously added. Routing added without conditions is the default delegate. We can use type routing to make the specific kind of nodes unique, and also we can use the lambda function to make the particular state of nodes unique (ex. full/collapsed).
It’s possible to use type and lambda routing at the same time. Here are the usage examples:
```python
delegate.add_route(TextureDelegate(), type="Texture2d")
delegate.add_route(CollapsedDelegate(), expression=is_collapsed)
```
## Delegate API
Each delegate added to the router is derived from `AbstractGraphNodeDelegate`. The delegate generates widgets that together form the node using the model. The following figure shows the LIST layout of the node.
COLUMNS layout allows for putting input and output ports on the same line:
```
[A] node_header_input
[B] node_header_output
[C] port_input
[D] port_output
[E] node_footer_input (TODO)
[F] node_footer_output (TODO)
```
For every zone, there is a method that is called to build this zone. For example, `port_input` is the API to be called to create the left part of the port that will be used as input.
# Node Background
`node_background` is the API to be called to create widgets of the entire node background.
# Customized Delegate
If you find that `omni.kit.graph.delegate.modern` is the look you like, you want to use it, but there are some special things that don’t exist in the delegate, how can you tweak that to create a variant modern look?
We can create a new delegate which is derived from GraphNodeDelegate of omni.kit.graph.delegate.modern. Then you can override the `port_input`, `port_input` or `connection` to obtain a different look for a special type of port and connections. Or you can override the `node_background` or `node_header` to achieve a different style for nodes.
You can potentially override any functions from the delegate class to customize your own delegate. Mix and match delegates from different delegate extensions to create your own. Feel free to fork the code and explore your artistic side to create the delegate that fulfills your needs.
# Add right click action on Nodes/Ports
For example, if I want to use `omni.kit.graph.delegate.modern`, but I need to add a drop down menu to enable some actions when I right click on output ports, how can I do that?
Firstly, we are going to inherit the delegate from the modern extension. Then we can override the `port_output` method from the modern delegate. Create a new frame layer, draw the base class output port within the frame, and add `set_mouse_pressed_fn` callback on the frame to add a right click menu for the output port.
```python
from omni.kit.graph.delegate.modern.delegate import GraphNodeDelegate
from typing import Any
class MyDelegate(GraphNodeDelegate):
"""
The delegate for the input/output nodes of the compound.
"""
def __init__(self):
super().__init__()
def __on_menu(self, model, node: Any, port: Any):
# create menu
pass
def port_output(self, model, node_desc, port_desc):
node = node_desc.node
port = port_desc.port
frame = ui.Frame()
with frame:
super().port_output(model, node_desc, port_desc)
frame.set_mouse_pressed_fn(lambda x, y, b, _ , m=model, n=node, p=port: b == 1 and self.__on_menu(m, n, p))
```
# Curve Anchors
BezierCurves and Lines have the ability to display a curve anchor, or decoration, that is bound to a specific parametric value on the curve. The widgets that are drawn in the anchor are created in the `anchor_fn` on the FreeBezierCurve or Line. The current parametric (0-1) value where the anchor decoration will be attached is specified with `anchor_position`.
Because there is an interest in attaching some widgets to the curve and drawing them just on top of the curve (a dot, for example), but drawing other widgets, like a floating label decoration, on top of all nodes, the graph drawing is broken up so that connection components can draw into 2 different layers.
## Graph Drawing Layers
The graph is drawn using a ZStack which goes from back to front. It contains these layers:
- **__backdrops_stack** (For backdrops, because they are behind everything.)
- **__connections_under_stack** (All connection curves and anchors directly connected to curves - all above backdrops, but behind nodes. This layer is always used, regardless of the value of `draw_curve_top_layer`.)
- **__nodes_stack** (all nodes)
- **__connections_over_stack** (Meant for floating anchor decorations that should draw above all nodes. Curves drawn here should be transparent, so you don’t see two copies of them - you only see the floating anchor decoration. Only used when `draw_curve_top_layer` is True.)
A `connection()` method in the delegate is equipped with a `foreground` arg, like:
```python
def connection(self, model: GraphModel, source: GraphConnectionDescription, target: GraphConnectionDescription, foreground: bool = False)
```
Using the above drawing layer order as a guide, the design is that in the non-`foreground` mode, the connection curve is drawn normally, and any anchor widgets that should be directly on top of the curve should be drawn with the `anchor_fn` (see `draw_anchor_dot` in the code below). These elements will all show up behind nodes in the graph. In the `foreground` pass, the curve should be drawn transparently (using the style) and any floating widgets that should live in front of all nodes should be drawn with a different `anchor_fn` (see `draw_value_display` in the code below). It should be noted that the `foreground=True` pass of `connection()` doesn’t run at all unless the GraphView has its `draw_curve_top_layer` arg set to True (it’s False by default).
There are 2 things you may have to keep in sync, when using curve anchors in a graph:
1. If you have a FreeBezierCurve representation of a connection when zoomed in, but a FreeLine representation when zoomed out, you will have to make sure any changes to the `anchor_position` in one representation also carry over to the other.
2. If you have both a “dot” anchor widget that is on the curve, as well as a floating decoration, that should stay bound to where the dot is, you need to keep the `anchor_position` for both elements in sync.
Here is some example code from `build_connection` to help with implementing curve anchor decorations:
```python
ANCHOR_ALIGNMENT = ui.Alignment.CENTER
ANCHOR_POS = .25
decoration_label = None
def drag_anchor(curve, x: float, y: float, button, mod):
global ANCHOR_POS
global decoration_label
if curve:
t = curve.get_closest_parametric_position(x, y)
curve.anchor_position = ANCHOR_POS = t
if decoration_label:
decoration_label.text = f"Anchor {ANCHOR_POS:.2f}"
def remove_anchor(curve, x: float, y: float, button, mod):
async def wait_and_turn_off_anchor_frame():
await omni.kit.app.get_app().next_update_async()
curve.set_anchor_fn(None)
if button == 2:
asyncio.ensure_future(wait_and_turn_off_anchor_frame())
def draw_anchor_dot(curve=None):
global ANCHOR_POS
global decoration_label
if curve:
curve.anchor_position = ANCHOR_POS
with ui.VStack(style={"margin": 0}):
```
```python
with ui.VStack(content_clipping=1, style={"margin_height": 22}):
dot = ui.Circle(
# Make sure this alignment is the same as the anchor_alignment
# or this circle won't stick to the curve correctly.
alignment=ANCHOR_ALIGNMENT,
radius=6,
style={"background_color": cl.orange},
size_policy=ui.CircleSizePolicy.FIXED,
)
dot.set_mouse_pressed_fn(partial(remove_anchor, curve))
dot.set_mouse_moved_fn(partial(drag_anchor, curve))
def draw_value_display(curve=None):
global ANCHOR_POS
global decoration_label
if curve:
curve.anchor_position = ANCHOR_POS
with ui.VStack(style={"margin": 0}):
with ui.Placer(stable_size=0, draggable=True, offset_x=0, offset_y=-50):
with ui.ZStack(content_clipping=1):
rect = ui.Rectangle(style={
"background_color": 0xFF773322,
"border_color": cl.white,
"border_width": 2,
})
decoration_label = ui.Label(f"Anchor {ANCHOR_POS:.2f}",
style={"margin": 8, "color": cl.white})
if foreground:
style["color"] = cl.transparent
curve_container_widget = ui.ZStack()
with curve_container_widget:
freeline_widget = ui.FreeLine(
target.widget,
source.widget,
alignment=ui.Alignment.UNDEFINED,
style=style,
name=port_type,
anchor_position=ANCHOR_POS, # both line and curve will use the same value
anchor_alignment=ANCHOR_ALIGNMENT,
visible_max=PORT_VISIBLE_MIN,
style_type_name_override=override_style_name,
)
curve_widget = ui.FreeBezierCurve(
target.widget,
source.widget,
start_tangent_width=ui.Percent(-CONNECTION_CURVE * source_reversed_tangent),
end_tangent_width=ui.Percent(CONNECTION_CURVE * target_reversed_tangent),
name=port_type,
style=style,
anchor_position=ANCHOR_POS,
anchor_alignment=ANCHOR_ALIGNMENT,
visible_min=PORT_VISIBLE_MIN,
style_type_name_override=override_style_name,
)
# Doing this outside the curve creation to be able to pass the curve_widget in as an arg.
if foreground:
freeline_widget.set_anchor_fn(partial(draw_value_display, freeline_widget))
```
```python
if True:
curve_widget.set_anchor_fn(partial(draw_value_display, curve_widget))
else:
freeline_widget.set_anchor_fn(partial(draw_anchor_dot, freeline_widget))
curve_widget.set_anchor_fn(partial(draw_anchor_dot, curve_widget))
freeline_widget.set_tooltip_fn(tooltip)
curve_widget.set_tooltip_fn(tooltip)
return curve_container_widget, freeline_widget, curve_widget
```
This is what that might look like visually: | 11,733 |
Graph%20Model.md | # Graph Model
The graph model is the central component of the graph widget. It is the application’s dynamic data structure, independent of the user interface. It directly manages the data and closely follows the model-view pattern. It defines the interface to be able to interoperate with the components of the model-view architecture.
## GraphModel
GraphModel is the base class for graph model which provides the standard API. It is not supposed to be instantiated directly. Instead, the user subclasses it to create a new model.
The model manages two kinds of data elements. Nodes and Ports are the atomic data elements of the model.
There is no specific Python type for the elements of the model. Since Python has dynamic types, the model can return any object as a node or a port. When the widget needs to get a property of the node, it provides the given node back to the model, e.g.
```python
model[port].name
```
in the delegate to query a port’s name.
Here is a simple model, defining the nodes and ports which are the key elements for a graph, as well as the properties for the element: connections, name and type:
```python
# define the graph root
graph_root = GraphNode("MyGraph")
# define two nodes with different types under the graph root
nodeA = EventNode("Event", graph_root)
graph_root.add_child(nodeA)
nodeB = AnimationNode("Animation", graph_root)
graph_root.add_child(nodeB)
class MyModel(GraphModel):
"""
A simple model derived from GraphModel
"""
@property
def nodes(self, item=None):
# when the node is None, we return the graph level node
if item is None:
return graph_root
# when the input item root, we return all the nodes exist on the current graph
# the return type is a Node list, so the graph nodes are Node type in MyModel
if item == graph_root:
return [child for child in graph_root.children()]
return []
@property
def ports(self, item=None):
# if input is a Node type we return the ports
if isinstance(item, Node):
return item.in_ports + item.out_ports
# if input is a Port type we return the subports of the input port
elif isinstance(item, Port):
return item.children
return []
@property
def name(self, item=None):
# name of the item, item here could either be Node or Port
```
```python
return item.name
@property
def type(self, item):
"""type of the item, the item here could be Node or Port"""
return item.type
@property
def inputs(self, item):
# Node type doesn't have connection
if isinstance(item, Node):
return None
# return all the input port's inputs
if item.is_input:
return item.inputs
return None
@property
def outputs(self, item):
# Node type doesn't have connection
if isinstance(item, Node):
return None
# return all the output port's outputs
if not item.is_input:
return item.outputs
return None
@inputs.setter
def inputs(self, value, item):
# disconnection
if len(value) == 0:
if isinstance(item, Port):
if len(item.inputs) > 0:
item.inputs.clear()
elif len(item.outputs) > 0:
item.outputs.clear()
else:
# when the item is not a Port, but a CompoundNode, it means that we are connecting a port to the Output node of
# a compoundNode. In this case, we need to create a new output port for the node
source = value[0]
if isinstance(item, CompoundNode):
ports = [port.name for port in item.out_ports]
new_port_name = self.get_next_free_name(item, ports, source.name)
new_port = Port(new_port_name, source.type, item)
item.out_ports.append(new_port)
# We are connecting to the new Port
new_port.outputs.append(source)
new_port.node = item
# if the source is a CompoundNode, then we are connection a port to the Input node of a CompoundNode.
# we need to create a new input port
elif isinstance(source, CompoundNode):
ports = [port.name for port in source.in_ports]
new_port_name = self.get_next_free_name(source, ports, item.name)
new_port = Port(new_port_name, item.type, source)
source.in_ports.append(new_port)
# add connection
item.inputs.append(new_port)
new_port.node = source
else:
# do the connection
if item.is_input:
item.inputs.append(source)
else:
item.outputs.append(source)
self._item_changed(None)
# Accessing nodes and properties example
model = MyModel()
```
# query the graph
# The graph/node/port is accessed through evaluation of model[key]. It will
# return the proxy object that redirects its properties back to
# model. So the following line will call MyModel.nodes(None).
graph = model[None].nodes
nodes = model[graph].nodes
for node in nodes:
node_name = model[node].name
node_type = model[node].type
print(f"The model has node {node_name} with type {node_type}")
ports = model[node].ports
for port in ports:
# this will call MyModel.name(port)
port_name = model[port].name
port_type = model[port].type
print(f"The node {node_name} has port {port_name} with type {port_type}")
# prepare data for connection
if port_name == "output:time":
source_port = port
elif port_name == "input:time":
target_port = port
subports = model[port].ports
if subports:
for subport in subports:
subport_name = model[subport].name
subport_type = model[subport].type
print(f"The port {port_name} has subport {subport_name} with type {subport_type}")
# do the connection
if source_port and target_port:
model[target_port].inputs = [source_port]
print(f"There is a connection between {target_port.path} and {source_port.path}")
Here is the result by running the above script in the script editor:
The model has node Event with type Event
The node Event has port input:Default Input with type str
The node Event has port input:Group Input with type group
The port input:Group Input has subport input:child1 with type int
The port input:Group Input has subport input:child2 with type int
The node Event has port output:time with type float
The model has node Animation with type Animation
The node Animation has port input:asset with type asset
The node Animation has port input:time with type float
The node Animation has port output:num_frames with type int
The node Animation has port output:num_skeletons with type int
The node Animation has port output:is_live with type bool
There is a connection between MyGraph:Animation:time and MyGraph:Event:time
Here is a visual representation of the graph in the above example.
Define node and port
===================
The above example is using Node and Port type from
\`\`\`
omni.kit.graph.editor.example.nodes
\`\`\`
. You can of course define your own type of node and port. For example, you can use Usd.Prim as the node type and Usd.Attribute as the port type (e.g. the node and port in
\`\`\`
omni.kit.window.material_graph
\`\`\`
) or you can use Sdf.Path for both node and port types.
The return type from the API of
\`\`\`
def nodes
\`\`\`
defines the node type and
\`\`\`
def ports
\`\`\`
defines the port type. You can map your own class of nodes and ports to graph’s node and port type. A graph can have any number of nodes and a node can have any number of ports. The port can have any number of subports, and further on, subports can have subsubports and so on.
For the above example,
\`\`\`
def nodes
\`\`\`
will return
\`\`\`
MyGraph
\`\`\`
GraphNode when input item is
\`\`\`
None
\`\`\`
, and when the input item is
\`\`\`
MyGraph
\`\`\`
, it will return a list containing
\`\`\`
Event
\`\`\`
and
\`\`\`
Animation
\`\`\`
Nodes.
\`\`\`
def ports
\`\`\`
will return a list containing
\`\`\`
Default Input
\`\`\`
and
\`\`\`
Group Input
\`\`\`
when input item is an
\`\`\`
Event
\`\`\`
node and return a list containing
\`\`\`
child1
\`\`\`
and
\`\`\`
child2
\`\`\`
when input item is
\`\`\`
Group Input
\`\`\`
.
Define connections
===================
The property of inputs and outputs define the connections for graphs. At the moment most of our graphs only support connections between one input and one output. The one side connection (two inputs or two outputs) is also available with more details in the future docs. Let’s take the common case of one input and one output connection as an example: connect Event node’s output time port (source port) with Animation’s input time port (destination port).
When we execute the connection using code (
\`\`\`
model[target_port].inputs = [source_port]
\`\`\`
) or edit the graph to click and drag the source port to connect to the target port,
\`\`\`
inputs.setter
\`\`\`
is called with the input item as the Animation’s input time port and value as a list containing Event node’s output time port in this case. The same happens when we right click to disconnect the connection. During the disconnection, the input value will be empty list
\`\`\`
[]
\`\`\`
During connection, the first thing we do is to check whether it is a disconnection or connection. Then we execute necessary data changes to cache this connection/disconnection.
How does the delegate know that we should have a connection at a port? The answer is the return value from
\`\`\`
inputs
\`\`\`
and
\`\`\`
outputs
\`\`\`
.
# Graph Connections
The `inputs` property returns the input source port for the item port and `outputs` returns the target port for the item port. Take the above connection as an example. Looking at the `MyGraph:Animation:time` port as the input item, `inputs` returns a list containing the Event node’s output time port. And there are no outputs for Animation’s time port, so `outputs` will return None for Animation’s time port. That’s enough to describe a connection between two ports. One might want to define `outputs` for `MyGraph:Event:time` as [MyGraph:Animation:time] and None for `inputs`. Keep your graph upstream or downstream through the whole graph to be consistent.
So if we are using upstream connections, we will see most of the time `outputs` will return None. There are exceptions for the subgraph.
# Subgraph and IsolationGraphModel
To create a subgraph node, just drag and drop a subgraph node into the graph (named Scene Graph in the example). When you double click the subgraph node, you enter the subgraph graph editor, you will see that the navigation bar on the top left has updated to your current graph location. More details about navigation in the Graph Core session.
When you want to expose some attributes from the subgraph and connect to nodes outside of the subgraph, firstly, you need to expose the attributes to the subgraph node. You can create Input nodes to expose inputs and Output nodes to expose outputs. The creation of Input and Output nodes is dealt with by IsolationGraphModel. You can create Inputs/Outputs using `add_input_or_output`.
Once Input/Output nodes are created, you can connect the port you want to expose to the EmptyPort of the Input/Output node. During that, `inputs.setter` is called as a normal connection. The only difference is when you connect to EmptyPort, the port doesn’t exist on the subgraph node, so we need to create the port first then do the connection. That’s the code path of `isinstance(item, CompoundNode)` and `isinstance(source, CompoundNode)` in `inputs.setter`.
Once the attributes are exposed (Default input and child1 from Event as inputs, is_live from Animation as output), you can go back to the MyGraph level by clicking `MyGraph` on the navigation bar. You will see that three ports are created on the Compound node, and then finally, we can connect the exposed port to other nodes, e.g. Debug.is_debug in the above image.
The connection between Animation’s is_live and Compound’s is_live is reflected as the `outputs` return value for Animation’s is_live, since we have no idea about Compound’s is_live attribute until that’s created by the connection.
# GraphModel with batch position
We created a `GraphModelBatchPositionHelper` class to manage batch position processing. For example, moving a backdrop node, multi-selecting a few nodes and moving them together, or moving the current node’s upstream nodes all together, where we need to deal with a collection of positions at the same time.
That’s the reason our SimpleGraphModel from the example extension is inherited both from the GraphModel and GraphModelBatchPositionHelper. GraphModel defines the basic graph data structure and GraphModelBatchPositionHelper allows us to deal with batch position processing much more easily.
## Backdrop
A Backdrop is used to group nodes together to make the graph more organized. Different from subgraphs, it lives on the same level of the nodes placed in the given backdrop. A Backdrop just gives a visual UI group to the nodes. When we move the backdrop, the nodes which are placed in the given backdrop will move together. We leverage GraphModelBatchPositionHelper to do that.
BackdropGetter is defined in `omni.kit.widget.graph` as a helper to get the nodes that are placed in the given backdrop. `BackdropGetter(self, lambda item: self[item].type == "Backdrop")` defines the drive item to be the one has the type of “Backdrop” and returns all the nodes which are placed in the drive item.
We add the function to GraphModelBatchPositionHelper using `self.add_get_moving_items_fn(BackdropGetter(...))` for `batch_position_begin_edit` later to determine which items to move. And `batch_position_end_edit` is used to end the position editing.
## Multi-selection move
This is similar to Backdrop, but the group scheme is using multi-selection instead of Backdrop.
## SelectionGetter
provides a `SelectionGetter` to get all the selected nodes of the given model, corresponding to BackdropGetter.
## Moving Upstream Nodes Together
We provide an example in the `omni.kit.graph.editor.example` such that when you press D and move a node, all the upstreams of the current nodes will move together. This could be useful for organizing your graph faster. It is similar to backdrops and multi-selection, but we need to create a customized `DescendantGetter` ourselves by deriving it from `AbstractBatchPositionGetter`. Again it just returns back all the upstream nodes for the drive node. It acts the same as Backdrop or multi-selection by calling `batch_position_begin_edit` and `batch_position_end_edit`. | 14,806 |
GraphConcepts.md | # Graph Concepts
This article covers core graph concepts found in EF. Readers are encouraged to review the [Execution Framework Overview](#ef-framework) before diving into this article.
![Figure 7: The Execution Framework pipeline. This article covers concepts found in the Execution Graph (IR).](#id1)
The core data structure Execution Framework (EF) uses to describe execution is a *graph of graphs*. Each *graph* contains a [root node](#ef-root-node). The root node can connect to zero or many downstream [nodes](#ef-nodes) via directed [edges](#ef-edges).
Nodes represent work to be executed. Edges represent ordering dependencies between nodes.
![Figure 8: A simple graph.](#ef-fig-simple)
The work each node represents is encapsulated in a [definition](#ef-definition). Each node in the graph may have a pointer to a definition. There are two categories of definitions: [opaque](#ef-opaque-definition) and [graph](#ef-graph-definition).
An *opaque definition* is a work implementation hidden from the framework. An example would be a function pointer.
The second type of definition is another *graph*. Allowing a node’s work definition to be yet another graph is why we say EF’s core execution data structure is a *graph of graphs*.
The top-level container of the *graph of graphs* is called the [execution graph](#ef-execution-graph). The graphs to which individual nodes point are called [graph definitions](#ef-graph-definition) or simply [graphs](#ef-graph-definition).
The following sections dive into each of the topics above with the goal of providing the reader with a general understanding of each of the core concepts in EF’s *graph of graphs*.
## Nodes
Nodes in a [graph](#ef-graph-definition) represent work to be executed. The actual work to be performed is stored in a [definition](#ef-definition), to which a node points.
Nodes can have both parent and child nodes. This relationship between parent and child defines an ordering dependency.
The interface for interacting with nodes is `INode`. EF contains the `NodeT`.
## Nodes
Node implementation of INode for instantiation when constructing graph definitions.
Each node is logically contained within a single graph definition (i.e. INodeGraphDef).
## Edges
Edges represent ordering between nodes in a graph definition. Edges are represented in EF with simple raw pointers between nodes. These pointers can be accessed with INode::getParents() to list nodes that are before a node, and INode::getChildren() to list nodes that are after the node.
## Definitions
Definitions define the work each node represents.
Definitions can be opaque, meaning EF has no visibility into the actual work being performed. Opaque definitions implement the INodeDef interface. Helper classes, like NodeDefLambda exists to easily wrap chunks of code into an opaque definition.
Definitions can also be defined with a graph, making the definitions transparent. The transparency of graph definitions enables EF to perform many optimizations such as:
- Execute nodes in the graph in parallel
- Optimize the graph for the current hardware environment
- Reorder/Defer execution of nodes to minimize lock contention
Many of these optimizations are enabled by writing custom passes and executors. See Pass Creation and Executor Creation for details.
Graph definitions are defined by the INodeGraphDef interface. During graph construction, it is common for IPass authors to instantiate custom graph definitions to bridge EF with the authoring layer. The NodeGraphDef class is designed to help implement these custom definitions.
Definition instances are not unique to each node. Definitions are designed to be shared between multiple nodes. This means two different INode instances are free to point to the same definition instance. This not only saves space, it also decreases graph construction time.
Above we see the graph from Figure 8, but now with pointers to definitions (dashed lines). Notice how definitions are shared between nodes. Furthermore, notice that nodes in graph definitions can point to other graph definitions.
Both INodeDef and NodeGraphDef classes are designed to help implement these custom definitions.
## Definitions
`INodeDef` (i.e. opaque definitions) and `INodeGraphDef` (i.e. graph definitions) inherit from the `IDef` interface. All user definitions must implement either `INodeDef` or `INodeGraphDef`.
Definitions are attached to nodes and can be accessed with `INode::getDef()`. Note, a node is not required to have a definition. In fact, each graph’s root node will not have an attached definition.
## Execution Graph
The top-level container for execution is the *execution graph*. The execution graph is special. It is the only entity, other than a node, that can contain a definition. In particular, the execution graph always contains a single graph definition. It is this graph definition that is the actual *graph of graphs*. The execution graph does not contain nodes, rather, it is the execution graph’s definition that contains nodes.
In addition to containing the top-level graph definition, the execution graph’s other jobs are to track:
- If the graph is currently being constructed
- Gross changes to the topologies in the execution graph. See invalidation for details.
The execution graph is defined by the `IGraph` interface. EF contains the `Graph` implementation of `IGraph` for applications to instantiate.
## Topology
Each graph definition owns a *topology* object. Each topology object is owned by a single graph definition.
The topology object has several tasks:
- Owns and provides access to the root node
- Assigns each node in the graph definition an unique index
- Handles and tracks invalidation of the topology (via stamps)
Topology is defined by the `ITopology` interface and accessed via `INodeGraphDef::getTopology()`.
## Root Nodes
Each graph definition contains a topology which owns a *root node*. The root node is where traversal in a graph definition starts. Only descendants of the root node will be traversed.
The root node is accessed with `INodeGraphDef::getTopology()`.
# 图概念概述
`ITopology::getRoot()` 的使用在图定义的构建过程中经常被观察到。
根节点在图定义中是特殊的,因为它们没有附带的定义,尽管图定义的执行器可能会赋予根节点特殊的含义。
根节点通过 `INode` 接口定义,就像任何其他节点一样。
每个图定义(实际上是图定义的拓扑)都有一个根节点。这意味着在EF中存在许多根节点(即EF是一个图的图)。
# 下一步
本文提供了图概念的概述。要了解这些概念如何在图构建过程中被利用,请继续阅读关于 [Pass Concepts](#ef-pass-concepts) 的文章。 | 6,403 |
GraphEditors.md | # Visual Graph Editors
After creating an OmniGraph through scripting or Create -> Visual Scripting you can open up an editor in which you can view and edit the graph through the Window -> Visual Scripting.
The difference between the editors offered is that each is tailored to a graph with a specific type of evaluation; one for an Action Graph and the Generic Graph which applies to either a Push Graph or a Lazy Graph. The basic authoring operations in either one are very similar.
After opening the graph editor you will be offered the choice of editing an existing graph or creating a new one.
After selecting or creating a new graph you can edit it in a variety of ways. The basic view of a graph with nodes will look something like this:
See the online documentation for more details on how you can further interact with the graph editor. | 849 |
GraphInvalidation.md | # Graph Invalidation
This is an advanced Execution Framework topic. It is recommended you first review the
Execution Framework Overview along with basic topics such as Graphs Concepts, Pass Concepts, and Execution Concepts.
EF employs a fast, efficient, and lazy invalidation scheme to detect changes in the execution graph. In this article, we cover how a graph is invalidated, how it is marked valid, and the various entities used for invalidation.
## Stamps
The heart of the invalidation system are EF’s stamps.
Stamps track the state/version of a resource. Stamps are implemented as an unsigned number. If the state of a resource changes, the stamp is incremented.
Stamps are broken into two parts.
The first part is implemented by the `Stamp` class. As a resource changes, `Stamp::next()` is called to denote the new state of the resource. `Stamp` objects are owned by the resource they track.
The second part of stamps is implemented by the `SyncStamp` class. `SyncStamp` tracks/synchronizes to the state of a `Stamp`. `SyncStamp` objects are owned by the entities that wish to utilize the mutating resource.
See `Stamp`’s documentation for further details.
EF makes extensive use of stamps to detect changes in pass registration, graph topology, and graph construction.
## Invalidating a Graph
## Graph invalidation starts with a call to
`ITopology::invalidate()`
.
`ITopology`
objects are owned by
graph definitions
. Therefore, a call to
`ITopology::invalidate()`
is equivalent to saying “this
definition
is no longer valid.”
Unlike some other invalidation schemes, the call to
`ITopology::invalidate()`
is cheap. If the
topology
is already invalid (i.e.
`ITopology::invalidate()`
has previously been called and the
topology
has not yet be rebuilt), invalidation exits early. Otherwise, the topology’s
stamps
is incremented and the invalidation is “forwarded” to a list of registered listeners.
This forwarding process may sound expensive. In practice, it is not for the following reasons:
- As previously mentioned,
`ITopology::invalidate()`
detects spurious invalidations and performs an early exit.
- Invalidation forwarders do not immediately react to the invalidation (i.e. they do not immediately rebuild the
graph
). Rather, they are designed to note the invalidation and handle it later. For example, rebuilding a graph definition is delayed until the start of the next execution of the
execution graph
.
- Usually only a single listener is registered per-
graph definition
. That listener does not forward the invalidation.
The single invalidation forwarder mentioned above notifies the top-level execution graph (e.g.
`IGraph`
) that something within the graph has become invalid. It does this by incrementing the execution graph’s
global topology stamp
via
`IGraph::getGlobalTopologyStamp()`
.
## Global Topology Stamp
The top-level
`IGraph`
object’s global topology
stamps
tracks the validity of all
topologies
within all
graph definitions
in the
execution graph
. The
stamps
is incremented each time a graph definition’s topology is invalidated.
Use of this stamp usually falls into two categories.
The first category is cache invalidation. As an example,
`IExecutionContext`
uses the global topology stamp to determine if its cached list of traversed node paths is still valid.
The second category is detecting if the execution graph should be rebuilt.
`IPassPipeline`
uses the global topology
stamp to determine if the
pipeline’s passes should run. These passes traverse the entire execution graph, looking for graph definition’s whose topology is invalid.
This rebuild process is not a full rebuild of the execution graph. Rather, because invalidation is tracked at the graph definition level, only those definitions that have been invalidated need to be rebuilt.
Graph construction is covered in detail in Pass Concepts.
## Making a Graph Valid
The ITopology object stored in each graph definition (e.g. INodeGraphDef) has the concept of validity. The topology is marked invalid with ITopology::invalidate(). ITopology::invalidate() is often called by the authoring layer. For example, OmniGraph will call ITopology::invalidate() when a user connects two nodes.
The validity of a topology can be checked with ITopology::isValid(). ITopology::isValid() is often used during graph construction to determine if a graph definition needs to be rebuilt.
One of the ITopology object’s jobs is to store and provide access to the root node of the definition. ITopology::isValid() works by checking if the root node’s SyncStamp is synchronized with the topology’s Stamp.
Once ITopology::invalidate() is called, the topology’s root node stamp will be out-of-sync until INode::validateOrResetTopology() is called on the root node. INode::validateOrResetTopology() is called during graph construction, usually by IGraphBuilder::connect.
```cpp
IGraphBuilder::connect(INode*,
INode*)
```
when the root node is connected to a downstream node. In some cases, nothing connects to the root node and it is up to the IPass (usually via the constructed graph definition) to call INode::validateOrResetTopology() on the root node.
Graph construction is covered in detail in Pass Concepts. | 5,274 |
GraphTraversalAdvanced.md | # Graph Traversal In-Depth
This is an advanced Execution Framework topic. It is recommended you first review the [Execution Framework Overview](Overview.html#ef-framework) along with basic topics such as [Graphs Concepts](GraphConcepts.html#ef-graph-concepts), [Pass Concepts](PassConcepts.html#ef-pass-concepts), and [Execution Concepts](ExecutionConcepts.html#ef-execution-concepts).
As was mentioned in the [Graph Traversal Guide](GraphTraversalGuide.html#ef-graph-traversal-guide), **graph traversal** is an essential component of EF. It brings dynamism to an otherwise-static representation of a runtime environment, allowing for fine-tuned decision-making when it comes to how the IR is constructed, populated, transformed, and eventually evaluated. Although traversals can occur at any point in time, typically (and perhaps most importantly) they are employed during graph construction (see [Pass Concepts](PassConcepts.html#ef-pass-concepts)) and execution (see [Execution Concepts](ExecutionConcepts.html#ef-execution-concepts)).
In order to form a practical and functional understanding of how graph traversal works, especially in regards to its applications in EF, this document will build upon the example traversals highlighted in the [Graph Traversal Guide](GraphTraversalGuide.html#ef-graph-traversal-guide) by introducing various key definitions and methodologies underpinning the subject as a whole and tying the learnings together to explore their most significant utilizations in EF.
> For the purposes of this discussion, we will only deal with connected, cyclic, directed, simple graphs permitting loops – since those are the IR’s characteristics – and whenever the term graph is used generally one can assume that the aforementioned qualifiers apply, unless explicitly stated otherwise.
## Core Search Algorithms
Although there exist myriad different approaches to graph traversal, this section will focus on the so-called **depth-first search (DFS)** and **breadth-first search (BFS)** techniques, which tend to be the most popular thanks to their versatility and relative simplicity.
As can be seen in [Getting Started with Writing Graph Traversals](GraphTraversalGuide.html#getting-started-with-writing-graph-traversals) and [Serial vs. Parallel Graph Traversal](#graph-traversal-apis), EF fully implements and exposes these algorithms on the API level to external developers so that the root logic doesn’t have to be rewritten on a per-user basis. These methods also come wrapped with [other important functionality related to visit strategies](#visitation-strategies) that will be explained later; for this reason, we relegate highlighting the API methods themselves for [a later section](#graph-traversal-apis), after [Visitation Strategies](#visitation-strategies).
are covered. For the time being, we’ll instead delve into a more conceptual, non-EF-specific overview of these algorithms.
To facilitate this higher-level conversation, here we introduce the following connected, directed, acyclic graph \(G_2\):
Note
====
1. The individual edge members are ordered from tail to head, e.g. \(\{a, b\}\) is directed from the upstream node \(a\) to the downstream node \(b\).
2. For clarity’s sake, edges are ordered based on the node letterings’ place in the alphabet (similar to \(G_1\)), e.g. \(\{a, b\}\) and \(\{a, c\}\) are the first and second edges protruding off of node \(a\). This in turn implies that nodes \(b\) and \(c\) are the first and second children of \(a\), respectively. These orders are also numbered explicitly on the figure itself.
Depth-First Search (DFS)
========================
Starting at a given node, DFS will recursively visit all of the node’s children. This effectively leads to DFS exploring as far as possible downstream along a connected branch, marking nodes along the way as having been visited, until it hits a dead end (usually defined as either reaching a node with no children or a node that has already been visited), before backtracking to a previous node that still has open avenues for exploration. The search continues until all nodes in the graph have been visited.
As an example, suppose that we were to start a DFS at node \(a \in G_2\) and chose to enter nodes along the first available edge (an important distinction to make, which is more fully addressed in Visitation Strategies). For simplicity’s sake, let us further assume that we perform the search in a serial fashion. Play through the following interactive animation to see what the resultant traversal and ordered set of visited nodes/edges (which, when combined, form a depth-first search tree, highlighted in blue at the end) would look like:
Note
====
Spread throughout this document are a series of interactive animations that show different traversals over various graphs in a step-by-step fashion. Some key points to consider:
1. To move forward one step, press the `>` button. To move back one step, press the `<` button.
2. To fast-forward to the final, fully-traversed graph, press the `>>` button. To go back to the start, press the `<<` button.
3. The nodes/edges that have not been visited are colored in black.
4. The nodes/edges that are currently being attempted to be visited are colored in yellow.
5. The nodes/edges that have been successfully visited are colored in blue.
6. The nodes that fail to be visited along a specific edge will glow red momentarily before returning to their initial color, while the corresponding edge will remain red (highlighting that we were not able to enter said node along that now-red edge).
1
2
1
2
1
3
1
2
1
2
a
b
c
d
e
f
g
h
i
𝐺
2
<!--Buttons-->
<g onclick=" onClickGoToStart1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M508 800C508 795.582 511.582 792 516 792L548 792C552.418 792 556 795.582 556 800L556 832C556 836.418 552.418 840 548 840L516 840C511.582 840 508 836.418 508 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(316.183 821)">
<<
<g onclick=" onClickBackward1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M580 800C580 795.582 583.582 792 588 792L620 792C624.418 792 628 795.582 628 800L628 832C628 836.418 624.418 840 620 840L588 840C583.582 840 580 836.418 580 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(393.017 821)">
<
<g onclick=" onClickForward1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M652 800C652 795.582 655.582 792 660 792L692 792C696.418 792 700 795.582 700 800L700 832C700 836.418 696.418 840 692 840L660 840C655.582 840 652 836.418 652 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(465.017 821)">
>
<g onclick=" onClickGoToEnd1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M724 800C724 795.582 727.582 792 732 792L764 792C768.418 792 772 795.582 772 800L772 832C772 836.418 768.418 840 764 840L732 840C727.582 840 724 836.418 724 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(532.183 821)">
>>
<style id="dynamicStyles1">
/*Center the SVG*/
#efGraphTraversalAnim01 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
<script type="text/javascript">
//<![CDATA[
let dynamicStyle1 = document.getElementById("dynamicStyles1");
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent1(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges1:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges1:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges1:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes1.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitSuccess:nth-child(${nodeIdx})>path {
animation: node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes1.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim01 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
}
```javascript
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
```
```javascript
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering1 = [
[["a1", "node", "try"]],
[["a1", "node", "success"]],
[["ab1", "edge", "try"], ["b1", "node", "try"]],
[["ab1", "edge", "success"], ["b1", "node", "success"]],
[["bd1", "edge", "try"], ["d1", "node", "try"]],
[["bd1", "edge", "success"], ["d1", "node", "success"]],
[["df1", "edge", "try"], ["f1", "node", "try"]],
[["df1", "edge", "success"], ["f1", "node", "success"]],
[["fi1", "edge", "try"], ["i1", "node", "try"]],
[["fi1", "edge", "success"], ["i1", "node", "success"]],
[["dg1", "edge", "try"], ["g1", "node", "try"]],
[["dg1", "edge", "success"], ["g1", "node", "success"]],
[["dh1", "edge", "try"], ["h1", "node", "try"]],
[["dh1", "edge", "success"], ["h1", "node", "success"]],
[["ac1", "edge", "try"], ["c1", "node", "try"]],
[["ac1", "edge", "success"], ["c1", "node", "success"]],
[["cd1", "edge", "try"], ["d1", "node", "try"]],
[["cd1", "edge", "failure"], ["d1", "node", "failure"]],
[["ce1", "edge", "try"], ["e1", "node", "try"]],
[["ce1", "edge", "success"], ["e1", "node", "success"]],
[["eh1", "edge", "try"], ["h1", "node", "try"]],
[["eh1", "edge", "failure"], ["h1", "node", "failure"]],
[["ei1", "edge", "try"], ["i1", "node", "try"]],
[["ei1", "edge", "failure"], ["i1", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors1 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor1 = "#FFFFFF";
const buttonHoverColor1 = "#BFBFBF";
const buttonDownColor1 = "#7F7F7F";
let cnt1 = -1;
function onClickGoToStart1(buttonElement) {
// Reset counter to start.
cnt1 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges1");
for (const edge of edges.children) {
edge.classList.value = "edges1";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes1");
for (const node of nodes.children) {
node.classList.value = "nodes1";
const path = node.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward1(buttonElement) {
if (cnt1 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering1[cnt1];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges1" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges1" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges1");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(0, edgeIdx, nodeAndEdgeColors1, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
}
}
}
```
```javascript
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes1" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes1" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes1");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(nodeIdx, prevEdgeIdx, nodeAndEdgeColors1, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// "try" was the first-ever for the given node (i.e. checking the
// node's fill color).
if (status == "try") {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
```
```javascript
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
}
}
cnt1 -= 1;
}
function onClickForward1(buttonElement) {
if (cnt1 >= nodesAndEdgesOrdering1.length - 1) {
return;
}
cnt1 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering1[cnt1];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges1" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges1" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges1");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(0, edgeIdx, nodeAndEdgeColors1, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
} else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
edge.classList.value = "edges1";
}, { once: true });
} else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
} else if (type == "node") {
// Get the "nodes1" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes1" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes1");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(nodeIdx, prevEdgeIdx, nodeAndEdgeColors1, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
// Set the node animation based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
} else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
} else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
}
}
}
```
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
}
}
function onClickGoToEnd1(buttonElement) {
// Set counter to end.
cnt1 = nodesAndEdgesOrdering1.length - 1;
for (let i = 0; i < nodesAndEdgesOrdering1.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering1[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
if (status == "try") {
continue;
}
// Set all elements to their final colors.
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
}, { once: true });
}
}
}
function onMouseDown1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor1);
}
function onMouseUp1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
```javascript
buttonPathElement.setAttribute("fill", buttonHoverColor1);
}
function onMouseOver1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor1);
}
function onMouseLeave1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor1);
}
//]]>
```
Make sure to read
- Print all Node Names
- Print all Node Traversal Paths Recursively
- Print all Node Names Recursively in Topological Order
- Using Custom NodeUserData
- Store and Print all Node Names Concurrently
for traversal samples that utilize
- DFS.
## Breadth-First Search (BFS)
Starting at a given node, BFS will first visit all children of the current node before exploring any other nodes that lie further downstream. Like DFS, this process will continue until all nodes in the graph have been discovered.
As an example, suppose that we were to start a BFS at node \(a \in G_2\) and chose to enter nodes along the first available edge (similar to the DFS example above). As in the previous example, we’ll be assuming a serial traversal. The resultant exploration and ordered set of visited nodes/edges (which, when combined, form a breadth-first search tree, highlighted in blue at the end) would look like this:
𝐺
2
a
b
c
d
e
f
g
h
i
<<
<
>
>>
```javascript
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent2(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges2:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges2:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges2:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes2.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitSuccess:nth-child(${nodeIdx})>path {
animation: node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes2.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim02 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
`;
}
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering2 = [
[["a2", "node", "try"]],
[["a2", "node", "success"]],
[["ab2", "edge", "try"], ["b2", "node", "try"]],
[["ab2", "edge", "success"], ["b2", "node", "success"]],
[["ac2", "edge", "try"], ["c2", "node", "try"]],
[["ac2", "edge", "success"], ["c2", "node", "success"]],
[["bd2", "edge", "try"], ["d2", "node", "try"]],
[["bd2", "edge", "success"], ["d2", "node", "success"]],
[["cd2", "edge", "try"], ["d2", "node", "try"]],
[["cd2", "edge", "failure"], ["d2", "node", "failure"]],
[["ce2", "edge", "try"], ["e2", "node", "try"]],
[["ce2", "edge", "success"], ["e2", "node", "success"]],
[["df2", "edge", "try"], ["f2", "node", "try"]],
[["df2", "edge", "success"], ["f2", "node", "success"]],
[["dg2", "edge", "try"], ["g2", "node", "try"]],
[["dg2", "edge", "success"], ["g2", "node", "success"]],
[["dh2", "edge", "try"], ["h2", "node", "try"]],
[["dh2", "edge", "success"], ["h2", "node", "success"]],
[["eh2", "edge", "try"], ["h2", "node", "try"]],
[["eh2", "edge", "failure"], ["h2", "node", "failure"]],
[["ei2", "edge", "try"], ["i2", "node", "try"]],
[["ei2", "edge", "success"], ["i2", "node", "success"]],
[["fi2", "edge", "try"], ["i2", "node", "try"]],
[["fi2", "edge", "failure"], ["i2", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors2 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor2 = "#FFFFFF";
const buttonHoverColor2 = "#BFBFBF";
const buttonDownColor2 = "#7F7F7F";
let cnt2 = -1;
function onClickGoToStart2(buttonElement) {
// Reset counter to start.
cnt2 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges2");
for (const edge of edges.children) {
edge.classList.value = "edges2";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
}, { once: true });
}
}
```
```javascript
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes2");
for (const node of nodes.children) {
node.classList.value = "nodes2";
const path = node.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}, { once: true });
}
function onClickBackward2(buttonElement) {
if (cnt2 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering2[cnt2];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges2" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges2" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges2");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(0, edgeIdx, nodeAndEdgeColors2, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes2" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes2" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes2");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(nodeIdx, prevEdgeIdx, nodeAndEdgeColors2, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// "try" was the first-ever for the given node (i.e. checking the
// node's fill color).
if (status == "try") {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
}
}
}
}
```
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
}
cnt2 -= 1;
function onClickForward2() {
if (cnt2 >= nodesAndEdgesOrdering2.length - 1) {
return;
}
cnt2 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering2[cnt2];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges2" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges2" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges2");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(0, edgeIdx, nodeAndEdgeColors2, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
}
}
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes2" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes2" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes2");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(nodeIdx, prevEdgeIdx, nodeAndEdgeColors2, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
// Set the node animation based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
```javascript
function onClickGoToEnd2(buttonElement) {
// Set counter to end.
cnt2 = nodesAndEdgesOrdering2.length - 1;
for (let i = 0; i < nodesAndEdgesOrdering2.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering2[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
if (status == "try") {
continue;
}
// Set all elements to their final colors.
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
}, { once: true });
}
}
}
function onMouseDown2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor2);
}
function onMouseUp2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor2);
}
function onMouseOver2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor2);
}
function onMouseLeave2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor2);
}
```
Make sure to read
Print all Edges Recursively
for traversal samples that utilize
BFS
.
## Visitation Strategies
Thus far many of our examples have asserted that we’d enter
nodes
on the
first available
edge
, i.e. we would always visit a
node
via the first connected
edge
that we happened to traverse over, regardless of whether or not the
node
in question also has other entrance avenues. This doesn’t always have to be the case, however, and some situations will
force
us to utilize different sets of criteria when determining when a
node
should be entered during exploration (see
Print all Node Names Recursively in Topological Order
for a concrete example). The relevant decision-making logic is encoded in so-called
visitation strategies
, which are policies passed down to traversal algorithms that inform the latter of specific conditions that must be met prior to entering a
node
. Although developers are free to write their own visit strategies, the three most commonly-used ones –
```
VisitFirst, VisitLast, and VisitAll – have already been implemented and made available through the API.
Note that the visit strategies presented below are templated to utilize a transient set of per-node-specific data `NodeData` that, among other information, tracks the number of node visits via a `visitCount` variable. This data structure is only meant to exist for the duration of the graph traversal.
### VisitFirst Strategy
The VisitFirst strategy allows for a given node to be entered the first time that it is discovered, i.e., along the first available edge. This is the formal name given to the strategy employed in the DFS and BFS examples in the Next Steps section.
The implementation looks like this:
#### Listing 50
VisitFirst strategy implementation.
```cpp
//! Traversal strategy that enters the node when it was first time discovered
struct VisitFirst
{
//! Call to traverse the graph with a strategy to visit only when first time discovered
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node* node, NodeData& nodeData)
{
auto lastVisit = nodeData.visitCount++; // read+increment only once. other threads can be doing the same.
return (lastVisit == 0) ? VisitOrder::eFirst : VisitOrder::eUnknown;
}
};
```
Here’s an animated example of a serial DFS through graph \(G_1\) that employs the VisitFirst strategy:
Execution Graph
NodeGraphDef
𝐺
1
has associated executor type
a
b
0/1
c
0/1
d
0/1
e
Node e
NodeGraphDef
X
0/1
Node f
NodeGraphDef
Y
0/1
g
0/1
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef
X
0/1
h
i
0/1
j
0/1
Root is a special node used to discover the entire topology.
Root
Node
Def
NodeGraph
Def
Each node in topology has one of two execution definition types.
<!--Buttons-->
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes3.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes3.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes3.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to the path that draws the circle*/
.nodes3.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to all other child elements of the node, which is just text.*/
.nodes3.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes3.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes3.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim03 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
```
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering = [
[["a3", "node", "try", "1"]],
[["a3", "node", "success"]],
[["ab3", "edge", "try"], ["b3", "node", "try", "1"]],
[["ab3", "edge", "success"], ["b3", "node", "success"]],
[["be3", "edge", "try"], ["e3", "node", "try", "1"]],
[["be3", "edge", "success"], ["e3", "node", "success"]],
[["h13", "node", "try", "1"]],
[["h13", "node", "success"]],
[["h1i13", "edge", "try"], ["i13", "node", "try", "1"]],
[["h1i13", "edge", "success"], ["i13", "node", "success"]],
[["i1j13", "edge", "try"], ["j13", "node", "try", "1"]],
[["i1j13", "edge", "success"], ["j13", "node", "success"]],
[["j1i13", "edge", "try"], ["i13", "node", "try", "2"]],
[["j1i13", "edge", "failure"], ["i13", "node", "failure"]],
[["eg3", "edge", "try"], ["g3", "node", "try", "1"]],
[["eg3", "edge", "success"], ["g3", "node", "success"]],
[["ac3", "edge", "try"], ["c3", "node", "try", "1"]],
[["ac3", "edge", "success"], ["c3", "node", "success"]],
[["cf3", "edge", "try"], ["f3", "node", "try", "1"]],
[["cf3", "edge", "success"], ["f3", "node", "success"]],
[["k3", "node", "try", "1"]],
[["k3", "node", "success"]],
[["kl3", "edge", "try"], ["l3", "node", "try", "1"]],
[["kl3", "edge", "success"], ["l3", "node", "success"]],
[["lm3", "edge", "try"], ["m3", "node", "try", "1"]],
[["lm3", "edge", "success"], ["m3", "node", "success"]],
[["h23", "node", "try", "1"]],
[["h23", "node", "success"]],
[["h2i23", "edge", "try"], ["i23", "node", "try", "1"]],
[["h2i23", "edge", "success"], ["i23", "node", "success"]],
[["i2j23", "edge", "try"], ["j23", "node", "try", "1"]],
[["i2j23", "edge", "success"], ["j23", "node", "success"]],
[["j2i23", "edge", "try"], ["i23", "node", "try", "2"]],
[["j2i23", "edge", "failure"], ["i23", "node", "failure"]],
[["fd3", "edge", "try"], ["d3", "node", "try", "1"]],
[["fd3", "edge", "success"], ["d3", "node", "success"]],
[["df3", "edge", "try"], ["f3", "node", "try", "2"]],
[["df3", "edge", "failure"], ["f3", "node", "failure"]],
[["fg3", "edge", "try"], ["g3", "node", "try", "2"]],
[["fg3", "edge", "failure"], ["g3", "node", "failure"]],
[["ad3", "edge", "try"], ["d3", "node", "try", "2"]],
[["ad3", "edge", "failure"], ["d3", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors3 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor3 = "#FFFFFF";
const buttonHoverColor3 = "#BFBFBF";
const buttonDownColor3 = "#7F7F7F";
let cnt3 = -1;
function onClickGoToStart3(buttonElement) {
// Reset counter to start.
cnt3 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges3");
for (const edge of edges.children) {
edge.classList.value = "edges3";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes3");
for (const node of nodes.children) {
node.classList.value = "nodes3";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = "0/" + vcnt3[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward3(buttonElement) {
if (cnt3 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering[cnt3];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges3" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges3" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges3");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(0, edgeIdx, nodeAndEdgeColors3, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
```javascript
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes3" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes3" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes3");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(nodeIdx, prevEdgeIdx, nodeAndEdgeColors3, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
vcnt3[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt3[0] + "/" + vcnt3[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
}, { once: true });
}
}
```
// When reversing a "try", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a try).
else if (status == "try") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitTry");
}
else {
node.classList.add("unfilledVisitTry");
}
node.setAttribute("visited-past-try", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes3" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes3" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes3");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(nodeIdx, prevEdgeIdx, nodeAndEdgeColors3, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
} else {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes3";
}, { once: true });
} else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
} else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
// ...
}, { once: true });
}
}
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
node.classList.value = "nodes3";
}, { once: true });
} else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
} else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes3";
}, { once: true });
}
}
function onClickGoToEnd3(buttonElement) {
// Set counter to end.
cnt3 = nodesAndEdgesOrdering.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes3").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = "0/" + vcnt3[1];
}
}
for (let i = 0; i < nodesAndEdgesOrdering.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes3");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
}
} else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
}
});
}
}
}
```javascript
else if (type == "node") {
element.classList.add("nodes3");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes3");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onMouseDown3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor3);
}
function onMouseUp3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor3);
}
function onMouseOver3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor3);
}
function onMouseLeave3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor3);
}
//]]>
<p>
Make sure to read
<span class="std std-ref">
Print all Node Names
,
<span class="std std-ref">
Print all Node Traversal Paths Recursively
, and
<span class="std std-ref">
Store and Print all Node Names Concurrently
for traversal samples that utilize the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitFirst
strategy.
<section id="visitlast-strategy">
<span id="visit-last-strategy">
<h3>
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
Strategy
<p>
The
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
strategy allows for a given
<span class="std std-ref">
node
to be entered only when the
<em>
entirety
of its upstream/parent
<span class="std std-ref">
nodes
have already been visited, thereby implying that this is the last opportunity to enter the
<span class="std std-ref">
node
. We sometimes refer to the ordering of
<span class="std std-ref">
node
visits produced by using
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
as being the
<em>
topographical
traversal order (as was seen in
<span class="std std-ref">
Getting Started with Writing Graph Traversals
, for example).
<p>
To justify the need and merit of this strategy, suppose we had the following IR
<span class="std std-ref">
graph
<span class="math notranslate nohighlight">
\(G_3\)
:
<figure class="align-center" id="ef-graph-traversal-03">
Figure 26 Example IR graph \(G_3\) which contains a fan in/out flow pattern. Assume that \(\{r,a\}\) and \(\{r,b\}\) are root node \(r\)’s first and second edges, respectively.
As has been discussed in previous articles, connections between \(c\) and the parents represent upstream execution dependencies for \(c\), i.e. in order to successfully compute \(c\), we first need the results of \(a\)’s and \(b\)’s executions. Now, suppose that we tried traversing this graph in a serial, DFS manner using the same policy of entering any node on the first available edge, and immediately executing each node that we visit. Based on what has already been presented, the traversal path (and subsequently the order of node executions) would look like this (assuming we begin from \(r\)):
\[r \rightarrow a \rightarrow c \rightarrow b\]
This is problematic because \(c\) was evaluated before all of its parents; more specifically, not all of the requisite upstream information for \(c\)’s compute were passed down prior to triggering its evaluation, since \(b\) was executed after \(c\). To remedy this, we’d need to specify in the traversal implementation that nodes are only to be entered once all of their parents have been executed. Said differently, we should only enter on the last available edge, which implies that all other parents have already executed, and now that the final parent is also done computing we can safely continue flowing downstream since we have the necessary upstream inputs to perform subsequent calculations. In the above example, rather than directly entering \(c\) from \(a\), we’d actually first bounce to the other branch to evaluate \(b\), and only then enter \(c\) from \(b\). The amended traversal path would thus be:
\[r \rightarrow a \rightarrow b \rightarrow c\]
The implementation for VisitLast looks like this:
```cpp
//! Traversal strategy that enters the node when entire upstream was already visited and this is the last
//! opportunity to enter the node.
//!
//! In case of cycles, this algorithm is relying on knowledge of number of parents that are causing cycles.
struct VisitLast
{
//! Call to traverse the graph with a strategy to visit only when no more visits are possible
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node& node, NodeData& nodeData)
{
Listing 51 VisitLast strategy implementation.
- The root node (which doesn’t get counted as the parent of any node) and no parent cycles, so `requiredCount == 0`. This is also the first time we’ve attempted to enter \(a\), so `currentVisit == 1`. By these two conditions, the node can be entered.
- From \(a\) we try to visit all of its children. Since \(b\) is its only child, we attempt to visit \(b\).
- \(b\) has 2 parents (\(a\) and \(c\), since both have directed edges pointing from themselves to \(b\)) and 1 parent cycle (formed thanks to \(c\)). Since this is the first time that we’ve visited \(b\), `currentVisit == 1`. Now, suppose that we only computed `requiredCount` based exclusively off of the number of parents, i.e. `auto requiredCount = node->getParents().size()`. In this case `requiredCount == 2`, which implies that we’d need to visit both \(a\) and \(c\) first before entering \(c\). But, \(c\) also lies downstream of \(b\) in addition to being upstream (such is the nature of cycles), and the only way to enter \(c\) is through \(b\). So we’d need to enter \(b\) before \(c\), which can only be done if \(c\) is visited, and on-and-on goes the circular logic. In short, using this specific rule we’d never be able to enter either \(b\) or \(c\) (as evidenced by the fact that our `requiredCount` of 2 is not equal to the `currentVisit` value of 1). While this could be viable visitation behavior for situations where we want to prune cycles from traversal, the VisitLast strategy was written with the goal of making all nodes in a cyclic graph be reachable. This is why we ultimately subtract the parent cycle count from the required total – we essentially stipulate that it is not necessary for upstream nodes that are members of the same cycle(s) that the downstream node in question is in to be computed prior to entering the latter. Using this ruleset, `requiredCount` for \(b\) becomes 1, and thus `currentVisit == requiredCount` is satisfied.
- We skip the rest of the traversal steps since they’re not relevant to the present discussion.
DFS through graph \(G_1\) that employs the `VisitLast` strategy:
Execution Graph
NodeGraphDef
\(G_1\)
has associated executor type
a
b
0/1
c
0/1
d
0/1
Node e
NodeGraphDef X
0/1
Node f
NodeGraphDef Y
0/2
g
0/2
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef X
0/1
h
i
Root is a special node used to
discover the entire topology.
Each node in topology has
one of two execution
definition types.
Root
Node
Def
NodeGraph
Def
<<
<
>
>>
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges4:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges4:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges4:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes4.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes4.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes4.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes4.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes4.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes4.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes4.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim04 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
```javascript
const edges = document.getElementById("edges4");
for (const edge of edges.children) {
edge.classList.value = "edges4";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes4");
for (const node of nodes.children) {
node.classList.value = "nodes4";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = "0/" + vcnt4[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}, { once: true });
}
```
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes4" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes4" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes4");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(nodeIdx, prevEdgeIdx, nodeAndEdgeColors4, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
vcnt4[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt4[0] + "/" + vcnt4[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
}, { once: true });
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes4";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
}
}
cnt4 -= 1;
}
function onClickForward4(buttonElement) {
if (cnt4 >= nodesAndEdgesOrdering4.length - 1) {
return;
}
cnt4 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering4[cnt4];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges4" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges4" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges4");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(0, edgeIdx, nodeAndEdgeColors4, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes4" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes4" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes4");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(nodeIdx, prevEdgeIdx, nodeAndEdgeColors4, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes4";
}, { once: true });
}
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onClickGoToEnd4(buttonElement) {
// Set counter to end.
cnt4 = nodesAndEdgesOrdering4.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes4").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = "0/" + vcnt4[1];
}
}
for (let i = 0; i < nodesAndEdgesOrdering4.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering4[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges4");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes4");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
}
} else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges4");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
}
}
});
}
}
}
```javascript
// ... (JavaScript code related to SVG element manipulation)
```
```javascript
function onMouseDown4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor4);
}
function onMouseUp4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor4);
}
function onMouseOver4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor4);
}
function onMouseLeave4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor4);
}
```
```html
<!-- ... (HTML code related to SVG and script tags) -->
```
<p>
Make sure to read
<span class="std std-ref">
Print all Node Names Recursively in Topological Order
for a traversal sample that utilizes the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
strategy.
<section id="visitall-strategy">
<h3>
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
Strategy
<p>
The
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
strategy allows for all
<span class="std std-ref">
edges
in an EF
<span class="std std-ref">
graph
to be explored. While the previous two strategies are meant to be used with specific traversal continuation logic in mind (i.e. continuing traversal along the first/last
<span class="std std-ref">
edge
in the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitFirst
/
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
strategies, respectively),
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
is more open-ended in that it encourages the user to establish how traversal continuation should proceed (this is touched on in more detail
<span class="std std-ref">
here
).
<p>
The implementation looks like this:
<div class="literal-block-wrapper docutils container" id="ef-listing-visit-all">
<!-- ... (code block content) -->
### Listing 52
VisitAll strategy implementation.
```c++
//! Traversal strategy that allows discovering all the edges in the graph. Traversal continuation is controlled by user code.
//! struct VisitAll
struct VisitAll
{
//! Call to traverse the graph with a strategy to visit all edges of the graph
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node& node, NodeData& nodeData)
{
auto parentCount = node->getParents().size();
auto requiredCount = parentCount - node->getCycleParentCount();
auto currentVisit = ++nodeData.visitCount; // increment+read only once. other threads can be doing the same.
if (requiredCount == 0 && currentVisit == 1)
{
return (VisitOrder::eFirst | VisitOrder::eLast);
}
VisitOrder ret = VisitOrder::eUnknown;
if (currentVisit > requiredCount)
{
ret = VisitOrder::eCycle;
}
else if (currentVisit == requiredCount)
{
ret = (currentVisit == 1) ? (VisitOrder::eFirst | VisitOrder::eLast) : VisitOrder::eLast;
}
else if (currentVisit == 1)
{
ret = VisitOrder::eFirst;
}
else
{
ret = VisitOrder::eNext;
}
return ret;
}
};
```
Note how we’re outputting the specific type of visit that gets made when processing a given node (i.e. did we visit a node along its first edge, last edge, a cyclic edge, or something in between), unlike VisitFirst.
VisitFirst
and
VisitLast
which only check whether their own respective visit conditions have been met (and output a
VisitOrder::eUnknown
result if those conditions aren’t satisfied).
Here’s an animated example of a
serial
DFS
through
graph
\(G_1\)
that employs the
VisitAll
strategy and continues traversal along the first discovered
edge
:
b
0/1
c
0/1
d
0/1
Node e
NodeGraphDef
X
0/1
Node f
NodeGraphDef
Y
0/1
g
0/1
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef
X
0/1
h
0/1
i
0/1
j
0/1
Root is a special node used to
discover the entire topology.
Root
Node
Def
NodeGraph
Def
Each node in topology has
one of two execution
definition types.
<<
<
>
>>
```html
let dynamicStyle5 = document.getElementById("dynamicStyles5");
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent5(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges5:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges5:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges5:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes5.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes5.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to the path that draws the circle*/
.nodes5.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to all other child elements of the node, which is just text.*/
.nodes5.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitSuccessWithPrevSuccesses:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes5.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim05 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
`;
}
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering5 = [
[["a5", "node", "try", "1"]],
[["a5", "node", "success", "1"]],
[["ab5", "edge", "try"], ["b5", "node", "try", "1"]],
[["ab5", "edge", "success"], ["b5", "node", "success", "1"]],
[["be5", "edge", "try"], ["e5", "node", "try", "1"]],
[["be5", "edge", "success"], ["e5", "node", "success", "1"]],
[["h15", "node", "try", "1"]],
[["h15", "node", "success", "1"]],
[["h1i15", "edge", "try"], ["i15", "node", "try", "1"]],
[["h1i15", "edge", "success"], ["i15", "node", "success", "1"]],
[["i1j15", "edge", "try"], ["j15", "node", "try", "1"]],
[["i1j15", "edge", "success"], ["j15", "node", "success", "1"]],
[["j1i15", "edge", "try"], ["i15", "node", "try", "2"]],
[["j1i15", "edge", "success"], ["i15", "node", "success", "2"]],
`;
[["eg5", "edge", "try"], ["g5", "node", "try", "1"]],
[["eg5", "edge", "success"], ["g5", "node", "success", "1"]],
[["ac5", "edge", "try"], ["c5", "node", "try", "1"]],
[["ac5", "edge", "success"], ["c5", "node", "success", "1"]],
[["cf5", "edge", "try"], ["f5", "node", "try", "1"]],
[["cf5", "edge", "success"], ["f5", "node", "success", "1"]],
[["k5", "node", "try", "1"]],
[["k5", "node", "success", "1"]],
[["kl5", "edge", "try"], ["l5", "node", "try", "1"]],
[["kl5", "edge", "success"], ["l5", "node", "success", "1"]],
[["lm5", "edge", "try"], ["m5", "node", "try", "1"]],
[["lm5", "edge", "success"], ["m5", "node", "success", "1"]],
[["h25", "node", "try", "1"]],
[["h25", "node", "success", "1"]],
[["h2i25", "edge", "try"], ["i25", "node", "try", "1"]],
[["h2i25", "edge", "success"], ["i25", "node", "success", "1"]],
[["i2j25", "edge", "try"], ["j25", "node", "try", "1"]],
[["i2j25", "edge", "success"], ["j25", "node", "success", "1"]],
[["j2i25", "edge", "try"], ["i25", "node", "try", "2"]],
[["j2i25", "edge", "success"], ["i25", "node", "success", "2"]],
[["fd5", "edge", "try"], ["d5", "node", "try", "1"]],
[["fd5", "edge", "success"], ["d5", "node", "success", "1"]],
[["df5", "edge", "try"], ["f5", "node", "try", "2"]],
[["df5", "edge", "success"], ["f5", "node", "success", "2"]],
[["fg5", "edge", "try"], ["g5", "node", "try", "2"]],
[["fg5", "edge", "success"], ["g5", "node", "success", "2"]],
[["ad5", "edge", "try"], ["d5", "node", "try", "2"]],
[["ad5", "edge", "success"], ["d5", "node", "success", "2"]]
// Node + edge colors.
const nodeAndEdgeColors5 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor5 = "#FFFFFF";
const buttonHoverColor5 = "#BFBFBF";
const buttonDownColor5 = "#7F7F7F";
let cnt5 = -1;
function onClickGoToStart5(buttonElement) {
// Reset counter to start.
cnt5 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges5");
for (const edge of edges.children) {
edge.classList.value = "edges5";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes5");
for (const node of nodes.children) {
node.classList.value = "nodes5";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = "0/" + vcnt5[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward5(buttonElement) {
if (cnt5 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering5[cnt5];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges5" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges5" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges5");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(0, edgeIdx, nodeAndEdgeColors5, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes5" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes5" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes5");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(nodeIdx, prevEdgeIdx, nodeAndEdgeColors5, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
vcnt5[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt5[0] + "/" + vcnt5[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes5";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success). We do need to check if the node has been
// successfully visited in the past though (e.g. with the VisitAll strategy).
else if (status == "success") {
const visitCount = elementAttrs[3];
// Check if the node has been successfully visited in previous steps,
// not counting the current step that's about to be reversed.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (visitCount <= vcnt5[1]) {
node.setAttribute("successful-past-visit", "false");
}
}
else if (visitCount == "1") {
node.setAttribute("successful-past-visit", "false");
}
// Set the appropriate animation depending on whether or not
// we're reversing the very first successfull visit.
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
}
else {
node.classList.add("visitSuccessWithPrevSuccesses");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
}
cnt5 -= 1;
function onClickForward5(buttonElement) {
if (cnt5 >= nodesAndEdgesOrdering5.length - 1) {
return;
}
cnt5 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering5[cnt5];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges5" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges5" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges5");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(0, edgeIdx, nodeAndEdgeColors5, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes5" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes5" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes5");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(nodeIdx, prevEdgeIdx, nodeAndEdgeColors5, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
}
}
}
```javascript
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes5";
}, { once: true });
}
else if (status == "success") {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
}
else {
node.classList.add("visitSuccessWithPrevSuccesses");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes5";
}, { once: true });
}
```
```javascript
function onClickGoToEnd5(buttonElement) {
// Set counter to end.
cnt5 = nodesAndEdgesOrdering5.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes5").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
```
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = "0/" + vcnt5[1];
}
for (let i = 0; i < nodesAndEdgesOrdering5.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering5[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
}
}
else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onMouseDown5(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor5);
}
function onMouseUp5(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
}
Make sure to read
- **Print all Edges Recursively**
- **Using Custom NodeUserData**
for traversal samples that utilize the **VisitAll** strategy.
## Serial vs. Parallel Graph Traversal
In the previous traversal examples we alluded to the fact that many of the searches were performed **serially**, as opposed to in **parallel**. The difference between the two is presented below:
### Serial Graph Traversal
- **Serial**: A **single** thread is utilized to perform the **graph** traversal. As a consequence, **node** visitation ordering will be deterministic, and depends entirely on the order of the corresponding connecting **edges**. This is why, in both the **DFS** and **BFS** examples shown in **Next Steps**, we visited **node** \(b\) before **node** \(c\) when kickstarting the search from **node** \(a\). While such **serial** traversal is usually easier to conceptualize – hence their liberal use in this article – it will also be much slower to traverse through a **graph** than an equivalent **parallel** search.
### Parallel Graph Traversal
- **Parallel**: **Multiple** threads are utilized to perform the **graph** traversal. As a consequence, **node** visitation ordering will **not** be deterministic, since different threads will begin and end their explorations at varying times depending on a number of external factors (the sizes of the subgraphs that are rooted at each child **node**, fluctuations in how the OS dispatches threads, etc.); this in turn implies that the generated depth/breadth-first search trees can differ between different concurrent traversals of the same **graph**. **Parallel** traversals will typically take **significantly** less time to complete than their **serial** counterparts.
Below is an example parallel graph traversal implementation using the APIs.
## Store and Print all Node Names **Concurrently**
**Listing 53** is similar to **Listing 26**, except that we now print the **node** names in **parallel** by performing the traversal in a multi-threaded fashion and store the results in an external data container.
tbb refers to Intel's Threading Building Blocks library.
### Listing 53
#### Parallel DFS using the VisitFirst strategy to print and store all top-level visited node names.
```cpp
tbb::task_group taskGroup;
tbb::concurrent_vector<INode*> nodes;
{
auto traversal =
traverseDepthFirstAsync<VisitFirst>(myGraph->getRoot(),
[&nodes, &taskGroup](auto info, INode* prev, INode* curr)
{
taskGroup.run(
[&nodes, info, prev, curr]() mutable
{
nodes.emplace_back(curr);
// Increase the chance for race conditions to arise by
// sleeping.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
info.continueVisit(curr);
});
});
taskGroup.wait(); // Wait for all the parallel work to complete.
// Traversal object now is safe to destroy (which will happen when leaving the scope).
}
for (INode* const nodeName : nodes)
{
std::cout << nodeName->getName() << std::endl;
}
```
Applying this concurrent traversal to \(G_1\) would produce a list containing \(b\), \(e\), \(g\), \(c\), \(f\), and \(d\), although the exact ordering is impossible to determine thanks to some inherent non-determinisms associated with multi-threaded environments (variability when threads are spawned to perform work, distribution of tasks amongst threads, etc.).
## Traversal APIs
Now that we’ve covered DFS / BFS and Visitation Strategies, let’s bring our attention to the various traversal API helper methods. Currently there are 4 such traversal functions, all of which can be found in
```
# Traversal Methods
## Overview
The following traversal methods are available:
- **traverseDepthFirst()** can be used to perform serial DFS.
- **traverseBreadthFirst()** can be used to perform serial BFS.
- **traverseDepthFirstAsync()** can be used to perform both serial and parallel DFS.
- **traverseBreadthFirstAsync()** can be used to perform both serial and parallel BFS.
## Additional Details
It is worth mentioning that:
1. These methods are templated to include a `Strategy` type, which refers to the Visitation Strategies from before. This allows users to pass in custom-defined policies for graph exploration.
2. The traversal methods are also templated to include an optional `NodeUserData` type struct, which can be useful for passing in more sophisticated per-node data.
3. All four of the traversal methods accept a user-defined callback as part of their arguments, which gets evaluated whenever a node is able to be visited.
4. Technically, **traverseDepthFirstAsync()** and **traverseBreadthFirstAsync()** don’t implement parallel versions of these algorithms from the start; they simply allocate an internal `Traversal` object to the heap for concurrent access. The actual multithreaded search mechanism needs to be added by the user in the callback.
. Note that this also means that one could technically use
traverseDepthFirstAsync()/traverseBreadthFirstAsync() for
serial searches by writing the appropriate callbacks, although this is discouraged since
traverseDepthFirst() and traverseBreadthFirst() already exist to fulfill that functionality. | 217,658 |
Helpers.md | # Menu Helpers
Requires omni.kit.menu.utils version 1.5.8 or above
## MenuHelperExtension
This helper assists with menu creation but minimal window creation help, adds menu_startup(), menu_shutdown() & menu_refresh() functions by MenuHelperExtension subclass. Allowing user to control window open/closing. But does require ui.Workspace.set_show_window_fn to be set as it uses this to open/close/get state for the window
```python
from omni.kit.menu.utils import MenuHelperExtension
class ActionsExtension(omni.ext.IExt, MenuHelperExtension):
def on_startup(self):
self._actions_window = None
ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, self.show_window)
self.menu_startup(ActionsExtension.WINDOW_NAME, ActionsExtension.WINDOW_NAME, ActionsExtension.MENU_GROUP)
ui.Workspace.show_window(ActionsExtension.WINDOW_NAME, False)
def on_shutdown(self):
self.menu_shutdown()
ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, None)
if self._actions_window:
self._actions_window.destroy()
self._actions_window = None
def show_window(self, visible: bool):
if visible:
self._actions_window = ui.Window(ActionsExtension.WINDOW_NAME)
self._actions_window.set_visibility_changed_fn(self._visiblity_changed_fn)
self.menu_refresh()
elif self._actions_window:
self._actions_window.visible = False
def _visiblity_changed_fn(self, visible):
# tell omni.kit.menu.utils that actions window menu open/close state needs updating
self.menu_refresh()
```
Building window widgets can be done by sub-classing _show function, although it’s recommended that this should be done by sub-classing ui.Window and adding a frame build_fn via self.frame.set_build_fn(self._build_ui)
```python
def _show(self):
super()._show()
if self._window:
with self._window.frame:
with ui.VStack(height=0, spacing=8):
with ui.HStack(height=460):
ui.Label("myWindow")
```
## MenuHelperExtensionFull
- This helper assists with menu creation and window creation, handles show/hide and menu state updating. Adds menu_startup(), menu_shutdown() & menu_refresh() functions by MenuHelperExtensionFull subclass, all user has-to provide a function call to create the window.
```python
from omni.kit.menu.utils import MenuHelperExtensionFull
class OscilloscopeWindowExtension(omni.ext.IExt, MenuHelperExtensionFull):
def on_startup(self):
self.menu_startup(lambda: ui.Window("Audio Oscilloscope", width=512, height=540), "Audio Oscilloscope", "Oscilloscope", "Window")
ui.Workspace.show_window("Audio Oscilloscope", True)
def on_shutdown(self):
self.menu_shutdown()
```
or
```python
from omni.kit.menu.utils import MenuHelperExtensionFull, MenuHelperWindow
class OscilloscopeWindowExtension(omni.ext.IExt, MenuHelperExtensionFull):
def on_startup(self):
self.menu_startup(lambda: MenuHelperWindow("Audio Oscilloscope", width=512, height=540), "Audio Oscilloscope", "Oscilloscope", "Window")
ui.Workspace.show_window("Audio Oscilloscope", True)
def on_shutdown(self):
self.menu_shutdown()
``` | 3,289 |
high-level-code-overview_Overview.md | # Usage
## Usage
To enable this extension, go to the Extension Manager menu and enable omni.importer.urdf extension.
## High Level Code Overview
### Python
The URDF Importer extension sets attributes of `ImportConfig` on initialization, along with the UI giving the user options to change certain attributes. The complete list of configs can be found in `bindings/BindingsUrdfPython.cpp`.
When the import button is pressed, the `URDFParseAndImportFile` command from `python/commands.py` is invoked; this first calls `URDFParseFile` command, which binds to `parseUrdf` in `plugins/Urdf.cpp`. It then runs `import_robot` which binds to `importRobot` in `plugins/Urdf.cpp`.
### C++
#### `parseUrdf` in `plugins/Urdf.cpp`
Calls `parseUrdf` in `plugins/UrdfParser.cpp`, which parses the URDF file using tinyxml2 and calls `parseRobot` in the same file. `parseRobot` writes to the `urdfRobot` class, which is an the internal data structure that contains the name, the links, the joints, and the materials of the robot. It first parses materials, which are stored in a map between material name and `UrdfMaterial` class that contains the material name, the color, and the texture file path. It then parses the links, which are stored in a map between the link name and `UrdfLink` class containing the name, the inertial, visual mesh, and collision mesh. It finally parses the joints and store each joint in `UrdfJoint`. Note that for joints, if there is no axis specified, the axis defaults to (1,0,0). If there is no origin, it defaults to the identity transformation.
#### `importRobot` in `plugins/Urdf.cpp`
```
# Import Robot in plugins/Urdf.cpp
Initializes `urdfImporter` class defined in `plugins/UrdfImporter.h`. Calls `urdfImporter.addToStage`, which does the following:
- Creates a physics scene if desired in the config
- Creates a new prim that represents the robot and applies Articulation API, enables self-collision is set in the config, and sets the position and velocity iteration count to 32 and 16 by default.
- Sets the robot prim as the default prim if desired in the config
- Initializes a `KinematicChain` object from `plugins/KinematicChain.h` and calls `computeKinematicChain` given the `urdfRobot`. `computeKinematicChain` first finds the base link and calls `computeChildNodes` recursively to populate the entire kinematic chain.
- If the asset needs to be made instanceable, it will create a new stage, go through every link in the kinematic chain, import the meshes onto the new stage, and save the new stage as a USD file at the specified path.
- Recursively calls `addLinksAndJoints` along the entire kinematic chain to add the link and joint prims on stage.
# Limitations
- The URDF importer can only import robots that can be represented with a kinematic tree and hence cannot handle parallel robots. However, this is a limitation of the URDF format itself as opposed to a limitation of the URDF importer. For parallel robots, please consider switching to using MJCF along with the MJCF importer.
- The URDF importer does not currently support the `planar` joint type. In order to achieve a planar movement, please define two prismatic joints in tandem in place of a planar joint.
- The URDF importer does not support `<mimic>` for joints. However, a mimicing joint effect can be achieved manually in code by setting the joint target value to `multiplier * other_joint_value + offset`. | 3,421 |
hoops-converter_Overview.md | # Hoops Converter
## Overview
The Hoops Converter extension enables conversion for many common CAD file formats to USD.
USD Explorer includes the Hoops Converter extension enabled by default.
## Supported CAD file formats
The following file formats are supported by Hoops Converter:
- CATIA V5 Files (`*.CATPart`, `*.CATProduct`, `*.CGR`)
- CATIA V6 Files (`*.3DXML`)
- IFC Files (`*.ifc`, `*.ifczip`)
- Siemens NX Files (`*.prt`)
- Parasolid Files (`*.xmt`, `*.x_t`, `*.x_b`, `*.xmt_txt`)
- SolidWorks Files (`*.sldprt`, `*.sldasm`)
- STL Files (`*.stl`)
- Autodesk Inventor Files (`*.IPT`, `*.IAM`)
- AutoCAD 3D Files (`*.DWG`, `*.DXF`)
- Creo - Pro/E Files (`*.ASM`, `*.PRT`)
- Revit Files (`*.RVT`, `*.RFA`)
- Solid Edge Files (`*.ASM`, `*.PAR`, `*.PWD`, `*.PSM`)
- Step/Iges (`*.STEP`, `*.IGES`)
- JT Files (`*.jt`)
- DGN (`*.DGN`)
The file formats *.fbx, *.obj, *.gltf, *.glb, *.lxo, *.md5, *.e57 and *.pts are supported by Asset Converter and also available by default.
### Note
If expert tools such as Creo, Revit or Alias are installed, we recommend using the corresponding connectors. These provide more extensive options for conversion.
### Note
CAD Assemblies may not work when converting files from Nucleus. When converting assemblies with external references we recommend either working with local files or using Omniverse Drive.
## Converter Options
This section covers options for configuration of conversions of Hoops file formats to USD.
## Related Extensions
These related extensions make up the Hoops Converter. This extension provides import tasks to the extensions through their interfaces.
### Core Converter
- Hoops Core: :doc:`omni.kit.converter.hoops_core<omni.kit.converter.hoops_core:Overview>
### Services
- CAD Converter Service: :doc:`omni.services.convert.cad`
### Utils
- Converter Common: :doc:`omni.kit.converter.common` | 1,870 |
hotkey-registry_Overview.md | # Overview — Omniverse Kit 1.3.5 documentation
## Overview
The Omni Kit Hotkeys Core extension is a framework for creating, registering, and discovering hotkeys. Hotkeys are programmable objects include key binding, action and focus window. A hotkey can be created in one extension and then binded action can be executed when binded key pressed/released in desired window.
### Hotkeys
Hotkeys can be:
- Created, registered and discovered from any extension
- Edited, exported, imported
### Terms
- Local hotkey: Hotkey is executed in reference to an context rather that the application as a whole.
- Global hotkey: Hotkey will be executed no matter what “context” user is in
- Context: What window/tool/area the user is in. This is determined by Where the user’s mouse is hover
Local Hotkeys can override (Global) Hotkeys. If same key binding defined in both local hotkey and global hotkey, it will trigger in order:
- Local hotkey if special window focused
- Otherwise global hotkey
### Hotkey Registry
The Hotkey Registry maintains a collection of all registered hotkeys and allows any extension to:
- Register new hotkeys.
- Deregister existing hotkeys.
- Discover registered hotkeys.
- Edit existing hotkeys to change key binding or associated window name
Here is an example of registering a global hokey from Python that execute action “omni.kit.window.file::new” to create a new file when CTRL + N pressed:
```cpp
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey_registry.register_hotkey(
"your_extension_id",
"CTRL + N",
"omni.kit.window.file",
"new",
filter=None,
)
```
For more examples, please consult the usage pages. | 1,676 |
how-can-i-extend-precense-layer-to-share-data-not-listed_Overview.md | # Introduction — Omniverse Kit 1.0.9 documentation
## Introduction
Presence Layer works for providing storage to exchange persistent data for all users in the same Live Session (see module `omni.kit.usd.layers`). The theory is that it uses .live layer as transport layer, on top of which all user data is structured as USD prim. It provides easy API to access the data without using raw USD API, and also event stream to subscribe the data changes. Currently, it’s used for spatial awareness, which includes the following applications:
- Bound Camera.
- Selections.
- User Following.
User can exchange and synchronize their local states of the above applications into the Presence Layer for other users to be aware of.
## Limitation
Currently, Presence Layer is created only when Root Layer enters a Live Session, no support for other layers in the layer stack.
## How can I Extend Precense Layer to Share Data not Listed?
Presence Layer currently exposes the raw underlying storage, which is a USD stage, so it shares all the benefits of USD and you can operate the stage with USD API to extend your own functionality. You can see `omni.kit.collaboration.presence_layer.PresenceAPI` for reference.
## Programming Guide
### Subscribe Spatial Awareness Events
Here is an example to subscribe spatial awareness events with Presence Layer, in a stage (specifically the Root Layer) that has already joined a Live Session (see `omni.kit.usd.layers.LiveSyncing`):
```python
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
def _on_layers_event(event):
nonlocal payload
p = pl.get_presence_layer_event_payload(event)
if not p.event_type:
return
if p.event_type == pl.PresenceLayerEventType.SELECTIONS_CHANGED:
... # Peer Client's selections changed.
elif p.event_type == pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED:
... # Local Client enters into following mode.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED:
# Peer Client changes its bound camera.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED:
... # Peer Client changes the properties of its bound camera.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_RESYNCED:
... # Peer Client's bound camera resynced.
usd_context = omni.usd.get_context()
layers_interface = layers.get_layers(usd_context)
subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layers_event, name="xxxxxxxxx"
)
...
<p>
As you can see above, all events from Presence Layer are sent through event stream from
<code>
omni.kit.usd.layers.Layers
as Presence Layer is part of Live Syncing workflow.
<section id="send-spatial-awareness-events-with-scripting">
<h2>
Send Spatial Awareness Events with Scripting
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="kn">import
...
usd_context = omni.usd.get_context()
# Gets instance of Presence Layer bound to an UsdContext.
presence_layer = pl.get_presence_layer_interface(usd_context)
# Boradcasts local bound camera to other clients
your_bound_camera_path = ...
presence_layer.broadcast_local_bound_camera(your_local_camera_path)
# Enters into following mode
following_user_id = ...
presence_layer.enter_follow_mode(following_user_id)
...
# Quits following mode
presence_layer.quit_follow_mode()
<p>
You can refer
<code>
omni.kit.usd.layers.LiveSyncing
and
<code>
omni.kit.usd.layers.LiveSession
about how to get the current Live Session and all of its joined users.
<footer>
<hr/>
| 3,642 |
how-it-works.md | # How It Works
The main `AutoNode` decorator, `@og.create_node_type`, wraps a Python function by creating a node type definition that allows that function to act as a node type’s `compute()` function. The logistics involve three phases - Analysis, which analyzes the function signature to define the input and output attributes that will be part of the node type definition as well as the node type’s critical definition information, `compute()` Definition, which wraps the decorated function in some code that interfaces with the OmniGraph `NodeType` ABI, and Runtime Registration/Deregistration, which manages the lifetime of the node types the decorator creates.
## Analysis
The analysis of the decorated function is triggered by import of the decorator `@og.create_node_type`. When it is encountered it uses both the parameters passed to the decorator itself and the signature of the function it is decorating to extract the information necessary to define an OmniGraph node type.
`AutoNode` generates node signatures by extracting type annotations stored in function signatures. In order for node types to be generated, type annotations are used in order to relate Python arguments to their OmniGraph attribute type equivalents.
The OmniGraph type annotations are imported from the module `omni.graph.core.types`. They encompass all of the legal attribute data type definitions, and are used as build-time identifiers for the data types being used in `AutoNode` definitions. To see the full list of data types available for use see Data Types.
Under the hood, annotation extraction is done with the python `__annotations__` (PEP 3107) dictionary in every class. In particular, it makes use of the `inspect` module’s function `inspect.get_annotations()` to retrieve and parse that information.
The annotations used have a table of correspondence between them and their .ogn attribute type names. The table is found in the build file `exts/omni.graph.tools/ogn/DataTypeNameConversions.json`. It contains the type name conversions between various representations, such as USD, SDF, Python annotations, and .ogn file text.
The decorator uses this table plus the extracted function signature to map the inputs and outputs to equivalent attribute definitions. (This mapping has some shortcomings, some of which can be worked around.)
Here is a map describing the various pieces of a simple decorator and what they are used for:
![AutoNodeDecoratorMap](_images/AutoNodeDecoratorMap.png)
# 文档标题
## 节点类型定义的额外信息
There is one more piece of information that will be extracted from the definition and used if possible and that is the name of the extension in which the node type was defined. For definitions executed through an extension-neutral location such as the script editor a special internal name will be applied in lieu of the extension name.
The extension name is discovered using inspection of the Python module top which the decorated function belongs and a lookup of extensions by module provided by the Kit extension manager. This extension information might be used in the **registration/deregistration management**.
## compute() Definition
As you can see from the decorator example above there is no requirement for the Python function being decorated to look anything like a regular OmniGraph **compute()** function, however there must be such a function in order for the node type to successfully integrate into OmniGraph.
The **AutoNode** implementation makes use of the internal runtime node type definition utility, which will create a new node type definition when given a few of the standard parameters. These include the attributes, which **AutoNode** parses from the function signature, any node type metadata, gleaned from the docstring and optional decorator arguments, and implementations for functions required for the node type to operate. The minimal set of such functions is the **compute()** function, and that is what **AutoNode** generates.
The function is a standalone function so there is not problem with trying to hook it into an existing object. The standard **compute()** function takes two parameters and returns a boolean indicating success:
```python
def compute(node: og.Node, context: og.GraphContext) -> bool:
return True
```
Note that this is also the magic that enables the **inspection trick** to find the node and context from within the decorated function.
A local function with this signature is instantiated by the decorator, with the interior of the function filled in with a very simple algorithm:
1. Walk the list of input attributes extracted by the analysis and use **node.get_attribute(NAME).get()** to get its current value
2. Call the decorated function with the retrieved values as parameters, in the order the function expects them
3. Walk the list of output attributes extracted by the analysis and use **node.get_attribute(NAME).set()** to set each of the values using the tuple or single value returned from the function call
4. Surround the function call with a try/except that will log an error and return False if an **og.OmniGraphError** is raised
## Runtime Registration/Deregistration
The last detail to be handled is the registration and deregistration of the node types, which can also be thought of as the node type life cycle management.
For convenience the node type will always be registered by the decorator so the start of the life cycle is well defined. Once a node type has been created and registered these are the events and reactions that will manage the end of the node type’s life cycle. It roughly follows the cycle of any Python object defined where it was defined.
**User executes the same decorated function, or another with the same unique name**
The existing node type with that name is deregistered and the new one is registered in its place. This enables the workflow of iterating on a node type definition in the script editor.
**User uses the og.deregister_node_type() API to manually deregister the node type**
The internal database is watching those events and updates itself so that it knows the node type is no longer registered.
**The omni.graph extension unloads**
While there is firewall code that deregisters any existing node types when the extension is disabled it also expects that through the extension dependencies that list should already be empty. That expectation is no longer valid and any still-active **AutoNode** node type definitions must be deregistered with any internal registries and callbacks being removed at that time as well. | 6,575 |
how-to-create-a-new-hydratexture_Overview.md | # Overview
## Introduction
A very low level extension for receiving renderer output as texture, which is usually then piped into the UI or captured directly. {py:mod}omni.kit.widget.viewport uses this extension to start a render and begin receiving its output.
Generally it is better to use higher level extensions like `omni.kit.widget.viewport` or `omni.kit.viewport.window`.
## How to create a new HydraTexture
### Python
1. Import the relevant module and function.
```python
from omni.kit.hydra_texture import acquire_hydra_texture_factory_interface
```
2. Get the HydraTexture factory interface to start creating HydraTextures
```python
texture_factory = acquire_hydra_texture_factory_interface()
# Make sure to run any initialization/startup that must occur
texture_factory.startup()
```
3. Make sure the engine-type is attached to the UsdContext
```python
engine_name = "rtx"
usd_context_name = ""
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
raise RuntimeError(f"UsdContext named '{usd_context_name}' does not exist")
if engine_name not in usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(engine_name, usd_context)
```
4. Create a HydraTexture object rendering with RTX at 1280x720, for a UsdGeom.Camera named “/OmniverseKit_Persp” on the default omni.usd.UsdContext (named “”)
```python
hydra_texture = texture_factory.create_hydra_texture(
name="your_unique_name",
width=1280,
height=720,
engine_name="rtx",
camera_path="/OmniverseKit_Persp"
)
```
```python
height = 720,
usd_context_name = "usd_context_name",
usd_camera_path = "/OmniverseKit_Persp",
hydra_engine_name = "engine_name"
```
5. Subscribe to the event with a callback when a new frame is delivered
```python
# Import carb for logging and type-hinting support with the callback
import carb
def renderer_completed(event: carb.events.IEvent):
if event.type != omni.kit.hydra_texture.EVENT_TYPE_DRAWABLE_CHANGED:
carb.log_error("Wrong event captured for EVENT_TYPE_DRAWABLE_CHANGED!")
return
# Get a handle to the result
result_handle = event.payload['result_handle']
# And pass that to the HydraTexture instance to get the AOV's that are available
aov_info = hydra_texture.get_aov_info(result_handle)
print(f"Available AOVs: {aov_info}")
# Get an object for a specific AOV and include the GPU texture in the info
ldr_info_array = hydra_texture.get_aov_info(result_handle, 'LdrColor', include_texture=True)
print(f"LdrColor AOVs are: {ldr_info_array}")
ldr_texture = ldr_info_array[0].get("texture", None)
assert ldr_texture is not None
ldr_color_res = ldr_texture.get("rp_resource")
ldr_color_gpu_tex = ldr_texture.get("rp_resource")
print(f"LdrColor[0]: {ldr_color_res}, {ldr_color_gpu_tex}")
# YOU CANNOT USE THE RESOURCE OUTSIDE OF THIS FUNCTION/SCOPE
# ldr_color_gpu_tex must be consumed now or passed to another object
# that will use / add-ref the underlying GPU-texture.
event_sub = hydra_texture.get_event_stream().create_subscription_to_push_by_type(
omni.kit.hydra_texture.EVENT_TYPE_DRAWABLE_CHANGED,
renderer_completed,
name="Your unique event name for profiling/debug purposes"
)
# When event_sub object is destroyed (from going out of scope or being re-assigned)
# then the callback will stop being triggered.
# event_sub = None
```
``` | 3,494 |
how-to-create-a-new-viewportwidget_Overview.md | # Overview
## Introduction
A low level implementation of an `omni.ui.Widget` that displays rendered output. The `omni.kit.widget.viewport.ViewportWidget` does not include any additional features (such as menu-items or manipulators). It is used by `omni.kit.viewport.window.ViewportWindow` to provide a higher level, default Viewport experience in Kit based apps.
## How to create a new ViewportWidget
### Python
1. Import `omni.ui` so the `ViewportWidget` can be created inside an `omni.ui.Window`
```python
import omni.ui as ui
```
2. Import the class from the package:
```python
from omni.kit.widget.viewport import ViewportWidget
```
3. Choose the resolution and camera this instance will start rendering with.
```python
resolution = (512, 512)
camera_path = "/OmniverseKit_Persp"
```
4. Create an empty `omni.ui.Window` and instantiate a new `ViewportWidget` in its `omni.ui.Frame`
```python
window = ui.Window("Demo ViewportWidget", width=resolution[0], height=resolution[1])
```
```python
with window.frame:
vp_widget = ViewportWidget(camera_path=camera_path, resolution=resolution)
```
3. Get the active ViewportAPI attached to the
```python
ViewportWidget
```
and inspect some properties.
```python
viewport_api = vp_widget.viewport_api
usd_context = viewport_api.usd_context
usd_context_name = viewport_api.usd_context_name
usd_stage = viewport_api.stage
camera_path = viewport_api.camera_path
resolution = viewport_api.resolution
```
## Further reading
- Viewport Documentation
- Tutorials | 1,563 |
how-to-create-a-new-viewportwindow_Overview.md | # Overview
## Introduction
A high level implementation of a Window that contains a Viewport and variety of menus and manipulators for interacting and controlling a `pxr.usd.UsdStage` attached to a specific `omni.usd.UsdContext`.
## How to create a new ViewportWindow
### Python
1. Import the class from the package:
```python
from omni.kit.viewport.window import ViewportWindow
```
2. Create a ViewportWindow instance named “Demo”, attached to the default UsdContext
```python
viewport_window = ViewportWindow("Demo", width=640, height=480)
```
3. Get the active ViewportAPI attached to the ViewportWindow and inspect some properties.
```python
viewport_api = viewport_window.viewport_api
usd_context = viewport_api.usd_context
usd_context_name = viewport_api.usd_context_name
usd_stage = viewport_api.stage
camera_path = viewport_api.camera_path
resolution = viewport_api.resolution
```
## Further reading
- Viewport Documentation
- Tutorials | 987 |
HowTo.md | # OmniGraph How-To Guide
Find the area of interest here and click through to get the implementation details.
## Table of Contents
- [Node Categories](Categories.html)
- [Controller Class](Controller.html)
- [Initializing Attributes to Non-Default Values](RuntimeInitialize.html)
- [Writing a `computeVectorized` function](VectorizedCompute.html)
- [Set Up OmniGraph Tests](Testing.html)
- [Running Minimal Kit With OmniGraph](RunningOneScript.html)
## Additional Resources
- [How To Use The Script Node](../../../omni.graph.scriptnode/1.18.2/GeneratedNodeDocumentation/OgnScriptNode.html#omni-graph-scriptnode-scriptnode) | 626 |
http-api.md | # HTTP API
Launcher uses port 33480 to provide the HTTP API that can be used by other programs to retrieve information about the current session or get the list of installed apps.
This document describes all available HTTP endpoints supported by Launcher.
## Authentication
### [GET] /auth
Returns Starfleet information about the current user session.
**Method**: GET
**Content type**: `application/json`
#### Response
| Property | Type | Description |
|----------|--------|-----------------------------------------------------------------------------|
| `email` | string | Email used for authentication. Can be used to uniquely identify a user. |
| `username` | string | Preferred username displayed in the UI. This field should not be used for unique user identification. Use `email` field instead. |
| `accessToken` | string | The access token returned from Starfleet. |
| `idToken` | string | The ID token used in Starfleet for retrieving user’s information. |
| `expires` | Date | The access token expiration date in ISO format. |
#### Errors
| Error Code | Description |
|------------|-----------------------------------------------------------------------------|
| | |
# Installed apps and connectors
Launcher classifies all installed apps and connectors as `_components_`.
## [GET] /components
Returns the list of all installed apps and connectors.
**Method**: GET
**Content type**: `application/json`
### Response
Returns a list with the following **Component** objects (`?` means that the property is optional):
| Property | Type | Description |
|----------|--------|-----------------------------------------------------------------------------|
| `slug` | string | The unique component name. |
| `name` | string | The full displayed component name. |
| `version`| string | The latest version of this component available for download. Use `installedVersions` to check installed versions. |
| `shortName` | string | The short name used in the side menu. |
| `kind` | string | Specifies the component kind: `apps` or `connectors`. |
| `category` | string | The category used for grouping this component in the library. |
| `productArea` | _string?_ | Represents the product area – one product area can include multiple components that can be installed separately. Displayed in the component card title. |
| `installedVersions` | InstalledVersions | Lists versions of this component installed by the user. |
| `description` | string[] | Paragraphs with component description, supports markdown and HTML. |
| Property | Type | Description |
|----------|------|-------------|
| platforms | string[] | Represents OSs where this component can be installed. |
| settings | Settings[] | Represents settings used for installing this component. |
| image | _URL?_ | The image displayed on the detailed page. |
| card | _URL?_ | The image displayed on the card on the Exchange tab. |
| icon | _URL?_ | The icon displayed in the component card title. |
| tags | string[] | Tags shown below the component description. |
| featured | boolean | Defines if this component is shown in the featured section. |
| featuredImage | _URL?_ | The image displayed in the featured section. |
| links | string[] | Hyperlinks displayed in the library and in the component details. |
### Installed Versions
###### [](#installed-versions)
| Property | Type | Description |
|----------|------|-------------|
| all | string[] | All installed versions of this component. |
| current | string | The current installed version that is used for launching the component. |
| latest | string | The latest version of this component installed by the user. |
### Settings
###### [](#settings)
| Property | Type | Description |
|----------|------|-------------|
| Key | Type | Description |
|-----------------|------------|-----------------------------------------------------------------------------|
| slug | string | The unique component name. |
| version | string | The installed component version associated with these settings. |
| packages | Package[] | Thin packages used by this version. |
| path | string | The path to the main package. |
| base | string | The base path for the component that contains all packages. |
| showInLibrary | boolean | Defines whether this component should be displayed in the library. |
| sideBySide | boolean | Defines whether this component supports side-by-side installations. |
| runWithLauncher | boolean | Specifies whether this component should be started automatically with Launcher. |
| launch | _Script?_ | The script used for launching the component. |
| open | _Script?_ | The script used for opening omniverse:// links. |
| preInstall | _Script?_ | The script used before the installation starts. |
| install | _Script?_ | The main script for installing the component. |
| postInstall | _Script?_ | The script used after the installation. |
| register | _Script?_ | The script used when the user selects this component version. |
| unregister | _Script?_ | The script used to clean up the system when uses selects another component version. |
## Script
### Property
| Property | Type | Description |
|----------|------|-------------|
| path | string | Path to the script. |
| root | string | Defines where the component is installed. |
| args | _string[]?_ | Specifies all command line arguments used for the script. |
| environment | Map<string, string> | Specifies all predefined environment variables used for the script. |
## Package
### Property
| Property | Type | Description |
|----------|------|-------------|
| name | string | The unique package name. |
| url | string | The unsigned URL for downloading the package. Can’t be used directly, must be signed first. |
| hash | string | The package hash. Used to deduplicate installed packages. |
| main | _boolean?_ | Specifies if this package is the main package of the component. Main packages contain launcher.toml files and installation scripts. |
## [GET] /components/:slug
Returns information about the installed component with the specified slug.
Method: GET
Content type: application/json
Response
Returns a Component object. See details in Installed apps and connectors.
### Errors
| Status | Description |
|--------|-------------|
| HTTP404 | Component with the specified slug is not installed. | | 7,429 |
id1_api_ll_users_guide.md | # Low Level API (NvBlast)
## Introduction
The low-level API is the core of Blast destruction. It is designed to be a minimal API that allows an experienced user to incorporate destruction into their application. Summarizing what the low-level API has, and doesn’t have:
- There is no physics representation. The low-level API is agnostic with respect to any physics engine, and furthermore does not have any notion of collision geometry. The NvBlastActor is an abstraction which is intended to correspond to a rigid body. However, it is up to the user to implement that connection. The NvBlastActor references a list of visible chunk indices, which correspond to NvBlastChunk data in the asset. The NvBlastChunk contains a userData field which can be used to associate collision geometry with the actor based upon the visible chunks. The same is true for constraints created between actors. Bonds contain a userData field that can be used to inform the user that actors should have joints created at a particular location, but it is up to the user to create and manage physical joints between two actors.
- There is no graphics representation. Just as there is no notion of collision geometry, there is also no notion of graphics geometry. The NvBlastChunk userData field (see the item above) can be used to associate graphics geometry with the actor based upon the visible chunks.
- There is no notion of threading. The API is a collection of free functions which the user may call from appropriate threads. Blast guarantees that it is safe to operate on different actors from different threads.
- There is no global memory manager, message handler, etc. All low-level API functions take an optional message function pointer argument in order to report warnings or errors. Memory is managed by the user, and functions that build objects require an appropriately-sized memory block to be passed in. A corresponding utility function that calculates the memory requirements is always present alongside such functions. Temporary storage needed by a function is always handled via user-supplied scratch space. For scratch, there is always a corresponding “RequiredScratch” function or documentation which lets the user know how much scratch space is needed based upon the function arguments.
- Backwards-compatible, versioned, device-independent serialization is not handled by Blast. There is, however, a Blast extension which does, see Serialization (NvBlastExtSerialization). However, a simple form of serialization may be performed on assets and families (see Definitions) via simple memory copy. The data associated with these objects is available to the user, and may be copied and stored by the user. Simply casting a pointer to such a block of memory to the correct object type will produce a usable object for Blast. (The only restriction is that the block must be 16-byte aligned.) Families contain a number of actors and so this form of deserialization recreates all actors in the family. This form of serialization may be used between two devices which have the same endianness, and contain Blast SDKs which use the same object format.
- Single-actor serialization and deserialization is, however, supported. This is not as light-weight as family serialization, but may be a better serialization model for a particular application. To deserialize a single actor, one must have a family to hold the actor, created from the appropriate asset. If none exists already, the user may create an empty family. After that, all actors that had been in that family may be deserialized into it one-at-a-time, in any order.
## Linking and Header Files
## To use the low-level Blast SDK
The application need only include the header NvBlast.h, found in the top-level `include` folder, and link against the appropriate version of the NvBlast library. Depending on the platform and configuration, various suffixes will be added to the library name. The general naming scheme is:
- NvBlast(config)(arch).(ext)
- (config) is DEBUG, CHECKED, OR PROFILE for the corresponding configurations. For a release configuration, there is no (config) suffix.
- (arch) is _x86 or _x64 for Windows 32- and 64-bit builds, respectively, and empty for non-Windows platforms.
- (ext) is .lib for static linking and .dll for dynamic linking on Windows.
## Creating an Asset from a Descriptor (Authoring)
The NvBlastAsset is an opaque type pointing to an object constructed by Blast in memory allocated by the user. To create an asset from a descriptor, use the function `NvBlastCreateAsset`. See the function documentation for a description of its parameters.
N.B., there are strict rules for the ordering of chunks with an asset, and also conditions on the chunks marked as “support” (using the NvBlastChunkDesc::SupportFlag). See the function documentation for these conditions. `NvBlastCreateAsset` does *not* reorder chunks or modify support flags to meet these conditions. If the conditions are not met, `NvBlastCreateAsset` fails and returns NULL. However, Blast provides helper functions to reorder chunk descriptors and modify the support flags within those descriptors so that they are valid for asset creation. The helper functions return a mapping from the original chunk ordering to the new chunk ordering, so that corresponding adjustments or mappings may be made for graphics and other data the user associates with chunks.
Example code is given below. Throughout, we assume the user has defined a logging function called `logFn`, with the signature of NvBlastLog. In all cases, the log function is optional, and NULL may be passed in its place.
```cpp
// Create chunk descriptors
std::vector<NvBlastChunkDesc> chunkDescs;
chunkDescs.resize( chunkCount ); // chunkCount > 0
chunkDescs[0].parentChunkIndex = UINT32_MAX; // invalid index denotes a chunk hierarchy root
chunkDescs[0].centroid[0] = 0.0f; // centroid position in asset-local space
chunkDescs[0].centroid[1] = 0.0f;
chunkDescs[0].centroid[2] = 0.0f;
chunkDescs[0].volume = 1.0f; // Unit volume
chunkDescs[0].flags = NvBlastChunkDesc::NoFlags;
chunkDescs[0].userData = 0; // User-supplied ID. For example, this can be the index of the chunkDesc.
// The userData can be left undefined.
chunkDescs[1].parentChunkIndex = 0; // child of chunk described by chunkDescs[0]
chunkDescs[1].centroid[0] = 2.0f; // centroid position in asset-local space
chunkDescs[1].centroid[1] = 4.0f;
chunkDescs[1].centroid[2] = 6.0f;
chunkDescs[1].volume = 1.0f; // Unit volume
chunkDescs[1].flags = NvBlastChunkDesc::SupportFlag; // This chunk should be represented in the support graph
chunkDescs[1].userData = 1;
// ... etc. for all chunks
// Create bond descriptors
std::vector<NvBlastBondDesc> bondDescs;
bondDescs.resize( bondCount ); // bondCount > 0
bondDescs[0].chunkIndices[0] = 1; // chunkIndices refer to chunk descriptor indices for support chunks
bondDescs[0].chunkIndices[1] = 2;
bondDescs[0].bond.normal[0] = 1.0f; // normal in the +x direction
bondDescs[0].bond.normal[1] = 0.0f;
bondDescs[0].bond.normal[2] = 0.0f;
bondDescs[0].bond.area = 1.0f; // unit area
bondDescs[0].bond.centroid[0] = 1.0f; // centroid position in asset-local space
bondDescs[0].bond.centroid[1] = 2.0f;
bondDescs[0].bond.centroid[2] = 3.0f;
bondDescs[0].userData = 0; // this can be used to tell the user more information about this
// bond for example to create a joint when this bond breaks
bondDescs[1].chunkIndices[0] = 1;
bondDescs[1].chunkIndices[1] = ~0; // ~0 (UINT32_MAX) is the "invalid index." This creates a world bond
// ... etc. for bondDescs[1], all other fields are filled in as usual
// ... etc. for all bonds
// Set the fields of the descriptor
NvBlastAssetDesc assetDesc;
assetDesc.chunkCount = chunkCount;
assetDesc.chunkDescs = chunkDescs.data();
assetDesc.bondCount = bondCount;
assetDesc.bondDescs = bondDescs.data();
// Now ensure the support coverage in the chunk descriptors is exact, and the chunks are correctly ordered
std::vector<char> scratch( chunkCount * sizeof(NvBlastChunkDesc) ); // This is enough scratch for both NvBlastEnsureAssetExactSupportCoverage and NvBlastReorderAssetDescChunks
NvBlastEnsureAssetExactSupportCoverage( chunkDescs.data(), chunkCount, scratch.data(), logFn );
std::vector<uint32_t> map(chunkCount); // Will be filled with a map from the original chunk descriptor order to the new one
NvBlastReorderAssetDescChunks( chunkDescs.data(), chunkCount, bondDescs.data(), bondCount, map, true, scratch.data(), logFn );
// Create the asset
scratch.resize( NvBlastGetRequiredScratchForCreateAsset( &assetDesc ) ); // Provide scratch memory for asset creation
void* mem = malloc( NvBlastGetAssetMemorySize( &assetDesc ) ); // Allocate memory for the asset object
NvBlastAsset* asset = NvBlastCreateAsset( mem, &assetDesc, scratch.data(), logFn );
```
It should be noted that the geometric information (centroid, volume, area, normal) in chunks and bonds is only used by damage shader functions. Depending on the shader, some, all, or none of the geometric information will be needed. The user may write damage shader functions that interpret this data in any way they wish.
## Cloning an Asset
To clone an asset, one only needs to copy the memory associated with the NvBlastAsset.
```cpp
uint32_t assetSize = NvBlastAssetGetSize( asset );
NvBlastAsset* newAsset = (NvBlastAsset*)malloc(assetSize); // NOTE: the memory buffer MUST be 16-byte aligned!
memcpy( newAsset, asset, assetSize ); // this data may be copied into a buffer, stored to a file, etc.
```
N.B. the comment after the malloc call above. NvBlastAsset memory **must** be 16-byte aligned.
## Releasing an Asset
Blast low-level does no internal allocation; since the memory is allocated by the user, one simply has to free the memory they’ve allocated. The asset pointer returned by NvBlastCreateAsset has the same numerical value as the mem block passed in (if the function is successful, or NULL otherwise). So releasing an asset with memory allocated by `malloc` is simply done with a call to `free`:
```cpp
free( asset );
```
## Creating Actors and Families
Actors live within a family created from asset data. To create an actor, one must first create a family. This family is used by the initial actor created from the asset, as well as all of the descendant actors created by recursively fracturing the initial actor. As with assets, family allocation is done by the user.
The family will
*not*
be automatically released when all actors within it are invalidated using NvBlastActorDeactivate. However, the user may query the number of active actors in a family using
```cpp
uint32_t actorCount = NvBlastFamilyGetActorCount( family, logFn );
```
## Damage and Fracturing
Damaging and fracturing is a staged process.
In a first step, a **NvBlastDamageProgram** creates lists of Bonds and Chunks to damage - so called Fracture Commands.
The lists are created from input specific to the NvBlastDamageProgram.<br>
NvBlastDamagePrograms are composed of a **NvBlastGraphShaderFunction** and a **NvBlastSubgraphShaderFunction** operating on support graphs (support chunks and bonds) and disconnected subsupport chunks respectively.
An implementer can freely define the shader functions and parameters.
Different functions can have the effect of emulating different physical materials.<br>
Blast provides reference implementations of such functions in **Damage Shaders (NvBlastExtShaders)**, see also NvBlastExtDamageShaders.h.
The NvBlastDamageProgram is used through **BlastActorGenerateFracture** that will provide the necessary internal data for the NvBlastActor being processed.
The shader functions see the internal data as **BlastGraphShaderActor** and **BlastSubgraphShaderActor** respectively.
The second stage is carried out with **BlastActorApplyFracture**. This function takes the previously generated Fracture Commands and applies them to the NvBlastActor.
The result of every applied command is reported as a respective Fracture Event if requested.
Fracture Commands and Fracture Events both are represented by a **NvBlastFractureBuffer**.
The splitting of the actor into child actors is not done until the third stage, **BlastActorSplit**, is called.
Fractures may be repeatedly applied to an actor before splitting.
The **NvBlastActorGenerateFracture**, **NvBlastActorApplyFracture** and **NvBlastActorSplit** functions are profiled in Profile configurations.
This is done through a pointer to a NvBlastTimers struct passed into the functions.
If this pointer is not NULL, then timing values will be accumulated in the referenced struct.
The following example illustrates the process:
```cpp
// Step one: Generate Fracture Commands
// Damage programs (shader functions), material properties and damage description relate to each other.
// Together they define how actors will break by generating the desired set of Fracture Commands for Bonds and Chunks.
NvBlastDamageProgram damageProgram = { GraphShader, SubgraphShader };
NvBlastProgramParams programParams = { damageDescs, damageDescCount, materialProperties };
// Generating the set of Fracture Commands does not modify the NvBlastActor.
NvBlastActorGenerateFracture( fractureCommands, actor, damageProgram, &programParams, logFn, &timers );
// Step two: Apply Fracture Commands
// Applying Fracture Commands does modify the state of the NvBlastActor.
// The Fracture Events report the resulting state of each Bond or Chunk involved.
// Chunks fractured hard enough will also fracture their children, creating Fracture Events for each.
NvBlastActorApplyFracture( fractureEvents, actor, fractureCommands, logFn, &timers );
// Step three: Splitting
// The Actor may be split into all its smallest pieces.
uint32_t maxNewActorCount = NvBlastActorGetMaxActorCountForSplit( actor, logFn );
std::vector<NvBlastActor*> newActors( maxNewActorCount );
// Make this memory available to NvBlastSplitEvent.
NvBlastActorSplitEvent splitEvent;
splitEvent.newActors = newActors.data();
// Some temporary memory is necessary as well.
std::vector<char> scratch( NvBlastActorGetRequiredScratchForSplit( actor, logFn ) );
// New actors created are reported in splitEvent.newActors.
// If newActorCount != 0, then the old actor is deleted and is reported in splitEvent.deletedActor.
size_t newActorCount = NvBlastActorSplit( &splitEvent, actor, maxNewActorCount, scratch.data(), logFn, &timers );
``` | 14,516 |
id2_index.md | # Execution Framework
The Omniverse ecosystem enjoys a bevy of software components (e.g. PhysX, RTX, USD, OmniGraph, etc). These software components can be assembled together to form domain specific applications and services. One of the powerful concepts of the Omniverse ecosystem is that the assembly of these components is not limited to compile time. Rather, **users** are able to assemble these components **on-the-fly** to create tailor-made tools, services, and experiences.
With this great power comes challenges. In particular, many of these software components are siloed and monolithic. Left on their own, they can starve other components from hardware resources, and introduce non-deterministic behavior into the system. Often the only way to integrate these components together was with a model “don’t call me, I’ll call you”.
For such a dynamic environment to be viable, an intermediary must be present to guide these different components in a composable way. The **Execution Framework** is this intermediary.
The Omniverse Execution Framework’s job is to orchestrate, at runtime, computation across different software components and logical application stages by decoupling the description of the compute from execution.
## Architecture Pillars
The Execution Framework (i.e. EF) has three main architecture pillars.
The first pillar is **decoupling** the authoring format from the computation back end. Multiple authoring front ends are able to populate EF’s intermediate representation (IR). EF calls this intermediate representation the [execution graph](#ef-execution-graph). Once populated by the front end, the execution graph is transformed and refined, taking into account the available hardware resources. By decoupling the authoring front end from the computation back end, developers are able to assemble software components without worrying about multiple hardware configurations. Furthermore, the decoupling allows EF to optimize the computation for the current execution environment (e.g. HyperScale).
The second pillar is **extensibility**. Extensibility allows developers to augment and extend EF’s capabilities without changes to the core library. Graph [transformations](#ef-pass-concepts), [traversals](#ef-graph-traversal-guide), [execution behavior](#ef-execution-concepts), computation logic, and [scheduling](#ef-execution-concepts) are examples of EF features that can be [extended](#ef-plugin-creation) by developers.
# Composable architecture
The third pillar of EF is **composability**. Composability is the principle of constructing novel building blocks out of existing smaller building blocks. Once constructed, these novel building blocks can be used to build yet other larger building blocks. In EF, these building blocks are nodes (i.e. `Node`).
Nodes stores two important pieces of information. The first piece they store is connectivity information to other nodes (i.e. topology edges). Second, they stores the **computation definition**. Computation definitions in EF are defined by the `NodeDef` and `NodeGraphDef` classes. `NodeDef` defines opaque computation while `NodeGraphDef` contains an entirely new graph. It is via `NodeGraphDef` that EF derives its composibility power.
The big picture of what EF is trying to do is simple: take all of the software components that wish to run, generate nodes/graphs for the computation each component wants to perform, add edges between the different software components’ nodes/graphs to define execution order, and then optimize the graph for the current execution environment. Once the **execution graph** is constructed, an **executor** traverses the graph (in parallel when possible) making sure each software component gets its chance to compute.
## Practical Examples
Let’s take a look at how Omniverse USD Composer, built with Omniverse Kit, handles the the update of the USD stage.
Kit maintains a list of extensions (i.e. software components) that either the developer or user has requested to be loaded. These extensions register callbacks into Kit to be executed at fixed points in Kit’s update loop. Using an empty scene, and USD Composer’s default extensions, the populated execution graph looks like this:
CurveManipulator
OmniSkel
SkeletonsCombo
SingletonCurveEditor
CurveCreator
AnimationGraph
Stage Recorder
SequencePlayer
PhysXCameraPrePhysics
PhysXSupportUI
PhysxInspector Before Update Physics
PhysXVehiclePrePhysics
PhysxInspector After Update Physics
UsdPhysicsUI
PhysXUI
PhysXCameraPostPhysics
PhysxInspector Debug visualization
SkelAnimationAnnotation
PhysXVehiclePostPhysics
PhysX
SceneVisualization
PhysXFabric
DebugDraw
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text414" text-anchor="middle" x="6216.4199" y="-535.79999">
WarpKernelAttach
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text432" text-anchor="middle" x="7164.7598" y="-535.79999">
FlowUsd
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text444" text-anchor="middle" x="7349.98" y="-535.79999">
PhysXStageUpdateLast
<span class="caption-text">
USD Composer's execution graph used to update the USD stage.
Notice in the picture above that each node in the graph is represented as an opaque node, except for the OmniGraph (OG) front-end. The OmniGraph node further refines the compute definition by expressing its update pipeline with *pre-simulation*, *simulation*, and *post-simulation* nodes. This would not be possible without EF’s **composable architecture**.
Below, we illustrate an example of a graph authored in OG that runs during the simulation stage of the OG pipeline. This example runs as part of Omniverse Kit, with a limited number of extensions loaded to increase the readability of the graph and to illustrate the dynamic aspect of the execution graph population.
<text font-family="Times, serif" font-size="14px" id="text759" text-anchor="middle" x="1479.3" y="-1087.4">
EXECUTION GRAPH | kit.def.execution(8412328473570437098)
<text font-family="Times, serif" font-size="14px" id="text765" text-anchor="middle" x="2137.3899" y="-778.40002">
/World/ActionGraph(1) | og.def.graph_execution(1354986524710330633)
<text font-family="Times, serif" font-size="14px" id="text771" text-anchor="middle" x="1596.3" y="-1054.4">
kit.legacyPipeline(2) | kit.def.legacyPipeline(14601541822497998125)
<text font-family="Times, serif" font-size="14px" id="text777" text-anchor="middle" x="1743.0601" y="-897.40002">
OmniGraph(2) | OmniGraphDef(13532122613264624703)
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text783" text-anchor="middle" x="138.78999" y="-844.79999">
kit.customPipeline
<text font-family="Times, serif" font-size="14px" id="text789" text-anchor="middle" x="830.34003" y="-837.40002">
og.pre_simulation(1) | og.def.pre_simulation(18371527843990822053)
<text font-family="Times, serif" font-size="14px" id="text795" text-anchor="middle" x="2008.09" y="-811.40002">
og.simulation(2) | og.def.simulation(2058752528039269071)
<text font-family="Times, serif" font-size="14px" id="text807" text-anchor="middle" x="1366.47" y="-864.40002">
og.post_simulation(3) | og.def.post_simulation(12859070463537551084)
<figure class="align-center">
<figcaption>
<p>
<span class="caption-text">
An example of the OmniGraph definition
Generating more fine-grained execution definitions allows OG to scale performance with available CPU resources. Leveraging **extensibility** allows implementation of executors for different graph types outside of the core OG library. This joined
**composability** creates a foundation for executing compound graphs.
The final example in this overview focuses on execution pipelines in Omniverse Kit. Leveraging all of the architecture pillars, we can start customizing per application (and/or per scene) execution pipelines. There is no longer a need to base execution ordering only on a fixed number or keep runtime components siloed. In the picture below, as a proof-of-concept, we define at runtime a new custom execution pipeline. This new pipeline runs before the “legacy” one ordered by a magic number and introduces fixed and variable update times. Extending the ability of OG to choose the pipeline stage in which it runs, we are able to place it anywhere in this new custom pipeline. Any other runtime component can do the same thing and leverage the EF architecture to orchestrate executions in their application.
custom.async
custom.syncMain
omni_graph_nodes_constantdouble3
CubeReadAttrib_02
on_playback_tick
og.customPipelineToUsd
make_transformation_matrix_from_trs_01
PhysX
matrix_multiply
SkelAnimationAnnotation
get_translation
<figure class="align-center">
<figcaption>
<p>
<span class="caption-text">
The customizable execution pipeline in Kit - POC
## Next Steps
Above we provided a brief overview of EF’s philosophy and capabilities. Readers are encouraged to continue learning about EF by first reviewing Graph Concepts. | 9,049 |
Imgui.md | # IMGUI
This extension adds support for setup imgui StyleColor and StyleVar on demand.
Imgui settings can be specified in `[[settings.exts."omni.app.setup".imgui]]` sections.
For example:
```toml
[settings.exts."omni.app.setup".imgui.color]
ScrollbarGrab = 0.4
ScrollbarGrabHovered = [0.1, 0.2, 0.3]
ScrollbarGrabActive = [0.4, 0.5, 0.6, 0.7]
[settings.exts."omni.app.setup".imgui.float]
DockSplitterSize = 2
```
This equals to
```c++
import carb.imgui as _imgui
imgui = _imgui.acquire_imgui()
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrab, carb.Float4(0.4, 0.4, 0.4, 1))
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabHovered, carb.Float4(0.1, 0.2, 0.3, 1))
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabActive, carb.Float4(0.4, 0.5, 0.6, 0.7))
imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2)
``` | 845 |
index.md | # omni.simready.cadtools: SimReady CAD Tools
## omni.simready.cadtools
- [Simready CAD Tools [omni.simready.cadtools]](Overview.html)
- [API (python)](API.html)
- [Changelog](Changelog.html)
- [1.0.0-alpha.1] - 2024-03-13](Changelog.html#alpha-1-2024-03-13) | 261 |
indices-and-tables_index.md | # Omni.VDB API Documentations and Tutorials
## Contents
- [Omni.VDB](README.html)
- [Extensions](source/extensions/index.html)
- [omni.vdb.neuralvdb](source/extensions/omni.vdb.neuralvdb/docs/index.html)
- [omni.vdb.tool](source/extensions/omni.vdb.tool/docs/index.html)
- [Changelog](CHANGELOG.html)
- [0.5.2] - 2024-03-07
- [0.5.1] - 2024-02-26
- [0.5.0] - 2024-02-09
- [0.4.1] - 2024-01-10
- [0.4.0] - 2023-11-14
- [0.3.7] - 2023-11-06
- [0.3.6] - 2023-10-19
- [0.3.5] - 2023-10-12
- [0.3.4] - 2023-10-10
- [0.3.3] - 2023-09-20
- [0.3.2] - 2023-08-02
## Indices and tables
- [Index](genindex.html)
- [Module Index](py-modindex.html)
- [Search Page](search.html) | 692 |
Input.md | # Carbonite Input Plugin
## Overview
Carbonite input plugin acts like an input hub, the goal is to make it easy for the input providers to register input devices and events in the input plugin and input users to consume input events or states, abstracting away the underlying mechanisms.
### Input users
Any plugin or client that only cares about consuming the inputs are called input users. Input could be consumed either by registering event listeners or directly polling the input state. Input users should use the `carb::input::IInput` interface.
The main idea behind the user interface design is to unify discrete and analog controls, and assign any type of controls to the user-specified action mapping. More information about the specifics of such unification is presented in the [Values] and [Button flags] sections, and how to set up a user-specified action mapping is described in the [Action mapping] section.
### Input states
Alternatively, it is possible to poll the input device state using functions like `carb::input::IInput::getKeyboardValue` and `carb::input::IInput::getKeyboardButtonFlags`. Similar functions are present for mouse and gamepad input devices. The difference between `get*Value` and `get*ButtonFlags` functions is in how the device button states are treated, and the reasoning behind having two types of interpretations of the same underlying input states is allowing the user to assign any kind of input state, whether it is discrete or analog, to the specific actions. For example, this approach allows to interpret gamepad analog stick as D-pad, assigning discrete actions to analog controls–e.g. analog stick driven up or trigger pressed above specified threshold, can trigger a certain menu to pop up. This works as well if a user wants to move a slider for a determined amount when a discrete keyboard key is pressed.
It is important to note, that there are two input states mapped to any single axis–negative and positive, e.g. `carb::input::MouseInput::eMoveLeft` / `carb::input::MouseInput::eMoveRight` corresponding to mouse move on the X axis, or `GamepadInput::eLeftStickLeft` / `GamepadInput::eLeftStickRight` corresponding to the same axis of a left gamepad stick–this is done for consistency and finer action mapping control; user can set up one actions on the negative stick/mouse axis move and a different one for the positive stick/mouse axis move, thus effectively turning them into d-pads. Or allow to rebind camera pitch and yaw control to the keyboard keys.
## Values
The `get*Value` functions return floating point numbers representing the current button state–for discrete device inputs (like keyboard keys, mouse or gamepad buttons) it is either 0.0 or 1.0, and for analog inputs (e.g. mouse axes or gamepad sticks) the returned number can take values between 0.0 and 1.0.
## Frames
`carb.input` transfers the current state to a previous state in the `update*()` functions: `carb::input::InputProvider::updateKeyboard`, `carb::input::InputProvider::updateMouse`, and `carb::input::InputProvider::updateGamepad`. When these functions are called it is considered the beginning of the next frame of the device.
## Button flags
The `get*ButtonFlags` functions return interpreted state flags that tell the user whether particular device input can be considered activated or deactivated for the discrete actions. It also allows callers to distinguish between states when the input was just activated/deactivated, or if they were in that particular state for more than one frame. In other words, mouse button could be just pressed or is held for a while. List describing flags combination and their meaning:
1. `carb::input::kButtonFlagStateUp`: Button is up and was up on a previous frame–basically a default, “null” state.
2. `kButtonFlagStateUp | kButtonFlagTransitionUp`: Button is up, but was just released (i.e. on the previous “frame” it was down)–for the single-time events which typically go on the `onMouseButtonPress`
3. `carb::input::kButtonFlagStateDown`: Button is down, and was down on a previous frame–for the cases when you make the action while the button is pressed (think drawing using pencil in paint or dragging something).
4. `kButtonFlagStateDown | kButtonFlagTransitionDown`: Button is down, but was just pressed (i.e. on the previous “frame” it was up)–for the cases when you need to set some state only once per button down event.
Button flags expressed this way decrease user-side code verbosity and improve usability versus other approaches. For example, if button flags were expressed as four distinct states: `Held`, `Up`, `Pressed`, `Released` – if user only cares about the case when the device input is in the “down” state, the code becomes:
```c++
if (input->getMouseButtonFlags(mouse, MouseInput::eLeftButton) == kButtonFlagPressed ||
input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftButton) == kButtonFlagHeld)
```
i.e. it is now required to check for both `Held` and `Pressed` states, because both mean that the actual state is `Down`. With the button flags approach, it is easy to check for the mouse down event:
```c++
if (input->getMouseButtonFlags(mouse, MouseInput::eLeftButton) & kButtonFlagStateDown)
```
## Input events
### Input events
carb::input::IInput interface provides ways to subscribe and unsubscribe to the input event streams with functions like carb::input::IInput::subscribeToKeyboardEvents / carb::input::IInput::unsubscribeToKeyboardEvents (similar events present for mouse and gamepads).
## Action mapping
### Action mapping
User interface for the input plugin allows to assign any kind of device input to a named action. Each named action can have several device inputs assigned to it. Actions support both state polling and event subscription, similar to the regular device inputs: carb::input::IInput::getActionValue returns floating point value for the named action, carb::input::IInput::getActionButtonFlags returns discrete button flag, and carb::input::IInput::subscribeToActionEvents / carb::input::IInput::unsubscribeToActionEvents allow to manage named action event stream subscriptions.
In case when several inputs are assigned, a prioritizing logic determines the exact action value or flag. Typically, when queried for the continuous action value, maximum absolute value of the assigned inputs is determined–i.e. if two axes of different sticks are assigned to the same action, the stick with maximum deviation from the initial state is prioritized. Alternatively, when queried for the discrete action flag, the following logic determines the prioritized button flag (in the order of decreasing priority):
1. The device input is “held” for some time.
2. The device input was just “pressed”.
3. The device input was just “released”.
4. The device input is in idle state.
This list of priorities for the button flag was designed to make sure that different device inputs assigned to the same action do not conflict with each other–for example if two inputs assigned to the same action were “held”, and then one of the inputs gets released, the action is not interrupted.
**NOTE**: the prioritization logic described is only a recommendation for the input plugin implementation, and is true for the default Carbonite input plugin (carb.input.plugin). Other input plugin implementations may implement different logic to determine action flags or values.
## Input providers
### Input providers
Plugins that aim to feed the input events and states use carb::input::InputProvider interface. | 7,549 |
installing_launcher.md | # Installing Launcher
Please watch the following video for instructions on installing Omniverse Launcher.
## Administrator Rights
Local Admin Rights on the installed computer is recommended for full use and capability of the Omniverse Launcher. Though the launcher will install without admin rights, some tools, connectors, apps, etc. may require admin rights (UAC) to complete the installation.
## First Run
When first running the launcher after install, you will be presented with a series of options.
### Data Collection
Users must agree to allow NVIDIA to collect data regarding usage of the Omniverse Platform.
### Paths
Next you will be presented with a series of path selections.
#### Option
| Option | Description |
|--------------|-----------------------------------------------------------------------------|
| Library Path | This location specifies where apps, connectors and tools are installed when installed from Launcher. |
| Data Path | Displays and allows selection of the Data Path. The data path is where all content on the local Nucleus is stored. |
| Cache Path | This is the location the Cache Database will use to store its cache files. (if installed) |
### Install cache
Though Omniverse Cache is optional, it is highly recommended for users who plan to collaborate with other Omniverse users on your network. This option does require Administrator Privileges on the installed machine and can be installed at a later time if necessary.
Once the installation is complete, please refer to the [User Guide](workstation-launcher.html) for additional help and information on using Launcher. | 1,698 |
install_guide_linux.md | # Installation on Linux
## Prerequisites for Installation
There are two elements that you need to have prior to starting the installation process. Both components are available within the NVIDIA Licensing Portal (NLP).
It’s important to note that the entitlements themselves are provided to the person at the company who makes the purchase, and that person can add others (including the IT Managers) to the Licensing Portal so that they can grab the components listed below. You can read more about this process as part of [Enterprise Quick Start Guide](https://docs.omniverse.nvidia.com/enterprise/latest/enterprise_quickstart-guide.html).
- **Download the IT Managed Launcher Installer.**
- (.AppImage) AppImage since you’re running Linux
- Your Organization Name Identifier (org-name).
To find the IT Managed Launcher executable on the NLP:
1. Once you’ve logged into the Portal, go to the Software Downloads section and look for the NVIDIA Omniverse IT Managed Launcher for your platform of choice (Linux in this case).
2. Click Download to initiate the download process of the installer.
**Note**
Once the installer is downloaded, you should place it onto your designated staging hardware inside of your company firewall.
Next you’ll grab your Organization’s Name Identifier (org-name).
1. To do this, at the top of the portal, hover your mouse over your user account until you see a **View Settings** message pop up. (See image below)
2. Within the resulting My Info dialog, under the Organization area, you will see an **org-name** section. The information that is presented there represents your Organization Name and will be required later.
**View Settings:**
![nlp_license_setting](_images/nlp_license_setting.png)
Be sure to capture this information **before** you begin the installation process. You will need it to install the IT Managed Launcher as well as configure your enterprise enablement.
**Organization Name**
![nlp_cust_id](_images/nlp_cust_id.png)
Once you have this information, it’s time to install the **IT Managed Launcher**.
There are two ways to install the IT Managed Launcher on Linux.
- **Manually**: You can install the Launcher manually on a user’s workstation directly (e.g. Terminal / Bash)
- **Deployment**: You can pre-configure the Launcher to be installed as part of a deployment software strategy (e.g. SaltStack).
## Terminal / Bash
### Deploying Launcher
To install the IT Managed Launcher on Linux (Ubuntu 20.04 and 22.04), follow these steps:
Run the IT Managed Launcher by launching the AppImage you downloaded from the Licensing Portal locally on users workstations.
#### Important
On Linux, instead of running the IT Managed Launcher installer, you first need to set the AppImage as an **executable program** and launch it. This will register the app as the default handler for `omniverse-launcher://` custom URLs described elsewhere in this document that installs the applications themselves.
For Ubuntu users, make sure you have done the following so that the AppImage will launch.
From the Terminal, first run:
```
> sudo apt install libfuse2
```
Then make sure you check the permissions of the downloaded AppImage file to verify that it can be run as a program.
Using the UI, right-click on the AppImage and choose Properties. Go to the Permissions section and ensure that the Allow executing file as program checkbox is checked.
Or, from the Terminal, in the directory where the AppImage was saved:
```
> chmod +x omniverse-launcher-linux-enterprise.AppImage
```
Once those items are completed, you should be able to double-click on the AppImage package and have it run. Or, run it from the Terminal:
```
> ./omniverse-launcher-linux-enterprise.AppImage
```
### Setting up TOML Files
( Learn more about TOML syntax: https://toml.io/en/ )
1) When the AppImage launches, you’ll immediately be prompted to set a number of default locations for Omniverse. These paths determine where Omniverse will place the installed applications (Library Path), data files (Data Path), content files (Content Path) and Cache information.
All of the paths set here will be recorded and stored within an `omniverse.toml` file for later editing as needed. It’s important to note that all of the paths can be changed as per preference and/or IT Policy at a later time. By default, the installer takes all of your path preferences and stores them in the following folder structure:
```
~/Home/.nvidia-omniverse/config
```
2) Once you’ve set the default paths for Omniverse to use, click on the **Continue Button**.
You should now be presented with a blank Library window inside of the launcher.
3) Close the IT Managed Launcher.
At this point, the IT Managed Launcher is installed. However, before you start to install Omniverse applications, you’ll need to add two additional, important configuration files.
When you look at the default configuration location in Linux (`~/Home/.nvidia-omniverse/config`), you should see the `omniverse.toml` file that the installer added as shown below.
This `omniverse.toml` file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step 1. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
```
[paths]
library_root = "/home/myuser/.local/share/ov/pkg" # Path where to install all applications
data_root = "/home/myuser/.local/share/ov/data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "/home/myuser/.cache/ov" # Folder where Omniverse apps store their cache and temporary files
logs_root = "/home/myuser/.nvidia-omniverse/logs" # Folder where Launcher and Omniverse apps store their logs
extension_root = /home/myuser/Documents/kit/shared/exts # Folder where all Omniverse shared extensions are stored
content_root = "/home/myuser/Downloads" # Folder where Launcher saves downloaded content packs
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
#### Note
If a system administrator doesn’t want to allow users to change these paths, the omniverse.toml file can be marked as read-only.
Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like `~/Home/Shared` on Linux, they need to specify a shared folder for `library_root` and `logs_root` path in the `omniverse.toml` file.
```
```toml
omniverse.toml
```
```code
file.
```
```markdown
You’re now going to add two additional files to this
```code
/config
```
folder in addition to the
```code
omniverse.toml
```
file.
```
```markdown
- ```code
privacy.toml
```
file to record consent choices for data collection and capture of crash logs.
- ```code
license.toml
```
to provide your license details.
```
```markdown
**Important**
By opting into telemetry, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this section.
```
```markdown
**4)**
Within the /config folder, create a text file named privacy.toml, which is the configuration file for Omniverse telemetry. Within this privacy file, specify the following:
```
```toml
[privacy]
performance = true
personalization = true
usage = true
```
```markdown
Once this file contains these four lines, save the file.
```
```markdown
**Note**
If your IT or Security Policy prohibits the collection of telemetry, set all of these values to **false**.
```
```markdown
**5)**
For the last file needed in this folder, create a text file named license.toml, which is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the Licensing Portal:
```
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
```markdown
Once this file contains these two lines, save the file.
```
```markdown
When you’ve completed these steps, your ```code
~/Home/.nvidia-omniverse/config
``` folder should have the directory and ```code
.toml
``` files like the screenshot below:
```
```markdown
That completes the IT Managed Launcher installation for Linux and Omniverse applications can now be installed to users’ workstations.
```
```markdown
**Setting Up Packages**
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
```
```markdown
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
```
```markdown
**1)**
To begin, log into the Omniverse Enterprise Web Portal.
```
```markdown
**2)**
In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
```
```markdown
**3)**
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
```
```markdown
- **Beta**
- Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production.
- **Release**
- Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production.
- **Enterprise**
- Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software.
```
```markdown
**4)**
Select a package version in the dropdown list and click **Download**.
```
```markdown
**5)**
Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation’s OS.
```
## Deploying the Apps
Installation of the Omniverse applications is handled via a custom protocol URL on the user’s machine or using a deployment framework like SaltStack to manage the process and trigger the IT Managed Launcher to run and install the chosen application.
The most basic way to install Omniverse foundation applications is to open a custom protocol URL directly on the user’s machine. The simple command below will trigger the IT Managed Launcher to run the installation routine for the given Omniverse application .zip archive.
The format of the custom protocol can vary depending on the command line interface used, but as a general rule of thumb, the settings are as follows:
```
omniverse-launcher://install?path=<package.zip>
```
Where `<package.zip>` represents the name and path where the downloaded application archive is on the local workstation. Be aware that it does not matter where you place the archive, the custom protocol will install the application to its default location based on the `library_root` path in the `omniverse.toml` file that you configured earlier as part of the IT Managed Launcher installation process.
Example:
```
xdg-open omniverse-launcher://install?path=/var/packages/usd_explorer.zip
```
When the command is run, it will trigger the IT Managed Launcher to open and it will begin the installation process. You should see a screen similar to the one below that shows the progress bar for the application being installed in the upper right of the Launcher window.
Once the installation is complete, the Omniverse application will appear in the **Library** section of the Launcher window and these steps can be repeated for any additional applications you want to make available to your users.
## SaltStack
To deploy the IT Managed Launcher executable file to users’ Linux workstations you will need to perform several tasks.
You’ll need to download and stage the IT Managed Launcher .AppImage file and place it on the Salt master under the file storage location listed under `files_roots` in `/etc/salt/master`. For example:
```
file_roots:
base:
- /srv/salt
```
Next, you’ll create and pre-configure a user’s `omniverse.toml`, `policy.toml`, and `license.toml` files and stage them in the same shared network location.
After that, you’ll create an `omniverse.SLS` template Salt file to control the installation process and reference `.toml` files you’ve set up.
Finally, you’ll configure the `top.sls` Salt file within the Windows Local Group Policy to execute at user logon to trigger the installation and configuration of the IT Managed Launcher for the user on their local workstation.
As per the prerequisite section of this document, you should have already downloaded the Linux version of the IT Managed Launcher install file from the **Enterprise Web Portal**. If not, please do that first and place it in the Salt master under the file storage location as described above.
### Setting up TOML Files
The first step is to create and stage the three `.toml` files for deployment.
**omniverse.toml**: Copy the following information into a new text document, replacing the path information with the location you want Omniverse and its data installed on each user’s workstation. Once done, save it to the Salt master file storage location (`/srv/salt`).
```
[paths]
library_root = "/home/myuser/.local/share/ov/pkg" # Path where to install all applications
data_root = "/home/myuser/.local/share/ov/data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "/home/myuser/.cache/ov" # Folder where Omniverse apps store their cache and temporary files
logs_root = "/home/myuser/.nvidia-omniverse/logs" # Folder where Launcher and Omniverse apps store their logs
extension_root = /home/myuser/Documents/kit/shared/exts # Folder where all Omniverse shared extensions are stored
content_root = "/home/myuser/Downloads" # Folder where Launcher saves downloaded content packs
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
Where `/myuser/` represents the local user’s account.
- **privacy.toml**: Copy the following information into a new text document. This is the configuration file for Omniverse telemetry capture for each user’s workstation. Once done, save it to the Salt master file storage location (`/srv/salt`).
```toml
[privacy]
performance = true
personalization = true
usage = true
```
- **Note**: If your IT or Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to **false**.
- **license.toml**: This is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the Licensing Portal in the prerequisites section. Once done, save it to the staging location (`/srv/salt`).
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
- Once you’ve saved all three `.toml` files, it’s time to build the script file that will be used to help deploy the files to each user’s workstation.
## Deploying Launcher
1. Create a new `omniverse.SLS` Salt template in `/srv/salt` with the following information:
```yaml
omniverse_enterprise_launcher:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/launcher.AppImage
- source: salt://Launcher.AppImage
omniverse_config_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/omniverse.toml
- source: salt://omniverse.toml
omniverse_privacy_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/privacy.toml
- source: salt://privacy.toml
omniverse_license_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/license.toml
- source: salt://license.toml
omniverse_dirs:
file.directory:
- user: ubuntu
- group: ubuntu
- mode: 777
- names:
- /home/ubuntu/Omniverse
- /home/ubuntu/Omniverse/logs
- /home/ubuntu/Omniverse/data
- /home/ubuntu/Omniverse/cache
- /home/ubuntu/.nvidia-omniverse/logs
```
2. With that ready, you now need to add this omniverse template to your top.sls file.
```yaml
base:
'omni*': # All minions with a minion_id that begins with "omni"
- omniverse
```
3. Apply the Salt state: `salt 'omni*' state.apply`
4. When the user logs into their desktop, have them run `./Omniverse/launcher.AppImage` from a terminal. This will open the **IT Managed Launcher**.
## Setting up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
1. To begin, log into the Omniverse Enterprise Web Portal.
2. In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
- **Beta**: Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production.
- **Release**: Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production.
- **Enterprise**: Enterprise builds are the most stable and secure builds, optimized for large-scale deployments.
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
|-----------|------------------------------------------------------------------------------------------------------------------------|
**3)** Select a package version in the dropdown list and click **Download**.
**4)** Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
**5)** Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
## Deploying the Apps
**1)** To deploy usd_explorer in your SaltStack, update your `omniverse.SLS` Salt template in `/srv/salt` to include the following information:
```text
omniverse_enterprise_launcher:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/launcher.AppImage
- source: salt://Launcher.AppImage
omniverse_usd_explorer_zip:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/usd_explorer.zip
- source: salt://usd_explorer.zip
omniverse_config_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/omniverse.toml
- source: salt://omniverse.toml
omniverse_privacy_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/privacy.toml
- source: salt://privacy.toml
omniverse_license_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/license.toml
- source: salt://license.toml
omniverse_dirs:
file.directory:
- user: ubuntu
- group: ubuntu
- mode: 777
- names:
- /home/ubuntu/Omniverse
- /home/ubuntu/Omniverse/logs
- /home/ubuntu/Omniverse/data
- /home/ubuntu/Omniverse/cache
- /home/ubuntu/.nvidia-omniverse/logs
```
**2)** Apply the Salt state: `salt ‘omni*’ state.apply`.
**3)** When the user logs in to the desktop, have them run:
```text
> ./Omniverse/launcher.AppImage
```
This will open the launcher.
**4)** From a separate terminal, have them run:
```text
> xdg-open omniverse-launcher://install?path=./Omniverse/code.zip
```
When it completes, they will have the code extension installed in their launcher. | 21,072 |
install_guide_win.md | # Installation on Windows
## Prerequisites for Installation
There are two elements that you need to have prior to starting the installation process. Both components are available within the NVIDIA Licensing Portal (NLP).
It’s important to note that the entitlements themselves are provided to the person at the company who makes the purchase, and that person can add others (including the IT Managers) to the Licensing Portal so that they can grab the components listed below. You can read more about this process as part of our Enterprise Quick Start Guide.
- **Download the IT Managed Launcher Installer.**
- (.exe) Executable since you’re running Windows.
- Your Organization Name Identifier (org-name).
To find the IT Managed Launcher executable on the NLP:
1. Once you’ve logged into the Portal, go to the Software Downloads section (left nav) and look for the NVIDIA Omniverse IT Managed Launcher for your platform of choice (Windows in this case).
2. Click Download to initiate the download process of the installer.
**Note**
Once the installer is downloaded, you should place it onto your designated staging hardware inside of your company firewall.
Next you’ll grab your Organization’s Name Identifier (org-name).
1. To do this, at the top of the portal, hover your mouse over your user account until you see a **View Settings** message pop up. (See image below)
2. Within the resulting My Info dialog, under the Organization area, you will see an **org-name** section. The information that is presented there represents your Organization Name and will be required later.
**View Settings:**
![nlp_license_setting](_images/nlp_license_setting.png)
Be sure to capture this information **before** you begin the installation process. You will need it to install the IT Managed Launcher as well as configure your enterprise enablement.
**Organization Name**
![nlp_cust_id](_images/nlp_cust_id.png)
Once you have this information, it’s time to install the **IT Managed Launcher**.
There are two ways to install the IT Managed Launcher on Windows:
- **Manually**: You can install the Launcher manually on a user’s workstation directly (e.g. using CMD or PowerShell).
- **Deployment**: You can pre-configure the Launcher to be installed as part of a deployment software strategy (e.g. SCCM / Group Policy)
## PowerShell
### Deploying Launcher
1. Run the IT Managed Launcher installer you downloaded from the Licensing Portal locally on a user’s workstation. This can be done in the UI by double-clicking `omniverse-launcher-win-enterprise.exe` or via the PowerShell terminal, by typing:
```
./omniverse-launcher-win-enterprise.exe
```
2. Follow the prompts until the installer finishes. At the end of the install process, the option to immediately run the IT Managed Launcher will be checked by default.
3. Leave that option checked, then click **Finish** to finish the install process.
**Note:**
You can install the IT Managed Launcher silently by adding the /S parameter to the end of the filename. Example:
```
./omniverse-launcher-win-enterprise.exe /S
```
**Note:**
You can install the IT Managed Launcher to a specific location by adding the /D parameter to the end of the filename. Example:
```
./omniverse-launcher-win-enterprise.exe /S /D="C:\Program Files\NVIDIA Corporation\NVIDIA Omniverse Launcher"
```
### Setting Up TOML Files
(Learn more about TOML syntax: https://toml.io/en/)
**1)** When the IT Managed Launcher first opens, you’ll immediately be prompted to set a number of default locations for Omniverse data. These paths determine where Omniverse will place the installed applications (Library Path), data files (Data Path), content files (Content Path) and Cache information.
All of the paths set here will be recorded and stored within an `omniverse.toml` file for later editing as needed. It’s important to note that all of the paths set here can be changed as per preference and IT Policy at a later time. By default, the installer takes all of these path preferences and stores them in the omniverse.toml under the following folder structure:
```
c:\Users\[username]\.nvidia-omniverse\config
```
Where **[username]** represents the local user’s account.
**2)** Once you’ve set the default paths for Omniverse to use, click on the **Continue Button**.
You should now be presented with a blank Library window inside of the launcher.
**3)** Close the IT Managed Launcher.
At this point, the IT Managed Launcher is installed. However, before you start to install Omniverse applications, you’ll need to add two additional, important configuration files.
When you look at the default configuration location in Windows (`c:\Users\[username]\.nvidia-omniverse\config`), you should see the `omniverse.toml` file that the installer added as shown below.
This `omniverse.toml` file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step **1**. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
```
[paths]
library_root = "C:\\Omniverse\\library" # Path where to install all Omniverse applications
data_root = "C:\\Omniverse\\data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "C:\\Omniverse\\cache" # Folder where Omniverse apps store their cache and temporary files
logs_root = "C:\\Users\\[username]\\.nvidia-omniverse\\logs" # Folder where Launcher and Omniverse apps store their logs
content_root = “C:\\Users\\[username]\\Downloads” # Folder where Launcher saves downloaded content packs
extension_root = “C:\\Users\\[username]\\Documents\\kit\\shared\\exts” # Folder where all Omniverse shared extensions are stored
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
**Important:**
Also be aware that all paths on Windows require a **double backslash** (\) for proper operation.
**Note:**
If a system administrator doesn’t want to allow users to change these paths, the `omniverse.toml` file can be marked as read-only. Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like Program Files on Windows, they need to specify a shared folder for **library_root** and logs_root path in `omniverse.toml`.
# Setting Up the IT Managed Launcher
You’re now going to add two additional files to this `/config` folder in addition to the `omniverse.toml` file.
- `privacy.toml` file to record consent choices for data collection and capture of crash logs.
- `license.toml` to provide your license details.
## Note
When creating or editing these configuration files, use a text editor such as Windows Notepad. Do **not** use a rich-text editor such as **Wordpad** or **Microsoft Word**.
## Important
By opting into telemetry within the privacy.toml, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this section.
**4)** Within the `/config` folder, create a text file named `privacy.toml`. This is the configuration file for Omniverse telemetry. Within this privacy file, copy the following information:
```toml
[privacy]
performance = true
personalization = true
usage = true
```
Once this file contains these four lines, save the file.
## Note
If your IT or Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to false.
**5)** For the last file needed in your `/config` folder, create a text file named `license.toml`. This is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the **Licensing Portal** in the prerequisites section:
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
Once this file contains these two lines, save the file.
Once you’ve completed these steps, your `/.nvidia-omniverse/config` folder should have the directory and required .toml files.
That completes the IT Managed Launcher manual installation for Windows and Omniverse applications can now be installed to users’ workstations.
# Setting Up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
**1)** To begin, log into the Omniverse Enterprise Web Portal.
**2)** In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
**3)** Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
| Release Type | Description |
|--------------|-------------|
| Beta | Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production. |
| Release | Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production. |
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
**4)** Select a package version in the dropdown list and click **Download**.
## Downloading the Apps
5) Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
6) Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
## Deploying the Apps
The most basic way to install Omniverse foundation applications is to open a custom protocol URL directly on the user’s machine. The simple command below will trigger the IT Managed Launcher to run the installation routine for the given Omniverse application .zip archive.
The format of the custom protocol can vary depending on the command line interface used, but as a general rule of thumb, the settings are as follows:
omniverse-launcher://install?path=<package.zip>
```
Where `<package.zip>` represents the name and path where the downloaded application archive is on the local workstation. Be aware that it does not matter where you place the archive, the custom protocol will install the application to its default location based on the `library_root` path in the `omniverse.toml` file that you configured earlier as part of the IT Managed Launcher installation process.
Example:
```markdown
start omniverse-launcher://install?path=C:/temp/usd_explorer.zip
```
Example:
```markdown
start omniverse-launcher://install?path=//Mainframe/temp/usd_explorer.zip
```
When the command is run, it will trigger the IT Managed Launcher to open and it will begin the installation process. You should see a screen similar to the one below that shows the progress bar for the application being installed in the upper right of the Launcher window.
Once the installation is complete, the Omniverse application will appear in the **Library** section of the Launcher window and these steps can be repeated for any additional applications you want to make available to your users.
## SCCM
To deploy the IT Managed Launcher executable file to users’ Windows workstations you will need to perform several tasks.
- You’ll need to download and stage the IT Managed Launcher .EXE file to a shared network location inside your firewall that all of the users’ workstations can see and access.
- Next, you’ll create and pre-configure a user’s `omniverse.toml`, `policy.toml`, and `license.toml` files and stage them in the same shared network location.
- After that, you’ll create a .bat file to control the installation process and reference .toml files you’ve set up.
- Finally, you’ll configure another .bat file within the Windows Local Group Policy to execute at user logon to trigger the installation and configuration of the IT Managed Launcher for the user on their local workstation.
As per the prerequisite section of this document, you should have already downloaded the Windows version of the IT Managed Launcher install file from the **Enterprise Web Portal**. If not, please do that first.
### Setting up TOML Files
(Learn more about TOML syntax: https://toml.io/en/)
The first step is to create and stage the three **.toml** files for deployment.
- `omniverse.toml`: Copy the following information into a new text document, replacing the path information with the location you want Omniverse and its data installed on each user’s workstation. Once done, save it to the staging location.
```toml
[paths]
library_root = "C:\\Omniverse\\library" # Path where to install all Omniverse applications
data_root = "C:\\Omniverse\\data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "C:\\Omniverse\\cache" # Folder where Omniverse apps store their cache and temporary files
logs_root = "C:\\Users\\[username]\\.nvidia-omniverse\\logs" # Folder where Launcher and Omniverse apps store their logs
content_root = "C:\\Users\\[username]\\Downloads" # Folder where Launcher saves downloaded content packs
extension_root = "C:\\Users\\[username]\\Documents\\kit\\shared\\exts" # Folder where all Omniverse shared extensions are stored
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
| Path | Description |
| --- | --- |
| library_root = “C:\Omniverse\library” | Path where to install all Omniverse applications |
| data_root = “C:\Omniverse\data” | Folder where Launcher and Omniverse apps store their data files |
| cache_root = “C:\Omniverse\cache” | Folder where Omniverse apps store their cache and temporary files |
| logs_root = “C:\Users\[username]\.nvidia-omniverse\logs” | Folder where Launcher and Omniverse apps store their logs |
| content_root = “C:\Users\[username]\Downloads” | Folder where Launcher saves downloaded content packs |
| extension_root = “C:\Users\[username]\Documents\kit\shared\exts” | Folder where all Omniverse shared extensions are stored |
| confirmed = true | Confirmation that all paths are set correctly, must be set to `true` |
### Important
Also be aware that all paths on Windows require a double backslash (\) for proper operation.
- `privacy.toml`: Copy the following information into a new text document. This is the configuration file for Omniverse telemetry capture for each user’s workstation. Once done, save it to the staging location.
```toml
[privacy]
performance = true
personalization = true
usage = true
```
### Note
If your Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to **false**.
- `license.toml`: This is the licensing configuration file for Omniverse. Within this licensing file, specify the Organization Name Identifier (org-name) you retrieved from the Licensing Portal in the prerequisites section. Once done, save it to the staging location.
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
Once you’ve saved all three `.toml` files, it’s time to build a .bat file that will be used to help deploy the files to each user’s workstation.
## Deploying Launcher
1) Create a new .bat file (you can name the file as needed, e.g. `deployment-omniverse.bat`). In that batch file, add the following information:
```bat
@echo off
SETLOCAL EnableDelayedExpansion
set CONFIG_PATH=%USERPROFILE%\.nvidia-omniverse\config\
set INSTALL_PATH=%ProgramFiles%\NVIDIA Corporation\NVIDIA Omniverse Launcher\
set SCRIPT_PATH=%~dp0
set REG_QUERY=Reg Query "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ddd216ee-cf6c-55b0-9ca8-733b2ef622a0" /v "DisplayName"
:CONFIGURATION
:: Test for existing omniverse.toml config file.
if exist "%CONFIG_PATH%\omniverse.toml" GOTO INSTALLLAUNCHER
:: Copy.toml files to user's configuration.
xcopy /y "%SCRIPT_PATH%\omniverse.toml" "%CONFIG_PATH%"
xcopy /y "%SCRIPT_PATH%\privacy.toml" "%CONFIG_PATH%"
xcopy /y "%SCRIPT_PATH%\license.toml" "%CONFIG_PATH%"
:: Substitute [username] with %USERNAME%.
del "%CONFIG_PATH%\omniverse.txt" 2>NUL
for /f "usebackq tokens=*" %%a in ("%CONFIG_PATH%\omniverse.toml") do (
set LINE=%%a
set LINE=!LINE:[username]=%USERNAME%!
echo !LINE! >> "%CONFIG_PATH%\omniverse.txt"
)
```
```shell
del "%CONFIG_PATH%\omniverse.toml" 2>NUL
ren "%CONFIG_PATH%\omniverse.txt" "omniverse.toml"
:: Set the readonly flag to prevent users from changing the configured paths
attrib +r "%CONFIG_PATH%"\*.toml
::INSTALLLAUNCHER
:: Test if Launcher is already installed.
%REG_QUERY% 1>NUL 2>&1
if %ERRORLEVEL%==0 GOTO STARTLAUNCHER
:: Run the installer and wait until Launcher is installed (silent).
start /WAIT %SCRIPT_PATH%\omniverse-launcher-win-enterprise.exe /S /D="%INSTALL_PATH%"
::STARTLAUNCHER
:: Start the Launcher.
start "" "%INSTALL_PATH%\NVIDIA Omniverse Launcher.exe"
timeout /T 5 1>NUL 2>&1
::END
ENDLOCAL
```
- The .bat script above copies the .toml files and installs Launcher.
- All files must be located in the root directory of the script. (.toml / omniverse-launcher-win-enterprise.exe).
- Install into a public folder, example C:NVIDIA.
**2)** Save this file to the same location as the pre-configured .toml files on the staging hardware.
In order to run the .bat file as part of a deployment strategy, you need to set up a local group policy for your users’ workstations.
**3)** Open the Local Group Policy Editor on the GPO manager machine.
**4)** Double-click to choose **Logon**.
**5)** From the Logon Properties dialog, choose **Add**.
**6)** Then point to the .bat file you created earlier and click **OK**.
The file should appear in the Logon Properties dialog.
**7)** Click OK to close the dialog
**8)** The scripts will run on the remote machines during the next Logon.
## Setting Up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
**1)** To begin, log into the Omniverse Enterprise Web Portal.
**2)** In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
| Release | Description |
|---------|-------------|
| Beta | Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production. |
| Release | Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production. |
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
**3)** Select a package version in the dropdown list and click **Download**.
**4)** Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
**5)** Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
# 部署 Omniverse 应用到用户 Windows 工作站
## 步骤概览
1. 下载并准备 Omniverse 应用的 .zip 文件到内部网络共享位置。
2. 创建一个 .bat 文件来控制下载的安装过程。
3. 配置另一个 .bat 文件,通过 Windows 本地组策略在用户登录时触发安装和配置。
## 详细步骤
### 下载和准备
根据本文件的前提条件部分,您应该已经从 **企业网络门户** 下载了每个要部署的 Omniverse 应用的 Windows .zip 文件。如果没有,请先进行下载。
### 创建安装脚本
下一步是创建处理本地用户工作站安装过程的 .bat 文件。
#### 步骤 1
创建一个新的 .bat 文件用于应用安装(您可以根据需要命名文件,例如 deploy_OV<AppName>.bat)。在该批处理文件中,添加以下信息:
```bat
@echo off
SETLOCAL EnableDelayedExpansion
set CONFIG_PATH=%USERPROFILE%\.nvidia-omniverse\config\
set SCRIPT_PATH=%~dp0
:INSTALLAPPS
:: Find library_root from omniverse.toml
for /f "usebackq tokens=*" %%a in ("%CONFIG_PATH%\omniverse.toml") do (
set LINE=%%a
echo !LINE!|find "library_root" 1>NUL 2>&1
if !ERRORLEVEL!==0 (
for /f tokens^=^2^ delims^=^" %%i in ("!LINE!") do set LIBRARY_ROOT_PATH=%%i
set LIBRARY_ROOT_PATH=!LIBRARY_ROOT_PATH:\\=\!
)
)
:: Find .zip files
for /f "tokens=*" %%a in ('dir /B "%SCRIPT_PATH%\*.zip"') do (
set ZIP_FILE=%%a
set ZIP_FILE_SUB=!ZIP_FILE:.windows-x86_64-ent-package.zip=!
:: Check if ZIP_FILE_SUB is a folder in LIBRARY_ROOT_PATH. If not, install.
dir /B "!LIBRARY_ROOT_PATH!"| findstr "!ZIP_FILE_SUB!" 1>NUL 2>&1
if !ERRORLEVEL!==1 (
start omniverse-launcher://install?path="%SCRIPT_PATH%\!ZIP_FILE!"
timeout /T 600 1>NUL 2>&1
)
)
:END
ENDLOCAL
```
您可以串联尽可能多的自定义协议命令来安装所有您想要安装的 Omniverse 应用。
### 注意事项
您也可以选择将此信息添加到用于安装 IT 管理启动器的现有 .bat 文件中。
### 安装要求
- 上述 .bat 脚本从 .zip 文件安装应用。
- 所有文件必须位于脚本的根目录中(例如 “App”.zip)。
- 安装到之前安装启动器的同一目录。
### 配置组策略
#### 步骤 2
将此 .bat 文件保存到暂存硬件。
#### 步骤 3
在 GPO 管理机器上打开本地组策略编辑器。
#### 步骤 4
双击选择登录。
#### 步骤 5
在登录属性对话框中选择添加。
#### 步骤 6
指向您之前创建的 .bat 文件并点击确定。
#### 步骤 7
点击确定关闭对话框。
#### 步骤 8
脚本将在下次登录时在远程机器上运行。 | 22,451 |
intro.md | # Getting Started
## What is Slang
Slang is a shading language backward compatible with HLSL that makes it easier to build and maintain large shader codebases in a modular and extensible fashion, while also maintaining the highest possible performance on modern GPUs and graphics APIs. Slang is based on years of collaboration between researchers at NVIDIA, Carnegie Mellon University, and Stanford.
For better understanding of language usage and features, please refer to the User’s Guide provided by Slang developers.
## What is Slang Node
Slang nodes can be placed in all types of OmniGraph. Slang node, when executed, runs a compute Slang function. Node’s *input*, *output*, and *state* attributes define variables that can be referenced in the Slang code. The code of the node’s function can be edited in the Code editor and is saved in the USDA file as a node’s token attribute.
The current implementation only runs the Slang code single-threaded on the CPU target. Multithreaded and GPU support will be added in future releases.
## When should I use Slang Node
The node allows users to write their own functions executed in OmniGraph. Slang code is compiled once during the stage load or on user request in the Code Editor. The node execution does not bring any additional overhead during the OmniGraph updates.
Detail usage of the Slang node is covered in the tutorial How to use Slang node in OmniGraph.
## Future work
1. Multithreading and GPU target support
2. COM interface support to allow C++ functions callbacks from Slang code
3. Code editor UX improvements | 1,584 |
introduction_index.md | # Omni Asset Validator (Tutorial)
## Introduction
The `Omniverse Asset Validator` is an extensible framework to validate [USD](https://graphics.pixar.com/usd/release/index.html). Initially inspired from [Pixar Compliance Checker](https://graphics.pixar.com/usd/release/toolset.html#usdchecker), it extends upon these ideas and adds more validation rules applicable throughout Omniverse, as well as adding the ability to automatically fix issues.
Currently, there are two main components:
1. [Omni Asset Validator (Core)](../index.html): Core components for Validation engine. Feel free to use this component to implement programmatic functionality or extend Core functionality through its framework.
2. [Omni Asset Validator (UI)](../../../omni.asset_validator.ui/docs/index.html): Convenient UI for Omniverse. Used for daily tasks with Omniverse tools as Create.
The following tutorial will help you to:
1. Run basic operations for Asset Validator, `ValidationEngine`, and `IssueFixer`.
2. Get familiar with existing Rules to diagnose and fix problems.
3. Create your custom Rules.
## Tutorials
### Testing assets
In order to run Asset Validator, we need to enable the extension `Omni asset validator (Core)`. Optionally we can also enable `Omni asset validator (UI)` to perform similar operations using the user interface. Through this tutorial we will use `Script Editor`, enable it under the `Window` menu.
The following tutorial uses the file `BASIC_TUTORIAL_PATH` which is bundled together with `omni.asset_validator.core`. We can see its contents with the following snippet:
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
```
```python
print(stage.ExportToString())
```
The contents should be equivalent to:
```usda
#usda 1.0
(
doc="""Generated from Composed Stage of root layer C:\\some\\location\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda"""
)
def Xform "Hello"
{
def Sphere "World"
{
}
}
```
To run a simple asset validation, with `Script Editor`, execute the following code.
```python
import omni.asset_validator.core
engine = omni.asset_validator.core.ValidationEngine()
print(engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH))
```
> **Note**
> For more information about ValidationEngine together with more examples can be found at the ValidationEngine API.
The above code would produce similar results to.
```text
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
Issue(
message="Stage does not specify an upAxis.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage does not specify its linear scale in metersPerUnit.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=OmniDefaultPrimChecker,
at=StageId(
identifier="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda"
),
suggestion=Suggestion(
callable=UpdateDefaultPrim,
message="Updates the default prim"
)
)
]
)
```
The main result of validation engine is called an `Issue`. The main task of Asset validation is to detect and fix issues.
An `Issue` has important information on how to achieve both tasks.
- **Detect**. Once an issue has been found it offers a description of the problem (through a human-readable message), its severity, the `Rule` that found the issue and its location (i.e. the `Usd.Prim`).
- **Fix**. If a suggestion is available, it will help to address the `Issue` found. Information on the `Rule` and the location of the issue will be used to address it.
In the following section we will walk you through on how to identify and fix issues.
> **Note**
> For more information see the Issue API.
## Understanding Rules
Omni asset validator (Core) ships with multiple rules, in the previous example we already covered two:
- `StageMetadataChecker`: All stages should declare their `upAxis` and `metersPerUnit`. Stages that can be consumed as referencable assets should furthermore have a valid `defaultPrim` declared, and stages meant for consumer-level packaging should always have upAxis set to `Y`.
- `OmniDefaultPrimChecker`: Omniverse requires a single, active, `Xformable` root prim, also set to the layer’s defaultPrim.
Refer to [Rules](../rules.html) for the rest of rules. In the previous example when calling `ValidationEngine`
we invoked
all rules available.
```
```html
<code class="docutils literal notranslate">
<span class="pre">
ValidationRulesRegistry
```
has a registry of all rules to be used by
```html
<code class="docutils literal notranslate">
<span class="pre">
ValidationEngine
```
.
```python
import omni.asset_validator.core
for category in omni.asset_validator.core.ValidationRulesRegistry.categories():
for rule in omni.asset_validator.core.ValidationRulesRegistry.rules(category=category):
print(rule.__name__)
```
If we want to have finer control of what we can execute, we can also specify which rules to run, for example:
```python
import omni.asset_validator.core
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(omni.asset_validator.core.OmniDefaultPrimChecker)
print(engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH))
```
There are two new elements present here:
- `initRules`: By default set to `true`. if set to `false`, no rules will be automatically loaded.
- `enableRule`: A method of `ValidationEngine` to add rules.
The above would produce the following result:
```python
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=OmniDefaultPrimChecker,
at=StageId(
identifier="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda"
),
suggestion=Suggestion(
callable=UpdateDefaultPrim,
message="Updates the default prim"
)
)
]
)
```
In this particular case, `OmniDefaultPrimChecker` has implemented a suggestion for this specific issue. The second important class in `Core` we want to cover is `IssueFixer`, the way to invoke it is quite straightforward.
```python
import omni.asset_validator.core
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
fixer.fix([])
```
`fixer.fix` will receive the list of issues that should be addressed. The list of issues to address can be accessed through `issues` method in `Results` class.
**Note**
For more information about IssueFixer see [IssueFixer API](../api.html#omni.asset_validator.core.IssueFixer).
By combining the previous two examples we can now, detect and fix issues for a specific rule.
```python
import omni.asset_validator.core
# Detect issues
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(omni.asset_validator.core.OmniDefaultPrimChecker)
result = engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
# Fix issues
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
print(stage.ExportToString())
```
We can find the issue reported by `OmniDefaultPrimChecker` is fixed:
```usda
#usda 1.0
(
defaultPrim="Hello"
doc="""Generated from Composed Stage of root layer C:\\some\\location\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda"""
)
def Xform "Hello"
{
def Sphere "World"
{
}
}
```
```python
import omni.asset_validator.core
from pxr import Usd
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def CheckPrim(self, prim: Usd.Prim) -> None:
if prim.GetPath() == "/Hello/World":
self._AddFailedCheck(
message="Goodbye!",
at=prim,
)
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
```
```text
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
]
)
```
```python
from pxr import Usd
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def Callable(self, stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
def CheckPrim(self, prim: Usd.Prim) -> None:
if prim.GetPath() == "/Hello/World":
self._AddFailedCheck(
message="Goodbye!",
at=prim,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=self.Callable,
)
)
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(MyRule)
result = engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
result = fixer.fix(result.issues())
print(result)
```
Notice how the `NotImplementedError` error was not thrown during `fixer.fix`. However, we can access the result of execution by inspecting `result`:
```
[
FixResult(
issue=Issue(
message='Goodbye!',
severity=FAILURE,
rule=<class '__main__.MyRule'>,
at=PrimId(
stage_ref=StageId(identifier='C:\\sources\\asset-validator\\_build\\windows-x86_64\\release\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda'),
path='/Hello/World'
),
suggestion=Suggestion(callable=Callable, message='Avoids saying goodbye!')
),
status=FAILURE,
exception=NotImplementedError()
)
]
```
Finally, if you decide to run your custom `Rule` with the rest of the rules, it may be useful to register it in `ValidationRulesRegistry`, this can be done using `registerRule`.
```python
import omni.asset_validator.core
from pxr import Usd
@omni.asset_validator.core.registerRule("MyCategory")
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def CheckPrim(self, prim: Usd.Prim) -> None:
pass
for rule in omni.asset_validator.core.ValidationRulesRegistry.rules(category="MyCategory"):
print(rule.__name__)
```
### Custom Rule: Locations
For this section, let us use LAYERS_TUTORIAL_PATH. We proceed like in the previous section:
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
print(stage.ExportToString())
```
The contents should be equivalent to:
```usda
#usda 1.0
(
doc="Generated from Composed Stage of root layer C:\\some\\location\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial2.usda"
)
def Xform "Hello"
{
def Sphere "World"
{
double3 xformOp:translate = (-250, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
}
}
```
What we are doing is adding an opinion to the prim “/Hello/World”. In the previous section we learned how to create a
```
Rule
```
and issue a
```
Failure
```
.
The data model is similar to the following code snippet:
```python
from pxr import Usd
import omni.asset_validator.core
# We open the stage
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
# We inspect a specific prim
prim = stage.GetPrimAtPath("/Hello/World")
# We create the data model for the issue
def Callable(stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
issue = omni.asset_validator.core.Issue(
message="Goodbye!",
at=prim,
severity=omni.asset_validator.core.IssueSeverity.FAILURE,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=Callable
),
)
# Inspect the fixing points for the suggestion
for fix_at in issue.all_fix_sites:
layer_id = fix_at.layer_id
path = fix_at.path
print(layer_id, path)
```
The output of the above snippet should show first the path of layers tutorial (i.e. `LAYERS_TUTORIAL_PATH`) and second the basic tutorial (i.e. `BASIC_TUTORIAL_PATH`).
While this may be correct for above issue, different issues may need to override this information.
Every issue, has associated fixing sites (i.e. property `all_fix_sites`). The fixing sites are all places that contribute opinions to the prim from `strongest` to `weakest` order. When no layer is provided to fix, by default will be the `strongest`. If no indicated (as above) the preferred site will be the `Root` layer.
To change the preferred site to fix, we can add the `at` attribute to `Suggestion`.
```python
from pxr import Usd, Sdf
import omni.asset_validator.core
# We open the stage
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
# We inspect a specific prim
prim = stage.GetPrimAtPath("/Hello/World")
# We create the data model for the issue
def Callable(stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
```
```python
raise NotImplementedError()
issue = omni.asset_validator.core.Issue(
message="Goodbye!",
at=prim,
severity= omni.asset_validator.core.IssueSeverity.FAILURE,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=Callable,
at=[Sdf.Layer.FindOrOpen(omni.asset_validator.core.BASIC_TUTORIAL_PATH)]
),
)
# Inspect the fixing points for the suggestion
for fix_at in issue.all_fix_sites:
layer_id = fix_at.layer_id
path = fix_at.path
print(layer_id, path)
```
The output will change the order now, and you should see basic tutorial path
**first** (i.e. `BASIC_TUTORIAL_PATH`).
The previous tutorial should have helped you to:
- Create a custom Rule, generating an error and a suggestion to fix it.
- Run ValidationEngine with a specific rule.
- Run IssueFixer to fix specific issues and review the response.
### Frequently Asked Questions
**Are there any guards to make sure fixes are still relevant / don’t collide?**
In our general practice we have noticed:
- **Fixing an issue may solve another issue**. If a consecutive suggestion may fail to be applied, we just keep the exception in `FixResult` and continue execution. You will then decide the steps to take with `FixResult`.
- **Fixing an issue may generate another issue**. For the second case it is recommended to run `ValidationEngine` again, to discover those cases. Think of it as an iterative process with help of an automated tool.
**Are fixes addressed in the root layer? strongest layer?**
Currently, some Issues would perform the suggestion on the strongest layer, while many on the root layer. We are working into offer flexibility to decide in which layer aim the changes, while also offering a default layer for automated workflows. | 15,969 |
introduction_Overview.md | # omni.syntheticdata
## Introduction
This extension provides low level OmniGraph nodes for preparing synthetic data AOVs and annotator outputs for the higher level Omniverse Replicator extension. End user applications should use the Replicator APIs, rather than using this extension directly.
The extension also includes support for older deprecated Omniverse Synthetic Data APIs. If you are currently using these older APIs, we suggest reviewing the newer Replicator APIs and switching to these.
A preview visualization component is also included - this is accessible from the viewport synthetic data icon when the extension is installed.
### OmniGraph Nodes In This Extension
- Sd Fabric Time Range Execution
- Sd Frame Identifier
- Sd Instance Mapping
- Sd Instance Mapping Ptr
- Sd Linear Array To Texture
- Sd No Op
- Sd On New Frame
- Sd On New Render Product Frame
- Sd Post Comp Render Var Textures
- Sd Post Instance Mapping
- Sd Post Render Var Display Texture
- Sd Post Render Var Host To Disk
- Sd Post Render Var Texture To Buffer
- Sd Post Render Var To Host
- Sd Post Semantic3d Bounding Box Camera Projection
- Sd Post Semantic3d Bounding Box Filter
- Sd Post Semantic Bounding Box
- Sd Post Semantic Filter Segmentation Map
- Sd Render Product Camera
- Sd Render Var Display Texture
- Sd Render Var Ptr
- Sd Render Var To Raw Array
- Sd Semantic Filter
- Sd Semantic Labels Map
- Sd Sim Instance Mapping
- Sd Sim Render Product Camera
- Sd Test Instance Mapping
- Sd Test Print Raw Array
- Sd Test Rational Time Sync Gate
- Sd Test Render Product Camera
- Sd Test Sim Fabric Time Range
- Sd Test Stage Manipulation Scenarii
- Sd Test Stage Synchronization
- Sd Texture To Linear Array
- Sd Time Change Execution
- Sd Update Sw Frame Number | 1,759 |
isaac-sim-conventions_reference_conventions.md | # Isaac Sim Conventions
This section provides a reference for the units, representations, and coordinate conventions used within Omniverse Isaac Sim.
## Default Units
| Measurement | Units | Notes |
|-------------|----------|-------|
| Length | Meter | |
| Mass | Kilogram | |
| Time | Seconds | |
| Physics Time-Step | Seconds | Configurable by User. Default is 1/60. |
| Force | Newton | |
| Frequency | Hertz | |
| Linear Drive Stiffness | \(kg/s^2\) | |
| Angular Drive Stiffness | \((kg*m^2)/(s^2*angle)\) | |
| Linear Drive Damping | \(kg/s\) | |
| Angular Drive Damping | \((kg*m^2)/(s*angle)\) | |
| Diagonal of Inertia | \((kg*m^2)\) | |
## Default Rotation Representations
### Quaternions
| API | Representation |
|--------------|----------------|
```
# Isaac Sim Core
## Angles
### API
### Representation
| API | Representation |
|----------------|---------------|
| Isaac Sim Core | Radians |
| USD | Degrees |
| PhysX | Radians |
| Dynamic Control| Radians |
## Matrix Order
### API
### Representation
| API | Representation |
|----------------|---------------|
| Isaac Sim Core | Row Major |
| USD | Row Major |
## World Axes
Omniverse Isaac Sim follows the right-handed coordinate conventions.
| Direction | Axis | Notes |
|-----------|------|-------|
| Up | +Z | |
| Forward | +X | |
## Default Camera Axes
| Direction | Axis | Notes |
|-----------|------|-------|
| Up | +Y | |
| Forward | -Z | |
### Note
**Isaac Sim to ROS Conversion**: To convert from Isaac Sim Camera Coordinates to ROS Camera Coordinates, rotate 180 degrees about the X-Axis.
## Image Frames (Synthetic Data)
| Coordinate | Corner |
|------------|------------|
| (0,0) | Top Left | | 1,944 |
it-managed-installation-overview.md | # IT Managed Launcher Overview
The **IT Managed Launcher** is an enterprise user’s front end to all of the Omniverse applications that their company makes available to them on their local workstation.
Its main use is to allow a company more control over deployment of Omniverse to its users. Some of the features included:
- Support for deployment tools such as PowerShell, Group Policy, SCCM, as well as Linux deployment tools.
- Does not require an Nvidia Account login for the end users.
- Can be used in an a firewalled environment.
- End users cannot download, install, or update Apps.
It is designed to be installed by IT department personnel given many corporate networks have strict security policies in place. The IT Managed Launcher is available for both Windows and Linux operating systems.
This launcher and its interface differ from the standard Omniverse Workstation Launcher in that it is **not** designed to allow an end user to install anything directly on their own workstation or update installed applications themselves. It is therefore missing the top-level _Exchange_ and _Nucleus_ sections of the Workstation Launcher **by design**.
These sections are not present within the IT Managed Launcher as these elements are intended to be installed and configured by the IT Managers and Systems Administrators within your organization.
The other major difference between the IT Managed Launcher and the normal Workstation Launcher is that the IT Managed Launcher does **not** require a developer account login for it to function.
The IT Managed Launcher is a critical component for accessing the Omniverse foundation apps for your organization and users, so as a first step, your initial task is to install this component to your local users’ workstations.
## IT Managed Launcher components
### IT Managed Launcher Installer
This is the main application that will be installed on each users machine. Installers are available for Windows and Linux.
### TOML File
The TOML ml files control the setting for the install. There are three TOML files.
`Omniverse.toml` Used to define all the main path and options for the launcher. file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step 1. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
| Path | Description |
|-------------------------------|--------------------------------------------------|
| library_root = “C:\Omniverse\library” | Path where to install all Omniverse applications |
| data_root = “C:\Omniverse\data” | Folder where Launcher and Omniverse apps store their data files |
<section id="config-folder">
<h2>
Config Folder
<a class="headerlink" href="#config-folder" title="Permalink to this headline">
<table>
<tbody>
<tr class="row-even">
<td>
<p>
cache_root = “C:\Omniverse\cache”
<td>
<p>
Folder where Omniverse apps store their cache and temporary files
<tr class="row-odd">
<td>
<p>
logs_root = “C:\Users\[username]\.nvidia-omniverse\logs”
<td>
<p>
Folder where Launcher and Omniverse apps store their logs
<tr class="row-even">
<td>
<p>
content_root = “C:\Users\[username]\Downloads”
<td>
<p>
Folder where Launcher saves downloaded content packs
<tr class="row-odd">
<td>
<p>
extension_root = “C:\Users\[username]\Documents\kit\shared\exts”
<td>
<p>
Folder where all Omniverse shared extensions are stored
<tr class="row-even">
<td>
<p>
confirmed = true
<td>
<p>
Confirmation that all paths are set correctly, must be set to
<cite>
true
<div class="admonition important">
<p class="admonition-title">
Important
<p>
Also be aware that all paths on Windows require a double backslash (\) for proper operation.
<div class="admonition note">
<p class="admonition-title">
Note
<p>
If a system administrator doesn’t want to allow users to change these paths, the omniverse.toml file can be marked as
<strong>
read-only
. Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like Program Files on Windows, they need to specify a shared folder for
<strong>
library_root
and
<strong>
logs_root
path in omniverse.toml file.
<p>
You’re now going to add two additional files to this /config folder in addition to the omniverse.toml file.
<section id="auth-toml">
<h3>
Auth.toml
<section id="license-toml">
<h3>
License.toml
<p>
File to provide your license details and Customer ID.
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span>
<span class="n">org-name
<section id="privacy-toml">
<h3>
Privacy.toml
<p>
file to record consent choices for data collection and capture of crash logs
Within the
<code class="docutils literal notranslate">
<span class="pre">
/config
<span class="pre">
folder
, then create a text file named
<strong>
privacy.toml
. This is the configuration file for Omniverse telemetry. The file contains following information:
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span>
<span class="n">performance
<span class="n">personalization
<span class="n">usage
<div class="admonition important">
<p class="admonition-title">
Important
<p>
By opting into telemetry within the
<code class="docutils literal notranslate">
<span class="pre">
privacy.toml
, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this
<em>
section
.
<section id="packages">
<h3>
Packages
<p>
Packages are what get deployed to each user. The packages are available here. Applications and Contents Packs are available to download for linux and windows to deploy to users.
| 6,902 |
it-managed-launcher.md | # Installation Guide
This guide is designed for IT Managers and Systems Administrators who need to install and configure Omniverse Enterprise within a firewalled, air-gapped environment (i.e., limited or no Internet access), or want to prevent users from installing unapproved Omniverse applications.
The instructions and information provided covers the installation and functional use of Omniverse Foundation applications and 3D sample content.
There are four primary steps involved in setting up a user’s workstation in a firewalled environment, and we encourage you to fully read the instructions before proceeding.
1. Downloading, installing, and configuring the **IT Managed Launcher** on a user’s workstation.
2. Downloading and Installing one or more **Omniverse Foundation Applications** on a user’s workstation.
3. Optional download Installation and configuration of Omniverse **Sample 3D Content** which can be stored in one of two locations:
- Users’ workstations local hard disk.
- Stored on a shared Enterprise Nucleus Server that the users’ workstations can access through a local network.
## Planning Your Installation
## Installation on Windows
## Installation on Linux
## Uninstalling Apps (Win & Linux) | 1,231 |
jt-converter_Overview.md | # JT Converter
## Overview
The JT Converter extension enables conversion for JT file formats to USD.
USD Explorer includes the JT Converter extension enabled by default.
## Supported CAD file formats
The following file formats are supported by JT Converter:
- JT Files (`*.jt`)
**Note:**
The file formats *.fbx, *.obj, *.gltf, *.glb, *.lxo, *.md5, *.e57 and *.pts are supported by Asset Converter and also available by default.
**Note:**
If expert tools such as Creo, Revit or Alias are installed, we recommend using the corresponding connectors. These provide more extensive options for conversion.
**Note:**
CAD Assemblies may not work when converting files from Nucleus. When converting assemblies with external references we recommend either working with local files or using Omniverse Drive.
## Converter Options
This section covers options for configuration of conversions of JT file formats to USD.
## Related Extensions
These related extensions make up the JT Converter. This extension provides import tasks to the extensions through their interfaces.
### Core Converter
- JT Core: `omni.kit.converter.jt_core:Overview`
### Services
- CAD Converter Service: `omni.services.convert.cad:Overview`
### Utils
- Converter Common: `omni.kit.converter.common:Overview` | 1,281 |
Kind.md | # Kind module
Summary: The Kind library provides a runtime-extensible taxonomy known as “kinds”. Useful for classifying scenegraph objects.
## Python bindings for libKind
**Classes:**
| Class | Description |
| --- | --- |
| `Registry` | A singleton that holds known kinds and information about them. |
| `Tokens` | |
### KindRegistry Threadsafty
KindRegistry serves performance-critical clients that operate under the stl threading model, and therefore itself follows that model in order to avoid locking during HasKind() and IsA() queries.
To make this robust, KindRegistry exposes no means to mutate the registry. All extensions must be accomplished via plugInfo.json files, which are consumed once during the registry initialization (See Extending the KindRegistry)
**Methods:**
| Method | Description |
| --- | --- |
| `GetAllKinds()` | **classmethod** GetAllKinds() -> list[str] |
| `GetBaseKind(kind)` | **classmethod** GetBaseKind(kind) -> str |
| `HasKind(kind)` | **classmethod** HasKind(kind) -> bool |
## IsA
### classmethod
IsA(derivedKind, baseKind) -> bool
## Attributes:
### expired
True if this object has expired, False otherwise.
## GetAllKinds
### classmethod
GetAllKinds() -> list[str]
Return an unordered vector of all kinds known to the registry.
## GetBaseKind
### classmethod
GetBaseKind(kind) -> str
Return the base kind of the given kind.
If there is no base, the result will be an empty token. Issues a coding error if kind is unknown to the registry.
#### Parameters
- **kind** (str) –
## HasKind
### classmethod
HasKind(kind) -> bool
Test whether kind is known to the registry.
#### Parameters
- **kind** (str) –
## IsA
### classmethod
IsA(derivedKind, baseKind) -> bool
Test whether derivedKind is the same as baseKind or has it as a base kind (either directly or indirectly).
It is not required that derivedKind or baseKind be known to the registry: if they are unknown but equal, IsA will return true; otherwise if either is unknown, we will simply return false.
Therefore this method will not raise any errors.
#### Parameters
- **derivedKind** (str) –
- **baseKind** (str) –
## expired
### property
expired
True if this object has expired, False otherwise.
<dl class="py">
<dt>
<p>
<strong>
Attributes:
<table>
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr>
<td>
<p>
<code>
assembly
<td>
<p>
<tr>
<td>
<p>
<code>
component
<td>
<p>
<tr>
<td>
<p>
<code>
group
<td>
<p>
<tr>
<td>
<p>
<code>
model
<td>
<p>
<tr>
<td>
<p>
<code>
subcomponent
<td>
<p>
<dl class="py attribute">
<dt>
<span>
assembly
<em>
=
'assembly'
<dd>
<dl class="py attribute">
<dt>
<span>
component
<em>
=
'component'
<dd>
<dl class="py attribute">
<dt>
<span>
group
<em>
=
'group'
<dd>
<dl class="py attribute">
<dt>
<span>
model
<em>
=
'model'
<dd>
<dl class="py attribute">
<dt>
<span>
subcomponent
<em>
=
'subcomponent'
<dd>
| 4,240 |
kit-apps-extensions_kit_sdk_overview.md | # Kit SDK Overview
Omniverse is a developer platform. It provides Nucleus for collaboration and data storage. Connector API provides USD conversion capabilities. The Omniverse developer platform provides the Kit SDK for developing Applications, Extensions, and Services.
This tutorial is focused on creating Applications and Extensions on top of Kit SDK.
## Kit Apps & Extensions
The Kit SDK Extension Architecture allow developers to define Extensions and Applications. An Extension is defined by a `.toml` file and most commonly has a set of directories with Python or C++ code. Extensions can also bundle resources such as images. An Application is a single `.kit` file. These modules can state each other as dependencies to combine small capabilities into a greater whole providing complex solutions.
Throughout this document you will encounter many Extensions and Applications. You will start to think of Extensions as “pieces of capabilities” and of Applications as “the collection of Extensions”.
### Extension
- Defined by an `extension.toml` file
- Contains code (Python or C++) and/or resource files.
- Provides a user interface and/or runtime capability.
### App
- Defined by a `.kit` file.
- Combines dependencies into an end user workflow.
## Extension Architecture
At the foundation of Kit SDK, the Kit Kernel provides the ability to bootstrap Applications and execute code. All capability on top of the Kernel is provided by Extensions. Kit SDK contains hundreds of Extensions providing runtime functionality such as USD, rendering, and physics - and other Extensions providing workflow solutions such as USD Stage inspectors, viewport, and content browsers. By combining the Kit SDK Extensions with one or more custom Extensions, new workflow and service based solutions can be created. The Extension Architecture of Kit has been designed for extreme modularity - enabling rapid development of reusable modules:
- Extensions are lego pieces of functionality.
- One Extension can state any number of other Extensions as dependencies.
- Applications provide a complete solution by combining many Extensions.
- Any Omniverse developer can create more Extensions.
Here’s another way to conceptualize the stack of an Application. At the foundation level of an app we have the Kit Kernel. There are runtime Extensions such as USD, RTX, and PhysX. Also behind the scene, there are framework Extensions that enable interfaces to be created, Extension management, and so on. Finally, we have the Extensions that provide end users with interfaces - such as the Viewport, Content Browser, and Stage inspector.
Applications you create will have the same stack - the only difference is what Extensions the Application makes use of and how they are configured.
We will explore the Extensions available in Kit SDK, how to create Applications, and how to get started with Extension development.
# Getting Started with Python Development
## Introduction
Welcome to the Python development tutorial. In this tutorial, we will cover various aspects of Python programming, from basic syntax to advanced topics like web development and data analysis.
## Setting Up the Developer Environment
Before we dive into coding, let's ensure our development environment is properly set up. This includes installing Python, setting up a code editor, and configuring a terminal or command prompt.
### Installing Python
Python can be installed from the official website. Make sure to download the latest version for your operating system.
### Choosing a Code Editor
A good code editor can significantly improve your coding experience. Some popular choices include Visual Studio Code, PyCharm, and Atom.
### Configuring the Terminal
For running Python scripts and managing packages, a well-configured terminal is essential. On Windows, you can use PowerShell or Command Prompt. On macOS and Linux, the default terminal is usually sufficient.
## Conclusion
Setting up a proper development environment is crucial for efficient coding. Once you have your environment ready, you're all set to start learning Python.
--- | 4,123 |