file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantInt64.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantInt64Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantInt64
{
public:
static size_t computeVectorized(OgnConstantInt64Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantDouble3.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantDouble3Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantDouble3
{
public:
static size_t computeVectorized(OgnConstantDouble3Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantTexCoord3f.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantTexCoord3fDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantTexCoord3f
{
public:
static size_t computeVectorized(OgnConstantTexCoord3fDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 720 | C++ | 20.205882 | 81 | 0.7625 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantBool.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantBoolDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantBool
{
public:
static size_t computeVectorized(OgnConstantBoolDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantHalf3.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantHalf3Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantHalf3
{
public:
static size_t computeVectorized(OgnConstantHalf3Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantToken.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantTokenDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantToken
{
public:
static size_t computeVectorized(OgnConstantTokenDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantPath.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPath
{
public:
static size_t computeVectorized(OgnConstantPathDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantDouble.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantDoubleDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantDouble
{
public:
static size_t computeVectorized(OgnConstantDoubleDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantHalf.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantHalfDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantHalf
{
public:
static size_t computeVectorized(OgnConstantHalfDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantDouble4.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantDouble4Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantDouble4
{
public:
static size_t computeVectorized(OgnConstantDouble4Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantQuatf.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantQuatfDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantQuatf
{
public:
static size_t computeVectorized(OgnConstantQuatfDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantPi.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantPiDatabase.h>
#include <omni/math/linalg/math.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPi
{
public:
static size_t computeVectorized(OgnConstantPiDatabase& db, size_t count)
{
auto ptr = db.outputs.value.vectorized(count);
auto pFactor = db.inputs.factor.vectorized(count);
for (size_t i =0 ; i < count; ++i)
ptr[i] = pFactor[i] * M_PI;
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 931 | C++ | 22.897435 | 77 | 0.709989 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantUInt.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantUIntDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantUInt
{
public:
static size_t computeVectorized(OgnConstantUIntDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantFloat2.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantFloat2Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantFloat2
{
public:
static size_t computeVectorized(OgnConstantFloat2Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantDouble2.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantDouble2Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantDouble2
{
public:
static size_t computeVectorized(OgnConstantDouble2Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantQuatd.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantQuatdDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantQuatd
{
public:
static size_t computeVectorized(OgnConstantQuatdDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantTexCoord3h.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantTexCoord3hDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantTexCoord3h
{
public:
static size_t computeVectorized(OgnConstantTexCoord3hDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 720 | C++ | 20.205882 | 81 | 0.7625 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantFloat.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantFloatDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantFloat
{
public:
static size_t computeVectorized(OgnConstantFloatDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantInt4.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantInt4Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantInt4
{
public:
static size_t computeVectorized(OgnConstantInt4Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantString.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantString
{
public:
static size_t computeVectorized(OgnConstantStringDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantTexCoord2h.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantTexCoord2hDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantTexCoord2h
{
public:
static size_t computeVectorized(OgnConstantTexCoord2hDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 720 | C++ | 20.205882 | 81 | 0.7625 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantHalf4.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantHalf4Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantHalf4
{
public:
static size_t computeVectorized(OgnConstantHalf4Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantColor4f.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantColor4fDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantColor4f
{
public:
static size_t computeVectorized(OgnConstantColor4fDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantTexCoord2f.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantTexCoord2fDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantTexCoord2f
{
public:
static size_t computeVectorized(OgnConstantTexCoord2fDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 720 | C++ | 20.205882 | 81 | 0.7625 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantHalf2.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantHalf2Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantHalf2
{
public:
static size_t computeVectorized(OgnConstantHalf2Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantUChar.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantUCharDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantUChar
{
public:
static size_t computeVectorized(OgnConstantUCharDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 705 | C++ | 19.764705 | 77 | 0.757447 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantUInt64.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantUInt64Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantUInt64
{
public:
static size_t computeVectorized(OgnConstantUInt64Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantPoint3d.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantPoint3dDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPoint3d
{
public:
static size_t computeVectorized(OgnConstantPoint3dDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantInt2.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnConstantInt2Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantInt2
{
public:
static size_t computeVectorized(OgnConstantInt2Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 702 | C++ | 19.67647 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantColor3f.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantColor3fDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantColor3f
{
public:
static size_t computeVectorized(OgnConstantColor3fDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantFloat4.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantFloat4Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantFloat4
{
public:
static size_t computeVectorized(OgnConstantFloat4Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantPoint3f.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantPoint3fDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPoint3f
{
public:
static size_t computeVectorized(OgnConstantPoint3fDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 711 | C++ | 19.941176 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantFloat3.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantFloat3Database.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantFloat3
{
public:
static size_t computeVectorized(OgnConstantFloat3Database&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 708 | C++ | 19.852941 | 77 | 0.758475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/constants/OgnConstantInt.cpp |
// Copyright (c) 2021, 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.
//
#include <OgnConstantIntDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantInt
{
public:
static size_t computeVectorized(OgnConstantIntDatabase&, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 699 | C++ | 19.588235 | 77 | 0.755365 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector3.cpp | // Copyright (c) 2022, 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.
//
#include <OgnMakeVector3Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryMakeVector(OgnMakeVector3Database& db, size_t count = 1)
{
const auto x = db.inputs.x().template get<Type>();
const auto y = db.inputs.y().template get<Type>();
const auto z = db.inputs.z().template get<Type>();
const auto vector = db.outputs.tuple().template get<Type[3]>();
if (x && y && z && vector)
{
const auto px = x.vectorized(count);
const auto py = y.vectorized(count);
const auto pz = z.vectorized(count);
const auto pvector = vector.vectorized(count);
if (not(pvector.empty() || px.empty() || py.empty() || pz.empty()))
{
for (size_t i = 0; i < count; i++)
{
pvector[i][0] = px[i];
pvector[i][1] = py[i];
pvector[i][2] = pz[i];
}
return true;
}
return false;
}
for(size_t i = 0; i < count ; ++i)
{
const auto xArray = db.inputs.x(i).template get<Type[]>();
const auto yArray = db.inputs.y(i).template get<Type[]>();
const auto zArray = db.inputs.z(i).template get<Type[]>();
auto vectorArray = db.outputs.tuple(i).template get<Type[][3]>();
if (!vectorArray || !xArray || !yArray || !zArray){
return false;
}
if (xArray->size() != yArray->size() || xArray->size() != zArray->size())
{
throw ogn::compute::InputError("Input arrays of different lengths x:" + std::to_string(xArray->size()) +
", y:" + std::to_string(yArray->size()) +
", z:" + std::to_string(zArray->size()));
}
vectorArray->resize(xArray->size());
for (size_t i = 0; i < vectorArray->size(); i++)
{
(*vectorArray)[i][0] = (*xArray)[i];
(*vectorArray)[i][1] = (*yArray)[i];
(*vectorArray)[i][2] = (*zArray)[i];
}
}
return true;
}
} // namespace
// Node to merge 3 scalers together to make 3-vector
class OgnMakeVector3
{
public:
static size_t computeVectorized(OgnMakeVector3Database& db, size_t count)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db, count))
return count;
else if (tryMakeVector<float>(db, count))
return count;
else if (tryMakeVector<pxr::GfHalf>(db, count))
return count;
else if (tryMakeVector<int32_t>(db, count))
return count;
else
{
db.logError("Failed to resolve input types");
return 0;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return 0;
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::z.token());
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token());
auto xType = vector.iAttribute->getResolvedType(x);
auto yType = vector.iAttribute->getResolvedType(y);
auto zType = vector.iAttribute->getResolvedType(z);
// If one of the inputs is resolved we can resolve the other because they should match
std::array<AttributeObj, 3> attrs { x, y, z };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
zType = vector.iAttribute->getResolvedType(z);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown &&
yType.baseType != BaseDataType::eUnknown &&
zType.baseType != BaseDataType::eUnknown )
{
std::array<AttributeObj, 4> attrs{ x, y, z, vector };
std::array<uint8_t, 4> tuples{ 1, 1, 1, 3 };
std::array<uint8_t, 4> arrays{
xType.arrayDepth,
yType.arrayDepth,
zType.arrayDepth,
xType.arrayDepth,
};
std::array<AttributeRole, 4> roles{ xType.role, yType.role, zType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(
nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,523 | C++ | 33.098765 | 116 | 0.565635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstantPrims.cpp | // Copyright (c) 2020-2023, 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.
//
#include <OgnConstantPrimsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPrims
{
public:
static size_t computeVectorized(OgnConstantPrimsDatabase& db, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 739 | C++ | 21.424242 | 79 | 0.749662 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstructArray.cpp | // Copyright (c) 2022, 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.
//
#include <OgnConstructArrayDatabase.h>
#include <carb/logging/Log.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <array>
#include <unordered_map>
#include <vector>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
static constexpr size_t kMaxAttrNameLen{ 32 };
void formatAttrName(size_t n, std::array<char, kMaxAttrNameLen>& outName)
{
snprintf(outName.data(), kMaxAttrNameLen, "inputs:input%zu", n);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto iNode = nodeObj.iNode;
GraphObj graphObj = iNode->getGraph(nodeObj);
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto const outputArrayAttr = iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
if (outputArrayType.baseType == BaseDataType::eUnknown)
{
return false;
}
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!outputArray)
return false;
size_t const arraySize = static_cast<size_t>(std::max(0, db.inputs.arraySize()));
(*outputArray).resize(arraySize);
memset(outputArray->data(), 0, sizeof(BaseType) * arraySize);
// read dynamic inputs
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (iNode->getAttributeExists(nodeObj, outName.data()) && i < arraySize) {
auto inAttrib = iNode->getAttribute(nodeObj, outName.data());
auto inputAttribType = inAttrib.iAttribute->getResolvedType(inAttrib);
if (inputAttribType.baseType != BaseDataType::eUnknown)
{
ConstAttributeDataHandle handle = inAttrib.iAttribute->getConstAttributeDataHandle(inAttrib, db.getInstanceIndex());
auto const dataPtr = getDataR<BaseType>(context, handle);
if (dataPtr)
(*outputArray)[i] = *dataPtr;
}
++i;
formatAttrName(i, outName);
}
// fill the rest of the array using the last input value if necessary
if (0 < i && i < arraySize)
{
for (size_t j = i; j < arraySize; ++j)
{
(*outputArray)[j] = (*outputArray)[i - 1];
}
}
return true;
}
template<typename BaseType, size_t TupleSize>
bool tryComputeAssumingType(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto iNode = nodeObj.iNode;
GraphObj graphObj = iNode->getGraph(nodeObj);
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto const outputArrayAttr = iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
if (outputArrayType.baseType == BaseDataType::eUnknown)
{
return false;
}
auto outputArray = db.outputs.array().template get<BaseType[][TupleSize]>();
if (!outputArray)
return false;
size_t const arraySize = static_cast<size_t>(std::max(0, db.inputs.arraySize()));
(*outputArray).resize(arraySize);
memset(outputArray->data(), 0, sizeof(BaseType) * arraySize * TupleSize);
// read dynamic inputs
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (iNode->getAttributeExists(nodeObj, outName.data()) && i < arraySize) {
auto inAttrib = iNode->getAttribute(nodeObj, outName.data());
auto inputAttribType = inAttrib.iAttribute->getResolvedType(inAttrib);
if (inputAttribType.baseType != BaseDataType::eUnknown)
{
ConstAttributeDataHandle handle = inAttrib.iAttribute->getConstAttributeDataHandle(inAttrib, db.getInstanceIndex());
auto const dataPtr = getDataR<BaseType[TupleSize]>(context, handle);
if (dataPtr)
memcpy(&((*outputArray)[i]), dataPtr, sizeof(BaseType) * TupleSize);
}
++i;
formatAttrName(i, outName);
}
// fill the rest of the array using the last input value if necessary
if (0 < i && i < arraySize)
{
for (size_t j = i; j < arraySize; ++j)
{
memcpy(&((*outputArray)[j]), &((*outputArray)[i - 1]), sizeof(BaseType) * TupleSize);
}
}
return true;
}
} // namespace
class OgnConstructArray
{
static void tryResolveAttribute(omni::graph::core::NodeObj const& nodeObj,
omni::graph::core::AttributeObj attrib,
omni::graph::core::Type attribType)
{
Type valueType{ attrib.iAttribute->getResolvedType(attrib) };
bool attribIsValid = (attribType.baseType != BaseDataType::eUnknown);
if (valueType.baseType != BaseDataType::eUnknown)
{
// Resolved
// Case 1: We didn't find a valid source attribute => unresolve
// Case 2: We found an attribute but it is not compatible with our current resolution => unresolve
// Else: All good
if (!attribIsValid or (attribType != valueType))
{
// Not compatible! Request that the attribute be un-resolved. Note that this could fail if there are
// connections that result in a contradiction during type propagation
attrib.iAttribute->setResolvedType(attrib, Type(BaseDataType::eUnknown));
}
}
// If it's unresolved (and we have a valid attribute) we can request a resolution
if (attribIsValid and (attrib.iAttribute->getResolvedType(attrib).baseType == BaseDataType::eUnknown))
{
attrib.iAttribute->setResolvedType(attrib, attribType);
}
}
static void tryResolveArrayAttributes(omni::graph::core::NodeObj const& nodeObj, bool reconnectInputs)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
// Get the input attributes
std::vector<AttributeObj> inputAttributes;
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (nodeObj.iNode->getAttributeExists(nodeObj, outName.data()))
{
inputAttributes.push_back(nodeObj.iNode->getAttribute(nodeObj, outName.data()));
++i;
formatAttrName(i, outName);
}
// Determine the output array type from the specified array type and connected inputs
Type outputType = state.m_inputArrayType; // Initialize to the specified array type ('eUnknown' if unspecified, i.e. 'inputs:arrayType' is set to 'auto')
for (auto const& inAttrib : inputAttributes)
{
// Check if input is an array
if (inAttrib.iAttribute->getResolvedType(inAttrib).arrayDepth != 0)
{
OgnConstructArrayDatabase::logError(nodeObj, "Nested arrays not supported: The input array element at attribute '%s' is an array",
inAttrib.iAttribute->getName(inAttrib));
// Unresolve output and return
auto outputArrayAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
tryResolveAttribute(nodeObj, outputArrayAttrib, Type(BaseDataType::eUnknown));
return;
}
// Skip unconnected inputs
size_t upstreamConnectionCount = inAttrib.iAttribute->getUpstreamConnectionCount(inAttrib);
if (upstreamConnectionCount != 1)
continue;
// Get the type of the current input from the upstream connection
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
Type const upstreamType = upstreamConnection.attrObj.iAttribute->getResolvedType(upstreamConnection.attrObj);
// The array type is not specified, so infer from the first connected and resolved input
if (upstreamType.baseType != BaseDataType::eUnknown)
{
if (outputType.baseType == BaseDataType::eUnknown)
{
outputType = upstreamType;
}
else
{
// Check if the specified or inferred array type matches the type of the current input
if (!outputType.compatibleRawData(upstreamType))
{
OgnConstructArrayDatabase::logError(
nodeObj, "Mismatched array element type on input attribute '%s': expected '%s', got '%s'",
inAttrib.iAttribute->getName(inAttrib), getOgnTypeName(outputType).c_str(),
getOgnTypeName(upstreamType).c_str());
outputType = Type(BaseDataType::eUnknown);
break;
}
}
}
}
// Resolve inputs
for (auto& inAttrib : inputAttributes)
{
size_t upstreamConnectionCount = inAttrib.iAttribute->getUpstreamConnectionCount(inAttrib);
if (upstreamConnectionCount == 0)
{
// Resolve unconnected inputs to the specified array type, or the inferred array type if the array type is unspecified
if (state.m_inputArrayType.baseType != BaseDataType::eUnknown)
{
if (inAttrib.iAttribute->getResolvedType(inAttrib) != state.m_inputArrayType)
{
// Case: The current input is disconnected and the array type is specified
// Action: Resolve the current input to the specified array type
tryResolveAttribute(nodeObj, inAttrib, state.m_inputArrayType);
}
}
else
{
if (inAttrib.iAttribute->getResolvedType(inAttrib) != outputType)
{
// Case: The current input is disconnected and the array type is unspecified (auto)
// Action: Resolve the current input to the inferred array type if any input is connected.
// If no inputs are connected, then outputType will be 'eUnknown', unresolving the current input.
tryResolveAttribute(nodeObj, inAttrib, outputType);
}
}
}
else if (upstreamConnectionCount == 1 && reconnectInputs) // reconnectInputs avoids an infinite loop
{
// Resolve connected inputs to the specified array type, or their upstream types if the array type is unspecified
if (state.m_inputArrayType.baseType != BaseDataType::eUnknown)
{
// Check if already resolved to the specified array type
if (inAttrib.iAttribute->getResolvedType(inAttrib) != state.m_inputArrayType)
{
// Disconnect before re-resolving
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
inAttrib.iAttribute->disconnectAttrs(upstreamConnection.attrObj, inAttrib, true);
// Case: The current input is connected and the array type is specified
// Action: Resolve the current input to the specified array type
tryResolveAttribute(nodeObj, inAttrib, state.m_inputArrayType);
// Reconnect
ConnectionInfo destConnection {inAttrib, upstreamConnection.connectionType};
inAttrib.iAttribute->connectAttrsEx(upstreamConnection.attrObj, destConnection, true);
}
}
else
{
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
Type const upstreamType = upstreamConnection.attrObj.iAttribute->getResolvedType(upstreamConnection.attrObj);
// Check if already resolved to the upstream type
if (inAttrib.iAttribute->getResolvedType(inAttrib) != upstreamType)
{
// Disconnect before re-resolving
inAttrib.iAttribute->disconnectAttrs(upstreamConnection.attrObj, inAttrib, true);
// Case: The current input is connected and the array type is unspecified (auto)
// Action: Resolve the current input to its upstream type (not the inferred array type 'outputType',
// which could be a different but compatible type or 'eUnknown')
tryResolveAttribute(nodeObj, inAttrib, Type(BaseDataType::eUnknown)); // Must be resolved to 'eUnknown', not 'upstreamType'
// Reconnect
ConnectionInfo destConnection {inAttrib, upstreamConnection.connectionType};
inAttrib.iAttribute->connectAttrsEx(upstreamConnection.attrObj, destConnection, true);
}
}
}
}
// Resolve the output
// If there is a type mismatch (regardless of whether the array type was specified), then 'outputType' gets set to 'eUnknown', so 'outputs:array' gets unresolved.
// If the array type is unspecified (auto) and no inputs are connected (i.e. no type is inferred), then 'outputType' gets set to 'eUnknown' as well (but the node does not error).
// Otherwise, 'outputs:array' gets resolved to the specified or inferred array type 'outputType'.
outputType.arrayDepth = 1;
auto outputArrayAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
tryResolveAttribute(nodeObj, outputArrayAttrib, outputType);
}
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
ConstAttributeDataHandle handle =
attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex);
auto const dataPtr = getDataR<NameToken>(context, handle);
if (dataPtr)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
state.m_inputArrayType = state.m_arrayTypes[*dataPtr];
}
tryResolveArrayAttributes(nodeObj, true);
}
static void onConnected(AttributeObj const& otherAttrib, AttributeObj const& inAttrib, void* userData)
{
NodeObj nodeObj{ inAttrib.iAttribute->getNode(inAttrib) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
NodeObj* thisNodeObj = reinterpret_cast<NodeObj*>(userData);
if (nodeObj.nodeHandle != thisNodeObj->nodeHandle)
return;
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
// Deregister onConnected callback to avoid infinite loop
struct ConnectionCallback connectedCallback = {onConnected, &state.m_nodeObj};
nodeObj.iNode->deregisterConnectedCallback(nodeObj, connectedCallback);
tryResolveArrayAttributes(nodeObj, true);
// Re-register onConnected callback
nodeObj.iNode->registerConnectedCallback(nodeObj, connectedCallback);
}
public:
omni::graph::core::NodeObj m_nodeObj;
std::unordered_map<NameToken, omni::graph::core::Type> m_arrayTypes;
omni::graph::core::Type m_inputArrayType;
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
state.m_nodeObj = nodeObj;
state.m_arrayTypes = {
{OgnConstructArrayDatabase::tokens.Bool, Type(BaseDataType::eBool)},
{OgnConstructArrayDatabase::tokens.Double, Type(BaseDataType::eDouble)},
{OgnConstructArrayDatabase::tokens.Float, Type(BaseDataType::eFloat)},
{OgnConstructArrayDatabase::tokens.Half, Type(BaseDataType::eHalf)},
{OgnConstructArrayDatabase::tokens.Int, Type(BaseDataType::eInt)},
{OgnConstructArrayDatabase::tokens.Int64, Type(BaseDataType::eInt64)},
{OgnConstructArrayDatabase::tokens.Token, Type(BaseDataType::eToken)},
{OgnConstructArrayDatabase::tokens.UChar, Type(BaseDataType::eUChar)},
{OgnConstructArrayDatabase::tokens.UInt, Type(BaseDataType::eUInt)},
{OgnConstructArrayDatabase::tokens.UInt64, Type(BaseDataType::eUInt64)},
{OgnConstructArrayDatabase::tokens.Double_2, Type(BaseDataType::eDouble, 2)},
{OgnConstructArrayDatabase::tokens.Double_3, Type(BaseDataType::eDouble, 3)},
{OgnConstructArrayDatabase::tokens.Double_4, Type(BaseDataType::eDouble, 4)},
{OgnConstructArrayDatabase::tokens.Double_9, Type(BaseDataType::eDouble, 9, 0, AttributeRole::eMatrix)},
{OgnConstructArrayDatabase::tokens.Double_16, Type(BaseDataType::eDouble, 16, 0, AttributeRole::eMatrix)},
{OgnConstructArrayDatabase::tokens.Float_2, Type(BaseDataType::eFloat, 2)},
{OgnConstructArrayDatabase::tokens.Float_3, Type(BaseDataType::eFloat, 3)},
{OgnConstructArrayDatabase::tokens.Float_4, Type(BaseDataType::eFloat, 4)},
{OgnConstructArrayDatabase::tokens.Half_2, Type(BaseDataType::eHalf, 2)},
{OgnConstructArrayDatabase::tokens.Half_3, Type(BaseDataType::eHalf, 3)},
{OgnConstructArrayDatabase::tokens.Half_4, Type(BaseDataType::eHalf, 4)},
{OgnConstructArrayDatabase::tokens.Int_2, Type(BaseDataType::eInt, 2)},
{OgnConstructArrayDatabase::tokens.Int_3, Type(BaseDataType::eInt, 3)},
{OgnConstructArrayDatabase::tokens.Int_4, Type(BaseDataType::eInt, 4)},
};
AttributeObj arrayTypeAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::arrayType.m_token);
arrayTypeAttrib.iAttribute->registerValueChangedCallback(arrayTypeAttrib, onValueChanged, true);
struct ConnectionCallback connectedCallback = {onConnected, &state.m_nodeObj};
nodeObj.iNode->registerConnectedCallback(nodeObj, connectedCallback);
onValueChanged(arrayTypeAttrib, nullptr);
}
static bool compute(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto const outputArrayAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
try
{
switch (outputArrayType.baseType)
{
case BaseDataType::eBool:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<bool>(db)) return true;
break;
case BaseDataType::eDouble:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<double>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<double, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<double, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<double, 4>(db)) return true;
break;
case 9:
if (tryComputeAssumingType<double, 9>(db)) return true;
break;
case 16:
if (tryComputeAssumingType<double, 16>(db)) return true;
break;
}
break;
case BaseDataType::eFloat:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<float>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<float, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<float, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<float, 4>(db)) return true;
break;
}
break;
case BaseDataType::eHalf:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<pxr::GfHalf>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<pxr::GfHalf, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<pxr::GfHalf, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<pxr::GfHalf, 4>(db)) return true;
break;
}
break;
case BaseDataType::eInt:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<int32_t>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<int32_t, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<int32_t, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<int32_t, 4>(db)) return true;
break;
}
break;
case BaseDataType::eInt64:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<int64_t>(db)) return true;
break;
case BaseDataType::eToken:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<OgnToken>(db)) return true;
break;
case BaseDataType::eUChar:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint8_t>(db)) return true;
break;
case BaseDataType::eUInt:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint32_t>(db)) return true;
break;
case BaseDataType::eUInt64:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint64_t>(db)) return true;
break;
default:
break;
}
db.logError("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
tryResolveArrayAttributes(nodeObj, false);
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 24,641 | C++ | 44.381215 | 186 | 0.603831 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendString.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnAppendStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnAppendString
{
public:
static bool compute(OgnAppendStringDatabase& db)
{
auto const& suffix = db.inputs.suffix();
if (suffix.type().baseType == BaseDataType::eToken)
return computeForToken(db);
return computeForString(db);
}
static bool computeForString(OgnAppendStringDatabase& db)
{
auto const inputValue = db.inputs.value();
auto const suffixIn = db.inputs.suffix();
auto const suffixData = suffixIn.get<uint8_t[]>();
auto& outValue = db.outputs.value();
// No suffix? Just copy in to out
if (suffixData->empty())
{
db.outputs.value().copyData(inputValue);
return true;
}
auto const inputValueData = inputValue.get<uint8_t[]>();
std::string outVal;
outVal.reserve(inputValueData.size() + suffixData.size());
outVal.append(reinterpret_cast<char const*>(inputValueData->data()), inputValueData.size());
outVal.append(reinterpret_cast<char const*>(suffixData->data()), suffixData.size());
auto outData = outValue.get<uint8_t[]>();
size_t outBufferSize = outVal.size();
outData->resize(outBufferSize);
memcpy(outData->data(), reinterpret_cast<uint8_t const*>(outVal.data()), outBufferSize);
return true;
}
static bool computeForToken(OgnAppendStringDatabase& db)
{
auto const& inputValue = db.inputs.value();
auto const& suffix = db.inputs.suffix();
std::vector<char const*> suffixes;
if (suffix.type().arrayDepth == 0)
{
NameToken suffixToken = *suffix.get<OgnToken>();
if (suffixToken != omni::fabric::kUninitializedToken)
suffixes.push_back(db.tokenToString(suffixToken));
}
else
{
const auto suffixTokens = *suffix.get<OgnToken[]>();
suffixes.resize(suffixTokens.size());
std::transform(suffixTokens.begin(), suffixTokens.end(), suffixes.begin(),
[&db](auto t) { return db.tokenToString(t); });
}
// No suffix? Just copy in to out
if (suffixes.empty())
{
db.outputs.value().copyData(inputValue);
return true;
}
if (inputValue.type().arrayDepth > 0)
{
const auto inputValueArray = *inputValue.get<OgnToken[]>();
auto outputPathArray = *db.outputs.value().get<OgnToken[]>();
outputPathArray.resize(inputValueArray.size());
if (suffixes.size() == 1)
{
const char* suffixStr = suffixes[0];
std::transform(inputValueArray.begin(), inputValueArray.end(), outputPathArray.begin(),
[&](const auto& p)
{
std::string s = db.tokenToString(p);
s += suffixStr;
return db.stringToToken(s.c_str());
});
}
else
{
if (inputValueArray.size() != suffixes.size())
{
CARB_LOG_ERROR("inputs:value and inputs:suffix arrays are not the same size (%zu and %zu)",
inputValueArray.size(), suffixes.size());
return false;
}
for (size_t i = 0; i < inputValueArray.size(); ++i)
{
std::string s = db.tokenToString(inputValueArray[i]);
s += suffixes[i];
outputPathArray[i] = db.stringToToken(s.c_str());
}
}
return true;
}
else
{
NameToken inValue = *inputValue.get<OgnToken>();
std::string s;
if (inValue != omni::fabric::kUninitializedToken)
{
s = db.tokenToString(inValue);
}
s += suffixes[0];
*db.outputs.value().get<OgnToken>() = db.stringToToken(s.c_str());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto inputVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::inputs::value.m_token);
auto outputVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::outputs::value.m_token);
auto suffixVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::inputs::suffix.m_token);
//in type
auto type = inputVal.iAttribute->getResolvedType(inputVal);
//if input is an array of token, suffix is allowed to be either a simple or an array of token(s)
if (type.baseType == BaseDataType::eToken && type.arrayDepth != 0)
{
// both in and out needs to be the same
std::array<AttributeObj, 2> attrs{ inputVal, outputVal };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
//change suffix if necessary
auto suffixType = suffixVal.iAttribute->getResolvedType(suffixVal);
if (suffixType.baseType == BaseDataType::eUChar)//string not compatible with tokens
suffixVal.iAttribute->setResolvedType(suffixVal, type);
}
else
{
// else, the 3 needs to have the same type
std::array<AttributeObj, 3> attrs{ inputVal, suffixVal, outputVal };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 6,240 | C++ | 35.497076 | 114 | 0.567949 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToHalf.cpp | // Copyright (c) 2022, 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.
//
#include <OgnToHalfDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToHalfDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = pxr::GfHalf(float(value)); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, pxr::GfHalf>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToHalfDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = pxr::GfHalf(float(value)); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, pxr::GfHalf>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToHalf
{
public:
// Node to convert numeric inputs to halfs
static bool computeVectorized(OgnToHalfDatabase& db, size_t count)
{
const auto& inputsValue = db.inputs.value();
auto& type = inputsValue.type();
bool result = false;
switch (type.baseType)
{
case BaseDataType::eBool:
{
result = tryComputeAssumingType<bool>(db, count);
break;
}
case BaseDataType::eDouble:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<double>(db, count);
break;
case 2:
result = tryComputeAssumingType<double, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<double, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<double, 4>(db, count);
break;
case 9:
result = tryComputeAssumingType<double, 9>(db, count);
break;
case 16:
result = tryComputeAssumingType<double, 16>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eFloat:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<float>(db, count);
break;
case 2:
result = tryComputeAssumingType<float, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<float, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<float, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eHalf:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<pxr::GfHalf>(db, count);
break;
case 2:
result = tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eInt:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<int32_t>(db, count);
break;
case 2:
result = tryComputeAssumingType<int32_t, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<int32_t, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<int32_t, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eInt64:
{
result = tryComputeAssumingType<int64_t>(db, count);
break;
}
case BaseDataType::eUChar:
{
result = tryComputeAssumingType<unsigned char>(db, count);
break;
}
case BaseDataType::eUInt:
{
result = tryComputeAssumingType<uint32_t>(db, count);
break;
}
case BaseDataType::eUInt64:
{
result = tryComputeAssumingType<uint64_t>(db, count);
break;
}
default:
{
result = false;
}
}
if (!result)
{
db.logError("Input could not be converted to half");
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eHalf, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 6,928 | C++ | 33.30198 | 132 | 0.487298 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnIsEmpty.cpp | // Copyright (c) 2022, 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.
//
#include <OgnIsEmptyDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/Types.h>
#include <string>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnIsEmpty
{
public:
static bool compute(OgnIsEmptyDatabase& db)
{
const auto& variable = db.inputs.input();
auto& type = variable.type();
switch (type.baseType)
{
case BaseDataType::eBool:
case BaseDataType::eUChar:
case BaseDataType::eInt:
case BaseDataType::eUInt:
case BaseDataType::eInt64:
case BaseDataType::eUInt64:
case BaseDataType::eHalf:
case BaseDataType::eFloat:
case BaseDataType::eDouble:
{
db.outputs.isEmpty() = variable.size() == 0;
return true;
}
case BaseDataType::eToken:
{
std::string converted = tryConvertToString<ogn::Token>(db, variable);
db.outputs.isEmpty() = converted.length() == 0;
return true;
}
default:
{
db.logError("Type %s not supported", getOgnTypeName(type).c_str());
}
}
return false;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 1,804 | C++ | 25.940298 | 85 | 0.601441 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToToken.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnToTokenDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
#include <sstream>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
bool tryComputeAssumingType(OgnToTokenDatabase& db)
{
std::string converted = tryConvertToString<T>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = db.stringToToken(converted.c_str());
return true;
}
template <typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToTokenDatabase& db)
{
std::string converted = tryConvertToString<T, tupleSize>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = db.stringToToken(converted.c_str());
return true;
}
} // namespace
class OgnToToken
{
public:
// Node to convert any input to a token
static bool compute(OgnToTokenDatabase& db)
{
NodeObj nodeObj = db.abi_node();
const AttributeObj attr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
const Type attrType = attr.iAttribute->getResolvedType(attr);
auto value = db.inputs.value();
if (attrType.baseType == BaseDataType::eUnknown)
{
db.logError("Unknown input data type");
return false;
}
// Compute the components, if the types are all resolved.
// This handles char and string case (get<ogn::string>() will return invalid result)
if (attrType.baseType == BaseDataType::eUChar)
{
if ((attrType.arrayDepth == 1) &&
((attrType.role == AttributeRole::eText) || (attrType.role == AttributeRole::ePath)))
{
auto val = db.inputs.value().template get<uint8_t[]>();
if (!val)
{
db.logError("Unable to resolve input type");
return false;
}
auto charData = val->data();
std::string str(charData, charData + val->size());
db.outputs.converted() = db.stringToToken(str.c_str());
return true;
}
else if (attrType.arrayDepth == 0)
{
uchar val = *db.inputs.value().template get<uchar>();
db.outputs.converted() = db.stringToToken(std::string(1, static_cast<char>(val)).c_str());
}
return true;
}
try
{
auto& inputType = db.inputs.value().type();
switch (inputType.baseType)
{
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double, 2>(db);
case 3: return tryComputeAssumingType<double, 3>(db);
case 4: return tryComputeAssumingType<double, 4>(db);
case 9: return tryComputeAssumingType<double, 9>(db);
case 16: return tryComputeAssumingType<double, 16>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float, 2>(db);
case 3: return tryComputeAssumingType<float, 3>(db);
case 4: return tryComputeAssumingType<float, 4>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t, 2>(db);
case 3: return tryComputeAssumingType<int32_t, 3>(db);
case 4: return tryComputeAssumingType<int32_t, 4>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to a token: %s", e.what());
return false;
}
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,950 | C++ | 33.598837 | 106 | 0.562689 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector2.cpp | // Copyright (c) 2022, 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.
//
#include <OgnBreakVector2Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryBreakVector(OgnBreakVector2Database& db)
{
const auto vector = db.inputs.tuple().template get<Type[2]>();
auto x = db.outputs.x().template get<Type>();
auto y = db.outputs.y().template get<Type>();
if (!vector || !x || !y){
return false;
}
*x = (*vector)[0];
*y = (*vector)[1];
return true;
}
} // namespace
// Node to break a 2-vector into it's component scalers
class OgnBreakVector2
{
public:
static bool compute(OgnBreakVector2Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryBreakVector<double>(db))
return true;
else if (tryBreakVector<float>(db))
return true;
else if (tryBreakVector<pxr::GfHalf>(db))
return true;
else if (tryBreakVector<int32_t>(db))
return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be broken: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token());
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::y.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
// Require inputs to be resolved before determining outputs' type
if (vectorType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs{ vector, x, y };
std::array<uint8_t, 3> tuples{ 2, 1, 1 };
std::array<uint8_t, 3> arrays{ 0, 0, 0 };
std::array<AttributeRole, 3> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 2,913 | C++ | 29.041237 | 142 | 0.625815 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToFloat.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnToFloatDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, float>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, float>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToFloat
{
public:
// Node to convert numeric inputs to floats
static bool computeVectorized(OgnToFloatDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to float: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eFloat, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,427 | C++ | 38.911764 | 126 | 0.609176 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRotate.cpp | // Copyright (c) 2021-2023, 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.
//
#include <OgnArrayRotateDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
// Custom implementation of std::rotate.
// Using std::rotate fails to build on Linux when the underlying type is a tuple (eg int[3])
template<class ForwardIt>
constexpr
ForwardIt
rotateArray(ForwardIt first, ForwardIt n_first, ForwardIt last)
{
if(first == n_first) return last;
if(n_first == last) return first;
ForwardIt read = n_first;
ForwardIt write = first;
ForwardIt next_read = first; // read position for when "read" hits "last"
while(read != last) {
if(write == next_read) next_read = read; // track where "first" went
std::iter_swap(write++, read++);
}
// rotate the remaining sequence into place
(rotateArray)(write, next_read, last);
return write;
}
template<typename T>
bool tryComputeAssumingType(OgnArrayRotateDatabase& db)
{
const auto& steps = db.inputs.steps();
if (auto array = db.inputs.array().template get<T[]>())
{
if (auto result = db.outputs.array().template get<T[]>())
{
*result = *array;
if (!result->empty())
{
if (steps < 0)
{
rotateArray(result->begin(), result->begin() - steps, result->end());
}
else if (steps > 0)
{
rotateArray(result->rbegin(), result->rbegin() + steps, result->rend());
}
}
return true;
}
}
return false;
}
} // namespace
class OgnArrayRotate
{
public:
static bool compute(OgnArrayRotateDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnArrayRotate: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
std::array<AttributeObj, 2> attrs {
node.iNode->getAttributeByToken(node, inputs::array.token()),
node.iNode->getAttributeByToken(node, outputs::array.token())
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 5,703 | C++ | 33.780488 | 92 | 0.57198 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSelectIf.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnSelectIfDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
result = condition ? a : b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool, T>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
if (condition)
{
memcpy(result, a, sizeof(T) * N);
}
else
{
memcpy(result, b, sizeof(T) * N);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool, T[N]>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
} // namespace
class OgnSelectIf
{
public:
static bool computeVectorized(OgnSelectIfDatabase& db, size_t count)
{
NodeObj nodeObj = db.abi_node();
const AttributeObj ifTrueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifTrue.token());
const Type ifTrueType = ifTrueAttr.iAttribute->getResolvedType(ifTrueAttr);
const AttributeObj ifFalseAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifFalse.token());
const Type ifFalseType = ifFalseAttr.iAttribute->getResolvedType(ifFalseAttr);
const AttributeObj conditionAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::condition.token());
const Type conditionType = conditionAttr.iAttribute->getResolvedType(conditionAttr);
// This handles string case (arrays of strings are not supported)
if (ifTrueType.baseType == BaseDataType::eUChar && ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar && ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const bool condition = *db.inputs.condition(idx).template get<bool>();
auto ifTrue = db.inputs.ifTrue(idx).template get<uint8_t[]>();
auto ifFalse = db.inputs.ifFalse(idx).template get<uint8_t[]>();
auto result = db.outputs.result(idx).template get<uint8_t[]>();
if (condition)
{
result->resize(ifTrue->size());
memcpy(&((*result)[0]), &((*ifTrue)[0]), result->size());
}
else
{
result->resize(ifFalse->size());
memcpy(&((*result)[0]), &((*ifFalse)[0]), result->size());
}
}
return true;
}
try
{
switch (ifTrueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db, count);
case BaseDataType::eDouble:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto ifTrue = node.iNode->getAttributeByToken(node, inputs::ifTrue.token());
auto ifFalse = node.iNode->getAttributeByToken(node, inputs::ifFalse.token());
auto condition = node.iNode->getAttributeByToken(node, inputs::condition.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto ifTrueType = ifTrue.iAttribute->getResolvedType(ifTrue);
auto ifFalseType = ifFalse.iAttribute->getResolvedType(ifFalse);
auto conditionType = condition.iAttribute->getResolvedType(condition);
// Require ifTrue, ifFalse, and condition to be resolved before determining result's type
if (ifTrueType.baseType != BaseDataType::eUnknown && ifFalseType.baseType != BaseDataType::eUnknown
&& conditionType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { ifTrue, ifFalse, result };
std::array<uint8_t, 3> tupleCounts {
ifTrueType.componentCount,
ifFalseType.componentCount,
std::max(ifTrueType.componentCount, ifFalseType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
ifTrueType.arrayDepth,
ifFalseType.arrayDepth,
std::max(conditionType.arrayDepth, std::max(ifTrueType.arrayDepth, ifFalseType.arrayDepth))
};
const bool isStringInput = (ifTrueType.baseType == BaseDataType::eUChar
&& ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar
&& ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0
&& ifTrueType.role == AttributeRole::eText
&& ifFalseType.role == AttributeRole::eText);
std::array<AttributeRole, 3> rolesBuf {
ifTrueType.role,
ifFalseType.role,
isStringInput ? AttributeRole::eText : AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 9,218 | C++ | 43.110048 | 114 | 0.580386 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayGetSize.cpp |
// Copyright (c) 2022, 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.
//
#include <OgnArrayGetSizeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
class OgnArrayGetSize
{
public:
static bool compute(OgnArrayGetSizeDatabase& db)
{
try
{
db.outputs.size() = int(db.inputs.array().size());
return true;
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 1> attrs { inputArray };
// all should have the same tuple count
std::array<uint8_t, 1> tupleCounts {
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 1> arrayDepths {
1
};
std::array<AttributeRole, 1> rolesBuf {
inputArrayType.role
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 2,153 | C++ | 31.636363 | 107 | 0.628425 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBuildString.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnBuildStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnBuildString
{
public:
static bool compute(OgnBuildStringDatabase& db)
{
auto const& inputValue = db.inputs.a();
auto const& suffixIn = db.inputs.b();
auto& outValue = db.outputs.value();
bool result = true;
if (inputValue.type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, inputValue, suffixIn, outValue);
else
result = result && computeForString(db, inputValue, suffixIn, outValue);
auto const& dynamicInputs = db.getDynamicInputs();
if (!result || dynamicInputs.empty())
return result;
auto accumulatingValue = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.value(), outputs::value.token());
for (auto const& input : dynamicInputs)
{
if (input().type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, accumulatingValue, input(), outValue);
else
result = result && computeForString(db, accumulatingValue, input(), outValue);
}
return result;
}
static bool computeForString(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffixIn,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
auto const suffixData = suffixIn.get<uint8_t[]>();
// No suffix? Just copy in to out
if (suffixData->empty())
{
// the inputValue may be an alias for the outValue
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
auto const inputValueData = inputValue.get<uint8_t[]>();
std::string outVal;
outVal.reserve(inputValueData.size() + suffixData.size());
outVal.append(reinterpret_cast<char const*>(inputValueData->data()), inputValueData.size());
outVal.append(reinterpret_cast<char const*>(suffixData->data()), suffixData.size());
auto outData = outValue.get<uint8_t[]>();
size_t outBufferSize = outVal.size();
outData->resize(outBufferSize);
memcpy(outData->data(), reinterpret_cast<uint8_t const*>(outVal.data()), outBufferSize);
return true;
}
static bool computeForToken(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffix,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
std::vector<char const*> suffixes;
if (suffix.type().arrayDepth == 0)
{
NameToken suffixToken = *suffix.get<OgnToken>();
if (suffixToken != omni::fabric::kUninitializedToken)
suffixes.push_back(db.tokenToString(suffixToken));
}
else
{
const auto suffixTokens = *suffix.get<OgnToken[]>();
suffixes.resize(suffixTokens.size());
std::transform(suffixTokens.begin(), suffixTokens.end(), suffixes.begin(),
[&db](auto t) { return db.tokenToString(t); });
}
// No suffix? Just copy in to out
if (suffixes.empty())
{
// the input value may be an alias for the output value
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
if (inputValue.type().arrayDepth > 0)
{
const auto inputValueArray = *inputValue.get<OgnToken[]>();
auto outputPathArray = *db.outputs.value().get<OgnToken[]>();
outputPathArray.resize(inputValueArray.size());
if (suffixes.size() == 1)
{
const char* suffixStr = suffixes[0];
std::transform(inputValueArray.begin(), inputValueArray.end(), outputPathArray.begin(),
[&](const auto& p)
{
std::string s = db.tokenToString(p);
s += suffixStr;
return db.stringToToken(s.c_str());
});
}
else
{
if (inputValueArray.size() != suffixes.size())
{
CARB_LOG_ERROR("inputs:value and inputs:suffix arrays are not the same size (%zu and %zu)",
inputValueArray.size(), suffixes.size());
return false;
}
for (size_t i = 0; i < inputValueArray.size(); ++i)
{
std::string s = db.tokenToString(inputValueArray[i]);
s += suffixes[i];
outputPathArray[i] = db.stringToToken(s.c_str());
}
}
return true;
}
else
{
NameToken inValue = *inputValue.get<OgnToken>();
std::string s;
if (inValue != omni::fabric::kUninitializedToken)
{
s = db.tokenToString(inValue);
}
s += suffixes[0];
*db.outputs.value().get<OgnToken>() = db.stringToToken(s.c_str());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto inputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::inputs::a.m_token);
auto outputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::outputs::value.m_token);
// in and out needs to be the same
std::array<AttributeObj, 2> io{ inputVal, outputVal };
node.iNode->resolveCoupledAttributes(node, io.data(), io.size());
//retrieve all other input attributes
auto totalCount = node.iNode->getAttributeCount(node);
std::vector<AttributeObj> attrs(totalCount);
node.iNode->getAttributes(node, attrs.data(), totalCount);
size_t idx = 0;
size_t count = totalCount;
while (idx != count)
{
if (attrs[idx].iAttribute->getPortType(attrs[idx]) != AttributePortType::kAttributePortType_Input ||
attrs[idx].attributeHandle == inputVal.attributeHandle)
{
count--;
std::swap(attrs[idx], attrs[count]);
}
else
{
idx++;
}
}
auto type = inputVal.iAttribute->getResolvedType(inputVal);
// if input is an array of token, suffixes are allowed to be either a simple or an array of token(s)
if (type.baseType == BaseDataType::eToken && type.arrayDepth != 0)
{
for (auto const& attr : attrs)
{
auto suffixType = attr.iAttribute->getResolvedType(attr);
if (suffixType.baseType == BaseDataType::eUChar) // string not compatible with tokens
attr.iAttribute->setResolvedType(attr, type);
}
}
else if (type.baseType != BaseDataType::eUnknown)
{
// else, they all needs to have the same type
for (auto const& attr : attrs)
attr.iAttribute->setResolvedType(attr, type);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 8,071 | C++ | 36.544186 | 130 | 0.564118 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToDouble.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnToDoubleDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToDoubleDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<double>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, double>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToDoubleDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<double>(value); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, double>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToDouble
{
public:
// Node to convert numeric inputs to floats
static bool computeVectorized(OgnToDoubleDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to float: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eDouble, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 5,463 | C++ | 39.17647 | 127 | 0.609555 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToUint64.cpp | // Copyright (c) 2022, 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.
//
#include <OgnToUint64Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToUint64Database& db)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<uint64_t>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, uint64_t>(db.inputs.value(), db.outputs.converted(), functor);
}
} // namespace
class OgnToUint64
{
public:
// Node to convert numeric inputs to floats
static bool compute(OgnToUint64Database& db)
{
auto& valueType = db.inputs.value().type();
switch (valueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<uint8_t>(db);
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eHalf:
return tryComputeAssumingType<pxr::GfHalf>(db);
case BaseDataType::eFloat:
return tryComputeAssumingType<float>(db);
case BaseDataType::eDouble:
return tryComputeAssumingType<double>(db);
default:
db.logError("Failed to resolve input types");
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eUInt64, 1, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,870 | C++ | 33.178571 | 122 | 0.666899 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnStartsWith.cpp | // Copyright (c) 2022, 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.
//
#include <OgnStartsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnStartsWith
{
public:
static bool compute(OgnStartsWithDatabase& db)
{
auto const& prefix = db.inputs.prefix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(prefix.begin(), prefix.end(), value.begin(), value.end());
db.outputs.isPrefix() = (iters.first == prefix.end());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 972 | C++ | 24.605263 | 93 | 0.704733 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSetGatheredAttribute.cpp | // Copyright (c) 2021-2021, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnSetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
// WARNING!
// The following code uses low-level ABI functionality and should not be copied for other purposes when such
// low level access is not required. Please use the OGN-generated API whenever possible.
#define RETURN_TRUE_EXEC \
{\
db.outputs.execOut() = kExecutionAttributeStateEnabled;\
return true;\
}
class OgnSetGatheredAttribute
{
public:
static bool compute(OgnSetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
const auto& value = db.inputs.value();
const auto& mask = db.inputs.mask();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
RETURN_TRUE_EXEC
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
if (gatherId == kInvalidGatherId)
RETURN_TRUE_EXEC
if (!mask.empty() && value.size() > 1 && mask.size() != value.size())
{
db.logError("The length of the write mask (%zd) does not match the length of the value (%zd)",
mask.size(), value.size());
return false;
}
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
if (elementSize == 0)
{
db.logError("The element type %s has zero size", elementType.getOgnTypeName().c_str());
return false;
}
Type srcDataType = db.inputs.value().type();
bool srcIsScaler = srcDataType.arrayDepth == 0;
if (!srcIsScaler)
{
// A scaler value will be broadcast
--srcDataType.arrayDepth;
}
if (!srcDataType.compatibleRawData(elementType))
{
db.logWarning("Attribute %s is not compatible with type '%s'", elementType.getTypeName().c_str(),
srcDataType.getTypeName().c_str());
RETURN_TRUE_EXEC
}
// determine the length of the content
size_t totalPrimCount{ 0 };
size_t inputArraySize = value.size();
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
(void)db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
if (inputArraySize > 1 && totalPrimCount + numRepeatedPaths != inputArraySize)
{
db.logError(
"Given value of length %zd is not equal to the number of gathered attributes (%zd)", inputArraySize, totalPrimCount + numRepeatedPaths);
return false;
}
//printf("Setting %zd prims worth (%zd bytes) to %s\n", totalPrimCount, totalPrimCount * elementSize,
// attributeNameStr);
// Finally, we copy the data from the attribute to the buckets
const IAttributeData& iAttributeData = *db.abi_context().iAttributeData;
AttributeObj inputAttr =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnSetGatheredAttributeAttributes::inputs::value.m_token);
ConstAttributeDataHandle inputHandle = inputAttr.iAttribute->getConstAttributeDataHandle(inputAttr);
ConstRawPtr srcPtr{ nullptr };
{
const void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
iAttributeData.getDataR((const void**)outPtr, db.abi_context(), &inputHandle, 1);
if (srcIsScaler)
srcPtr = reinterpret_cast<ConstRawPtr>(out);
else
srcPtr = reinterpret_cast<ConstRawPtr>(*out);
}
if (!srcPtr)
{
// No data to read
RETURN_TRUE_EXEC
}
size_t maskIndex = 0;
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (mask.empty())
{
size_t totalBytes = elementSize * primCount;
memcpy(destPtr, srcPtr, totalBytes);
if (!srcIsScaler)
srcPtr += totalBytes;
}
else
{
for (size_t j = 0; j < primCount; ++j)
{
if (mask[maskIndex++])
memcpy(destPtr, srcPtr, elementSize);
destPtr += elementSize;
if (!srcIsScaler)
srcPtr += elementSize;
}
}
}
// Set attribute for repeated paths
if (numRepeatedPaths > 0)
{
// If there are repeated paths, the set behaviour might be unexpected. Warn the user.
db.logWarning("Trying to set attribute when there are repeated prims in the gather. The first %zd values might be overwritten", totalPrimCount);
}
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
PathBucketIndex pathBucketIndex = repeatedPaths[i];
BucketId bucketId = std::get<1>(pathBucketIndex);
ArrayIndex index = std::get<2>(pathBucketIndex);
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
if (mask.empty() || mask[maskIndex++])
{
size_t byteCount = elementSize * index;
memcpy(destPtr + byteCount, srcPtr, elementSize);
if (!srcIsScaler)
srcPtr += elementSize;
}
}
RETURN_TRUE_EXEC
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,672 | C++ | 32.616279 | 156 | 0.577721 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFindValue.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayFindValueDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayFindValueDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
auto const value = db.inputs.value().template get<BaseType>();
if (!value || !inputArray)
return false;
for (size_t i = 0; i < inputArraySize; ++i)
{
if (memcmp(&((*inputArray)[i]), &*value, sizeof(BaseType)) == 0)
{
db.outputs.index() = int(i);
return true;
}
}
db.outputs.index() = -1;
return true;
}
} // namespace
class OgnArrayFindValue
{
public:
static bool compute(OgnArrayFindValueDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { inputArray, inputValue };
// all should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0,
};
std::array<AttributeRole, 2> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 5,811 | C++ | 37.490066 | 107 | 0.576149 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleInspector.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnBundleInspectorDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
template <typename CppType>
std::string valueToString(const CppType& value)
{
return std::to_string(value);
}
template <>
std::string valueToString(const pxr::GfHalf& value)
{
return std::to_string((float) value);
}
template <>
std::string valueToString(const bool& value)
{
return value ? "True" : "False";
}
// TODO: This string conversion code is better suited to the BundledAttribute where it is accessible to all
// Since there are only three matrix dimensions a lookup is faster than a sqrt() call.
const int matrixDimensionMap[17]{ 1, 1, 1, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 4 };
// Helper template to output a convertible simple value as a string. Used when std::to_string works on the type.
template <typename CppType>
bool simpleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
valueToSet = valueToString(*value);
return true;
}
return false;
}
// Helper template to output a convertible simple tuple value as a string.
// The output format is parenthesized "(X, Y, Z)"
template <typename CppType>
bool tupleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
valueToSet = "(";
if (inputType.isMatrixType())
{
uint8_t dimension = inputType.dimension();
uint8_t index{ 0 };
for (uint8_t row=0; row<dimension; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<dimension; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[index++]);
}
valueToSet += ")";
}
}
else
{
for (uint8_t tupleIndex=0; tupleIndex<value.tupleSize(); ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
return true;
}
return false;
}
// Helper template to output a convertible simple array value as a string.
// The output format has square brackets "[X, Y, Z]"
template <typename CppType>
bool arrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto arrayValue = runtimeInput.get<CppType>() )
{
auto role = runtimeInput.type().role;
auto baseType = runtimeInput.type().baseType;
const bool isString = (baseType == BaseDataType::eUChar) && ((role == AttributeRole::eText) || (role == AttributeRole::ePath));
if (isString)
{
std::string rawString(reinterpret_cast<const char*>(arrayValue->data()), arrayValue->size());
valueToSet = "'";
valueToSet += rawString;
valueToSet += "'";
}
else
{
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *arrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value);
}
valueToSet += "]";
}
return true;
}
return false;
}
// Helper template to output a convertible tuple array value as a string.
// The output format has square brackets "[(X1, Y1), (X2, Y2), (X3, Y3))]"
template <typename CppType>
bool tupleArrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto tupleArrayValue = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
const bool isMatrix = inputType.isMatrixType();
auto tupleSize = inputType.dimension();
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *tupleArrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
if (isMatrix)
{
int tupleIndex{ 0 };
for (int row=0; row<tupleSize; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<tupleSize; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex++]);
}
valueToSet += ")";
}
}
else
{
for (int tupleIndex=0; tupleIndex<tupleSize; ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
}
valueToSet += "]";
return true;
}
return false;
}
// Node whose responsibility is to analyze the contents of an input bundle attribute
// and create outputs describing them.
class OgnBundleInspector
{
private:
static void inspectRecursive
(
const int currentDepth,
const int inspectDepth,
const bool printContents,
OgnBundleInspectorDatabase& db,
const ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> &inputBundle,
std::ostream &output,
ogn::array<NameToken> &names,
ogn::array<NameToken> &types,
ogn::array<NameToken> &roles,
ogn::array<int> &arrayDepths,
ogn::array<int> &tupleCounts,
ogn::array<NameToken> &values
)
{
IToken const* iToken = carb::getCachedInterface<omni::fabric::IToken>();
auto bundleName = inputBundle.abi_bundleInterface()->getName();
std::string indent{" "};
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
output << "Bundle '" << iToken->getText(bundleName) << "' from " << db.abi_node().iNode->getPrimPath(db.abi_node())
<< " (attributes = " << attributeCount << " children = " << childCount << ")" << std::endl;
// Walk the contents of the input bundle, extracting the attribute information along the way
size_t index = 0;
for (const auto& bundledAttribute : inputBundle)
{
if (bundledAttribute.isValid())
{
// The attribute names and etc apply only to top level bundle passed to the BundleInspector
if (currentDepth == 0) names[index] = bundledAttribute.name();
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << indent << "[" << index << "] " << db.tokenToString(bundledAttribute.name());
const Type& attributeType = bundledAttribute.type();
output << "(" << attributeType << ")";
if (currentDepth == 0)
{
{
std::ostringstream nameStream;
nameStream << attributeType.baseType;
types[index] = db.stringToToken(nameStream.str().c_str());
}
{
std::ostringstream nameStream;
nameStream << getOgnRoleName(attributeType.role);
roles[index] = db.stringToToken(nameStream.str().c_str());
}
arrayDepths[index] = attributeType.arrayDepth;
tupleCounts[index] = attributeType.componentCount;
}
// Convert the value into a string, using an empty string for unknown types
std::string valueAsString{"__unsupported__"};
bool noOutput = !simpleValueToString<bool>(bundledAttribute, valueAsString)
&& !arrayValueToString<bool[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<int64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint8_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint8_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint32_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint32_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<double>(bundledAttribute, valueAsString)
&& !arrayValueToString<double[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][4]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[9]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][9]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[16]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][16]>(bundledAttribute, valueAsString)
&& !simpleValueToString<float>(bundledAttribute, valueAsString)
&& !arrayValueToString<float[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int>(bundledAttribute, valueAsString)
&& !arrayValueToString<int[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<pxr::GfHalf>(bundledAttribute, valueAsString)
&& !arrayValueToString<pxr::GfHalf[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][4]>(bundledAttribute, valueAsString)
;
if (noOutput)
{
if (const auto tokenValue = bundledAttribute.get<OgnToken>() )
{
std::ostringstream tokenValueStream;
tokenValueStream << std::quoted(db.tokenToString(*tokenValue));
valueAsString = tokenValueStream.str();
noOutput = false;
}
}
if (noOutput)
{
if (const auto tokenArrayValue = bundledAttribute.get<OgnToken[]>() )
{
std::ostringstream tokenArrayValueStream;
tokenArrayValueStream << "[";
size_t index{ 0 };
for (const auto& value : *tokenArrayValue)
{
if (index++ > 0)
{
tokenArrayValueStream << ", ";
}
tokenArrayValueStream << std::quoted(db.tokenToString(value));
}
tokenArrayValueStream << "]";
valueAsString = tokenArrayValueStream.str();
noOutput = false;
}
}
output << " = " << valueAsString << std::endl;
if (currentDepth == 0) values[index] = db.stringToToken(valueAsString.c_str());
if (noOutput)
{
std::ostringstream nameStream;
nameStream << attributeType;
db.logWarning("No value output known for attribute %zu (%s), defaulting to '__unsupported__'", index, nameStream.str().c_str());
}
index++;
}
else
{
output << indent << "Bundle is invalid" << std::endl;
db.logWarning("Ignoring invalid bundle member '%s'", db.tokenToString(bundledAttribute.name()));
}
}
// Walk through its children, if any
if (printContents && childCount && ((currentDepth < inspectDepth) || (inspectDepth <= -1)))
{
IConstBundle2* inputBundleIFace = inputBundle.abi_bundleInterface();
// context is for building the child BundleContents
const auto context = inputBundleIFace->getContext();
std::vector<ConstBundleHandle> childBundleHandles(childCount);
inputBundleIFace->getConstChildBundles(childBundleHandles.data(), childCount);
for (const auto& childHandle : childBundleHandles)
{
if (childHandle.isValid())
{
ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> childBundle(context, childHandle);
for (int numIndent = 0; numIndent < currentDepth + 1; numIndent++) output << indent;
output << "Has Child "; // No std::endl -> "Has Child Bundle from ..."
inspectRecursive(currentDepth+1, inspectDepth, printContents, db, childBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
}
else
{
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << "One child is invalid." << std::endl;
}
}
}
}
public:
static bool compute(OgnBundleInspectorDatabase& db)
{
const auto& inputBundle = db.inputs.bundle();
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
db.outputs.bundle() = inputBundle;
const auto& printContents = db.inputs.print();
const auto& inspectDepth = db.inputs.inspectDepth();
// Rather than pollute the file with a bunch of "if (printContents)" setting up a file stream with a
// bad bit causes the output to be thrown away without parsing.
std::ofstream ofs;
ofs.setstate(std::ios_base::badbit);
auto& output = printContents ? std::cout : ofs;
db.outputs.count() = attributeCount;
db.outputs.attributeCount() = attributeCount;
db.outputs.childCount() = childCount;
// Extract the output interfaces to nicer names
auto& names = db.outputs.names();
auto& types = db.outputs.types();
auto& roles = db.outputs.roles();
auto& arrayDepths = db.outputs.arrayDepths();
auto& tupleCounts = db.outputs.tupleCounts();
auto& values = db.outputs.values();
// All outputs except the count are arrays of that size - preallocate them here
names.resize(attributeCount);
types.resize(attributeCount);
roles.resize(attributeCount);
arrayDepths.resize(attributeCount);
tupleCounts.resize(attributeCount);
values.resize(attributeCount);
inspectRecursive(0, inspectDepth, printContents, db, inputBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 18,952 | C++ | 42.872685 | 162 | 0.538518 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayInsertValue.cpp |
// Copyright (c) 2022-2023, 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.
//
#include <OgnArrayInsertValueDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to clamp a given index to [0:arrayLength]
size_t tryWrapIndex(int index, size_t arraySize)
{
if (index < 0)
index = 0;
if (index > static_cast<int>(arraySize))
index = static_cast<int>(arraySize);
return static_cast<size_t>(index);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayInsertValueDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize);
auto const value = db.inputs.value().template get<BaseType>();
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!value || !inputArray)
return false;
(*outputArray).resize(inputArraySize+1);
memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * index);
memcpy(&((*outputArray)[index]), &*value, sizeof(BaseType));
memcpy(outputArray->data() + index + 1, inputArray->data() + index, sizeof(BaseType) * (inputArraySize - index));
return true;
}
} // namespace
class OgnArrayInsertValue
{
public:
static bool compute(OgnArrayInsertValueDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray };
// all should have the same tuple count
std::array<uint8_t, 3> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 3> arrayDepths {
1,
0,
1
};
std::array<AttributeRole, 3> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 6,511 | C++ | 38.95092 | 117 | 0.592689 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector2.cpp | // Copyright (c) 2022, 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.
//
#include <OgnMakeVector2Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryMakeVector(OgnMakeVector2Database& db)
{
const auto x = db.inputs.x().template get<Type>();
const auto y = db.inputs.y().template get<Type>();
auto vector = db.outputs.tuple().template get<Type[2]>();
if (vector && x && y){
(*vector)[0] = *x;
(*vector)[1] = *y;
return true;
}
const auto xArray = db.inputs.x().template get<Type[]>();
const auto yArray = db.inputs.y().template get<Type[]>();
auto vectorArray = db.outputs.tuple().template get<Type[][2]>();
if (!vectorArray || !xArray || !yArray){
return false;
}
if (xArray->size() != yArray->size())
{
throw ogn::compute::InputError("Input arrays of different lengths x:" +
std::to_string(xArray->size()) + ", y:" + std::to_string(yArray->size()));
}
vectorArray->resize(xArray->size());
for (size_t i = 0; i < vectorArray->size(); i++)
{
(*vectorArray)[i][0] = (*xArray)[i];
(*vectorArray)[i][1] = (*yArray)[i];
}
return true;
}
} // namespace
// Node to merge 2 scalers together to make 2-vector
class OgnMakeVector2
{
public:
static bool compute(OgnMakeVector2Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db))
return true;
else if (tryMakeVector<float>(db))
return true;
else if (tryMakeVector<pxr::GfHalf>(db))
return true;
else if (tryMakeVector<int32_t>(db))
return true;
else
{
db.logError("Failed to resolve input types");
return false;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::y.token());
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token());
auto xType = vector.iAttribute->getResolvedType(x);
auto yType = vector.iAttribute->getResolvedType(y);
// If one of the inputs is resolved we can resolve the other because they should match
std::array<AttributeObj, 2> attrs { x, y };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown && yType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs{ x, y, vector };
std::array<uint8_t, 3> tuples{ 1, 1, 2 };
std::array<uint8_t, 3> arrays{
xType.arrayDepth,
yType.arrayDepth,
xType.arrayDepth,
};
std::array<AttributeRole, 3> roles{ xType.role, yType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 4,201 | C++ | 30.593985 | 142 | 0.598429 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayIndex.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayIndexDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to wrap a given index from legal range [-arrayLength, arrayLength) to [0:arrayLength).
// values outside of the legal range with throw
size_t tryWrapIndex(int index, size_t arraySize)
{
int wrappedIndex = index;
if (index < 0)
wrappedIndex = (int)arraySize + index;
if ((wrappedIndex >= (int)arraySize) or (wrappedIndex < 0))
throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize));
return size_t(wrappedIndex);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayIndexDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const index = tryWrapIndex(db.inputs.index(), db.inputs.array().size());
auto outputValue = db.outputs.value().template get<BaseType>();
if (!outputValue || !inputArray)
return false;
memcpy(&*outputValue, &((*inputArray)[index]), sizeof(BaseType));
return true;
}
} // namespace
class OgnArrayIndex
{
public:
static bool compute(OgnArrayIndexDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const array = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const value = node.iNode->getAttributeByToken(node, outputs::value.token());
auto const arrayType = array.iAttribute->getResolvedType(array);
auto const valueType = value.iAttribute->getResolvedType(value);
if ((arrayType.baseType == BaseDataType::eUnknown) != (valueType.baseType == BaseDataType::eUnknown))
{
std::array<AttributeObj, 2> attrs { array, value };
// array and value should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
std::max(arrayType.componentCount, valueType.componentCount),
std::max(arrayType.componentCount, valueType.componentCount)
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0
};
std::array<AttributeRole, 2> rolesBuf {
arrayType.role,
// Copy the attribute role from the array type to the value type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,415 | C++ | 39.352201 | 142 | 0.595168 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPath.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnGetPrimPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPath
{
public:
static size_t computeVectorized(OgnGetPrimPathDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
auto primPaths = db.outputs.primPath.vectorized(count);
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prim(i);
if (prims.size() > 0)
{
auto text = pathInterface->getText(prims[0]);
db.outputs.path(i) = text;
primPaths[i] = tokenInterface->getHandle(text);
}
else
{
db.outputs.path(i) = "";
primPaths[i] = Token();
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,592 | C++ | 26.947368 | 79 | 0.607412 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetRelativePath.cpp | // Copyright (c) 2020-2023, 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.
//
#include <OgnGetRelativePathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getRelativePath(const NameToken& pathAsToken, const pxr::SdfPath& anchor)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto relPath = pxr::SdfPath(pathToken).MakeRelativePath(anchor);
return *asInt(&relPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetRelativePath
{
public:
static size_t computeVectorized(OgnGetRelativePathDatabase& db, size_t count)
{
auto anchor = db.inputs.anchor.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.relativePath(idx).copyData(db.inputs.path(idx));
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.relativePath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getRelativePath(p, anchorPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldAnchor = db.state.anchor.vectorized(count);
auto op = db.outputs.relativePath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldAnchor[idx] != anchor[idx] || oldInputs[idx] != inputPath[idx])
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
outputs[idx] = getRelativePath(inputPath[idx], anchorPath);
}
oldAnchor[idx] = anchor[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetRelativePathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetRelativePathAttributes::outputs::relativePath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,813 | C++ | 35.323809 | 136 | 0.577236 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendPath.cpp | // Copyright (c) 2020-2021, 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.
//
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/sdf/valueTypeName.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/FabricUSD.h>
#include <OgnAppendPathDatabase.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& appendPath(const NameToken& pathAsToken, const pxr::SdfPath& suffix)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto newPath = pxr::SdfPath(pathToken).AppendPath(suffix);
return *asInt(&newPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnAppendPath
{
public:
static size_t computeVectorized(OgnAppendPathDatabase& db, size_t count)
{
auto suffix = db.inputs.suffix.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.path(idx).copyData(db.inputs.path(idx));
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.path(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return appendPath(p, suffixPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldSuffix = db.state.suffix.vectorized(count);
auto op = db.outputs.path().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldSuffix[idx] != suffix[idx] || oldInputs[idx] != inputPath[idx])
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
outputs[idx] = appendPath(inputPath[idx], suffixPath);
}
oldSuffix[idx] = suffix[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnAppendPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnAppendPathAttributes::outputs::path.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,897 | C++ | 33.495575 | 123 | 0.576084 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnFindPrims.cpp | // Copyright (c) 2020-2021, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnFindPrimsDatabase.h>
#include <omni/fabric/FabricUSD.h>
#include "ReadPrimCommon.h"
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnFindPrims
{
struct Listener
{
UsdStageChangeListenerRefPtr changeListener; // Lets us know when the USD stage changes
};
public:
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener = UsdStageChangeListener::New(context, UsdStageChangeListener::ListenMode::eResync);
}
// ----------------------------------------------------------------------------
static void release(const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener.Reset();
}
// ----------------------------------------------------------------------------
static bool compute(OgnFindPrimsDatabase& db)
{
auto& ls = db.sharedState<Listener>();
auto inputType = db.inputs.type();
auto rootPrimPath = db.inputs.rootPrimPath();
auto rootPrim = db.inputs.rootPrim();
auto recursive = db.inputs.recursive();
auto namePrefix = db.inputs.namePrefix();
auto requiredAttributesStr = db.inputs.requiredAttributes();
auto requiredRelationship = db.inputs.requiredRelationship();
auto requiredRelationshipTargetStr = db.inputs.requiredRelationshipTarget();
auto requiredTarget = db.inputs.requiredTarget();
auto pathPattern = db.inputs.pathPattern();
auto ignoreSystemPrims = db.inputs.ignoreSystemPrims();
// We can skip compute if our state isn't dirty, and our inputs haven't changed
if (not ls.changeListener->checkDirty())
{
if (db.state.inputType() == inputType &&
db.state.rootPrim().size() == rootPrim.size() &&
(db.state.rootPrim().size() == 0 ? db.state.rootPrimPath() == rootPrimPath
: db.state.rootPrim()[0] == rootPrim[0]) &&
db.state.recursive() == recursive &&
db.state.namePrefix() == namePrefix &&
requiredAttributesStr == db.state.requiredAttributes() &&
db.state.requiredRelationship() == requiredRelationship &&
(db.state.requiredTarget.size() == 0 ? requiredRelationshipTargetStr == db.state.requiredRelationshipTarget()
: db.state.requiredTarget()[0] == requiredTarget[0]) &&
pathPattern == db.state.pathPattern() &&
ignoreSystemPrims == db.state.ignoreSystemPrims())
{
// Not dirty and inputs didn't change
return true;
}
}
db.state.inputType() = inputType;
db.state.rootPrimPath() = rootPrimPath;
db.state.rootPrim() = rootPrim;
db.state.recursive() = recursive;
db.state.namePrefix() = namePrefix;
db.state.requiredAttributes() = requiredAttributesStr;
db.state.requiredRelationship() = requiredRelationship;
db.state.requiredRelationshipTarget() = requiredRelationshipTargetStr;
db.state.requiredTarget() = requiredTarget;
db.state.pathPattern() = pathPattern;
db.state.ignoreSystemPrims() = ignoreSystemPrims;
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
pxr::UsdPrim startPrim;
if(rootPrim.size() == 0)
{
if (rootPrimPath == omni::fabric::kUninitializedToken)
startPrim = stage->GetPseudoRoot();
else
{
if (const char* primPathStr = db.tokenToString(rootPrimPath))
{
startPrim = stage->GetPrimAtPath(pxr::SdfPath(primPathStr));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", primPathStr);
return false;
}
}
}
}
else
{
if(rootPrim.size() > 1)
db.logWarning("Only one rootPrim target is supported, the rest will be ignored");
startPrim = stage->GetPrimAtPath(omni::fabric::toSdfPath(rootPrim[0]));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", db.pathToString(rootPrim[0]));
return false;
}
}
// Figure out the required type if any
pxr::TfToken requiredTypeName;
if (inputType != omni::fabric::kUninitializedToken)
{
if (char const* typeStr = db.tokenToString(inputType))
requiredTypeName = pxr::TfToken(typeStr);
}
char const* requiredNamePrefix{ db.tokenToString(namePrefix) };
// Figure out require relationship target if any
pxr::SdfPath requiredRelationshipTarget;
pxr::TfToken requiredRelName;
if (requiredRelationship != omni::fabric::kUninitializedToken)
{
requiredRelName = pxr::TfToken(db.tokenToString(requiredRelationship));
if (!requiredRelName.IsEmpty())
{
bool validTarget = (requiredTarget.size() == 0 && !requiredRelationshipTargetStr.empty());
if(requiredTarget.size() == 0)
{
if(!requiredRelationshipTargetStr.empty())
requiredRelationshipTarget = pxr::SdfPath{ requiredRelationshipTargetStr };
}
else
{
if(requiredTarget.size() > 1)
db.logWarning("Only one requiredTarget is supported, the rest will be ignored");
requiredRelationshipTarget = omni::fabric::toSdfPath(requiredTarget[0]);
}
if (validTarget && !requiredRelationshipTarget.IsPrimPath())
{
db.logError("Required relationship target \"%s\" is not valid", requiredRelationshipTarget.GetText());
}
}
}
// now find matching prims
pxr::TfToken requiredAttribs{ std::string{ requiredAttributesStr.data(), requiredAttributesStr.size() } };
PathVector matchedPaths;
findPrims_findMatching(matchedPaths, startPrim, recursive, requiredNamePrefix, requiredTypeName,
requiredAttribs, requiredRelName, requiredRelationshipTarget,
omni::fabric::intToToken(pathPattern), ignoreSystemPrims);
// output PathC
auto outputPrims = db.outputs.prims();
outputPrims.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPrims.begin(),
[&db](auto path) {return path;});
// convert PathC to TokenC
auto outputPaths = db.outputs.primPaths();
outputPaths.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPaths.begin(),
[&db](auto path)
{
const char* pathStr = omni::fabric::intToPath(path).GetText();
return db.stringToToken(pathStr);
});
return true;
}
static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// backward compatibility: `inputs:type`
// Prior to this version `inputs:type` attribute did not support wild cards.
// The meaning of an empty string was to include all types. With the introduction of the wild cards
// we need to convert an empty string to "*" in order to include all types.
static Token const value{ "*" };
if (nodeObj.iNode->getAttributeExists(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name))
{
AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name);
auto roHandle = attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex);
Token const* roValue = getDataR<Token const>(context, roHandle);
if (roValue && roValue->getString().empty())
{
Token* rwValue = getDataW<Token>(
context, attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex));
*rwValue = value;
}
}
else
{
nodeObj.iNode->createAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name, Type(BaseDataType::eToken), &value, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
}
return false;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 10,203 | C++ | 40.819672 | 149 | 0.565814 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToString.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnToStringDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToStringDatabase& db)
{
std::string converted = tryConvertToString<T>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = converted.c_str();
return true;
}
template<>
bool tryComputeAssumingType<ogn::Token>(OgnToStringDatabase& db)
{
std::string converted = tryConvertToString<ogn::Token>(db, db.inputs.value());
db.outputs.converted() = converted.c_str();
return true;
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToStringDatabase& db)
{
std::string converted = tryConvertToString<T, tupleSize>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = converted.c_str();
return true;
}
} // namespace
class OgnToString
{
public:
// Node to convert any input to a string
static bool compute(OgnToStringDatabase& db)
{
NodeObj nodeObj = db.abi_node();
const AttributeObj attr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
const Type attrType = attr.iAttribute->getResolvedType(attr);
auto value = db.inputs.value();
if (attrType.baseType == BaseDataType::eUnknown)
{
db.logError("Unknown input data type");
return false;
}
// Compute the components, if the types are all resolved.
// This handles char and string case (get<ogn::string>() will return invalid result)
if (attrType.baseType == BaseDataType::eUChar)
{
if ((attrType.arrayDepth == 1) &&
((attrType.role == AttributeRole::eText) || (attrType.role == AttributeRole::ePath)))
{
auto val = db.inputs.value().template get<uint8_t[]>();
if (!val)
{
db.logError("Unable to resolve input type");
return false;
}
auto charData = val->data();
std::string str = std::string(charData, charData + val->size());
db.outputs.converted() = str.c_str();
return true;
}
else if (attrType.arrayDepth == 0)
{
uchar val = *db.inputs.value().template get<uchar>();
db.outputs.converted() = std::string(1, static_cast<char>(val)).c_str();
return true;
}
}
try
{
auto& inputType = db.inputs.value().type();
switch (inputType.baseType)
{
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double, 2>(db);
case 3: return tryComputeAssumingType<double, 3>(db);
case 4: return tryComputeAssumingType<double, 4>(db);
case 9: return tryComputeAssumingType<double, 9>(db);
case 16: return tryComputeAssumingType<double, 16>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float, 2>(db);
case 3: return tryComputeAssumingType<float, 3>(db);
case 4: return tryComputeAssumingType<float, 4>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t, 2>(db);
case 3: return tryComputeAssumingType<int32_t, 3>(db);
case 4: return tryComputeAssumingType<int32_t, 4>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to string: %s", e.what());
return false;
}
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 6,249 | C++ | 33.530387 | 101 | 0.566971 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetGatheredAttribute.cpp | // Copyright (c) 2021-2021, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnGetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
class OgnGetGatheredAttribute
{
public:
static bool compute(OgnGetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
return true;
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
Type outputType(elementType);
++outputType.arrayDepth;
// Determine if the output attribute has already been resolved to an incompatible type
if (db.outputs.value().resolved())
{
Type outType = db.outputs.value().type();
if (!outputType.compatibleRawData(outType))
{
db.logWarning("Resolved type %s of outputs:value is not compatible with type %s",
outType.getOgnTypeName().c_str(), db.outputs.value().type().getOgnTypeName().c_str());
return false;
}
}
// If it's resolved, we already know that it is compatible from the above check
if (!db.outputs.value().resolved())
{
// Not resolved, so we have to resolve it now. This node is strange in that the resolved output type
// depends on external state instead of other attributes.
AttributeObj out = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token);
out.iAttribute->setResolvedType(out, outputType);
db.outputs.value().reset(db.abi_context(), out.iAttribute->getAttributeDataHandle(out), out);
}
AttributeObj outputAttr = nodeObj.iNode->getAttributeByToken(
nodeObj, OgnGetGatheredAttributeAttributes::outputs::value.m_token);
AttributeDataHandle outputHandle = outputAttr.iAttribute->getAttributeDataHandle(outputAttr);
// determine the length of the output
size_t totalPrimCount{ 0 };
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
void* ptr = db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
if (!ptr)
{
CARB_LOG_WARN("Attribute %s not found in Gather %zd, bucket %zd", attributeNameStr, gatherId, size_t(bucketId));
return true;
}
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
//printf("Getting %zd prims worth of %s\n", totalPrimCount, attributeNameStr);
// Set the required length of output array
db.abi_context().iAttributeData->setElementCount(db.abi_context(), outputHandle, totalPrimCount + numRepeatedPaths);
// Get pointer to target data
uint8_t* destPtr = nullptr;
{
void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
db.abi_context().iAttributeData->getDataW(outPtr, db.abi_context(), &outputHandle, 1);
destPtr = (uint8_t*)(*out);
}
CARB_ASSERT(destPtr);
// Finally, we copy the data into the output, bucket by bucket
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
size_t byteCount = elementSize * primCount;
{
// Copy the data
memcpy(destPtr, srcPtr, byteCount);
// Move the write pointer
destPtr += byteCount;
}
}
// Copy the data for repeated paths
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
BucketId bucketId = std::get<1>(repeatedPaths[i]);
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
ArrayIndex index = std::get<2>(repeatedPaths[i]);
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
size_t byteCount = elementSize * index;
{
// Copy the data
memcpy(destPtr, srcPtr + byteCount, elementSize);
// Move the write pointer
destPtr += elementSize;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 7,383 | C++ | 34.84466 | 128 | 0.592713 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeArray.py | """
This is the implementation of the OGN node defined in OgnMakeArrayDouble3.ogn
"""
import omni.graph.core as og
class OgnMakeArray:
"""
Makes an output array attribute from input values
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN:
return False
array_size = db.inputs.arraySize
out_array = []
if array_size > 0:
out_array.append(db.inputs.a.value)
if array_size > 1:
out_array.append(db.inputs.b.value)
if array_size > 2:
out_array.append(db.inputs.c.value)
if array_size > 3:
out_array.append(db.inputs.d.value)
if array_size > 4:
out_array.append(db.inputs.e.value)
out_array.extend([db.inputs.e.value] * (array_size - 5))
db.outputs.array.value = out_array
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
attribs = [(node.get_attribute("inputs:" + a), None, 0, None) for a in ("a", "b", "c", "d", "e")]
attribs.append((node.get_attribute("outputs:array"), None, 1, None))
og.resolve_base_coupled(attribs)
| 1,266 | Python | 29.902438 | 105 | 0.591627 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPath.cpp | // Copyright (c) 2020-2023, 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.
//
#include <OgnGetParentPathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getParentPath(const NameToken& pathAsToken)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto parentPath = pxr::SdfPath(pathToken).GetParentPath();
return *asInt(&parentPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPath
{
public:
static bool computeVectorized(OgnGetParentPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.parentPath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getParentPath(p); });
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto op = db.outputs.parentPath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldInputs[idx] != inputPath[idx])
{
outputs[idx] = getParentPath(inputPath[idx]);
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetParentPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetParentPathAttributes::outputs::parentPath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,841 | C++ | 32.046511 | 132 | 0.619852 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector3.cpp | // Copyright (c) 2022, 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.
//
#include <OgnBreakVector3Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryBreakVector(OgnBreakVector3Database& db, size_t count = 1)
{
const auto vector = db.inputs.tuple().template get<Type[3]>();
const auto x = db.outputs.x().template get<Type>();
const auto y = db.outputs.y().template get<Type>();
const auto z = db.outputs.z().template get<Type>();
if (!vector || !x || !y || !z)
return false;
const auto pVector = vector.vectorized(count);
const auto px = x.vectorized(count);
const auto py = y.vectorized(count);
const auto pz = z.vectorized(count);
if (pVector.empty() || px.empty() || py.empty() || pz.empty())
return false;
for (size_t i = 0; i < count; i++)
{
px[i] = pVector[i][0];
py[i] = pVector[i][1];
pz[i] = pVector[i][2];
}
return true;
}
} // namespace
// Node to break a 3-vector into it's component scalers
class OgnBreakVector3
{
public:
static size_t computeVectorized(OgnBreakVector3Database& db, size_t count)
{
// Compute the components, if the types are all resolved.
try
{
if (tryBreakVector<double>(db, count))
return count;
else if (tryBreakVector<float>(db, count))
return true;
else if (tryBreakVector<pxr::GfHalf>(db, count))
return count;
else if (tryBreakVector<int32_t>(db, count))
return count;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be broken: %s", e.what());
return 0;
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token());
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::z.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
// Require inputs to be resolved before determining outputs' type
if (vectorType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 4> attrs{ vector, x, y, z };
std::array<uint8_t, 4> tuples{ 3, 1, 1, 1};
std::array<uint8_t, 4> arrays{ 0, 0, 0, 0 };
std::array<AttributeRole, 4> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 3,528 | C++ | 30.792793 | 142 | 0.622166 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArraySetIndex.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArraySetIndexDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to wrap a given index from legal range [-arrayLength, arrayLength) to [0:arrayLength)
// This will throw if the wrapped index is greater than arraySize when resizeToFit is false,
// or if the wrapped index is negative.
size_t tryWrapIndex(int index, size_t arraySize, bool resizeToFit)
{
int wrappedIndex = index;
if (index < 0)
wrappedIndex = static_cast<int>(arraySize) + index;
if ((wrappedIndex >= static_cast<int>(arraySize) && !resizeToFit) || wrappedIndex < 0)
throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize));
return static_cast<size_t>(wrappedIndex);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArraySetIndexDatabase& db)
{
auto inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize, db.inputs.resizeToFit());
auto const value = db.inputs.value().template get<BaseType>();
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!value || !inputArray)
return false;
// tryWrapIndex would have thrown already if index >= inputArraySize and resizeToFit is false
size_t outputArraySize = std::max(inputArraySize, index + 1);
(*outputArray).resize(outputArraySize);
memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * inputArraySize);
if (outputArraySize > inputArraySize)
memset(&((*outputArray)[inputArraySize]), 0, sizeof(BaseType) * (outputArraySize - inputArraySize));
memcpy(&((*outputArray)[index]), &*value, sizeof(BaseType));
return true;
}
} // namespace
class OgnArraySetIndex
{
public:
static bool compute(OgnArraySetIndexDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray };
// all should have the same tuple count
std::array<uint8_t, 3> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 3> arrayDepths {
1,
0,
1
};
std::array<AttributeRole, 3> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 7,156 | C++ | 41.1 | 142 | 0.608161 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveIndex.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayRemoveIndexDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to wrap a given index from legal range [-arrayLength, arrayLength) to [0:arrayLength)
// This will throw if the wrapped index is out of bounds
size_t tryWrapIndex(int index, size_t arraySize)
{
int wrappedIndex = index;
if (index < 0)
wrappedIndex = static_cast<int>(arraySize) + index;
if (wrappedIndex < 0 || wrappedIndex >= static_cast<int>(arraySize))
throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize));
return static_cast<size_t>(wrappedIndex);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayRemoveIndexDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize);
if (!inputArray)
return false;
// make sure the types match before copying input into output
if (db.inputs.array().type() != db.outputs.array().type())
{
auto attribute = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::array.m_token);
auto handle = db.outputs.array().abi_handle();
attribute.iAttribute->setResolvedType(attribute, db.inputs.array().type());
db.outputs.array().reset(db.abi_context(), handle, attribute);
}
db.outputs.array().copyData(db.inputs.array());
auto outputArray = db.outputs.array().template get<BaseType[]>();
memcpy(outputArray->data() + index, outputArray->data() + index + 1, sizeof(BaseType) * (inputArraySize - index - 1));
(*outputArray).resize(inputArraySize - 1);
return true;
}
} // namespace
class OgnArrayRemoveIndex
{
public:
static bool compute(OgnArrayRemoveIndexDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { inputArray, outputArray };
// all should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
1
};
std::array<AttributeRole, 2> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 6,771 | C++ | 40.292683 | 142 | 0.608477 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimRelationship.cpp | // Copyright (c) 2021, 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.
//
#include "OgnGetPrimRelationshipDatabase.h"
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <algorithm>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimRelationship
{
public:
// Queries relationship data on a prim
static bool compute(OgnGetPrimRelationshipDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
try {
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::path.token(),
inputs::usePath.token(), db.getInstanceIndex());
const char* relName = db.tokenToString(db.inputs.name());
if (!relName)
return false;
long int stageId = iContext->getStageId(contextObj);
pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
pxr::UsdPrim prim = stage->GetPrimAtPath(primPath);
if (!prim)
return false;
pxr::UsdRelationship relationship = prim.GetRelationship(pxr::TfToken(relName));
pxr::SdfPathVector targets;
if (relationship.GetTargets(&targets))
{
auto& outputPaths = db.outputs.paths();
outputPaths.resize(targets.size());
std::transform(targets.begin(), targets.end(), outputPaths.begin(),
[&db](const pxr::SdfPath& path) { return db.stringToToken(path.GetText()); });
}
return true;
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// for older nodes, inputs:usePath must equal true so the prim path method is on by default
const bool val{ true };
nodeObj.iNode->createAttribute(nodeObj, "inputs:usePath", Type(BaseDataType::eBool), &val, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
return false;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,133 | C++ | 31.309278 | 122 | 0.618896 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimsAtPath.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnGetPrimsAtPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimsAtPath
{
public:
static bool computeVectorized(OgnGetPrimsAtPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
auto& outPrims = db.outputs.prims(idx);
const auto paths = *db.inputs.path(idx).template get<OgnToken[]>();
outPrims.resize(paths.size());
std::transform(paths.begin(), paths.end(), outPrims.begin(),
[&](const auto& p) {
return (p != omni::fabric::kUninitializedToken) ? db.tokenToPath(p) : omni::fabric::kUninitializedPath;
});
}
}
else
{
const auto pathPtr = db.inputs.path().template get<OgnToken>();
if (pathPtr)
{
auto path = pathPtr.vectorized(count);
auto oldPath = db.state.path.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
auto outPrims = db.outputs.prims(idx);
if (oldPath[idx] != path[idx])
{
if (path[idx] != omni::fabric::kUninitializedToken)
{
outPrims.resize(1);
outPrims[0] = db.tokenToPath(path[idx]);
}
else
{
outPrims.resize(0);
}
}
}
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,255 | C++ | 30.333333 | 127 | 0.504656 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector4.cpp | // Copyright (c) 2022, 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.
//
#include <OgnMakeVector4Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryMakeVector(OgnMakeVector4Database& db)
{
const auto x = db.inputs.x().template get<Type>();
const auto y = db.inputs.y().template get<Type>();
const auto z = db.inputs.z().template get<Type>();
const auto w = db.inputs.w().template get<Type>();
auto vector = db.outputs.tuple().template get<Type[4]>();
if (vector && x && y && z && w)
{
(*vector)[0] = *x;
(*vector)[1] = *y;
(*vector)[2] = *z;
(*vector)[3] = *w;
return true;
}
const auto xArray = db.inputs.x().template get<Type[]>();
const auto yArray = db.inputs.y().template get<Type[]>();
const auto zArray = db.inputs.z().template get<Type[]>();
const auto wArray = db.inputs.w().template get<Type[]>();
auto vectorArray = db.outputs.tuple().template get<Type[][4]>();
if (!vectorArray || !xArray || !yArray || !zArray || !wArray)
{
return false;
}
if (xArray->size() != yArray->size() || xArray->size() != zArray->size() || xArray->size() != wArray->size())
{
throw ogn::compute::InputError("Input arrays of different lengths x:" +
std::to_string(xArray->size()) + ", y:" +
std::to_string(yArray->size()) + ", z:" +
std::to_string(zArray->size()) + ", w:" +
std::to_string(wArray->size()));
}
vectorArray->resize(xArray->size());
for (size_t i = 0; i < vectorArray->size(); i++)
{
(*vectorArray)[i][0] = (*xArray)[i];
(*vectorArray)[i][1] = (*yArray)[i];
(*vectorArray)[i][2] = (*zArray)[i];
(*vectorArray)[i][3] = (*wArray)[i];
}
return true;
}
} // namespace
// Node to merge 4 scalers together to make 4-vector
class OgnMakeVector4
{
public:
static bool compute(OgnMakeVector4Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db))
return true;
else if (tryMakeVector<float>(db))
return true;
else if (tryMakeVector<pxr::GfHalf>(db))
return true;
else if (tryMakeVector<int32_t>(db))
return true;
else
{
db.logError("Failed to resolve input types");
return false;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::z.token());
auto w = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::w.token());
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token());
auto xType = vector.iAttribute->getResolvedType(x);
auto yType = vector.iAttribute->getResolvedType(y);
auto zType = vector.iAttribute->getResolvedType(z);
auto wType = vector.iAttribute->getResolvedType(w);
std::array<AttributeObj, 4> attrs{ x, y, z, w };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
zType = vector.iAttribute->getResolvedType(z);
wType = vector.iAttribute->getResolvedType(w);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown && yType.baseType != BaseDataType::eUnknown &&
zType.baseType != BaseDataType::eUnknown && wType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 5> attrs{ x, y, z, w, vector };
std::array<uint8_t, 5> tuples{ 1, 1, 1, 1, 4 };
std::array<uint8_t, 5> arrays{
xType.arrayDepth,
yType.arrayDepth,
zType.arrayDepth,
wType.arrayDepth,
xType.arrayDepth
};
std::array<AttributeRole, 5> roles{ xType.role, yType.role, zType.role, wType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(
nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,369 | C++ | 33.645161 | 119 | 0.583349 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFill.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayFillDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
// Custom implementation of std::rotate.
// Using std::fill fails to build on Linux when the underlying type is a tuple (eg int[3])
template< class ForwardIt, class T >
void fillArray(ForwardIt first, ForwardIt last, const T& value)
{
for (; first != last; ++first) {
memcpy(&*first, &value, sizeof(*first));
}
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayFillDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
auto const fillValue = db.inputs.fillValue().template get<BaseType>();
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!fillValue || !inputArray)
return false;
(*outputArray).resize(inputArraySize);
fillArray(outputArray->begin(), outputArray->end(), *fillValue);
return true;
}
} // namespace
class OgnArrayFill
{
public:
static bool compute(OgnArrayFillDatabase& db)
{
auto& inputType = db.inputs.fillValue().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputFillValue = node.iNode->getAttributeByToken(node, inputs::fillValue.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { inputArray, inputFillValue, outputArray };
// all should have the same tuple count
std::array<uint8_t, 3> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 3> arrayDepths {
1,
0,
1
};
std::array<AttributeRole, 3> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 6,298 | C++ | 38.616352 | 107 | 0.591458 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveValue.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayRemoveValueDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
// Custom implementation of std::remove_if.
// Using std::remove_if fails to build when the underlying type is a tuple (eg int[3])
template<class ForwardIt, class UnaryPredicate>
int removeArray(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
int outputArraySize = 0;
first = std::find_if(first, last, p);
if (first != last) {
for(ForwardIt i = first; ++i != last; ) {
if (!p(*i)) {
memcpy(&*first++, &*i, sizeof(*first));
outputArraySize++;
}
}
}
return outputArraySize;
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayRemoveValueDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
auto const value = db.inputs.value().template get<BaseType>();
bool const removeAll = db.inputs.removeAll();
size_t const inputArraySize = db.inputs.array().size();
size_t const stride = sizeof(BaseType);
db.outputs.found() = false;
if (!value || !inputArray)
return false;
// make sure the types match before copying input into output
if (db.inputs.array().type() != db.outputs.array().type())
{
auto attribute = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::array.m_token);
auto handle = db.outputs.array().abi_handle();
attribute.iAttribute->setResolvedType(attribute, db.inputs.array().type());
db.outputs.array().reset(db.abi_context(), handle, attribute);
}
db.outputs.array().copyData(db.inputs.array());
auto equalsValue = [&value, &stride](auto &i) { return memcmp(&i, &*value, stride) == 0; };
auto const it = std::find_if(inputArray->begin(), inputArray->end(), equalsValue);
if (it == inputArray->end()){
return true;
}
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (removeAll) {
const int outputArraySize = removeArray(outputArray->begin(), outputArray->end(), equalsValue);
(*outputArray).resize(outputArraySize);
}
else {
const int index = static_cast<int>(it - inputArray->begin());
memcpy(outputArray->data() + index, outputArray->data() + index + 1, stride * (inputArraySize - index - 1));
(*outputArray).resize(inputArraySize - 1);
}
db.outputs.found() = true;
return true;
}
} // namespace
class OgnArrayRemoveValue
{
public:
static bool compute(OgnArrayRemoveValueDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray };
// all should have the same tuple count
std::array<uint8_t, 3> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 3> arrayDepths {
1,
0,
1
};
std::array<AttributeRole, 3> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 7,776 | C++ | 38.678571 | 116 | 0.592335 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnCompare.cpp | // Copyright (c) 2021-2023, 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.
//
#include <OgnCompareDatabase.h>
#include <functional>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
std::function<bool(const T&, const T&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
// Find the desired comparison
std::function<bool(const T&, const T&)> fn;
if (operation == db.tokens.gt) fn = [](const T& a, const T& b){ return a > b; };
else if (operation == db.tokens.lt) fn =[](const T& a, const T& b){ return a < b; };
else if (operation == db.tokens.ge) fn = [](const T& a, const T& b){ return a >= b; };
else if (operation == db.tokens.le) fn = [](const T& a, const T& b){ return a <= b; };
else if (operation == db.tokens.eq) fn = [](const T& a, const T& b){ return a == b; };
else if (operation == db.tokens.ne) fn = [](const T& a, const T& b){ return a != b; };
else
{
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
}
return fn;
}
template<>
std::function<bool(const OgnToken&, const OgnToken&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
std::function<bool(const OgnToken&, const OgnToken&)> fn;
if (operation == db.tokens.eq)
fn = [](const OgnToken& a, const OgnToken& b) { return a == b; };
else if (operation == db.tokens.ne)
fn = [](const OgnToken& a, const OgnToken& b) { return a != b; };
else if (operation == db.tokens.gt || operation == db.tokens.lt || operation == db.tokens.ge || operation == db.tokens.le)
throw ogn::compute::InputError("Operation " + std::string(db.tokenToString(operation)) +
" not supported for Tokens, expected one of (==,!=)");
else
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
return fn;
}
template<typename T>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
result = op(a, b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Lexicographical comparison of tuples
result = true;
for (size_t i = 0; i < N; i++)
{
if (i < (N - 1) && (a[i] == b[i]))
continue;
else if (op(a[i], b[i]))
{
result = true;
break;
}
else
{
result = false;
break;
}
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
bool tryComputeAssumingString(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<ogn::const_string>(db, operation);
for (size_t idx = 0; idx < count; ++idx)
{
auto stringA = db.inputs.a(idx).get<const char[]>();
auto stringB = db.inputs.b(idx).get<const char[]>();
*(db.outputs.result(idx).get<bool>()) = op(stringA(), stringB());
}
return true;
}
} // namespace
class OgnCompare
{
public:
static bool computeVectorized(OgnCompareDatabase& db, size_t count)
{
try
{
auto& aType = db.inputs.a().type();
auto& bType = db.inputs.b().type();
if (aType.baseType != bType.baseType || aType.componentCount != bType.componentCount)
throw ogn::compute::InputError("Failed to resolve input types");
const auto& operation = db.inputs.operation();
if ((operation != db.tokens.gt) and (operation != db.tokens.lt) and (operation != db.tokens.ge) and
(operation != db.tokens.le) and (operation != db.tokens.eq) and (operation != db.tokens.ne))
{
std::string op{ "Unknown" };
char const* opStr = db.tokenToString(operation);
if (opStr)
op = opStr;
throw ogn::compute::InputError("Unrecognized operation '" + op + std::string("'"));
}
auto node = db.abi_node();
auto opAttrib = node.iNode->getAttributeByToken(node, inputs::operation.m_token);
bool isOpConstant = opAttrib.iAttribute->isRuntimeConstant(opAttrib);
using FUNC_SIG = bool (*)(OgnCompareDatabase& db, NameToken operation, size_t count);
auto repeatWork = [&](FUNC_SIG const& func)
{
if (isOpConstant)
{
return func(db, operation, count);
}
bool ret = true;
while (count)
{
ret = func(db, operation, 1) && ret;
db.moveToNextInstance();
--count;
}
return ret;
};
switch (aType.baseType)
{
case BaseDataType::eBool:
return repeatWork(tryComputeAssumingType<bool>);
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<double>);
case 2: return repeatWork(tryComputeAssumingType<double, 2>);
case 3: return repeatWork(tryComputeAssumingType<double, 3>);
case 4: return repeatWork(tryComputeAssumingType<double, 4>);
case 9: return repeatWork(tryComputeAssumingType<double, 9>);
case 16: return repeatWork(tryComputeAssumingType<double, 16>);
}
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<float>);
case 2: return repeatWork(tryComputeAssumingType<float, 2>);
case 3: return repeatWork(tryComputeAssumingType<float, 3>);
case 4: return repeatWork(tryComputeAssumingType<float, 4>);
}
case BaseDataType::eInt:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<int32_t>);
case 2: return repeatWork(tryComputeAssumingType<int32_t, 2>);
case 3: return repeatWork(tryComputeAssumingType<int32_t, 3>);
case 4: return repeatWork(tryComputeAssumingType<int32_t, 4>);
}
case BaseDataType::eHalf:
return repeatWork(tryComputeAssumingType<pxr::GfHalf>);
case BaseDataType::eInt64:
return repeatWork(tryComputeAssumingType<int64_t>);
case BaseDataType::eUChar:
if (aType.role == AttributeRole::eText && bType.role == AttributeRole::eText &&
aType.arrayDepth == 1 && bType.arrayDepth == 1 && aType.componentCount == 1 &&
bType.componentCount == 1)
{
return repeatWork(tryComputeAssumingString);
}
return repeatWork(tryComputeAssumingType<unsigned char>);
case BaseDataType::eUInt:
return repeatWork(tryComputeAssumingType<uint32_t>);
case BaseDataType::eToken:
return repeatWork(tryComputeAssumingType<OgnToken>);
case BaseDataType::eUInt64:
return repeatWork(tryComputeAssumingType<uint64_t>);
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining result's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
const bool isStringInput = (aType.baseType == BaseDataType::eUChar && bType.baseType == BaseDataType::eUChar
&& aType.role == AttributeRole::eText && bType.role == AttributeRole::eText
&& aType.arrayDepth == 1 && bType.arrayDepth == 1
&& aType.componentCount == 1 && bType.componentCount == 1);
const uint8_t resultArrayDepth = isStringInput ? 0 : std::max(aType.arrayDepth, bType.arrayDepth);
Type resultType(BaseDataType::eBool, 1, resultArrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 10,275 | C++ | 40.772358 | 142 | 0.57635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleConstructor.py | """
Module contains the OmniGraph node implementation of BundleConstructor
"""
import omni.graph.core as og
class OgnBundleConstructor:
"""Node to create a bundle out of dynamic attributes"""
@staticmethod
def compute(db) -> bool:
"""Compute the bundle from the dynamic input attributes"""
# Start with an empty output bundle.
output_bundle = db.outputs.bundle
output_bundle.clear()
# Walk the list of node attribute, looking for dynamic inputs
for attribute in db.abi_node.get_attributes():
if attribute.is_dynamic():
if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT:
continue
if attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR:
db.log_warn(f"Cannot add extended attribute types like '{attribute.get_name()}' to a bundle")
continue
if attribute.get_resolved_type().base_type in [og.BaseDataType.RELATIONSHIP]:
db.log_warn(f"Cannot add bundle attribute types like '{attribute.get_name()}' to a bundle")
continue
# The bundled name does not need the port namespace
new_name = attribute.get_name().replace("inputs:", "")
output_bundle.insert((attribute.get_resolved_type(), new_name))
return True
| 1,448 | Python | 37.131578 | 113 | 0.619475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPaths.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnGetPrimPathsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPaths
{
public:
static size_t computeVectorized(OgnGetPrimPathsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t p = 0; p < count; p++)
{
const auto& prims = db.inputs.prims(p);
auto& primPaths = db.outputs.primPaths(p);
primPaths.resize(prims.size());
for (size_t i = 0; i < prims.size(); i++)
{
primPaths[i] = tokenInterface->getHandle(pathInterface->getText(prims[i]));
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,448 | C++ | 27.411764 | 91 | 0.640884 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector4.cpp | // Copyright (c) 2022, 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.
//
#include <OgnBreakVector4Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryBreakVector(OgnBreakVector4Database& db)
{
const auto vector = db.inputs.tuple().template get<Type[4]>();
auto x = db.outputs.x().template get<Type>();
auto y = db.outputs.y().template get<Type>();
auto z = db.outputs.z().template get<Type>();
auto w = db.outputs.w().template get<Type>();
if (!vector || !x || !y || !z || !w){
return false;
}
*x = (*vector)[0];
*y = (*vector)[1];
*z = (*vector)[2];
*w = (*vector)[3];
return true;
}
} // namespace
// Node to break a 4-vector into it's component scalers
class OgnBreakVector4
{
public:
static bool compute(OgnBreakVector4Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryBreakVector<double>(db))
return true;
else if (tryBreakVector<float>(db))
return true;
else if (tryBreakVector<pxr::GfHalf>(db))
return true;
else if (tryBreakVector<int32_t>(db))
return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be broken: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token());
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::z.token());
auto w = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::w.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
// Require inputs to be resolved before determining outputs' type
if (vectorType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 5> attrs{ vector, x, y, z, w };
std::array<uint8_t, 5> tuples{ 4, 1, 1, 1, 1};
std::array<uint8_t, 5> arrays{ 0, 0, 0, 0, 0 };
std::array<AttributeRole, 5> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone};
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 3,295 | C++ | 31 | 153 | 0.623672 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPrims.cpp | // Copyright (c) 2020-2023, 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.
//
#include <OgnGetParentPrimsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPrims
{
public:
static size_t computeVectorized(OgnGetParentPrimsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
if (!pathInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prims(i);
auto& parentPaths = db.outputs.parentPrims(i);
parentPaths.resize(prims.size());
std::transform(prims.begin(), prims.end(), parentPaths.begin(),
[&](const auto& p) { return pathInterface->getParent(p); });
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,351 | C++ | 27.166666 | 87 | 0.647668 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnEndsWith.cpp | // Copyright (c) 2022, 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.
//
#include <OgnEndsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnEndsWith
{
public:
static bool compute(OgnEndsWithDatabase& db)
{
auto const& suffix = db.inputs.suffix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(suffix.rbegin(), suffix.rend(), value.rbegin(), value.rend());
db.outputs.isSuffix() = (iters.first == suffix.rend());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 971 | C++ | 24.578947 | 97 | 0.704428 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayResize.cpp | // Copyright (c) 2022-2023, 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.
//
#include <OgnArrayResizeDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayResizeDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
size_t newSize = db.inputs.newSize();
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!inputArray)
return false;
if (newSize < 0)
newSize = 0;
(*outputArray).resize(newSize);
memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * (std::min(inputArraySize, newSize)));
if (newSize > inputArraySize)
memset(outputArray->data() + inputArraySize, 0, sizeof(BaseType) * (newSize - inputArraySize));
return true;
}
} // namespace
class OgnArrayResize
{
public:
static bool compute(OgnArrayResizeDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { inputArray, outputArray };
// all should have the same tuple count
std::array<uint8_t, 3> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
1
};
std::array<AttributeRole, 2> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 5,930 | C++ | 38.278145 | 108 | 0.586678 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantNames.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantNames
{
public:
static bool compute(OgnGetVariantNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
auto variantNames = variantSet.GetVariantNames();
db.outputs.variantNames().resize(variantNames.size());
for (size_t i = 0; i < variantNames.size(); i++)
{
db.outputs.variantNames()[i] = db.stringToToken(variantNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,721 | C++ | 28.18644 | 89 | 0.639163 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnClearVariantSelection.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <OgnClearVariantSelectionDatabase.h>
namespace omni::graph::nodes
{
class OgnClearVariantSelection
{
public:
static bool compute(OgnClearVariantSelectionDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (db.inputs.setVariant())
{
bool success = variantSet.SetVariantSelection("");
if (!success)
throw warning(std::string("Failed to clear variant selection for variant set ") + variantSetName);
}
else
{
removeLocalOpinion(prim, variantSetName);
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,868 | C++ | 28.203125 | 118 | 0.630621 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnHasVariantSet.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <omni/usd/UsdContext.h>
#include <OgnHasVariantSetDatabase.h>
namespace omni::graph::nodes
{
class OgnHasVariantSet
{
public:
static bool compute(OgnHasVariantSetDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
db.outputs.exists() = variantSets.HasVariantSet(db.tokenToString(db.inputs.variantSetName()));
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.exists() = false;
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,373 | C++ | 24.444444 | 106 | 0.656956 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSetNames.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantSetNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantSetNames
{
public:
static bool compute(OgnGetVariantSetNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetNames = variantSets.GetNames();
db.outputs.variantSetNames().resize(variantSetNames.size());
for (size_t i = 0; i < variantSetNames.size(); i++)
{
db.outputs.variantSetNames()[i] = db.stringToToken(variantSetNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantSetNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,578 | C++ | 26.701754 | 95 | 0.636882 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnSetVariantSelection.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <OgnSetVariantSelectionDatabase.h>
namespace omni::graph::nodes
{
class OgnSetVariantSelection
{
public:
static bool compute(OgnSetVariantSelectionDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
auto variantName = db.tokenToString(db.inputs.variantName());
if (db.inputs.setVariant())
{
removeLocalOpinion(prim, variantSetName, variantName);
bool success = variantSet.SetVariantSelection(variantName);
if (!success)
throw warning(std::string("Failed to set variant selection for variant set ") + variantSetName +
" to variant " + variantName);
}
else
{
setLocalOpinion(prim, variantSetName, variantName);
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 2,089 | C++ | 30.194029 | 116 | 0.624701 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSelection.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantSelectionDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantSelection
{
public:
static bool compute(OgnGetVariantSelectionDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
auto variantSelection = variantSet.GetVariantSelection();
db.outputs.variantName() = db.stringToToken(variantSelection.c_str());
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantName() = db.stringToToken("");
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,590 | C++ | 27.927272 | 86 | 0.66478 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnBlendVariants.cpp | // Copyright (c) 2022, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <omni/fabric/Enums.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/usd/UsdContext.h>
#include <pxr/usd/sdf/variantSetSpec.h>
#include <pxr/usd/sdf/variantSpec.h>
#include <OgnBlendVariantsDatabase.h>
using omni::graph::core::ogn::eAttributeType::kOgnOutput;
using omni::graph::core::ogn::eMemoryType::kCpu;
using omni::math::linalg::vec3f;
using DB = OgnBlendVariantsDatabase;
namespace omni::graph::nodes
{
namespace
{
using LerpFunction = void (*)(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute);
template <typename T>
void floatLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
T c = pxr::GfLerp(alpha, a, b);
if (attribute.IsValid())
attribute.Set<T>(c);
}
template <typename T>
void discreteLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
if (attribute.IsValid())
{
if (alpha < 0.5)
attribute.Set<T>(a);
else
attribute.Set<T>(b);
}
}
void lerpAttribute(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
const pxr::UsdAttribute& attribute)
{
if (propertyA->GetSpecType() != propertyB->GetSpecType())
throw warning("Property spec types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetTypeName() != attribute.GetTypeName())
throw warning("Attribute types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetValueType() != propertyB->GetValueType())
throw warning("Property value types do not match");
auto typeName = propertyA->GetValueType().GetTypeName();
auto handleType = [alpha, &propertyA, &propertyB, &attribute, &typeName](const char* type, LerpFunction lerpFunction) -> bool
{
if (typeName == type)
{
lerpFunction(alpha, propertyA, propertyB, attribute);
return true;
}
return false;
};
if (!handleType("bool", discreteLerp<bool>)
&& !handleType("double", floatLerp<double>)
&& !handleType("float", floatLerp<float>)
&& !handleType("pxr_half::half", floatLerp<pxr::GfHalf>)
&& !handleType("int", discreteLerp<int>)
&& !handleType("__int64", discreteLerp<int64_t>) // Windows
&& !handleType("long", discreteLerp<int64_t>) // Linux
&& !handleType("unsigned char", discreteLerp<uint8_t>)
&& !handleType("unsigned int", discreteLerp<uint32_t>)
&& !handleType("unsigned __int64", discreteLerp<uint64_t>) // Windows
&& !handleType("unsigned long", discreteLerp<uint64_t>) // Linux
&& !handleType("TfToken", discreteLerp<pxr::TfToken>)
&& !handleType("SdfTimeCode", floatLerp<pxr::SdfTimeCode>)
&& !handleType("GfVec2d", floatLerp<pxr::GfVec2d>)
&& !handleType("GfVec2f", floatLerp<pxr::GfVec2f>)
&& !handleType("GfVec2h", floatLerp<pxr::GfVec2h>)
&& !handleType("GfVec2i", discreteLerp<pxr::GfVec2i>)
&& !handleType("GfVec3d", floatLerp<pxr::GfVec3d>)
&& !handleType("GfVec3f", floatLerp<pxr::GfVec3f>)
&& !handleType("GfVec3h", floatLerp<pxr::GfVec3h>)
&& !handleType("GfVec3i", discreteLerp<pxr::GfVec3i>)
&& !handleType("GfVec4d", floatLerp<pxr::GfVec4d>)
&& !handleType("GfVec4f", floatLerp<pxr::GfVec4f>)
&& !handleType("GfVec4h", floatLerp<pxr::GfVec4h>)
&& !handleType("GfVec4i", discreteLerp<pxr::GfVec4i>)
&& !handleType("GfQuatd", floatLerp<pxr::GfQuatd>)
&& !handleType("GfQuatf", floatLerp<pxr::GfQuatf>)
&& !handleType("GfQuath", floatLerp<pxr::GfQuath>)
&& !handleType("GfMatrix2d", floatLerp<pxr::GfMatrix2d>)
&& !handleType("GfMatrix3d", floatLerp<pxr::GfMatrix3d>)
&& !handleType("GfMatrix4d", floatLerp<pxr::GfMatrix4d>))
throw warning("Unsupported property type " + typeName);
}
}
class OgnBlendVariants
{
public:
static bool compute(OgnBlendVariantsDatabase& db)
{
auto ok = [&db]()
{
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
};
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
std::string variantSetName = db.tokenToString(db.inputs.variantSetName());
std::string variantNameA = db.tokenToString(db.inputs.variantNameA());
std::string variantNameB = db.tokenToString(db.inputs.variantNameB());
double blend = std::max(std::min(db.inputs.blend(), 1.0), 0.0);
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (!variantSet.IsValid())
throw warning("Invalid variant set " + variantSetName);
bool finishing = (1.0 - blend) < 1e-6;
if (finishing && db.inputs.setVariant())
variantSet.SetVariantSelection(variantNameB);
VariantData a = getVariantData(prim, variantSetName, variantNameA);
VariantData b = getVariantData(prim, variantSetName, variantNameB);
for (const auto& [path, propertyA] : a)
{
if (b.find(path) == b.end())
continue;
auto propertyB = b[path];
auto attribute = prim.GetStage()->GetAttributeAtPath(path);
if (!attribute.IsValid())
throw warning("Invalid attribute " + path.GetString());
if (finishing && db.inputs.setVariant())
attribute.Clear();
else
lerpAttribute(blend, propertyA, propertyB, attribute);
}
return ok();
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 7,396 | C++ | 35.800995 | 129 | 0.611682 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveFrame.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnCurveFrameDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <math.h>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace nodes
{
static vec3f perpendicular(vec3f v)
{
vec3f av(abs(v[0]), abs(v[1]), abs(v[2]));
// Find the smallest coordinate of v.
int axis = (av[0] < av[1] && av[0] < av[2]) ? 0 : ((av[1] < av[2]) ? 1 : 2);
// Start with that coordinate.
vec3f p(0.0f);
p[axis] = 1.0f;
// Subtract the portion parallel to v.
p -= (GfDot(p, v) / GfDot(v, v)) * v;
// Normalize
return p.GetNormalized();
}
static vec3f rotateLike(vec3f v, vec3f a, vec3f aPlusb)
{
// To apply to another vector v, the rotation that brings tangent a to tangent b:
// - reflect v through the line in direction of unit vector a
// - reflect that through the line in direction of a+b
vec3f temp = (2 * GfDot(a, v)) * a - v;
return (2 * GfDot(aPlusb, temp) / GfDot(aPlusb, aPlusb)) * aPlusb - temp;
}
class OgnCurveFrame
{
public:
static bool compute(OgnCurveFrameDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
auto& tangentArray = db.outputs.tangent();
auto& upArray = db.outputs.up();
auto &outArray = db.outputs.out();
size_t curveCount = vertexStartIndices.size();
if (vertexCounts.size() < curveCount)
curveCount = vertexCounts.size();
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
tangentArray.resize(0);
upArray.resize(0);
outArray.resize(0);
return true;
}
tangentArray.resize(pointCount);
upArray.resize(pointCount);
outArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
tangentArray[vertex] = vec3f( 0.0f, 0.0f, 1.0f );
upArray[vertex] = vec3f( 0.0f, 1.0f, 0.0f );
outArray[vertex] = vec3f( 1.0f, 0.0f, 0.0f );
continue;
}
// First, compute all tangents.
// The first tangent is the first edge direction.
// TODO: Skip zero-length edges to get the first real edge direction.
vec3f prev = curvePoints[vertex];
vec3f current = curvePoints[vertex + 1];
vec3f prevDir = (current - prev).GetNormalized();
tangentArray[vertex] = prevDir;
for (size_t i = 1; i < vertexCount - 1; ++i)
{
vec3f next = curvePoints[vertex + i + 1];
vec3f nextDir = (next - current).GetNormalized();
// Middle tangents are averages of previous and next directions.
vec3f dir = (prevDir + nextDir).GetNormalized();
tangentArray[vertex + i] = dir;
prev = current;
current = next;
prevDir = nextDir;
}
// The last tangent is the last edge direction.
tangentArray[vertex + vertexCount - 1] = prevDir;
// Choose the first up vector as anything that's perpendicular to the first tangent.
// TODO: Use a curve "normal" for more consistency.
vec3f prevTangent = tangentArray[vertex];
vec3f prevUpVector = perpendicular(prevTangent);
// x = cross(y, z)
vec3f prevOutVector = GfCross(prevUpVector, prevTangent);
upArray[vertex] = prevUpVector;
outArray[vertex] = prevOutVector;
for (size_t i = 1; i < vertexCount; ++i)
{
vec3f nextTangent = tangentArray[vertex + i];
vec3f midTangent = prevTangent + nextTangent;
vec3f nextUpVector = rotateLike(prevUpVector, prevTangent, midTangent);
vec3f nextOutVector = rotateLike(prevOutVector, prevTangent, midTangent);
upArray[vertex + i] = nextUpVector;
outArray[vertex + i] = nextOutVector;
prevTangent = nextTangent;
prevUpVector = nextUpVector;
prevOutVector = nextOutVector;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,465 | C++ | 32.533742 | 96 | 0.579323 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnLengthAlongCurve.cpp | // Copyright (c) 2020, 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.
//
#include <OgnLengthAlongCurveDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnLengthAlongCurve
{
public:
static bool compute(OgnLengthAlongCurveDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
const auto& normalize = db.inputs.normalize();
auto& lengthArray = db.outputs.length();
size_t curveCount = std::min(vertexStartIndices.size(), vertexCounts.size());
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
lengthArray.resize(0);
return true;
}
lengthArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
lengthArray[vertex] = 0.0f;
continue;
}
// First, compute all lengths along the curve.
auto prev = curvePoints[vertex];
lengthArray[vertex] = 0.0f;
// Sum in double precision to avoid catastrophic roundoff error.
double lengthSum = 0.0;
for (size_t i = 1; i < vertexCount; ++i)
{
auto& current = curvePoints[vertex + i];
auto edge = (current - prev);
lengthSum += edge.GetLength();
lengthArray[vertex + i] = float(lengthSum);
prev = current;
}
// Don't normalize if lengthSum is zero.
if (normalize && float(lengthSum) != 0)
{
for (size_t i = 0; i < vertexCount; ++i)
{
lengthArray[vertex + i] /= float(lengthSum);
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,908 | C++ | 28.98969 | 96 | 0.563274 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCreateTubeTopology.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnCreateTubeTopologyDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnCreateTubeTopology
{
public:
static bool compute(OgnCreateTubeTopologyDatabase& db)
{
const auto& inputRows = db.inputs.rows();
const auto& inputColumns = db.inputs.cols();
auto& faceVertexCounts = db.outputs.faceVertexCounts();
auto& faceVertexIndices = db.outputs.faceVertexIndices();
const size_t rowValueCount = inputRows.size();
const size_t colValueCount = inputColumns.size();
size_t inputTubeCount;
if (colValueCount == 1 || colValueCount == rowValueCount)
{
inputTubeCount = rowValueCount;
}
else if (rowValueCount == 1)
{
inputTubeCount = colValueCount;
}
else
{
faceVertexCounts.resize(0);
faceVertexIndices.resize(0);
return true;
}
size_t validTubeCount = 0;
size_t quadCount = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
const size_t currentQuadCount = size_t(rows) * cols;
quadCount += currentQuadCount;
++validTubeCount;
}
// Generate a faceVertexCounts array with all 4, for all quads.
faceVertexCounts.resize(quadCount);
for (auto& faceVertex : faceVertexCounts)
{
faceVertex = 4;
}
faceVertexIndices.resize(4 * quadCount);
size_t faceVertexIndex{ 0 };
int pointIndex = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
for (auto row = 0; row < rows; ++row)
{
// Main quads of the row
for (auto col = 0; col < cols - 1; ++col)
{
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
// Wrap around
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex - cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
pointIndex += cols;
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,600 | C++ | 30.867256 | 81 | 0.565 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubeST.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnCurveTubeSTDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <omni/graph/core/ArrayWrapper.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using omni::math::linalg::vec2f;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewSs(std::vector<float>& sValues, size_t edgeCount)
{
if (sValues.size() == edgeCount + 1)
return;
sValues.resize(edgeCount + 1);
sValues[0] = 0.0f;
if (edgeCount == 0)
return;
for (size_t i = 1; i < edgeCount; ++i)
{
sValues[i] = float(double(i) / double(edgeCount));
}
sValues[edgeCount] = 1.0f;
}
class OgnCurveTubeST
{
public:
static bool compute(OgnCurveTubeSTDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& tubeSTStartArray = db.inputs.tubeSTStarts();
const auto& tubeQuadStartArray = db.inputs.tubeQuadStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& tArray = db.inputs.t();
auto scaleTLikeS = db.inputs.scaleTLikeS(); // Might change, so get a copy
auto& stArray = db.outputs.primvars_st();
auto& stIndicesArray = db.outputs.primvars_st_indices();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeSTStartArray.size();
if (tubeQuadStartArray.size() < tubeCount)
{
tubeCount = tubeQuadStartArray.size();
}
const size_t colValueCount = columnsArray.size();
const int32_t tubeSTsCount = (tubeCount == 0) ? 0 : tubeSTStartArray[tubeCount - 1];
const int32_t tubeQuadsCount = (tubeCount == 0) ? 0 : tubeQuadStartArray[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t tCount = tArray.size();
size_t widthCount = 0;
if (scaleTLikeS)
{
widthCount = widthArray.size();
if (widthCount == 0 || (widthCount != 1 && widthCount != tCount && widthCount != tubeCount))
{
scaleTLikeS = false;
}
}
if (tubeSTsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
if (tCount == 0)
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
std::vector<float> sValues;
size_t circleN = 0;
float perimeterScale = 0.0f;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
stArray.resize(tubeSTsCount);
stIndicesArray.resize(4 * tubeQuadsCount);
float width = (scaleTLikeS ? widthArray[0] : 0.0f);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeSTStartArray[tube] < 0 || curveStartIndices[tube] < 0 || tubeQuadStartArray[tube] < 0 ||
tubeVertexCounts[tube] < 0)
continue;
size_t tubeSTStartIndex = tubeSTStartArray[tube];
size_t tubeSTEndIndex = tubeSTStartArray[tube + 1];
size_t tubeQuadStartIndex = 4 * tubeQuadStartArray[tube];
size_t tubeQuadEndIndex = 4 * tubeQuadStartArray[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
if ((int32_t)tubeSTEndIndex > tubeSTsCount || tubeSTEndIndex < tubeSTStartIndex)
break;
if (tubeSTEndIndex == tubeSTStartIndex)
continue;
size_t curveTCount = curveEndIndex - curveStartIndex;
size_t tubeSTCount = tubeSTEndIndex - tubeSTStartIndex;
if (curveTCount * (circleN + 1) != tubeSTCount)
{
continue;
}
if (scaleTLikeS)
{
if (widthCount == tubeCount)
{
width = widthArray[tube];
}
else if (widthCount == tCount)
{
// Use the max width along the curve for the whole curve's
// t scaling, just for stability for now.
// Some situations need varying scale, but that's more complicated,
// and not what's needed for the current use cases.
width = widthArray[curveStartIndex];
for (size_t i = curveStartIndex + 1; i < curveEndIndex; ++i)
{
if (widthArray[i] > width)
{
width = widthArray[i];
}
}
}
}
// First, compute the st values.
size_t circleIndex = 0;
float tScale = 1.0f;
if (scaleTLikeS)
{
// Scale t by 1/(2nr*sin(2pi/2n)), where 2r*sin(2pi/2n) is the side length,
// and the full denominator is the perimeter of the tube's circle.
// This is, in a sense, scaling t by the same factor that s was "scaled"
// by, to make it go from 0 to 1, instead of 0 to the perimeter.
// This way, t will change proportionally to s moving along the surface in 3D space.
tScale = 1.0f / (width * perimeterScale);
}
float tValue = tScale * tArray[curveStartIndex];
for (size_t sti = tubeSTStartIndex; sti < tubeSTEndIndex; ++sti)
{
vec2f st( sValues[circleIndex], tValue );
stArray[sti] = st;
++circleIndex;
if (circleIndex >= circleN + 1)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
tValue = tScale * tArray[curveStartIndex];
}
}
}
// Second, compute indices into the st values.
circleIndex = 0;
for (size_t indexi = tubeQuadStartIndex, sti = tubeSTStartIndex; indexi < tubeQuadEndIndex; indexi += 4, ++sti)
{
stIndicesArray[indexi] = int32_t(sti);
stIndicesArray[indexi + 1] = int32_t(sti + 1);
stIndicesArray[indexi + 2] = int32_t(sti + circleN + 1 + 1);
stIndicesArray[indexi + 3] = int32_t(sti + circleN + 1);
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++sti;
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,158 | C++ | 32.995833 | 123 | 0.537509 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubePositions.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnCurveTubePositionsDatabase.h>
#include <carb/Framework.h>
#include <carb/Types.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using carb::Float2;
using carb::Float3;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewCircle(std::vector<Float2>& circle, size_t edgeCount)
{
if (circle.size() == edgeCount)
return;
circle.resize(edgeCount);
circle[0] = Float2{ 1.0f, 0.0f };
for (size_t i = 1; i < edgeCount; ++i)
{
double theta = ((2 * M_PI) / double(edgeCount)) * double(i);
float c = float(cos(theta));
float s = float(sin(theta));
circle[i] = Float2{ c, s };
}
}
class OgnCurveTubePositions
{
public:
static bool compute(OgnCurveTubePositionsDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& curvePointsArray = db.inputs.curvePoints();
const auto& tubeStartIndices = db.inputs.tubePointStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& upArray = db.inputs.up();
const auto& outArray = db.inputs.out();
auto& pointsArray = db.outputs.points();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeStartIndices.size();
const size_t colValueCount = columnsArray.size();
const int32_t tubePointsCount = (tubeCount == 0) ? 0 : tubeStartIndices[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t curvePointCount = curvePointsArray.size();
const size_t upCount = upArray.size();
const size_t outCount = outArray.size();
const size_t widthCount = widthArray.size();
size_t curvePointsCount = curvePointCount;
if (upCount != 1 && upCount < curvePointsCount)
curvePointsCount = upCount;
if (outCount != 1 && outCount < curvePointsCount)
curvePointsCount = outCount;
if (widthCount != 1 && widthCount < curvePointsCount)
curvePointsCount = widthCount;
if (tubePointsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
pointsArray.resize(0);
return true;
}
if (curvePointsCount == 0)
{
pointsArray.resize(0);
return true;
}
std::vector<Float2> circle;
size_t circleN = 0;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewCircle(circle, circleN);
}
pointsArray.resize(tubePointsCount);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeStartIndices[tube] < 0 || curveStartIndices[tube] < 0 || tubeVertexCounts[tube] < 0)
continue;
size_t tubeStartIndex = tubeStartIndices[tube];
size_t tubeEndIndex = tubeStartIndices[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewCircle(circle, circleN);
}
if ((int32_t)tubeEndIndex > tubePointsCount || tubeEndIndex < tubeStartIndex)
break;
if (tubeEndIndex == tubeStartIndex)
continue;
size_t curvePointCount = curveEndIndex - curveStartIndex;
size_t tubePointCount = tubeEndIndex - tubeStartIndex;
if (curvePointCount * circleN != tubePointCount)
{
continue;
}
size_t circleIndex = 0;
// Do bounds check on up and out arrays.
auto center = curvePointsArray[curveStartIndex];
auto up = upArray[(upCount == 1) ? 0 : curveStartIndex];
auto out = outArray[(outCount == 1) ? 0 : curveStartIndex];
float width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
for (size_t point = tubeStartIndex; point < tubeEndIndex; ++point)
{
float x = width * circle[circleIndex].x;
float y = width * circle[circleIndex].y;
auto newPoint = (center + (x * out + y * up));
pointsArray[point] = newPoint;
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
center = curvePointsArray[curveStartIndex];
up = upArray[(upCount == 1) ? 0 : curveStartIndex];
out = outArray[(outCount == 1) ? 0 : curveStartIndex];
width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
}
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,884 | C++ | 33.415204 | 107 | 0.57155 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleAllocator.cpp | // Copyright (c) 2021-2022, 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.
//
#include "OgnRpResourceExampleAllocatorDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleAllocator
{
// NOTE: this node is meant only as an early example of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
bool previousReload;
std::vector<rtx::resourcemanager::RpResource*> resourcePointerCollection;
std::vector<uint64_t> pointCountCollection;
std::vector<NameToken> primPathCollection;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::release" << std::endl;
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
rtx::resourcemanager::ResourceManager* resourceManager = gpuFoundation->getResourceManager();
rtx::resourcemanager::Context* resourceManagerContext = gpuFoundation->getResourceManagerContext();
auto& internalState = OgnRpResourceExampleAllocatorDatabase::sInternalState<OgnRpResourceExampleAllocator>(nodeObj);
auto& resourcePointerCollection = internalState.resourcePointerCollection;
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
}
}
}
static bool compute(OgnRpResourceExampleAllocatorDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleAllocator::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnRpResourceExampleAllocator>();
const bool previousSuccess = internalState.previousSuccess;
const bool previousReload = internalState.previousReload;
internalState.previousSuccess = false;
internalState.previousReload= false;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleAllocator::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = internalState.resourcePointerCollection;
auto& pointCountCollection = internalState.pointCountCollection;
auto& primPathCollection = internalState.primPathCollection;
const bool reloadAttr = db.inputs.reload();
if ((reloadAttr && !previousReload) || !previousSuccess)
{
internalState.previousReload = true;
if (resourcePointerCollection.size() != 0)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
resourcePointerCollection.resize(0);
pointCountCollection.resize(0);
primPathCollection.resize(0);
}
}
if (resourcePointerCollection.size() == 0)
{
const auto& pointsAttr = db.inputs.points();
const size_t pointsCount = pointsAttr.size();
const vec3f* points = pointsAttr.data();
const NameToken primPath = db.inputs.primPath();
if (pointsCount == 0)
return false;
if (points == nullptr)
return false;
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
const uint32_t deviceIndex = 0;
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
for (size_t i = 0; i < 2; i++)
{
rtx::resourcemanager::RpResource* rpResource = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
float* cpuPtr = new float[pointsCount * dimension];
for (size_t j = 0; j < pointsCount; j++)
{
cpuPtr[dimension * j] = points[j][0];
cpuPtr[dimension * j + 1] = points[j][1];
cpuPtr[dimension * j + 2] = points[j][2];
if (dimension == 4)
cpuPtr[dimension * j + 3] = 1.f;
}
void* cudaPtr = resourceManager->getCudaDevicePointer(*rpResource, deviceIndex);
cudaError_t err = cudaMemcpy(cudaPtr, cpuPtr, pointsCount * dimension * sizeof(float), cudaMemcpyHostToDevice);
delete [] cpuPtr;
if (verbose)
{
std::cout << "prim: " << db.tokenToString(primPath) << std::endl;
std::cout << "cudaMemcpy to device error code: " << err << std::endl;
std::cout << "errorName: " << cudaGetErrorName(err) << std::endl;
std::cout << "errorDesc: " << cudaGetErrorString(err) << std::endl;
std::cout << std::endl;
}
resourcePointerCollection.push_back(rpResource);
}
pointCountCollection.push_back((uint64_t)pointsCount);
primPathCollection.push_back(primPath);
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
}
if (resourcePointerCollection.size() == 0)
{
return false;
}
db.outputs.stream() = (uint64_t)stream;
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 10,107 | C++ | 38.027027 | 157 | 0.624617 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleHydra.cpp | // Copyright (c) 2021, 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <omni/hydra/IOmniHydra.h>
#include <omni/usd/UsdContextIncludes.h>
#include <omni/usd/UsdContext.h>
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include "OgnRpResourceExampleHydraDatabase.h"
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleHydra
{
public:
static bool compute(OgnRpResourceExampleHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra::compute");
const bool sendToHydra = db.inputs.sendToHydra();
const bool verbose = db.inputs.verbose();
//const size_t dimension = 4;
const size_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
if (verbose)
{
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
return false;
}
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
omni::usd::hydra::IOmniHydra* omniHydra = sendToHydra ?
carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>() :
nullptr;
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResource = rpResources[2 * primIndex + 1]; //only want deformed positions
const uint64_t& pointsCount = pointCounts[primIndex];
const NameToken& primPath = primPaths[primIndex];
if (verbose)
{
carb::graphics::AccessFlags accessFlags = resourceManager->getResourceAccessFlags(*rpResource, deviceIndex);
std::cout << "Sending to Hydra..." << std::endl;
std::cout << "prim path: " << db.tokenToString(primPath) << std::endl;
std::cout << "\trpResource: " << rpResource << std::endl;
std::cout << "\taccessFlags: " << accessFlags << std::endl;
if (accessFlags & carb::graphics::kAccessFlagUnknown)
std::cout << "\t\tkAccessFlagUnknown" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagVertexBuffer)
std::cout << "\t\tkAccessFlagVertexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagIndexBuffer)
std::cout << "\t\tkAccessFlagIndexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagConstantBuffer)
std::cout << "\t\tkAccessFlagConstantBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagArgumentBuffer)
std::cout << "\t\tkAccessFlagArgumentBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagTextureRead)
std::cout << "\t\tkAccessFlagTextureRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageRead)
std::cout << "\t\tkAccessFlagStorageRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageWrite)
std::cout << "\t\tkAccessFlagStorageWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagColorAttachmentWrite)
std::cout << "\t\tkAccessFlagColorAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentWrite)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentRead)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopySource)
std::cout << "\t\tkAccessFlagCopySource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopyDestination)
std::cout << "\t\tkAccessFlagCopyDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructRead)
std::cout << "\t\tkAccessFlagAccelStructRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructWrite)
std::cout << "\t\tkAccessFlagAccelStructWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveSource)
std::cout << "\t\tkAccessFlagResolveSource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveDestination)
std::cout << "\t\tkAccessFlagResolveDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageClear)
std::cout << "\t\tkAccessFlagStorageClear" << std::endl;
const carb::graphics::BufferDesc* bufferDesc = resourceManager->getBufferDesc(rpResource);
std::cout << "\tbufferDesc: " << bufferDesc << std::endl;
if (bufferDesc != nullptr)
{
std::cout << "\tbuffer usage flags: " << bufferDesc->usageFlags << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagNone)
std::cout << "\t\tkBufferUsageFlagNone" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResource)
std::cout << "\t\tkBufferUsageFlagShaderResource" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResourceStorage)
std::cout << "\t\tkBufferUsageFlagShaderResourceStorage" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVertexBuffer)
std::cout << "\t\tkBufferUsageFlagVertexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagIndexBuffer)
std::cout << "\t\tkBufferUsageFlagIndexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConstantBuffer)
std::cout << "\t\tkBufferUsageFlagConstantBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRawOrStructuredBuffer)
std::cout << "\t\tkBufferUsageFlagRawOrStructuredBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagArgumentBuffer)
std::cout << "\t\tkBufferUsageFlagArgumentBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingAccelStruct)
std::cout << "\t\tkBufferUsageFlagRaytracingAccelStruct" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingScratchBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingScratchBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagExportShared)
std::cout << "\t\tkBufferUsageFlagExportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagImportShared)
std::cout << "\t\tkBufferUsageFlagImportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagSharedCrossAdapter)
std::cout << "\t\tkBufferUsageFlagSharedCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagHostMappedForeignMemory)
std::cout << "\t\tkBufferUsageFlagHostMappedForeignMemory" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConcurrentAccess)
std::cout << "\t\tkBufferUsageFlagConcurrentAccess" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVisibleCrossAdapter)
std::cout << "\t\tkBufferUsageFlagVisibleCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingShaderBindingTable)
std::cout << "\t\tkBufferUsageFlagRaytracingShaderBindingTable" << std::endl;
std::cout << "\tbuffer size: " << bufferDesc->size << std::endl;
std::cout << "\tbuffer debug name: " << bufferDesc->debugName << std::endl;
std::cout << "\tbuffer ext: " << bufferDesc->ext << std::endl;
}
}
if (sendToHydra)
{
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)rpResource;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(primPath)), desc);
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 11,707 | C++ | 50.80531 | 126 | 0.606987 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleDeformer.cpp | // Copyright (c) 2021, 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.
//
#include "OgnRpResourceExampleDeformerDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include <stdlib.h>
#include <iostream>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
extern "C" void modifyPositions(float3* points, size_t numPoints, unsigned sequenceCounter, int displacementAxis, bool verbose, cudaStream_t stream);
extern "C" void modifyPositionsSinusoidal(const float3* pointsRest, float3* pointsDeformed, size_t numPoints, unsigned sequenceCounter, float positionScale, float timeScale, float deformScale, bool verbose, cudaStream_t stream);
class OgnRpResourceExampleDeformer
{
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::release" << std::endl;
}
static bool compute(OgnRpResourceExampleDeformerDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleDeformer::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
bool& reloadAttr = db.outputs.reload();
auto& sequenceCounter = db.state.sequenceCounter();
if (reloadAttr)
{
reloadAttr = false;
sequenceCounter = 0;
}
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResourceRest = rpResources[2 * primIndex];
rtx::resourcemanager::RpResource* rpResourceDeformed = rpResources[2 * primIndex + 1];
const uint64_t& pointsCount = pointCounts[primIndex];
//const NameToken& path = primPaths[primIndex];
// run some simple kernel
if (verbose)
{
std::cout
<< "OgnRpResourceExampleDeformer: Modifying " << pointsCount
<< " positions at sequence point " << sequenceCounter
<< std::endl;
}
if (db.inputs.runDeformerKernel())
{
void* cudaPtrRest = resourceManager->getCudaDevicePointer(*rpResourceRest, deviceIndex);
void* cudaPtrDeformed = resourceManager->getCudaDevicePointer(*rpResourceDeformed, deviceIndex);
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::modifyPositions kernel");
modifyPositionsSinusoidal((float3*)cudaPtrRest, (float3*)cudaPtrDeformed, pointsCount, (unsigned)sequenceCounter, db.inputs.positionScale(), db.inputs.timeScale(), db.inputs.deformScale(), verbose, stream);
}
}
}
if (db.inputs.runDeformerKernel())
{
sequenceCounter++;
}
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
db.outputs.stream() = (uint64_t)stream;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,875 | C++ | 35.189473 | 228 | 0.651055 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnDeformedPointsToHydra.cpp | // Copyright (c) 2021-2022, 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.
//
#include "OgnDeformedPointsToHydraDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/hydra/IOmniHydra.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnDeformedPointsToHydra
{
// NOTE: this node is meant only for early usage of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
rtx::resourcemanager::RpResource* resourcePointer;
uint64_t pointCount;
NameToken primPath;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
OgnDeformedPointsToHydraDatabase db(context, nodeObj);
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
internalState.resourcePointer = nullptr;
internalState.pointCount = 0;
internalState.primPath = db.stringToToken("");
internalState.previousSuccess = false;
}
static void release(const NodeObj& nodeObj)
{
}
static bool compute(OgnDeformedPointsToHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnDeformedPointsToHydra::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
const bool previousSuccess = internalState.previousSuccess;
internalState.previousSuccess = false;
const bool verbose = db.inputs.verbose();
if (db.inputs.primPath() == db.stringToToken("") || db.inputs.points.size() == 0)
{
return false;
}
bool reload = false;
if (internalState.resourcePointer == nullptr ||
internalState.primPath != db.inputs.primPath() ||
internalState.pointCount != db.inputs.points.size() ||
!internalState.previousSuccess)
{
reload = true;
}
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnDeformedPointsToHydra::compute -- cudaStream: "<<stream<<std::endl;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
const uint32_t deviceIndex = 0;
const size_t pointsCount = db.inputs.points.size();
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
if (reload)
{
if (internalState.resourcePointer != nullptr)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
resourceManager->releaseResource(*internalState.resourcePointer);
internalState.resourcePointer = nullptr;
}
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
internalState.resourcePointer = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
internalState.pointCount = pointsCount;
internalState.primPath = db.inputs.primPath();
}
const float3* cudaSrc = (const float3*)(*db.inputs.points.gpu());
void* cudaDst = resourceManager->getCudaDevicePointer(*internalState.resourcePointer, deviceIndex);
cudaMemcpy(cudaDst, (const void*)cudaSrc, size, cudaMemcpyDeviceToDevice);
if (db.inputs.sendToHydra())
{
omni::usd::hydra::IOmniHydra* omniHydra = carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>();
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)internalState.resourcePointer;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(internalState.primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceToHydra_Arrays, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(internalState.primPath)), desc);
}
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,928 | C++ | 34.172589 | 138 | 0.667292 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStart.cpp | // Copyright (c) 2023, 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStartDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStart
{
public:
static bool compute(OgnTimelineStartDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
timeline->play();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 915 | C++ | 21.341463 | 77 | 0.714754 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineGet.cpp | // Copyright (c) 2023, 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineGetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineGet
{
public:
static bool compute(OgnTimelineGetDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
db.outputs.isLooping() = timeline->isLooping();
db.outputs.isPlaying() = timeline->isPlaying();
double const currentTime = timeline->getCurrentTime();
double const startTime = timeline->getStartTime();
double const endTime = timeline->getEndTime();
db.outputs.time() = currentTime;
db.outputs.startTime() = startTime;
db.outputs.endTime() = endTime;
db.outputs.frame() = timeline->timeToTimeCode(currentTime);
db.outputs.startFrame() = timeline->timeToTimeCode(startTime);
db.outputs.endFrame() = timeline->timeToTimeCode(endTime);
db.outputs.framesPerSecond() = timeline->getTimeCodesPerSecond();
// TODO: Should we return false when the outputs didn't change?
return true;
};
return timelineNodeEvaluate(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,706 | C++ | 28.431034 | 77 | 0.672333 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimer.cpp | // Copyright (c) 2022, 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.
//
#include "PrimCommon.h"
#include <OgnTimerDatabase.h>
using namespace pxr;
using DB = OgnTimerDatabase;
namespace omni::graph::nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
enum TimeState : uint32_t
{
kTimeStateInit,
kTimeStateStart,
kTimeStatePlay,
kTimeStateLast,
kTimeStateFinish
};
class OgnTimer
{
double m_startTime{ kUninitializedStartTime }; // The value of the context time when we started latent state
TimeState m_timeState{ kTimeStateInit };
public:
static bool compute(DB& db)
{
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnTimer>();
auto& timeState = state.m_timeState;
auto& startTime = state.m_startTime;
const double duration = std::max(db.inputs.duration(), 1.0e-6);
const double startValue = db.inputs.startValue();
const double endValue = db.inputs.endValue();
switch (timeState)
{
case kTimeStateInit:
{
timeState = kTimeStateStart;
db.outputs.finished() = kExecutionAttributeStateLatentPush;
break;
}
case kTimeStateStart:
{
startTime = now;
timeState = kTimeStatePlay;
// Do not break here, we want to fall through to the next case
}
case kTimeStatePlay:
{
double deltaTime = now - startTime;
double value = startValue + (endValue - startValue) * deltaTime / duration;
value = std::min(value, 1.0);
db.outputs.value() = value;
if (deltaTime >= duration)
{
timeState = kTimeStateLast;
}
else
{
db.outputs.updated() = kExecutionAttributeStateEnabled;
}
break;
}
case kTimeStateLast:
{
timeState = kTimeStateFinish;
db.outputs.value() = endValue;
db.outputs.updated() = kExecutionAttributeStateEnabled;
break;
}
case kTimeStateFinish:
{
startTime = kUninitializedStartTime;
timeState = kTimeStateInit;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
break;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
| 2,923 | C++ | 26.847619 | 112 | 0.6117 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnInterpolator.cpp | // Copyright (c) 2020-2021, 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.
//
#include <OgnInterpolatorDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
inline float computeInterpolation(size_t numSamples, const float* knots, const float* values, const float& param)
{
// do really simple search for now
for (size_t i = 0; i < numSamples - 1; i++)
{
float knot = knots[i];
float knotNext = knots[i + 1];
float value = values[i];
float valueNext = values[i + 1];
if (param < knot)
return value;
if (param <= knotNext)
{
float interpolant = (param - knot) / (knotNext - knot);
float interpolatedValue = interpolant * valueNext + (1.0f - interpolant) * value;
return interpolatedValue;
}
}
return values[numSamples - 1];
}
class OgnInterpolator
{
public:
static bool compute(OgnInterpolatorDatabase& db)
{
const auto& inputKnots = db.inputs.knots();
const auto& inputValues = db.inputs.values();
size_t numSamples = inputValues.size();
if (inputKnots.size() != numSamples)
{
db.logWarning("Knots size %zu does not match value size %zu, skipping evaluation", inputKnots.size(), numSamples);
return false;
}
if (numSamples > 0)
{
db.outputs.value() = computeInterpolation(numSamples, inputKnots.data(), inputValues.data(), db.inputs.param());
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,933 | C++ | 25.861111 | 126 | 0.636834 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStop.cpp | // Copyright (c) 2023, 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStopDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStop
{
public:
static bool compute(OgnTimelineStopDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
// Pause stops at the current frame, stop resets time
timeline->pause();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 979 | C++ | 22.333333 | 77 | 0.707865 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.