file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
arhix52/Strelka/cuda/random.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once template<unsigned int N> static __host__ __device__ __inline__ unsigned int tea( unsigned int val0, unsigned int val1 ) { unsigned int v0 = val0; unsigned int v1 = val1; unsigned int s0 = 0; for( unsigned int n = 0; n < N; n++ ) { s0 += 0x9e3779b9; v0 += ((v1<<4)+0xa341316c)^(v1+s0)^((v1>>5)+0xc8013ea4); v1 += ((v0<<4)+0xad90777d)^(v0+s0)^((v0>>5)+0x7e95761e); } return v0; } // Generate random unsigned int in [0, 2^24) static __host__ __device__ __inline__ unsigned int lcg(unsigned int &prev) { const unsigned int LCG_A = 1664525u; const unsigned int LCG_C = 1013904223u; prev = (LCG_A * prev + LCG_C); return prev & 0x00FFFFFF; } static __host__ __device__ __inline__ unsigned int lcg2(unsigned int &prev) { prev = (prev*8121 + 28411) % 134456; return prev; } // Generate random float in [0, 1) static __host__ __device__ __inline__ float rnd(unsigned int &prev) { return ((float) lcg(prev) / (float) 0x01000000); } static __host__ __device__ __inline__ unsigned int rot_seed( unsigned int seed, unsigned int frame ) { return seed ^ frame; }
2,678
C
35.69863
100
0.707244
arhix52/Strelka/cuda/curve.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <optix.h> #include <sutil/vec_math.h> #include <vector_types.h> // // First order polynomial interpolator // struct LinearInterpolator { __device__ __forceinline__ LinearInterpolator() {} __device__ __forceinline__ void initialize( const float4* q ) { p[0] = q[0]; p[1] = q[1] - q[0]; } __device__ __forceinline__ float4 position4( float u ) const { return p[0] + u * p[1]; // Horner scheme } __device__ __forceinline__ float3 position3( float u ) const { return make_float3( position4( u ) ); } __device__ __forceinline__ float radius( const float& u ) const { return position4( u ).w; } __device__ __forceinline__ float4 velocity4( float u ) const { return p[1]; } __device__ __forceinline__ float3 velocity3( float u ) const { return make_float3( velocity4( u ) ); } __device__ __forceinline__ float derivative_of_radius( float u ) const { return velocity4( u ).w; } __device__ __forceinline__ float3 acceleration3( float u ) const { return make_float3( 0.f ); } __device__ __forceinline__ float4 acceleration4( float u ) const { return make_float4( 0.f ); } float4 p[2]; }; // // Second order polynomial interpolator // struct QuadraticInterpolator { __device__ __forceinline__ QuadraticInterpolator() {} __device__ __forceinline__ void initializeFromBSpline( const float4* q ) { // Bspline-to-Poly = Matrix([[1/2, -1, 1/2], // [-1, 1, 0], // [1/2, 1/2, 0]]) p[0] = ( q[0] - 2.0f * q[1] + q[2] ) / 2.0f; p[1] = ( -2.0f * q[0] + 2.0f * q[1] ) / 2.0f; p[2] = ( q[0] + q[1] ) / 2.0f; } __device__ __forceinline__ void export2BSpline( float4 bs[3] ) const { // inverse of initializeFromBSpline // Bspline-to-Poly = Matrix([[1/2, -1, 1/2], // [-1, 1, 0], // [1/2, 1/2, 0]]) // invert to get: // Poly-to-Bspline = Matrix([[0, -1/2, 1], // [0, 1/2, 1], // [2, 3/2, 1]]) bs[0] = p[0] - p[1] / 2; bs[1] = p[0] + p[1] / 2; bs[2] = p[0] + 1.5f * p[1] + 2 * p[2]; } __device__ __forceinline__ float4 position4( float u ) const { return ( p[0] * u + p[1] ) * u + p[2]; // Horner scheme } __device__ __forceinline__ float3 position3( float u ) const { return make_float3( position4( u ) ); } __device__ __forceinline__ float radius( float u ) const { return position4( u ).w; } __device__ __forceinline__ float4 velocity4( float u ) const { return 2.0f * p[0] * u + p[1]; } __device__ __forceinline__ float3 velocity3( float u ) const { return make_float3( velocity4( u ) ); } __device__ __forceinline__ float derivative_of_radius( float u ) const { return velocity4( u ).w; } __device__ __forceinline__ float4 acceleration4( float u ) const { return 2.0f * p[0]; } __device__ __forceinline__ float3 acceleration3( float u ) const { return make_float3( acceleration4( u ) ); } float4 p[3]; }; // // Third order polynomial interpolator // // Storing {p0, p1, p2, p3} for evaluation: // P(u) = p0 * u^3 + p1 * u^2 + p2 * u + p3 // struct CubicInterpolator { __device__ __forceinline__ CubicInterpolator() {} // TODO: Initialize from polynomial weights. Check that sample doesn't rely on // legacy behavior. // __device__ __forceinline__ CubicBSplineSegment( const float4* q ) { initializeFromBSpline( q ); } __device__ __forceinline__ void initializeFromBSpline( const float4* q ) { // Bspline-to-Poly = Matrix([[-1/6, 1/2, -1/2, 1/6], // [ 1/2, -1, 1/2, 0], // [-1/2, 0, 1/2, 0], // [ 1/6, 2/3, 1/6, 0]]) p[0] = ( q[0] * ( -1.0f ) + q[1] * ( 3.0f ) + q[2] * ( -3.0f ) + q[3] ) / 6.0f; p[1] = ( q[0] * ( 3.0f ) + q[1] * ( -6.0f ) + q[2] * ( 3.0f ) ) / 6.0f; p[2] = ( q[0] * ( -3.0f ) + q[2] * ( 3.0f ) ) / 6.0f; p[3] = ( q[0] * ( 1.0f ) + q[1] * ( 4.0f ) + q[2] * ( 1.0f ) ) / 6.0f; } __device__ __forceinline__ void export2BSpline( float4 bs[4] ) const { // inverse of initializeFromBSpline // Bspline-to-Poly = Matrix([[-1/6, 1/2, -1/2, 1/6], // [ 1/2, -1, 1/2, 0], // [-1/2, 0, 1/2, 0], // [ 1/6, 2/3, 1/6, 0]]) // invert to get: // Poly-to-Bspline = Matrix([[0, 2/3, -1, 1], // [0, -1/3, 0, 1], // [0, 2/3, 1, 1], // [6, 11/3, 2, 1]]) bs[0] = ( p[1] * ( 2.0f ) + p[2] * ( -1.0f ) + p[3] ) / 3.0f; bs[1] = ( p[1] * ( -1.0f ) + p[3] ) / 3.0f; bs[2] = ( p[1] * ( 2.0f ) + p[2] * ( 1.0f ) + p[3] ) / 3.0f; bs[3] = ( p[0] + p[1] * ( 11.0f ) + p[2] * ( 2.0f ) + p[3] ) / 3.0f; } __device__ __forceinline__ void initializeFromCatrom(const float4* q) { // Catrom-to-Poly = Matrix([[-1/2, 3/2, -3/2, 1/2], // [1, -5/2, 2, -1/2], // [-1/2, 0, 1/2, 0], // [0, 1, 0, 0]]) p[0] = ( -1.0f * q[0] + ( 3.0f ) * q[1] + ( -3.0f ) * q[2] + ( 1.0f ) * q[3] ) / 2.0f; p[1] = ( 2.0f * q[0] + ( -5.0f ) * q[1] + ( 4.0f ) * q[2] + ( -1.0f ) * q[3] ) / 2.0f; p[2] = ( -1.0f * q[0] + ( 1.0f ) * q[2] ) / 2.0f; p[3] = ( ( 2.0f ) * q[1] ) / 2.0f; } __device__ __forceinline__ void export2Catrom(float4 cr[4]) const { // Catrom-to-Poly = Matrix([[-1/2, 3/2, -3/2, 1/2], // [1, -5/2, 2, -1/2], // [-1/2, 0, 1/2, 0], // [0, 1, 0, 0]]) // invert to get: // Poly-to-Catrom = Matrix([[1, 1, -1, 1], // [0, 0, 0, 1], // [1, 1, 1, 1], // [6, 4, 2, 1]]) cr[0] = ( p[0] * 6.f/6.f ) - ( p[1] * 5.f/6.f ) + ( p[2] * 2.f/6.f ) + ( p[3] * 1.f/6.f ); cr[1] = ( p[0] * 6.f/6.f ) ; cr[2] = ( p[0] * 6.f/6.f ) + ( p[1] * 1.f/6.f ) + ( p[2] * 2.f/6.f ) + ( p[3] * 1.f/6.f ); cr[3] = ( p[0] * 6.f/6.f ) + ( p[3] * 6.f/6.f ); } __device__ __forceinline__ float4 position4( float u ) const { return ( ( ( p[0] * u ) + p[1] ) * u + p[2] ) * u + p[3]; // Horner scheme } __device__ __forceinline__ float3 position3( float u ) const { // rely on compiler and inlining for dead code removal return make_float3( position4( u ) ); } __device__ __forceinline__ float radius( float u ) const { return position4( u ).w; } __device__ __forceinline__ float4 velocity4( float u ) const { // adjust u to avoid problems with tripple knots. if( u == 0 ) u = 0.000001f; if( u == 1 ) u = 0.999999f; return ( ( 3.0f * p[0] * u ) + 2.0f * p[1] ) * u + p[2]; } __device__ __forceinline__ float3 velocity3( float u ) const { return make_float3( velocity4( u ) ); } __device__ __forceinline__ float derivative_of_radius( float u ) const { return velocity4( u ).w; } __device__ __forceinline__ float4 acceleration4( float u ) const { return 6.0f * p[0] * u + 2.0f * p[1]; // Horner scheme } __device__ __forceinline__ float3 acceleration3( float u ) const { return make_float3( acceleration4( u ) ); } float4 p[4]; }; // Compute curve primitive surface normal in object space. // // Template parameters: // CurveType - A B-Spline evaluator class. // type - 0 ~ cylindrical approximation (correct if radius' == 0) // 1 ~ conic approximation (correct if curve'' == 0) // other ~ the bona fide surface normal // // Parameters: // bc - A B-Spline evaluator object. // u - segment parameter of hit-point. // ps - hit-point on curve's surface in object space; usually // computed like this. // float3 ps = ray_orig + t_hit * ray_dir; // the resulting point is slightly offset away from the // surface. For this reason (Warning!) ps gets modified by this // method, projecting it onto the surface // in case it is not already on it. (See also inline // comments.) // template <typename CurveType, int type = 2> __device__ __forceinline__ float3 surfaceNormal( const CurveType& bc, float u, float3& ps ) { float3 normal; if( u == 0.0f ) { normal = -bc.velocity3( 0 ); // special handling for flat endcaps } else if( u == 1.0f ) { normal = bc.velocity3( 1 ); // special handling for flat endcaps } else { // ps is a point that is near the curve's offset surface, // usually ray.origin + ray.direction * rayt. // We will push it exactly to the surface by projecting it to the plane(p,d). // The function derivation: // we (implicitly) transform the curve into coordinate system // {p, o1 = normalize(ps - p), o2 = normalize(curve'(t)), o3 = o1 x o2} in which // curve'(t) = (0, length(d), 0); ps = (r, 0, 0); float4 p4 = bc.position4( u ); float3 p = make_float3( p4 ); float r = p4.w; // == length(ps - p) if ps is already on the surface float4 d4 = bc.velocity4( u ); float3 d = make_float3( d4 ); float dr = d4.w; float dd = dot( d, d ); float3 o1 = ps - p; // dot(modified_o1, d) == 0 by design: o1 -= ( dot( o1, d ) / dd ) * d; // first, project ps to the plane(p,d) o1 *= r / length( o1 ); // and then drop it to the surface ps = p + o1; // fine-tuning the hit point if( type == 0 ) { normal = o1; // cylindrical approximation } else { if( type != 1 ) { dd -= dot( bc.acceleration3( u ), o1 ); } normal = dd * o1 - ( dr * r ) * d; } } return normalize( normal ); } template <int type = 1> __device__ __forceinline__ float3 surfaceNormal( const LinearInterpolator& bc, float u, float3& ps ) { float3 normal; if( u == 0.0f ) { normal = ps - ( float3 & )( bc.p[0] ); // special handling for round endcaps } else if( u >= 1.0f ) { // reconstruct second control point (Note: the interpolator pre-transforms // the control-points to speed up repeated evaluation. const float3 p1 = ( float3 & ) (bc.p[1] ) + ( float3 & )( bc.p[0] ); normal = ps - p1; // special handling for round endcaps } else { // ps is a point that is near the curve's offset surface, // usually ray.origin + ray.direction * rayt. // We will push it exactly to the surface by projecting it to the plane(p,d). // The function derivation: // we (implicitly) transform the curve into coordinate system // {p, o1 = normalize(ps - p), o2 = normalize(curve'(t)), o3 = o1 x o2} in which // curve'(t) = (0, length(d), 0); ps = (r, 0, 0); float4 p4 = bc.position4( u ); float3 p = make_float3( p4 ); float r = p4.w; // == length(ps - p) if ps is already on the surface float4 d4 = bc.velocity4( u ); float3 d = make_float3( d4 ); float dr = d4.w; float dd = dot( d, d ); float3 o1 = ps - p; // dot(modified_o1, d) == 0 by design: o1 -= ( dot( o1, d ) / dd ) * d; // first, project ps to the plane(p,d) o1 *= r / length( o1 ); // and then drop it to the surface ps = p + o1; // fine-tuning the hit point if( type == 0 ) { normal = o1; // cylindrical approximation } else { normal = dd * o1 - ( dr * r ) * d; } } return normalize( normal ); } // Compute curve primitive tangent in object space. // // Template parameters: // CurveType - A B-Spline evaluator class. // // Parameters: // bc - A B-Spline evaluator object. // u - segment parameter of tangent location on curve. // template <typename CurveType> __device__ __forceinline__ float3 curveTangent( const CurveType& bc, float u ) { float3 tangent = bc.velocity3( u ); return normalize( tangent ); }
14,969
C
34.813397
104
0.48567
arhix52/Strelka/cuda/helpers.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <vector_types.h> #include <sutil/vec_math.h> __forceinline__ __device__ float3 toSRGB( const float3& c ) { float invGamma = 1.0f / 2.4f; float3 powed = make_float3( powf( c.x, invGamma ), powf( c.y, invGamma ), powf( c.z, invGamma ) ); return make_float3( c.x < 0.0031308f ? 12.92f * c.x : 1.055f * powed.x - 0.055f, c.y < 0.0031308f ? 12.92f * c.y : 1.055f * powed.y - 0.055f, c.z < 0.0031308f ? 12.92f * c.z : 1.055f * powed.z - 0.055f ); } //__forceinline__ __device__ float dequantizeUnsigned8Bits( const unsigned char i ) //{ // enum { N = (1 << 8) - 1 }; // return min((float)i / (float)N), 1.f) //} __forceinline__ __device__ unsigned char quantizeUnsigned8Bits( float x ) { x = clamp( x, 0.0f, 1.0f ); enum { N = (1 << 8) - 1, Np1 = (1 << 8) }; return (unsigned char)min((unsigned int)(x * (float)Np1), (unsigned int)N); } __forceinline__ __device__ uchar4 make_color( const float3& c ) { // first apply gamma, then convert to unsigned char float3 srgb = toSRGB( clamp( c, 0.0f, 1.0f ) ); return make_uchar4( quantizeUnsigned8Bits( srgb.x ), quantizeUnsigned8Bits( srgb.y ), quantizeUnsigned8Bits( srgb.z ), 255u ); } __forceinline__ __device__ uchar4 make_color( const float4& c ) { return make_color( make_float3( c.x, c.y, c.z ) ); }
2,911
C
42.462686
130
0.687736
arhix52/Strelka/cuda/util.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #ifndef __CUDACC_RTC__ #include <stdio.h> #endif #define if_pixel( x_, y_ ) \ const uint3 launch_idx__ = optixGetLaunchIndex(); \ if( launch_idx__.x == (x_) && launch_idx__.y == (y_) ) \ #define print_pixel( x_, y_, str, ... ) \ do \ { \ const uint3 launch_idx = optixGetLaunchIndex(); \ if( launch_idx.x == (x_) && launch_idx.y == (y_) ) \ { \ printf( str, __VA_ARGS__ ); \ } \ } while(0);
2,534
C
50.734693
80
0.561957
arhix52/Strelka/tests/tests_main.cpp
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <doctest/doctest.h> // This is all that is needed to compile a test-runner executable. // More tests can be added here, or in a new tests/*.cpp file.
203
C++
32.999995
66
0.748768
arhix52/Strelka/tests/materialmanager/test_materialmanager.cpp
#include <materialmanager/materialmanager.h> // #include <render/render.h> #include <doctest/doctest.h> #include <filesystem> #include <fstream> #include <iostream> #include <cassert> using namespace oka; namespace fs = std::filesystem; TEST_CASE("mtlx to hlsl code gen test") { // static const char* DEFAULT_MTLX_DOC_1 = // "<?xml version=\"1.0\"?>" // "<materialx version=\"1.38\" colorspace=\"lin_rec709\">" // " <UsdPreviewSurface name=\"SR_Invalid\" type=\"surfaceshader\">" // " <input name=\"diffuseColor\" type=\"color3\" value=\"1.0, 0.0, 1.0\" />" // " <input name=\"roughness\" type=\"float\" value=\"1.0\" />" // " </UsdPreviewSurface>" // " <surfacematerial name=\"invalid\" type=\"material\">" // " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_Invalid\" />" // " </surfacematerial>" // "</materialx>"; static const char* DEFAULT_MTLX_DOC_1 = "<?xml version=\"1.0\"?>" "<materialx version=\"1.38\" colorspace=\"lin_rec709\">" " <UsdPreviewSurface name=\"SR_default\" type=\"surfaceshader\">" " <input name=\"diffuseColor\" type=\"color3\" value=\"0.18, 0.18, 0.18\" />" " <input name=\"emissiveColor\" type=\"color3\" value=\"0, 0, 0\" />" " <input name=\"useSpecularWorkflow\" type=\"integer\" value=\"0\" />" " <input name=\"specularColor\" type=\"color3\" value=\"0, 0, 0\" />" " <input name=\"metallic\" type=\"float\" value=\"0\" />" " <input name=\"roughness\" type=\"float\" value=\"0.5\" />" " <input name=\"clearcoat\" type=\"float\" value=\"0\" />" " <input name=\"clearcoatRoughness\" type=\"float\" value=\"0.01\" />" " <input name=\"opacity\" type=\"float\" value=\"1\" />" " <input name=\"opacityThreshold\" type=\"float\" value=\"0\" />" " <input name=\"ior\" type=\"float\" value=\"1.5\" />" " <input name=\"normal\" type=\"vector3\" value=\"0, 0, 1\" />" " <input name=\"displacement\" type=\"float\" value=\"0\" />" " <input name=\"occlusion\" type=\"float\" value=\"1\" />" " </UsdPreviewSurface>" " <surfacematerial name=\"USD_Default\" type=\"material\">" " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_default\" />" " </surfacematerial>" "</materialx>"; static const char* DEFAULT_MTLX_DOC_2 = "<?xml version=\"1.0\"?>" "<materialx version=\"1.38\" colorspace=\"lin_rec709\">" " <UsdPreviewSurface name=\"SR_Invalid\" type=\"surfaceshader\">" " <input name=\"diffuseColor\" type=\"color3\" value=\"0.0, 0.0, 1.0\" />" " <input name=\"roughness\" type=\"float\" value=\"1.0\" />" " </UsdPreviewSurface>" " <surfacematerial name=\"invalid\" type=\"material\">" " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_Invalid\" />" " </surfacematerial>" "</materialx>"; using namespace std; const fs::path cwd = fs::current_path(); cout << cwd.c_str() << endl; std::string mdlFile = "material.mdl"; std::ofstream mdlMaterial(mdlFile.c_str()); MaterialManager* matMngr = new MaterialManager(); CHECK(matMngr); const char* envUSDPath = std::getenv("USD_DIR"); if (!envUSDPath) { printf("Please, set USD_DIR variable\n"); assert(0); } const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\"; const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/" }; bool res = matMngr->addMdlSearchPath(paths, 2); CHECK(res); MaterialManager::Module* mdlModule = matMngr->createMtlxModule(DEFAULT_MTLX_DOC_1); assert(mdlModule); MaterialManager::MaterialInstance* materialInst = matMngr->createMaterialInstance(mdlModule, ""); assert(materialInst); MaterialManager::CompiledMaterial* materialComp = matMngr->compileMaterial(materialInst); assert(materialComp); MaterialManager::Module* mdlModule2 = matMngr->createMtlxModule(DEFAULT_MTLX_DOC_2); assert(mdlModule2); MaterialManager::MaterialInstance* materialInst2 = matMngr->createMaterialInstance(mdlModule2, ""); assert(materialInst2); MaterialManager::CompiledMaterial* materialComp2 = matMngr->compileMaterial(materialInst2); assert(materialComp2); MaterialManager::CompiledMaterial* materials[2] = { materialComp, materialComp2 }; // std::vector<MaterialManager::CompiledMaterial*> materials; // materials.push_back(materialComp); // materials.push_back(materialComp2); const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials, 2); CHECK(code); const char* hlsl = matMngr->getShaderCode(code, 0); std::string shaderFile = "test_material_output.hlsl"; std::ofstream out(shaderFile.c_str()); out << hlsl << std::endl; out.close(); delete matMngr; } TEST_CASE("MDL OmniPBR") { using namespace std; const fs::path cwd = fs::current_path(); cout << cwd.c_str() << endl; std::string mdlFile = "C:\\work\\StrelkaOptix\\build\\data\\materials\\mtlx\\OmniPBR.mdl"; // std::ofstream mdlMaterial(mdlFile.c_str()); MaterialManager* matMngr = new MaterialManager(); CHECK(matMngr); const char* envUSDPath = std::getenv("USD_DIR"); if (!envUSDPath) { printf("Please, set USD_DIR variable\n"); assert(0); } const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\"; const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/", "C:\\work\\StrelkaOptix\\build\\data\\materials\\mtlx\\", "C:\\work\\Strelka\\misc\\test_data\\mdl" }; bool res = matMngr->addMdlSearchPath(paths, 4); CHECK(res); MaterialManager::Module* currModule = matMngr->createModule(mdlFile.c_str()); CHECK(currModule); MaterialManager::MaterialInstance* materialInst1 = matMngr->createMaterialInstance(currModule, "OmniPBR"); CHECK(materialInst1); MaterialManager::CompiledMaterial* materialComp1 = matMngr->compileMaterial(materialInst1); CHECK(materialComp1); MaterialManager::CompiledMaterial* materials[1] = { materialComp1 }; const MaterialManager::TargetCode* targetCode = matMngr->generateTargetCode(materials, 1); CHECK(targetCode); const char* ptx = matMngr->getShaderCode(targetCode, 0); string ptxFileName = cwd.string() + "/output.ptx"; ofstream outPtxFile(ptxFileName.c_str()); outPtxFile << ptx << endl; outPtxFile.close(); delete matMngr; } // TEST_CASE("mdl to hlsl code gen test") // { // using namespace std; // const fs::path cwd = fs::current_path(); // cout << cwd.c_str() << endl; // std::string ptFile = cwd.string() + "/output.ptx"; // std::ofstream outHLSLShaderFile(ptFile.c_str()); // // Render r; // // r.HEIGHT = 600; // // r.WIDTH = 800; // // r.initWindow(); // // r.initVulkan(); // MaterialManager* matMngr = new MaterialManager(); // CHECK(matMngr); // const char* envUSDPath = std::getenv("USD_DIR"); // if (!envUSDPath) // { // printf("Please, set USD_DIR variable\n"); // assert(0); // } // const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\"; // const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/" }; // bool res = matMngr->addMdlSearchPath(paths, 2); // CHECK(res); // MaterialManager::Module* defaultModule = matMngr->createModule("default.mdl"); // CHECK(defaultModule); // MaterialManager::MaterialInstance* materialInst0 = matMngr->createMaterialInstance(defaultModule, "default_material"); // CHECK(materialInst0); // MaterialManager::CompiledMaterial* materialComp0 = matMngr->compileMaterial(materialInst0); // CHECK(materialComp0); // MaterialManager::CompiledMaterial* materialComp00 = matMngr->compileMaterial(materialInst0); // CHECK(materialComp00); // MaterialManager::CompiledMaterial* materialComp000 = matMngr->compileMaterial(materialInst0); // CHECK(materialComp000); // MaterialManager::Module* currModule = matMngr->createModule("OmniGlass.mdl"); // CHECK(currModule); // MaterialManager::MaterialInstance* materialInst1 = matMngr->createMaterialInstance(currModule, "OmniGlass"); // CHECK(materialInst1); // MaterialManager::CompiledMaterial* materialComp1 = matMngr->compileMaterial(materialInst1); // CHECK(materialComp1); // MaterialManager::CompiledMaterial* materialsDefault[1] = { materialComp0 }; // // const MaterialManager::TargetCode* codeDefault = matMngr->generateTargetCode(materialsDefault, 1); // // CHECK(codeDefault); // MaterialManager::CompiledMaterial* materials[4] = { materialComp0, materialComp00, materialComp1, materialComp000 }; // const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials, 4); // CHECK(code); // const char* hlsl = matMngr->getShaderCode(code); // // std::cout << hlsl << std::endl; // uint32_t size = matMngr->getArgBufferSize(code); // CHECK(size != 0); // size = matMngr->getArgBufferSize(code); // CHECK(size != 0); // size = matMngr->getResourceInfoSize(code); // CHECK(size != 0); // matMngr->dumpParams(code, materialComp1); // // nevk::TextureManager* mTexManager = new nevk::TextureManager(r.getDevice(), r.getPhysicalDevice(), // // r.getResManager()); // uint32_t texSize = matMngr->getTextureCount(code); // // CHECK(texSize == 8); // // for (uint32_t i = 0; i < texSize; ++i) // // { // // const float* data = matMngr->getTextureData(code, i); // // uint32_t width = matMngr->getTextureWidth(code, i); // // uint32_t height = matMngr->getTextureHeight(code, i); // // const char* type = matMngr->getTextureType(code, i); // // std::string name = matMngr->getTextureName(code, i); // // // mTexManager->loadTextureMdl(data, width, height, type, name); // // } // // CHECK(mTexManager->textures.size() == 7); // // CHECK(mTexManager->textures[0].texWidth == 512); // // CHECK(mTexManager->textures[0].texHeight == 512); // delete matMngr; // } // TEST_CASE("mtlx to mdl code gen test") // { // using namespace std; // const fs::path cwd = fs::current_path(); // cout << cwd.c_str() << endl; // std::string mdlFile = "material.mdl"; // std::ofstream mdlMaterial(mdlFile.c_str()); // std::string ptFile = cwd.string() + "/shaders/newPT.hlsl"; // std::ofstream outHLSLShaderFile(ptFile.c_str()); // Render r; // r.HEIGHT = 600; // r.WIDTH = 800; // r.initWindow(); // r.initVulkan(); // MaterialManager* matMngr = new MaterialManager(); // CHECK(matMngr); // const char* path[2] = { "misc/test_data/mdl/", "misc/test_data/mtlx" }; // todo: configure paths // bool res = matMngr->addMdlSearchPath(path, 2); // CHECK(res); // std::string file = "misc/test_data/mtlx/standard_surface_wood_tiled.mtlx"; // std::unique_ptr<MaterialManager::Module> currModule = matMngr->createMtlxModule(file.c_str()); // CHECK(currModule); // std::unique_ptr<MaterialManager::MaterialInstance> materialInst1 = // matMngr->createMaterialInstance(currModule.get(), ""); CHECK(materialInst1); // std::unique_ptr<MaterialManager::CompiledMaterial> materialComp1 = matMngr->compileMaterial(materialInst1.get()); // CHECK(materialComp1); // std::vector<std::unique_ptr<MaterialManager::CompiledMaterial>> materials; // materials.push_back(std::move(materialComp1)); // const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials); // CHECK(code); // const char* hlsl = matMngr->getShaderCode(code); // //std::cout << hlsl << std::endl; // uint32_t size = matMngr->getArgBufferSize(code); // CHECK(size != 0); // size = matMngr->getArgBufferSize(code); // CHECK(size != 0); // size = matMngr->getResourceInfoSize(code); // CHECK(size != 0); // nevk::TextureManager* mTexManager = new nevk::TextureManager(r.getDevice(), r.getPhysicalDevice(), // r.getResManager()); uint32_t texSize = matMngr->getTextureCount(code); for (uint32_t i = 1; i < texSize; ++i) // { // const float* data = matMngr->getTextureData(code, i); // uint32_t width = matMngr->getTextureWidth(code, i); // uint32_t height = matMngr->getTextureHeight(code, i); // const char* type = matMngr->getTextureType(code, i); // std::string name = matMngr->getTextureName(code, i); // if (data != NULL) // todo: for bsdf_text data is NULL in COMPILATION_CLASS. in default class there is no // bsdf_tex // { // mTexManager->loadTextureMdl(data, width, height, type, name); // } // } // CHECK(mTexManager->textures.size() == 2); // CHECK(mTexManager->textures[0].texWidth == 512); // CHECK(mTexManager->textures[0].texHeight == 512); // }
13,259
C++
40.698113
125
0.621465
arhix52/Strelka/sutil/Quaternion.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <sutil/Matrix.h> //------------------------------------------------------------------------------ // // Quaternion class // //------------------------------------------------------------------------------ namespace sutil { class Quaternion { public: Quaternion() { q[0] = q[1] = q[2] = q[3] = 0.0; } Quaternion( float w, float x, float y, float z ) { q[0] = w; q[1] = x; q[2] = y; q[3] = z; } Quaternion( const float3& from, const float3& to ); Quaternion( const Quaternion& a ) { q[0] = a[0]; q[1] = a[1]; q[2] = a[2]; q[3] = a[3]; } Quaternion ( float angle, const float3& axis ); // getters and setters void setW(float _w) { q[0] = _w; } void setX(float _x) { q[1] = _x; } void setY(float _y) { q[2] = _y; } void setZ(float _z) { q[3] = _z; } float w() const { return q[0]; } float x() const { return q[1]; } float y() const { return q[2]; } float z() const { return q[3]; } Quaternion& operator-=(const Quaternion& r) { q[0] -= r[0]; q[1] -= r[1]; q[2] -= r[2]; q[3] -= r[3]; return *this; } Quaternion& operator+=(const Quaternion& r) { q[0] += r[0]; q[1] += r[1]; q[2] += r[2]; q[3] += r[3]; return *this; } Quaternion& operator*=(const Quaternion& r); Quaternion& operator/=(const float a); Quaternion conjugate() { return Quaternion( q[0], -q[1], -q[2], -q[3] ); } void rotation( float& angle, float3& axis ) const; void rotation( float& angle, float& x, float& y, float& z ) const; Matrix4x4 rotationMatrix() const; float& operator[](int i) { return q[i]; } float operator[](int i)const { return q[i]; } // l2 norm float norm() const { return sqrtf(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]); } float normalize(); private: float q[4]; }; inline Quaternion::Quaternion( const float3& from, const float3& to ) { const float3 c = cross( from, to ); q[0] = dot(from, to); q[1] = c.x; q[2] = c.y; q[3] = c.z; } inline Quaternion::Quaternion( float angle, const float3& axis ) { const float n = length( axis ); const float inverse = 1.0f/n; const float3 naxis = axis*inverse; const float s = sinf(angle/2.0f); q[0] = naxis.x*s*inverse; q[1] = naxis.y*s*inverse; q[2] = naxis.z*s*inverse; q[3] = cosf(angle/2.0f); } inline Quaternion& Quaternion::operator*=(const Quaternion& r) { float w = q[0]*r[0] - q[1]*r[1] - q[2]*r[2] - q[3]*r[3]; float x = q[0]*r[1] + q[1]*r[0] + q[2]*r[3] - q[3]*r[2]; float y = q[0]*r[2] + q[2]*r[0] + q[3]*r[1] - q[1]*r[3]; float z = q[0]*r[3] + q[3]*r[0] + q[1]*r[2] - q[2]*r[1]; q[0] = w; q[1] = x; q[2] = y; q[3] = z; return *this; } inline Quaternion& Quaternion::operator/=(const float a) { float inverse = 1.0f/a; q[0] *= inverse; q[1] *= inverse; q[2] *= inverse; q[3] *= inverse; return *this; } inline void Quaternion::rotation( float& angle, float3& axis ) const { Quaternion n = *this; n.normalize(); axis.x = n[1]; axis.y = n[2]; axis.z = n[3]; angle = 2.0f * acosf(n[0]); } inline void Quaternion::rotation( float& angle, float& x, float& y, float& z ) const { Quaternion n = *this; n.normalize(); x = n[1]; y = n[2]; z = n[3]; angle = 2.0f * acosf(n[0]); } inline float Quaternion::normalize() { float n = norm(); float inverse = 1.0f/n; q[0] *= inverse; q[1] *= inverse; q[2] *= inverse; q[3] *= inverse; return n; } inline Quaternion operator*(const float a, const Quaternion &r) { return Quaternion(a*r[0], a*r[1], a*r[2], a*r[3]); } inline Quaternion operator*(const Quaternion &r, const float a) { return Quaternion(a*r[0], a*r[1], a*r[2], a*r[3]); } inline Quaternion operator/(const Quaternion &r, const float a) { float inverse = 1.0f/a; return Quaternion( r[0]*inverse, r[1]*inverse, r[2]*inverse, r[3]*inverse); } inline Quaternion operator/(const float a, const Quaternion &r) { float inverse = 1.0f/a; return Quaternion( r[0]*inverse, r[1]*inverse, r[2]*inverse, r[3]*inverse); } inline Quaternion operator-(const Quaternion& l, const Quaternion& r) { return Quaternion(l[0]-r[0], l[1]-r[1], l[2]-r[2], l[3]-r[3]); } inline bool operator==(const Quaternion& l, const Quaternion& r) { return ( l[0] == r[0] && l[1] == r[1] && l[2] == r[2] && l[3] == r[3] ); } inline bool operator!=(const Quaternion& l, const Quaternion& r) { return !(l == r); } inline Quaternion operator+(const Quaternion& l, const Quaternion& r) { return Quaternion(l[0]+r[0], l[1]+r[1], l[2]+r[2], l[3]+r[3]); } inline Quaternion operator*(const Quaternion& l, const Quaternion& r) { float w = l[0]*r[0] - l[1]*r[1] - l[2]*r[2] - l[3]*r[3]; float x = l[0]*r[1] + l[1]*r[0] + l[2]*r[3] - l[3]*r[2]; float y = l[0]*r[2] + l[2]*r[0] + l[3]*r[1] - l[1]*r[3]; float z = l[0]*r[3] + l[3]*r[0] + l[1]*r[2] - l[2]*r[1]; return Quaternion( w, x, y, z ); } inline float dot( const Quaternion& l, const Quaternion& r ) { return l.w()*r.w() + l.x()*r.x() + l.y()*r.y() + l.z()*r.z(); } inline Matrix4x4 Quaternion::rotationMatrix() const { Matrix4x4 m; const float qw = q[0]; const float qx = q[1]; const float qy = q[2]; const float qz = q[3]; m[0*4+0] = 1.0f - 2.0f*qy*qy - 2.0f*qz*qz; m[0*4+1] = 2.0f*qx*qy - 2.0f*qz*qw; m[0*4+2] = 2.0f*qx*qz + 2.0f*qy*qw; m[0*4+3] = 0.0f; m[1*4+0] = 2.0f*qx*qy + 2.0f*qz*qw; m[1*4+1] = 1.0f - 2.0f*qx*qx - 2.0f*qz*qz; m[1*4+2] = 2.0f*qy*qz - 2.0f*qx*qw; m[1*4+3] = 0.0f; m[2*4+0] = 2.0f*qx*qz - 2.0f*qy*qw; m[2*4+1] = 2.0f*qy*qz + 2.0f*qx*qw; m[2*4+2] = 1.0f - 2.0f*qx*qx - 2.0f*qy*qy; m[2*4+3] = 0.0f; m[3*4+0] = 0.0f; m[3*4+1] = 0.0f; m[3*4+2] = 0.0f; m[3*4+3] = 1.0f; return m; } } // end namespace sutil
7,605
C
26.963235
80
0.56121
arhix52/Strelka/sutil/Matrix.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <sutil/sutilapi.h> #include <sutil/Preprocessor.h> #include <sutil/vec_math.h> #if !defined(__CUDACC_RTC__) #include <cmath> #include <initializer_list> #endif #define RT_MATRIX_ACCESS(m,i,j) m[i*N+j] #define RT_MAT_DECL template <unsigned int M, unsigned int N> namespace sutil { template <int DIM> struct VectorDim { }; template <> struct VectorDim<2> { typedef float2 VectorType; }; template <> struct VectorDim<3> { typedef float3 VectorType; }; template <> struct VectorDim<4> { typedef float4 VectorType; }; template <unsigned int M, unsigned int N> class Matrix; template <unsigned int M> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,M>& operator*=(Matrix<M,M>& m1, const Matrix<M,M>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator-=(Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator+=(Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator*=(Matrix<M,N>& m1, float f); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>&operator/=(Matrix<M,N>& m1, float f); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator-(const Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator+(const Matrix<M,N>& m1, const Matrix<M,N>& m2); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator/(const Matrix<M,N>& m, float f); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator*(const Matrix<M,N>& m, float f); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator*(float f, const Matrix<M,N>& m); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM operator*(const Matrix<M,N>& m, const typename Matrix<M,N>::floatN& v ); RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN operator*(const typename Matrix<M,N>::floatM& v, const Matrix<M,N>& m); template<unsigned int M, unsigned int N, unsigned int R> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,R> operator*(const Matrix<M,N>& m1, const Matrix<N,R>& m2); // Partial specializations to make matrix vector multiplication more efficient template <unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const Matrix<2,N>& m, const typename Matrix<2,N>::floatN& vec ); template <unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,N>& m, const typename Matrix<3,N>::floatN& vec ); SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,4>& m, const float4& vec ); template <unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,N>& m, const typename Matrix<4,N>::floatN& vec ); SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,4>& m, const float4& vec ); /** * @brief A matrix with M rows and N columns * * @ingroup CUDACTypes * * <B>Description</B> * * @ref Matrix provides a utility class for small-dimension floating-point * matrices, such as transformation matrices. @ref Matrix may also be useful * in other computation and can be used in both host and device code. * Typedefs are provided for 2x2 through 4x4 matrices. * */ template <unsigned int M, unsigned int N> class Matrix { public: typedef typename VectorDim<N>::VectorType floatN; /// A row of the matrix typedef typename VectorDim<M>::VectorType floatM; /// A column of the matrix /** Create an uninitialized matrix */ SUTIL_HOSTDEVICE Matrix(); /** Create a matrix from the specified float array */ SUTIL_HOSTDEVICE explicit Matrix( const float data[M*N] ) { for(unsigned int i = 0; i < M*N; ++i) m_data[i] = data[i]; } /** Copy the matrix */ SUTIL_HOSTDEVICE Matrix( const Matrix& m ); SUTIL_HOSTDEVICE Matrix( const std::initializer_list<float>& list ); /** Assignment operator */ SUTIL_HOSTDEVICE Matrix& operator=( const Matrix& b ); /** Access the specified element 0..N*M-1 */ SUTIL_HOSTDEVICE float operator[]( unsigned int i )const { return m_data[i]; } /** Access the specified element 0..N*M-1 */ SUTIL_HOSTDEVICE float& operator[]( unsigned int i ) { return m_data[i]; } /** Access the specified row 0..M. Returns float, float2, float3 or float4 depending on the matrix size */ SUTIL_HOSTDEVICE floatN getRow( unsigned int m )const; /** Access the specified column 0..N. Returns float, float2, float3 or float4 depending on the matrix size */ SUTIL_HOSTDEVICE floatM getCol( unsigned int n )const; /** Returns a pointer to the internal data array. The data array is stored in row-major order. */ SUTIL_HOSTDEVICE float* getData(); /** Returns a const pointer to the internal data array. The data array is stored in row-major order. */ SUTIL_HOSTDEVICE const float* getData()const; /** Assign the specified row 0..M. Takes a float, float2, float3 or float4 depending on the matrix size */ SUTIL_HOSTDEVICE void setRow( unsigned int m, const floatN &r ); /** Assign the specified column 0..N. Takes a float, float2, float3 or float4 depending on the matrix size */ SUTIL_HOSTDEVICE void setCol( unsigned int n, const floatM &c ); /** Returns the transpose of the matrix */ SUTIL_HOSTDEVICE Matrix<N,M> transpose() const; /** Returns the inverse of the matrix */ SUTIL_HOSTDEVICE Matrix<4,4> inverse() const; /** Returns the determinant of the matrix */ SUTIL_HOSTDEVICE float det() const; /** Returns a rotation matrix */ SUTIL_HOSTDEVICE static Matrix<4,4> rotate(const float radians, const float3& axis); /** Returns a translation matrix */ SUTIL_HOSTDEVICE static Matrix<4,4> translate(const float3& vec); /** Returns a scale matrix */ SUTIL_HOSTDEVICE static Matrix<4,4> scale(const float3& vec); /** Creates a matrix from an ONB and center point */ SUTIL_HOSTDEVICE static Matrix<4,4> fromBasis( const float3& u, const float3& v, const float3& w, const float3& c ); /** Returns the identity matrix */ SUTIL_HOSTDEVICE static Matrix<3,4> affineIdentity(); SUTIL_HOSTDEVICE static Matrix<N,N> identity(); /** Ordered comparison operator so that the matrix can be used in an STL container */ SUTIL_HOSTDEVICE bool operator<( const Matrix<M, N>& rhs ) const; private: /** The data array is stored in row-major order */ float m_data[M*N]; }; template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix() { } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix( const Matrix<M,N>& m ) { for(unsigned int i = 0; i < M*N; ++i) m_data[i] = m[i]; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix( const std::initializer_list<float>& list ) { int i = 0; for( auto it = list.begin(); it != list.end(); ++it ) m_data[ i++ ] = *it; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& Matrix<M,N>::operator=( const Matrix& b ) { for(unsigned int i = 0; i < M*N; ++i) m_data[i] = b[i]; return *this; } /* template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<M,N>::operator[]( unsigned int i )const { return m_data[i]; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float& Matrix<M,N>::operator[]( unsigned int i ) { return m_data[i]; } */ template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN Matrix<M,N>::getRow( unsigned int m )const { typename Matrix<M,N>::floatN temp; float* v = reinterpret_cast<float*>( &temp ); const float* row = &( m_data[m*N] ); for(unsigned int i = 0; i < N; ++i) v[i] = row[i]; return temp; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM Matrix<M,N>::getCol( unsigned int n )const { typename Matrix<M,N>::floatM temp; float* v = reinterpret_cast<float*>( &temp ); for ( unsigned int i = 0; i < M; ++i ) v[i] = RT_MATRIX_ACCESS( m_data, i, n ); return temp; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float* Matrix<M,N>::getData() { return m_data; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE const float* Matrix<M,N>::getData() const { return m_data; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE void Matrix<M,N>::setRow( unsigned int m, const typename Matrix<M,N>::floatN &r ) { const float* v = reinterpret_cast<const float*>( &r ); float* row = &( m_data[m*N] ); for(unsigned int i = 0; i < N; ++i) row[i] = v[i]; } template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE void Matrix<M,N>::setCol( unsigned int n, const typename Matrix<M,N>::floatM &c ) { const float* v = reinterpret_cast<const float*>( &c ); for ( unsigned int i = 0; i < M; ++i ) RT_MATRIX_ACCESS( m_data, i, n ) = v[i]; } // Compare two matrices using exact float comparison template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE bool operator==(const Matrix<M,N>& m1, const Matrix<M,N>& m2) { for ( unsigned int i = 0; i < M*N; ++i ) if ( m1[i] != m2[i] ) return false; return true; } template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE bool operator!=(const Matrix<M,N>& m1, const Matrix<M,N>& m2) { for ( unsigned int i = 0; i < M*N; ++i ) if ( m1[i] != m2[i] ) return true; return false; } // Subtract two matrices of the same size. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N> operator-(const Matrix<M,N>& m1, const Matrix<M,N>& m2) { Matrix<M,N> temp( m1 ); temp -= m2; return temp; } // Subtract two matrices of the same size. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N>& operator-=(Matrix<M,N>& m1, const Matrix<M,N>& m2) { for ( unsigned int i = 0; i < M*N; ++i ) m1[i] -= m2[i]; return m1; } // Add two matrices of the same size. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N> operator+(const Matrix<M,N>& m1, const Matrix<M,N>& m2) { Matrix<M,N> temp( m1 ); temp += m2; return temp; } // Add two matrices of the same size. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N>& operator+=(Matrix<M,N>& m1, const Matrix<M,N>& m2) { for ( unsigned int i = 0; i < M*N; ++i ) m1[i] += m2[i]; return m1; } // Multiply two compatible matrices. template<unsigned int M, unsigned int N, unsigned int R> SUTIL_HOSTDEVICE Matrix<M,R> operator*( const Matrix<M,N>& m1, const Matrix<N,R>& m2) { Matrix<M,R> temp; for ( unsigned int i = 0; i < M; ++i ) { for ( unsigned int j = 0; j < R; ++j ) { float sum = 0.0f; for ( unsigned int k = 0; k < N; ++k ) { float ik = m1[ i*N+k ]; float kj = m2[ k*R+j ]; sum += ik * kj; } temp[i*R+j] = sum; } } return temp; } // Multiply two compatible matrices. template<unsigned int M> SUTIL_HOSTDEVICE Matrix<M,M>& operator*=(Matrix<M,M>& m1, const Matrix<M,M>& m2) { m1 = m1*m2; return m1; } // Multiply matrix by vector template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM operator*(const Matrix<M,N>& m, const typename Matrix<M,N>::floatN& vec ) { typename Matrix<M,N>::floatM temp; float* t = reinterpret_cast<float*>( &temp ); const float* v = reinterpret_cast<const float*>( &vec ); for (unsigned int i = 0; i < M; ++i) { float sum = 0.0f; for (unsigned int j = 0; j < N; ++j) { sum += RT_MATRIX_ACCESS( m, i, j ) * v[j]; } t[i] = sum; } return temp; } // Multiply matrix2xN by floatN template<unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const Matrix<2,N>& m, const typename Matrix<2,N>::floatN& vec ) { float2 temp = { 0.0f, 0.0f }; const float* v = reinterpret_cast<const float*>( &vec ); int index = 0; for (unsigned int j = 0; j < N; ++j) temp.x += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.y += m[index++] * v[j]; return temp; } // Multiply matrix3xN by floatN template<unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,N>& m, const typename Matrix<3,N>::floatN& vec ) { float3 temp = { 0.0f, 0.0f, 0.0f }; const float* v = reinterpret_cast<const float*>( &vec ); int index = 0; for (unsigned int j = 0; j < N; ++j) temp.x += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.y += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.z += m[index++] * v[j]; return temp; } // Multiply matrix4xN by floatN template<unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,N>& m, const typename Matrix<4,N>::floatN& vec ) { float4 temp = { 0.0f, 0.0f, 0.0f, 0.0f }; const float* v = reinterpret_cast<const float*>( &vec ); int index = 0; for (unsigned int j = 0; j < N; ++j) temp.x += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.y += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.z += m[index++] * v[j]; for (unsigned int j = 0; j < N; ++j) temp.w += m[index++] * v[j]; return temp; } // Multiply matrix4x4 by float4 SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,4>& m, const float4& vec ) { float3 temp; temp.x = m[ 0] * vec.x + m[ 1] * vec.y + m[ 2] * vec.z + m[ 3] * vec.w; temp.y = m[ 4] * vec.x + m[ 5] * vec.y + m[ 6] * vec.z + m[ 7] * vec.w; temp.z = m[ 8] * vec.x + m[ 9] * vec.y + m[10] * vec.z + m[11] * vec.w; return temp; } // Multiply matrix4x4 by float4 SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,4>& m, const float4& vec ) { float4 temp; temp.x = m[ 0] * vec.x + m[ 1] * vec.y + m[ 2] * vec.z + m[ 3] * vec.w; temp.y = m[ 4] * vec.x + m[ 5] * vec.y + m[ 6] * vec.z + m[ 7] * vec.w; temp.z = m[ 8] * vec.x + m[ 9] * vec.y + m[10] * vec.z + m[11] * vec.w; temp.w = m[12] * vec.x + m[13] * vec.y + m[14] * vec.z + m[15] * vec.w; return temp; } // Multiply vector by matrix template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN operator*(const typename Matrix<M,N>::floatM& vec, const Matrix<M,N>& m) { typename Matrix<M,N>::floatN temp; float* t = reinterpret_cast<float*>( &temp ); const float* v = reinterpret_cast<const float*>( &vec); for (unsigned int i = 0; i < N; ++i) { float sum = 0.0f; for (unsigned int j = 0; j < M; ++j) { sum += v[j] * RT_MATRIX_ACCESS( m, j, i ) ; } t[i] = sum; } return temp; } // Multply matrix by a scalar. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N> operator*(const Matrix<M,N>& m, float f) { Matrix<M,N> temp( m ); temp *= f; return temp; } // Multply matrix by a scalar. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N>& operator*=(Matrix<M,N>& m, float f) { for ( unsigned int i = 0; i < M*N; ++i ) m[i] *= f; return m; } // Multply matrix by a scalar. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N> operator*(float f, const Matrix<M,N>& m) { Matrix<M,N> temp; for ( unsigned int i = 0; i < M*N; ++i ) temp[i] = m[i]*f; return temp; } // Divide matrix by a scalar. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N> operator/(const Matrix<M,N>& m, float f) { Matrix<M,N> temp( m ); temp /= f; return temp; } // Divide matrix by a scalar. template<unsigned int M, unsigned int N> SUTIL_HOSTDEVICE Matrix<M,N>& operator/=(Matrix<M,N>& m, float f) { float inv_f = 1.0f / f; for ( unsigned int i = 0; i < M*N; ++i ) m[i] *= inv_f; return m; } // Returns the transpose of the matrix. template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<N,M> Matrix<M,N>::transpose() const { Matrix<N,M> ret; for( unsigned int row = 0; row < M; ++row ) for( unsigned int col = 0; col < N; ++col ) ret[col*M+row] = m_data[row*N+col]; return ret; } // Returns the determinant of the matrix. template<> SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<3,3>::det() const { const float* m = m_data; float d = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7] - m[0]*m[5]*m[7] - m[1]*m[3]*m[8] - m[2]*m[4]*m[6]; return d; } // Returns the determinant of the matrix. template<> SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<4,4>::det() const { const float* m = m_data; float d = m[0]*m[5]*m[10]*m[15]- m[0]*m[5]*m[11]*m[14]+m[0]*m[9]*m[14]*m[7]- m[0]*m[9]*m[6]*m[15]+m[0]*m[13]*m[6]*m[11]- m[0]*m[13]*m[10]*m[7]-m[4]*m[1]*m[10]*m[15]+m[4]*m[1]*m[11]*m[14]- m[4]*m[9]*m[14]*m[3]+m[4]*m[9]*m[2]*m[15]- m[4]*m[13]*m[2]*m[11]+m[4]*m[13]*m[10]*m[3]+m[8]*m[1]*m[6]*m[15]- m[8]*m[1]*m[14]*m[7]+m[8]*m[5]*m[14]*m[3]- m[8]*m[5]*m[2]*m[15]+m[8]*m[13]*m[2]*m[7]- m[8]*m[13]*m[6]*m[3]- m[12]*m[1]*m[6]*m[11]+m[12]*m[1]*m[10]*m[7]- m[12]*m[5]*m[10]*m[3]+m[12]*m[5]*m[2]*m[11]- m[12]*m[9]*m[2]*m[7]+m[12]*m[9]*m[6]*m[3]; return d; } // Returns the inverse of the matrix. template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::inverse() const { Matrix<4,4> dst; const float* m = m_data; const float d = 1.0f / det(); dst[0] = d * (m[5] * (m[10] * m[15] - m[14] * m[11]) + m[9] * (m[14] * m[7] - m[6] * m[15]) + m[13] * (m[6] * m[11] - m[10] * m[7])); dst[4] = d * (m[6] * (m[8] * m[15] - m[12] * m[11]) + m[10] * (m[12] * m[7] - m[4] * m[15]) + m[14] * (m[4] * m[11] - m[8] * m[7])); dst[8] = d * (m[7] * (m[8] * m[13] - m[12] * m[9]) + m[11] * (m[12] * m[5] - m[4] * m[13]) + m[15] * (m[4] * m[9] - m[8] * m[5])); dst[12] = d * (m[4] * (m[13] * m[10] - m[9] * m[14]) + m[8] * (m[5] * m[14] - m[13] * m[6]) + m[12] * (m[9] * m[6] - m[5] * m[10])); dst[1] = d * (m[9] * (m[2] * m[15] - m[14] * m[3]) + m[13] * (m[10] * m[3] - m[2] * m[11]) + m[1] * (m[14] * m[11] - m[10] * m[15])); dst[5] = d * (m[10] * (m[0] * m[15] - m[12] * m[3]) + m[14] * (m[8] * m[3] - m[0] * m[11]) + m[2] * (m[12] * m[11] - m[8] * m[15])); dst[9] = d * (m[11] * (m[0] * m[13] - m[12] * m[1]) + m[15] * (m[8] * m[1] - m[0] * m[9]) + m[3] * (m[12] * m[9] - m[8] * m[13])); dst[13] = d * (m[8] * (m[13] * m[2] - m[1] * m[14]) + m[12] * (m[1] * m[10] - m[9] * m[2]) + m[0] * (m[9] * m[14] - m[13] * m[10])); dst[2] = d * (m[13] * (m[2] * m[7] - m[6] * m[3]) + m[1] * (m[6] * m[15] - m[14] * m[7]) + m[5] * (m[14] * m[3] - m[2] * m[15])); dst[6] = d * (m[14] * (m[0] * m[7] - m[4] * m[3]) + m[2] * (m[4] * m[15] - m[12] * m[7]) + m[6] * (m[12] * m[3] - m[0] * m[15])); dst[10] = d * (m[15] * (m[0] * m[5] - m[4] * m[1]) + m[3] * (m[4] * m[13] - m[12] * m[5]) + m[7] * (m[12] * m[1] - m[0] * m[13])); dst[14] = d * (m[12] * (m[5] * m[2] - m[1] * m[6]) + m[0] * (m[13] * m[6] - m[5] * m[14]) + m[4] * (m[1] * m[14] - m[13] * m[2])); dst[3] = d * (m[1] * (m[10] * m[7] - m[6] * m[11]) + m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[6] * m[3] - m[2] * m[7])); dst[7] = d * (m[2] * (m[8] * m[7] - m[4] * m[11]) + m[6] * (m[0] * m[11] - m[8] * m[3]) + m[10] * (m[4] * m[3] - m[0] * m[7])); dst[11] = d * (m[3] * (m[8] * m[5] - m[4] * m[9]) + m[7] * (m[0] * m[9] - m[8] * m[1]) + m[11] * (m[4] * m[1] - m[0] * m[5])); dst[15] = d * (m[0] * (m[5] * m[10] - m[9] * m[6]) + m[4] * (m[9] * m[2] - m[1] * m[10]) + m[8] * (m[1] * m[6] - m[5] * m[2])); return dst; } // Returns a rotation matrix. // This is a static member. template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::rotate(const float radians, const float3& axis) { Matrix<4,4> Mat = Matrix<4,4>::identity(); float *m = Mat.getData(); // NOTE: Element 0,1 is wrong in Foley and Van Dam, Pg 227! float sintheta=sinf(radians); float costheta=cosf(radians); float ux=axis.x; float uy=axis.y; float uz=axis.z; m[0*4+0]=ux*ux+costheta*(1-ux*ux); m[0*4+1]=ux*uy*(1-costheta)-uz*sintheta; m[0*4+2]=uz*ux*(1-costheta)+uy*sintheta; m[0*4+3]=0; m[1*4+0]=ux*uy*(1-costheta)+uz*sintheta; m[1*4+1]=uy*uy+costheta*(1-uy*uy); m[1*4+2]=uy*uz*(1-costheta)-ux*sintheta; m[1*4+3]=0; m[2*4+0]=uz*ux*(1-costheta)-uy*sintheta; m[2*4+1]=uy*uz*(1-costheta)+ux*sintheta; m[2*4+2]=uz*uz+costheta*(1-uz*uz); m[2*4+3]=0; m[3*4+0]=0; m[3*4+1]=0; m[3*4+2]=0; m[3*4+3]=1; return Matrix<4,4>( m ); } // Returns a translation matrix. // This is a static member. template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::translate(const float3& vec) { Matrix<4,4> Mat = Matrix<4,4>::identity(); float *m = Mat.getData(); m[3] = vec.x; m[7] = vec.y; m[11]= vec.z; return Matrix<4,4>( m ); } // Returns a scale matrix. // This is a static member. template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::scale(const float3& vec) { Matrix<4,4> Mat = Matrix<4,4>::identity(); float *m = Mat.getData(); m[0] = vec.x; m[5] = vec.y; m[10]= vec.z; return Matrix<4,4>( m ); } // This is a static member. template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::fromBasis( const float3& u, const float3& v, const float3& w, const float3& c ) { float m[16]; m[ 0] = u.x; m[ 1] = v.x; m[ 2] = w.x; m[ 3] = c.x; m[ 4] = u.y; m[ 5] = v.y; m[ 6] = w.y; m[ 7] = c.y; m[ 8] = u.z; m[ 9] = v.z; m[10] = w.z; m[11] = c.z; m[12] = 0.0f; m[13] = 0.0f; m[14] = 0.0f; m[15] = 1.0f; return Matrix<4,4>( m ); } template<> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<3,4> Matrix<3,4>::affineIdentity() { Matrix<3,4> m; m.m_data[ 0] = 1.0f; m.m_data[ 1] = 0.0f; m.m_data[ 2] = 0.0f; m.m_data[ 3] = 0.0f; m.m_data[ 4] = 0.0f; m.m_data[ 5] = 1.0f; m.m_data[ 6] = 0.0f; m.m_data[ 7] = 0.0f; m.m_data[ 8] = 0.0f; m.m_data[ 9] = 0.0f; m.m_data[10] = 1.0f; m.m_data[11] = 0.0f; return m; } // Returns the identity matrix. // This is a static member. template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<N,N> Matrix<M,N>::identity() { float temp[N*N]; for(unsigned int i = 0; i < N*N; ++i) temp[i] = 0; for( unsigned int i = 0; i < N; ++i ) RT_MATRIX_ACCESS( temp,i,i ) = 1.0f; return Matrix<N,N>( temp ); } // Ordered comparison operator so that the matrix can be used in an STL container. template<unsigned int M, unsigned int N> SUTIL_INLINE SUTIL_HOSTDEVICE bool Matrix<M,N>::operator<( const Matrix<M, N>& rhs ) const { for( unsigned int i = 0; i < N*M; ++i ) { if( m_data[i] < rhs[i] ) return true; else if( m_data[i] > rhs[i] ) return false; } return false; } typedef Matrix<2, 2> Matrix2x2; typedef Matrix<2, 3> Matrix2x3; typedef Matrix<2, 4> Matrix2x4; typedef Matrix<3, 2> Matrix3x2; typedef Matrix<3, 3> Matrix3x3; typedef Matrix<3, 4> Matrix3x4; typedef Matrix<4, 2> Matrix4x2; typedef Matrix<4, 3> Matrix4x3; typedef Matrix<4, 4> Matrix4x4; SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<3,3> make_matrix3x3(const Matrix<4,4> &matrix) { Matrix<3,3> Mat; float *m = Mat.getData(); const float *m4x4 = matrix.getData(); m[0*3+0]=m4x4[0*4+0]; m[0*3+1]=m4x4[0*4+1]; m[0*3+2]=m4x4[0*4+2]; m[1*3+0]=m4x4[1*4+0]; m[1*3+1]=m4x4[1*4+1]; m[1*3+2]=m4x4[1*4+2]; m[2*3+0]=m4x4[2*4+0]; m[2*3+1]=m4x4[2*4+1]; m[2*3+2]=m4x4[2*4+2]; return Mat; } } // end namespace sutil #undef RT_MATRIX_ACCESS #undef RT_MAT_DECL
26,645
C
31.855734
158
0.576994
arhix52/Strelka/sutil/Preprocessor.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #if defined(__CUDACC__) || defined(__CUDABE__) # define SUTIL_HOSTDEVICE __host__ __device__ # define SUTIL_INLINE __forceinline__ # define CONST_STATIC_INIT( ... ) #else # define SUTIL_HOSTDEVICE # define SUTIL_INLINE inline # define CONST_STATIC_INIT( ... ) = __VA_ARGS__ #endif
1,882
C
41.795454
74
0.741764
arhix52/Strelka/sutil/sutilapi.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #ifndef SUTILAPI # if sutil_7_sdk_EXPORTS /* Set by CMAKE */ # if defined( _WIN32 ) || defined( _WIN64 ) # define SUTILAPI __declspec(dllexport) # define SUTILCLASSAPI # elif defined( linux ) || defined( __linux__ ) || defined ( __CYGWIN__ ) # define SUTILAPI __attribute__ ((visibility ("default"))) # define SUTILCLASSAPI SUTILAPI # elif defined( __APPLE__ ) && defined( __MACH__ ) # define SUTILAPI __attribute__ ((visibility ("default"))) # define SUTILCLASSAPI SUTILAPI # else # error "CODE FOR THIS OS HAS NOT YET BEEN DEFINED" # endif # else /* sutil_7_sdk_EXPORTS */ # if defined( _WIN32 ) || defined( _WIN64 ) # define SUTILAPI __declspec(dllimport) # define SUTILCLASSAPI # elif defined( linux ) || defined( __linux__ ) || defined ( __CYGWIN__ ) # define SUTILAPI __attribute__ ((visibility ("default"))) # define SUTILCLASSAPI SUTILAPI # elif defined( __APPLE__ ) && defined( __MACH__ ) # define SUTILAPI __attribute__ ((visibility ("default"))) # define SUTILCLASSAPI SUTILAPI # elif defined( __CUDACC_RTC__ ) # define SUTILAPI # define SUTILCLASSAPI # else # error "CODE FOR THIS OS HAS NOT YET BEEN DEFINED" # endif # endif /* sutil_7_sdk_EXPORTS */ #endif
2,869
C
42.484848
76
0.696758
arhix52/Strelka/sutil/vec_math.h
// // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <sutil/Preprocessor.h> #include <vector_functions.h> #include <vector_types.h> #if !defined(__CUDACC_RTC__) #include <cmath> #include <cstdlib> #endif /* scalar functions used in vector functions */ #ifndef M_PIf #define M_PIf 3.14159265358979323846f #endif #ifndef M_PI_2f #define M_PI_2f 1.57079632679489661923f #endif #ifndef M_1_PIf #define M_1_PIf 0.318309886183790671538f #endif #if !defined(__CUDACC__) SUTIL_INLINE SUTIL_HOSTDEVICE int max(int a, int b) { return a > b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE int min(int a, int b) { return a < b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE long long max(long long a, long long b) { return a > b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE long long min(long long a, long long b) { return a < b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int max(unsigned int a, unsigned int b) { return a > b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int min(unsigned int a, unsigned int b) { return a < b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long max(unsigned long long a, unsigned long long b) { return a > b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long min(unsigned long long a, unsigned long long b) { return a < b ? a : b; } SUTIL_INLINE SUTIL_HOSTDEVICE float min(const float a, const float b) { return a < b ? a : b; } /** lerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float lerp(const float a, const float b, const float t) { return a + t*(b-a); } /** bilerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float bilerp(const float x00, const float x10, const float x01, const float x11, const float u, const float v) { return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v ); } template <typename IntegerType> SUTIL_INLINE SUTIL_HOSTDEVICE IntegerType roundUp(IntegerType x, IntegerType y) { return ( ( x + y - 1 ) / y ) * y; } #endif /** clamp */ SUTIL_INLINE SUTIL_HOSTDEVICE float clamp( const float f, const float a, const float b ) { return fmaxf( a, fminf( f, b ) ); } /* float2 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float s) { return make_float2(s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const int2& a) { return make_float2(float(a.x), float(a.y)); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const uint2& a) { return make_float2(float(a.x), float(a.y)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a) { return make_float2(-a.x, -a.y); } /** min * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 fminf(const float2& a, const float2& b) { return make_float2(fminf(a.x,b.x), fminf(a.y,b.y)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float2& a) { return fminf(a.x, a.y); } /** @} */ /** max * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 fmaxf(const float2& a, const float2& b) { return make_float2(fmaxf(a.x,b.x), fmaxf(a.y,b.y)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float2& a) { return fmaxf(a.x, a.y); } /** @} */ /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float2& a, const float2& b) { return make_float2(a.x + b.x, a.y + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float2& a, const float b) { return make_float2(a.x + b, a.y + b); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float a, const float2& b) { return make_float2(a + b.x, a + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float2& a, const float2& b) { a.x += b.x; a.y += b.y; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a, const float2& b) { return make_float2(a.x - b.x, a.y - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a, const float b) { return make_float2(a.x - b, a.y - b); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float a, const float2& b) { return make_float2(a - b.x, a - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float2& a, const float2& b) { a.x -= b.x; a.y -= b.y; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float2& a, const float2& b) { return make_float2(a.x * b.x, a.y * b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float2& a, const float s) { return make_float2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float s, const float2& a) { return make_float2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float2& a, const float2& s) { a.x *= s.x; a.y *= s.y; } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float2& a, const float s) { a.x *= s; a.y *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float2& a, const float2& b) { return make_float2(a.x / b.x, a.y / b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float2& a, const float s) { float inv = 1.0f / s; return a * inv; } SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float s, const float2& a) { return make_float2( s/a.x, s/a.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float2& a, const float s) { float inv = 1.0f / s; a *= inv; } /** @} */ /** lerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 lerp(const float2& a, const float2& b, const float t) { return a + t*(b-a); } /** bilerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 bilerp(const float2& x00, const float2& x10, const float2& x01, const float2& x11, const float u, const float v) { return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v ); } /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 clamp(const float2& v, const float a, const float b) { return make_float2(clamp(v.x, a, b), clamp(v.y, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 clamp(const float2& v, const float2& a, const float2& b) { return make_float2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y)); } /** @} */ /** dot product */ SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float2& a, const float2& b) { return a.x * b.x + a.y * b.y; } /** length */ SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float2& v) { return sqrtf(dot(v, v)); } /** normalize */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 normalize(const float2& v) { float invLen = 1.0f / sqrtf(dot(v, v)); return v * invLen; } /** floor */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 floor(const float2& v) { return make_float2(::floorf(v.x), ::floorf(v.y)); } /** reflect */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 reflect(const float2& i, const float2& n) { return i - 2.0f * n * dot(n,i); } /** Faceforward * Returns N if dot(i, nref) > 0; else -N; * Typical usage is N = faceforward(N, -ray.dir, N); * Note that this is opposite of what faceforward does in Cg and GLSL */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 faceforward(const float2& n, const float2& i, const float2& nref) { return n * copysignf( 1.0f, dot(i, nref) ); } /** exp */ SUTIL_INLINE SUTIL_HOSTDEVICE float2 expf(const float2& v) { return make_float2(::expf(v.x), ::expf(v.y)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float2& v, int i) { return ((float*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float2& v, int i, float x) { ((float*)(&v))[i] = x; } /* float3 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float s) { return make_float3(s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float2& a) { return make_float3(a.x, a.y, 0.0f); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const int3& a) { return make_float3(float(a.x), float(a.y), float(a.z)); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const uint3& a) { return make_float3(float(a.x), float(a.y), float(a.z)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a) { return make_float3(-a.x, -a.y, -a.z); } /** min * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 fminf(const float3& a, const float3& b) { return make_float3(fminf(a.x,b.x), fminf(a.y,b.y), fminf(a.z,b.z)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float3& a) { return fminf(fminf(a.x, a.y), a.z); } /** @} */ /** max * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 fmaxf(const float3& a, const float3& b) { return make_float3(fmaxf(a.x,b.x), fmaxf(a.y,b.y), fmaxf(a.z,b.z)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float3& a) { return fmaxf(fmaxf(a.x, a.y), a.z); } /** @} */ /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float3& a, const float3& b) { return make_float3(a.x + b.x, a.y + b.y, a.z + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float3& a, const float b) { return make_float3(a.x + b, a.y + b, a.z + b); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float a, const float3& b) { return make_float3(a + b.x, a + b.y, a + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float3& a, const float3& b) { a.x += b.x; a.y += b.y; a.z += b.z; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a, const float3& b) { return make_float3(a.x - b.x, a.y - b.y, a.z - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a, const float b) { return make_float3(a.x - b, a.y - b, a.z - b); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float a, const float3& b) { return make_float3(a - b.x, a - b.y, a - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float3& a, const float3& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float3& a, const float3& b) { return make_float3(a.x * b.x, a.y * b.y, a.z * b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float3& a, const float s) { return make_float3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float s, const float3& a) { return make_float3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float3& a, const float3& s) { a.x *= s.x; a.y *= s.y; a.z *= s.z; } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float3& a, const float s) { a.x *= s; a.y *= s; a.z *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float3& a, const float3& b) { return make_float3(a.x / b.x, a.y / b.y, a.z / b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float3& a, const float s) { float inv = 1.0f / s; return a * inv; } SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float s, const float3& a) { return make_float3( s/a.x, s/a.y, s/a.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float3& a, const float s) { float inv = 1.0f / s; a *= inv; } /** @} */ /** lerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 lerp(const float3& a, const float3& b, const float t) { return a + t*(b-a); } /** bilerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 bilerp(const float3& x00, const float3& x10, const float3& x01, const float3& x11, const float u, const float v) { return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v ); } /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 clamp(const float3& v, const float a, const float b) { return make_float3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 clamp(const float3& v, const float3& a, const float3& b) { return make_float3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z)); } /** @} */ /** dot product */ SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float3& a, const float3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } /** cross product */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 cross(const float3& a, const float3& b) { return make_float3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); } /** length */ SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float3& v) { return sqrtf(dot(v, v)); } /** normalize */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 normalize(const float3& v) { float invLen = 1.0f / sqrtf(dot(v, v)); return v * invLen; } /** floor */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 floor(const float3& v) { return make_float3(::floorf(v.x), ::floorf(v.y), ::floorf(v.z)); } /** reflect */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 reflect(const float3& i, const float3& n) { return i - 2.0f * n * dot(n,i); } /** Faceforward * Returns N if dot(i, nref) > 0; else -N; * Typical usage is N = faceforward(N, -ray.dir, N); * Note that this is opposite of what faceforward does in Cg and GLSL */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 faceforward(const float3& n, const float3& i, const float3& nref) { return n * copysignf( 1.0f, dot(i, nref) ); } /** exp */ SUTIL_INLINE SUTIL_HOSTDEVICE float3 expf(const float3& v) { return make_float3(::expf(v.x), ::expf(v.y), ::expf(v.z)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float3& v, int i) { return ((float*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float3& v, int i, float x) { ((float*)(&v))[i] = x; } /* float4 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float s) { return make_float4(s, s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& a) { return make_float4(a.x, a.y, a.z, 0.0f); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const int4& a) { return make_float4(float(a.x), float(a.y), float(a.z), float(a.w)); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const uint4& a) { return make_float4(float(a.x), float(a.y), float(a.z), float(a.w)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a) { return make_float4(-a.x, -a.y, -a.z, -a.w); } /** min * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 fminf(const float4& a, const float4& b) { return make_float4(fminf(a.x,b.x), fminf(a.y,b.y), fminf(a.z,b.z), fminf(a.w,b.w)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float4& a) { return fminf(fminf(a.x, a.y), fminf(a.z, a.w)); } /** @} */ /** max * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 fmaxf(const float4& a, const float4& b) { return make_float4(fmaxf(a.x,b.x), fmaxf(a.y,b.y), fmaxf(a.z,b.z), fmaxf(a.w,b.w)); } SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float4& a) { return fmaxf(fmaxf(a.x, a.y), fmaxf(a.z, a.w)); } /** @} */ /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float4& a, const float4& b) { return make_float4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float4& a, const float b) { return make_float4(a.x + b, a.y + b, a.z + b, a.w + b); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float a, const float4& b) { return make_float4(a + b.x, a + b.y, a + b.z, a + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float4& a, const float4& b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a, const float4& b) { return make_float4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a, const float b) { return make_float4(a.x - b, a.y - b, a.z - b, a.w - b); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float a, const float4& b) { return make_float4(a - b.x, a - b.y, a - b.z, a - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float4& a, const float4& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float4& a, const float4& s) { return make_float4(a.x * s.x, a.y * s.y, a.z * s.z, a.w * s.w); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float4& a, const float s) { return make_float4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float s, const float4& a) { return make_float4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float4& a, const float4& s) { a.x *= s.x; a.y *= s.y; a.z *= s.z; a.w *= s.w; } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float4& a, const float s) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float4& a, const float4& b) { return make_float4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float4& a, const float s) { float inv = 1.0f / s; return a * inv; } SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float s, const float4& a) { return make_float4( s/a.x, s/a.y, s/a.z, s/a.w ); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float4& a, const float s) { float inv = 1.0f / s; a *= inv; } /** @} */ /** lerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 lerp(const float4& a, const float4& b, const float t) { return a + t*(b-a); } /** bilerp */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 bilerp(const float4& x00, const float4& x10, const float4& x01, const float4& x11, const float u, const float v) { return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v ); } /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 clamp(const float4& v, const float a, const float b) { return make_float4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 clamp(const float4& v, const float4& a, const float4& b) { return make_float4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w)); } /** @} */ /** dot product */ SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float4& a, const float4& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } /** length */ SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float4& r) { return sqrtf(dot(r, r)); } /** normalize */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 normalize(const float4& v) { float invLen = 1.0f / sqrtf(dot(v, v)); return v * invLen; } /** floor */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 floor(const float4& v) { return make_float4(::floorf(v.x), ::floorf(v.y), ::floorf(v.z), ::floorf(v.w)); } /** reflect */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 reflect(const float4& i, const float4& n) { return i - 2.0f * n * dot(n,i); } /** * Faceforward * Returns N if dot(i, nref) > 0; else -N; * Typical usage is N = faceforward(N, -ray.dir, N); * Note that this is opposite of what faceforward does in Cg and GLSL */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 faceforward(const float4& n, const float4& i, const float4& nref) { return n * copysignf( 1.0f, dot(i, nref) ); } /** exp */ SUTIL_INLINE SUTIL_HOSTDEVICE float4 expf(const float4& v) { return make_float4(::expf(v.x), ::expf(v.y), ::expf(v.z), ::expf(v.w)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float4& v, int i) { return ((float*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float4& v, int i, float x) { ((float*)(&v))[i] = x; } /* int functions */ /******************************************************************************/ /** clamp */ SUTIL_INLINE SUTIL_HOSTDEVICE int clamp(const int f, const int a, const int b) { return max(a, min(f, b)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int1& v, int i) { return ((int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int1& v, int i, int x) { ((int*)(&v))[i] = x; } /* int2 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int s) { return make_int2(s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const float2& a) { return make_int2(int(a.x), int(a.y)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a) { return make_int2(-a.x, -a.y); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 min(const int2& a, const int2& b) { return make_int2(min(a.x,b.x), min(a.y,b.y)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 max(const int2& a, const int2& b) { return make_int2(max(a.x,b.x), max(a.y,b.y)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator+(const int2& a, const int2& b) { return make_int2(a.x + b.x, a.y + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int2& a, const int2& b) { a.x += b.x; a.y += b.y; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a, const int2& b) { return make_int2(a.x - b.x, a.y - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a, const int b) { return make_int2(a.x - b, a.y - b); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int2& a, const int2& b) { a.x -= b.x; a.y -= b.y; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int2& a, const int2& b) { return make_int2(a.x * b.x, a.y * b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int2& a, const int s) { return make_int2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int s, const int2& a) { return make_int2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int2& a, const int s) { a.x *= s; a.y *= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 clamp(const int2& v, const int a, const int b) { return make_int2(clamp(v.x, a, b), clamp(v.y, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 clamp(const int2& v, const int2& a, const int2& b) { return make_int2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int2& a, const int2& b) { return a.x == b.x && a.y == b.y; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int2& a, const int2& b) { return a.x != b.x || a.y != b.y; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int2& v, int i) { return ((int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int2& v, int i, int x) { ((int*)(&v))[i] = x; } /* int3 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int s) { return make_int3(s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const float3& a) { return make_int3(int(a.x), int(a.y), int(a.z)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator-(const int3& a) { return make_int3(-a.x, -a.y, -a.z); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 min(const int3& a, const int3& b) { return make_int3(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 max(const int3& a, const int3& b) { return make_int3(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator+(const int3& a, const int3& b) { return make_int3(a.x + b.x, a.y + b.y, a.z + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int3& a, const int3& b) { a.x += b.x; a.y += b.y; a.z += b.z; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator-(const int3& a, const int3& b) { return make_int3(a.x - b.x, a.y - b.y, a.z - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int3& a, const int3& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int3& a, const int3& b) { return make_int3(a.x * b.x, a.y * b.y, a.z * b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int3& a, const int s) { return make_int3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int s, const int3& a) { return make_int3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int3& a, const int s) { a.x *= s; a.y *= s; a.z *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int3& a, const int3& b) { return make_int3(a.x / b.x, a.y / b.y, a.z / b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int3& a, const int s) { return make_int3(a.x / s, a.y / s, a.z / s); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int s, const int3& a) { return make_int3(s /a.x, s / a.y, s / a.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(int3& a, const int s) { a.x /= s; a.y /= s; a.z /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 clamp(const int3& v, const int a, const int b) { return make_int3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 clamp(const int3& v, const int3& a, const int3& b) { return make_int3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int3& a, const int3& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int3& a, const int3& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int3& v, int i) { return ((int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int3& v, int i, int x) { ((int*)(&v))[i] = x; } /* int4 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int s) { return make_int4(s, s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const float4& a) { return make_int4((int)a.x, (int)a.y, (int)a.z, (int)a.w); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator-(const int4& a) { return make_int4(-a.x, -a.y, -a.z, -a.w); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 min(const int4& a, const int4& b) { return make_int4(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z), min(a.w,b.w)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 max(const int4& a, const int4& b) { return make_int4(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z), max(a.w,b.w)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator+(const int4& a, const int4& b) { return make_int4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int4& a, const int4& b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator-(const int4& a, const int4& b) { return make_int4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int4& a, const int4& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int4& a, const int4& b) { return make_int4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int4& a, const int s) { return make_int4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int s, const int4& a) { return make_int4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int4& a, const int s) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int4& a, const int4& b) { return make_int4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int4& a, const int s) { return make_int4(a.x / s, a.y / s, a.z / s, a.w / s); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int s, const int4& a) { return make_int4(s / a.x, s / a.y, s / a.z, s / a.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(int4& a, const int s) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int4 clamp(const int4& v, const int a, const int b) { return make_int4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 clamp(const int4& v, const int4& a, const int4& b) { return make_int4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int4& a, const int4& b) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int4& a, const int4& b) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int4& v, int i) { return ((int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int4& v, int i, int x) { ((int*)(&v))[i] = x; } /* uint functions */ /******************************************************************************/ /** clamp */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int clamp(const unsigned int f, const unsigned int a, const unsigned int b) { return max(a, min(f, b)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint1& v, unsigned int i) { return ((unsigned int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint1& v, int i, unsigned int x) { ((unsigned int*)(&v))[i] = x; } /* uint2 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const unsigned int s) { return make_uint2(s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const float2& a) { return make_uint2((unsigned int)a.x, (unsigned int)a.y); } /** @} */ /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 min(const uint2& a, const uint2& b) { return make_uint2(min(a.x,b.x), min(a.y,b.y)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 max(const uint2& a, const uint2& b) { return make_uint2(max(a.x,b.x), max(a.y,b.y)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator+(const uint2& a, const uint2& b) { return make_uint2(a.x + b.x, a.y + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint2& a, const uint2& b) { a.x += b.x; a.y += b.y; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator-(const uint2& a, const uint2& b) { return make_uint2(a.x - b.x, a.y - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator-(const uint2& a, const unsigned int b) { return make_uint2(a.x - b, a.y - b); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint2& a, const uint2& b) { a.x -= b.x; a.y -= b.y; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const uint2& a, const uint2& b) { return make_uint2(a.x * b.x, a.y * b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const uint2& a, const unsigned int s) { return make_uint2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const unsigned int s, const uint2& a) { return make_uint2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint2& a, const unsigned int s) { a.x *= s; a.y *= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint2 clamp(const uint2& v, const unsigned int a, const unsigned int b) { return make_uint2(clamp(v.x, a, b), clamp(v.y, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 clamp(const uint2& v, const uint2& a, const uint2& b) { return make_uint2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint2& a, const uint2& b) { return a.x == b.x && a.y == b.y; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint2& a, const uint2& b) { return a.x != b.x || a.y != b.y; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint2& v, unsigned int i) { return ((unsigned int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint2& v, int i, unsigned int x) { ((unsigned int*)(&v))[i] = x; } /* uint3 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const unsigned int s) { return make_uint3(s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const float3& a) { return make_uint3((unsigned int)a.x, (unsigned int)a.y, (unsigned int)a.z); } /** @} */ /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 min(const uint3& a, const uint3& b) { return make_uint3(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 max(const uint3& a, const uint3& b) { return make_uint3(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator+(const uint3& a, const uint3& b) { return make_uint3(a.x + b.x, a.y + b.y, a.z + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint3& a, const uint3& b) { a.x += b.x; a.y += b.y; a.z += b.z; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator-(const uint3& a, const uint3& b) { return make_uint3(a.x - b.x, a.y - b.y, a.z - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint3& a, const uint3& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const uint3& a, const uint3& b) { return make_uint3(a.x * b.x, a.y * b.y, a.z * b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const uint3& a, const unsigned int s) { return make_uint3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const unsigned int s, const uint3& a) { return make_uint3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint3& a, const unsigned int s) { a.x *= s; a.y *= s; a.z *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const uint3& a, const uint3& b) { return make_uint3(a.x / b.x, a.y / b.y, a.z / b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const uint3& a, const unsigned int s) { return make_uint3(a.x / s, a.y / s, a.z / s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const unsigned int s, const uint3& a) { return make_uint3(s / a.x, s / a.y, s / a.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(uint3& a, const unsigned int s) { a.x /= s; a.y /= s; a.z /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint3 clamp(const uint3& v, const unsigned int a, const unsigned int b) { return make_uint3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 clamp(const uint3& v, const uint3& a, const uint3& b) { return make_uint3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint3& a, const uint3& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint3& a, const uint3& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint3& v, unsigned int i) { return ((unsigned int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint3& v, int i, unsigned int x) { ((unsigned int*)(&v))[i] = x; } /* uint4 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int s) { return make_uint4(s, s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const float4& a) { return make_uint4((unsigned int)a.x, (unsigned int)a.y, (unsigned int)a.z, (unsigned int)a.w); } /** @} */ /** min * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 min(const uint4& a, const uint4& b) { return make_uint4(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z), min(a.w,b.w)); } /** @} */ /** max * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 max(const uint4& a, const uint4& b) { return make_uint4(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z), max(a.w,b.w)); } /** @} */ /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator+(const uint4& a, const uint4& b) { return make_uint4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint4& a, const uint4& b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator-(const uint4& a, const uint4& b) { return make_uint4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint4& a, const uint4& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const uint4& a, const uint4& b) { return make_uint4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const uint4& a, const unsigned int s) { return make_uint4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const unsigned int s, const uint4& a) { return make_uint4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint4& a, const unsigned int s) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const uint4& a, const uint4& b) { return make_uint4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const uint4& a, const unsigned int s) { return make_uint4(a.x / s, a.y / s, a.z / s, a.w / s); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const unsigned int s, const uint4& a) { return make_uint4(s / a.x, s / a.y, s / a.z, s / a.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(uint4& a, const unsigned int s) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE uint4 clamp(const uint4& v, const unsigned int a, const unsigned int b) { return make_uint4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 clamp(const uint4& v, const uint4& a, const uint4& b) { return make_uint4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint4& a, const uint4& b) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint4& a, const uint4& b) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint4& v, unsigned int i) { return ((unsigned int*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint4& v, int i, unsigned int x) { ((unsigned int*)(&v))[i] = x; } /* long long functions */ /******************************************************************************/ /** clamp */ SUTIL_INLINE SUTIL_HOSTDEVICE long long clamp(const long long f, const long long a, const long long b) { return max(a, min(f, b)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong1& v, int i) { return ((long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong1& v, int i, long long x) { ((long long*)(&v))[i] = x; } /* longlong2 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const long long s) { return make_longlong2(s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const float2& a) { return make_longlong2(int(a.x), int(a.y)); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a) { return make_longlong2(-a.x, -a.y); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 min(const longlong2& a, const longlong2& b) { return make_longlong2(min(a.x, b.x), min(a.y, b.y)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 max(const longlong2& a, const longlong2& b) { return make_longlong2(max(a.x, b.x), max(a.y, b.y)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator+(const longlong2& a, const longlong2& b) { return make_longlong2(a.x + b.x, a.y + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong2& a, const longlong2& b) { a.x += b.x; a.y += b.y; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a, const longlong2& b) { return make_longlong2(a.x - b.x, a.y - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a, const long long b) { return make_longlong2(a.x - b, a.y - b); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong2& a, const longlong2& b) { a.x -= b.x; a.y -= b.y; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const longlong2& a, const longlong2& b) { return make_longlong2(a.x * b.x, a.y * b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const longlong2& a, const long long s) { return make_longlong2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const long long s, const longlong2& a) { return make_longlong2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong2& a, const long long s) { a.x *= s; a.y *= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 clamp(const longlong2& v, const long long a, const long long b) { return make_longlong2(clamp(v.x, a, b), clamp(v.y, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 clamp(const longlong2& v, const longlong2& a, const longlong2& b) { return make_longlong2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong2& a, const longlong2& b) { return a.x == b.x && a.y == b.y; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong2& a, const longlong2& b) { return a.x != b.x || a.y != b.y; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong2& v, int i) { return ((long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong2& v, int i, long long x) { ((long long*)(&v))[i] = x; } /* longlong3 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const long long s) { return make_longlong3(s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const float3& a) { return make_longlong3( (long long)a.x, (long long)a.y, (long long)a.z); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator-(const longlong3& a) { return make_longlong3(-a.x, -a.y, -a.z); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 min(const longlong3& a, const longlong3& b) { return make_longlong3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 max(const longlong3& a, const longlong3& b) { return make_longlong3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator+(const longlong3& a, const longlong3& b) { return make_longlong3(a.x + b.x, a.y + b.y, a.z + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong3& a, const longlong3& b) { a.x += b.x; a.y += b.y; a.z += b.z; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator-(const longlong3& a, const longlong3& b) { return make_longlong3(a.x - b.x, a.y - b.y, a.z - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong3& a, const longlong3& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const longlong3& a, const longlong3& b) { return make_longlong3(a.x * b.x, a.y * b.y, a.z * b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const longlong3& a, const long long s) { return make_longlong3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const long long s, const longlong3& a) { return make_longlong3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong3& a, const long long s) { a.x *= s; a.y *= s; a.z *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const longlong3& a, const longlong3& b) { return make_longlong3(a.x / b.x, a.y / b.y, a.z / b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const longlong3& a, const long long s) { return make_longlong3(a.x / s, a.y / s, a.z / s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const long long s, const longlong3& a) { return make_longlong3(s /a.x, s / a.y, s / a.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(longlong3& a, const long long s) { a.x /= s; a.y /= s; a.z /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 clamp(const longlong3& v, const long long a, const long long b) { return make_longlong3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 clamp(const longlong3& v, const longlong3& a, const longlong3& b) { return make_longlong3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong3& a, const longlong3& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong3& a, const longlong3& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong3& v, int i) { return ((long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong3& v, int i, int x) { ((long long*)(&v))[i] = x; } /* longlong4 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long s) { return make_longlong4(s, s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const float4& a) { return make_longlong4((long long)a.x, (long long)a.y, (long long)a.z, (long long)a.w); } /** @} */ /** negate */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator-(const longlong4& a) { return make_longlong4(-a.x, -a.y, -a.z, -a.w); } /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 min(const longlong4& a, const longlong4& b) { return make_longlong4(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z), min(a.w, b.w)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 max(const longlong4& a, const longlong4& b) { return make_longlong4(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z), max(a.w, b.w)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator+(const longlong4& a, const longlong4& b) { return make_longlong4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong4& a, const longlong4& b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator-(const longlong4& a, const longlong4& b) { return make_longlong4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong4& a, const longlong4& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const longlong4& a, const longlong4& b) { return make_longlong4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const longlong4& a, const long long s) { return make_longlong4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const long long s, const longlong4& a) { return make_longlong4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong4& a, const long long s) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const longlong4& a, const longlong4& b) { return make_longlong4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const longlong4& a, const long long s) { return make_longlong4(a.x / s, a.y / s, a.z / s, a.w / s); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const long long s, const longlong4& a) { return make_longlong4(s / a.x, s / a.y, s / a.z, s / a.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(longlong4& a, const long long s) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 clamp(const longlong4& v, const long long a, const long long b) { return make_longlong4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 clamp(const longlong4& v, const longlong4& a, const longlong4& b) { return make_longlong4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong4& a, const longlong4& b) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong4& a, const longlong4& b) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong4& v, int i) { return ((long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong4& v, int i, long long x) { ((long long*)(&v))[i] = x; } /* ulonglong functions */ /******************************************************************************/ /** clamp */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long clamp(const unsigned long long f, const unsigned long long a, const unsigned long long b) { return max(a, min(f, b)); } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong1& v, unsigned int i) { return ((unsigned long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong1& v, int i, unsigned long long x) { ((unsigned long long*)(&v))[i] = x; } /* ulonglong2 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const unsigned long long s) { return make_ulonglong2(s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const float2& a) { return make_ulonglong2((unsigned long long)a.x, (unsigned long long)a.y); } /** @} */ /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 min(const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(min(a.x, b.x), min(a.y, b.y)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 max(const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(max(a.x, b.x), max(a.y, b.y)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator+(const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(a.x + b.x, a.y + b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong2& a, const ulonglong2& b) { a.x += b.x; a.y += b.y; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator-(const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(a.x - b.x, a.y - b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator-(const ulonglong2& a, const unsigned long long b) { return make_ulonglong2(a.x - b, a.y - b); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong2& a, const ulonglong2& b) { a.x -= b.x; a.y -= b.y; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(a.x * b.x, a.y * b.y); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const ulonglong2& a, const unsigned long long s) { return make_ulonglong2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const unsigned long long s, const ulonglong2& a) { return make_ulonglong2(a.x * s, a.y * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong2& a, const unsigned long long s) { a.x *= s; a.y *= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 clamp(const ulonglong2& v, const unsigned long long a, const unsigned long long b) { return make_ulonglong2(clamp(v.x, a, b), clamp(v.y, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 clamp(const ulonglong2& v, const ulonglong2& a, const ulonglong2& b) { return make_ulonglong2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong2& a, const ulonglong2& b) { return a.x == b.x && a.y == b.y; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong2& a, const ulonglong2& b) { return a.x != b.x || a.y != b.y; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong2& v, unsigned int i) { return ((unsigned long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong2& v, int i, unsigned long long x) { ((unsigned long long*)(&v))[i] = x; } /* ulonglong3 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const unsigned long long s) { return make_ulonglong3(s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const float3& a) { return make_ulonglong3((unsigned long long)a.x, (unsigned long long)a.y, (unsigned long long)a.z); } /** @} */ /** min */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 min(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); } /** max */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 max(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); } /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator+(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(a.x + b.x, a.y + b.y, a.z + b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong3& a, const ulonglong3& b) { a.x += b.x; a.y += b.y; a.z += b.z; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator-(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(a.x - b.x, a.y - b.y, a.z - b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong3& a, const ulonglong3& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(a.x * b.x, a.y * b.y, a.z * b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const ulonglong3& a, const unsigned long long s) { return make_ulonglong3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const unsigned long long s, const ulonglong3& a) { return make_ulonglong3(a.x * s, a.y * s, a.z * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong3& a, const unsigned long long s) { a.x *= s; a.y *= s; a.z *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(a.x / b.x, a.y / b.y, a.z / b.z); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const ulonglong3& a, const unsigned long long s) { return make_ulonglong3(a.x / s, a.y / s, a.z / s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const unsigned long long s, const ulonglong3& a) { return make_ulonglong3(s / a.x, s / a.y, s / a.z); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(ulonglong3& a, const unsigned long long s) { a.x /= s; a.y /= s; a.z /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 clamp(const ulonglong3& v, const unsigned long long a, const unsigned long long b) { return make_ulonglong3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 clamp(const ulonglong3& v, const ulonglong3& a, const ulonglong3& b) { return make_ulonglong3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong3& a, const ulonglong3& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong3& a, const ulonglong3& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong3& v, unsigned int i) { return ((unsigned long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong3& v, int i, unsigned long long x) { ((unsigned long long*)(&v))[i] = x; } /* ulonglong4 functions */ /******************************************************************************/ /** additional constructors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long s) { return make_ulonglong4(s, s, s, s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const float4& a) { return make_ulonglong4((unsigned long long)a.x, (unsigned long long)a.y, (unsigned long long)a.z, (unsigned long long)a.w); } /** @} */ /** min * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 min(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z), min(a.w, b.w)); } /** @} */ /** max * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 max(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z), max(a.w, b.w)); } /** @} */ /** add * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator+(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong4& a, const ulonglong4& b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } /** @} */ /** subtract * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator-(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong4& a, const ulonglong4& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } /** @} */ /** multiply * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const ulonglong4& a, const unsigned long long s) { return make_ulonglong4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const unsigned long long s, const ulonglong4& a) { return make_ulonglong4(a.x * s, a.y * s, a.z * s, a.w * s); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong4& a, const unsigned long long s) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; } /** @} */ /** divide * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const ulonglong4& a, const unsigned long long s) { return make_ulonglong4(a.x / s, a.y / s, a.z / s, a.w / s); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const unsigned long long s, const ulonglong4& a) { return make_ulonglong4(s / a.x, s / a.y, s / a.z, s / a.w); } SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(ulonglong4& a, const unsigned long long s) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; } /** @} */ /** clamp * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 clamp(const ulonglong4& v, const unsigned long long a, const unsigned long long b) { return make_ulonglong4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b)); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 clamp(const ulonglong4& v, const ulonglong4& a, const ulonglong4& b) { return make_ulonglong4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w)); } /** @} */ /** equality * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong4& a, const ulonglong4& b) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong4& a, const ulonglong4& b) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w; } /** @} */ /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong4& v, unsigned int i) { return ((unsigned long long*)(&v))[i]; } /** If used on the device, this could place the the 'v' in local memory */ SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong4& v, int i, unsigned long long x) { ((unsigned long long*)(&v))[i] = x; } /******************************************************************************/ /** Narrowing functions * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int3& v0) { return make_int2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int4& v0) { return make_int2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int4& v0) { return make_int3( v0.x, v0.y, v0.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const uint3& v0) { return make_uint2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const uint4& v0) { return make_uint2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const uint4& v0) { return make_uint3( v0.x, v0.y, v0.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const longlong3& v0) { return make_longlong2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const longlong4& v0) { return make_longlong2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const longlong4& v0) { return make_longlong3( v0.x, v0.y, v0.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const ulonglong3& v0) { return make_ulonglong2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const ulonglong4& v0) { return make_ulonglong2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const ulonglong4& v0) { return make_ulonglong3( v0.x, v0.y, v0.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float3& v0) { return make_float2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float4& v0) { return make_float2( v0.x, v0.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float4& v0) { return make_float3( v0.x, v0.y, v0.z ); } /** @} */ /** Assemble functions from smaller vectors * @{ */ SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int v0, const int2& v1) { return make_int3( v0, v1.x, v1.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int2& v0, const int v1) { return make_int3( v0.x, v0.y, v1 ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int v1, const int2& v2) { return make_int4( v0, v1, v2.x, v2.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int2& v1, const int v2) { return make_int4( v0, v1.x, v1.y, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int2& v0, const int v1, const int v2) { return make_int4( v0.x, v0.y, v1, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int3& v1) { return make_int4( v0, v1.x, v1.y, v1.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int3& v0, const int v1) { return make_int4( v0.x, v0.y, v0.z, v1 ); } SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int2& v0, const int2& v1) { return make_int4( v0.x, v0.y, v1.x, v1.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const unsigned int v0, const uint2& v1) { return make_uint3( v0, v1.x, v1.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const uint2& v0, const unsigned int v1) { return make_uint3( v0.x, v0.y, v1 ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const unsigned int v1, const uint2& v2) { return make_uint4( v0, v1, v2.x, v2.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const uint2& v1, const unsigned int v2) { return make_uint4( v0, v1.x, v1.y, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint2& v0, const unsigned int v1, const unsigned int v2) { return make_uint4( v0.x, v0.y, v1, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const uint3& v1) { return make_uint4( v0, v1.x, v1.y, v1.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint3& v0, const unsigned int v1) { return make_uint4( v0.x, v0.y, v0.z, v1 ); } SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint2& v0, const uint2& v1) { return make_uint4( v0.x, v0.y, v1.x, v1.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const long long v0, const longlong2& v1) { return make_longlong3(v0, v1.x, v1.y); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const longlong2& v0, const long long v1) { return make_longlong3(v0.x, v0.y, v1); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const long long v1, const longlong2& v2) { return make_longlong4(v0, v1, v2.x, v2.y); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const longlong2& v1, const long long v2) { return make_longlong4(v0, v1.x, v1.y, v2); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong2& v0, const long long v1, const long long v2) { return make_longlong4(v0.x, v0.y, v1, v2); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const longlong3& v1) { return make_longlong4(v0, v1.x, v1.y, v1.z); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong3& v0, const long long v1) { return make_longlong4(v0.x, v0.y, v0.z, v1); } SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong2& v0, const longlong2& v1) { return make_longlong4(v0.x, v0.y, v1.x, v1.y); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const unsigned long long v0, const ulonglong2& v1) { return make_ulonglong3(v0, v1.x, v1.y); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const ulonglong2& v0, const unsigned long long v1) { return make_ulonglong3(v0.x, v0.y, v1); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const unsigned long long v1, const ulonglong2& v2) { return make_ulonglong4(v0, v1, v2.x, v2.y); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const ulonglong2& v1, const unsigned long long v2) { return make_ulonglong4(v0, v1.x, v1.y, v2); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong2& v0, const unsigned long long v1, const unsigned long long v2) { return make_ulonglong4(v0.x, v0.y, v1, v2); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const ulonglong3& v1) { return make_ulonglong4(v0, v1.x, v1.y, v1.z); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong3& v0, const unsigned long long v1) { return make_ulonglong4(v0.x, v0.y, v0.z, v1); } SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong2& v0, const ulonglong2& v1) { return make_ulonglong4(v0.x, v0.y, v1.x, v1.y); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float2& v0, const float v1) { return make_float3(v0.x, v0.y, v1); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float v0, const float2& v1) { return make_float3( v0, v1.x, v1.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float v1, const float2& v2) { return make_float4( v0, v1, v2.x, v2.y ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float2& v1, const float v2) { return make_float4( v0, v1.x, v1.y, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float2& v0, const float v1, const float v2) { return make_float4( v0.x, v0.y, v1, v2 ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float3& v1) { return make_float4( v0, v1.x, v1.y, v1.z ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& v0, const float v1) { return make_float4( v0.x, v0.y, v0.z, v1 ); } SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float2& v0, const float2& v1) { return make_float4( v0.x, v0.y, v1.x, v1.y ); } /** @} */
73,688
C
27.104119
184
0.631785
arhix52/Strelka/sutil/vec_math_adv.h
#pragma once #include "sutil/vec_math.h" #include <sutil/Preprocessor.h> #include <vector_functions.h> #include <vector_types.h> #if !defined(__CUDACC_RTC__) #include <cmath> #include <cstdlib> #endif // SUTIL_INLINE SUTIL_HOSTDEVICE float clamp( const float f, const float a, const float b ) // { // return fmaxf( a, fminf( f, b ) ); // } // SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& a, float w) // { // return make_float4(a.x, a.y, a.z, w); // } SUTIL_INLINE SUTIL_HOSTDEVICE float3 saturate(const float3 v) { float3 r = v; r.x = clamp(r.x, 0.0f, 1.0f); r.y = clamp(r.y, 0.0f, 1.0f); r.z = clamp(r.z, 0.0f, 1.0f); return r; } SUTIL_INLINE SUTIL_HOSTDEVICE float saturate(const float v) { return clamp(v, 0.0f, 1.0f); } SUTIL_INLINE SUTIL_HOSTDEVICE bool all(const float3 v) { return v.x != 0.0f && v.y != 0.0f && v.z != 0.0f; } SUTIL_INLINE SUTIL_HOSTDEVICE bool any(const float3 v) { return v.x != 0.0f || v.y != 0.0f || v.z != 0.0f; } SUTIL_INLINE SUTIL_HOSTDEVICE bool isnan(const float3 v) { return isnan(v.x) || isnan(v.y) || isnan(v.z); } SUTIL_INLINE SUTIL_HOSTDEVICE float3 powf(const float3 v, const float p) { float3 r = v; r.x = powf(r.x, p); r.y = powf(r.y, p); r.z = powf(r.z, p); return r; }
1,303
C
20.032258
91
0.617038
cadop/HumanGenerator/README.md
# Overview ovmh (ov_makehuman) is a MakeHuman extension for Nvidia Omniverse. This project relies on the makehuman project from https://github.com/makehumancommunity/makehuman. ![mh_ov_thumbnail](https://user-images.githubusercontent.com/11399119/189240366-adb86b3d-50dc-49e6-8ef7-4a55df441bf9.PNG) # Getting Started The easiest way to get started is using Omniverse Create. Navigate to the Extensions window and click on "Community". Search for `makehuman` and you should see our extension show up. The extension may take a few minutes to install as it will download makehuman and install it in the Omniverse's local Python instance. For use, check out the walkthrough video [![Walkthrough](https://img.youtube.com/vi/8GD3ld1Ep7c/0.jpg)](https://www.youtube.com/watch?v=8GD3ld1Ep7c) ## License *Our license restrictions are due to the AGPL of MakeHuman. In line with the statements from MakeHuman, the targets and resulting characters are CC0, meaning you can use whatever you create for free, without restrictions. It is only the codebase that is AGPL.
1,073
Markdown
43.749998
259
0.788444
cadop/HumanGenerator/exts/siborg.create.human/API_EXAMPLE.py
# Human Generator API Example # Author: Joshua Grebler | SiBORG Lab | 2023 # Description: This is an example of how to use the Human Generator API to create human models in NVIDIA Omniverse. # The siborg.create.human extension must be installed and enabled for this to work. # The script generates 10 humans, placing them throughout the stage. Random modifiers and clothing are applied to each. import siborg.create.human as hg from siborg.create.human.shared import data_path import omni.usd import random # Get the stage context = omni.usd.get_context() stage = context.get_stage() # Make a single Human to start with human = hg.Human() human.add_to_scene() # Apply a modifier by name (you can find the names of all the available modifiers # by using the `get_modifier_names()` method) height = human.get_modifier_by_name("macrodetails-height/Height") human.set_modifier_value(height, 1) # Update the human in the scene human.update_in_scene(human.prim_path) # Gather some default clothing items (additional clothing can be downloaded from the extension UI) clothes = ["nvidia_Casual/nvidia_casual.mhclo", "omni_casual/omni_casual.mhclo", "siborg_casual/siborg_casual.mhclo"] # Convert the clothing names to their full paths. clothes = [data_path(f"clothes/{c}") for c in clothes] # Create 20 humans, placing them randomly throughout the scene, and applying random modifier values for _ in range(10): h = hg.Human() h.add_to_scene() # Apply a random translation and Y rotation to the human prim translateOp = h.prim.AddTranslateOp() translateOp.Set((random.uniform(-50, 50), 0, random.uniform(-50, 50))) rotateOp = h.prim.AddRotateXYZOp() rotateOp.Set((0, random.uniform(0, 360), 0)) # Apply a random value to the last 9 modifiers in the list. # These modifiers are macros that affect the overall shape of the human more than any individual modifier. # Get the last 9 modifiers modifiers = h.get_modifiers()[-9:] # Apply a random value to each modifier. Use the modifier's min/max values to ensure the value is within range. for m in modifiers: h.set_modifier_value(m, random.uniform(m.getMin(), m.getMax())) # Update the human in the scene h.update_in_scene(h.prim_path) # Add a random clothing item to the human h.add_item(random.choice(clothes))
2,343
Python
36.806451
119
0.733248
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/human.py
from typing import Tuple, List, Dict, Union from .mhcaller import MHCaller import numpy as np import omni.kit import omni.usd from pxr import Sdf, Usd, UsdGeom, UsdSkel from .shared import sanitize, data_path from .skeleton import Skeleton from module3d import Object3D from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, UsdSkel, Vt import carb from .materials import get_mesh_texture, create_material, bind_material class Human: """Class representing a human in the scene. This class is used to add a human to the scene, and to update the human in the scene. The class also contains functions to add and remove proxies (clothing, etc.) and apply modifiers, as well as a skeleton. Attributes ---------- name : str Name of the human prim : UsdSkel.Root Reference to the usd prim for the skelroot representing the human in the stage. Can be changed using set_prim() prim_path : str Path to the human prim scale : float Scale factor for the human. Defaults to 10 (Omniverse provided humans are 10 times larger than makehuman) skeleton : Makehuman.Skeleton Skeleton object for the human usd_skel : UsdSkel.Skeleton Skeleton object for the human in the USD stage. Imported from the skeleton object. objects : List[Object3D] List of objects attached to the human. Fetched from the makehuman app mh_meshes : List[Object3D] List of meshes attached to the human. Fetched from the makehuman app """ def __init__(self, name='human', **kwargs): """Constructs an instance of Human. Parameters ---------- name : str Name of the human. Defaults to 'human' """ self.name = name # Reference to the usd prim for the skelroot representing the human in the stage self.prim = None # Provide a scale factor (Omniverse provided humans are 10 times larger than makehuman) self.scale = 10 # Create a skeleton object for the human self.skeleton = Skeleton(self.scale) # usd_skel is none until the human is added to the stage self.usd_skel = None # Set the human in makehuman to default values MHCaller.reset_human() def reset(self): """Resets the human in makehuman and adds a new skeleton to the human""" # Reset the human in makehuman MHCaller.reset_human() # Re-add the skeleton to the human self.skeleton = Skeleton(self.scale) def delete_proxies(self): """Deletes the prims corresponding to proxies attached to the human""" # Delete any child prims corresponding to proxies if self.prim: # Get the children of the human prim and delete them all at once proxy_prims = [child.GetPath() for child in self.prim.GetChildren() if child.GetCustomDataByKey("Proxy_path:")] omni.kit.commands.execute("DeletePrims", paths=proxy_prims) @property def prim_path(self): """Path to the human prim""" if self.prim: return self.prim.GetPath().pathString else: return None @property def objects(self): """List of objects attached to the human. Fetched from the makehuman app""" return MHCaller.objects @property def mh_meshes(self): """List of meshes attached to the human. Fetched from the makehuman app""" return MHCaller.meshes def add_to_scene(self): """Adds the human to the scene. Creates a prim for the human with custom attributes to hold modifiers and proxies. Also creates a prim for each proxy and attaches it to the human prim. Returns ------- str Path to the human prim""" # Get the current stage stage = omni.usd.get_context().get_stage() root_path = "/" # Get default prim. default_prim = stage.GetDefaultPrim() if default_prim.IsValid(): # Set the rootpath under the stage's default prim, if the default prim is valid root_path = default_prim.GetPath().pathString # Create a path for the next available prim prim_path = omni.usd.get_stage_next_free_path(stage, root_path + "/" + self.name, False) # Create a prim for the human # Prim should be a SkelRoot so we can rig the human with a skeleton later self.prim = UsdSkel.Root.Define(stage, prim_path) # Write the properties of the human to the prim self.write_properties(prim_path, stage) # Get the objects of the human from mhcaller objects = MHCaller.objects # Get the human object from the list of objects human = objects[0] # Determine the offset for the human from the ground offset = -1 * human.getJointPosition("ground") # Import makehuman objects into the scene mesh_paths = self.import_meshes(prim_path, stage, offset = offset) # Add the skeleton to the scene self.usd_skel= self.skeleton.add_to_stage(stage, prim_path, offset = offset) # Create bindings between meshes and the skeleton. Returns a list of # bindings the length of the number of meshes bindings = self.setup_bindings(mesh_paths, stage, self.usd_skel) # Setup weights for corresponding mh_meshes (which hold the data) and # bindings (which link USD_meshes to the skeleton) self.setup_weights(self.mh_meshes, bindings, self.skeleton.joint_names, self.skeleton.joint_paths) self.setup_materials(self.mh_meshes, mesh_paths, root_path, stage) # Explicitly setup material for human skin texture_path = data_path("skins/textures/skin.png") skin = create_material(texture_path, "Skin", root_path, stage) # Bind the skin material to the first prim in the list (the human) bind_material(mesh_paths[0], skin, stage) Human._set_scale(self.prim.GetPrim(), self.scale) return self.prim def update_in_scene(self, prim_path: str): """Updates the human in the scene. Writes the properties of the human to the human prim and imports the human and proxy meshes. This is called when the human is updated Parameters ---------- prim_path : str Path to the human prim (prim type is SkelRoot) """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path) prim = stage.GetPrimAtPath(prim_path) if prim and stage: print(prim.GetPath().pathString) prim_kind = prim.GetTypeName() # Check if the prim is a SkelRoot and a human if prim_kind == "SkelRoot" and prim.GetCustomDataByKey("human"): # Get default prim. default_prim = stage.GetDefaultPrim() if default_prim.IsValid(): # Set the rootpath under the stage's default prim, if the default prim is valid root_path = default_prim.GetPath().pathString else: root_path = "/" # Write the properties of the human to the prim self.write_properties(prim_path, stage) # Get the objects of the human from mhcaller objects = MHCaller.objects # Get the human object from the list of objects human = objects[0] # Determine the offset for the human from the ground offset = -1 * human.getJointPosition("ground") # Import makehuman objects into the scene mesh_paths = self.import_meshes(prim_path, stage, offset = offset) # Update the skeleton values and insert it into the stage self.usd_skel = self.skeleton.update_in_scene(stage, prim_path, offset = offset) # Create bindings between meshes and the skeleton. Returns a list of # bindings the length of the number of meshes bindings = self.setup_bindings(mesh_paths, stage, self.usd_skel) # Setup weights for corresponding mh_meshes (which hold the data) and # bindings (which link USD_meshes to the skeleton) self.setup_weights(self.mh_meshes, bindings, self.skeleton.joint_names, self.skeleton.joint_paths) self.setup_materials(self.mh_meshes, mesh_paths, root_path, stage) # Explicitly setup material for human skin texture_path = data_path("skins/textures/skin.png") skin = create_material(texture_path, "Skin", root_path, stage) # Bind the skin material to the first prim in the list (the human) bind_material(mesh_paths[0], skin, stage) else: carb.log_warn("The selected prim must be a human!") else: carb.log_warn("Can't update human. No prim selected!") def import_meshes(self, prim_path: str, stage: Usd.Stage, offset: List[float] = [0, 0, 0]): """Imports the meshes of the human into the scene. This is called when the human is added to the scene, and when the human is updated. This function creates mesh prims for both the human and its proxies, and attaches them to the human prim. If a mesh already exists in the scene, its values are updated instead of creating a new mesh. Parameters ---------- prim_path : str Path to the human prim stage : Usd.Stage Stage to write to offset : List[float], optional Offset to move the mesh relative to the prim origin, by default [0, 0, 0] Returns ------- paths : array of: Sdf.Path Usd Sdf paths to geometry prims in the scene """ # Get the objects of the human from mhcaller objects = MHCaller.objects # Get the meshes of the human and its proxies meshes = [o.mesh for o in objects] usd_mesh_paths = [] for mesh in meshes: # Number of vertices per face nPerFace = mesh.vertsPerFaceForExport # Lists to hold pruned lists of vertex and UV indices newvertindices = [] newuvindices = [] # Array of coordinates organized [[x1,y1,z1],[x2,y2,z2]...] # Adding the given offset moves the mesh relative to the prim origin coords = mesh.getCoords() + offset for fn, fv in enumerate(mesh.fvert): if not mesh.face_mask[fn]: continue # only include <nPerFace> verts for each face, and order them # consecutively newvertindices += [(fv[n]) for n in range(nPerFace)] fuv = mesh.fuvs[fn] # build an array of (u,v)s for each face newuvindices += [(fuv[n]) for n in range(nPerFace)] # Type conversion newvertindices = np.array(newvertindices) # Create mesh prim at appropriate path. Does not yet hold any data name = sanitize(mesh.name) usd_mesh_path = prim_path + "/" + name usd_mesh_paths.append(usd_mesh_path) # Check to see if the mesh prim already exists prim = stage.GetPrimAtPath(usd_mesh_path) if prim.IsValid(): # omni.kit.commands.execute("DeletePrims", paths=[usd_mesh_path]) point_attr = prim.GetAttribute('points') point_attr.Set(coords) face_count = prim.GetAttribute('faceVertexCounts') nface = [nPerFace] * int(len(newvertindices) / nPerFace) face_count.Set(nface) face_idx = prim.GetAttribute('faceVertexIndices') face_idx.Set(newvertindices) normals_attr = prim.GetAttribute('normals') normals_attr.Set(mesh.getNormals()) meshGeom = UsdGeom.Mesh(prim) # If it doesn't exist, make it. This will run the first time a human is created and # whenever a new proxy is added else: # First determine if the mesh is a proxy p = mesh.object.proxy if p: # Determine if the mesh is a clothes proxy or a proxymesh. If not, then # an existing proxy of this type already exists, and we must overwrite it type = p.type if p.type else "proxymeshes" if not (type == "clothes" or type == "proxymeshes"): for child in self.prim.GetChildren(): child_type = child.GetCustomDataByKey("Proxy_type:") if child_type == type: # If the child prim has the same type as the proxy, delete it omni.kit.commands.execute("DeletePrims", paths=[child.GetPath()]) break meshGeom = UsdGeom.Mesh.Define(stage, usd_mesh_path) prim = meshGeom.GetPrim() # Set vertices. This is a list of tuples for ALL vertices in an unassociated # cloud. Faces are built based on indices of this list. # Example: 3 explicitly defined vertices: # meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10)] meshGeom.CreatePointsAttr(coords) # Set face vertex count. This is an array where each element is the number # of consecutive vertex indices to include in each face definition, as # indices are given as a single flat list. The length of this list is the # same as the number of faces # Example: 4 faces with 4 vertices each # meshGeom.CreateFaceVertexCountsAttr([4, 4, 4, 4]) nface = [nPerFace] * int(len(newvertindices) / nPerFace) meshGeom.CreateFaceVertexCountsAttr(nface) # Set face vertex indices. # Example: one face with 4 vertices defined by 4 indices. # meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) meshGeom.CreateFaceVertexIndicesAttr(newvertindices) # Set vertex normals. Normals are represented as a list of tuples each of # which is a vector indicating the direction a point is facing. This is later # Used to calculate face normals # Example: Normals for 3 vertices # meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, # 0)]) meshGeom.CreateNormalsAttr(mesh.getNormals()) meshGeom.SetNormalsInterpolation("vertex") # If the mesh is a proxy, write the proxy path to the mesh prim if mesh.object.proxy: p = mesh.object.proxy type = p.type if p.type else "proxymeshes" prim.SetCustomDataByKey("Proxy_path:", p.file) prim.SetCustomDataByKey("Proxy_type:", type) prim.SetCustomDataByKey("Proxy_name:", p.name) # Set vertex uvs. UVs are represented as a list of tuples, each of which is a 2D # coordinate. UV's are used to map textures to the surface of 3D geometry # Example: texture coordinates for 3 vertices # texCoords.Set([(0, 1), (0, 0), (1, 0)]) texCoords = meshGeom.CreatePrimvar( "st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying ) texCoords.Set(mesh.getUVs(newuvindices)) # # Subdivision is set to none. The mesh is as imported and not further refined meshGeom.CreateSubdivisionSchemeAttr().Set("none") # ConvertPath strings to USD Sdf paths. TODO change to map() for performance paths = [Sdf.Path(mesh_path) for mesh_path in usd_mesh_paths] return paths def get_written_modifiers(self) -> Union[Dict[str, float], None]: """List of modifier names and values written to the human prim. MAY BE STALE IF THE HUMAN HAS BEEN UPDATED IN MAKEHUMAN AND THE CHANGES HAVE NOT BEEN WRITTEN TO THE PRIM. Returns ------- Dict[str, float] Dictionary of modifier names and values. Keys are modifier names, values are modifier values""" return self.prim.GetCustomDataByKey("Modifiers") if self.prim else None def get_changed_modifiers(self): """List of modifiers which have been changed in makehuman. Fetched from the human in makehuman. MAY NOT MATCH `get_written_modifiers()` IF CHANGES HAVE NOT BEEN WRITTEN TO THE PRIM.""" return MHCaller.modifiers def get_modifiers(self): """Retrieve the list of all modifiers available to the human, whether or not their values have changed.""" return MHCaller.default_modifiers def set_modifier_value(self, modifier, value: float): """Sets the value of a modifier in makehuman. Validates the value before setting it. Returns true if the value was set, false otherwise. Parameters ---------- modifier : makehuman.humanmodifier.Modifier Modifier to change value : float Value to set the modifier to """ # Get the range of the modifier val_min = modifier.getMin() val_max = modifier.getMax() # Check if the value is within the range of the modifier if value >= val_min and value <= val_max: # Set the value of the modifier modifier.setValue(value) return True else: carb.log_warn(f"Value must be between {str(val_min)} and {str(val_max)}") return False def get_modifier_by_name(self, name: str): """Gets a modifier from the list of modifiers attached to the human by name Parameters ---------- name : str Name of the modifier to get Returns ------- makehuman.modifiers.Modifier Modifier with the given name """ return MHCaller.human.getModifier(name) def get_modifier_names(self): return MHCaller.human.getModifierNames() def write_properties(self, prim_path: str, stage: Usd.Stage): """Writes the properties of the human to the human prim. This includes modifiers and proxies. This is called when the human is added to the scene, and when the human is updated Parameters ---------- prim_path : str Path to the human prim stage : Usd.Stage Stage to write to """ prim = stage.GetPrimAtPath(prim_path) # Add custom data to the prim by key, designating the prim is a human prim.SetCustomDataByKey("human", True) # Get the modifiers of the human in mhcaller modifiers = MHCaller.modifiers for m in modifiers: # Add the modifier to the prim as custom data by key. For modifiers, # the format is "group/modifer:value" prim.SetCustomDataByKey("Modifiers:" + m.fullName, m.getValue()) # NOTE We are not currently using proxies in the USD export. Proxy data is stored # in their respective mesh prims, so that deleting proxy prims will also remove the # proxies. The following code is left here for reference. # Get the proxies of the human in mhcaller # proxies = MHCaller.proxies # for p in proxies: # # Add the proxy to the prim as custom data by key under "Proxies". # # Proxy type should be "proxymeshes" if type cannot be determined from the # # proxy.type property. # type = p.type if p.type else "proxymeshes" # # Only "proxymeshes" and "clothes" should be subdictionaries of "Proxies" # if type == "clothes" or type == "proxymeshes": # prim.SetCustomDataByKey("Proxies:" + type + ":" + p.name, p.file) # # Other proxy types should be added as a key to the prim with their # # type as the key and the path as the value # else: # prim.SetCustomDataByKey("Proxies:" + type, p.file) def set_prim(self, usd_prim : Usd.Prim): """Updates the human based on the given prim's attributes Parameters ---------- usd_prim : Usd.Prim Prim from which to update the human model.""" self.prim = usd_prim # Get the data from the prim humandata = self.prim.GetCustomData() # Get the list of modifiers from the prim modifiers = humandata.get("Modifiers") for m, v in modifiers.items(): MHCaller.human.getModifier(m).setValue(v, skipDependencies=False) # Gather proxies from the prim children proxies = [] for child in self.prim.GetChildren(): if child.GetTypeName() == "Mesh" and child.GetCustomDataByKey("Proxy_path:"): proxies.append(child) # Clear the makehuman proxies MHCaller.clear_proxies() # # Make sure the proxy list is not empty if proxies: for p in proxies: type = p.GetCustomDataByKey("Proxy_type:") path = p.GetCustomDataByKey("Proxy_path:") # name = p.GetCustomDataByKey("Proxy_name:") MHCaller.add_proxy(path, type) # Update the human in MHCaller MHCaller.human.applyAllTargets() def setup_weights(self, mh_meshes: List['Object3D'], bindings: List[UsdSkel.BindingAPI], joint_names: List[str], joint_paths: List[str]): """Apply weights to USD meshes using data from makehuman. USD meshes, bindings and skeleton must already be in the active scene Parameters ---------- mh_meshes : list of `Object3D` Makehuman meshes which store weight data bindings : list of `UsdSkel.BindingAPI` USD bindings between meshes and skeleton joint_names : list of str Unique, plaintext names of all joints in the skeleton in USD (breadth-first) order. joint_paths : list of str List of the full usd path to each joint corresponding to the skeleton to bind to """ # Generate bone weights for all meshes up front so they can be reused for all rawWeights = MHCaller.human.getVertexWeights( MHCaller.human.getSkeleton() ) # Basemesh weights for mesh in self.mh_meshes: if mesh.object.proxy: # Transfer weights to proxy parentWeights = mesh.object.proxy.getVertexWeights( rawWeights, MHCaller.human.getSkeleton() ) else: parentWeights = rawWeights # Transfer weights to face/vert masked and/or subdivided mesh weights = mesh.getVertexWeights(parentWeights) # Attach these vertexWeights to the mesh to pass them around the # exporter easier, the cloned mesh is discarded afterwards, anyway # if this is the same person, just skip updating weights mesh.vertexWeights = weights # Iterate through corresponding meshes and bindings for mh_mesh, binding in zip(mh_meshes, bindings): # Calculate vertex weights indices, weights = self.calculate_influences(mh_mesh, joint_names) # Type conversion to native ints and floats from numpy indices = list(map(int, indices)) weights = list(map(float, weights)) # Type conversion to USD indices = Vt.IntArray(indices) weights = Vt.FloatArray(weights) # The number of weights to apply to each vertex, taken directly from # MakeHuman data elementSize = int(mh_mesh.vertexWeights._nWeights) # weight_data = list(mh_mesh.vertexWeights.data) TODO remove # We might not need to normalize. Makehuman weights are automatically # normalized when loaded, see: # http://www.makehumancommunity.org/wiki/Technical_notes_on_MakeHuman UsdSkel.NormalizeWeights(weights, elementSize) UsdSkel.SortInfluences(indices, weights, elementSize) # Assign indices to binding indices_attribute = binding.CreateJointIndicesPrimvar( constant=False, elementSize=elementSize ) joint_attr = binding.GetPrim().GetAttribute('skel:joints') joint_attr.Set(joint_paths) indices_attribute.Set(indices) # Assign weights to binding weights_attribute = binding.CreateJointWeightsPrimvar( constant=False, elementSize=elementSize ) weights_attribute.Set(weights) def calculate_influences(self, mh_mesh: Object3D, joint_names: List[str]): """Build arrays of joint indices and corresponding weights for each vertex. Joints are in USD (breadth-first) order. Parameters ---------- mh_mesh : Object3D Makehuman-format mesh. Contains weight and vertex data. joint_names : list of str Unique, plaintext names of all joints in the skeleton in USD (breadth-first) order. Returns ------- indices : list of int Flat list of joint indices for each vertex weights : list of float Flat list of weights corresponding to joint indices """ # The maximum number of weights a vertex might have max_influences = mh_mesh.vertexWeights._nWeights # Named joints corresponding to vertices and weights ie. # {"joint",([indices],[weights])} influence_joints = mh_mesh.vertexWeights.data num_verts = mh_mesh.getVertexCount(excludeMaskedVerts=False) # all skeleton joints in USD order binding_joints = joint_names # Corresponding arrays of joint indices and weights of length num_verts. # Allots the maximum number of weights for every vertex, and pads any # remaining weights with 0's, per USD spec, see: # https://graphics.pixar.com/usd/dev/api/_usd_skel__schemas.html#UsdSkel_BindingAPI # "If a point has fewer influences than are needed for other points, the # unused array elements of that point should be filled with 0, both for # joint indices and for weights." indices = np.zeros((num_verts, max_influences)) weights = np.zeros((num_verts, max_influences)) # Keep track of the number of joint influences on each vertex influence_counts = np.zeros(num_verts, dtype=int) for joint, joint_data in influence_joints.items(): # get the index of the joint in our USD-ordered list of all joints joint_index = binding_joints.index(joint) for vert_index, weight in zip(*joint_data): # Use influence_count to keep from overwriting existing influences influence_count = influence_counts[vert_index] # Add the joint index to our vertex array indices[vert_index][influence_count] = joint_index # Add the weight to the same vertex weights[vert_index][influence_count] = weight # Add to the influence count for this vertex influence_counts[vert_index] += 1 # Check for any unweighted verts (this is a test routine) # for i, d in enumerate(indices): if np.all((d == 0)): print(i) # Flatten arrays to one dimensional lists indices = indices.flatten() weights = weights.flatten() return indices, weights def setup_bindings(self, paths: List[Sdf.Path], stage: Usd.Stage, skeleton: UsdSkel.Skeleton): """Setup bindings between meshes in the USD scene and the skeleton Parameters ---------- paths : List of Sdf.Path USD Sdf paths to each mesh prim stage : Usd.Stage The USD stage where the prims can be found skeleton : UsdSkel.Skeleton The USD skeleton to apply bindings to Returns ------- array of: UsdSkel.BindingAPI Array of bindings between each mesh and the skeleton, in "path" order """ bindings = [] # TODO rename "mesh" to "path" for mesh in paths: # Get the prim in the stage prim = stage.GetPrimAtPath(mesh) attrs = prim.GetAttribute('primvars:skel:jointWeights') # Check if joint weights have already been applied if attrs.IsValid(): prim_path = prim.GetPath() sdf_path = Sdf.Path(prim_path) binding = UsdSkel.BindingAPI.Get(stage, sdf_path) # relationships = prim.GetRelationships() # 'material:binding' , 'proxyPrim', 'skel:animationSource','skel:blendShapeTargets','skel:skeleton' # get_binding.GetSkeletonRel() else: # Create a binding applied to the prim binding = UsdSkel.BindingAPI.Apply(prim) # Create a relationship between the binding and the skeleton binding.CreateSkeletonRel().SetTargets([skeleton.GetPath()]) # Add the binding to the list to return bindings.append(binding) return bindings def setup_materials(self, mh_meshes: List['Object3D'], meshes: List[Sdf.Path], root: str, stage: Usd.Stage): """Fetches materials from Makehuman meshes and applies them to their corresponding Usd mesh prims in the stage. Parameters ---------- mh_meshes : List['Object3D'] List of makehuman meshes meshes : List[Sdf.Path] Paths to Usd meshes in the stage root : str The root path under which to create new prims stage : Usd.Stage Usd stage in which to create materials, and which contains the meshes to which to apply materials """ for mh_mesh, mesh in zip(self.mh_meshes, meshes): # Get a texture path and name from the makehuman mesh texture, name = get_mesh_texture(mh_mesh) if texture: # If we can get a texture from the makehuman mesh, create a material # from it and bind it to the corresponding USD mesh in the stage material = create_material(texture, name, root, stage) bind_material(mesh, material, stage) def add_item(self, path: str): """Add a new asset to the human. Propagates changes to the Makehuman app and then upates the stage with the new asset. If the asset is a proxy, targets will not be applied. If the asset is a skeleton, targets must be applied. Parameters ---------- path : str Path to an asset on disk """ # Check if human has a prim if self.prim: # Add an item through the MakeHuman instance and update the widget view MHCaller.add_item(path) self.update_in_scene(self.prim.GetPath().pathString) else: carb.log_warn("Can't add asset. No human prim selected!") @staticmethod def _set_scale(prim : Usd.Prim, scale : float): """Set scale of a prim. Parameters ---------- prim : Usd.Prim The prim to scale. scale : float The scale to apply.""" if prim == None: return # Uniform scale. sV = Gf.Vec3f(scale, scale, scale) scale = prim.GetAttribute("xformOp:scale").Get() if scale != None: prim.GetAttribute("xformOp:scale").Set(Gf.Vec3f(sV)) else: # xformOpOrder is also updated. xformAPI = UsdGeom.XformCommonAPI(prim) xformAPI.SetScale(Gf.Vec3f(sV))
32,659
Python
40.030151
141
0.598212
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/styles.py
# Stylesheet for parameter panels panel_style = { "Rectangle::group_rect": { "background_color": 0xFF313333, "border_radius": 5, "margin": 5, }, "VStack::contents": { "margin": 10, }, } # Stylesheet for sliderentry widgets sliderentry_style = { "Label::label_param": { "margin_width": 10, }, } # stylesheet for collapseable frame widgets, used for each modifier category frame_style = { "CollapsableFrame": { "background_color": 0xFF1F2123, }, } # stylesheet for main UI window window_style = { "Rectangle::splitter": {"background_color": 0xFF454545}, "Rectangle::splitter:hovered": {"background_color": 0xFFFFCA83}, } # Stylesheet for buttons button_style = { "Button:disabled": { "background_color": 0xFF424242, }, "Button:disabled.Label": { "color": 0xFF848484, }, }
894
Python
20.309523
76
0.608501
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/mhcaller.py
from typing import TypeVar, Union import warnings import io import makehuman from pathlib import Path # Makehuman loads most modules by manipulating the system path, so we have to # run this before we can run the rest of our makehuman imports makehuman.set_sys_path() import human import animation import bvh import files3d import mh from core import G from mhmain import MHApplication from shared import wavefront import humanmodifier, skeleton import proxy, gui3d, events3d, targets from getpath import findFile import numpy as np import carb from .shared import data_path class classproperty: """Class property decorator. Allows us to define a property on a class method rather than an instance method.""" def __init__(cls, fget): cls.fget = fget def __get__(cls, obj, owner): return cls.fget(owner) class MHCaller: """A singleton wrapper around the Makehuman app. Lets us use Makehuman functions without launching the whole application. Also holds all data about the state of our Human and available modifiers/assets, and allows us to create new humans without creating a new instance of MHApp. Attributes ---------- G : Globals Makehuman global object. Stores globals needed by Makehuman internally human : Human Makehuman Human object. Encapsulates all human data (parameters, available) modifiers, skeletons, meshes, assets, etc) and functions. """ G = G human = None def __init__(cls): """Constructs an instance of MHCaller. This involves setting up the needed components to use makehuman modules independent of the GUI. This includes app globals (G) and the human object.""" cls._config_mhapp() cls.init_human() def __new__(cls): """Singleton pattern. Only one instance of MHCaller can exist at a time.""" if not hasattr(cls, 'instance'): cls.instance = super(MHCaller, cls).__new__(cls) return cls.instance @classmethod def _config_mhapp(cls): """Declare and initialize the makehuman app, and move along if we encounter any errors (omniverse sometimes fails to purge the app singleton on extension reload, which can throw an error. This just means the app already exists) """ try: cls.G.app = MHApplication() except: return cls.human_mapper = {} @classmethod def reset_human(cls): """Resets the human object to its initial state. This involves setting the human's name to its default, resetting all modifications, and resetting all proxies. Does not reset the skeleton. Also flags the human as having been reset so that the new name can be created when adding to the Usd stage. """ cls.human.resetMeshValues() # Subdivide the human mesh. This also means that any proxies added to the human are subdivided cls.human.setSubdivided(True) # Restore eyes # cls.add_proxy(data_path("eyes/high-poly/high-poly.mhpxy"), "eyes") # Reset skeleton to the game skeleton cls.human.setSkeleton(cls.game_skel) # Reset the human to tpose cls.set_tpose() # HACK Set the age to itcls to force an update of targets, otherwise humans # are created with the MH base mesh, see: # http://static.makehumancommunity.org/makehuman/docs/professional_mesh_topology.html cls.human.setAge(cls.human.getAge()) @classmethod def init_human(cls): """Initialize the human and set some required files from disk. This includes the skeleton and any proxies (hair, clothes, accessories etc.) The weights from the base skeleton must be transfered to the chosen skeleton or else there will be unweighted verts on the meshes. """ cls.human = human.Human(files3d.loadMesh(mh.getSysDataPath("3dobjs/base.obj"), maxFaces=5)) # set the makehuman instance human so that features (eg skeletons) can # access it globally cls.G.app.selectedHuman = cls.human humanmodifier.loadModifiers(mh.getSysDataPath("modifiers/modeling_modifiers.json"), cls.human) # Add eyes # cls.add_proxy(data_path("eyes/high-poly/high-poly.mhpxy"), "eyes") cls.base_skel = skeleton.load( mh.getSysDataPath("rigs/default.mhskel"), cls.human.meshData, ) # Load the game developer skeleton # The root of this skeleton is at the origin which is better for animation # retargeting cls.game_skel = skeleton.load(data_path("rigs/game_engine.mhskel"), cls.human.meshData) # Build joint weights on our chosen skeleton, derived from the base # skeleton cls.game_skel.autoBuildWeightReferences(cls.base_skel) # Set the base skeleton cls.human.setBaseSkeleton(cls.base_skel) # Set the game skeleton cls.human.setSkeleton(cls.game_skel) @classproperty def objects(cls): """List of objects attached to the human. Returns ------- list of: guiCommon.Object All 3D objects included in the human. This includes the human itcls, as well as any proxies """ # Make sure proxies are up-to-date cls.update() return cls.human.getObjects() @classproperty def meshes(cls): """All of the meshes of all of the objects attached to a human. This includes the mesh of the human itcls as well as the meshes of all proxies (clothing, hair, musculature, eyes, etc.)""" return [o.mesh for o in cls.objects] @classproperty def modifiers(cls): """List of modifers attached to the human. These are all macros as well as any individual modifiers which have changed. Returns ------- list of: humanmodifier.Modifier The macros and changed modifiers included in the human """ return [m for m in cls.human.modifiers if m.getValue() or m.isMacro()] @classproperty def default_modifiers(cls): """List of all the loaded modifiers, whether or not their default values have been changed. ------- list of: humanmodifier.Modifier The macros and changed modifiers included in the human """ return cls.human.modifiers @classproperty def proxies(cls): """List of proxies attached to the human. Returns ------- list of: proxy.Proxy All proxies included in the human """ return cls.human.getProxies() @classmethod def update(cls): """Propagate changes to meshes and proxies""" # For every mesh object except for the human (first object), update the # mesh and corresponding proxy # See https://github.com/makehumancommunity/makehuman/search?q=adaptproxytohuman for obj in cls.human.getObjects()[1:]: mesh = obj.getSeedMesh() pxy = obj.getProxy() # Update the proxy and fit to posed human # args are (mesh, fit_to_posed = false) by default pxy.update(mesh, True) # Update the mesh mesh.update() @classmethod def add_proxy(cls, proxypath : str, proxy_type : str = None): """Load a proxy (hair, nails, clothes, etc.) and apply it to the human Parameters ---------- proxypath : str Path to the proxy file on disk proxy_type: str, optional Proxy type, None by default Can be automatically determined using path names, but otherwise must be defined (this is a limitation of how makehuman handles proxies) """ # Derived from work by @tomtom92 at the MH-Community forums # See: http://www.makehumancommunity.org/forum/viewtopic.php?f=9&t=17182&sid=7c2e6843275d8c6c6e70288bc0a27ae9 # Get proxy type if none is given if proxy_type is None: proxy_type = cls.guess_proxy_type(proxypath) # Load the proxy pxy = proxy.loadProxy(cls.human, proxypath, type=proxy_type) # Get the mesh and Object3D object from the proxy applied to the human mesh, obj = pxy.loadMeshAndObject(cls.human) # TODO is this next line needed? mesh.setPickable(True) # TODO Can this next line be deleted? The app isn't running gui3d.app.addObject(obj) # Fit the proxy mesh to the human mesh2 = obj.getSeedMesh() fit_to_posed = True pxy.update(mesh2, fit_to_posed) mesh2.update() # Set the object to be subdivided if the human is subdivided obj.setSubdivided(cls.human.isSubdivided()) # Set/add proxy based on type if proxy_type == "eyes": cls.human.setEyesProxy(pxy) elif proxy_type == "clothes": cls.human.addClothesProxy(pxy) elif proxy_type == "eyebrows": cls.human.setEyebrowsProxy(pxy) elif proxy_type == "eyelashes": cls.human.setEyelashesProxy(pxy) elif proxy_type == "hair": cls.human.setHairProxy(pxy) else: # Body proxies (musculature, etc) cls.human.setProxy(pxy) vertsMask = np.ones(cls.human.meshData.getVertexCount(), dtype=bool) proxyVertMask = proxy.transferVertexMaskToProxy(vertsMask, pxy) # Apply accumulated mask from previous layers on this proxy obj.changeVertexMask(proxyVertMask) # Delete masked vertices # TODO add toggle for this feature in UI # verts = np.argwhere(pxy.deleteVerts)[..., 0] # vertsMask[verts] = False # cls.human.changeVertexMask(vertsMask) Proxy = TypeVar("Proxy") @classmethod def remove_proxy(cls, proxy: Proxy): """Removes a proxy from the human. Executes a particular method for removal based on proxy type. Parameters ---------- proxy : proxy.Proxy The Makehuman proxy to remove from the human """ proxy_type = proxy.type.lower() # Use MakeHuman internal methods to remove proxy based on type if proxy_type == "eyes": cls.human.setEyesProxy(None) elif proxy_type == "clothes": cls.human.removeClothesProxy(proxy.uuid) elif proxy_type == "eyebrows": cls.human.setEyebrowsProxy(None) elif proxy_type == "eyelashes": cls.human.setEyelashesProxy(None) elif proxy_type == "hair": cls.human.setHairProxy(None) else: # Body proxies (musculature, etc) cls.human.setProxy(None) @classmethod def clear_proxies(cls): """Removes all proxies from the human""" for pxy in cls.proxies: cls.remove_proxy(pxy) Skeleton = TypeVar("Skeleton") @classmethod def remove_item(cls, item : Union[Skeleton, Proxy]): """Removes a Makehuman asset from the human. Assets include Skeletons as well as proxies. Determines removal method based on asset object type. Parameters ---------- item : Union[Skeleton,Proxy] Makehuman skeleton or proxy to remove from the human """ if isinstance(item, proxy.Proxy): cls.remove_proxy(item) else: return @classmethod def add_item(cls, path : str): """Add a Makehuman asset (skeleton or proxy) to the human. Parameters ---------- path : str Path to the asset on disk """ if "mhpxy" in path or "mhclo" in path: cls.add_proxy(path) elif "mhskel" in path: cls.set_skel(path) @classmethod def set_skel(cls, path : str): """Change the skeleton applied to the human. Loads a skeleton from disk. The skeleton position can be used to drive the human position in the scene. Parameters ---------- path : str The path to the skeleton to load from disk """ # Load skeleton from path skel = skeleton.load(path, cls.human.meshData) # Build skeleton weights based on base skeleton skel.autoBuildWeightReferences(cls.base_skel) # Set the skeleton and update the human cls.human.setSkeleton(skel) cls.human.applyAllTargets() # Return the skeleton object return skel @classmethod def guess_proxy_type(cls, path : str): """Guesses a proxy's type based on the path from which it is loaded. Parameters ---------- path : str The path to the proxy on disk Returns ------- Union[str,None] The proxy type, or none if the type could not be determined """ proxy_types = ("eyes", "clothes", "eyebrows", "eyelashes", "hair") for type in proxy_types: if type in path: return type return None @classmethod def set_tpose(cls): """Sets the human to the T-Pose""" # Load the T-Pose BVH file filepath = data_path('poses\\tpose.bvh') bvh_file = bvh.load(filepath, convertFromZUp="auto") # Create an animation track from the BVH file anim = bvh_file.createAnimationTrack(cls.human.getBaseSkeleton()) # Add the animation to the human cls.human.addAnimation(anim) # Set the active animation to the T-Pose cls.human.setActiveAnimation(anim.name) # Refresh the human pose cls.human.refreshPose() return # Create an instance of MHCaller when imported MHCaller()
13,875
Python
34.218274
118
0.622198
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/extension.py
import omni.ext import omni.ui as ui import carb import carb.events import omni from functools import partial import asyncio import omni.usd from pxr import Usd from typing import Union from .window import MHWindow, WINDOW_TITLE, MENU_PATH class MakeHumanExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): # subscribe to stage events # see https://github.com/mtw75/kit_customdata_view _usd_context = omni.usd.get_context() self._selection = _usd_context.get_selection() self._human_selection_event = carb.events.type_from_string("siborg.create.human.human_selected") # subscribe to stage events self._events = _usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_push( self._on_stage_event, name='human seletion changed', ) # get message bus event stream so we can push events to the message bus self._bus = omni.kit.app.get_app().get_message_bus_event_stream() ui.Workspace.set_show_window_fn(WINDOW_TITLE, partial(self.show_window, None)) # create a menu item to open the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( MENU_PATH, self.show_window, toggle=True, value=True ) # show the window ui.Workspace.show_window(WINDOW_TITLE) print("[siborg.create.human] HumanGeneratorExtension startup") def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(WINDOW_TITLE, None) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def visibility_changed(self, visible): # Called when window closed by user editor_menu = omni.kit.ui.get_editor_menu() # Update the menu item to reflect the window state if editor_menu: editor_menu.set_value(MENU_PATH, visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): """Handles showing and hiding the window""" if value: self._window = MHWindow(WINDOW_TITLE) # # Dock window wherever the "Content" tab is found (bottom panel by default) self._window.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.set_visibility_changed_fn(self.visibility_changed) elif self._window: self._window.visible = False def _on_stage_event(self, event): """Handles stage events. This is where we get notified when the user selects/deselects a prim in the viewport.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): # Get the current selection selection = self._selection.get_selected_prim_paths() # Check if the selection is empty if not selection: # Push an event to the message bus with "None" as a payload # This event will be picked up by the window and used to update the UI carb.log_warn("Human deselected") self._bus.push(self._human_selection_event, payload={"prim_path": None}) else: # Get the stage _usd_context = omni.usd.get_context() stage = _usd_context.get_stage() if selection and stage: if len(selection) > 0: path = selection[-1] print(path) prim = stage.GetPrimAtPath(path) prim = self._get_typed_parent(prim, "SkelRoot") # If the selection is a human, push an event to the event stream with the prim as a payload # This event will be picked up by the window and used to update the UI if prim and prim.GetCustomDataByKey("human"): # carb.log_warn("Human selected") path = prim.GetPath().pathString self._bus.push(self._human_selection_event, payload={"prim_path": path}) else: # carb.log_warn("Human deselected") self._bus.push(self._human_selection_event, payload={"prim_path": None}) def _get_typed_parent(self, prim: Union[Usd.Prim, None], type_name: str, level: int = 5): """Returns the first parent of the given prim with the given type name. If no parent is found, returns None. Parameters: ----------- prim : Usd.Prim or None The prim to search from. If None, returns None. type_name : str The parent type name to search for level : int The maximum number of levels to traverse. Defaults to 5. Returns: -------- Usd.Prim The first parent of the given prim with the given type name. If no match is found, returns None. """ if (not prim) or level == 0: return None elif prim and prim.GetTypeName() == type_name: return prim else: return self._get_typed_parent(prim.GetParent(), type_name, level - 1)
6,003
Python
40.986014
121
0.590038
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/skeleton.py
from pxr import Usd, Gf, UsdSkel from typing import List import numpy as np from .shared import sanitize from .mhcaller import skeleton as mhskel from .mhcaller import MHCaller class Bone: """Bone which constitutes skeletons to be imported using the HumanGenerator extension. Has a parent and children, transforms in space, and named joints at the head and tail. Attributes ---------- name : str Human-readable bone name. """ def __init__(self, skel: 'Skeleton', name: str, parent: str, head: str, tail: str) -> None: """Create a Bone instance Parameters ---------- skel : Skeleton Skeleton to which the bone belongs name : str Name of the bone parent : str Name of the parent bone. This is the bone "above" and is one level closer to the root of the skeleton head : str Name of the head joint tail : str Name of the tail joint """ self._mh_bone = mhskel.Bone(skel, name, parent, head, tail) self.name = name self.skeleton = skel self.headJoint = head self.tailJoint = tail def getRelativeMatrix(self, offset: List[float] = [0, 0, 0]) -> np.ndarray: """_summary_ Parameters ---------- offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] Returns ------- np.ndarray _description_ """ return self._mh_bone.getRelativeMatrix(offset) def getRestMatrix(self, offset: List[float] = [0, 0, 0]) -> np.ndarray: """_summary_ Parameters ---------- offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] Returns ------- np.ndarray _description_ """ return self._mh_bone.getRestMatrix(offset) def getBindMatrix(self, offset: List[float] = [0, 0, 0]) -> np.ndarray: """_summary_ Parameters ---------- offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] Returns ------- np.ndarray _description_ """ return self._mh_bone.getBindMatrix(offset)[1] class Skeleton: """Skeleton which can be imported using the HumanGenerator extension. Provides root bone(s), which have a tree of children that can be traversed to get the data for the entire rig. Attributes ---------- name : str Name of the skeleton rig, by default "Skeleton" roots : list of Bone Root bones. Bones which have children that can be traversed to constitute the entire skeleton. joint_paths : list of: str Paths to joints in the stage hierarchy that are used as joint indices joint_names : list of: str List of joint names in USD (breadth-first traversal) order. It is important that joints be ordered this way so that their indices can be used for skinning / weighting. """ def __init__(self, name="Skeleton") -> None: """Create a skeleton instance Parameters ---------- name : str, optional Name of the skeleton, by default "Skeleton" """ # Set the skeleton to the makehuman default _mh_skeleton = MHCaller.human.getSkeleton() self._rel_transforms = [] self._bind_transforms = [] self.roots = _mh_skeleton.roots self.joint_paths = [] self.joint_names = [] self.name = name def addBone(self, name: str, parent: str, head: str, tail: str) -> Bone: """Add a new bone to the Skeleton Parameters ---------- name : str Name of the new bone parent : str Name of the parent bone under which to put the new bone head : str Name of the joint at the head of the new bone tail : str Name of the joint at the tail of the new bone Returns ------- Bone The bone which has been added to the skeleton """ _bone = Bone(self, name, parent, head, tail) # HACK Bone() creates a new Bone for _mh_bone by default. How can we # avoid doing this twice without revealing it to the user? _bone._mh_bone = self._mh_skeleton.addBone(name, parent, head, tail) return _bone def add_to_stage(self, stage: Usd.Stage, skel_root_path: str, offset: List[float] = [0, 0, 0], new_root_bone: bool = False): """Adds the skeleton to the USD stage Parameters ---------- stage : Usd.Stage Stage in which to create skeleton prims skelroot_path : str Path to the human root prim in the stage offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] new_root_bone : bool, optional Whether or not to prepend a new root at the origin, by default False """ root_bone = self.roots[0] if new_root_bone: root_bone = self.prepend_root(root_bone) self.setup_skeleton(root_bone, offset=offset) skeleton_path = skel_root_path + "/Skeleton" usdSkel = UsdSkel.Skeleton.Define(stage, skeleton_path) # add joints to skeleton by path attribute = usdSkel.GetJointsAttr() # exclude root attribute.Set(self.joint_paths) # Add bind transforms to skeleton usdSkel.CreateBindTransformsAttr(self._bind_transforms) # setup rest transforms in joint-local space usdSkel.CreateRestTransformsAttr(self._rel_transforms) return usdSkel def prepend_root(self, oldRoot: Bone, newroot_name: str = "RootJoint", offset: List[float] = [0, 0, 0]) -> Bone: """Adds a new root bone to the head of a skeleton, ahead of the existing root bone. Parameters ---------- oldRoot : Bone The original MakeHuman root bone newroot_name : str, optional The name for the new root bone, by default "RootJoint" offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] Returns ------- newRoot : Bone The new root bone of the Skeleton """ # make a "super-root" bone, parent to the root, with identity transforms so # we can abide by Lina Halper's animation retargeting guidelines: # https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_animation-retargeting.html newRoot = self.addBone( newroot_name, None, "newRoot_head", oldRoot.tailJoint) oldRoot.parent = newRoot newRoot.headPos -= offset newRoot.build() newRoot.children.append(oldRoot) return newRoot def _process_bone(self, bone: Bone, path: str, offset: List[float] = [0, 0, 0]) -> None: """Get the name, path, relative transform, and bind transform of a joint and add its values to the lists of stored values Parameters ---------- bone : Bone The bone to process for Usd path : str Path to the parent of this bone offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] """ # sanitize the name for USD paths name = sanitize(bone.name) path += name self.joint_paths.append(path) # store original name for later joint weighting self.joint_names.append(bone.name) # Get matrix for joint transform relative to its parent. Move to offset # to match mesh transform in scene relxform = bone.getRelativeMatrix(offsetVect=offset) # Transpose the matrix as USD stores transforms in row-major format relxform = relxform.transpose() # Convert type for USD and store relative_transform = Gf.Matrix4d(relxform.tolist()) self._rel_transforms.append(relative_transform) # Get matrix which represents a joints transform in its binding position # for binding to a mesh. Move to offset to match mesh transform. # getBindMatrix() returns a tuple of the bind matrix and the bindinv # matrix. Since omniverse uses row-major format, we can just use the # already transposed bind matrix. bxform = bone.getBindMatrix(offsetVect=offset) # Convert type for USD and store bind_transform = Gf.Matrix4d(bxform[1].tolist()) # bind_transform = Gf.Matrix4d().SetIdentity() TODO remove self._bind_transforms.append(bind_transform) def setup_skeleton(self, bone: Bone, offset: List[float] = [0, 0, 0]) -> None: """Traverse the imported skeleton and get the data for each bone for adding to the stage Parameters ---------- bone : Bone The root bone at which to start traversing the imported skeleton. offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] """ # Setup a breadth-first search of our skeleton as a tree # Use the new root of the imported skeleton as the root bone of our tree visited = [] # List to keep track of visited bones. queue = [] # Initialize a queue path_queue = [] # Keep track of paths in a parallel queue visited.append(bone) queue.append(bone) name = sanitize(bone.name) path_queue.append(name + "/") # joints are relative to the root, so we don't prepend a path for the root self._process_bone(bone, "", offset=offset) # Traverse skeleton (breadth-first) and store joint data while queue: v = queue.pop(0) path = path_queue.pop(0) for neighbor in v.children: if neighbor not in visited: visited.append(neighbor) queue.append(neighbor) name = sanitize(neighbor.name) path_queue.append(path + name + "/") self._process_bone(neighbor, path, offset) def update_in_scene(self, stage: Usd.Stage, skel_root_path: str, offset: List[float] = [0, 0, 0]): """Resets the skeleton values in the stage, updates the skeleton from makehuman. Parameters ---------- stage : Usd.Stage The stage in which to update the skeleton skel_root_path : str The path to the skeleton root in the stage offset : List[float], optional Geometric translation to apply, by default [0, 0, 0] Returns ------- UsdSkel.Skeleton The updated skeleton in USD """ # Get the skeleton from makehuman _mh_skeleton = MHCaller.human.getSkeleton() # Clear out any existing data self._rel_transforms = [] self._bind_transforms = [] self.joint_paths = [] self.joint_names = [] # Get the root bone(s) of the skeleton self.roots = _mh_skeleton.roots # Overwrite the skeleton in the stage with the new skeleton return self.add_to_stage(stage, skel_root_path, offset)
11,468
Python
33.032641
128
0.586327
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/__init__.py
from .extension import * from .human import Human
49
Python
23.999988
24
0.795918
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/materials.py
from typing import List from module3d import Object3D from pxr import Usd, UsdGeom, UsdShade, Sdf def get_mesh_texture(mh_mesh: Object3D): """Gets mesh diffuse texture from a Makehuman mesh object Parameters ---------- mh_mesh : Object3D A Makehuman mesh object. Contains path to bound material/textures Returns ------- Tuple (str,str) Returns the path to a texture on disk, and a name for the texture Returns (None, None) if no texture exists """ # TODO return additional maps (AO, roughness, normals, etc) material = mh_mesh.material texture = material.diffuseTexture name = material.name if texture: return texture, name else: return (None, None) def create_material(diffuse_image_path: str, name: str, root_path: str, stage: Usd.Stage): """Create OmniPBR Material with specified diffuse texture Parameters ---------- diffuse_image_path : str Path to diffuse texture on disk name : str Material name root_path : str Root path under which to place material scope stage : Usd.Stage USD stage into which to add the material Returns ------- UsdShade.Material Material with diffuse texture applied """ materialScopePath = root_path + "/Materials" # Check for a scope in which to keep materials. If it doesn't exist, make # one scopePrim = stage.GetPrimAtPath(materialScopePath) if scopePrim.IsValid() is False: UsdGeom.Scope.Define(stage, materialScopePath) # Create material (omniPBR). materialPath = materialScopePath + "/" + name material = UsdShade.Material.Define(stage, materialPath) # Store shaders inside their respective material path shaderPath = materialPath + "/Shader" # Create shader shader = UsdShade.Shader.Define(stage, shaderPath) # Use OmniPBR as a source to define our shader shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.GetPrim().CreateAttribute( "info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform, ).Set("OmniPBR") # Set Diffuse texture. diffTexIn = shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset) diffTexIn.Set(diffuse_image_path) diffTexIn.GetAttr().SetColorSpace("sRGB") # Set Diffuse value. TODO make default color NVIDIA Green # diffTintIn = shader.CreateInput("diffuse_tint", Sdf.ValueTypeNames.Color3f) # diffTintIn.Set((0.9, 0.9, 0.9)) # Connect Material to Shader. mdlOutput = material.CreateSurfaceOutput("mdl") mdlOutput.ConnectToSource(shader, "out") return material def bind_material(mesh_path: Sdf.Path, material: UsdShade.Material, stage: Usd.Stage): """Bind a material to a mesh Parameters ---------- mesh_path : Sdf.Path The USD formatted path to a mesh prim material : UsdShade.Material USD material object stage : Usd.Stage Stage in which to find mesh prim """ # Get the mesh prim meshPrim = stage.GetPrimAtPath(mesh_path) # Bind the mesh UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
3,210
Python
29.292453
90
0.669782
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/ext_ui.py
import omni.ui as ui from typing import List, TypeVar, Union, Callable from dataclasses import dataclass, field from . import styles from .mhcaller import MHCaller from pxr import Usd import os import inspect import makehuman import targets from siborg.create.human.shared import data_path class SliderEntry: """Custom UI element that encapsulates a labeled slider and field Attributes ---------- label : str Label to display for slider/field model : ui.SimpleFloatModel Model to publish changes to fn : object Function to run when updating the human after changes are made image: str Path on disk to an image to display step : float Division between values for the slider min : float Minimum value max : float Maximum value default : float Default parameter value """ def __init__( self, label: str, model: ui.SimpleFloatModel, fn: object, image: str = None, step: float = 0.01, min: float = None, max: float = None, default: float = 0, ): """Constructs an instance of SliderEntry Parameters ---------- label : str Label to display for slider/field model : ui.SimpleFloatModel Model to publish changes to fn : object Function to run when changes are made image: str, optional Path on disk to an image to display. By default None step : float, optional Division between values for the slider, by default 0.01 min : float, optional Minimum value, by default None max : float, optional Maximum value, by default None default : float, optional Default parameter value, by default 0 """ self.label = label self.model = model self.fn = fn self.step = step self.min = min self.max = max self.default = default self.image = image self._build_widget() def _build_widget(self): """Construct the UI elements""" with ui.HStack(height=0, style=styles.sliderentry_style): # If an image is available, display it if self.image: ui.Image(self.image, height=75, style={"border_radius": 5}) # Stack the label and slider on top of each other with ui.VStack(spacing = 5): ui.Label( self.label, height=15, alignment=ui.Alignment.CENTER, name="label_param", ) # create a floatdrag (can be used as a slider or an entry field) to # input parameter values self.drag = ui.FloatDrag(model=self.model, step=self.step) # Limit drag values to within min and max if provided if self.min is not None: self.drag.min = self.min if self.max is not None: self.drag.max = self.max @dataclass class Param: """Dataclass to store SliderEntry parameter data Attributes ---------- name: str The name of the parameter. Used for labeling. full_name: str The full name of the parameter. Used for referencing fn: object The method to execute when making changes to the parameter image: str, optional The path to the image to use for labeling. By default None min: float, optional The minimum allowed value of the parameter. By default 0 max: float The maximum allowed value of the parameter. By default 1 default: float The default value of the parameter. By default 0.5 value : ui.SimpleFloatModel The model to track the current value of the parameter. By default None """ name: str full_name: str fn: object image: str = None min: float = 0 max: float = 1 default: float = 0.5 value: ui.SimpleFloatModel = None class SliderEntryPanelModel: """Provides a model for referencing SliderEntryPanel data. References models for each individual SliderEntry widget in the SliderEntryPanel widget. Attributes ---------- params : list of `Param` List of parameter objects. Each contains a float model to track the current value toggle : ui.SimpleBoolModel Tracks whether or not the human should update immediately when changes are made instant_update : Callable A function to call when instant update is toggled subscriptions : list of `Subscription` List of event subscriptions triggered by editing a SliderEntry """ def __init__(self, params: List[Param], toggle: ui.SimpleBoolModel = None, instant_update: Callable = None): """Constructs an instance of SliderEntryPanelModel and instantiates models to hold parameter data for individual SliderEntries Parameters ---------- params : list of `Param` A list of parameter objects, each of which contains the data to create a SliderEntry widget and a model to track the current value toggle : ui.SimpleBoolModel, optional Tracks whether or not the human should update immediately when changes are made, by default None instant_update : Callable A function to call when instant update is toggled """ self.params = [] """Param objects corresponding to each SliderEntry widget""" self.changed_params = [] """Params o SliderEntry widgets that have been changed""" self.toggle = toggle self.instant_update = instant_update self.subscriptions = [] """List of event subscriptions triggered by editing a SliderEntry""" for p in params: self.add_param(p) def add_param(self, param: Param): """Adds a parameter to the SliderEntryPanelModel. Subscribes to the parameter's model to check for editing changes Parameters ---------- param : Param The Parameter object from which to create the subscription """ # Create a model to track the current value of the parameter. Set the value to the default param.value = ui.SimpleFloatModel(param.default) # Add the parameter to the list of parameters self.params.append(param) # Subscribe to changes in parameter editing self.subscriptions.append( param.value.subscribe_end_edit_fn( lambda m: self._sanitize_and_run(param)) ) def reset(self): """Resets the values of each floatmodel to parameter default for UI reset """ for param in self.params: param.value.set_value(param.default) def _sanitize_and_run(self, param: Param): """Make sure that values are within an acceptable range and then add the parameter to the list of changed parameters Parameters ---------- param : Param Parameter object which contains acceptable value bounds and references the function to run """ m = param.value # Get the value from the slider model getval = m.get_value_as_float # Set the value to the min or max if it goes under or over respectively if getval() < param.min: m.set_value(param.min) if getval() > param.max: m.set_value(param.max) # Check if the parameter is already in the list of changed parameters. If so, remove it. # Then, add the parameter to the list of changed parameters if param in self.changed_params: self.changed_params.remove(param) self.changed_params.append(param) # If instant update is toggled on, add the changes to the stage instantly if self.toggle.get_value_as_bool(): # Apply the changes self.apply_changes() # Run the instant update function self.instant_update() def apply_changes(self): """Apply the changes made to the parameters. Runs the function associated with each parameter using the value from the widget """ for param in self.changed_params: param.fn(param.value.get_value_as_float()) # Clear the list of changed parameters self.changed_params = [] def destroy(self): """Destroys the instance of SliderEntryPanelModel. Deletes event subscriptions. Important for preventing zombie-UI and unintended behavior when the extension is reloaded. """ self.subscriptions = None class SliderEntryPanel: """A UI widget providing a labeled group of slider entries Attributes ---------- model : SliderEntryPanelModel Model to hold parameters for each slider label : str Display title for the group. Can be none if no title is desired. """ def __init__(self, model: SliderEntryPanelModel, label: str = None): """ Parameters ---------- model : SliderEntryPanelModel Model to hold parameters label : str, Optional Display title for the group, by default None """ self.label = label self.model = model self._build_widget() def _build_widget(self): """Construct the UI elements""" # Layer widgets on top of a rectangle to create a group frame with ui.ZStack(style=styles.panel_style, height=0): ui.Rectangle(name="group_rect") with ui.VStack(name="contents", spacing = 8): # If the panel has a label, show it if self.label: ui.Label(self.label, height=0) # Create a slider entry for each parameter for param in self.model.params: SliderEntry( param.name, param.value, param.fn, image=param.image, min=param.min, max=param.max, default=param.default, ) def destroy(self): """Destroys the instance of SliderEntryPanel. Executes the destructor of the SliderEntryPanel's SliderEntryPanelModel instance. """ self.model.destroy() class ParamPanelModel(ui.AbstractItemModel): def __init__(self, toggle: ui.SimpleBoolModel, **kwargs): """Constructs an instance of ParamPanelModel, which stores data for a ParamPanel. Parameters ---------- toggle : ui.SimpleBoolModel Model to track whether changes should be instant """ super().__init__(**kwargs) # model to track whether changes should be instant self.toggle = toggle # Reference to models for each modifier/parameter. The models store modifier # data for reference in the UI, and track the values of the sliders self.models = [] class ParamPanel(ui.Frame): """UI Widget for displaying and modifying human parameters Attributes ---------- model : ParamPanelModel Stores data for the panel toggle : ui.SimpleBoolModel Model to track whether changes should be instant models : list of SliderEntryPanelModel Models for each group of parameter sliders """ def __init__(self, model: ParamPanelModel, instant_update : Callable = None, **kwargs): """Constructs an instance of ParamPanel. Panel contains a scrollable list of collapseable groups. These include a group of macros (which affect multiple modifiers simultaneously), as well as groups of modifiers for different body parts. Each modifier can be adjusted using a slider or doubleclicking to enter values directly. Values are restricted based on the limits of a particular modifier. Parameters ---------- model: ParamPanelModel Stores data for the panel. Contains a toggle model to track whether changes should be instant instant_update : Callable Function to call when a parameter is changed (if instant update is toggle on) """ # Subclassing ui.Frame allows us to use styling on the whole widget super().__init__(**kwargs) self.model = model self.toggle = model.toggle # If no instant update function is passed, use a dummy function and do nothing self.instant_update = instant_update if instant_update else lambda *args: None self.models = model.models self.set_build_fn(self._build_widget) def _build_widget(self): """Build widget UI """ Modifier = TypeVar('Modifier') def modifier_param(m: Modifier): """Generate a parameter data object from a human modifier, Parameters ---------- m : Modifier Makehuman Human modifier object. Represents a set of targets to apply to the human when modifying Returns ------- Param Parameter data object holding all the modifier data needed to build UI elements """ # print(m.name) # Guess a suitable title from the modifier name tlabel = m.name.split("-") if "|" in tlabel[len(tlabel) - 1]: tlabel = tlabel[:-1] if len(tlabel) > 1 and tlabel[0] == m.groupName: label = tlabel[1:] else: label = tlabel label = " ".join([word.capitalize() for word in label]) # Guess a suitable image path from modifier name tlabel = m.name.replace("|", "-").split("-") image = modifier_image(("%s.png" % "-".join(tlabel)).lower()) # Store modifier info in dataclass for building UI elements return Param( label, m.fullName, m.updateValue, image=image, min=m.getMin(), max=m.getMax(), default=m.getDefaultValue(), ) def group_params(group: str): """Creates a list of parameters for all the modifiers in the given group Parameters ---------- group : str The name name of a modifier group Returns ------- List of Param A list of all the parameters built from modifiers in the group """ params = [modifier_param(m) for m in MHCaller.human.getModifiersByGroup(group)] return params def build_macro_frame(): """Builds UI widget for the group of macro modifiers (which affect multiple individual modifiers simultaneously). This includes: + Gender + Age + Muscle + Weight + Height + Proportions Parameters that affect how much the human resembles a particular racial group: + African + Asian + Caucasian """ # Shorten human reference for convenience human = MHCaller.human # Explicitly create parameters for panel of macros (general modifiers that # affect a group of targets). Otherwise these look bad. Creates a nice # panel to have open by default macro_params = ( Param("Gender", "macrodetails/Gender", human.setGender), Param("Age", "macrodetails/Age", human.setAge), Param("Muscle", "macrodetails-universal/Muscle", human.setMuscle), Param("Weight", "macrodetails-universal/Weight", human.setWeight), Param("Height", "macrodetails-height/Height", human.setHeight), Param("Proportions", "macrodetails-proportions/BodyProportions", human.setBodyProportions), ) # Create a model for storing macro parameter data macro_model = SliderEntryPanelModel(macro_params, self.toggle, self.instant_update) # Separate set of race parameters to also be included in the Macros group # TODO make race parameters automatically normalize in UI race_params = ( Param("African", "macrodetails/African", human.setAfrican), Param("Asian", "macrodetails/Asian", human.setAsian), Param("Caucasian", "macrodetails/Caucasian", human.setCaucasian), ) # Create a model for storing race parameter data race_model = SliderEntryPanelModel(race_params, self.toggle, self.instant_update) self.models.append(macro_model) self.models.append(race_model) # Create category widget for macros with ui.CollapsableFrame("Macros", style=styles.frame_style, height=0, collapsed=True): with ui.VStack(): # Create panels for macros and race self.panels = ( SliderEntryPanel(macro_model, label="General"), SliderEntryPanel(race_model, label="Race"), ) # The scrollable list of modifiers with ui.ScrollingFrame(): with ui.VStack(): # Add the macros frame first build_macro_frame() # Create a set of all modifier groups that include macros macrogroups = [ g for g in MHCaller.human.modifierGroups if "macrodetails" in g] macrogroups = set(macrogroups) # Remove macro groups from list of modifier groups as we have already # included them explicitly allgroups = set( MHCaller.human.modifierGroups).difference(macrogroups) for group in allgroups: # Create a collapseable frame for each modifier group with ui.CollapsableFrame(group.capitalize(), style=styles.frame_style, collapsed=True): # Model to hold panel parameters model = SliderEntryPanelModel( group_params(group), self.toggle,self.instant_update) self.models.append(model) # Create panel of slider entries for modifier group SliderEntryPanel(model) def reset(self): """Reset every SliderEntryPanel to set UI values to defaults """ for model in self.models: model.reset() def load_values(self, human_prim: Usd.Prim): """Load values from the human prim into the UI. Specifically, this function loads the values of the modifiers from the prim and updates any which have changed. Parameters ---------- HumanPrim : Usd.Prim The USD prim representing the human """ # Make the prim exists if not human_prim.IsValid(): return # Reset the UI to defaults self.reset() # Get the data from the prim humandata = human_prim.GetCustomData() modifiers = humandata.get("Modifiers") # Set any changed values in the models for SliderEntryPanelModel in self.models: for param in SliderEntryPanelModel.params: if param.full_name in modifiers: param.value.set_value(modifiers[param.full_name]) def update_models(self): """Update all models""" for model in self.models: model.apply_changes() def destroy(self): """Destroys the ParamPanel instance as well as the models attached to each group of parameters """ super().destroy() for model in self.models: model.destroy() class NoSelectionNotification: """ When no human selected, show notification. """ def __init__(self): self._container = ui.ZStack() with self._container: ui.Rectangle() with ui.VStack(spacing=10): ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() ui.ImageWithProvider( data_path('human_icon.png'), width=192, height=192, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT ) ui.Spacer() self._message_label = ui.Label( "No human is current selected.", height=0, alignment=ui.Alignment.CENTER ) self._suggestion_label = ui.Label( "Select a human prim to see its properties here.", height=0, alignment=ui.Alignment.CENTER ) @property def visible(self) -> bool: return self._container.visible @visible.setter def visible(self, value) -> None: self._container.visible = value def set_message(self, message: str) -> None: messages = message.split("\n") self._message_label.text = messages[0] self._suggestion_label.text = messages[1] def modifier_image(name : str): """Guess the path to a modifier's corresponding image on disk based on the name of the modifier. Useful for building UI for list of modifiers. Parameters ---------- name : str Name of the modifier Returns ------- str The path to the image on disk """ if name is None: # If no modifier name is provided, we can't guess the file name return None name = name.lower() # Return the modifier path based on the modifier name # TODO determine if images can be loaded from the Makehuman module stored in # site-packages so we don't have to include the data twice return os.path.join(os.path.dirname(inspect.getfile(makehuman)),targets.getTargets().images.get(name, name))
22,469
Python
35.359223
119
0.582936
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/shared.py
from pathlib import Path import os # Shared methods that are useful to several modules def data_path(path): """Returns the absolute path of a path given relative to "exts/<omni.ext>/data" Parameters ---------- path : str Relative path Returns ------- str Absolute path """ # Uses an absolute path, and then works its way up the folder directory to find the data folder data = os.path.join(str(Path(__file__).parents[3]), "data", path) return data def sanitize(s: str): """Sanitize strings for use a prim names. Strips and replaces illegal characters. Parameters ---------- s : str Input string Returns ------- s : str Primpath-safe output string """ # List of illegal characters # TODO create more comprehensive list # TODO switch from blacklisting illegal characters to whitelisting valid ones illegal = (".", "-") for c in illegal: # Replace illegal characters with underscores s = s.replace(c, "_") return s
1,072
Python
21.829787
99
0.613806
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/window.py
from .ext_ui import ParamPanelModel, ParamPanel, NoSelectionNotification from .browser import MHAssetBrowserModel, AssetBrowserFrame from .human import Human from .mhcaller import MHCaller from .styles import window_style, button_style import omni.ui as ui import omni.kit.ui import omni import carb WINDOW_TITLE = "Human Generator" MENU_PATH = f"Window/{WINDOW_TITLE}" class MHWindow(ui.Window): """ Main UI window. Contains all UI widgets. Extends omni.ui.Window. Attributes ----------- panel : HumanPanel A widget that includes panels for modifiers, listing/removing applied proxies, and executing human creation and updates browser: AssetBrowserFrame A browser for MakeHuman assets, including clothing, hair, and skeleton rigs. """ def __init__(self, title): """Constructs an instance of MHWindow Parameters ---------- menu_path : str The path to the menu item that opens the window """ super().__init__(title) # Holds the state of the realtime toggle self.toggle_model = ui.SimpleBoolModel() # Holds the state of the parameter list self.param_model = ParamPanelModel(self.toggle_model) # Keep track of the human self._human = Human() # A model to hold browser data self.browser_model = MHAssetBrowserModel( self._human, filter_file_suffixes=["mhpxy", "mhskel", "mhclo"], timeout=carb.settings.get_settings().get( "/exts/siborg.create.human.browser.asset/data/timeout" ), ) # Subscribe to selection events on the message bus bus = omni.kit.app.get_app().get_message_bus_event_stream() selection_event = carb.events.type_from_string("siborg.create.human.human_selected") self._selection_sub = bus.create_subscription_to_push_by_type(selection_event, self._on_selection_changed) self.frame.set_build_fn(self._build_ui) def _build_ui(self): spacer_width = 3 with self.frame: # Widgets are built starting on the left with ui.HStack(style=window_style): # Widget to show if no human is selected self.no_selection_notification = NoSelectionNotification() self.property_panel = ui.HStack(visible=False) with self.property_panel: with ui.ZStack(width=0): # Draggable splitter with ui.Placer(offset_x=self.frame.computed_content_width/1.8, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=spacer_width, name="splitter") with ui.HStack(): # Left-most panel is a browser for MakeHuman assets. It includes # a reference to the list of applied proxies so that an update # can be triggered when new assets are added self.browser = AssetBrowserFrame(self.browser_model) ui.Spacer(width=spacer_width) with ui.HStack(): with ui.VStack(): self.param_panel = ParamPanel(self.param_model,self.update_human) with ui.HStack(height=0): # Toggle whether changes should propagate instantly ui.ToolButton(text = "Update Instantly", model = self.toggle_model) with ui.VStack(width = 100, style=button_style): # Creates a new human in scene and resets modifiers and assets ui.Button( "New Human", clicked_fn=self.new_human, ) # Updates current human in omniverse scene self.update_button = ui.Button( "Update Human", clicked_fn=self.update_human, enabled=False, ) # Resets modifiers and assets on selected human self.reset_button = ui.Button( "Reset Human", clicked_fn=self.reset_human, enabled=False, ) def _on_selection_changed(self, event): """Callback for human selection events Parameters ---------- event : carb.events.Event The event that was pushed to the event stream. Contains payload data with the selected prim path, or "None" if no human is selected """ # Get the stage stage = omni.usd.get_context().get_stage() prim_path = event.payload["prim_path"] # If a valid human prim is selected, if not prim_path or not stage.GetPrimAtPath(prim_path): # Hide the property panel self.property_panel.visible = False # Show the no selection notification self.no_selection_notification.visible = True # Deactivate the update and reset buttons self.update_button.enabled = False self.reset_button.enabled = False else: # Show the property panel self.property_panel.visible = True # Hide the no selection notification self.no_selection_notification.visible = False # Activate the update and reset buttons self.update_button.enabled = True self.reset_button.enabled = True # Get the prim from the path in the event payload prim = stage.GetPrimAtPath(prim_path) # Update the human in MHCaller self._human.set_prim(prim) # Update the list of applied modifiers self.param_panel.load_values(prim) def new_human(self): """Creates a new human in the scene and selects it""" # Reset the human class self._human.reset() # Create a new human self._human.prim = self._human.add_to_scene() # Get selection. selection = omni.usd.get_context().get_selection() # Select the new human. selection.set_selected_prim_paths([self._human.prim_path], True) def update_human(self): """Updates the current human in the scene""" # Collect changed values from the parameter panel self.param_panel.update_models() # Update the human in the scene self._human.update_in_scene(self._human.prim_path) def reset_human(self): """Resets the current human in the scene""" # Reset the human self._human.reset() # Delete the proxy prims self._human.delete_proxies() # Update the human in the scene and reset parameter widgets self.update_human() def destroy(self): """Called when the window is destroyed. Unsuscribes from human selection events""" self._selection_sub.unsubscribe() self._selection_sub = None super().destroy()
7,214
Python
36
124
0.570834
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/browser/delegate.py
import carb from omni.kit.browser.folder.core.models.folder_browser_item import FileDetailItem import omni.ui as ui import omni.kit.app from omni.kit.browser.core import get_legacy_viewport_interface from omni.kit.browser.folder.core import FolderDetailDelegate from .model import MHAssetBrowserModel, AssetDetailItem from ..mhcaller import MHCaller import asyncio from pathlib import Path from typing import Optional # TODO remove unused imports # TODO remove CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") class AssetDetailDelegate(FolderDetailDelegate): """Delegate to show Makehuman asset item in detail view and execute drag-and- drop and doubleclick behavior. Attributes ---------- model : MHAssetBrowserModel Model that stores AssetBrowser data """ def __init__(self, model: MHAssetBrowserModel): """Constructs an instance of AssetDetailDelegate, which handles execution of functions Parameters ---------- model : MHAssetBrowserModel Makehuman asset browser model """ super().__init__(model=model) # Reference to the browser asset model self.model = model # Reference to the human self._human = model.human self._settings = carb.settings.get_settings() # The context menu that opens on right_click self._context_menu: Optional[ui.Menu] = None self._action_item: Optional[AssetDetailItem] = None self._viewport = None self._drop_helper = None def destroy(self): """Destructor for AssetDetailDelegate. Removes references and destroys superclass.""" self._viewport = None self._drop_helper = None super().destroy() def get_thumbnail(self, item : AssetDetailItem) -> str: """Get the thumbnail for an asset Parameters ---------- item : AssetDetailItem The item in the browser for which we are getting a thumbnail Returns ------- str Path to the thumbnail image """ return item.thumbnail def on_drag(self, item: AssetDetailItem) -> str: """Displays a translucent UI widget when an asset is dragged Parameters ---------- item : AssetDetailItem The item being dragged Returns ------- str The path on disk of the item being dragged (passed to whatever widget accepts the drop) """ thumbnail = self.get_thumbnail(item) icon_size = 128 with ui.VStack(width=icon_size): if thumbnail: ui.Spacer(height=2) with ui.HStack(): ui.Spacer() ui.ImageWithProvider( thumbnail, width=icon_size, height=icon_size ) ui.Spacer() ui.Label( item.name, word_wrap=False, elided_text=True, skip_draw_when_clipped=True, alignment=ui.Alignment.TOP, style_type_name_override="GridView.Item", ) # Return the path of the item being dragged so it can be accessed by # the widget on which it is dropped return item.url def on_double_click(self, item: FileDetailItem): """Method to execute when an asset is doubleclicked. Adds the asset to the human. Parameters ---------- item : FileDetailItem The item that has been doubleclicked """ self._human.add_item(item.url)
3,725
Python
30.05
93
0.595973
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/browser/downloader.py
from typing import Callable import carb import aiohttp import omni.client import os, zipfile class Downloader: """Downloads and unzips remote files and tracks download status/progress""" def __init__(self, log_fn : Callable[[float], None]) -> None: """Construct an instance of Downloader. Assigns the logging function and sets initial is_downloading status Parameters ---------- log_fn : Callable[[float], None] Function to which to pass progress. Recieves a proportion that represents the amount downloaded """ self._is_downloading = False self._log_fn = log_fn async def download(self, url : str, dest_url : str) -> None: """Download a given url to disk and unzip it Parameters ---------- url : str Remote URL to fetch dest_url : str Local path at which to write and then unzip the downloaded files Returns ------- dict of str, Union[omni.client.Result, str] Error message and location on disk """ ret_value = {"url": None} async with aiohttp.ClientSession() as session: self._is_downloading = True content = bytearray() # Download content from the given url downloaded = 0 async with session.get(url) as response: size = int(response.headers.get("content-length", 0)) if size > 0: async for chunk in response.content.iter_chunked(1024 * 512): content.extend(chunk) downloaded += len(chunk) if self._log_fn: self._log_fn(float(downloaded) / size) else: if self._log_fn: self._log_fn(0) content = await response.read() if self._log_fn: self._log_fn(1) if response.ok: # Write to destination filename = os.path.basename(url.split("?")[0]) dest_url = f"{dest_url}/{filename}" (result, list_entry) = await omni.client.stat_async(dest_url) ret_value["status"] = await omni.client.write_file_async(dest_url, content) ret_value["url"] = dest_url if ret_value["status"] == omni.client.Result.OK: # TODO handle file already exists pass z = zipfile.ZipFile(dest_url, 'r') z.extractall(os.path.dirname(dest_url)) else: carb.log_error(f"[access denied: {url}") ret_value["status"] = omni.client.Result.ERROR_ACCESS_DENIED self._is_downloading = False return ret_value def not_downloading(self): return not self._is_downloading
2,935
Python
37.12987
115
0.529131
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/browser/__init__.py
from omni.kit.browser.folder.core import FolderBrowserWidget from .delegate import AssetDetailDelegate from .model import MHAssetBrowserModel from .options_menu import FolderOptionsMenu import omni.ui as ui class AssetBrowserFrame: """A widget to browse and select Makehuman assets Attributes ---------- mhcaller : MHCaller Wrapper object for Makehuman functions """ def __init__(self, model: MHAssetBrowserModel, **kwargs): """Constructs an instance of AssetBrowserFrame. This is a browser that displays available Makehuman assets (skeletons/rigs, proxies) and allows a user to apply them to the human. Parameters ---------- model : MHAssetBrowserModel A model to hold browser data """ self.model = model self.build_widget() def build_widget(self): """Build UI widget""" # The delegate to execute browser actions self._delegate = AssetDetailDelegate(self.model) # Drop down menu to hold options self._options_menu = FolderOptionsMenu() with ui.VStack(): self._widget = FolderBrowserWidget( self.model, detail_delegate=self._delegate, options_menu=self._options_menu) ui.Separator(height=2) # Progress bar to show download progress (initially hidden) self._progress_bar = ui.ProgressBar(height=20, visible=False) self._options_menu.bind_progress_bar(self._progress_bar)
1,520
Python
34.372092
92
0.653289
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/browser/model.py
import os from typing import List, Union import carb.settings import omni.kit.commands from siborg.create.human.mhcaller import MHCaller import omni.usd from omni.kit.browser.core import DetailItem from omni.kit.browser.folder.core import ( FolderBrowserModel, FileDetailItem, BrowserFile, ) from siborg.create.human.shared import data_path from ..human import Human class AssetDetailItem(FileDetailItem): """Represents Makehuman asset detail item """ def __init__(self, file: BrowserFile): """Constructs an instance of AssetDetailItem Parameters ---------- file : BrowserFile BrowserFile object from which to create detail item """ dirs = file.url.split("/") name = dirs[-1] super().__init__(name, file.url, file, file.thumbnail) class MHAssetBrowserModel(FolderBrowserModel): """Represents Makehuman asset browser model """ def __init__(self, human: Human, *args, **kwargs): """Constructs an instance of MHAssetBrowserModel Parameters ---------- human : Human The human to which to add assets """ self.human = human super().__init__( *args, show_category_subfolders=True, hide_file_without_thumbnails=False, **kwargs, ) # Add the data path as the root folder from which to build a collection super().append_root_folder(data_path(""), name="MakeHuman") def create_detail_item( self, file: BrowserFile ) -> Union[FileDetailItem, List[FileDetailItem]]: """Create detail item(s) from a file. A file may include multiple detail items. Overwrite parent function to add thumbnails. Parameters ---------- file : BrowserFile File object to create detail item(s) Returns ------- Union[FileDetailItem, List[FileDetailItem]] FileDetailItem or list of items created from file """ dirs = file.url.split("/") name = dirs[-1] # Get the file name without the extension filename_noext = os.path.splitext(file.url)[0] thumb = filename_noext + ".thumb" thumb_png = filename_noext + ".png" # If there is already a PNG, get it. If not, rename the thumb file to a PNG # (They are the same format just with different extensions). This lets us # use Makehuman's asset thumbnails if os.path.exists(thumb_png): thumb = thumb_png elif os.path.exists(thumb): os.rename(thumb, thumb_png) thumb = thumb_png else: thumb = None return FileDetailItem(name, file.url, file, thumb)
2,789
Python
28.0625
83
0.603801
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/browser/options_menu.py
from omni.kit.browser.core import OptionMenuDescription, OptionsMenu from omni.kit.browser.folder.core.models.folder_browser_item import FolderCollectionItem import carb import asyncio from ..shared import data_path from .downloader import Downloader import omni.ui as ui class FolderOptionsMenu(OptionsMenu): """ Represent options menu used in material browser. """ def __init__(self): super().__init__() # Progress bar widget to show download progress self._progress_bar : ui.ProgressBar = None self.downloader = Downloader(self.progress_fn,) self._download_menu_desc = OptionMenuDescription( "Download Assets", clicked_fn=self._on_download_assets, get_text_fn=self._get_menu_item_text, enabled_fn=self.downloader.not_downloading ) self.append_menu_item(self._download_menu_desc) def destroy(self) -> None: super().destroy() def progress_fn(self, proportion: float): carb.log_info(f"Download is {int(proportion * 100)}% done") if self._progress_bar: self._progress_bar.model.set_value(proportion) def _get_menu_item_text(self) -> str: # Show download state if download starts if self.downloader._is_downloading: return "Download In Progress" return "Download Assets" def bind_progress_bar(self, progress_bar): self._progress_bar = progress_bar def _on_download_assets(self): # Show progress bar if self._progress_bar: self._progress_bar.visible = True loop = asyncio.get_event_loop() asyncio.run_coroutine_threadsafe(self._download(), loop) def _is_remove_collection_enabled(self) -> None: '''Don't allow removing the default collection''' if self._browser_widget is not None: return self._browser_widget.collection_index >= 1 else: return False def _on_remove_collection(self) -> None: if self._browser_widget is None or self._browser_widget.collection_index < 0: return else: browser_model = self._browser_widget.model collection_items = browser_model.get_collection_items() if browser_model.remove_collection(collection_items[self._browser_widget.collection_index]): # Update collection combobox and default none selected browser_model._item_changed(None) self._browser_widget.collection_index -= 1 def _hide_progress_bar(self): if self._progress_bar: self._progress_bar.visible = False async def _download(self): # Makehuman system assets url = "http://files.makehumancommunity.org/asset_packs/makehuman_system_assets/makehuman_system_assets_cc0.zip" # Smaller zip for testing # url = "https://download.tuxfamily.org/makehuman/asset_packs/shirts03/shirts03_ccby.zip" dest_url = data_path("") await self.downloader.download(url, dest_url) self._hide_progress_bar() self.refresh_collection() def refresh_collection(self): collection_item: FolderCollectionItem = self._browser_widget.collection_selection if collection_item: folder = collection_item.folder folder._timeout = 10 asyncio.ensure_future(folder.start_traverse())
3,422
Python
37.033333
119
0.643776
cadop/HumanGenerator/exts/siborg.create.human/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "0.0.2" preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # The title and description fields are primarily for displaying extension info in UI title = "HumanGenerator" description="Human Generator for Omniverse. Create and customize humans in your Omniverse scenes." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Services" feature = true # Keywords for the extension keywords = ["kit", "makehuman","human","character","generator","person"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.usd" = {} "omni.anim.skelJoint" = {} "omni.kit.browser.core" = {} "omni.kit.browser.folder.core" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "siborg.create.human" [settings] exts."siborg.create.human.browser.asset".instanceable = [] exts."siborg.create.human.browser.asset".timeout = 10 [python.pipapi] use_online_index = true # Use this to specify a list of additional repositories if your pip package is hosted somewhere other # than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument repositories = ["https://test.pypi.org/simple/"] requirements = ["makehuman==1.2.2"]
1,558
TOML
28.980769
105
0.734275
cadop/HumanGenerator/exts/siborg.create.human/docs/README.md
# Overview HumanGenerator generates parametric, rigged, outfitted humans in NVIDIA Omniverse. This project relies on the Makehuman project from https://github.com/makehumancommunity/makehuman. # Getting Started The easiest way to get started is using Omniverse Create. Navigate to the Extensions window and click on "Community". Search for `HumanGenerator` and you should see our extension show up. The extension may take a few minutes to install as it will download makehuman and install it in the Omniverse's local Python instance. For use, check out the walkthrough video on Github. ## License *Our license restrictions are due to the AGPL of MakeHuman. In line with the statements from MakeHuman, the targets and resulting characters are CC0, meaning you can use whatever you create for free, without restrictions. It is only the codebase that is AGPL.
871
Markdown
44.894734
259
0.797933
cadop/crowds/README.md
![preview](https://user-images.githubusercontent.com/11399119/226725400-fa9054e3-a13f-4a9f-8294-d08cbee51519.PNG) This repository is for the omniverse extension for crowd simulation. If you are looking for a project that can be run without omniverse, checkout [Python-only crowd simulation](https://github.com/cadop/warpcrowd) A crowd simulator API with a default demo scene. The main python API can be used in a few ways. There is an examples folder showing a few use-cases. Users can also switch between social forces and PAM as the crowds algorithm. The extension will load an populate some demo configuration. It will create an Xform called CrowdGoals. To add a goal for the crowd. Create an xform under the "CrowdGoals". We automatically check for those prims as the method of determing crowd goals. For every additional xform under CrowdGoals, we evenly split the crowd to assign those goals. There are two options for the crowd objects. The default uses geompoints, which is faster and runs its own integration of the forces for position and velocity. It does not interact with any physics in the scene. Alternatively the "Rigid Body" can be used, which creates physical spheres that interact with the scene. Press Play to see the crowd. The default number of demo agents is a 3x3 grid (9 agents). The current simulator in python may struggle above 25 agents, depending on CPU configuration. We plan to support more methods in the future, as well as more crowd simulators. Contributions are welcome.
1,525
Markdown
88.764701
348
0.796066
cadop/crowds/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
cadop/crowds/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
cadop/crowds/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/simulator.py
import numpy as np from numpy import random from omni.physx import get_physx_interface import omni import carb from pxr import UsdGeom, Gf, Sdf, UsdShade import warp as wp import copy import usdrt from siborg.simulate.crowd.crowds import CrowdConfig from siborg.simulate.crowd.models import socialforces from siborg.simulate.crowd.models import pam wp.init() from siborg.simulate.crowd.models import socialforces_warp as crowd_force class Simulator(CrowdConfig): def __init__(self, world=None): super().__init__() self.world = world # a default dt that is surely overwritten later self._dt = 1/60.0 # set radius self.radius = 0.7 self.radius_min = 0.5 self.radius_max = 1.0 # A subscription to the physics simulation, used when this class # is asked to manage the updates self._simulation_event = None # Will use a physics scene self.rigidbody = False self.use_pam = False self.on_gpu = False self.use_instancer = False self.add_jane = False self.use_heading = False # Tracks if user wants to update agent position on each sim step self.update_agents_sim = False self.update_viz = False self.instancer_paths = ["/World/PointInstancer_Bob", "/World/PointInstancer_Jane"] self.point_instancer_sets = [] self.agent_instance_path_bob = '/World/Scope/CrowdBob' self.agent_instance_path_jane = '/World/Scope/CrowdJane' self.instance_forward_vec = (1.0,0.0,0.0) # TODO get from instance object self.instance_up_vec = (0.0,1.0,0.0) # TODO Fix to be flexible later self.vel_epsilon = 0.05 self._get_world_up() def _get_world_up(self): stage = omni.usd.get_context().get_stage() up = UsdGeom.GetStageUpAxis(stage) if up =='X': self.world_up = 0 if up =='Y': self.world_up = 1 if up =='Z': self.world_up = 2 return def register_simulation(self): self._callbacks() # we need to update the agents, otherwise won't see these results self.update_agents_sim = True self.update_viz = True def _callbacks(self): self._simulation_event = get_physx_interface( ).subscribe_physics_step_events( self._on_simulation_update) def _unregister(self): try: self._simulation_event.unsubscribe() except: self._simulation_event = None def _on_simulation_update(self, dt): if self.agent_bodies is None: return self._dt = dt self.run() def set_xform_goal(self, p): '''set the goal based on a subscribed xform Example of usage watcher = omni.usd.get_watcher() self._goal_subscriber = watcher.subscribe_to_change_info_path( Sdf.Path('/World/Goal.xformOp:translate'), self.Sim.set_xform_goal) Parameters ---------- p : str(prim path) a subscribed path ''' stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(str(p).split('.')[0]) goal_point = omni.usd.utils.get_world_transform_matrix(prim).ExtractTranslation() # Set agent destination self.goals = np.asarray([goal_point for x in range(self.nagents)]) def integrate(self, x, v, f, dt): ''' take position, velocity, force, and dt to compute updated position and velocity ''' v1 = v + ( (f * 1.0) * dt ) # new velocity x1 = x + (v1 * dt) # new position return x1, v1 def update_goals(self, new_goal): '''update the goals of agents Parameters ---------- new_goal : ndarray([x,y,z]) can either be one goal that is applied to all agents, or a list of the same size as number of agents ''' if len(new_goal) == 1: self.goals = np.asarray([new_goal for x in range(self.nagents)]) else: self.goals = new_goal def compute_step(self, agent): # Set the model to PAM if asked if self.use_pam: model = pam else: model = socialforces # Get the neighbors of this agent to use in computing forces pn = model.get_neighbors(self.agents_pos[agent], self.agents_pos, self.agents_percept[agent])[1] _force = model.compute_force(self.agents_pos[agent], self.agents_radi[agent], self.agents_vel[agent], self.agents_mass[agent], self.goals[agent], self.agents_pos[pn], self.agents_vel[pn], self.agents_radi[pn], self._dt) return _force def run(self): '''Runs the simulation for one step Updates agent positions and velocities if instance flag is true Returns ------- ndarray[x,y,z] forces ''' self.force_list = [] for agent in range(self.nagents): _force = self.compute_step(agent) # remove world (up) forces _force[self.world_up] = 0 # Store all forces to be applied to agents self.force_list.append(_force) self.step_processing() def step_processing(self): '''Process the computed step for simulation Returns ------- _type_ _description_ ''' # only update agent positions if user requests, otherwise they might want to # update using forces themselves if self.update_agents_sim: # If using rigid body, apply forces to agents if self.rigidbody: self.apply_force(self.force_list) else: self.internal_integration() if self.use_instancer: self.set_instance_agents() else: self.set_geompoints() def internal_integration(self): # Integrate for new position for i in range(self.nagents): self.agents_pos[i], self.agents_vel[i] = self.integrate(self.agents_pos[i], self.agents_vel[i], self.force_list[i], self._dt) def apply_force(self, force_list): '''Used for when rigidbody agents are used Parameters ---------- force_list : List[x,y,z] list of forces in order of the agents ''' # Apply forces to simulation # with Sdf.ChangeBlock(): # for idx, force in enumerate(force_list): # self._add_force(force, self.agent_bodies[idx], self.agent_bodies[idx].position) self._add_force3(force_list, self.agent_bodies) # Update positions and velocities for i in range(self.nagents): self.agents_pos[i] = self.agent_bodies[i].position self.agents_vel[i] = self.agent_bodies[i].velocity def _add_force(self, force, rigid_body, position): force = carb.Float3(force) position = carb.Float3(position) get_physx_interface().apply_force_at_pos(rigid_body.skinMeshPath, force, position) def _add_force2(self, force, rigid_body, position): # force = Gf.Vec3d(force) _ = force[0] force = Gf.Vec3d(float(force[0]), float(force[1]),float(force[2])) rigid_body.forceAttr.Set(force) #position def _add_force3(self, force_list, rigid_body): # force = Gf.Vec3d(force) # stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) # # prim = stage.GetPrimAtPath("/World/boxActor") # attr = prim.CreateAttribute("_worldForce", usdrt.Sdf.ValueTypeNames.Float3, True) # if attr: # attr.Set(usdrt.Gf.Vec3f(50000.0, 0.0, 0.0)) # prefixes = set(prefix for path in paths for prefix in path.GetPrefixes()) # with Sdf.ChangeBlock(): # for path in prefixes: # prim_spec = Sdf.CreatePrimInLayer(layer, path) # prim_spec.specifier = Sdf.SpecifierDef # prim_spec.typeName = UsdGeom.Xform.__name__ for idx, body in enumerate(rigid_body): force = force_list[idx] force = usdrt.Gf.Vec3d(float(force[0]), float(force[1]),float(force[2])) # body.forceAttr.Set(force) #position if body.world_force_attr: body.world_force_attr.Set(force) def create_geompoints(self, stage_path=None, color=None): '''create and manage geompoints representing agents Parameters ---------- stage_path : str, optional if not set, will use /World/Points, by default None color : (r,g,b), optional if not set, will make color red, by default None ''' if stage_path: stage_loc = stage_path else: stage_loc = "/World/Points" self.stage = omni.usd.get_context().get_stage() self.agent_point_prim = UsdGeom.Points.Define(self.stage, stage_loc) self.agent_point_prim.CreatePointsAttr() width_attr = self.agent_point_prim.CreateWidthsAttr() width_attr.Set(self.agents_radi) # width_attr.Set([1 for x in range(self.nagents)]) self.agent_point_prim.CreateDisplayColorAttr() # For RTX renderers, this only works for UsdGeom.Tokens.constant color_primvar = self.agent_point_prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant) if color: point_color = color else: point_color = (1,0,0) color_primvar.Set([point_color]) def set_geompoints(self): # Set the position with an offset based on the radius # Since it is a sphere, we render_pos = np.copy(self.agents_pos) render_pos[:,1] += (self.agents_radi/2) self.agent_point_prim.GetPointsAttr().Set(render_pos) def create_instance_agents(self): if self.add_jane: bob_size = int(self.nagents/2) bob_pos = self.agents_pos[:bob_size] point_instancer = self._single_agent_instance(bob_pos, bob_size, self.agent_instance_path_bob, self.instancer_paths[0]) self.point_instancer_sets.append(point_instancer) # TODO find way to split colors of instances jane_size = int(self.nagents/2) jane_pos = self.agents_pos[bob_size:] point_instancer = self._single_agent_instance(jane_pos, jane_size , self.agent_instance_path_jane, self.instancer_paths[1]) self.point_instancer_sets.append(point_instancer) else: point_instancer = self._single_agent_instance(self.agents_pos, self.nagents, self.agent_instance_path_bob, self.instancer_paths[0]) self.point_instancer_sets.append(point_instancer) def _single_agent_instance(self, agent_pos, nagents, agent_instance_path, instance_path): stage = omni.usd.get_context().get_stage() point_instancer = UsdGeom.PointInstancer.Get(stage, instance_path) if not point_instancer: point_instancer = UsdGeom.PointInstancer(stage.DefinePrim(instance_path, "PointInstancer")) point_instancer.CreatePrototypesRel().SetTargets([agent_instance_path]) self.proto_indices_attr = point_instancer.CreateProtoIndicesAttr() self.proto_indices_attr.Set([0] * nagents) ## max radius is scale of 1 agent_scales = self.agents_radi/self.radius_max self.agent_instancer_scales = [(x,x,x) for x in agent_scales] # change to numpy # Set scale point_instancer.GetScalesAttr().Set(self.agent_instancer_scales) point_instancer.GetPositionsAttr().Set(agent_pos) # Set orientation rot = Gf.Rotation() rot.SetRotateInto(self.instance_forward_vec, self.instance_forward_vec) self.agent_headings = [Gf.Quath(rot.GetQuat()) for x in range(nagents)] point_instancer.GetOrientationsAttr().Set(self.agent_headings) return point_instancer def set_instance_agents(self): # update the points # self.point_instancer.CreatePrototypesRel().SetTargets([self.agent_instance_path]) # self.proto_indices_attr = self.point_instancer.CreateProtoIndicesAttr() # self.proto_indices_attr.Set([0] * self.nagents) for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agents_pos = self.agents_pos else: _slice = int(self.nagents/2) if idx == 0: # Positions for this instance agents_pos = self.agents_pos[:_slice] else: # Positions for this instance agents_pos = self.agents_pos[_slice:] # Set position point_instancer.GetPositionsAttr().Set(agents_pos) if not self.use_heading: continue self.set_heading() def set_heading(self): for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agents_vel = self.agents_vel nagents = self.nagents else: _slice = int(self.nagents/2) nagents = _slice if idx == 0: # Velocities for this instance agents_vel = self.agents_vel[:_slice] else: # Velocities for this instance agents_vel = self.agents_vel[_slice:] # Create array of agent headings based on velocity normalize_vel = agents_vel rot = Gf.Rotation() self.agent_headings = [] cur_orient = point_instancer.GetOrientationsAttr().Get() for i in range(0, nagents): if np.sqrt(normalize_vel[i].dot(normalize_vel[i])) < self.vel_epsilon: tovec = cur_orient[i] self.agent_headings.append(cur_orient[i]) else: tovec = Gf.Vec3d(tuple(normalize_vel[i])) rot.SetRotateInto(self.instance_forward_vec, tovec) self.agent_headings.append(Gf.Quath(rot.GetQuat())) # Set orientation point_instancer.GetOrientationsAttr().Set(self.agent_headings) return #### Change colors stage = omni.usd.get_context().get_stage() # get path of material mat_path = '/CrowdBob/Looks/Linen_Blue' linen_mat = Sdf.Path(f'/World/Scope{mat_path}') mat_prim = stage.GetPrimAtPath(linen_mat) # print(mat_prim) # shader_path = '/Shader.inputs:diffuse_tint' # tint_shader = f'/World{mat_path}{shader_path}' shader = omni.usd.get_shader_from_material(mat_prim) # print(shader) #inp = shader.GetInput('diffuse_tint').Get() inp = shader.GetInput('diffuse_tint').Set((0.5,0.5,1.0)) class WarpCrowd(Simulator): '''A class to manage the warp-based version of crowd simulation ''' def __init__(self, world=None): super().__init__(world) self.device = 'cuda:0' # generate n number of agents self.nagents = 9 # set radius self.radius = 0.7 self.radius_min = 0.5 self.radius_max = 1.0 self.hash_radius = 0.7 # Radius to use for hashgrid # set mass self.mass = 20 # set pereption radius self.perception_radius = 6 # self.dt = 1.0/30.0 self.goal = [0.0,0.0,0.0] self.generation_origin = [10,10.0,0.0] self.inv_up = wp.vec3(1.0,1.0,1.0) # z-up self.inv_up[self.world_up] = 0.0 self.on_gpu = True def demo_agents(self, s=1.6, m=50, n=50): o = self.generation_origin # Initialize agents in a grid for testing self.agents_pos = np.asarray([ np.array([(s/2) + (x * s) +(o[0]/2) , (s/2) + (y * s) +(o[1]/2), 0 ], dtype=np.double) for x in range(m) for y in range(n) ]) self.nagents = len(self.agents_pos) self.configure_params() def configure_params(self): '''Convert all parameters to warp ''' self.agents_pos = np.asarray(self.agents_pos) # self.agents_pos = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) self.agents_vel = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) # # Set a quath for heading # rot = Gf.Rotation() # rot.SetRotateInto(self.instance_forward_vec, self.instance_forward_vec) # from, to # _hquat = Gf.Quath(rot.GetQuat()) # # Get rotation between agent forward direction self.agents_hdir = np.asarray([np.array([0,0,0,1], dtype=float) for x in range(self.nagents)]) self.force_list = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) self.agents_radi = np.random.uniform(self.radius_min, self.radius_max, self.nagents) self.agents_mass = [self.mass for x in range(self.nagents)] self.agents_percept = np.asarray([self.perception_radius for x in range(self.nagents)]) self.agents_goal = np.asarray([np.array(self.goal, dtype=float) for x in range(self.nagents)]) self.agent_force_wp = wp.zeros(shape=self.nagents,device=self.device, dtype=wp.vec3) self.agents_pos_wp = wp.array(self.agents_pos, device=self.device, dtype=wp.vec3) self.agents_vel_wp = wp.array(self.agents_vel, device=self.device, dtype=wp.vec3) self.agents_hdir_wp = wp.array(self.agents_hdir, device=self.device, dtype=wp.vec4) self.agents_goal_wp = wp.array(self.agents_goal, device=self.device, dtype=wp.vec3) self.agents_radi_wp = wp.array(self.agents_radi, device=self.device, dtype=float) self.agents_mass_wp = wp.array(self.agents_mass, device=self.device, dtype=float) self.agents_percept_wp = wp.array(self.agents_percept, device=self.device, dtype=float) self.xnew_wp = wp.zeros_like(wp.array(self.agents_pos, device=self.device, dtype=wp.vec3)) self.vnew_wp = wp.zeros_like(wp.array(self.agents_pos, device=self.device, dtype=wp.vec3)) self.hdir_wp = wp.zeros_like(wp.array(self.agents_hdir, device=self.device, dtype=wp.vec4)) def config_hasgrid(self, nagents=None): '''Create a hash grid based on the number of agents Currently assumes z up Parameters ---------- nagents : int, optional _description_, by default None ''' if nagents is None: nagents = self.nagents self.grid = wp.HashGrid(dim_x=200, dim_y=200, dim_z=1, device=self.device) # self.grid = wp.HashGrid(dim_x=nagents, dim_y=nagents, dim_z=1, device=self.device) def config_mesh(self, points, faces): '''Create a warp mesh object from points and faces Parameters ---------- points : List[[x,y,z]] A list of floating point xyz vertices of a mesh faces : List[int] A list of integers corresponding to vertices. Must be triangle-based ''' # fake some points and faces if empty list was passed if len(points) == 0: points = [(0,0,0), (0,0,0), (0,0,0)] faces = [[1, 2, 3]] # print(points) # print(faces) # Init mesh for environment collision self.mesh = wp.Mesh( points=wp.array(points, dtype=wp.vec3, device=self.device), indices=wp.array(faces, dtype=int ,device=self.device) ) def update_goals(self, new_goal): if len(new_goal) == 1: self.goals = np.asarray([new_goal for x in range(self.nagents)]) else: self.goals = new_goal self.agents_goal_wp = wp.array(self.goals, device=self.device, dtype=wp.vec3) def run(self): # Rebuild hashgrid given new positions self.grid.build(points=self.agents_pos_wp, radius=self.hash_radius) # launch kernel wp.launch(kernel=crowd_force.get_forces, dim=self.nagents, inputs=[self.agents_pos_wp, self.agents_vel_wp, self.agents_goal_wp, self.agents_radi_wp, self.agents_mass_wp, self._dt, self.agents_percept_wp, self.grid.id, self.mesh.id, self.inv_up], outputs=[self.agent_force_wp], device=self.device ) self.force_list = self.agent_force_wp.numpy() self.step_processing() self.agents_pos_wp = wp.array(self.agents_pos, device=self.device, dtype=wp.vec3) self.agents_vel_wp = wp.array(self.agents_vel, device=self.device, dtype=wp.vec3) return self.agent_force_wp def internal_integration(self): # Given the forces, integrate for pos and vel wp.launch(kernel=crowd_force.integrate, dim=self.nagents, inputs=[self.agents_pos_wp, self.agents_vel_wp, self.agent_force_wp, self._dt], outputs=[self.xnew_wp, self.vnew_wp], device=self.device ) self.agents_pos_wp = self.xnew_wp self.agents_vel_wp = self.vnew_wp self.agents_pos = self.agents_pos_wp.numpy() self.agents_vel = self.agents_vel_wp.numpy() def set_heading(self): up = wp.vec3(0.0,1.0,0.0) forward = wp.vec3(1.0,0.0,0.0) wp.launch(kernel=crowd_force.heading, dim=self.nagents, inputs=[self.agents_vel_wp, up, forward], outputs=[self.hdir_wp], device=self.device ) self.agents_hdir_wp = self.hdir_wp self.agents_hdir = self.agents_hdir_wp.numpy() for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agent_headings = self.agents_hdir else: _slice = int(self.nagents/2) if idx == 0: agent_headings = self.agents_hdir[:_slice] else: agent_headings = self.agents_hdir[_slice:] # Set orientation point_instancer.GetOrientationsAttr().Set(agent_headings)
23,588
Python
37.231767
143
0.558632
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/usd_utils.py
import numpy as np from pxr import UsdGeom, Gf, Usd import omni def get_mesh(usd_stage, objs): points, faces = [],[] for obj in objs: f_offset = len(points) # f, p = convert_to_mesh(obj)#usd_stage.GetPrimAtPath(obj)) f, p = meshconvert(obj)#usd_stage.GetPrimAtPath(obj)) points.extend(p) faces.extend(f+f_offset) return points, faces def get_all_stage_mesh(stage, start_prim): found_meshes = [] # Traverse the scene graph and print the paths of prims, including instance proxies for x in Usd.PrimRange(start_prim, Usd.TraverseInstanceProxies()): if x.IsA(UsdGeom.Mesh): found_meshes.append(x) points, faces = get_mesh(stage, found_meshes) return points, faces def convert_to_mesh(prim): ''' convert a prim to BVH ''' # Get mesh name (prim name) m = UsdGeom.Mesh(prim) # Get verts and triangles tris = m.GetFaceVertexIndicesAttr().Get() tris_cnt = m.GetFaceVertexCountsAttr().Get() verts = m.GetPointsAttr().Get() tri_list = np.array(tris) vert_list = np.array(verts) xform = UsdGeom.Xformable(prim) time = Usd.TimeCode.Default() # The time at which we compute the bounding box world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotationMatrix() # rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) rotation = rotation.GetOrthonormalized() # New vertices vert_list = np.dot((vert_list * scale ), rotation) + translation # vert_scaled = vert_list # vert_list[:,0] *= scale[0] # vert_list[:,1] *= scale[1] # vert_list[:,2] *= scale[2] # vert_rotated = np.dot(vert_scaled, rotation) # Rotate points # vert_translated = vert_rotated + translation # vert_list = vert_translated # Check if the face counts are 4, if so, reshape and turn to triangles if tris_cnt[0] == 4: quad_list = tri_list.reshape(-1,4) tri_list = quad_to_tri(quad_list) tri_list = tri_list.flatten() return tri_list, vert_list def quad_to_tri(a): idx = np.flatnonzero(a[:,-1] == 0) out0 = np.empty((a.shape[0],2,3),dtype=a.dtype) out0[:,0,1:] = a[:,1:-1] out0[:,1,1:] = a[:,2:] out0[...,0] = a[:,0,None] out0.shape = (-1,3) mask = np.ones(out0.shape[0],dtype=bool) mask[idx*2+1] = 0 return out0[mask] def selected_as_mesh(): # Get the current active selection of the stage stage = omni.usd.get_context().get_stage() # Get the selections from the stage _usd_context = omni.usd.get_context() _selection = _usd_context.get_selection() selected_paths = _selection.get_selected_prim_paths() # Expects a list, so take first selection prims = [stage.GetPrimAtPath(x) for x in selected_paths] points, faces = get_mesh(stage, selected_paths) return points, faces def children_as_mesh(stage, parent_prim): children = parent_prim.GetAllChildren() children = [child.GetPrimPath() for child in children] points, faces = get_mesh(stage, children) return points, faces def meshconvert(prim): # Create an XformCache object to efficiently compute world transforms xform_cache = UsdGeom.XformCache() # Get the mesh schema mesh = UsdGeom.Mesh(prim) # Get verts and triangles tris = mesh.GetFaceVertexIndicesAttr().Get() if not tris: return [], [] tris_cnt = mesh.GetFaceVertexCountsAttr().Get() # Get the vertices in local space points_attr = mesh.GetPointsAttr() local_points = points_attr.Get() # Convert the VtVec3fArray to a NumPy array points_np = np.array(local_points, dtype=np.float64) # Add a fourth component (with value 1.0) to make the points homogeneous num_points = len(local_points) ones = np.ones((num_points, 1), dtype=np.float64) points_np = np.hstack((points_np, ones)) # Compute the world transform for this prim world_transform = xform_cache.GetLocalToWorldTransform(prim) # Convert the GfMatrix to a NumPy array matrix_np = np.array(world_transform, dtype=np.float64).reshape((4, 4)) # Transform all vertices to world space using matrix multiplication world_points = np.dot(points_np, matrix_np) tri_list = convert_to_triangle_mesh(tris, tris_cnt) tri_list = tri_list.flatten() world_points = world_points[:,:3] return tri_list, world_points def convert_to_triangle_mesh(FaceVertexIndices, FaceVertexCounts): """ Convert a list of vertices and a list of faces into a triangle mesh. A list of triangle faces, where each face is a list of indices of the vertices that form the face. """ # Parse the face vertex indices into individual face lists based on the face vertex counts. faces = [] start = 0 for count in FaceVertexCounts: end = start + count face = FaceVertexIndices[start:end] faces.append(face) start = end # Convert all faces to triangles triangle_faces = [] for face in faces: if len(face) < 3: newface = [] # Invalid face elif len(face) == 3: newface = [face] # Already a triangle else: # Fan triangulation: pick the first vertex and connect it to all other vertices v0 = face[0] newface = [[v0, face[i], face[i + 1]] for i in range(1, len(face) - 1)] triangle_faces.extend(newface) return np.array(triangle_faces) # from pxr import UsdGeom, Sdf, Usd # import os # def add_ext_reference(prim: Usd.Prim, ref_asset_path: str, ref_target_path: Sdf.Path) -> None: # references: Usd.References = prim.GetReferences() # references.AddReference( # assetPath=ref_asset_path, # primPath=ref_target_path # OPTIONAL: Reference a specific target prim. Otherwise, uses the referenced layer's defaultPrim. # ) # class makescope: # def __init__(self): # self.stage = omni.usd.get_context().get_stage() # scope = UsdGeom.Scope.Define(self.stage, Sdf.Path('/World/Scope')) # ref_prim = UsdGeom.Xform.Define(self.stage, Sdf.Path('/World/Scope/CrowdJane')).GetPrim() # dir_path = os.path.join('G:/ProjectRepos/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/data/', 'CrowdBob.usda') # add_ext_reference(ref_prim, dir_path, Sdf.Path("<Default Prim>")) # ms = makescope()
6,666
Python
30.154205
132
0.645665
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/extension.py
import numpy as np import omni.ext import omni.ui as ui import omni.usd from omni.physx import get_physx_interface try: from omni.usd import get_world_transform_matrix except: from omni.usd.utils import get_world_transform_matrix from . import window from . import simulator from .env import Environment from . import usd_utils class SFsim(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query # additional information, like where this extension is located on filesystem. def on_startup(self, ext_id): print("[siborg.simulate.crowd] Social Forces Sim startup") self.goal_prim_path = '/World/CrowdGoals' self.obstacle_prim_path = '/World/Obstacles' self.grid_size = 3 self.rigid_flag = False self.pam_flag = False self.gpu_flag = False self.instancer_flag = False self.jane_flag = False self.heading_flag = False self.init_scene() self.show() self.goal_prim_dict = {} # {Prim path, subscriber} self._on_update_sub = None def show(self): self._window = ui.Window("Social Forces Demo Settings", width=500, height=250) gui_window = window.make_window_elements(self, self._window, self.Sim) def init_goal_prim(self, prim_path): omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=prim_path, attributes={}, select_new_prim=True) def modify_goals(self, _new_goals): if len(_new_goals) == 0: return if self.Sim.nagents == 0: return # Assign goals based on number of goals available if len(_new_goals)>self.Sim.nagents: _new_goals = _new_goals[self.Sim.nagents:] # Get strides self.Sim.goals = np.asarray(self.Sim.goals, dtype=object) goal_cast = np.array_split(self.Sim.goals, len(_new_goals)) # Reassign the split arrays their new goals for idx in range(len(goal_cast)): goal_cast[idx][:] = _new_goals[idx] # Reshape into xyz vector goal_cast = np.vstack(goal_cast) goal_cast = np.asarray(goal_cast, dtype=np.float) # Update the simulations goals self.Sim.update_goals(goal_cast) def init_scene(self): self.World = Environment() if self.gpu_flag: self.Sim = simulator.WarpCrowd() else: self.Sim = simulator.Simulator() # Create the goal hierarchy self.init_goal_prim(self.goal_prim_path) self.init_goal_prim(self.obstacle_prim_path) def _on_update_event(self, dt): # Check the Goals xform path and see if there are any changes needed to the goal watchers self.stage = omni.usd.get_context().get_stage() parent_prim = self.stage.GetPrimAtPath(self.goal_prim_path) children = parent_prim.GetAllChildren() # Check if any children are gone from our dict, if so, unsubscribe their watcher dead_kids = [kid for kid in self.goal_prim_dict.keys() if kid not in children] for kid in dead_kids: try: self.goal_prim_dict[kid].unsubscribe() except: self.goal_prim_dict[kid] = None self.goal_prim_dict.pop(kid) # Check if there are any new children not in our dict, if so, add them as a goal and update watcher babies = [child for child in children if child not in self.goal_prim_dict.keys()] for baby in babies: self.goal_prim_dict[baby] = None # Update the goals new_goals = [] for x in self.goal_prim_dict.keys(): _prim = x try: t = omni.usd.get_world_transform_matrix(_prim).ExtractTranslation() except: t = omni.usd.utils.get_world_transform_matrix(_prim).ExtractTranslation() new_goals.append(t) if len(new_goals) == 0: return self.modify_goals(new_goals) def assign_meshes(self): self.stage = omni.usd.get_context().get_stage() # Use the meshes that are parent_prim = self.stage.GetPrimAtPath(self.obstacle_prim_path) # points, faces = usd_utils.children_as_mesh(self.stage, parent_prim) points, faces = usd_utils.get_all_stage_mesh(self.stage,parent_prim) self.Sim.config_mesh(points, faces) def api_example(self): self.Sim._unregister() if self.gpu_flag: self.Sim = simulator.WarpCrowd(self.World) self.Sim.config_hasgrid() self.assign_meshes() else: self.Sim = simulator.Simulator(self.World) self.demo_api_call(self.Sim) def demo_api_call(self, Sim): # Use the builtin function for demo agents Sim.rigidbody = self.rigid_flag # Set origin for spawning agents self.stage = omni.usd.get_context().get_stage() parent_prim = self.stage.GetPrimAtPath('/World/GenerationOrigin') Sim.generation_origin = [0,0,0] if parent_prim: Sim.generation_origin = get_world_transform_matrix(parent_prim).ExtractTranslation() Sim.generation_origin[2] = Sim.generation_origin[1] Sim.init_demo_agents(m=self.grid_size,n=self.grid_size,s=1.6) if self.pam_flag: Sim.use_pam = True if self.gpu_flag: Sim.configure_params() if not Sim.rigidbody: if self.jane_flag: # TODO make this work for all sim types Sim.add_jane = True else: Sim.add_jane = False if self.instancer_flag: Sim.point_instancer_sets = [] Sim.use_instancer = True if self.heading_flag: Sim.use_heading = True Sim.create_instance_agents() # Create a usdgeom point instance for easy visualization Sim.set_instance_agents() # update the usdgeom points for visualization else: Sim.use_instancer = False Sim.create_geompoints() # Create a usdgeom point instance for easy visualization Sim.set_geompoints() # update the usdgeom points for visualization # tell simulator to update positions after each run Sim.update_agents_sim = True # tell simulator to handle the update visualization Sim.update_viz = True # Register the simulation to updates, and the Sim will handle it from here Sim.register_simulation() if not self._on_update_sub: self._on_update_sub = get_physx_interface().subscribe_physics_step_events(self._on_update_event) def on_shutdown(self): print("[siborg.simulate.crowd] Crowd Sim shutdown") try: self.Sim._unregister() except: pass try: self._goal_subscriber.unsubscribe() except: self._goal_subscriber = None try: self._on_update_sub.unsubscribe() except: self._on_update_sub = None self.Sim._simulation_event = None self._window = None self.Sim = None
7,277
Python
35.39
108
0.601896
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/crowds.py
import numpy as np from siborg.simulate.crowd.agent import Agent class CrowdConfig: def __init__(self): self._goal = [0,0,0] self.goals = None self.agent_bodies = None self.nagents = 1 # set pereption radius self.perception_radius = 1.5 # set radius self.radius = .5 # set mass self.mass = 2 # Will use a physics scene self.rigidbody = False # Assume z-up world self.world_up = 2 def create_agents(self, num=None, goals=None, pos=None): '''Creates a set of agents and goals Uses the class instance defaults for radius, mass, perception, etc. Parameters ---------- num : int, optional number of agents to create (if not defined in init), by default None goals : ndarray([x,y,z]), optional either 1 or size equal to number of agents, by default None pos : ndarray([x,y,z]), optional must be same size as number of agents (otherwise will set all to origin, which is bad), because they will explode, by default None ''' # generate n number of agents if num: self.nagents = num # Check we can assign goals to agents if not goals: goals = [self._goal] if len(goals) != 1: if len(goals) != self.nagents: raise ValueError('If goals is not 1, must be same size as number of agents') elif len(goals) == 1: self.goals = np.asarray([goals[0] for x in range(self.nagents)], dtype=np.double) else: self.goals = goals # Set the agent positions if pos is not None: self.agents_pos = np.asarray(pos, dtype=np.double) else: self.agents_pos = np.asarray([np.array(0,0,0, dtype=np.double) for x in range(self.nagents)]) # only create an agent instance if user wants physics-based spheres if self.rigidbody: self.agent_bodies = [Agent() for x in range(self.nagents)] # move agents to their positions for i in range(len(self.agent_bodies)): x,y,z = self.agents_pos[i] self.agent_bodies[i].translate(x,y,z) else: self.agent_bodies = [None for x in range(self.nagents)] # set initial velocities to 0 self.agents_vel = np.asarray([np.array([0,0,0], dtype=np.double) for x in range(self.nagents)]) self.set_radius() self.set_mass() self.set_perception_radius() def set_radius(self,v=None): '''sets agents radius Parameters ---------- v : List[float], float, optional set the radius of the agents, if None, all agents get same radius, by default None ''' if v: if type(v) is float: self.agents_radi = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('Radius array must be same size as number of agents') else: self.agents_radi = v else: self.agents_radi = np.asarray([self.radius for x in range(self.nagents)]) def set_mass(self,v=None): '''sets agents mass Parameters ---------- v : List[float], optional set the mass of the agents, if None, all agents get same mass, by default None Raises ------ ValueError if size of mass array does not match number of agents ''' if v: if type(v) is float: self.agents_mass = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('mass array must be same size as number of agents') else: self.agents_mass = v else: self.agents_mass = np.asarray([self.mass for x in range(self.nagents)]) def set_perception_radius(self, v=None): '''sets agents perception radius Parameters ---------- v : List[float], optional set the percept radius of the agents, if None, all agents get same raidus, by default None Raises ------ ValueError if size of perception array does not match number of agents ''' if v: if type(v) is float: self.agents_percept = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('perception radius array must be same size as number of agents') else: self.agents_percept = v else: self.agents_percept = np.asarray([self.perception_radius for x in range(self.nagents)]) def init_demo_agents(self, m=5, n=5, s=1, o=[0,0,0]): '''Create a set of demo agents Parameters ---------- m : int, optional number of agents in row, by default 5 n : int, optional number of agents in col, by default 5 s : int, optional spacing between agents, by default 1 ''' o = self.generation_origin # Initialize agents in a grid for testing self.agents_pos = np.asarray([ np.array([(s/2) + (x * s) +(o[0]/2) , (s/2) + (y * s) +(o[1]/2), 0], dtype=np.double) for x in range(m) for y in range(n) ]) # # Initialize agents in a grid for testing # self.agents_pos = np.asarray([ # np.array([(s/2) + (x * s), (s/2) + (y * s), 0], dtype=np.double) # for x in range(m) # for y in range(n) # ]) self.agents_pos[:, [2, self.world_up]] = self.agents_pos[:, [self.world_up, 2]] self.nagents = len(self.agents_pos) #### if self.rigidbody: self.agent_bodies = [Agent() for x in range(self.nagents)] for i in range(len(self.agent_bodies)): x,y,z = self.agents_pos[i] self.agent_bodies[i].translate(x,y,z) else: self.agent_bodies = [None for x in range(self.nagents)] self.goals = np.asarray([self._goal for x in range(self.nagents)], dtype=np.double) self.agents_vel = np.asarray([np.array([0,0,0],dtype=np.double) for x in range(self.nagents)]) self.set_radius() self.set_mass() self.set_perception_radius()
6,938
Python
34.584615
105
0.511098
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/env.py
import omni import omni.kit.commands from pxr import Usd, Gf from pxr import UsdGeom from pxr import UsdPhysics, PhysxSchema class Environment: def __init__(self): print('Initializing Environment') self._stage = omni.usd.get_context().get_stage() self.set_scene(self._stage) def set_scene(self, stage): print(f'Setting up {stage}') self._stage = stage self.defaultPrimPath = str(self._stage.GetDefaultPrim().GetPath()) # Physics scene # UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) self.scene = UsdPhysics.Scene.Define(stage, self.defaultPrimPath + "/physicsScene") stage_axis = UsdGeom.GetStageUpAxis(stage) gravity_dir = Gf.Vec3f(0.0, 0.0, 0) if stage_axis is 'X': gravity_dir[0] = -1.0 if stage_axis is 'Y': gravity_dir[1] = -1.0 if stage_axis is 'Z': gravity_dir[2] = -1.0 self.scene.CreateGravityDirectionAttr().Set(gravity_dir) self.scene.CreateGravityMagnitudeAttr().Set(9.81) physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(self.scene.GetPrim()) physxSceneAPI.CreateEnableCCDAttr().Set(True) # Check if there is a physics groundplane in the scene plane_path = self.defaultPrimPath+"/GroundPlane" if self._stage.GetPrimAtPath(plane_path).IsValid(): pass else: # If not, make one omni.kit.commands.execute('AddGroundPlaneCommand', stage=self._stage, planePath='/GroundPlane', axis=UsdGeom.GetStageUpAxis(stage), size=1.0, position=Gf.Vec3f(0.0, 0.0, 0.0), color=Gf.Vec3f(0.5, 0.5, 0.5))
1,923
Python
34.629629
91
0.566823
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/agent.py
import omni from omni.physx.scripts import physicsUtils from pxr import Gf, UsdPhysics, PhysxSchema, UsdGeom, UsdShade import usdrt class Agent: def __init__(self): stage = omni.usd.get_context().get_stage() # Create a sphere representing the agent self.skin_mesh , self.skinMeshPath = self.sphere(stage) # Set a rigid body material and collider self.set_material(stage, self.skinMeshPath) # Add a translation operator and set it to zero position # Since we changed to create this object with an xform, don't need to add, just get it. # self.translateOp = self.skin_mesh.AddTranslateOp() self.translateOp = UsdGeom.XformOp(self.skin_mesh.GetPrim().GetAttribute("xformOp:translate")) self.translateOp.Set(Gf.Vec3f(0.0, 0.0, 0.0)) def sphere(self, stage): # Create sphere representing agent _, skinMeshPath = omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type="Sphere", prim_path='/World/Agents/Sphere', prepend_default_prim=True) skin_mesh = UsdGeom.Mesh.Get(stage, skinMeshPath) prim = skin_mesh.GetPrim() # setup physics - rigid body self.rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(prim) linVelocity = Gf.Vec3f(0.0, 0.0, 0.0) angularVelocity = Gf.Vec3f(0.0, 0.0, 0.0) # apply initial velocities self.rigidBodyAPI.CreateVelocityAttr().Set(linVelocity) self.rigidBodyAPI.CreateAngularVelocityAttr().Set(angularVelocity) self.massAPI = UsdPhysics.MassAPI.Apply(prim) self.massAPI.CreateMassAttr(2) self.massAPI.CreateCenterOfMassAttr().Set(Gf.Vec3f(0.0, 0.0, 0.0)) # Add a force attribute # shuttleForcePath = skinMeshPath + "/shuttleForce" # xform = UsdGeom.Xform.Define(stage, shuttleForcePath) # self.forceApi = PhysxSchema.PhysxForceAPI.Apply(xform.GetPrim()) # # self.forceApi = PhysxSchema.PhysxForceAPI.Apply(prim) # self.forceAttr = self.forceApi.GetForceAttr() self.usdrt_stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) prim = self.usdrt_stage.GetPrimAtPath(skinMeshPath) self.world_force_attr = prim.CreateAttribute("_worldForce", usdrt.Sdf.ValueTypeNames.Float3, True) return skin_mesh, skinMeshPath def translate(self, x=0, y=0, z=0): self.translateOp.Set(self.translateOp.Get() + Gf.Vec3d( x, y, z)) @property def position(self): return self.translateOp.Get() @property def velocity(self): return self.rigidBodyAPI.GetVelocityAttr().Get() def set_material(self, stage, skinMeshPath): defaultPrimPath = str(stage.GetDefaultPrim().GetPath()) # Floor Material path = defaultPrimPath + "/rigidMaterial" prim_path = stage.GetPrimAtPath(skinMeshPath) # Set it as a rigid body rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(prim_path) # Add a collider (defaults to mesh triangulation) UsdPhysics.CollisionAPI.Apply(prim_path) # Apply a specific mass parameter UsdPhysics.MassAPI.Apply(prim_path) #Get the rigidbody parameter to set values on physxRbAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(prim_path) #Enable CCD for this object physxRbAPI.CreateEnableCCDAttr().Set(True) # Create a (separate) physics material that gets added to the object path = defaultPrimPath + "/highdensitymaterial" UsdShade.Material.Define(stage, path) material = UsdPhysics.MaterialAPI.Apply(stage.GetPrimAtPath(path)) material.CreateStaticFrictionAttr().Set(0) material.CreateDynamicFrictionAttr().Set(0) material.CreateRestitutionAttr().Set(.2) material.CreateDensityAttr().Set(0.01) # Add material physicsUtils.add_physics_material_to_prim(stage, prim_path, path)
4,141
Python
38.075471
107
0.642357
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/window.py
from .models.socialforces import Parameters import omni.ui as ui combo_sub = None def make_window_elements(self, _window, Sim): with _window.frame: with ui.VStack(): with ui.HStack(): ui.Label('Max Speed') max_speed = ui.FloatField(height=20) max_speed.model.add_value_changed_fn(lambda m : setattr(Parameters, 'max_speed', m.get_value_as_float())) max_speed.model.set_value(Parameters.max_speed) with ui.HStack(): ui.Label('Desired Speed') v_desired = ui.FloatField(height=20) v_desired.model.add_value_changed_fn(lambda m : setattr(Parameters, 'v_desired', m.get_value_as_float())) v_desired.model.set_value(Parameters.v_desired) with ui.HStack(): ui.Label('A') A = ui.FloatField(height=20) A.model.add_value_changed_fn(lambda m : setattr(Parameters, 'A', m.get_value_as_float())) A.model.set_value(Parameters.A) with ui.HStack(): ui.Label('B') B = ui.FloatField(height=20) B.model.add_value_changed_fn(lambda m : setattr(Parameters, 'B', m.get_value_as_float())) B.model.set_value(Parameters.B) with ui.HStack(): ui.Label('kn') kn = ui.FloatField(height=20) kn.model.add_value_changed_fn(lambda m : setattr(Parameters, 'kn', m.get_value_as_float())) kn.model.set_value(Parameters.kn) with ui.HStack(): ui.Label('kt') kt = ui.FloatField(height=20) kt.model.add_value_changed_fn(lambda m : setattr(Parameters, 'kt', m.get_value_as_float())) kt.model.set_value(Parameters.kt) with ui.HStack(): ui.Label('Agent grid (nxn)') agent_grid = ui.IntField(height=20) agent_grid.model.add_value_changed_fn(lambda m : setattr(self, 'grid_size', m.get_value_as_int())) agent_grid.model.set_value(3) # with ui.HStack(): # ui.Label('Agent Mass') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : setattr(Sim, 'mass', m.get_value_as_float())) # kt.model.set_value(Sim.mass) # with ui.HStack(): # ui.Label('Agent Radius') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : Sim.set_radius(m.get_value_as_float())) # kt.model.set_value(Sim.radius) # with ui.HStack(): # ui.Label('Agent Perception Radius') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : setattr(Sim, 'perception_radius', m.get_value_as_float())) # kt.model.set_value(Sim.perception_radius) # with ui.HStack(height=20): # ui.Button("Gen Agents", clicked_fn=Sim.create_agents) # nagents = ui.IntField(height=5) # nagents.model.set_value(Sim.nagents) # nagents.model.add_value_changed_fn(lambda m : setattr(Sim, 'nagents', m.get_value_as_int())) with ui.HStack(height=20): ui.Label('GPU', width=20) WarpModel = ui.CheckBox(width=30) WarpModel.model.add_value_changed_fn(lambda m : setattr(self, 'gpu_flag', m.get_value_as_bool())) WarpModel.model.set_value(True) ui.Label('Use Instances', width=20) SFModel = ui.CheckBox(width=30) SFModel.model.add_value_changed_fn(lambda m : setattr(self, 'instancer_flag', m.get_value_as_bool())) SFModel.model.set_value(True) ui.Label('Add Jane', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'jane_flag', m.get_value_as_bool())) RigidBody.model.set_value(False) ui.Label('Use Direction', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'heading_flag', m.get_value_as_bool())) RigidBody.model.set_value(True) ui.Label('Rigid Body', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'rigid_flag', m.get_value_as_bool())) RigidBody.model.set_value(False) ui.Label('PAM', width=20) SFModel = ui.CheckBox(width=30) SFModel.model.add_value_changed_fn(lambda m : setattr(self, 'pam_flag', m.get_value_as_bool())) SFModel.model.set_value(False) # options = ["GeomPoints", "RigidBody"] # combo_model: ui.AbstractItemModel = ui.ComboBox(0, *options).model # def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): # value_model = item_model.get_item_value_model(item) # current_index = value_model.as_int # option = options[current_index] # print(f"Selected '{option}' at index {current_index}.") # combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) # def clicked(): # value_model = combo_model.get_item_value_model() # current_index = value_model.as_int # option = options[current_index] # print(f"Button Clicked! Selected '{option}' at index {current_index}.") # self.api_example(current_index) # ui.Button("Set Selected Meshes", width=5, clicked_fn=self.assign_meshes) ui.Button("Start Demo", width=5, clicked_fn=self.api_example) with ui.HStack(height=10): pass
6,133
Python
45.1203
121
0.536768
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex4.py
'''_summary_ ''' from siborg.simulate.crowd.simulator import Simulator def example_4(): # Example of using API Sim = Simulator() Sim.rigidbody = True # use rigid bodies Sim.init_demo_agents(m=3, n=5, s=1.1) # Register the simulation to updates, and the Sim will handle it from here Sim.register_simulation() # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # tell simulator to handle the update visualization Sim.update_viz = True example_4()
558
Python
26.949999
92
0.691756
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex3.py
'''_summary_ ''' import time from omni.physx import get_physx_interface from siborg.simulate.crowd.simulator import Simulator Sim = Simulator() start_time = time.time() _simulation_event = None def example_3(): # Example of using API # Use a builtin helper function to generate a grid of agents Sim.init_demo_agents(m=3, n=5, s=1.1) Sim.create_geompoints() # Create a usdgeom point instance for easy visualization Sim.set_geompoints() # update the usdgeom points for visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = False # Register to our own physx update sim_subscriber() def sim_subscriber(): # This would need to get cleaned up _simulation_event = get_physx_interface().subscribe_physics_step_events(_on_update) def _on_update(dt): # Run one step of simulation # don't need to use forces since we told simulator to update forces = Sim.run() Sim.set_geompoints() # update the usdgeom points for visualization # For this demo we will unsubscribe after a few seconds if time.time() - start_time > 100 : print('ending') _simulation_event.unsubscribe() example_3()
1,338
Python
28.755555
92
0.701046
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex2.py
'''Example for Simulator handling update and using GeomPoints. Uses a helper function for initializing agents ''' from siborg.simulate.crowd.simulator import Simulator def example_2(): Sim = Simulator() # Use a builtin helper function to generate a grid of agents Sim.init_demo_agents(m=3,n=5,s=1.1) Sim.create_geompoints() # Create a usdgeom point instance for easy visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = True Sim.register_simulation() example_2()
669
Python
32.499998
92
0.730942
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex1.py
'''Example for Simulator handling update and using GeomPoints ''' from siborg.simulate.crowd.simulator import Simulator import numpy as np from math import sqrt def example_1(): # Example of using API Sim = Simulator() nagents = 10 # Some trickery to make a grid of agents and get the cloest number of agents to an even grid pos = np.asarray([ np.array([(1/2) + (x), (1/2) + (y), 0], dtype=np.double) for x in range(int(sqrt(nagents))) for y in range(int(sqrt(nagents))) ]) pos[:, [2, Sim.world_up]] = pos[:, [Sim.world_up, 2]] nagents = len(pos) Sim.create_agents(num=nagents, goals=[[10,10,0]], pos=pos) # initialize a set of agents Sim.create_geompoints() # Create a usdgeom point instance for easy visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = True Sim.register_simulation() example_1()
1,119
Python
35.129031
96
0.626452
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/pam.py
''' Python implementation of the Predictive Avoidance Model (PAM) from A Predictive Collision Avoidance Model for Pedestrian Simulation, I. Karamouzas, P. Heil, P. van Beek, M. H. Overmars Motion in Games (MIG 2009), Lecture Notes in Computer Science (LNCS), Vol. 5884, 2009 ''' from dataclasses import dataclass import numpy as np from scipy.spatial import distance @dataclass class Parameters: # The agents field of view field_of_view = 200.0 # The agents radius ? Used here in this implementation or in sim? agent_radius = 0.5 # Minimum agent distance min_agent_dist = 0.1 # the mid distance parameters in peicewise personal space function predictive force dist dmid = 4.0 # KSI ksi = 0.5 # Nearest Neighbour distance ? Used here in this implementation or in sim? neighbor_dist = 10.0 # Maximum neighbours to consider ? Used here in this implementation or in sim? max_neighbors = 3 # Maximum acceleration ? Used here in this implementation or in sim/physics? max_accel = 20.0 # Maximum speed max_speed = 7 # Preferred Speed preferred_vel = 2.5 # Goal acquired radius goal_radius = 1.0 # Time Horizon time_horizon = 4.0 # Agent Distance agent_dist = 0.1 # Wall Distance wall_dist = 0.1 # Wall Steepnes wall_steepness = 2.0 # Agent Strength agent_strength = 1.0 # wFactor, factor to progressively scale down forces in when in a non-collision state w_factor = 0.8 # Noise flag (should noise be added to the movement action) noise = False force_clamp = 40.0 # *private* Ideal wall distance _ideal_wall_dist = agent_radius + wall_dist # *private* Squared ideal wall distance _SAFE = _ideal_wall_dist * _ideal_wall_dist # *private* Agent Personal space _agent_personal_space = agent_radius + min_agent_dist # *private* the min distance parameters in peicewise personal space function _dmin = agent_radius + _agent_personal_space # *private* the max distance parameters in peicewise personal space function _dmax = time_horizon * max_speed # *private* FOV cosine _cosFOV = np.cos((0.5 * np.pi * field_of_view) / 180.0) def ray_intersects_disc(pi, pj, v, r): # calc ray disc est. time to collision t = 0.0 w = pj - pi a = np.dot(v, v) b = np.dot(w, v) c = np.dot(w, w) - (r * r) discr = (b * b) - (a * c) if discr > 0.0: t = (b - np.sqrt(discr)) / a if t < 0.0: t = 999999.0 else: t = 999999.0 return t def mag(v): # calc magnitude of vector v_mag = np.sqrt(v.dot(v)) return v_mag def norm(v): # normalize a vector v_norm = np.array([0, 0, 0], dtype='float64') magnitude = mag(v) if magnitude > 0.0: v_norm = v / magnitude return v_norm def get_neighbors(cur, agents, pn_r): dist = distance.cdist([cur], agents) pn = dist < pn_r # Index to remove is when its zero pn_self = dist == 0 pn_self = np.nonzero(pn_self) pn[pn_self] = False pn = np.nonzero(pn) return pn def wall_force(obstacles, rr_i, closest_point, SAFE, add_force): for i in range(len(obstacles)): # Step 1: get closest point on obstacle to agent # [[ Need python code for this in simulation ]] n_w = rr_i - closest_point d_w = mag(n_w) * mag(n_w) if (d_w < SAFE): d_w = np.sqrt(d_w) if (d_w > 0): n_w /= d_w if ((d_w - Parameters.agent_radius) < 0.001): dist_min_radius = 0.001 else: d_w - Parameters.agent_radius obstacle_force = (Parameters._ideal_wall_dist - d_w) / np.pow(dist_min_radius, Parameters.wall_steepness) * n_w add_force(obstacle_force) def calc_goal_force(goal, rr_i, vv_i): # Preferred velocity is preferred speed in direction of goal preferred_vel = Parameters.preferred_vel * norm(goal - rr_i) # Goal force, is always added goal_force = (preferred_vel - vv_i) / Parameters.ksi return goal_force def collision_param(rr_i, vv_i, desired_vel, pn_rr, pn_vv, pn_r): # Keep track of if we ever enter a collision state agent_collision = False t_pairs = [] # Handle agents tc values for predictive forces among neighbours for j, rr_j in enumerate(pn_rr): # Get position and velocity of neighbor agent vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] combined_radius = Parameters._agent_personal_space + rj w = rr_j - rr_i if (mag(w) < combined_radius): agent_collision = True t_pairs.append((0.0, j)) else: rel_dir = norm(w) if np.dot(rel_dir, norm(vv_i)) < Parameters._cosFOV: continue tc = ray_intersects_disc(rr_i, rr_j, desired_vel - vv_j, combined_radius) if tc < Parameters.time_horizon: if len(t_pairs) < Parameters.max_neighbors: t_pairs.append((tc, j)) elif tc < t_pairs[0][0]: t_pairs.pop() t_pairs.append((tc, j)) return t_pairs, agent_collision def predictive_force(rr_i, desired_vel, desired_speed, pn_rr, pn_vv, pn_r, vv_i): # Handle predictive forces// Predictive forces # Setup collision parameters t_pairs, agent_collision = collision_param(rr_i, vv_i, desired_vel, pn_rr, pn_vv, pn_r) # This will be all the other forces, added in a particular way steering_force = np.array([0, 0, 0], dtype='float64') # will store a list of tuples, each tuple is (tc, agent) force_count = 0 for t_pair in t_pairs: # Nice variables from the t_pair tuples t = t_pair[0] agent_idx = t_pair[1] force_dir = rr_i + (desired_vel * t) - pn_rr[agent_idx] - (pn_vv[agent_idx] * t) force_dist = mag(force_dir) if force_dist > 0: force_dir /= force_dist collision_dist = np.maximum(force_dist - Parameters.agent_radius - pn_r[agent_idx], 0.0) #D = input to evasive force magnitude piecewise function D = np.maximum( (desired_speed * t) + collision_dist, 0.001) force_mag = 0.0 if D < Parameters._dmin: force_mag = Parameters.agent_strength * Parameters._dmin / D elif D < Parameters.dmid: force_mag = Parameters.agent_strength elif D < Parameters._dmax: force_mag = Parameters.agent_strength * (Parameters._dmax - D) / (Parameters._dmax - Parameters.dmid) else: continue force_mag *= np.power( (1.0 if agent_collision else Parameters.w_factor), force_count) force_count += 1 steering_force = force_mag * force_dir return steering_force def add_noise(steering_force): angle = np.random.uniform(0.0, 1.0) * 2.0 * np.pi dist = np.random.uniform(0.0, 1.0) * 0.001 steering_force += dist * np.array([np.cos(angle),np.sin(angle),0], dtype='float64') return steering_force def compute_force(rr_i, ri, vv_i, mass, goal, pn_rr, pn_vv, pn_r, dt): # Get the goal force goal_force = calc_goal_force(goal, rr_i, vv_i) # Desired values if all was going well in an empty world desired_vel = vv_i + goal_force * dt desired_speed = mag(desired_vel) # Get obstacle (wall) forces obstacle_force = np.array([0, 0, 0], dtype='float64') #@TODO # obstacle_force = wall_force() # Get predictive steering forces steering_force = predictive_force(rr_i, desired_vel, desired_speed, pn_rr, pn_vv, pn_r, vv_i) # Add noise for reducing deadlocks adding naturalness if Parameters.noise: steering_force = add_noise(steering_force) # Clamp driving force if mag(steering_force) > Parameters.force_clamp: steering_force = norm(steering_force) * Parameters.force_clamp return goal_force + obstacle_force + steering_force
8,170
Python
32.080972
123
0.599143
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/socialforces.py
from dataclasses import dataclass import numpy as np from scipy.spatial import distance # zero_vec = np.array([0,0,0], dtype='float64') @dataclass class Parameters: # names from https://www.sciencedirect.com/science/article/pii/S0378437120306853 Tau = 0.5 #(s) A = 2000.0 B = 0.08 kn = 1.2 * 100_000 # Kgs^-2 kt = 2.4 * 100_000 # Kg m^-1 s^-1 max_speed = 10 v_desired = 3.5 def calc_wall_force(): # TODO add wall and geometry recognition force = np.array([0,0,0], dtype='float64') return force def calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r): # Sum the forces of neighboring agents force = np.array([0,0,0], dtype='float64') # Set the total force of the other agents to zero ff_ij = np.array([0,0,0], dtype='float64') rr_j =np.array([0,0,0], dtype='float64') # Iterate through the neighbors and sum (f_ij) for j, rr_j in enumerate(pn_rr): # Get position and velocity of neighbor agent vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] # Pass agent position to AgentForce calculation ff_ij = neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j) # Sum Forces force += ff_ij return force def neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j): # Calculate the force exerted by another agent # Take in this agent (i) and a neighbors (j) position and radius # Sum of radii rij = ri + rj # distance between center of mass d_ij = mag(rr_i - rr_j) # "n_ij is the normalized vector points from pedestrian j to i" n_ij = norm(rr_i - rr_j) # Normalized vector pointing from j to i # t_ij "Vector of tangential relative velocity pointing from i to j." # A sliding force is applied on agent i in this direction to reduce the relative velocity. t_ij = np.cross(vv_j - vv_i, [0,0,1] ) dv_ji = np.dot(vv_j - vv_i, t_ij) # Calculate f_ij force = repulsion(rij, d_ij, n_ij) + proximity(rij, d_ij, n_ij) + sliding(rij, d_ij, dv_ji, t_ij) return force def calc_goal_force(goal, pos, vel, mass, v_desired, dt): ee_i = norm(goal - pos) force = mass * ( ( (v_desired * ee_i) - vel ) / Parameters.Tau ) return force def G(r_ij, d_ij): # g(x) is a function that returns zero if pedestrians touch # otherwise is equal to the argument x if (d_ij > r_ij): return 0.0 return r_ij - d_ij; def repulsion(r_ij, d_ij, n_ij): force = Parameters.A * np.exp( (r_ij - d_ij) / Parameters.B) * n_ij return force def proximity(r_ij, d_ij, n_ij): force = Parameters.kn * G(r_ij, d_ij) * n_ij return force def sliding(r_ij, d_ij, dv_ji, t_ij): force = Parameters.kt * G(r_ij, d_ij) * (dv_ji * t_ij) return force def mag(v): # calc magnitude of vector v_mag = np.sqrt(v.dot(v)) return v_mag def norm(v): # normalize a vector v_norm = v / mag(v) return v_norm def get_neighbors(cur, agents, pn_r): dist = distance.cdist([cur], agents) pn = dist < pn_r # Index to remove is when its zero pn_self = dist == 0 pn_self = np.nonzero(pn_self) pn[pn_self] = False pn = np.nonzero(pn) return pn def compute_force(rr_i, ri, vv_i, mass, goal, pn_rr, pn_vv, pn_r, dt): # Get the force for this agent to the goal goal = calc_goal_force(goal, rr_i, vv_i, mass, Parameters.v_desired, dt) agent = calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r) wall = calc_wall_force() force = goal + agent + wall force = norm(force) * min(mag(force), Parameters.max_speed) return force
3,633
Python
26.323308
102
0.603909
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/socialforces_warp.py
import warp as wp Tau = wp.constant(0.5) # s (acceleration) A = wp.constant(2000.0) # N B = wp.constant(0.08) # m kn = wp.constant(1.2 * 100000) # kg/s^-2 kt = wp.constant(2.4 * 100000) # kg/m^-1 s^-2 max_speed = wp.constant(10.0) # m/s v_desired = wp.constant(2.5) # m/s @wp.kernel def get_forces(positions: wp.array(dtype=wp.vec3), velocities: wp.array(dtype=wp.vec3), goals: wp.array(dtype=wp.vec3), radius: wp.array(dtype=float), mass: wp.array(dtype=float), dt: float, percept : wp.array(dtype=float), grid : wp.uint64, mesh: wp.uint64, inv_up: wp.vec3, forces: wp.array(dtype=wp.vec3), ): # thread index tid = wp.tid() cur_pos = positions[tid] cur_rad = radius[tid] cur_vel = velocities[tid] cur_mass = mass[tid] goal = goals[tid] pn = percept[tid] _force = compute_force(cur_pos, cur_rad, cur_vel, cur_mass, goal, positions, velocities, radius, dt, pn, grid, mesh) # Clear any vertical forces with Element-wise mul _force = wp.cw_mul(_force, inv_up) # compute distance of each point from origin forces[tid] = _force @wp.kernel def integrate(x : wp.array(dtype=wp.vec3), v : wp.array(dtype=wp.vec3), f : wp.array(dtype=wp.vec3), dt: float, xnew: wp.array(dtype=wp.vec3), vnew: wp.array(dtype=wp.vec3), ): tid = wp.tid() x0 = x[tid] v0 = v[tid] f0 = f[tid] v1 = v0 + (f0*1.0) * dt x1 = x0 + v1 * dt xnew[tid] = x1 vnew[tid] = v1 @wp.kernel def heading(v : wp.array(dtype=wp.vec3), up : wp.vec3, forward : wp.vec3, hdir: wp.array(dtype=wp.vec4), ): tid = wp.tid() v0 = v[tid] vnorm = wp.normalize(v0) hdir[tid] = velocity_to_quaternion(up, forward, vnorm) @wp.func def velocity_to_quaternion(up : wp.vec3, forward : wp.vec3, velocity: wp.vec3): # Construct a quaternion that rotates the agent's forward direction to align with the velocity vector if wp.length(forward) > 0: forward = wp.normalize(forward) if wp.length(velocity) > 0: velocity = wp.normalize(velocity) else: velocity = forward dot = wp.dot(forward, velocity) # Clip the dot product to avoid numerical instability if dot == 1.0: # If the forward and velocity vectors are already aligned, return the identity quaternion return wp.vec4(0.0, 0.0, 0.0, 1.0) else: axis = wp.cross(forward, velocity) axis = up * wp.sign(wp.dot(axis, up)) # Project the axis onto the up plane if wp.length(axis) > 0.0: axis = wp.normalize(axis) # Normalize the axis of rotation else:axis = up # Use a default axis of rotation if the iwput is a zero vector angle = wp.acos(dot) # Calculate the angle of rotation with clipping qw = wp.cos(angle/2.0) # Calculate the scalar component of the quaternion qx = wp.sin(angle/2.0) * axis[0] # Calculate the vector component of the quaternion qy = wp.sin(angle/2.0) * axis[1] # Calculate the vector component of the quaternion qz = wp.sin(angle/2.0) * axis[2] # Calculate the vector component of the quaternion return wp.vec4(qx, qy, qz, qw) @wp.func def calc_goal_force(goal: wp.vec3, pos: wp.vec3, vel: wp.vec3, mass: float, v_desired: float, dt: float): ee_i = wp.normalize(goal - pos) force = mass * ( ( (v_desired * ee_i) - vel ) / (Tau) ) return force @wp.func def calc_wall_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, mesh: wp.uint64): ''' rr_i : position ri : radius vv_i : velocity Computes: (A * exp[(ri-diw)/B] + kn*g(ri-diw))*niw - kt * g(ri-diw)(vi * tiw)tiw ''' face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) force = wp.vec3(0.0,0.0,0.0) # Define the up direction up_dir = wp.vec3(0.0, 0.0, 1.0) max_dist = float(ri * 5.0) has_point = wp.mesh_query_point(mesh, rr_i, max_dist, sign, face_index, face_u, face_v) if (not has_point): return wp.vec3(0.0, 0.0, 0.0) p = wp.mesh_eval_position(mesh, face_index, face_u, face_v) # d_iw = distance to wall W d_iw = wp.length(p - rr_i) # vector of the wall to the agent nn_iw = wp.normalize(rr_i - p) # perpendicular vector of the agent-wall (tangent force) tt_iw = wp.cross(up_dir, nn_iw) if wp.dot(vv_i, tt_iw) < 0.0: tt_iw = -1.0 * tt_iw # Compute force # f_iW = { A * exp[(ri-diw)/B] + kn*g(ri-diw) } * niw # - kt * g(ri-diw)(vi * tiw)tiw f_rep = ( A * wp.exp((ri-d_iw)/B) + kn * G(ri, d_iw) ) * nn_iw f_tan = kt * G(ri,d_iw) * wp.dot(vv_i, tt_iw) * tt_iw force = f_rep - f_tan return force @wp.func def calc_agent_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, pn_rr: wp.array(dtype=wp.vec3), pn_vv: wp.array(dtype=wp.vec3), pn_r: wp.array(dtype=float), pn: float, grid : wp.uint64, ): '''Sum the forces of neighboring agents''' # Set the total force of the other agents to zero force = wp.vec3(0.0, 0.0, 0.0) ff_ij = wp.vec3(0.0, 0.0, 0.0) rr_j = wp.vec3(0.0, 0.0, 0.0) # create grid query around point query = wp.hash_grid_query(grid, rr_i, pn) index = int(0) # Iterate through the neighbors and sum (f_ij) while(wp.hash_grid_query_next(query, index)): j = index neighbor = pn_rr[j] # compute distance to neighbor point dist = wp.length(rr_i-neighbor) if (dist <= pn): # Get position and velocity of neighbor agent rr_j = pn_rr[j] vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] # Pass agent position to AgentForce calculation ff_ij = neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j) # Sum Forces force += ff_ij return force @wp.func def neighbor_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, rr_j: wp.vec3, rj: float, vv_j: wp.vec3): '''Calculate the force exerted by another agent. Take in this agent (i) and a neighbors (j) position and radius''' # Sum of radii rij = ri + rj # distance between center of mass d_ij = wp.length(rr_i - rr_j) # "n_ij is the normalized vector points from pedestrian j to i" n_ij = wp.normalize(rr_i - rr_j) # Normalized vector pointing from j to i # t_ij "Vector of tangential relative velocity pointing from i to j." # A sliding force is applied on agent i in this direction to reduce the relative velocity. t_ij = vv_j - vv_i dv_ji = wp.dot(vv_j - vv_i, t_ij) # Calculate f_ij force = repulsion(rij, d_ij, n_ij) + proximity(rij, d_ij, n_ij) + sliding(rij, d_ij, dv_ji, t_ij) return force @wp.func def G(r_ij: float, d_ij: float ): # g(x) is a function that returns zero if pedestrians touch # otherwise is equal to the argument x if (d_ij > r_ij): return 0.0 return r_ij - d_ij @wp.func def repulsion(r_ij: float, d_ij: float, n_ij: wp.vec3): force = A * wp.exp( (r_ij - d_ij) / B) * n_ij return force @wp.func def proximity(r_ij: float, d_ij: float, n_ij: wp.vec3): force = (kn * G(r_ij, d_ij)) * n_ij # body force return force @wp.func def sliding(r_ij: float, d_ij: float, dv_ji: float, t_ij: wp.vec3): force = kt * G(r_ij, d_ij) * (dv_ji * t_ij) return force @wp.func def compute_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, mass:float, goal:wp.vec3, pn_rr: wp.array(dtype=wp.vec3), pn_vv: wp.array(dtype=wp.vec3), pn_r: wp.array(dtype=float), dt: float, pn: float, grid : wp.uint64, mesh: wp.uint64 ): ''' rr_i : position ri : radius vv_i : velocity pn_rr : List[perceived neighbor positions] pn_vv : List[perceived neighbor velocities] pn_r : List[perceived neighbor radius] ''' # Get the force for this agent to the goal goal = calc_goal_force(goal, rr_i, vv_i, mass, v_desired, dt) agent = calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r, pn, grid) wall = calc_wall_force(rr_i, ri, vv_i, mesh) # Sum of forces force = goal + agent + wall force = wp.normalize(force) * wp.min(wp.length(force), max_speed) return force
9,633
Python
29.200627
105
0.508876
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import siborg.simulate.crowd # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = siborg.simulate.crowd.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,678
Python
34.723404
142
0.682956
cadop/crowds/exts/siborg.simulate.crowd/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.0.3-alpha" # The title and description fields are primarily for displaying extension info in UI title = "Crowd Simulation" description="An implementation of the Social Forces crowd simulation (it may or may not be correct). There is currently no environment detection. The current implementation is in PhysX. We plan to support more methods in the future, as well as more crowd simulators. Contributions are welcome." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Create" # Keywords for the extension keywords = ["kit", "example", "crowds", "simulation"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import siborg.simulate.crowd". [[python.module]] name = "siborg.simulate.crowd" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ] [python.pipapi] use_online_index = true requirements = ["scipy"]
1,357
TOML
29.177777
295
0.744289
cadop/crowds/exts/siborg.simulate.crowd/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
cadop/crowds/exts/siborg.simulate.crowd/docs/README.md
# Crowd Simulator A crowd simulator API with a default demo scene. The main python API can be used in a few ways. There is an examples folder showing a few use-cases. Users can also switch between social forces and PAM as the crowds algorithm. The extension will load an populate some demo configuration. It will create an Xform called CrowdGoals. To add a goal for the crowd. Create an xform under the "CrowdGoals". We automatically check for those prims as the method of determing crowd goals. For every additional xform under CrowdGoals, we evenly split the crowd to assign those goals. There are two options for the crowd objects. The default uses geompoints, which is faster and runs its own integration of the forces for position and velocity. It does not interact with any physics in the scene. Alternatively the "Rigid Body" can be used, which creates physical spheres that interact with the scene. Press Play to see the crowd. The default number of demo agents is a 3x3 grid (9 agents). The current simulator in python may struggle above 25 agents, depending on CPU configuration. We plan to support more methods in the future, as well as more crowd simulators. Contributions are welcome.
1,214
Markdown
85.785708
348
0.791598
cadop/arduverse/puppet_handle_1.py
from omni.kit.scripting import BehaviorScript import socket import numpy as np import math from pxr import Gf import numpy as np import math class Puppet2(BehaviorScript): def on_init(self): print(f"{__class__.__name__}.on_init()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8881 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) print("Waiting for data...") def on_destroy(self): print(f"{__class__.__name__}.on_destroy()->{self.prim_path}") self.sock = None rot = [0, 0, 0] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def on_play(self): print(f"{__class__.__name__}.on_play()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8881 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) # Time interval between sensor readings in seconds self.dt = 0.02 def on_pause(self): print(f"{__class__.__name__}.on_pause()->{self.prim_path}") def on_stop(self): print(f"{__class__.__name__}.on_stop()->{self.prim_path}") self.on_destroy() def on_update(self, current_time: float, delta_time: float): self.get_data() def get_data(self): # # Receive data from the Arduino data = self.clear_socket_buffer() if data is None: return # Decode the data and split it into Pitch and Roll data = data.decode() device, pitch, roll, yaw = data.split(",") x,y,z = float(roll), float(yaw), 180-float(pitch) rot = [x, y, z] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def clear_socket_buffer(self): # Function to clear the socket's buffer latest_data = None while True: try: # Try to read data from the socket in a non-blocking way latest_data, addr = self.sock.recvfrom(1024) except BlockingIOError: # No more data to read (buffer is empty) return latest_data
2,384
Python
30.8
72
0.575084
cadop/arduverse/puppet_handle_2.py
from omni.kit.scripting import BehaviorScript import socket import numpy as np import math from pxr import Gf import numpy as np import math class Puppet2(BehaviorScript): def on_init(self): print(f"{__class__.__name__}.on_init()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8882 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) print("Waiting for data...") def on_destroy(self): print(f"{__class__.__name__}.on_destroy()->{self.prim_path}") self.sock = None rot = [0, 0, 0] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def on_play(self): print(f"{__class__.__name__}.on_play()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8882 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) # Time interval between sensor readings in seconds self.dt = 0.02 def on_pause(self): print(f"{__class__.__name__}.on_pause()->{self.prim_path}") def on_stop(self): print(f"{__class__.__name__}.on_stop()->{self.prim_path}") self.on_destroy() def on_update(self, current_time: float, delta_time: float): self.get_data() def get_data(self): # # Receive data from the Arduino data = self.clear_socket_buffer() if data is None: return # Decode the data and split it into Pitch and Roll data = data.decode() device, pitch, roll, yaw = data.split(",") x,y,z = float(roll), float(yaw), 180-float(pitch) rot = [x, y, z] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def clear_socket_buffer(self): # Function to clear the socket's buffer latest_data = None while True: try: # Try to read data from the socket in a non-blocking way latest_data, addr = self.sock.recvfrom(1024) except BlockingIOError: # No more data to read (buffer is empty) return latest_data
2,384
Python
30.8
72
0.575084
cadop/arduverse/README.md
# arduverse Project files and source code for making a real-time streaming from arduino to omniverse Clone/download the repo. You should be able to just open the usda file in *PuppetScene* folder. To use: - Upload the *UDP_FilteredAngle.ino* file to an arduino (RP2040 is what I used). - Make sure to change the wifi network credentials to your own - Try to run the *udp.py* file to make sure the arduino is connecting and sending data - If the udp to python connection is working, you should be able to get the scene running. - To use the base file, in omniverse create a python behavior script on any xform, and attach the script (e.g. *puppet_handle_1.py*) Open an issue if you have problems. Also if you want to contribute go for it. ![Featured Puppet Image](https://github.com/cadop/arduverse/blob/main/FeaturedImg.png?raw=true)
842
Markdown
51.687497
132
0.764846
cadop/arduverse/udp.py
import socket # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT1 = 8881 UDP_PORT2 = 8882 # Create a UDP socket sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock1.bind((UDP_IP, UDP_PORT1)) sock2.bind((UDP_IP, UDP_PORT2)) sock1.setblocking(0) sock2.setblocking(0) print("Waiting for data...") while True: # Receive data from the Arduino try: data, addr = sock1.recvfrom(1024) print("Received message 1:", data.decode()) except: pass try: data, addr = sock2.recvfrom(1024) print("Received message 2:", data.decode()) except: pass
667
Python
22.857142
56
0.668666
cadop/arduverse/PuppetScene/puppet_handle_2.py
from omni.kit.scripting import BehaviorScript import socket import numpy as np import math from pxr import Gf import numpy as np import math class Puppet2(BehaviorScript): def on_init(self): print(f"{__class__.__name__}.on_init()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8882 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) print("Waiting for data...") def on_destroy(self): print(f"{__class__.__name__}.on_destroy()->{self.prim_path}") self.sock.close() self.sock = None rot = [0, 0, 0] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def on_play(self): print(f"{__class__.__name__}.on_play()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8882 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) # Time interval between sensor readings in seconds self.dt = 0.02 def on_pause(self): print(f"{__class__.__name__}.on_pause()->{self.prim_path}") def on_stop(self): print(f"{__class__.__name__}.on_stop()->{self.prim_path}") self.on_destroy() def on_update(self, current_time: float, delta_time: float): self.get_data() def get_data(self): # # Receive data from the Arduino data = self.clear_socket_buffer() if data is None: return # Decode the data and split it into Pitch and Roll data = data.decode() device, pitch, roll, yaw = data.split(",") x,y,z = float(roll), float(yaw), 180-float(pitch) rot = [x, y, z] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def clear_socket_buffer(self): # Function to clear the socket's buffer latest_data = None while True: try: # Try to read data from the socket in a non-blocking way latest_data, addr = self.sock.recvfrom(1024) except BlockingIOError: # No more data to read (buffer is empty) return latest_data
2,424
Python
30.089743
72
0.570957
jshrake-nvidia/kit-cv-video-example/README.md
# kit-cv-video-example Example Omniverse Kit extension that demonstrates how to stream video (webcam, RTSP, mp4, mov, ) to a dynamic texture using [OpenCV VideoCapture](https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html) and [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#byteimageprovider). ![demo](./images/demo.gif) For a basic example of how to use `omni.ui.DynamicTextureProvider`, please see <https://github.com/jshrake-nvidia/kit-dynamic-texture-example>. **WARNING**: This is a prototype and is not necessarily ready for production use. The performance of this example may not meet your performance requirements and is not optimized. This example is a temporary solution until a more mature and optimized streaming solution becomes available in the platform. This example currently only scales to a very limited number of low resolution streams. ## Getting Started - Requires Kit 104.1 >= - Tested in Create 2022.3.1, 2022.3.3 ``` ./link_app.bat --app create ./app/omni.create.bat --/rtx/ecoMode/enabled=false --ext-folder exts --enable omni.cv-video.example ``` Make sure that eco mode is disabled under Render Settings > Raytracing. From the extension UI window, update the URI and click the Create button. A plane prim will be created at (0, 0, 0) with an OmniPBR material containing a dynamic video stream for the albedo texture. The extension should support whatever the OpenCV VideoCapture API supports. Here are a few URIs you can use to test: - Your own web camera: `0` - HLS: `https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8` - RTSP: `rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4`
1,730
Markdown
54.838708
390
0.773988
jshrake-nvidia/kit-cv-video-example/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
jshrake-nvidia/kit-cv-video-example/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
jshrake-nvidia/kit-cv-video-example/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Omni RTSP Dyanmic Texture Example" description = "An example that demonstrates how to stream RTSP feeds using OpenCV and omni.ui.DynamicTextureProvider" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.pipapi" = {} "omni.warp" = {} [python.pipapi] requirements = [ "opencv-python" ] use_online_index = true [[python.module]] name = "omni.cv-video.example" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,245
TOML
23.431372
117
0.728514
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/extension.py
""" Omniverse Kit example extension that demonstrates how to stream video (such as RTSP) to a dynamic texture using [OpenCV VideoCapture](https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html) and [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#byteimageprovider). TODO: - [x] Investigate how to perform the color space conversion and texture updates in a separate thread - [ ] Investigate how to avoid the color space conversion and instead use the native format of the frame provided by OpenCV """ import asyncio import threading import time from typing import List import carb import carb.profiler import cv2 as cv import numpy as np import omni.ext import omni.kit.app import omni.ui from pxr import Kind, Sdf, Usd, UsdGeom, UsdShade DEFAULT_STREAM_URI = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4" #DEFAULT_STREAM_URI = "C:/Users/jshrake/Downloads/1080p.mp4" def create_textured_plane_prim( stage: Usd.Stage, prim_path: str, texture_name: str, width: float, height: float ) -> Usd.Prim: """ Creates a plane prim and an OmniPBR material with a dynamic texture for the albedo map """ hw = width / 2 hh = height / 2 # This code is mostly copy pasted from https://graphics.pixar.com/usd/release/tut_simple_shading.html billboard: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, f"{prim_path}/Mesh") billboard.CreatePointsAttr([(-hw, -hh, 0), (hw, -hh, 0), (hw, hh, 0), (-hw, hh, 0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) billboard.CreateExtentAttr([(-430, -145, 0), (430, 145, 0)]) texCoords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar( "st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying ) texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) material_path = f"{prim_path}/Material" material: UsdShade.Material = UsdShade.Material.Define(stage, material_path) shader: UsdShade.Shader = UsdShade.Shader.Define(stage, f"{material_path}/Shader") shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") shader.CreateIdAttr("OmniPBR") shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(f"dynamic://{texture_name}") material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") billboard.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(billboard).Bind(material) return billboard class OpenCvVideoStream: """ A small abstraction around OpenCV VideoCapture and omni.ui.DynamicTextureProvider, making a one-to-one mapping between the two Resources: - https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html - https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html - https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#omni.ui.ByteImageProvider.set_bytes_data_from_gpu """ def __init__(self, name: str, stream_uri: str): self.name = name self.uri = stream_uri self.texture_array = None try: # Attempt to treat the uri as an int # https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html#a5d5f5dacb77bbebdcbfb341e3d4355c1 stream_uri_as_int = int(stream_uri) self._video_capture = cv.VideoCapture(stream_uri_as_int) except: # Otherwise treat the uri as a str self._video_capture = cv.VideoCapture(stream_uri) self.fps: float = self._video_capture.get(cv.CAP_PROP_FPS) self.width: int = self._video_capture.get(cv.CAP_PROP_FRAME_WIDTH) self.height: int = self._video_capture.get(cv.CAP_PROP_FRAME_HEIGHT) self._dynamic_texture = omni.ui.DynamicTextureProvider(name) self._last_read = time.time() self.is_ok = self._video_capture.isOpened() # If this FPS is 0, set it to something sensible if self.fps == 0: self.fps = 24 @carb.profiler.profile def update_texture(self): # Rate limit frame reads to the underlying FPS of the capture stream now = time.time() time_delta = now - self._last_read if time_delta < 1.0 / self.fps: return self._last_read = now # Read the frame carb.profiler.begin(0, "read") ret, frame = self._video_capture.read() carb.profiler.end(0) # The video may be at the end, loop by setting the frame position back to 0 if not ret: self._video_capture.set(cv.CAP_PROP_POS_FRAMES, 0) self._last_read = time.time() return # By default, OpenCV converts the frame to BGR # We need to convert the frame to a texture format suitable for RTX # In this case, we convert to BGRA, but the full list of texture formats can be found at # # kit\source\extensions\omni.gpu_foundation\bindings\python\omni.gpu_foundation_factory\GpuFoundationFactoryBindingsPython.cpp frame: np.ndarray carb.profiler.begin(0, "color space conversion") frame = cv.cvtColor(frame, cv.COLOR_BGR2RGBA) carb.profiler.end(0) height, width, channels = frame.shape carb.profiler.begin(0, "set_bytes_data") self._dynamic_texture.set_data_array(frame, [width, height, channels]) carb.profiler.end(0) class OmniRtspExample(omni.ext.IExt): def on_startup(self, ext_id): # stream = omni.kit.app.get_app().get_update_event_stream() # self._sub = stream.create_subscription_to_pop(self._update_streams, name="update") self._streams: List[OpenCvVideoStream] = [] self._stream_threads: List[threading.Thread] = [] self._stream_uri_model = omni.ui.SimpleStringModel(DEFAULT_STREAM_URI) self._window = omni.ui.Window("OpenCV Video Streaming Example", width=800, height=200) with self._window.frame: with omni.ui.VStack(): omni.ui.StringField(model=self._stream_uri_model) omni.ui.Button("Create", clicked_fn=self._on_click_create) @carb.profiler.profile def _update_stream(self, i): async def loop(): while self._running: await asyncio.sleep(0.001) self._streams[i].update_texture() asyncio.run(loop()) def _on_click_create(self): name = f"Video{len(self._streams)}" image_name = name usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() prim_path = f"/World/{name}" # If the prim already exists, remove it so we can create it again try: stage.RemovePrim(prim_path) self._streams = [stream for stream in self._streams if stream.name != image_name] except: pass # Create the stream stream_uri = self._stream_uri_model.get_value_as_string() video_stream = OpenCvVideoStream(image_name, stream_uri) if not video_stream.is_ok: carb.log_error(f"Error opening stream: {stream_uri}") return self._streams.append(video_stream) carb.log_info(f"Creating video steam {stream_uri} {video_stream.width}x{video_stream.height}") # Create the mesh + material + shader model_root = UsdGeom.Xform.Define(stage, prim_path) Usd.ModelAPI(model_root).SetKind(Kind.Tokens.component) create_textured_plane_prim(stage, prim_path, image_name, video_stream.width, video_stream.height) # Clear the string model # self._stream_uri_model.set_value("") # Create the thread to pump the video stream self._running = True i = len(self._streams) - 1 thread = threading.Thread(target=self._update_stream, args=(i, )) thread.daemon = True thread.start() self._stream_threads.append(thread) def on_shutdown(self): # self._sub.unsubscribe() self._running = False for thread in self._stream_threads: thread.join() self._stream_threads = [] self._streams = []
8,262
Python
43.187166
201
0.657105
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/__init__.py
# TODO: Work around OM-108110 # by explicitly adding the python3.dll directory to the DLL search path list. # cv2.dll fails to load because it can't load the python3.dll dependency try: import os import pathlib import sys # The python3.dll lives in the python directory adjacent to the kit executable # Get the path to the current kit process exe_path = sys.executable exe_dir = pathlib.Path(exe_path).parent python_dir = exe_dir / "python" print(f"Adding {python_dir} to DLL search path list") os.add_dll_directory(python_dir) except Exception as e: print(f"Error adding python directory to DLL search path list {e}") from .extension import *
690
Python
33.549998
82
0.718841
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.hello.world # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = omni.hello.world.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,668
Python
34.510638
142
0.681055
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
jshrake-nvidia/kit-dynamic-texture-example/README.md
# Dynamic Texture Provider Example Demonstrates how to programmatically generate a textured quad using the [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html) API. Tested against Create 2022.3.1. ```console .\link_app.bat --path C:\Users\jshrake\AppData\Local\ov\pkg\prod-create-2022.3.1 .\app\omni.create.bat --ext-folder exts --enable omni.dynamic_texture_example ``` ![demo](./demo.gif) ## *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
7,339
Markdown
46.662337
318
0.751329
jshrake-nvidia/kit-dynamic-texture-example/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
jshrake-nvidia/kit-dynamic-texture-example/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
jshrake-nvidia/kit-dynamic-texture-example/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Dynamic Texture Example" description = "Demonstrates how to programmatically generate a textured quad using the omni.ui.DynamicTextureProvider API" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.pipapi" = {} [python.pipapi] requirements = [ "pillow" ] use_online_index = true # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.dynamic_texture_example" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,329
TOML
25.078431
122
0.738901
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/omni/dynamic_texture_example/extension.py
''' Demonstrates how to programmatically generate a textured quad using the omni.ui.DynamicTextureProvider API. This is contrived example that reads the image from the local filesystem (cat.jpg). You can imagine sourcing the image bytes from a network request instead. Resources: - https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html - See the full list of omni.ui.TextureFormat variants at .\app\kit\extscore\omni.gpu_foundation\omni\gpu_foundation_factory\_gpu_foundation_factory.pyi TODO(jshrake): - [ ] Currently the dynamic texture name only works with the OmniPBR.mdl material. Need to understand why it doesn't work with other materials, such as UsdPreviewSurface. - [ ] Test instantiating and using the DynamicTextureProvider in a separate thread ''' from typing import Tuple, Union import pathlib import omni import omni.ui as ui from PIL import Image from pxr import Kind, Sdf, Usd, UsdGeom, UsdShade def create_textured_plane_prim(stage: Usd.Stage, prim_path: str, texture_name: str) -> Usd.Prim: # This code is mostly copy pasted from https://graphics.pixar.com/usd/release/tut_simple_shading.html billboard: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, f"{prim_path}/Mesh") billboard.CreatePointsAttr([(-430, -145, 0), (430, -145, 0), (430, 145, 0), (-430, 145, 0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0,1,2,3]) billboard.CreateExtentAttr([(-430, -145, 0), (430, 145, 0)]) texCoords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) texCoords.Set([(0, 0), (1, 0), (1,1), (0, 1)]) material_path = f"{prim_path}/Material" material = UsdShade.Material.Define(stage, material_path) shader: UsdShade.Shader = UsdShade.Shader.Define(stage, f"{material_path}/Shader") shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") shader.CreateIdAttr("OmniPBR") shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(f"dynamic://{texture_name}") material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") billboard.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(billboard).Bind(material) return billboard def create_dynamic_texture(texture_name: str, bytes: bytes, resolution: Tuple[int, int], format: ui.TextureFormat) -> ui.DynamicTextureProvider: # See https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#omni.ui.ByteImageProvider.set_bytes_data_from_gpu bytes_list = list(bytes) dtp = ui.DynamicTextureProvider(texture_name) dtp.set_bytes_data(bytes_list, list(resolution), format) return dtp class DynamicTextureProviderExample(omni.ext.IExt): def on_startup(self, ext_id): self._texture: Union[None, ui.DynamicTextureProvider] = None self._window = ui.Window("Create Dynamic Texture Provider Example", width=300, height=300) with self._window.frame: ui.Button("Create", clicked_fn=self._on_click_create) def _on_click_create(self): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() name = f"TexturePlane" image_name = name prim_path = f"/World/{name}" # If the prim already exists, remove it so we can create it again try: stage.RemovePrim(prim_path) self._texture = None except: pass # Create the prim root model_root = UsdGeom.Xform.Define(stage, prim_path) Usd.ModelAPI(model_root).SetKind(Kind.Tokens.component) # Create the mesh + material + shader create_textured_plane_prim(stage, prim_path, image_name) # Open the adjacent cat.jpg file and create the texture dir = pathlib.Path(__file__).parent.resolve() image_path = dir.joinpath("cat.jpg") image: Image.Image = Image.open(image_path, mode='r') # Ensure the image format is RGBA image = image.convert('RGBA') image_bytes = image.tobytes() image_resolution = (image.width, image.height) image_format = ui.TextureFormat.RGBA8_UNORM self._texture = create_dynamic_texture(image_name, image_bytes, image_resolution, image_format) def on_shutdown(self): self._texture = None
4,533
Python
48.282608
156
0.692698
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/omni/dynamic_texture_example/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/omni/dynamic_texture_example/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/omni/dynamic_texture_example/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.hello.world # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = omni.hello.world.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,668
Python
34.510638
142
0.681055
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
renanmb/Omniverse_legged_robotics/README.md
The idea of this repo is to start converting open source models of robots into Omniverse Isaac-Sim friendly format. # URDF Descriptions The URDFs found in this repository have been forked/modified/linked from the following projects: ## Quadrupeds - [kodlab_gazebo - Ghost Robotics](https://github.com/KodlabPenn/kodlab_gazebo) - [ANYbotics](https://github.com/ANYbotics) - [ANYbotics' ANYmal B](https://github.com/ANYbotics/anymal_b_simple_description) - [ANYbotics' ANYmal B - Modified for CHAMP](https://github.com/chvmp/anymal_b_simple_description) - [ANYbotics' ANYmal C](https://github.com/ANYbotics/anymal_c_simple_description) - [ANYbotics' ANYmal B - Modified for CHAMP](https://github.com/chvmp/anymal_c_simple_description) - Boston Dynamic's Little Dog - [Boston Dynamic's Little Dog - by RobotLocomotion](https://github.com/RobotLocomotion/LittleDog) - [Boston Dynamic's Little Dog - Modified for CHAMP](https://github.com/chvmp/littledog_description) - Boston Dynamic's Spot - [Boston Dynamic's Spot - by heuristicus](https://github.com/heuristicus/spot_ros) - [Boston Dynamic's Spot - Modified for CHAMP](https://github.com/chvmp/spot_ros) - [Dream Walker](https://github.com/Ohaginia/dream_walker) - [MIT Mini Cheetah - Original](https://github.com/HitSZwang/mini-cheetah-gazebo-urdf) - [MIT Mini Cheetah - Modified for CHAMP](https://github.com/chvmp/mini-cheetah-gazebo-urdf) - [OpenDog V2 - Original](https://github.com/XRobots/openDogV2) - [OpenDog V2 - Modified for CHAMP](https://github.com/chvmp/opendog_description) - Open Quadruped - [Open Quadruped](https://github.com/moribots/spot_mini_mini) - [SpotMicroAI - Gitlab](https://gitlab.com/custom_robots/spotmicroai) - [Spot Micro](https://github.com/chvmp/spotmicro_description) - [Unitree Robotics All](https://github.com/unitreerobotics/unitree_ros) - [Unitree Robotics All - Modified for CHAMP](https://github.com/chvmp/unitree_ros) - [Unitree Robotics' A1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/a1_description) - [Unitree Robotics' AliengoZ1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/aliengoZ1_description) - [Unitree Robotics'Aliengo](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/aliengo_description) - [Unitree Robotics' B1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/b1_description) - [Unitree Robotics' Go1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/go1_description) - [Unitree Robotics' Laikago](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/laikago_description) - [Unitree Robotics' Z1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/z1_description) - [Stochlab's Stochlite](https://stochlab.github.io/) - [Stochlab's Stochlite - Modified by aditya-shirwatkar](https://github.com/aditya-shirwatkar/stochlite_description) - Mini Pupper - [MangDang's Mini Pupper](https://github.com/mangdangroboticsclub/QuadrupedRobot) - [simplified robot description of the MangDang's Mini Pupper](https://github.com/nisshan-x/mini_pupper_description) - [Stanford pupper - Original](https://stanfordstudentrobotics.org/pupper) - [Stanford pupper - Modified by Chandykunju Alex](https://github.com/chandyalex/stanford_pupper_description.git) ## Bipedal - [Agility Robotics' Cassie - UMich-BipedLab](https://github.com/UMich-BipedLab/cassie_description) - [Agility Robotics' Digit - DigitRobot.jl](https://github.com/adubredu/DigitRobot.jl) - [NJIT - TOCABI](https://github.com/cadop/tocabi) ## Manipulation - [GoogleAI ROBEL D'Kitty](https://github.com/google-research/robel-scenes) - [GoogleAI ROBEL D'Kitty - Modified for CHAMP](https://github.com/chvmp/dkitty_description) - [The Shadow Robot Company](https://github.com/shadow-robot) - [Shadow Hand - archived](https://github.com/AndrejOrsula/shadow_hand_ign) # ## Cassie_description This repository contains the .urdf model of the CASSIE robot from Agility Robotics. It also includes a way to visualize the robot using ROS and rviz. https://github.com/UMich-BipedLab/cassie_description ## a1 robot simulation - Python version This repository contains all the files and code needed to simulate the a1 quadrupedal robot using Gazebo and ROS. The software runs on ROS noetic and Ubuntu 20.04. https://github.com/lnotspotl/a1_sim_py ## Here are the ROS simulation packages for Unitree robots https://github.com/unitreerobotics/unitree_ros ## Zoo from CHAMP This repository contains configuration packages of various quadrupedal robots generated by CHAMP's setup assistant. The URDFs found in this repository have been forked/modified/linked from the following projects: https://github.com/chvmp/robots
4,799
Markdown
66.605633
163
0.761617
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/z1_description/config/robot_control.yaml
z1_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 Joint01_controller: type: unitree_legged_control/UnitreeJointController joint: joint1 pid: {p: 300.0, i: 0.0, d: 5.0} Joint02_controller: type: unitree_legged_control/UnitreeJointController joint: joint2 pid: {p: 300.0, i: 0.0, d: 5.0} Joint03_controller: type: unitree_legged_control/UnitreeJointController joint: joint3 pid: {p: 300.0, i: 0.0, d: 5.0} Joint04_controller: type: unitree_legged_control/UnitreeJointController joint: joint4 pid: {p: 300.0, i: 0.0, d: 5.0} Joint05_controller: type: unitree_legged_control/UnitreeJointController joint: joint5 pid: {p: 300.0, i: 0.0, d: 5.0} Joint06_controller: type: unitree_legged_control/UnitreeJointController joint: joint6 pid: {p: 300.0, i: 0.0, d: 5.0} gripper_controller: type: unitree_legged_control/UnitreeJointController joint: jointGripper pid: {p: 300.0, i: 0.0, d: 5.0}
1,227
YAML
29.699999
66
0.594947
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/laikago_description/config/robot_control.yaml
laikago_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 # FL Controllers --------------------------------------- FL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # FR Controllers --------------------------------------- FR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RL Controllers --------------------------------------- RL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RR Controllers --------------------------------------- RR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0}
2,291
YAML
31.28169
66
0.553907
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/a1_description/config/robot_control.yaml
a1_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 # FL Controllers --------------------------------------- FL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # FR Controllers --------------------------------------- FR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RL Controllers --------------------------------------- RL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RR Controllers --------------------------------------- RR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0}
2,286
YAML
31.211267
66
0.552931
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/aliengoZ1_description/config/robot_control.yaml
aliengoZ1_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 # FL Controllers --------------------------------------- FL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # FR Controllers --------------------------------------- FR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RL Controllers --------------------------------------- RL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RR Controllers --------------------------------------- RR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} Joint01_controller: type: unitree_legged_control/UnitreeJointController joint: joint1 pid: {p: 300.0, i: 0.0, d: 5.0} Joint02_controller: type: unitree_legged_control/UnitreeJointController joint: joint2 pid: {p: 300.0, i: 0.0, d: 5.0} Joint03_controller: type: unitree_legged_control/UnitreeJointController joint: joint3 pid: {p: 300.0, i: 0.0, d: 5.0} Joint04_controller: type: unitree_legged_control/UnitreeJointController joint: joint4 pid: {p: 300.0, i: 0.0, d: 5.0} Joint05_controller: type: unitree_legged_control/UnitreeJointController joint: joint5 pid: {p: 300.0, i: 0.0, d: 5.0} Joint06_controller: type: unitree_legged_control/UnitreeJointController joint: joint6 pid: {p: 300.0, i: 0.0, d: 5.0} gripper_controller: type: unitree_legged_control/UnitreeJointController joint: jointGripper pid: {p: 300.0, i: 0.0, d: 5.0}
3,328
YAML
30.40566
66
0.56881
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/README.md
# Introduction Here are the ROS simulation packages for Unitree robots, You can load robots and joint controllers in Gazebo, so you can perform low-level control (control the torque, position and angular velocity) of the robot joints. Please be aware that the Gazebo simulation cannot do high-level control, namely walking. Aside from these simulation functions, you can also control your real robots in ROS with the [unitree_ros_to_real](https://github.com/unitreerobotics/unitree_ros_to_real) packages. For real robots, you can do high-level and low-level control using our ROS packages. ## Packages: Robot description: `go1_description`, `a1_description`, `aliengo_description`, `laikago_description` Robot and joints controller: `unitree_controller` Simulation related: `unitree_gazebo`, `unitree_legged_control` # Dependencies * [ROS](https://www.ros.org/) Melodic or ROS Kinetic (has not been tested) * [Gazebo8](http://gazebosim.org/) * [unitree_legged_msgs](https://github.com/unitreerobotics/unitree_ros_to_real): `unitree_legged_msgs` is a package under [unitree_ros_to_real](https://github.com/unitreerobotics/unitree_ros_to_real). # Build <!-- If you would like to fully compile the `unitree_ros`, please run the following command to install relative packages. --> For ROS Melodic: ``` sudo apt-get install ros-melodic-controller-interface ros-melodic-gazebo-ros-control ros-melodic-joint-state-controller ros-melodic-effort-controllers ros-melodic-joint-trajectory-controller ``` For ROS Kinetic: ``` sudo apt-get install ros-kinetic-controller-manager ros-kinetic-ros-control ros-kinetic-ros-controllers ros-kinetic-joint-state-controller ros-kinetic-effort-controllers ros-kinetic-velocity-controllers ros-kinetic-position-controllers ros-kinetic-robot-controllers ros-kinetic-robot-state-publisher ros-kinetic-gazebo8-ros ros-kinetic-gazebo8-ros-control ros-kinetic-gazebo8-ros-pkgs ros-kinetic-gazebo8-ros-dev ``` And open the file `unitree_gazebo/worlds/stairs.world`. At the end of the file: ``` <include> <uri>model:///home/unitree/catkin_ws/src/unitree_ros/unitree_gazebo/worlds/building_editor_models/stairs</uri> </include> ``` Please change the path of `building_editor_models/stairs` to the real path on your PC. Then you can use catkin_make to build: ``` cd ~/catkin_ws catkin_make ``` If you face a dependency problem, you can just run `catkin_make` again. # Detail of Packages ## unitree_legged_control: It contains the joints controllers for Gazebo simulation, which allows users to control joints with position, velocity and torque. Refer to "[unitree_ros/unitree_controller/src/servo.cpp](https://github.com/unitreerobotics/unitree_ros/blob/master/unitree_controller/src/servo.cpp)" for joint control examples in different modes. ## The description of robots: Namely the description of Go1, A1, Aliengo and Laikago. Each package includes mesh, urdf and xacro files of robot. Take Laikago for example, you can check the model in Rviz by: ``` roslaunch laikago_description laikago_rviz.launch ``` ## unitree_gazebo & unitree_controller: You can launch the Gazebo simulation with the following command: ``` roslaunch unitree_gazebo normal.launch rname:=a1 wname:=stairs ``` Where the `rname` means robot name, which can be `laikago`, `aliengo`, `a1` or `go1`. The `wname` means world name, which can be `earth`, `space` or `stairs`. And the default value of `rname` is `laikago`, while the default value of `wname` is `earth`. In Gazebo, the robot should be lying on the ground with joints not activated. ### Stand controller After launching the gazebo simulation, you can start to control the robot: ``` rosrun unitree_controller unitree_servo ``` And you can add external disturbances, like a push or a kick: ``` rosrun unitree_controller unitree_external_force ``` ### Position and pose publisher Here we demonstrated how to control the position and pose of robot without a controller, which should be useful in SLAM or visual development. Then run the position and pose publisher in another terminal: ``` rosrun unitree_controller unitree_move_kinetic ``` The robot will turn around the origin, which is the movement under the world coordinate frame. And inside of the source file [move_publisher.cpp](https://github.com/unitreerobotics/unitree_ros/blob/master/unitree_controller/src/move_publisher.cpp), we also provide the method to move using the robot coordinate frame. You can change the value of `def_frame` to `coord::ROBOT` and run the catkin_make again, then the `unitree_move_publisher` will move robot under its own coordinate frame.
4,596
Markdown
57.935897
574
0.779373
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_gazebo/plugin/foot_contact_plugin.cc
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <string> #include <gazebo/common/Events.hh> #include <ros/ros.h> #include <ros/advertise_options.h> #include <gazebo/gazebo.hh> #include <gazebo/sensors/sensors.hh> #include <geometry_msgs/WrenchStamped.h> namespace gazebo { class UnitreeFootContactPlugin : public SensorPlugin { public: UnitreeFootContactPlugin() : SensorPlugin(){} ~UnitreeFootContactPlugin(){} void Load(sensors::SensorPtr _sensor, sdf::ElementPtr _sdf) { this->parentSensor = std::dynamic_pointer_cast<sensors::ContactSensor>(_sensor); // Make sure the parent sensor is valid. if (!this->parentSensor){ gzerr << "UnitreeFootContactPlugin requires a ContactSensor.\n"; return; } this->contact_namespace = "contact/"; this->rosnode = new ros::NodeHandle(this->contact_namespace); // add "visual" is for the same name of draw node this->force_pub = this->rosnode->advertise<geometry_msgs::WrenchStamped>("/visual/"+_sensor->Name()+"/the_force", 100); // Connect to the sensor update event. this->update_connection = this->parentSensor->ConnectUpdated(std::bind(&UnitreeFootContactPlugin::OnUpdate, this)); this->parentSensor->SetActive(true); // Make sure the parent sensor is active. count = 0; Fx = 0; Fy = 0; Fz = 0; ROS_INFO("Load %s plugin.", _sensor->Name().c_str()); } private: void OnUpdate() { msgs::Contacts contacts; contacts = this->parentSensor->Contacts(); count = contacts.contact_size(); // std::cout << count <<"\n"; for (unsigned int i = 0; i < count; ++i){ if(contacts.contact(i).position_size() != 1){ ROS_ERROR("Contact count isn't correct!!!!"); } for (unsigned int j = 0; j < contacts.contact(i).position_size(); ++j){ // std::cout << i <<" "<< contacts.contact(i).position_size() <<" Force:" // << contacts.contact(i).wrench(j).body_1_wrench().force().x() << " " // << contacts.contact(i).wrench(j).body_1_wrench().force().y() << " " // << contacts.contact(i).wrench(j).body_1_wrench().force().z() << "\n"; Fx += contacts.contact(i).wrench(0).body_1_wrench().force().x(); // Notice: the force is in local coordinate, not in world or base coordnate. Fy += contacts.contact(i).wrench(0).body_1_wrench().force().y(); Fz += contacts.contact(i).wrench(0).body_1_wrench().force().z(); } } if(count != 0){ force.wrench.force.x = Fx/double(count); force.wrench.force.y = Fy/double(count); force.wrench.force.z = Fz/double(count); count = 0; Fx = 0; Fy = 0; Fz = 0; } else{ force.wrench.force.x = 0; force.wrench.force.y = 0; force.wrench.force.z = 0; } this->force_pub.publish(force); } private: ros::NodeHandle* rosnode; ros::Publisher force_pub; event::ConnectionPtr update_connection; std::string contact_namespace; sensors::ContactSensorPtr parentSensor; geometry_msgs::WrenchStamped force; int count = 0; double Fx=0, Fy=0, Fz=0; }; GZ_REGISTER_SENSOR_PLUGIN(UnitreeFootContactPlugin) }
4,092
C++
42.542553
161
0.503666
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_gazebo/plugin/draw_force_plugin.cc
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <ignition/math/Color.hh> #include <gazebo/common/Events.hh> #include <gazebo/msgs/msgs.hh> #include <gazebo/transport/Node.hh> #include <gazebo/common/Plugin.hh> #include <ros/ros.h> #include "gazebo/rendering/DynamicLines.hh" #include "gazebo/rendering/RenderTypes.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/rendering/Scene.hh" #include <ros/ros.h> #include <boost/bind.hpp> #include <geometry_msgs/WrenchStamped.h> namespace gazebo { class UnitreeDrawForcePlugin : public VisualPlugin { public: UnitreeDrawForcePlugin():line(NULL){} ~UnitreeDrawForcePlugin(){ this->visual->DeleteDynamicLine(this->line); } void Load(rendering::VisualPtr _parent, sdf::ElementPtr _sdf ) { this->visual = _parent; this->visual_namespace = "visual/"; if (!_sdf->HasElement("topicName")){ ROS_INFO("Force draw plugin missing <topicName>, defaults to /default_force_draw"); this->topic_name = "/default_force_draw"; } else{ this->topic_name = _sdf->Get<std::string>("topicName"); } if (!ros::isInitialized()){ int argc = 0; char** argv = NULL; ros::init(argc,argv,"gazebo_visual",ros::init_options::NoSigintHandler|ros::init_options::AnonymousName); } this->line = this->visual->CreateDynamicLine(rendering::RENDERING_LINE_STRIP); this->line->AddPoint(ignition::math::Vector3d(0, 0, 0), common::Color(0, 1, 0, 1.0)); this->line->AddPoint(ignition::math::Vector3d(1, 1, 1), common::Color(0, 1, 0, 1.0)); this->line->setMaterial("Gazebo/Purple"); this->line->setVisibilityFlags(GZ_VISIBILITY_GUI); this->visual->SetVisible(true); this->rosnode = new ros::NodeHandle(this->visual_namespace); this->force_sub = this->rosnode->subscribe(this->topic_name+"/"+"the_force", 30, &UnitreeDrawForcePlugin::GetForceCallback, this); this->update_connection = event::Events::ConnectPreRender(boost::bind(&UnitreeDrawForcePlugin::OnUpdate, this)); ROS_INFO("Load %s Draw Force plugin.", this->topic_name.c_str()); } void OnUpdate() { this->line->SetPoint(1, ignition::math::Vector3d(Fx, Fy, Fz)); } void GetForceCallback(const geometry_msgs::WrenchStamped & msg) { Fx = msg.wrench.force.x/20.0; Fy = msg.wrench.force.y/20.0; Fz = msg.wrench.force.z/20.0; // Fx = msg.wrench.force.x; // Fy = msg.wrench.force.y; // Fz = msg.wrench.force.z; } private: ros::NodeHandle* rosnode; std::string topic_name; rendering::VisualPtr visual; rendering::DynamicLines *line; std::string visual_namespace; ros::Subscriber force_sub; double Fx=0, Fy=0, Fz=0; event::ConnectionPtr update_connection; }; GZ_REGISTER_VISUAL_PLUGIN(UnitreeDrawForcePlugin) }
3,448
C++
39.104651
142
0.571056
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/move_publisher.cpp
#include <ros/ros.h> #include <gazebo_msgs/ModelState.h> #include <gazebo_msgs/SetModelState.h> #include <string> #include <stdio.h> #include <tf/transform_datatypes.h> // #include <std_msgs/Float64.h> #include <math.h> #include <iostream> int main(int argc, char **argv) { enum coord { WORLD, ROBOT }; coord def_frame = coord::WORLD; ros::init(argc, argv, "move_publisher"); ros::NodeHandle nh; ros::Publisher move_publisher = nh.advertise<gazebo_msgs::ModelState>("/gazebo/set_model_state", 1000); gazebo_msgs::ModelState model_state_pub; std::string robot_name; ros::param::get("/robot_name", robot_name); std::cout << "robot_name: " << robot_name << std::endl; model_state_pub.model_name = robot_name + "_gazebo"; ros::Rate loop_rate(1000); if(def_frame == coord::WORLD) { model_state_pub.pose.position.x = 0.0; model_state_pub.pose.position.y = 0.0; model_state_pub.pose.position.z = 0.5; model_state_pub.pose.orientation.x = 0.0; model_state_pub.pose.orientation.y = 0.0; model_state_pub.pose.orientation.z = 0.0; model_state_pub.pose.orientation.w = 1.0; model_state_pub.reference_frame = "world"; long long time_ms = 0; //time, ms const double period = 5000; //ms const double radius = 1.5; //m tf::Quaternion q; while(ros::ok()) { model_state_pub.pose.position.x = radius * sin(2*M_PI*(double)time_ms/period); model_state_pub.pose.position.y = radius * cos(2*M_PI*(double)time_ms/period); model_state_pub.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, - 2*M_PI*(double)time_ms/period); move_publisher.publish(model_state_pub); loop_rate.sleep(); time_ms += 1; } } else if(def_frame == coord::ROBOT) { model_state_pub.twist.linear.x= 0.02; //0.02: 2cm/sec model_state_pub.twist.linear.y= 0.0; model_state_pub.twist.linear.z= 0.08; model_state_pub.twist.angular.x= 0.0; model_state_pub.twist.angular.y= 0.0; model_state_pub.twist.angular.z= 0.0; model_state_pub.reference_frame = "base"; while(ros::ok()) { move_publisher.publish(model_state_pub); loop_rate.sleep(); } } }
2,425
C++
29.325
126
0.585567
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/external_force.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <ros/ros.h> #include <geometry_msgs/Wrench.h> #include <signal.h> #include <termios.h> #include <stdio.h> #define KEYCODE_UP 0x41 #define KEYCODE_DOWN 0x42 #define KEYCODE_LEFT 0x44 #define KEYCODE_RIGHT 0x43 #define KEYCODE_SPACE 0x20 int mode = 1; // pulsed mode or continuous mode class teleForceCmd { public: teleForceCmd(); void keyLoop(); void pubForce(double x, double y, double z); private: double Fx, Fy, Fz; ros::NodeHandle n; ros::Publisher force_pub; geometry_msgs::Wrench Force; }; teleForceCmd::teleForceCmd() { Fx = 0; Fy = 0; Fz = 0; force_pub = n.advertise<geometry_msgs::Wrench>("/apply_force/trunk", 20); sleep(1); pubForce(Fx, Fy, Fz); } int kfd = 0; struct termios cooked, raw; void quit(int sig) { tcsetattr(kfd, TCSANOW, &cooked); ros::shutdown(); exit(0); } int main(int argc, char** argv) { ros::init(argc, argv, "external_force"); teleForceCmd remote; signal(SIGINT,quit); remote.keyLoop(); return(0); } void teleForceCmd::pubForce(double x, double y, double z) { Force.force.x = Fx; Force.force.y = Fy; Force.force.z = Fz; force_pub.publish(Force); ros::spinOnce(); } void teleForceCmd::keyLoop() { char c; bool dirty=false; // get the console in raw mode tcgetattr(kfd, &cooked); memcpy(&raw, &cooked, sizeof(struct termios)); raw.c_lflag &=~ (ICANON | ECHO); // Setting a new line, then end of file raw.c_cc[VEOL] = 1; raw.c_cc[VEOF] = 2; tcsetattr(kfd, TCSANOW, &raw); puts("Reading from keyboard"); puts("---------------------------"); puts("Use 'Space' to change mode, default is Pulsed mode:"); puts("Use 'Up/Down/Left/Right' to change direction"); for(;;){ // get the next event from the keyboard if(read(kfd, &c, 1) < 0){ perror("read():"); exit(-1); } ROS_DEBUG("value: 0x%02X\n", c); switch(c){ case KEYCODE_UP: if(mode > 0) { Fx = 60; } else { Fx += 16; if(Fx > 220) Fx = 220; if(Fx < -220) Fx = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_DOWN: if(mode > 0) { Fx = -60; } else { Fx -= 16; if(Fx > 220) Fx = 220; if(Fx < -220) Fx = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_LEFT: if(mode > 0) { Fy = 30; } else { Fy += 8; if(Fy > 220) Fy = 220; if(Fy < -220) Fy = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_RIGHT: if(mode > 0) { Fy = -30; } else { Fy -= 8; if(Fy > 220) Fy = 220; if(Fy < -220) Fy = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_SPACE: mode = mode*(-1); if(mode > 0){ ROS_INFO("Change to Pulsed mode."); } else { ROS_INFO("Change to Continuous mode."); } Fx = 0; Fy = 0; Fz = 0; ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; } if(dirty == true){ pubForce(Fx, Fy, Fz); if(mode > 0){ usleep(100000); // 100 ms Fx = 0; Fy = 0; Fz = 0; pubForce(Fx, Fy, Fz); } dirty=false; } } return; }
4,382
C++
25.245509
77
0.446143
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/body.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include "body.h" namespace unitree_model { ros::Publisher servo_pub[12]; unitree_legged_msgs::LowCmd lowCmd; unitree_legged_msgs::LowState lowState; // These parameters are only for reference. // Actual patameters need to be debugged if you want to run on real robot. void paramInit() { for(int i=0; i<4; i++){ lowCmd.motorCmd[i*3+0].mode = 0x0A; lowCmd.motorCmd[i*3+0].Kp = 70; lowCmd.motorCmd[i*3+0].dq = 0; lowCmd.motorCmd[i*3+0].Kd = 3; lowCmd.motorCmd[i*3+0].tau = 0; lowCmd.motorCmd[i*3+1].mode = 0x0A; lowCmd.motorCmd[i*3+1].Kp = 180; lowCmd.motorCmd[i*3+1].dq = 0; lowCmd.motorCmd[i*3+1].Kd = 8; lowCmd.motorCmd[i*3+1].tau = 0; lowCmd.motorCmd[i*3+2].mode = 0x0A; lowCmd.motorCmd[i*3+2].Kp = 300; lowCmd.motorCmd[i*3+2].dq = 0; lowCmd.motorCmd[i*3+2].Kd = 15; lowCmd.motorCmd[i*3+2].tau = 0; } for(int i=0; i<12; i++){ lowCmd.motorCmd[i].q = lowState.motorState[i].q; } } void stand() { double pos[12] = {0.0, 0.67, -1.3, -0.0, 0.67, -1.3, 0.0, 0.67, -1.3, -0.0, 0.67, -1.3}; moveAllPosition(pos, 2*1000); } void motion_init() { paramInit(); stand(); } void sendServoCmd() { for(int m=0; m<12; m++){ servo_pub[m].publish(lowCmd.motorCmd[m]); } ros::spinOnce(); usleep(1000); } void moveAllPosition(double* targetPos, double duration) { double pos[12] ,lastPos[12], percent; for(int j=0; j<12; j++) lastPos[j] = lowState.motorState[j].q; for(int i=1; i<=duration; i++){ if(!ros::ok()) break; percent = (double)i/duration; for(int j=0; j<12; j++){ lowCmd.motorCmd[j].q = lastPos[j]*(1-percent) + targetPos[j]*percent; } sendServoCmd(); } } }
2,130
C++
26.320512
82
0.532394
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/servo.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include "ros/ros.h" #include <stdio.h> #include <stdlib.h> #include "unitree_legged_msgs/LowCmd.h" #include "unitree_legged_msgs/LowState.h" #include "unitree_legged_msgs/MotorCmd.h" #include "unitree_legged_msgs/MotorState.h" #include <geometry_msgs/WrenchStamped.h> #include <sensor_msgs/Imu.h> #include <std_msgs/Bool.h> #include <vector> #include <string> #include <math.h> #include <nav_msgs/Odometry.h> #include "body.h" using namespace std; using namespace unitree_model; bool start_up = true; class multiThread { public: multiThread(string rname){ robot_name = rname; imu_sub = nm.subscribe("/trunk_imu", 1, &multiThread::imuCallback, this); footForce_sub[0] = nm.subscribe("/visual/FR_foot_contact/the_force", 1, &multiThread::FRfootCallback, this); footForce_sub[1] = nm.subscribe("/visual/FL_foot_contact/the_force", 1, &multiThread::FLfootCallback, this); footForce_sub[2] = nm.subscribe("/visual/RR_foot_contact/the_force", 1, &multiThread::RRfootCallback, this); footForce_sub[3] = nm.subscribe("/visual/RL_foot_contact/the_force", 1, &multiThread::RLfootCallback, this); servo_sub[0] = nm.subscribe("/" + robot_name + "_gazebo/FR_hip_controller/state", 1, &multiThread::FRhipCallback, this); servo_sub[1] = nm.subscribe("/" + robot_name + "_gazebo/FR_thigh_controller/state", 1, &multiThread::FRthighCallback, this); servo_sub[2] = nm.subscribe("/" + robot_name + "_gazebo/FR_calf_controller/state", 1, &multiThread::FRcalfCallback, this); servo_sub[3] = nm.subscribe("/" + robot_name + "_gazebo/FL_hip_controller/state", 1, &multiThread::FLhipCallback, this); servo_sub[4] = nm.subscribe("/" + robot_name + "_gazebo/FL_thigh_controller/state", 1, &multiThread::FLthighCallback, this); servo_sub[5] = nm.subscribe("/" + robot_name + "_gazebo/FL_calf_controller/state", 1, &multiThread::FLcalfCallback, this); servo_sub[6] = nm.subscribe("/" + robot_name + "_gazebo/RR_hip_controller/state", 1, &multiThread::RRhipCallback, this); servo_sub[7] = nm.subscribe("/" + robot_name + "_gazebo/RR_thigh_controller/state", 1, &multiThread::RRthighCallback, this); servo_sub[8] = nm.subscribe("/" + robot_name + "_gazebo/RR_calf_controller/state", 1, &multiThread::RRcalfCallback, this); servo_sub[9] = nm.subscribe("/" + robot_name + "_gazebo/RL_hip_controller/state", 1, &multiThread::RLhipCallback, this); servo_sub[10] = nm.subscribe("/" + robot_name + "_gazebo/RL_thigh_controller/state", 1, &multiThread::RLthighCallback, this); servo_sub[11] = nm.subscribe("/" + robot_name + "_gazebo/RL_calf_controller/state", 1, &multiThread::RLcalfCallback, this); } void imuCallback(const sensor_msgs::Imu & msg) { lowState.imu.quaternion[0] = msg.orientation.w; lowState.imu.quaternion[1] = msg.orientation.x; lowState.imu.quaternion[2] = msg.orientation.y; lowState.imu.quaternion[3] = msg.orientation.z; lowState.imu.gyroscope[0] = msg.angular_velocity.x; lowState.imu.gyroscope[1] = msg.angular_velocity.y; lowState.imu.gyroscope[2] = msg.angular_velocity.z; lowState.imu.accelerometer[0] = msg.linear_acceleration.x; lowState.imu.accelerometer[1] = msg.linear_acceleration.y; lowState.imu.accelerometer[2] = msg.linear_acceleration.z; } void FRhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[0].mode = msg.mode; lowState.motorState[0].q = msg.q; lowState.motorState[0].dq = msg.dq; lowState.motorState[0].tauEst = msg.tauEst; } void FRthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[1].mode = msg.mode; lowState.motorState[1].q = msg.q; lowState.motorState[1].dq = msg.dq; lowState.motorState[1].tauEst = msg.tauEst; } void FRcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[2].mode = msg.mode; lowState.motorState[2].q = msg.q; lowState.motorState[2].dq = msg.dq; lowState.motorState[2].tauEst = msg.tauEst; } void FLhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[3].mode = msg.mode; lowState.motorState[3].q = msg.q; lowState.motorState[3].dq = msg.dq; lowState.motorState[3].tauEst = msg.tauEst; } void FLthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[4].mode = msg.mode; lowState.motorState[4].q = msg.q; lowState.motorState[4].dq = msg.dq; lowState.motorState[4].tauEst = msg.tauEst; } void FLcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[5].mode = msg.mode; lowState.motorState[5].q = msg.q; lowState.motorState[5].dq = msg.dq; lowState.motorState[5].tauEst = msg.tauEst; } void RRhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[6].mode = msg.mode; lowState.motorState[6].q = msg.q; lowState.motorState[6].dq = msg.dq; lowState.motorState[6].tauEst = msg.tauEst; } void RRthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[7].mode = msg.mode; lowState.motorState[7].q = msg.q; lowState.motorState[7].dq = msg.dq; lowState.motorState[7].tauEst = msg.tauEst; } void RRcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[8].mode = msg.mode; lowState.motorState[8].q = msg.q; lowState.motorState[8].dq = msg.dq; lowState.motorState[8].tauEst = msg.tauEst; } void RLhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[9].mode = msg.mode; lowState.motorState[9].q = msg.q; lowState.motorState[9].dq = msg.dq; lowState.motorState[9].tauEst = msg.tauEst; } void RLthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[10].mode = msg.mode; lowState.motorState[10].q = msg.q; lowState.motorState[10].dq = msg.dq; lowState.motorState[10].tauEst = msg.tauEst; } void RLcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[11].mode = msg.mode; lowState.motorState[11].q = msg.q; lowState.motorState[11].dq = msg.dq; lowState.motorState[11].tauEst = msg.tauEst; } void FRfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[0].x = msg.wrench.force.x; lowState.eeForce[0].y = msg.wrench.force.y; lowState.eeForce[0].z = msg.wrench.force.z; lowState.footForce[0] = msg.wrench.force.z; } void FLfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[1].x = msg.wrench.force.x; lowState.eeForce[1].y = msg.wrench.force.y; lowState.eeForce[1].z = msg.wrench.force.z; lowState.footForce[1] = msg.wrench.force.z; } void RRfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[2].x = msg.wrench.force.x; lowState.eeForce[2].y = msg.wrench.force.y; lowState.eeForce[2].z = msg.wrench.force.z; lowState.footForce[2] = msg.wrench.force.z; } void RLfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[3].x = msg.wrench.force.x; lowState.eeForce[3].y = msg.wrench.force.y; lowState.eeForce[3].z = msg.wrench.force.z; lowState.footForce[3] = msg.wrench.force.z; } private: ros::NodeHandle nm; ros::Subscriber servo_sub[12], footForce_sub[4], imu_sub; string robot_name; }; int main(int argc, char **argv) { ros::init(argc, argv, "unitree_gazebo_servo"); string robot_name; ros::param::get("/robot_name", robot_name); cout << "robot_name: " << robot_name << endl; multiThread listen_publish_obj(robot_name); ros::AsyncSpinner spinner(1); // one threads spinner.start(); usleep(300000); // must wait 300ms, to get first state ros::NodeHandle n; ros::Publisher lowState_pub; //for rviz visualization // ros::Rate loop_rate(1000); // the following nodes have been initialized by "gazebo.launch" lowState_pub = n.advertise<unitree_legged_msgs::LowState>("/" + robot_name + "_gazebo/lowState/state", 1); servo_pub[0] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_hip_controller/command", 1); servo_pub[1] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_thigh_controller/command", 1); servo_pub[2] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_calf_controller/command", 1); servo_pub[3] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_hip_controller/command", 1); servo_pub[4] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_thigh_controller/command", 1); servo_pub[5] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_calf_controller/command", 1); servo_pub[6] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_hip_controller/command", 1); servo_pub[7] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_thigh_controller/command", 1); servo_pub[8] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_calf_controller/command", 1); servo_pub[9] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_hip_controller/command", 1); servo_pub[10] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_thigh_controller/command", 1); servo_pub[11] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_calf_controller/command", 1); motion_init(); while (ros::ok()){ /* control logic */ lowState_pub.publish(lowState); sendServoCmd(); } return 0; }
10,620
C++
41.654618
133
0.638606
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/include/body.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #ifndef __BODY_H__ #define __BODY_H__ #include "ros/ros.h" #include "unitree_legged_msgs/LowCmd.h" #include "unitree_legged_msgs/LowState.h" #include "unitree_legged_msgs/HighState.h" #define PosStopF (2.146E+9f) #define VelStopF (16000.f) namespace unitree_model { extern ros::Publisher servo_pub[12]; extern ros::Publisher highState_pub; extern unitree_legged_msgs::LowCmd lowCmd; extern unitree_legged_msgs::LowState lowState; void stand(); void motion_init(); void sendServoCmd(); void moveAllPosition(double* jointPositions, double duration); } #endif
855
C
27.533332
73
0.626901
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/unitree_controller_plugins.xml
<library path="lib/libunitree_legged_control"> <class name="unitree_legged_control/UnitreeJointController" type="unitree_legged_control::UnitreeJointController" base_class_type="controller_interface::ControllerBase"/> <description> The unitree joint controller. </description> </library>
354
XML
38.44444
75
0.661017
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/src/joint_controller.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ // #include "unitree_legged_control/joint_controller.h" #include "joint_controller.h" #include <pluginlib/class_list_macros.h> // #define rqtTune // use rqt or not namespace unitree_legged_control { UnitreeJointController::UnitreeJointController(){ memset(&lastCmd, 0, sizeof(unitree_legged_msgs::MotorCmd)); memset(&lastState, 0, sizeof(unitree_legged_msgs::MotorState)); memset(&servoCmd, 0, sizeof(ServoCmd)); } UnitreeJointController::~UnitreeJointController(){ sub_ft.shutdown(); sub_cmd.shutdown(); } void UnitreeJointController::setTorqueCB(const geometry_msgs::WrenchStampedConstPtr& msg) { if(isHip) sensor_torque = msg->wrench.torque.x; else sensor_torque = msg->wrench.torque.y; // printf("sensor torque%f\n", sensor_torque); } void UnitreeJointController::setCommandCB(const unitree_legged_msgs::MotorCmdConstPtr& msg) { lastCmd.mode = msg->mode; lastCmd.q = msg->q; lastCmd.Kp = msg->Kp; lastCmd.dq = msg->dq; lastCmd.Kd = msg->Kd; lastCmd.tau = msg->tau; // the writeFromNonRT can be used in RT, if you have the guarantee that // * no non-rt thread is calling the same function (we're not subscribing to ros callbacks) // * there is only one single rt thread command.writeFromNonRT(lastCmd); } // Controller initialization in non-realtime bool UnitreeJointController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { isHip = false; isThigh = false; isCalf = false; // rqtTune = false; sensor_torque = 0; name_space = n.getNamespace(); if (!n.getParam("joint", joint_name)){ ROS_ERROR("No joint given in namespace: '%s')", n.getNamespace().c_str()); return false; } // load pid param from ymal only if rqt need // if(rqtTune) { #ifdef rqtTune // Load PID Controller using gains set on parameter server if (!pid_controller_.init(ros::NodeHandle(n, "pid"))) return false; #endif // } urdf::Model urdf; // Get URDF info about joint if (!urdf.initParamWithNodeHandle("robot_description", n)){ ROS_ERROR("Failed to parse urdf file"); return false; } joint_urdf = urdf.getJoint(joint_name); if (!joint_urdf){ ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str()); return false; } if(joint_name == "FR_hip_joint" || joint_name == "FL_hip_joint" || joint_name == "RR_hip_joint" || joint_name == "RL_hip_joint"){ isHip = true; } if(joint_name == "FR_calf_joint" || joint_name == "FL_calf_joint" || joint_name == "RR_calf_joint" || joint_name == "RL_calf_joint"){ isCalf = true; } joint = robot->getHandle(joint_name); // Start command subscriber sub_ft = n.subscribe(name_space + "/" +"joint_wrench", 1, &UnitreeJointController::setTorqueCB, this); sub_cmd = n.subscribe("command", 20, &UnitreeJointController::setCommandCB, this); // pub_state = n.advertise<unitree_legged_msgs::MotorState>(name_space + "/state", 20); // Start realtime state publisher controller_state_publisher_.reset( new realtime_tools::RealtimePublisher<unitree_legged_msgs::MotorState>(n, name_space + "/state", 1)); return true; } void UnitreeJointController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min, const bool &antiwindup) { pid_controller_.setGains(p,i,d,i_max,i_min,antiwindup); } void UnitreeJointController::getGains(double &p, double &i, double &d, double &i_max, double &i_min, bool &antiwindup) { pid_controller_.getGains(p,i,d,i_max,i_min,antiwindup); } void UnitreeJointController::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { bool dummy; pid_controller_.getGains(p,i,d,i_max,i_min,dummy); } // Controller startup in realtime void UnitreeJointController::starting(const ros::Time& time) { // lastCmd.Kp = 0; // lastCmd.Kd = 0; double init_pos = joint.getPosition(); lastCmd.q = init_pos; lastState.q = init_pos; lastCmd.dq = 0; lastState.dq = 0; lastCmd.tau = 0; lastState.tauEst = 0; command.initRT(lastCmd); pid_controller_.reset(); } // Controller update loop in realtime void UnitreeJointController::update(const ros::Time& time, const ros::Duration& period) { double currentPos, currentVel, calcTorque; lastCmd = *(command.readFromRT()); // set command data if(lastCmd.mode == PMSM) { servoCmd.pos = lastCmd.q; positionLimits(servoCmd.pos); servoCmd.posStiffness = lastCmd.Kp; if(fabs(lastCmd.q - PosStopF) < 0.00001){ servoCmd.posStiffness = 0; } servoCmd.vel = lastCmd.dq; velocityLimits(servoCmd.vel); servoCmd.velStiffness = lastCmd.Kd; if(fabs(lastCmd.dq - VelStopF) < 0.00001){ servoCmd.velStiffness = 0; } servoCmd.torque = lastCmd.tau; effortLimits(servoCmd.torque); } if(lastCmd.mode == BRAKE) { servoCmd.posStiffness = 0; servoCmd.vel = 0; servoCmd.velStiffness = 20; servoCmd.torque = 0; effortLimits(servoCmd.torque); } // } else { // servoCmd.posStiffness = 0; // servoCmd.velStiffness = 5; // servoCmd.torque = 0; // } // rqt set P D gains // if(rqtTune) { #ifdef rqtTune double i, i_max, i_min; getGains(servoCmd.posStiffness,i,servoCmd.velStiffness,i_max,i_min); #endif // } currentPos = joint.getPosition(); currentVel = computeVel(currentPos, (double)lastState.q, (double)lastState.dq, period.toSec()); calcTorque = computeTorque(currentPos, currentVel, servoCmd); effortLimits(calcTorque); joint.setCommand(calcTorque); lastState.q = currentPos; lastState.dq = currentVel; // lastState.tauEst = calcTorque; // lastState.tauEst = sensor_torque; lastState.tauEst = joint.getEffort(); // pub_state.publish(lastState); // publish state if (controller_state_publisher_ && controller_state_publisher_->trylock()) { controller_state_publisher_->msg_.q = lastState.q; controller_state_publisher_->msg_.dq = lastState.dq; controller_state_publisher_->msg_.tauEst = lastState.tauEst; controller_state_publisher_->unlockAndPublish(); } // printf("sensor torque%f\n", sensor_torque); // if(joint_name == "wrist1_joint") printf("wrist1 setp:%f getp:%f t:%f\n", servoCmd.pos, currentPos, calcTorque); } // Controller stopping in realtime void UnitreeJointController::stopping(){} void UnitreeJointController::positionLimits(double &position) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(position, joint_urdf->limits->lower, joint_urdf->limits->upper); } void UnitreeJointController::velocityLimits(double &velocity) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(velocity, -joint_urdf->limits->velocity, joint_urdf->limits->velocity); } void UnitreeJointController::effortLimits(double &effort) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(effort, -joint_urdf->limits->effort, joint_urdf->limits->effort); } } // namespace // Register controller to pluginlib PLUGINLIB_EXPORT_CLASS(unitree_legged_control::UnitreeJointController, controller_interface::ControllerBase);
8,576
C++
36.291304
158
0.592001
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/include/unitree_joint_control_tool.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ // #ifndef _UNITREE_JOINT_CONTROL_TOOL_H_ // #define _UNITREE_JOINT_CONTROL_TOOL_H_ #ifndef _LAIKAGO_CONTROL_TOOL_H_ #define _LAIKAGO_CONTROL_TOOL_H_ #include <stdio.h> #include <stdint.h> #include <algorithm> #include <math.h> #define posStopF (2.146E+9f) // stop position control mode #define velStopF (16000.0f) // stop velocity control mode typedef struct { uint8_t mode; double pos; double posStiffness; double vel; double velStiffness; double torque; } ServoCmd; double clamp(double&, double, double); // eg. clamp(1.5, -1, 1) = 1 double computeVel(double current_position, double last_position, double last_velocity, double duration); // get current velocity double computeTorque(double current_position, double current_velocity, ServoCmd&); // get torque #endif
1,099
C
31.35294
129
0.627843
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/include/joint_controller.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #ifndef _UNITREE_ROS_JOINT_CONTROLLER_H_ #define _UNITREE_ROS_JOINT_CONTROLLER_H_ #include <ros/node_handle.h> #include <urdf/model.h> #include <control_toolbox/pid.h> #include <boost/scoped_ptr.hpp> #include <boost/thread/condition.hpp> #include <realtime_tools/realtime_publisher.h> #include <hardware_interface/joint_command_interface.h> #include <controller_interface/controller.h> #include <std_msgs/Float64.h> #include <realtime_tools/realtime_buffer.h> #include <controller_interface/controller.h> #include <hardware_interface/joint_command_interface.h> #include "unitree_legged_msgs/MotorCmd.h" #include "unitree_legged_msgs/MotorState.h" #include <geometry_msgs/WrenchStamped.h> #include "unitree_joint_control_tool.h" #define PMSM (0x0A) #define BRAKE (0x00) #define PosStopF (2.146E+9f) #define VelStopF (16000.0f) namespace unitree_legged_control { class UnitreeJointController: public controller_interface::Controller<hardware_interface::EffortJointInterface> { private: hardware_interface::JointHandle joint; ros::Subscriber sub_cmd, sub_ft; // ros::Publisher pub_state; control_toolbox::Pid pid_controller_; boost::scoped_ptr<realtime_tools::RealtimePublisher<unitree_legged_msgs::MotorState> > controller_state_publisher_ ; public: // bool start_up; std::string name_space; std::string joint_name; float sensor_torque; bool isHip, isThigh, isCalf, rqtTune; urdf::JointConstSharedPtr joint_urdf; realtime_tools::RealtimeBuffer<unitree_legged_msgs::MotorCmd> command; unitree_legged_msgs::MotorCmd lastCmd; unitree_legged_msgs::MotorState lastState; ServoCmd servoCmd; UnitreeJointController(); ~UnitreeJointController(); virtual bool init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n); virtual void starting(const ros::Time& time); virtual void update(const ros::Time& time, const ros::Duration& period); virtual void stopping(); void setTorqueCB(const geometry_msgs::WrenchStampedConstPtr& msg); void setCommandCB(const unitree_legged_msgs::MotorCmdConstPtr& msg); void positionLimits(double &position); void velocityLimits(double &velocity); void effortLimits(double &effort); void setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min, const bool &antiwindup = false); void getGains(double &p, double &i, double &d, double &i_max, double &i_min, bool &antiwindup); void getGains(double &p, double &i, double &d, double &i_max, double &i_min); }; } #endif
2,999
C
39.54054
147
0.674558
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/robots/laikago_description/config/robot_control.yaml
laikago_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 # FL Controllers --------------------------------------- FL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # FR Controllers --------------------------------------- FR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RL Controllers --------------------------------------- RL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RR Controllers --------------------------------------- RR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0}
2,291
YAML
31.28169
66
0.553907