file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcMultiplyMatrix.py | import numpy
# Create 4x4 matrix (identity matrix).
m1 = numpy.matrix(numpy.identity(4))
m2 = numpy.matrix(numpy.identity(4))
m1[3] = [22.3, 15.5, 3.0, 1.0]
m2[3] = [50.0, 100.0, -20.0, 1.0]
# Multiply matrix.
# (Same result for mA and mB)
mA = m1 * m2
mB = numpy.dot(m1, m2)
print(mA)
print(mB)
| 300 | Python | 16.705881 | 38 | 0.633333 |
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcVectorDotCross.py | import numpy
v1 = numpy.array([0.0, 1.0, 2.0])
v2 = numpy.array([1.2, 1.5, 2.3])
# Calculating the Inner Product.
v = numpy.dot(v1, v2)
print("Inner product : " + str(v))
# Calculating the Outer Product.
v = numpy.cross(v1, v2)
print("Outer product : " + str(v))
| 266 | Python | 19.53846 | 34 | 0.635338 |
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcMultiplyMatrixVector.py | import numpy
# Create Vector3.
v1 = numpy.array([0.0, 1.0, 2.0])
# Create 4x4 matrix.
m1 = numpy.matrix(numpy.identity(4))
m1[3] = [22.3, 15.5, 3.0, 1.0]
# Make sure that the vector to be multiplied has four elements.
vec4 = numpy.array(v1)
if v1.size == 3:
vec4 = numpy.array([v1[0], v1[1], v1[2], 1.0])
# Vector and matrix multiplication.
retM = numpy.dot(vec4, m1)
print(retM)
# Replace the result with Vector3.
retV = numpy.array([retM[0,0], retM[0,1], retM[0,2]])
print(retV)
| 488 | Python | 21.227272 | 63 | 0.657787 |
ft-lab/omniverse_sample_scripts/pip_archive/PIL/readme.md | # Pillow(PIL)
Pillow(PIL)を使用して、2D画像の操作を行います。
|ファイル|説明|
|---|---|
|[LoadImage.py](./LoadImage.py) |画像の読み込み|
|[DrawImage.py](./DrawImage.py) |画像の描画と出力|
| 177 | Markdown | 16.799998 | 47 | 0.564972 |
ft-lab/omniverse_sample_scripts/pip_archive/PIL/DrawImage.py | # PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image, ImageDraw, ImageFont
# Create new image.
im = Image.new("RGBA", (512, 512), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
# Draw rectangle (fill).
draw.rectangle((100, 100, 200, 200), fill=(255, 0, 0))
# Draw rectangle.
draw.rectangle((100, 220, 200, 320), outline=(0, 0, 255), width=1)
# Draw line.
draw.line((0, 0, im.width, im.height), fill=(0, 255, 0), width=2)
# Draw circle.
draw.ellipse((100, 400, 150, 450), outline=(0, 0, 255), width=2)
# Draw circle (fill).
draw.ellipse((280, 300, 380, 400), fill=(0, 0, 255))
# Polygon.
vers = ((40, 20), (140, 120), (180, 60))
draw.polygon(vers, outline=(128, 0, 0))
# Polygon (fill).
vers = ((240, 20), (340, 120), (380, 60))
draw.polygon(vers, fill=(128, 128, 0))
# Font.
font = None
try:
# The ttf font path should be replaced according to your environment.
basePath = "K:/fonts"
fontPath = basePath + "/SourceHanSansJP-Bold.otf"
font = ImageFont.truetype(fontPath, 48)
except Exception as e:
print(e)
# Draw text.
if font != None:
draw.multiline_text((16, 40), 'Draw Text!', fill=(0, 128, 0))
# Save image.
# Rewrite it to any file path and uncomment the following.
#im.save("K:/NVIDIA_omniverse/images/out.png", quality=95)
| 1,299 | Python | 25.530612 | 73 | 0.645112 |
ft-lab/omniverse_sample_scripts/pip_archive/PIL/LoadImage.py | # PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image
# Load image from file.
path = "K:/NVIDIA_omniverse/images/omniverse_64.png"
im = None
try:
im = Image.open(path)
# Get image size.
wid = im.size[0]
hei = im.size[1]
print("Image size : " + str(wid) + " x " + str(hei))
# Get format (PNG, JPEG, etc).
print("Format : " + str(im.format))
# Get mode (RGB, RGBA, etc.).
print("Mode : " + str(im.mode))
except Exception as e:
print(e)
| 515 | Python | 20.499999 | 66 | 0.6 |
ft-lab/omniverse_sample_scripts/Material/readme.md | # Material
マテリアルの割り当て/取得。
なお、テクスチャファイルについては「[textures](./textures)」をローカルの相対パスの位置に配置してご使用くださいませ。
マテリアルは UsdShade.Material ( https://graphics.pixar.com/usd/release/api/class_usd_shade_material.html )で定義されます。
Primに対して以下のようにバインドすることで、対象形状にマテリアルが反映されます。
```python
UsdShade.MaterialBindingAPI(prim).Bind(material)
```
また、マテリアルはShaderを割り当てる必要があります。
UsdShade.Shader ( https://graphics.pixar.com/usd/release/api/class_usd_shade_shader.html )。
このShaderは、USD標準のUsdPreviewSurfaceを使用するほか、独自のShaderを割り当てることができます。
Omniverseの場合は、MDL ( https://www.nvidia.com/ja-jp/design-visualization/technologies/material-definition-language/ )としてマテリアルを表現します。
|ファイル|説明|
|---|---|
|[UnbindMaterial.py](./UnbindMaterial.py)|選択Primに割り当てられているマテリアルのバインドをクリア|
|サンプル|説明|
|---|---|
|[GetMaterial](./GetMaterial)|マテリアル情報を取得|
|[UsdPreviewSurface](./UsdPreviewSurface)|マテリアルの割り当て (UsdPreviewSurface)|
|[OmniPBR](./OmniPBR)|マテリアルの割り当て (OmniPBR)|
| 984 | Markdown | 36.884614 | 134 | 0.731707 |
ft-lab/omniverse_sample_scripts/Material/UnbindMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Unbind Material.
UsdShade.MaterialBindingAPI(prim).UnbindAllBindings()
| 403 | Python | 25.933332 | 63 | 0.704715 |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithDiffuseTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Set Diffuse texture.
# Note : Texture files should be specified in the path where they exist.
#textureFilePath = '../textures/tile_image.png'
textureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/tile_image.png'
diffTexIn = shader.CreateInput('diffuse_texture', Sdf.ValueTypeNames.Asset)
diffTexIn.Set(textureFilePath)
diffTexIn.GetAttr().SetColorSpace('sRGB')
# Set Diffuse value.
diffTintIn = shader.CreateInput('diffuse_tint', Sdf.ValueTypeNames.Color3f)
diffTintIn.Set((0.9, 0.9, 0.9))
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
| 2,293 | Python | 35.999999 | 142 | 0.746184 |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithCommand.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit.commands
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create new material.
omni.kit.commands.execute('CreateAndBindMdlMaterialFromLibrary', mdl_name='OmniPBR.mdl',
mtl_name='OmniPBR', mtl_created_list=['/World/Looks/OmniPBR'])
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
# Path of the added material.
selectPrimPath = ""
for path in selectedPaths:
selectPrimPath = path
break
print(selectPrimPath) | 580 | Python | 26.666665 | 88 | 0.75 |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/readme.md | # OmniPBR
OmniPBRのマテリアルを割り当て。
|ファイル|説明|
|---|---|
|[CreateMaterial.py](./CreateMaterial.py)|球にシンプルなマテリアルを割り当て。<br>|
|[CreateMaterialWithCommand.py](./CreateMaterialWithCommand.py)|omni.kit.commandsを使ってOmniPBRの新しいマテリアルを作成|
|[CreateMaterialWithDiffuseTexture.py](./CreateMaterialWithDiffuseTexture.py)|MeshにdiffuseColorテクスチャを割り当てる。<br>|
|[CreateMaterialWithDiffuseNormalTexture.py](./CreateMaterialWithDiffuseNormalTexture.py)|MeshにdiffuseColorテクスチャ/法線マップテクスチャを割り当てる。<br>|
| 742 | Markdown | 60.916662 | 238 | 0.803235 |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithDiffuseNormalTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Set Diffuse texture.
# Note : Texture files should be specified in the path where they exist.
#diffuseTextureFilePath = '../textures/stone_01_diffuse.png'
diffuseTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_diffuse.png'
diffTexIn = shader.CreateInput('diffuse_texture', Sdf.ValueTypeNames.Asset)
diffTexIn.Set(diffuseTextureFilePath)
diffTexIn.GetAttr().SetColorSpace('sRGB')
# Set Diffuse value.
diffTintIn = shader.CreateInput('diffuse_tint', Sdf.ValueTypeNames.Color3f)
diffTintIn.Set((0.9, 0.9, 0.9))
# Set normal texture.
# Note : Texture files should be specified in the path where they exist.
#normalTextureFilePath = '../textures/stone_01_normal.png'
normalTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_normal.png'
normalTexIn = shader.CreateInput('normalmap_texture', Sdf.ValueTypeNames.Asset)
normalTexIn.Set(normalTextureFilePath)
# The ColorSpace of the Normal map must be raw.
normalTexIn.GetAttr().SetColorSpace('raw')
# Normal strength.
normalStrengthIn = shader.CreateInput('bump_factor', Sdf.ValueTypeNames.Float)
normalStrengthIn.Set(1.0)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
| 2,911 | Python | 37.315789 | 142 | 0.757472 |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
spherePath = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
sphereGeom.CreateRadiusAttr(20.0)
spherePrim = stage.GetPrimAtPath(spherePath)
spherePrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
spherePrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
prim = sphereGeom.GetPrim()
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
bindAPI = UsdShade.MaterialBindingAPI(prim)
bindAPI.Bind(material)
bindAPI.Apply(prim)
| 1,650 | Python | 32.693877 | 142 | 0.784242 |
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print('[ ' + prim.GetName() + ' ]')
for mTargetPath in pathList:
print(' material : ' + mTargetPath.pathString)
material = UsdShade.Material(stage.GetPrimAtPath(mTargetPath))
print(material)
| 620 | Python | 25.999999 | 70 | 0.680645 |
ft-lab/omniverse_sample_scripts/Material/GetMaterial/readme.md | # GetMaterial
マテリアル情報を取得。
以下は、形状からマテリアルを取得するサンプルです。
|ファイル|説明|
|---|---|
|[GetMaterial.py](./GetMaterial.py)|選択形状のマテリアル情報を取得|
以下は、マテリアルから情報を取得するサンプルです。
|ファイル|説明|
|---|---|
|[GetMaterialType.py](./GetMaterialType.py)|選択マテリアルの種類を取得(UsdPreviewSurface or MDL)|
|[GetMaterialInputs.py](./GetMaterialInputs.py)|選択マテリアルの入力パラメータを取得|
|[GetMaterialTexturePath.py](./GetMaterialTexturePath.py)|選択マテリアルの入力パラメータからテクスチャ情報のみを取得。<br>Sdf.AssetPathのpathは入力そのまま。resolvedPathはフルパスが入っている。|
| 528 | Markdown | 28.388887 | 148 | 0.702652 |
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialTexturePath.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
continue
# List textures referenced by Material.
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
print(f"[{shaderPrim.GetPath().pathString}]")
mInputs = shaderPrim.GetInputs()
for inputV in mInputs:
baseName = inputV.GetBaseName()
typeName = inputV.GetTypeName()
if typeName == "asset":
v = inputV.Get() # Sdf.AssetPath
if v.path != "":
# v.path ... display path.
# v.resolvedPath ... absolute path.
print(f" {baseName}")
print(f" path [ {v.path} ]")
print(f" resolvedPath [ {v.resolvedPath} ]")
| 1,204 | Python | 33.42857 | 73 | 0.524086 |
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialType.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Get material type (UsdPreviewSurface/OmniPBR/CustomMDL etc.)
def GetMaterialType (path : str):
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
return ""
materialTypeName = ""
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
# In the case of UsdPreviewSurface, ImplementationSource is "id".
# In the case of MDL, the ImplementationSource is "sourceAsset".
sourceV = shaderPrim.GetImplementationSource()
if sourceV == "id":
attr = shaderPrim.GetIdAttr()
idValue = attr.Get() # "UsdPreviewSurface"
if idValue == "UsdPreviewSurface":
materialTypeName = idValue
# Get MDL information.
if sourceV == "sourceAsset":
# Sdf.AssetPath
# assetPath.path ... display path.
# assetPath.resolvedPath ... absolute path.
assetPath = shaderPrim.GetSourceAsset("mdl")
# MDL name.
subIdentifier = shaderPrim.GetSourceAssetSubIdentifier("mdl")
if subIdentifier != "":
materialTypeName = subIdentifier
else:
materialTypeName = assetPath.resolvedPath
if materialTypeName != "":
break
return materialTypeName
# -----------------------------------.
for path in paths:
materialTypeName = GetMaterialType(path)
if materialTypeName != "":
print(f"{path} : {materialTypeName}")
| 1,902 | Python | 32.385964 | 77 | 0.569926 |
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialInputs.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
continue
print("[" + prim.GetPath().pathString + "]")
# Get Shader of Material and input parameters.
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
mInputs = shaderPrim.GetInputs()
for inputV in mInputs:
baseName = inputV.GetBaseName()
typeName = inputV.GetTypeName()
print(" [" + baseName + "] (" + str(typeName) + ")")
v = inputV.Get()
print(" " + str(type(v)) + " ==> " + str(v))
| 940 | Python | 28.406249 | 71 | 0.569149 |
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterialWithDiffuseTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Set diffuse texture.
stReader = UsdShade.Shader.Define(stage, materialPath + '/stReader')
stReader.CreateIdAttr('UsdPrimvarReader_float2')
diffuseTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/diffuseTexture')
diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#textureFilePath = '../textures/tile_image.png'
textureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/tile_image.png'
diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(textureFilePath)
diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI(), 'rgb')
stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token)
stInput.Set('st')
stReader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
| 2,616 | Python | 42.616666 | 128 | 0.768731 |
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/readme.md | # UsdPreviewSurface
UsdPreviewSurfaceのマテリアルを割り当て。
|ファイル|説明|
|---|---|
|[CreateMaterial.py](./CreateMaterial.py)|球にシンプルなマテリアルを割り当て。<br>|
|[CreateMaterialWithDiffuseTexture.py](./CreateMaterialWithDiffuseTexture.py) |MeshにdiffuseColorテクスチャを割り当てる。<br>|
|[CreateMaterialWithDiffuseNormalTexture.py](./CreateMaterialWithDiffuseNormalTexture.py)|MeshにdiffuseColorテクスチャ/法線マップテクスチャを割り当てる。<br>|
| 652 | Markdown | 58.363631 | 238 | 0.803681 |
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterialWithDiffuseNormalTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Set diffuse texture.
stReader = UsdShade.Shader.Define(stage, materialPath + '/stReader')
stReader.CreateIdAttr('UsdPrimvarReader_float2')
diffuseTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/diffuseTexture')
diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#diffuseTextureFilePath = '../textures/stone_01_diffuse.png'
diffuseTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_diffuse.png'
diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(diffuseTextureFilePath)
diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI(), 'rgb')
# Set normal texture.
normalTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/normalTexture')
normalTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#normalTextureFilePath = '../textures/stone_01_normal.png'
normalTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_normal.png'
normalTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(normalTextureFilePath)
normalTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
normalTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Normal3f)
pbrShader.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(normalTextureSampler.ConnectableAPI(), 'rgb')
stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token)
stInput.Set('st')
stReader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
| 3,442 | Python | 46.164383 | 128 | 0.781813 |
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
spherePath = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
sphereGeom.CreateRadiusAttr(20.0)
spherePrim = stage.GetPrimAtPath(spherePath)
spherePrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
spherePrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(spherePrim).Bind(material)
| 1,342 | Python | 38.499999 | 89 | 0.792101 |
ft-lab/omniverse_sample_scripts/Python/readme.md | # Python
Pythonの標準的な機能の覚書きです。
## サンプル
|ファイル|説明|
|---|---|
|[string](./string)|文字列処理|
|[Class](./Class)|クラスの使用|
|[Web](./Web)|Webブラウザへのアクセス|
| 160 | Markdown | 11.384615 | 28 | 0.54375 |
ft-lab/omniverse_sample_scripts/Python/Class/readme.md | # Class
Classのサンプル。
## サンプル
|ファイル|説明|
|---|---|
|[SimpleClass.py](./SimpleClass.py)|簡単なクラス。<br>コンストラクタとデストラクタ。|
| 132 | Markdown | 11.090908 | 63 | 0.55303 |
ft-lab/omniverse_sample_scripts/Python/Class/SimpleClass.py | # -----------------------------------------------.
# Simple class.
# -----------------------------------------------.
class ClassFoo:
_name = ""
# Constructor
def __init__(self, name : str):
self.name = name
print("Constructor")
# Destructor
def __del__(self):
print("Destructor")
def printName (self):
print("name = " + self.name)
def add (self, a : float, b : float):
return (a + b)
# -----------------------------------------------.
# Create new class.
foo = ClassFoo("test")
foo.printName()
print(foo.add(12.5, 8.2))
# Destroying a class.
foo = None
| 630 | Python | 18.718749 | 50 | 0.41746 |
ft-lab/omniverse_sample_scripts/Python/string/NumToStr.py | v = 0.25364
# number to string.
# ==> "0.25364"
print("Value = " + str(v))
# Digit number specification.
# ==> "0000.25364"
print("Value : {:#010}".format(v))
print("Value : " + format(v, '#010'))
# Specify the number of decimal places.
# ==> "0.254"
print("Value : {:.3f}".format(v))
print("Value : " + format(v, '.3f'))
# Replaced by hexadecimal.
# ==> "0x7fff"
v2 = 32767
print(hex(v2))
# Replaced by a binary number.
# ==> "0b101"
v2 = 5
print(bin(v2))
| 463 | Python | 16.185185 | 39 | 0.587473 |
ft-lab/omniverse_sample_scripts/Python/string/readme.md | # string
文字列処理。
## サンプル
|ファイル|説明|
|---|---|
|[NumToStr.py](./NumToStr.py)|数値を文字列に変換|
|[StringTest.py](./StringTest.py)|文字列指定時に変数を埋め込む|
| 155 | Markdown | 11.999999 | 49 | 0.567742 |
ft-lab/omniverse_sample_scripts/Python/string/StringTest.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
v = 25.3674
print("Value = " + str(v))
print(f"Value = {v}")
print(f"Type = {type(v)}")
# Specify the number of decimal places.
# ==> "25.367"
print(f"Value = {'{:.3f}'.format(v)}")
vec3 = Gf.Vec3f(1.2, 5.6, 90)
print(f"vec3 = {vec3}")
array = [1.2, "test", True]
print(f"array = {array}")
| 359 | Python | 18.999999 | 63 | 0.5961 |
ft-lab/omniverse_sample_scripts/Python/Web/readme.md | # Web
Webブラウザへのアクセス。
|サンプル|説明|
|---|---|
|[WebOpen](./WebOpen.py)|指定のURLをWebブラウザで開く。|
| 110 | Markdown | 10.099999 | 49 | 0.5 |
ft-lab/omniverse_sample_scripts/Python/Web/WebOpen.py | import webbrowser
url = "https://docs.omniverse.nvidia.com/"
webbrowser.open(url)
| 83 | Python | 15.799997 | 42 | 0.759036 |
ft-lab/omniverse_sample_scripts/AssetConverter/readme.md | # Asset Converter
obj/fbx/glTFなどのファイルをUSDにコンバートします。
|ファイル|説明|
|---|---|
|[importObjToUSD.py](./importObjToUSD.py)|指定のobjファイルをUSDファイルにコンバートします。<br>「[simple_obj.obj](./simple_obj/simple_obj.obj)」を入力のobjファイルの参考にしてくださいませ。|
| 243 | Markdown | 26.111108 | 151 | 0.687243 |
ft-lab/omniverse_sample_scripts/AssetConverter/importObjToUSD.py | # --------------------------------------------------.
# obj to usd conversion.
# See : https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_asset-converter.html
# --------------------------------------------------.
import carb
import omni
import asyncio
import omni.kit.asset_converter
# Progress of processing.
def progress_callback (current_step: int, total: int):
# Show progress
print(f"{current_step} of {total}")
# Convert asset file(obj/fbx/glTF, etc) to usd.
async def convert_asset_to_usd (input_asset: str, output_usd: str):
# Input options are defaults.
converter_context = omni.kit.asset_converter.AssetConverterContext()
converter_context.ignore_materials = False
converter_context.ignore_camera = False
converter_context.ignore_animations = False
converter_context.ignore_light = False
converter_context.export_preview_surface = False
converter_context.use_meter_as_world_unit = False
converter_context.create_world_as_default_root_prim = True
converter_context.embed_textures = True
converter_context.convert_fbx_to_y_up = False
converter_context.convert_fbx_to_z_up = False
converter_context.merge_all_meshes = False
converter_context.use_double_precision_to_usd_transform_op = False
converter_context.ignore_pivots = False
converter_context.keep_all_materials = True
converter_context.smooth_normals = True
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(input_asset, output_usd, progress_callback, converter_context)
# Wait for completion.
success = await task.wait_until_finished()
if not success:
carb.log_error(task.get_status(), task.get_detailed_error())
print("converting done")
# Rewrite it to suit your environment.
input_obj = "K:/Modeling/obj/simple_obj2/simple_obj.obj"
output_usd = "K:/Modeling/obj/simple_obj2/simple_obj/simple_obj.usd"
# Convert to USD (obj to USD).
asyncio.ensure_future(
convert_asset_to_usd(input_obj, output_usd)
)
| 2,014 | Python | 38.509803 | 103 | 0.706554 |
ft-lab/omniverse_sample_scripts/Event/UpdateInterval.py |
import omni.ui
import omni.kit.app
import carb.events
import time
import asyncio
class UpdateInterval:
_viewportWindow = None
_subs = None
_visible = True
_time = None
_vTime = None
def __init__(self):
pass
# Update event.
def on_update (self, e: carb.events.IEvent):
if self._viewportWindow == None:
return
curTime = time.time()
diffTime = curTime - self._time
self._time = curTime
if self._vTime == None:
self._vTime = curTime
if curTime < self._vTime + 0.5 and self._visible:
return
self._vTime = curTime
# Update UI.
with self._viewportWindow.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=30):
# Set label.
fpsV = 1.0 / diffTime
msgStr = "Update interval(sec) : {:.5f} sec, {:.2f} fps".format(diffTime, fpsV)
f = omni.ui.Label(msgStr)
f.visible = self._visible
f.set_style({"color": 0xff00ffff, "font_size": 32})
def startup (self):
# Get main window viewport.
self._viewportWindow = omni.ui.Window('Viewport')
self._time = time.time()
self._visible = True
# Register for update event.
self._subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self.on_update)
def shutdown (self):
# Release the update event.
async def _exitUpdateEvent ():
self._visible = False
await omni.kit.app.get_app().next_update_async()
self._subs = None
self._vTime = None
asyncio.ensure_future(_exitUpdateEvent())
# -----------------------------------------.
updateI = UpdateInterval()
updateI.startup()
# Finish the process below.
#updateI.shutdown()
| 1,942 | Python | 26.757142 | 112 | 0.54068 |
ft-lab/omniverse_sample_scripts/Event/readme.md | # Event
イベント処理を行います。
## 更新イベント
以下のように更新イベントを登録すると、コールバックとして更新処理が呼ばれます。
```python
import omni.kit.app
import carb.events
def on_update(e: carb.events.IEvent):
pass
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update)
```
## サンプル
|ファイル|説明|
|---|---|
|[UpdateInterval.py](./UpdateInterval.py)|update_event_streamの更新間隔をビューポートに表示|
| 401 | Markdown | 15.079999 | 93 | 0.683292 |
ft-lab/omniverse_sample_scripts/System/readme.md | # System
システムの情報を取得します。
|ファイル|説明|
|---|---|
|[GetPythonVersion.py](./GetPythonVersion.py)|Pythonのバージョンを取得|
|[GetSysPath.py](./GetSysPath.py)|Pythonの検索パスの取得と追加|
|[GetUSDVersion.py](./GetUSDVersion.py)|USDのバージョンを取得|
| 247 | Markdown | 21.545453 | 67 | 0.643725 |
ft-lab/omniverse_sample_scripts/System/GetUSDVersion.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
print(Usd.GetVersion())
| 89 | Python | 21.499995 | 63 | 0.741573 |
ft-lab/omniverse_sample_scripts/System/GetPythonVersion.py | import sys
print(sys.version)
| 31 | Python | 6.999998 | 18 | 0.774194 |
ft-lab/omniverse_sample_scripts/System/GetSysPath.py | import sys
import os
# Append path.
def appendSysPath (newPath):
existF = False
for path in sys.path:
if path == newPath:
existF = True
break
if existF:
return
sys.path.append(newPath)
for path in sys.path:
print(path)
| 273 | Python | 12.047618 | 28 | 0.600733 |
ft-lab/omniverse_sample_scripts/Geometry/readme.md | # Geometry
ジオメトリを作成するためのサンプルです。
## primvarの仕様変更
USD 20.08からUSD 22.11にかけて、primvarの仕様が変更されました。
「[UsdGeom.PrimvarsAPI](https://openusd.org/release/api/class_usd_geom_primvars_a_p_i.html)」を使用してprimvarを操作する必要があります。
## Samples
|サンプル|説明|
|---|---|
|[CreateSphere](./CreateSphere)|球を作成<br>UsdGeom.Sphere ( https://graphics.pixar.com/usd/release/api/class_usd_geom_sphere.html )を使用。|
|[CreateCube](./CreateCube)|直方体を作成<br>UsdGeom.Cube ( https://graphics.pixar.com/usd/release/api/class_usd_geom_cube.html )を使用。|
|[CreateMesh](./CreateMesh)|Meshを作成/Mesh情報を取得<br>UsdGeom.Mesh ( https://graphics.pixar.com/usd/release/api/class_usd_geom_mesh.html )を使用。|
|ファイル|説明|
|---|---|
|[GetMeshPrimvars.py](./GetMeshPrimvars.py)|選択Meshの「primvars:xxx」の情報を取得。|
|[SetMeshPrimvars.py](./SetMeshPrimvars.py)|選択Meshにprimvarを追加/削除。|
| 870 | Markdown | 35.291665 | 142 | 0.695402 |
ft-lab/omniverse_sample_scripts/Geometry/SetMeshPrimvars.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Mesh":
continue
m = UsdGeom.Mesh(prim)
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
# Set primvar(float).
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat1", Sdf.ValueTypeNames.Float)
attr = primvarV.GetAttr()
attr.Set((2.2))
if UsdGeom.primvarV(prim).HasPrimvar("dat1"): # Check primvar.
# Remove primvar.
UsdGeom.primvarV(prim).RemovePrimvar("dat1")
# Set primvar (float2).
# If there is already a primvar with the same name but a different type,
# it must be removed using RemoveProperty.
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat1", Sdf.ValueTypeNames.Float2)
attr = primvarV.GetAttr()
attr.Set((1.0, 2.0))
# Set primvar (color).
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat2", Sdf.ValueTypeNames.Color3f)
attr = primvarV.GetAttr()
attr.Set((1.0, 0.5, 0.2))
# Set primvar (float3 array)
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat3", Sdf.ValueTypeNames.Float3Array)
attr = primvarV.GetAttr()
attr.Set([(0.1, 0.2, 0.5), (0.4, 0.05, 0.0), (0.1, 0.4, 0.05)])
| 1,493 | Python | 31.47826 | 94 | 0.667113 |
ft-lab/omniverse_sample_scripts/Geometry/GetMeshPrimvars.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Mesh":
continue
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarsAPI = UsdGeom.PrimvarsAPI(prim)
primvars = primvarsAPI.GetPrimvars()
if len(primvars) > 0:
print("[" + prim.GetPath().pathString + "]")
for primvar in primvars:
primName = primvar.GetPrimvarName()
typeName = primvar.GetTypeName()
val = primvar.Get()
print(" " + primName + " (" + str(typeName) + ") : " + str(val))
| 853 | Python | 28.448275 | 80 | 0.617819 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateSimpleMesh.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, rootPath + "/mesh")
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
# Set normals.
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.SetNormalsInterpolation("vertex")
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
attr = primvarV.GetAttr()
attr.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
# Compute extent.
boundable = UsdGeom.Boundable(meshGeom.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
meshGeom.CreateExtentAttr(extent)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
| 1,538 | Python | 27.499999 | 119 | 0.718466 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateSimpleMeshWithSubset.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# --------------------------------------.
# Create new Material (OmniPBR).
# @param[in] materialPrimPath Prim path of Material
# @param[in] diffuseColor Diffuse color.
# --------------------------------------.
def createMaterialOmniPBR (materialPrimPath : str, diffuseColor : Gf.Vec3f):
material = UsdShade.Material.Define(stage, materialPrimPath)
shaderPath = materialPrimPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set(diffuseColor)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader.ConnectableAPI(), 'out')
return materialPrimPath
# --------------------------------------.
# Create mesh with subset.
# --------------------------------------.
def createMesh (meshPath : str):
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (0, 0, -10), (10, 0, -10), (-10, 0, 0), (0, 0, 0), (10, 0, 0)])
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4, 4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 3, 4, 1, 1, 4, 5, 2])
# Set normals and UVs for each face vertex.
# Set normals.
normalList = []
for i in range(2):
normalList.extend([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.CreateNormalsAttr(normalList)
meshGeom.SetNormalsInterpolation("faceVarying")
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
attr = primvarV.GetAttr()
uvsList = []
uvsList.extend([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0), (1.0, 1.0)])
uvsList.extend([(1.0, 1.0), (1.0, 0.0), (2.0, 0.0), (2.0, 1.0)])
attr.Set(uvsList)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# Create subset 1.
subsetPath = meshPath + "/submesh_1"
geomSubset1 = UsdGeom.Subset.Define(stage, subsetPath)
geomSubset1.CreateFamilyNameAttr("materialBind")
geomSubset1.CreateElementTypeAttr("face")
geomSubset1.CreateIndicesAttr([0]) # Set the index on the face.
# Bind material.
matPrim = stage.GetPrimAtPath(rootPath + "/Looks/mat1")
if matPrim.IsValid():
UsdShade.MaterialBindingAPI(geomSubset1).Bind(UsdShade.Material(matPrim))
# Create subset 2.
subsetPath = meshPath + "/submesh_2"
geomSubset2 = UsdGeom.Subset.Define(stage, subsetPath)
geomSubset2.CreateFamilyNameAttr("materialBind")
geomSubset2.CreateElementTypeAttr("face")
geomSubset2.CreateIndicesAttr([1]) # Set the index on the face.
# Bind material.
matPrim = stage.GetPrimAtPath(rootPath + "/Looks/mat2")
if matPrim.IsValid():
UsdShade.MaterialBindingAPI(geomSubset2).Bind(UsdShade.Material(matPrim))
# -----------------------------------------------------------.
# Create scope.
looksScopePath = rootPath + "/Looks"
scopePrim = stage.GetPrimAtPath(looksScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, looksScopePath)
# Create material.
createMaterialOmniPBR(rootPath + "/Looks/mat1", Gf.Vec3f(1.0, 0.0, 0.0))
createMaterialOmniPBR(rootPath + "/Looks/mat2", Gf.Vec3f(0.0, 1.0, 0.0))
# Create mesh.
createMesh(rootPath + "/mesh") | 4,316 | Python | 34.677686 | 146 | 0.654773 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/GetMeshInfo.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# ---------------------------------------.
# Dump mesh data.
# ---------------------------------------.
def DumpMeshData (prim):
typeName = prim.GetTypeName()
if typeName == 'Mesh':
m = UsdGeom.Mesh(prim)
# Get prim name.
name = prim.GetName()
# Get prim path.
path = prim.GetPath().pathString
# Get show/hide.
showF = (m.ComputeVisibility() == 'inherited')
# Get the number of faces of Mesh.
facesCou = len(m.GetFaceVertexCountsAttr().Get())
# Get number of normals.
normalsCou = len(m.GetNormalsAttr().Get())
# Total number of vertices.
versCou = len(m.GetPointsAttr().Get())
# Get UV.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarsAPI = UsdGeom.PrimvarsAPI(prim)
primvars = primvarsAPI.GetPrimvars()
uvsCou = 0
uvlayersCou = 0
for primvar in primvars:
typeName = str(primvar.GetTypeName().arrayType)
if typeName == 'float2[]' or typeName == 'texCoord2f[]':
# 'st'
pName = primvar.GetPrimvarName()
uvlayersCou += 1
uvsCou = len(primvar.Get())
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print(f"[ {name} ] {path}")
print(f"Show : {showF}")
print(f"Points : {versCou}")
print(f"Faces : {facesCou}")
print(f"uvs : {uvsCou}")
print(f"normals : {normalsCou}")
print(f"UV sets : {uvlayersCou}")
if len(pathList) > 0:
print("Material : ")
for mPath in pathList:
print(f" {mPath.pathString}")
print("")
# ---------------------------------------.
# Traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy (prim):
DumpMeshData(prim)
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
TraverseHierarchy(cPrim)
# ----------------------------------------------------.
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
TraverseHierarchy(prim)
| 2,515 | Python | 27.590909 | 84 | 0.527237 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateGear.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import math
import omni.ui
# Get stage.
stage = omni.usd.get_context().get_stage()
# -------------------------------------------------------.
# Calculate normal.
# -------------------------------------------------------.
def calcTriangleNormal (v1 : Gf.Vec3d, v2 : Gf.Vec3d, v3 : Gf.Vec3d):
e1 = v2 - v1
e2 = v3 - v2
e1 = Gf.Vec4f(e1[0], e1[1], e1[2],1.0)
e2 = Gf.Vec4f(e2[0], e2[1], e2[2],1.0)
e3 = Gf.HomogeneousCross(e1, e2)
n = Gf.Vec3d(e3[0], e3[1], e3[2])
return n.GetNormalized()
# -------------------------------------------------------.
# Attach thickness.
# @param[in] primPath Target Prim path.
# @param[in] thickness Thickness.
# -------------------------------------------------------.
def AttachThickness (primPath : str, thickness : float):
prim = stage.GetPrimAtPath(primPath)
if prim.IsValid() == False:
return
if prim.GetTypeName() != 'Mesh':
return
m = UsdGeom.Mesh(prim)
# Number of faces.
faceVCouList = m.GetFaceVertexCountsAttr().Get()
faceCou = len(faceVCouList)
if faceCou == 0:
return
normalsList = m.GetNormalsAttr().Get()
normalsCou = len(normalsList)
if normalsCou == 0:
return
normalV = normalsList[0]
versList = m.GetPointsAttr().Get()
versCou = len(versList)
if versCou < 3:
return
faceVIList = m.GetFaceVertexIndicesAttr().Get()
faceVICou = len(faceVIList)
# Stores the face number for each vertex.
vFList = [[]] * (versCou)
for i in range(versCou):
vFList[i] = []
index = 0
for i in range(len(faceVCouList)):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI = faceVIList[index + j]
vFList[vI].append(i)
index += faceVCou
faceIndicesList = [[]] * faceCou
for i in range(faceCou):
faceIndicesList[i] = []
# Rearrange the vertex indices per face.
index = 0
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
faceIndicesList[i].append(faceVIList[index + j])
index += faceVCou
# Create a list of independent edges.
edgesList = []
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI1 = faceIndicesList[i][j]
vI2 = faceIndicesList[i][(j + 1) % faceVCou]
chkF = False
cI = -1
for k in range(len(edgesList)):
if (edgesList[k][0] == vI1 and edgesList[k][1] == vI2) or (edgesList[k][0] == vI2 and edgesList[k][1] == vI1):
chkF = True
cI = k
break
if chkF == False:
edgesList.append([vI1, vI2, 1])
else:
cou = edgesList[cI][2]
edgesList[cI] = [vI1, vI2, cou + 1]
edgesOneList = []
for p in edgesList:
if p[2] == 1:
edgesOneList.append([p[0], p[1]])
# Create a symmetrical face.
faceVCouList2 = [0] * (faceCou * 2)
normalsList2 = [(0.0, 0.0, 0.0)] * (normalsCou * 2)
versList2 = [(0.0, 0.0, 0.0)] * (versCou * 2)
faceVIList2 = [0] * (faceVICou * 2)
for i in range(faceCou):
faceVCouList2[i] = faceVCouList[i]
faceVCouList2[i + faceCou] = faceVCouList[i]
for i in range(faceVICou):
faceVIList2[i] = faceVIList[i]
faceVIList2[i + faceVICou] = faceVIList[faceVICou - i - 1] + versCou
for i in range(normalsCou):
normalsList2[i] = normalsList[i]
normalsList2[i + normalsCou] = -normalsList[i]
for i in range(versCou):
versList2[i] = versList[i]
n = normalsList[i]
versList2[i + versCou] = versList[i] - (n * thickness)
# Create side faces.
vIndex = len(versList2)
for edgeI in edgesOneList:
e1 = edgeI[0]
e2 = edgeI[1]
i1 = e1
i2 = e2
i3 = e1 + versCou
i4 = e2 + versCou
v1 = versList2[i2]
v2 = versList2[i1]
v3 = versList2[i3]
v4 = versList2[i4]
n = calcTriangleNormal(v1, v2, v3)
faceVCouList2.append(4)
for j in range(4):
normalsList2.append(n)
versList2.append(v1)
versList2.append(v2)
versList2.append(v3)
versList2.append(v4)
for j in range(4):
faceVIList2.append(vIndex + j)
vIndex += 4
m.CreatePointsAttr(versList2)
m.CreateNormalsAttr(normalsList2)
m.CreateFaceVertexCountsAttr(faceVCouList2)
m.CreateFaceVertexIndicesAttr(faceVIList2)
# -------------------------------------------------------.
# Create gear.
# @param[in] name Prim name.
# @param[in] gearR Radius of gear.
# @param[in] filletCount Number of gear divisions.
# @param[in] filletHeight Fillet height.
# @param[in] gearWidth Gear width.
# -------------------------------------------------------.
def CreateGear (name : str, gearR : float, filletCount : int, filletHeight : float, gearWidth : float):
angle = 360.0 / filletCount # Angle of one tooth.
# Calculate the length of one tooth on the circumference.
D = (gearR * math.sin((angle / 2.0) * math.pi / 180.0)) * 2
dHalf = D * 0.5
dQuarter = D * 0.25
centerV = Gf.Vec3d(0, 0, 0)
versList = []
versList.append(centerV)
faceIndexList = []
maxVCou = 1 + (5 * filletCount)
index = 1
aV = 0.0
for i in range(filletCount):
# Vertices of a single tooth.
vDirX = math.cos(aV * math.pi / 180.0)
vDirY = math.sin(aV * math.pi / 180.0)
v2X = -vDirY
v2Y = vDirX
vD = Gf.Vec3d(vDirX, vDirY, 0)
vCrossD = Gf.Vec3d(v2X, v2Y, 0)
vCenter = vD * gearR
v1 = vCenter - (vCrossD * dHalf)
v2 = v1 + (vCrossD * dQuarter)
v3 = v2 + (vD * filletHeight)
v4 = v3 + (vCrossD * dHalf)
v5 = v4 - (vD * filletHeight)
v6 = v5 + (vCrossD * dQuarter)
dd = D * 0.1
vCD = vCrossD * dd
v3 += vCD
v4 -= vCD
v2 -= vCD
v5 += vCD
versList.append(v1)
versList.append(v2)
versList.append(v3)
versList.append(v4)
versList.append(v5)
faceIndexList.append(0)
faceIndexList.append(index)
faceIndexList.append(index + 1)
faceIndexList.append(index + 2)
faceIndexList.append(index + 3)
faceIndexList.append(index + 4)
if index + 5 >= maxVCou:
faceIndexList.append(1)
else:
faceIndexList.append(index + 5)
index += 5
aV += angle
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# Create mesh.
pathName = rootPath + '/gears'
prim = stage.GetPrimAtPath(pathName)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, pathName)
pathMeshName0 = pathName + '/' + name
pathMeshName = pathMeshName0
index = 0
while True:
pathMeshName = pathMeshName0
if index > 0:
pathMeshName += '_' + str(index)
prim = stage.GetPrimAtPath(pathMeshName)
if prim.IsValid() == False:
break
index += 1
meshGeom = UsdGeom.Mesh.Define(stage, pathMeshName)
# Set vertices.
stVersList = []
stNormalList = []
for i in range(len(versList)):
stVersList.append((versList[i][0], versList[i][1], versList[i][2]))
stNormalList.append((0, 0, 1))
meshGeom.CreatePointsAttr(stVersList)
# Set normals.
meshGeom.CreateNormalsAttr(stNormalList)
# Set face vertex count.
faceVCouList = []
for i in range(filletCount):
faceVCouList.append(7)
meshGeom.CreateFaceVertexCountsAttr(faceVCouList)
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr(faceIndexList)
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# Attach thickness.
if gearWidth > 0.0:
AttachThickness(pathMeshName, gearWidth)
# --------------------------------------------------------.
# Main UI.
# --------------------------------------------------------.
# Clicked button event.
def onButtonClick (hNameStringField, hRadiusFloatField, hFilletCouIntField, hFilletHeightFloatField, hGearWidthFloatField):
name = hNameStringField.model.get_value_as_string()
if name == '':
name = 'gear'
radius = hRadiusFloatField.model.get_value_as_float()
if radius < 0.00001:
radius = 0.00001
filletCou = hFilletCouIntField.model.get_value_as_int()
if filletCou < 4:
filletCou = 4
filletHeight = hFilletHeightFloatField.model.get_value_as_float()
if filletHeight < 0.00001:
filletHeight = 0.00001
gearWidth = hGearWidthFloatField.model.get_value_as_float()
if gearWidth < 0.00001:
gearWidth = 0.00001
# Create Cear.
CreateGear(name, radius, filletCou, filletHeight, gearWidth)
# ------------------------------------------.
my_window = omni.ui.Window("Create Gear", width=350, height=250)
with my_window.frame:
with omni.ui.VStack(height=0):
labelWidth = 120
with omni.ui.Placer(offset_x=8, offset_y=8):
# Set label.
f = omni.ui.Label("Create Gear.")
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Name : ", width=labelWidth)
hNameStringField = omni.ui.StringField(width=200, height=0)
hNameStringField.model.set_value("gear")
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Radius : ", width=labelWidth)
hRadiusFloatField = omni.ui.FloatField(width=200, height=0)
hRadiusFloatField.model.set_value(10.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Number of fillet : ", width=labelWidth)
hFilletCouIntField = omni.ui.IntField(width=200, height=0)
hFilletCouIntField.model.set_value(32)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Fillet height : ", width=labelWidth)
hFilletHeightFloatField = omni.ui.FloatField(width=200, height=0)
hFilletHeightFloatField.model.set_value(1.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Gear width : ", width=labelWidth)
hGearWidthFloatField = omni.ui.FloatField(width=200, height=0)
hGearWidthFloatField.model.set_value(2.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
# Set button.
btn = omni.ui.Button("Create", width=200, height=0)
btn.set_clicked_fn(lambda name = hNameStringField, f = hRadiusFloatField, f2 = hFilletCouIntField, f3 = hFilletHeightFloatField, f4 = hGearWidthFloatField: onButtonClick(name, f, f2, f3, f4))
| 11,599 | Python | 30.607629 | 203 | 0.559359 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/readme.md | # CreateMesh
Meshを生成/Mesh情報を取得します。
|ファイル|説明|
|---|---|
|[CreateSimpleMesh.py](./CreateSimpleMesh.py)|簡単な1枚板のMeshを作成<br>|
|[CreateMeshInterpolation.py](./CreateMeshInterpolation.py)|2つの四角形で構成されるMeshを作成。<br>「頂点ごと(vertex)」「面の頂点ごと(faceVarying)」の法線/UVの指定。|
|[CreateSimpleMeshWithSubset.py](./CreateSimpleMeshWithSubset.py)|2つの面を持つMeshにて、面のマテリアルを別々に指定。|
|[CreateGear.py](./CreateGear.py)|歯車のMeshを作成<br>|
|[GetMeshInfo.py](./GetMeshInfo.py)|選択形状がMeshの場合のMesh情報を取得|
| 584 | Markdown | 43.999997 | 135 | 0.724315 |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateMeshInterpolation.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# ------------------------------------------------.
# Create mesh.
# @param[in] path Prim path.
# @param[in] interpolation "vertex" or "faceVarying".
# ------------------------------------------------.
def createTestMesh (path : str, interpolation : str = "vertex", pos : Gf.Vec3f = Gf.Vec3f(0, 0, 0)):
if interpolation != "vertex" and interpolation != "faceVarying":
return
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, path)
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (0, 0, -10), (10, 0, -10), (-10, 0, 0), (0, 0, 0), (10, 0, 0)])
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4, 4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 3, 4, 1, 1, 4, 5, 2])
if interpolation == "vertex":
# Set normals and UVs for each vertex.
# Set normals.
meshGeom.CreateNormalsAttr([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.SetNormalsInterpolation("vertex")
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
attr = primvarV.GetAttr()
attr.Set([(0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (0.0, 0.0), (1.0, 0.0), (2.0, 0.0)])
else:
# Set normals and UVs for each face vertex.
# Set normals.
normalList = []
for i in range(2):
normalList.extend([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.CreateNormalsAttr(normalList)
meshGeom.SetNormalsInterpolation("faceVarying")
# Set uvs.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
attr = primvarV.GetAttr()
uvsList = []
uvsList.extend([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0), (1.0, 1.0)])
uvsList.extend([(1.0, 1.0), (1.0, 0.0), (2.0, 0.0), (2.0, 1.0)])
attr.Set(uvsList)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((pos[0], pos[1], pos[2]))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# -----------------------------------------------.
createTestMesh(rootPath + "/mesh_vertex", "vertex", Gf.Vec3f(0, 0, 0))
createTestMesh(rootPath + "/mesh_faceVarying", "faceVarying", Gf.Vec3f(0, 0, 20))
| 3,039 | Python | 35.626506 | 138 | 0.579467 |
ft-lab/omniverse_sample_scripts/Geometry/CreateCube/CreateCube.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create cube.
pathName = '/World/cube'
cubeGeom = UsdGeom.Cube.Define(stage, pathName)
# Set cube size.
cubeGeom.CreateSizeAttr(10.0)
# Set color.
cubeGeom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0.0, 5.0, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cubeGeom).SetScale((2.0, 1.0, 2.0))
| 476 | Python | 21.714285 | 63 | 0.714286 |
ft-lab/omniverse_sample_scripts/Geometry/CreateCube/readme.md | # CreateCube
|ファイル|説明|
|---|---|
|[CreateCube.py](./CreateCube.py)|直方体を作成<br>|
| 133 | Markdown | 18.142855 | 87 | 0.601504 |
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/GetSphereInfo.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
xformCache = UsdGeom.XformCache(0)
# ---------------------------------------.
# Dump sphere data.
# ---------------------------------------.
def DumpSphereData (prim):
typeName = prim.GetTypeName()
if typeName == 'Sphere':
sphereGeom = UsdGeom.Sphere(prim)
# Get prim name.
name = prim.GetName()
# Get prim path.
path = prim.GetPath().pathString
# Get show/hide.
showF = (sphereGeom.ComputeVisibility() == 'inherited')
# Decompose transform.
globalPose = xformCache.GetLocalToWorldTransform(prim)
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# Get radius.
r = sphereGeom.GetRadiusAttr().Get()
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print(f"[ {name} ] {path}")
print(f"Show : {showF}")
print(f"Radius : {r * scale[0]} , {r * scale[1]} , {r * scale[2]}")
if len(pathList) > 0:
print("Material : ")
for mPath in pathList:
print(f" {mPath.pathString}")
print("")
# ---------------------------------------.
# Traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy (prim):
DumpSphereData(prim)
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
TraverseHierarchy(cPrim)
# ----------------------------------------------------.
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
TraverseHierarchy(prim)
| 1,885 | Python | 26.735294 | 75 | 0.542175 |
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/CReateSphereWithRefinement.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(5.0)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((0.0, 5.0, 0.0))
# Set refinement.
objPrim = stage.GetPrimAtPath(pathName)
objPrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
objPrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
| 635 | Python | 26.652173 | 86 | 0.76063 |
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/readme.md | # CreateSphere
球を作成します。
|ファイル|説明|
|---|---|
|[CreateSphere.py](./CreateSphere.py)|簡単な球を作成<br>|
|[CreateSphereWithRefinement.py](./CReateSphereWithRefinement.py)|作成する球の分割数を増やす。<br>属性"Refinement"を指定。<br>|
|[GetSphereInfo.py](./GetSphereInfo.py)|球の情報を取得|
| 395 | Markdown | 31.999997 | 168 | 0.691139 |
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/CreateSphere.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(5.0)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((0.0, 5.0, 0.0))
| 415 | Python | 22.11111 | 64 | 0.727711 |
ft-lab/omniverse_sample_scripts/Extensions/readme.md | # Extension
簡単なサンプルのExtensionです。
Extensionはモジュール的にOmniverse(Kit)を使ったアプリを拡張します。
ExtensionはベースはPythonとして記載し、別途C言語(動的ライブラリとして関数呼び出し)で外部機能を実装することができます。
## Extensionの詳しいドキュメント
Extensionは構成のルールがあります。
Omniverse Createの[Help]-[Developers Manual]からOmniverse Kitのドキュメントの「Extensions」で詳しく解説されています。
## Extension作成に関する情報
* [extension.tomlでの記述内容](./knowledge/config_info.md)
## サンプル
|Extension|説明|
|---|---|
|[ft_lab.sample.hello](./ft_lab.sample.hello)|開始(startup)/破棄(shutdown)のみの簡単なExtension|
|[ft_lab.sample.callDLL](./ft_lab.sample.callDLL)|C言語のDLLより関数を読み込む|
|[ft_lab.sample.menu](./ft_lab.sample.menu)|メニューを追加。<br>|
|[ft_lab.sample.loadStage](./ft_lab.sample.loadStage)|Extension内に配置したusdファイルを新規Stageとして読み込む|
|[ft_lab.sample.widgets](./ft_lab.sample.widgets)|omni.uiの使用例。<br>ウィンドウを表示し、ウィジットを配置。<br>|
|[ft_lab.sample.widgets_progressBar](./ft_lab.sample.widgets_progressBar)|omni.ui.ProgressBarの使用例。<br>ボタンを押すとプログレスバーの開始/停止。<br>|
|[ft_lab.sample.uiScene](./ft_lab.sample.uiScene)|omni.ui.sceneの使用例。<br>ウィンドウを表示し、SceneViewに描画を行う。<br>|
|[ft_lab.sample.uiSceneDraw](./ft_lab.sample.uiSceneDraw)|omni.ui.sceneの使用例。<br>ウィンドウを表示し、SceneViewに順番を考慮した描画を行う。<br>また、描画を更新し、SceneViewでアニメーションする。<br>|
|[ft_lab.sample.uiSceneViewportOverlay](./ft_lab.sample.uiSceneViewportOverlay)|Kit.104以上で動作。<br>omni.ui.sceneの使用例。<br>ViewportにSceneViewをオーバレイ表示する。<br>カメラと同じ変換行列を使用し、3Dのワールド座標指定でワイヤーフレーム描画します。<br>「[Viewport](../UI/Viewport/readme.md)」もご参照くださいませ。|
|[ft_lab.sample.uiSceneShowPrimName](./ft_lab.sample.uiSceneShowPrimName)|Kit.104以上で動作。<br>omni.ui.sceneの使用例。<br>ViewportにSceneViewをオーバレイ表示する。<br>選択Prim名を形状のローカル座標の中心に表示。<br>NDC座標でラベルの描画を行います。<br>「[Viewport](../UI/Viewport/readme.md)」もご参照くださいませ。|
| 2,371 | Markdown | 75.516127 | 368 | 0.77267 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/readme.md | # ft_lab.sample.hello
"ft_lab.sample.hello" はExtensionの簡単なサンプルです。
"omni.example.hello"を参考にしました。
## Extensionの構成
"ft_lab.sample.hello" Extensionの構成です。
```
[ft_lab.sample.hello]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[hello]
__init__.py
hello.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.hello
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Python Extension Example"
description="xxxxxx."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.hello"
```
## ft_lab.sample.hello
"ft_lab.sample.hello"内は、"ft_lab/sample/hello"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[hello]
__init__.py
hello.py
```
### __init__.py
開始するメインファイル (hello.py)のインポートを指定します.
```
from .hello import *
```
### hello.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
```python
import omni.ext
class HelloExtension(omni.ext.IExt):
# Call startup.
def on_startup(self, ext_id):
print("[ft_lab.sample.hello] HelloExtension startup")
# Call shutdown.
def on_shutdown(self):
print("[ft_lab.sample.hello] HelloExtension shutdown")
```
このときのクラス名"HelloExtension"はどのような名前でも認識されるようでした。
"on_startup"でExtensionを開始したときの処理を記載します。
"on_shutdown"でExtensionを終了したときの処理を記載します。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
このとき、開発者が作成したExtensionを"pkg/create-2021.3.8/exts"に入れます。
なお、"pkg/create-2021.3.8/kit/exts"はOmniverse KitとしてのExtension、
"pkg/create-2021.3.8/kit/extscore"はコアExtensionとなり、
これらはOmniverseの内部的に使用されるExtensionのため、ここには独自Extensionは入れないほうがよさそうです。
作成した"ft_lab.sample.hello"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Python Extension Example"が存在するのを確認できました。

| 3,239 | Markdown | 18.756097 | 74 | 0.659463 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Python Extension Example"
description="Very simple extension."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.hello"
| 1,389 | TOML | 32.095237 | 118 | 0.75018 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/ft_lab/sample/hello/hello.py | import omni.ext
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class HelloExtension(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("[ft_lab.sample.hello] HelloExtension startup")
def on_shutdown(self):
print("[ft_lab.sample.hello] HelloExtension shutdown")
| 674 | Python | 43.999997 | 119 | 0.734421 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/ft_lab/sample/hello/__init__.py | from .hello import *
| 21 | Python | 9.999995 | 20 | 0.714286 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.hello`` extension.
| 95 | Markdown | 14.999998 | 79 | 0.757895 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/README.md | # Python Extension Example [ft_lab.sample.hello]
sample extension.
| 73 | Markdown | 13.799997 | 48 | 0.726027 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/index.rst | ft_lab.sample.hello
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 104 | reStructuredText | 8.545454 | 27 | 0.451923 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/readme.md | # ft_lab.sample.loadStage
"ft_lab.sample.loadStage" は、あらかじめ用意したusdファイルを開くだけのExtensionです。
## Extensionの構成
"ft_lab.sample.loadStage" Extensionの構成です。
```
[ft_lab.sample.loadStage]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[loadStage]
__init__.py
main.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.loadStage
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Python Extension Example"
description="xxxxxx."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.loadStage"
```
## ft_lab.sample.loadStage
"ft_lab.sample.loadStage"内は、"ft_lab/sample/loadStage"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[loadStage]
__init__.py
main.py
```
### __init__.py
開始するメインファイル (hello.py)のインポートを指定します.
```
from .main import *
```
### main.py
```python
from pathlib import Path
# Get USD file.
usdPath = Path(__file__).parent.joinpath("usd")
usdFile = f"{usdPath}/test.usd"
# Load stage.
omni.usd.get_context().open_stage(usdFile)
```
「Path(__file__)」で、main.py自身の絶対パスを返します。
「parent」でその親のフォルダ、「joinpath("usd")」でusdフォルダ。
この場合は、usdPathは「ft_lab/sample/loadStage/usd」のパスになります。
usdFileは「ft_lab/sample/loadStage/usd/test.usd」となります。
Extension内にusdファイルを入れている構成です。
「omni.usd.get_context().open_stage(usdFile)」で指定のパスのファイルをステージとして読み込みます。
| 2,610 | Markdown | 16.406667 | 75 | 0.635249 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Load Stage"
description="Sample of opening usd."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.loadStage"
| 1,379 | TOML | 31.857142 | 118 | 0.748368 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/ft_lab/sample/loadStage/main.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
import omni.ext
from pathlib import Path
class LoadStageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.loadStage] LoadStageExtension startup")
# Get USD file.
usdPath = Path(__file__).parent.joinpath("usd")
usdFile = f"{usdPath}/test.usd"
# Load stage.
omni.usd.get_context().open_stage(usdFile)
def on_shutdown(self):
print("[ft_lab.sample.loadStage] LoadStageExtension shutdown")
| 533 | Python | 28.666665 | 70 | 0.658537 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/ft_lab/sample/loadStage/__init__.py | from .main import *
| 20 | Python | 9.499995 | 19 | 0.7 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.loadStage`` extension.
| 99 | Markdown | 15.666664 | 83 | 0.767677 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/README.md | # Python Extension Example [ft_lab.sample.loadStage]
sample extension.
| 77 | Markdown | 14.599997 | 52 | 0.74026 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/index.rst | ft_lab.sample.loadStage
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 108 | reStructuredText | 8.90909 | 27 | 0.472222 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene draw example"
description="omni.ui scene draw example"
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.uiSceneDraw"
| 1,396 | TOML | 32.261904 | 118 | 0.75 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/ft_lab/sample/uiSceneDraw/main.py | import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
from pathlib import Path
import math
# -------------------------------------.
# Scene draw process.
# -------------------------------------.
class SceneDraw(sc.Manipulator):
_angle1 = 0.0
_angle2 = 0.0
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._angle1 = 0.0
self._angle2 = 45.0
def on_build(self):
# Consider the order. This uses the z-value Depth.
# -1.0 < depth <= 0.0
depth = 0.0
moveT = sc.Matrix44.get_translation_matrix(0.0, 0.0, depth)
with sc.Transform(transform=moveT):
sc.Rectangle(2.0, 2.0, wireframe=False, color=cl("#003000"))
depth = -0.1
rotT = sc.Matrix44.get_rotation_matrix(0, 0, self._angle1, True)
moveT = sc.Matrix44.get_translation_matrix(0.25, 0.3, depth)
viewT = moveT * rotT
with sc.Transform(transform=viewT):
sc.Rectangle(1.5, 0.15, wireframe=False, color=cl("#3030ff"))
depth = -0.15
rotT = sc.Matrix44.get_rotation_matrix(0, 0, self._angle2, True)
moveT = sc.Matrix44.get_translation_matrix(-0.25, -0.1, depth)
viewT = moveT * rotT
with sc.Transform(transform=viewT):
sc.Rectangle(1.5, 0.15, wireframe=False, color=cl("#ff3030"))
self._angle1 = math.fmod(self._angle1 + 0.2, 360.0)
self._angle2 = math.fmod(self._angle2 + 0.1, 360.0)
self.invalidate()
# ----------------------------------------------------------.
class UISceneDrawExtension(omni.ext.IExt):
_window = None
_scene_view = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
imagesPath = Path(__file__).parent.joinpath("images")
# Create new window.
self._window = omni.ui.Window("UI Scene Draw Window", width=400, height=400)
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
omni.ui.Spacer(height=4)
omni.ui.Label("Use omni.ui.scene for custom drawing.")
omni.ui.Spacer(height=4)
self._scene_view = sc.SceneView(
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=300
)
with self._scene_view.scene:
SceneDraw()
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
| 3,193 | Python | 31.927835 | 84 | 0.451926 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/ft_lab/sample/uiSceneDraw/__init__.py | from .main import *
| 20 | Python | 9.499995 | 19 | 0.7 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.uiSceneDraw`` extension.
| 101 | Markdown | 15.999997 | 85 | 0.772277 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/README.md | # Python Extension Example [ft_lab.sample.uiSceneDraw]
sample extension.
| 79 | Markdown | 14.999997 | 54 | 0.746835 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/index.rst | ft_lab.sample.uiSceneDraw
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 110 | reStructuredText | 9.090908 | 27 | 0.481818 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/readme.md | # ft_lab.sample.menu
"ft_lab.sample.menu" はメニューを追加する簡単なサンプルExtensionです。
## Extensionの構成
"ft_lab.sample.menu" Extensionの構成です。
```
[ft_lab.sample.menu]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[menu]
__init__.py
main.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.menu
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
version = "0.0.1"
authors = ["ft-lab"]
title = "Menu Test"
description="Sample of adding a Menu."
readme = "docs/README.md"
repository = ""
category = "Example"
keywords = ["kit", "example"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
[[python.module]]
name = "ft_lab.sample.menu"
```
## ft_lab.sample.menu
"ft_lab.sample.menu"内は、"ft_lab/sample/menu"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[menu]
__init__.py
main.py
```
### __init__.py
開始するメインファイル (main.py)のインポートを指定します.
```
from .main import *
```
### main.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
```python
class MenuExtension(omni.ext.IExt):
# Menu list.
_menu_list = None
_sub_menu_list = None
# Menu name.
_menu_name = "MenuTest"
def on_startup(self, ext_id):
print("[ft_lab.sample.menu] MenuExtension startup")
# Initialize menu.
self.init_menu()
def on_shutdown(self):
print("[ft_lab.sample.menu] MenuExtension shutdown")
# Term menu.
self.term_menu()
```
"on_startup"でExtensionを開始したときの処理を記載します。
ここの「self.init_menu()」にてメニューを作成しています。
"on_shutdown"でExtensionを終了したときの処理を記載します。
ここの「self.term_menu()」にてメニューの破棄処理を行っています。
メニューの初期化処理は以下のように記載。
```python
def init_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
def menu_select (mode):
if mode == 0:
print("Select MenuItem 1.")
if mode == 1:
print("Select MenuItem 2.")
if mode == 2:
print("Select MenuItem 3.")
if mode == 10:
print("Select Sub MenuItem 1.")
if mode == 11:
print("Select Sub MenuItem 2.")
self._sub_menu_list = [
MenuItemDescription(name="Sub MenuItem 1", onclick_fn=lambda: menu_select(10)),
MenuItemDescription(name="Sub MenuItem 2", onclick_fn=lambda: menu_select(11)),
]
self._menu_list = [
MenuItemDescription(name="MenuItem 1", onclick_fn=lambda: menu_select(0)),
MenuItemDescription(name="MenuItem 2", onclick_fn=lambda: menu_select(1)),
MenuItemDescription(name="MenuItem 3", onclick_fn=lambda: menu_select(2)),
MenuItemDescription(),
MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list),
]
# Rebuild with additional menu items.
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
self._sub_menu_listにメニュー項目を格納しています。
「MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list)」でサブメニューを追加しています。
```python
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
で、メニュー項目を追加し、遅延でメニューを更新しています。
メニュー項目が選択されたときに、選択されているメニュー項目名をprintしています。
メニューの破棄処理は以下のように記載。
```python
def term_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
# Remove and rebuild the added menu items.
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
「omni.kit.menu.utils.remove_menu_items」で追加したメニュー項目を削除。
「asyncio.ensure_future(_rebuild_menus())」で遅延でメニューを更新しています。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
作成した"ft_lab.sample.menu"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Python Extension Example"が存在するのを確認できました。

