Tutorial 20 - Tokens

Tokens are a method of providing fast access to strings that have fixed contents. All strings with the same contents can be translated into the same shared token. Token comparison is as fast as integer comparisons, rather than the more expensive string comparisons you would need for a general string.

One example of where they are useful is in having a fixed set of allowable values for an input string. For example you might choose a color channel by selecting from the names “red”, “green”, and “blue”, or you might know that a mesh bundle’s contents always use the attribute names “normals”, “points”, and “faces”.

Tokens can be accessed through the database methods tokenToString() and stringToToken(). Using the tokens keyword in a .ogn file merely provides a shortcut to always having certain tokens available. In the color case then if you have a token input containing the color your comparison code changes from this:

const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.stringToToken("red"))
{
    // do red stuff
}
else if (colorToken == db.stringToToken("green"))
{
    // do green stuff
}
else if (colorToken == db.stringToToken("blue"))
{
    // do blue stuff
}

to this, which has much faster comparison times:

const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.tokens.red)
{
    // do red stuff
}
else if (colorToken == db.tokens.green)
{
    // do green stuff
}
else if (colorToken == db.tokens.blue)
{
    // do blue stuff
}

In Python there isn’t a first-class object that is a token but the same token access is provided for consistency:

color_token = db.inputs.colorToken
if color_token == db.tokens.red:
    # do red stuff
elif color_token == db.tokens.green:
    # do green stuff
elif color_token == db.tokens.blue:
    # do blue stuff

OgnTutorialTokens.ogn

The ogn file shows the implementation of a node named “omni.graph.tutorials.Tokens”, which contains some hardcoded tokens to use in the compute method.

 1{
 2    "Tokens": {
 3        "version": 1,
 4        "categories": "tutorials",
 5        "scheduling": ["threadsafe"],
 6        "description": ["This is a tutorial node. It exercises the feature of providing hardcoded token values",
 7                        "in the database after a node type has been initialized. It sets output booleans to the",
 8                        "truth value of whether corresponding inputs appear in the hardcoded token list."
 9        ],
10        "uiName": "Tutorial Node: Tokens",
11        "inputs": {
12            "valuesToCheck": {
13                "type": "token[]",
14                "description": "Array of tokens that are to be checked"
15            }
16        },
17        "outputs": {
18            "isColor": {
19                "type": "bool[]",
20                "description": "True values if the corresponding input value appears in the token list"
21           }
22        },
23        "$comment": [
24            "The tokens can be a list or a dictionary. If a list then the token string is also the name of the",
25            "variable in the database through which they can be accessed. If a dictionary then the key is the",
26            "name of the access variable and the value is the actual token string. Use a list if your token values",
27            "are all legal variable names in your node's implementation language (C++ or Python)."
28        ],
29        "tokens": ["red", "green", "blue"],
30        "tests": [
31            {
32                "inputs:valuesToCheck": ["red", "Red", "magenta", "green", "cyan", "blue", "yellow"],
33                "outputs:isColor": [true, false, false, true, false, true, false]
34            }
35        ]
36    }
37}

OgnTutorialTokens.cpp

The cpp file contains the implementation of the compute method. It illustrates how to access the hardcoded tokens to avoid writing the boilerplate code yourself.

 1// SPDX-FileCopyrightText: Copyright (c) 2021-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 2// SPDX-License-Identifier: LicenseRef-NvidiaProprietary
 3//
 4// NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
 5// property and proprietary rights in and to this material, related
 6// documentation and any modifications thereto. Any use, reproduction,
 7// disclosure or distribution of this material and related documentation
 8// without an express license agreement from NVIDIA CORPORATION or
 9// its affiliates is strictly prohibited.
10#include <OgnTutorialTokensDatabase.h>
11
12
13class OgnTutorialTokens
14{
15public:
16    static bool compute(OgnTutorialTokensDatabase& db)
17    {
18        const auto& valuesToCheck = db.inputs.valuesToCheck();
19        auto& isColor = db.outputs.isColor();
20
21        size_t len = valuesToCheck.size();
22        isColor.resize(len);
23        if (len == 0)
24        {
25            return true;
26        }
27
28        // Walk the list of inputs, setting the corresponding output to true if and only if the input is in
29        // the list of allowable tokens.
30        for (size_t index = 0; index < len; index++)
31        {
32            const auto& inputValue = valuesToCheck[index];
33
34            // When the database is available you can use it to access the token values directly. When it is not
35            // you can access them statically (e.g. OgnTutorialTokensDatabase.token.red)
36            if ((inputValue == db.tokens.red) || (inputValue == db.tokens.green) || (inputValue == db.tokens.blue))
37            {
38                isColor[index] = true;
39            }
40            else
41            {
42                isColor[index] = false;
43            }
44        }
45
46        return true;
47    }
48};
49
50REGISTER_OGN_NODE()

OgnTutorialTokensPy.py

The py file contains the implementation of the compute method in Python. The .ogn file is the same as the above, except for the addition of the implementation language key "language": "python". The compute follows the same algorithm as the cpp equivalent.

 1"""
 2Implementation of a node handling hardcoded tokens. Tokens are a fixed set of strings, usually used for things
 3like keywords and enum names. In C++ tokens are more efficient than strings for lookup as they are represented
 4as a single long integer. The Python access methods are set up the same way, though at present there is no
 5differentiation between strings and tokens in Python code.
 6"""
 7
 8
 9class OgnTutorialTokensPy:
10    """Exercise access to hardcoded tokens"""
11
12    @staticmethod
13    def compute(db) -> bool:
14        """
15        Run through a list of input tokens and set booleans in a corresponding output array indicating if the
16        token appears in the list of hardcoded color names.
17        """
18
19        values_to_check = db.inputs.valuesToCheck
20
21        # When assigning the entire array the size does not have to be set in advance
22        db.outputs.isColor = [value in [db.tokens.red, db.tokens.green, db.tokens.blue] for value in values_to_check]
23
24        return True