これをOnにすると、"MenuTest"というメニュー項目が表示されます。

Offにした場合"MenuTest"内は空になりますが、トップメニューの"MenuTest"は残ってしまうようです (Omniverse Create 2021.3.8で確認)。
Omniverse Code 2022.1.0ではこの問題は起きなかったため、この現象は将来Kit側で修正されるものと思われます。
| 5,323 | Markdown | 23.090498 | 94 | 0.619012 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Menu Test"
description="Sample of adding a Menu."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.menu"
| 1,375 | TOML | 31.761904 | 118 | 0.746909 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/ft_lab/sample/menu/main.py | import omni.ext
import asyncio
import omni.kit.menu.utils
import omni.kit.undo
import omni.kit.commands
import omni.usd
from omni.kit.menu.utils import MenuItemDescription
class MenuExtension(omni.ext.IExt):
# Menu list.
_menu_list = None
_sub_menu_list = None
# Menu name.
_menu_name = "MenuTest"
# ------------------------------------------.
# Initialize menu.
# ------------------------------------------.
def init_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
def menu_select (mode):
if mode == 0:
print("Select MenuItem 1.")
if mode == 1:
print("Select MenuItem 2.")
if mode == 2:
print("Select MenuItem 3.")
if mode == 10:
print("Select Sub MenuItem 1.")
if mode == 11:
print("Select Sub MenuItem 2.")
self._sub_menu_list = [
MenuItemDescription(name="Sub MenuItem 1", onclick_fn=lambda: menu_select(10)),
MenuItemDescription(name="Sub MenuItem 2", onclick_fn=lambda: menu_select(11)),
]
self._menu_list = [
MenuItemDescription(name="MenuItem 1", onclick_fn=lambda: menu_select(0)),
MenuItemDescription(name="MenuItem 2", onclick_fn=lambda: menu_select(1)),
MenuItemDescription(name="MenuItem 3", onclick_fn=lambda: menu_select(2)),
MenuItemDescription(),
MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list),
]
# Rebuild with additional menu items.
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
# ------------------------------------------.
# Term menu.
# It seems that the additional items in the top menu will not be removed.
# ------------------------------------------.
def term_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
# Remove and rebuild the added menu items.
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
# ------------------------------------------.
def on_startup(self, ext_id):
print("[ft_lab.sample.menu] MenuExtension startup")
# Initialize menu.
self.init_menu()
def on_shutdown(self):
print("[ft_lab.sample.menu] MenuExtension shutdown")
# Term menu.
self.term_menu()
| 2,704 | Python | 32.395061 | 91 | 0.54068 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/ft_lab/sample/menu/__init__.py | from .main import *
| 20 | Python | 9.499995 | 19 | 0.7 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.menu`` extension.
| 94 | Markdown | 14.833331 | 78 | 0.755319 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/README.md | # Python Extension Example [ft_lab.sample.menu]
menu sample extension.
| 77 | Markdown | 14.599997 | 47 | 0.727273 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/index.rst | ft_lab.sample.menu
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 103 | reStructuredText | 8.454545 | 27 | 0.446602 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/readme.md | # ft_lab.sample.callDLL
"ft_lab.sample.hello" はExtensionからC言語のDLLを呼び出す簡単なサンプルです。
## Extensionの構成
"ft_lab.sample.callDLL" Extensionの構成です。
```
[ft_lab.sample.callDLL]
[bin]
[win]
[x64]
OmniverseSimpleDLL.dll ... dll(Win 64bit).
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[callDLL]
__init__.py
callDLL.py
[build]
[OmniverseSimpleDLL] ... DLL source project for VS2017.
```
[build]フォルダは説明のために入れていますが、Extensionの構成としては不要な要素です。
削除しても問題ありません。
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.callDLL
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Calling function from dll"
description="This is sample of calling function from dll using Python's LoadLibrary."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.callDLL"
# Load native library.
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
```
[[native.library]]にDLLを参照するための相対パスを指定します(DLLファイル名も含む)。
上記の場合は、Extension実行時に自動的に"bin/win/x64/"がdllの検索パスとして参照されます。
## ft_lab.sample.callDLL
"ft_lab.sample.callDLL"内は、"ft_lab/sample/callDLL"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[callDLL]
__init__.py
callDLL.py
```
### __init__.py
開始するメインファイル (callDLL.py)のインポートを指定します.
```
from .callDLL import *
```
### callDLL.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
"dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")"の指定によりDLLが読み込まれます。
```python
import omni.ext
from ctypes import *
# Load library.
# Add the search path for [[native.library]] to "config/extension.toml".
dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")
# ----------------------------------------------------.
# Call external function.
# ----------------------------------------------------.
def callExtFunc():
if dll == None:
return
v = dll.ext_add(3, 8)
print("dll.ext_add(3, 8) : " + str(v))
v2 = dll.ext_sub(3, 8)
print("dll.ext_sub(3, 8) : " + str(v2))
# ----------------------------------------------------.
class CallDLLExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.callDLL] HelloExtension startup")
callExtFunc()
def on_shutdown(self):
print("[ft_lab.sample.callDLL] HelloExtension shutdown")
```
"ext_add"、"ext_sub"がDLLに定義されている外部関数になります。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
このとき、開発者が作成したExtensionを"pkg/create-2021.3.8/exts"に入れます。
作成した"ft_lab.sample.callDLL"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Calling function from dll"が存在するのを確認できました。

| 4,108 | Markdown | 19.545 | 85 | 0.624878 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/build/OmniverseSimpleDLL/OmniverseSimpleDLL/sources/dllmain.cpp |
#include <windows.h>
#include <stdio.h>
#define DLL_API extern "C" __declspec(dllexport)
// ----------------------------------------------------------------.
// DLLMain.
// ----------------------------------------------------------------.
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ----------------------------------------------------------------.
// External functions.
// ----------------------------------------------------------------.
DLL_API int ext_add (int a, int b) {
return a + b;
}
DLL_API int ext_sub (int a, int b) {
return a - b;
}
| 863 | C++ | 22.999999 | 68 | 0.385863 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Calling function from dll"
description="This is sample of calling function from dll using Python's LoadLibrary."
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.callDLL"
# Load native library.
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
| 1,527 | TOML | 32.955555 | 118 | 0.751801 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/ft_lab/sample/callDLL/__init__.py | from .callDLL import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/ft_lab/sample/callDLL/callDLL.py | import omni.ext
from ctypes import *
# Load library.
# Add the search path for [[native.library]] to "config/extension.toml".
dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")
# ----------------------------------------------------.
# Call external function.
# ----------------------------------------------------.
def callExtFunc():
if dll == None:
return
v = dll.ext_add(3, 8)
print("dll.ext_add(3, 8) : " + str(v))
v2 = dll.ext_sub(3, 8)
print("dll.ext_sub(3, 8) : " + str(v2))
# ----------------------------------------------------.
class CallDLLExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.callDLL] HelloExtension startup")
callExtFunc()
def on_shutdown(self):
print("[ft_lab.sample.callDLL] HelloExtension shutdown")
| 823 | Python | 25.580644 | 72 | 0.507898 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.callDLL`` extension.
| 97 | Markdown | 15.333331 | 81 | 0.762887 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/README.md | # Calling function from dll [ft_lab.sample.callDLL]
This is sample of calling function from dll using Python's LoadLibrary.
| 129 | Markdown | 24.999995 | 74 | 0.767442 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/index.rst | ft_lab.sample.callDLL
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 106 | reStructuredText | 8.727272 | 27 | 0.462264 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Widgets ProgressBar example"
description="omni.ui widgets ProgressBar example"
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.widgets_progressBar"
| 1,419 | TOML | 32.809523 | 118 | 0.754052 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/ft_lab/sample/widgets_progressBar/extension.py | import omni.ext
import omni.ui
from pathlib import Path
import os.path
import carb.tokens
import carb.events
import time
# ----------------------------------------------------------.
class WidgetsExtension(omni.ext.IExt):
_window = None
_btn = None # omni.ui.Button.
_progressBar = None # omni.ui.ProgressBar.
_progressValue = 0.2 # PrograssBar value.
_progressStart = True # True if Progress is to proceed.
_subs = None # Update Events.
_timeV = 0
# ------------------------------------.
# Update event.
# ------------------------------------.
def on_update (self, e: carb.events.IEvent):
# Processing every 0.2 seconds.
curTimeV = time.time()
if curTimeV - self._timeV > 0.2:
self._timeV = curTimeV
# Update progressBar.
if self._progressStart:
self._progressValue += 0.05
if self._progressValue > 1.0:
self._progressValue -= 1.0
self._progressBar.model.set_value(self._progressValue)
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
self._progressStart = True
self._timeV = time.time()
# Create new window.
self._window = omni.ui.Window("Widgets Window(ProgressBar)", width=300, height=100)
# Callback when button is clicked.
def onButtonClicked (self):
if self._progressStart:
self._progressStart = False
else:
self._progressStart = True
# Change button text.
if self._progressStart:
self._btn.text = "Stop"
else:
self._btn.text = "Start"
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
# ------------------------------------------.
# ProgressBar & Button.
# ------------------------------------------.
omni.ui.Spacer(height=4)
self._progressBar = omni.ui.ProgressBar(height=14, style={"color": 0xffdd0000})
self._progressBar.model.set_value(self._progressValue)
omni.ui.Spacer(height=4)
self._btn = omni.ui.Button(" Button ")
self._btn.set_clicked_fn(lambda s = self : onButtonClicked(s))
if self._progressStart:
self._btn.text = "Stop"
else:
self._btn.text = "Start"
omni.ui.Spacer(height=4)
# Register for update events.
# To clear the event, specify "subs=None".
self._subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self.on_update)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._subs != None:
self._subs = None
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
| 3,611 | Python | 32.757009 | 112 | 0.425921 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/ft_lab/sample/widgets_progressBar/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.widgets_progressBar`` extension.
| 109 | Markdown | 17.33333 | 93 | 0.779817 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/README.md | # Python Extension Example [ft_lab.sample.widgets_progressBar]
sample extension.
| 87 | Markdown | 16.599997 | 62 | 0.758621 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/index.rst | ft_lab.sample.widgets_progressBar
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 118 | reStructuredText | 9.818181 | 33 | 0.508475 |
ft-lab/omniverse_sample_scripts/Extensions/knowledge/config_info.md | # extension.tomlでの記述内容
"extension.toml"に記載する内容の覚書です。
## 他のExtensionを使用し、機能を呼び出したい
他のExtensionの機能を使用したい場合、[dependencies]にExtension名を追加します。
```
[dependencies]
"omni.audioplayer" = {}
```
この場合は「omni.audioplayer」を有効にします。
こうすることで、Pythonで「import omni.audioplayer」が使用できるようになります。
なお、参照で記載するExtension名は [[python.module]] に記載しているものと同じになります。
以下は「omni.audioplayer」内の"extension.toml"の記載です。
```
[[python.module]]
name = "omni.audioplayer"
```
ここで記載しているExtensionがOnになっていない場合は、対象のExtensionを起動した時に自動的にOnになります。
## 外部のC/C++モジュールを呼び出す
Windows環境の場合、dllの形で外部関数を作成します。
これをExtensionから呼び出すことができます。
```
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
```
DLL呼び出しのサンプルExtensionは「[ft_lab.sample.callDLL](../ft_lab.sample.callDLL)」をご参照くださいませ。
| 784 | Markdown | 21.428571 | 89 | 0.743622 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Widgets example"
description="omni.ui widgets example"
# 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 = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.widgets"
| 1,383 | TOML | 31.95238 | 118 | 0.749819 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/ft_lab/sample/widgets/extension.py | import omni.ext
import omni.ui
from pathlib import Path
import os.path
import carb.tokens
# ----------------------------------------------------------.
class WidgetsExtension(omni.ext.IExt):
_window = None
_sField = None
_label0 = None
_radioCollection = None
_label1 = None
_checkbox = None
_label2 = None
_combobox = None
_label3 = None
_slider = None
_label4 = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
imagesPath = Path(__file__).parent.joinpath("images")
# Create new window.
self._window = omni.ui.Window("Widgets Window", width=300, height=400)
# Radio Button Style.
style = {
"": {"background_color": 0x0, "image_url": f"{imagesPath}/radio_off.svg"},
":checked": {"image_url": f"{imagesPath}/radio_on.svg"},
}
def onButtonClicked (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.model.get_value_as_string()
uiLabel.text = "Input : " + v
def onRadioValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_int()
uiLabel.text = "Select Radio : " + str(v)
def onCheckBoxValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
b = uiFieldModel.get_value_as_bool()
uiLabel.text = "CheckBox : " + str(b)
def onComboBoxValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_int()
uiLabel.text = "ComboBox : " + str(v)
def onSliderValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_float()
uiLabel.text = "Slider : " + str(v)
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
# ------------------------------------------.
# StringField & Button.
# ------------------------------------------.
omni.ui.Spacer(height=4)
self._sField = omni.ui.StringField(width=120, height=14, style={"color": 0xffffffff})
self._sField.model.set_value("xxx")
omni.ui.Spacer(height=4)
omni.ui.Spacer(height=4)
btn = omni.ui.Button(" Button ")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label0 = omni.ui.Label("")
btn.set_clicked_fn(lambda s = self._sField, l = self._label0: onButtonClicked(s, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Radio Button.
# ------------------------------------------.
# Radio button.
self._radioCollection = omni.ui.RadioCollection()
radioLBtnList = []
with omni.ui.HStack(width=0):
for i in range(3):
with omni.ui.HStack(style=style):
radio = omni.ui.RadioButton(radio_collection=self._radioCollection, width=30, height=30)
omni.ui.Label(f"Radio {i} ", name="text")
radioLBtnList.append(radio)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label1 = omni.ui.Label("")
# Update label.
onRadioValueChanged(self._radioCollection.model, self._label1)
for radio in radioLBtnList:
radio.set_clicked_fn(lambda f = self._radioCollection.model, l = self._label1: onRadioValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# CheckBox.
# ------------------------------------------.
# CheckBox
omni.ui.Spacer(height=4)
with omni.ui.HStack(width=0):
self._checkbox = omni.ui.CheckBox()
omni.ui.Label(" CheckBox")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label2 = omni.ui.Label("")
# Update label.
onCheckBoxValueChanged(self._checkbox.model, self._label2)
self._checkbox.model.add_value_changed_fn(lambda f = self._checkbox.model, l = self._label2: onCheckBoxValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# ComboBox.
# ------------------------------------------.
# ComboBox
omni.ui.Spacer(height=4)
self._combobox = omni.ui.ComboBox(1, "Item1", "Item2", "Item3")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label3 = omni.ui.Label("")
# Update label.
onComboBoxValueChanged(self._combobox.model.get_item_value_model(), self._label3)
cModel = self._combobox.model.get_item_value_model()
cModel.add_value_changed_fn(lambda f = cModel, l = self._label3: onComboBoxValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Slider.
# ------------------------------------------.
# Slider.
omni.ui.Spacer(height=4)
self._slider = omni.ui.FloatSlider(min=0.0, max=10.0)
self._slider.model.set_value(1.2)
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label4 = omni.ui.Label("")
onSliderValueChanged(self._slider.model, self._label4)
self._slider.model.add_value_changed_fn(lambda f = self._slider.model, l = self._label4: onSliderValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Image.
# ------------------------------------------.
# Kit file path.
kitAbsPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}"))
# Load image (RGBA).
imagePath = Path(kitAbsPath).joinpath("resources").joinpath("desktop-icons")
imagePath = f"{imagePath}/omniverse_64.png"
omni.ui.Image(imagePath, width=64, height=64)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
| 8,726 | Python | 36.294872 | 138 | 0.43273 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/ft_lab/sample/widgets/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.widgets`` extension.
| 97 | Markdown | 15.333331 | 81 | 0.762887 |
Subsets and Splits