file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
ft-lab/omniverse_sample_scripts/Settings/GetRenderingSize.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import carb.settings
# Get rendering size.
# If Render Resolution is "Viewport", -1 will be set.
settings = carb.settings.get_settings()
width = settings.get('/app/renderer/resolution/width')
height = settings.get('/app/renderer/resolution/height')
print("Rendering size : " + str(width) + " x " + str(height))
# Set rendering size.
#settings.set('/app/renderer/resolution/width', 1280)
#settings.set('/app/renderer/resolution/height', 720)
| 509 | Python | 32.999998 | 63 | 0.72888 |
ft-lab/omniverse_sample_scripts/Settings/GetKitPath.py | import os.path
import carb.tokens
kitPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}"))
print(kitPath)
| 130 | Python | 20.83333 | 79 | 0.753846 |
ft-lab/omniverse_sample_scripts/Settings/readme.md | # Settings
carb.settingsより、設定を取得します。
これは"/kit/config/kit-core.json"の情報を読み取ります。
|ファイル|説明|
|---|---|
|[GetKitVersion.py](./GetKitVersion.py)|Omniverse Kitのバージョンを取得|
|[GetKitPath.py](./GetKitPath.py)|Omniverse Kitの絶対パスを取得|
|[GetRenderingSize.py](./GetRenderingSize.py)|レンダリングサイズを取得|
|[GetRenderMode.py](./GetRenderMode.py)|Render Mode(RTX Real-time/RTX Path-traced)を取得、設定<br>Render Modeは、コルーチン内で「await omni.kit.app.get_app().next_update_async()」で1フレーム待ってから変更したほうが安全。|
| 509 | Markdown | 35.428569 | 189 | 0.701375 |
ft-lab/omniverse_sample_scripts/Settings/GetKitVersion.py | import omni.kit
# Get Omniverse Kit version.
kitVersion = omni.kit.app.get_app_interface().get_build_version()
# 102.1.2+release.xxxx
print("Kit Version : " + str(kitVersion))
# 102.1.2
print(str(" ") + kitVersion.split("+")[0])
| 235 | Python | 18.666665 | 65 | 0.67234 |
ft-lab/omniverse_sample_scripts/Settings/GetRenderMode.py | import omni.kit
import carb.settings
import asyncio
# Get Render Mode.
settings = carb.settings.get_settings()
renderMode = settings.get('/rtx/rendermode')
# rtx, iray
activeRender = settings.get('/renderer/active')
if activeRender == 'iray':
print("Render Mode : Iray")
else:
if renderMode == 'RaytracedLighting':
print("Render Mode : RTX Real-time")
else:
if renderMode == 'PathTracing':
print("Render Mode : RTX Path-traced")
else:
print("Render Mode : " + renderMode)
# Set Render mode.
# It is safe to wait for one frame in the coroutine to change the RenderMode.
async def SetRenderMode (modeName : str):
await omni.kit.app.get_app().next_update_async()
settings.set('/rtx/rendermode', modeName)
# Set "RTX Real-time"
asyncio.ensure_future(SetRenderMode('RaytracedLighting'))
# Set "RTX Path-traced"
asyncio.ensure_future(SetRenderMode('PathTracing'))
| 933 | Python | 25.685714 | 77 | 0.687031 |
ft-lab/omniverse_sample_scripts/Scene/OpenUSDFile.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
try:
# Open USD File.
ret = omni.usd.get_context().open_stage("xxx.usd")
print("open_stage : " + str(ret))
except Exception as e:
print(e)
| 209 | Python | 19.999998 | 54 | 0.626794 |
ft-lab/omniverse_sample_scripts/Scene/CloseStage.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
omni.usd.get_context().close_stage()
| 90 | Python | 21.749995 | 51 | 0.722222 |
ft-lab/omniverse_sample_scripts/Scene/StageUpAxis.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get UpAxis.
upAxis = UsdGeom.GetStageUpAxis(stage)
if upAxis == UsdGeom.Tokens.x:
print("UpAxis : X")
elif upAxis == UsdGeom.Tokens.y:
print("UpAxis : Y")
elif upAxis == UsdGeom.Tokens.z:
print("UpAxis : Z")
# Set UpAxis (Y-Up).
try:
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
except Exception as e:
print(e)
| 461 | Python | 19.999999 | 63 | 0.67679 |
ft-lab/omniverse_sample_scripts/Scene/GetResolvedPath.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
try:
# Open USD File.
usdPath = "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan.usdc"
ret = omni.usd.get_context().open_stage(usdPath)
if ret == True:
# Get stage.
stage = omni.usd.get_context().get_stage()
# Convert relative paths to absolute paths from Stage.
# It is necessary to specify the relative path where the texture name, Reference, etc. exists on the Stage.
absPath = stage.ResolveIdentifierToEditTarget("./cyawan_mat_albedo.png")
# "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan_mat_albedo.png"
print(absPath)
except Exception as e:
print(e)
| 721 | Python | 33.380951 | 115 | 0.667129 |
ft-lab/omniverse_sample_scripts/Scene/readme.md | # Scene
シーン(Stage)の情報を取得/操作します。
|ファイル|説明|
|---|---|
|[StageUpAxis.py](./StageUpAxis.py)|Stageのアップベクトルの取得/設定|
|[CreateHierarchy.py](./CreateHierarchy.py)|Xformを使って階層構造を作って形状を配置<br>|
|[GetAllFacesCount.py](./GetAllFacesCount.py)|シーン内のすべてのMeshの面数を合計して表示。<br>対象はMesh/PointInstancer。|
|[TraverseHierarchy.py](./TraverseHierarchy.py)|シーンの階層構造をたどってPrim名を表示。<br>Meshの場合はMeshの面数も表示。|
|[Traverse_mesh.py](./Traverse_mesh.py)|Usd.PrimRangeを使ってPrimを取得し、Meshのみを格納|
|[GetMetersPerUnit.py](./GetMetersPerUnit.py)|metersPerUnitの取得/設定|
|[NewStage.py](./NewStage.py)|何も配置されていない新しいStageを作成します。<br>なお、直前のStageの変更は保存されません。|
|[CloseStage.py](./CloseStage.py)|現在のStageを閉じます。<br>なお、直前のStageの変更は保存されません。|
|[OpenUSDFile.py](./OpenUSDFile.py)|指定のUSDファイルを開きます。<br>なお、直前のStageの変更は保存されません。|
|[GetResolvedPath.py](./GetResolvedPath.py)|カレントStageで指定されている相対パス(テクスチャやReferenceとして参照しているusdファイルなど)を絶対パスに変換。<br>存在しないパスを指定した場合は空文字が返る。|
## レイヤ関連
|ファイル|説明|
|---|---|
|[GetRealPath.py](./Layers/GetRealPath.py)|読み込んだStageのパスを取得|
|[GetSublayers.py](./Layers/GetSublayers.py)|SubLayerのパスを取得| | 1,197 | Markdown | 51.086954 | 141 | 0.729323 |
ft-lab/omniverse_sample_scripts/Scene/NewStage.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
omni.usd.get_context().new_stage()
print("New Stage !")
| 109 | Python | 20.999996 | 51 | 0.697248 |
ft-lab/omniverse_sample_scripts/Scene/GetAllFacesCount.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# ---------------------------------------.
# Get the number of faces used by PointInstancer.
# ---------------------------------------.
def TraversePointInstancer (prim):
typeName = prim.GetTypeName()
allCou = 0
if typeName == 'Mesh':
m = UsdGeom.Mesh(prim)
# If it is displayed.
if m.ComputeVisibility() == 'inherited':
# Get the number of faces of Mesh.
allCou += len(m.GetFaceVertexCountsAttr().Get())
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
allCou += TraversePointInstancer(cPrim)
return allCou
# ---------------------------------------.
# traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy_number (depth, prim):
if prim.IsValid() == None:
return 0
typeName = prim.GetTypeName()
allCou = 0
if typeName == 'PointInstancer':
m = UsdGeom.PointInstancer(prim)
# If it is displayed.
if m.ComputeVisibility() == 'inherited':
# Get the number of faces used by PointInstancer.
facesCou = TraversePointInstancer(prim)
piCou = 0
positionsA = m.GetPositionsAttr().Get()
if positionsA != None:
piCou = len(positionsA)
allCou += facesCou * piCou
return allCou
if typeName == 'Mesh':
m = UsdGeom.Mesh(prim)
# If it is displayed.
if m.ComputeVisibility() == 'inherited':
# Get the number of faces of Mesh.
allCou += len(m.GetFaceVertexCountsAttr().Get())
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
allCou += TraverseHierarchy_number(depth + 1, cPrim)
return allCou
# ---------------------------------------.
# 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
# traverse the hierarchy.
tPrim = stage.GetPrimAtPath(rootPath)
allFacesCou = TraverseHierarchy_number(0, tPrim)
print("Number of all faces : " + str(allFacesCou))
| 2,313 | Python | 26.879518 | 63 | 0.57112 |
ft-lab/omniverse_sample_scripts/Scene/CreateHierarchy.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 empty node(Xform).
UsdGeom.Xform.Define(stage, rootPath + '/node1')
# Create empty node(Xform).
UsdGeom.Xform.Define(stage, rootPath + '/node1/node1_2')
# Create sphere.
pathName = rootPath + '/node1/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(1.0)
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((-3, 0, 0))
# Create cube.
pathName = rootPath + '/node1/cube'
cubeGeom = UsdGeom.Cube.Define(stage, pathName)
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0, 0, 0))
| 856 | Python | 22.805555 | 63 | 0.731308 |
ft-lab/omniverse_sample_scripts/Scene/GetMetersPerUnit.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get metersPerUnit (default : 0.01).
metersPerUnit = UsdGeom.GetStageMetersPerUnit(stage)
print("MetersPerUnit : " + str(metersPerUnit))
# Set metersPerUnit.
try:
UsdGeom.SetStageMetersPerUnit(stage, 0.01)
except Exception as e:
print(e)
| 370 | Python | 23.733332 | 63 | 0.732432 |
ft-lab/omniverse_sample_scripts/Scene/TraverseHierarchy.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# ---------------------------------------.
# traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy (depth, prim):
if prim.IsValid() == None:
return
indentStr = ''
for i in range(depth):
indentStr += ' '
# Print Prim information.
name = prim.GetName()
typeName = prim.GetTypeName()
s = indentStr + '[ ' + name + ' ]'
s += ' type : ' + typeName
# If hidden.
if UsdGeom.Imageable(prim).ComputeVisibility() == 'invisible':
s += ' ** Hide **'
print(s)
if typeName == 'Mesh':
# Get the number of faces of Mesh.
m = UsdGeom.Mesh(prim)
faceCount = len(m.GetFaceVertexCountsAttr().Get())
print(indentStr + ' Face count : ' + str(faceCount))
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
TraverseHierarchy(depth + 1, cPrim)
# ---------------------------------------.
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
print("--- Default prim ---")
defaultPrim = stage.GetDefaultPrim()
if defaultPrim.IsValid():
print("DefaultPrim(Name) : " + defaultPrim.GetName())
print("DefaultPrim(Path) : " + defaultPrim.GetPath().pathString)
else:
print("Default Prim does not exist.")
print("")
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
print("Root path : " + rootPath)
print("")
# traverse the hierarchy.
tPrim = stage.GetPrimAtPath(rootPath)
print("--- Hierarchy ---")
TraverseHierarchy(0, tPrim)
print("")
| 1,683 | Python | 24.515151 | 68 | 0.57754 |
ft-lab/omniverse_sample_scripts/Scene/Traverse_mesh.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
defaultPrim = stage.GetDefaultPrim()
if defaultPrim.IsValid():
prims = []
for prim in Usd.PrimRange(defaultPrim):
if prim.IsA(UsdGeom.Mesh): # For Mesh.
prims.append(prim)
for prim in prims:
print(prim.GetName() + " (" + prim.GetPath().pathString + ")")
| 423 | Python | 25.499998 | 70 | 0.628842 |
ft-lab/omniverse_sample_scripts/Scene/Layers/GetSublayers.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get root layer.
rootLayer = stage.GetRootLayer()
# Get subLayer paths.
sublayerPaths = rootLayer.subLayerPaths
for path in sublayerPaths:
print(" " + path)
| 287 | Python | 19.571427 | 63 | 0.71777 |
ft-lab/omniverse_sample_scripts/Scene/Layers/GetRealPath.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get root layer.
rootLayer = stage.GetRootLayer()
# Get real path.
realPath = rootLayer.realPath
print("realPath : " + realPath)
| 254 | Python | 18.615383 | 63 | 0.712598 |
ft-lab/omniverse_sample_scripts/Audio/PlaySound.py | import omni.audioplayer # need "omni.audioplayer" extension.
import time
import asyncio
# ----------------------------------------------.
# AudioPlayer.
# ----------------------------------------------.
class AudioPlayer:
_player = None
_filePath = None
_loadSuccess = False
_loadBusy = False
def __init__(self):
pass
def startup (self):
self._player = omni.audioplayer.create_audio_player()
def shutdown (self):
self.stop()
self._player = None
def _file_loaded (self, success : bool):
self._loadSuccess = success
if success:
print("load success!")
soundLength = self._player.get_sound_length()
print(f"sound length : {soundLength} sec")
else:
print("load failed...")
self._loadBusy = False
# Load sound from file.
def loadFromFile (self, filePath : str):
self._loadSuccess = False
if self._player == None:
return
self._filePath = filePath
self._loadBusy = True
self._player.load_sound(filePath, self._file_loaded)
# Wait for it to finish loading.
def isLoad (self):
while self._loadBusy:
time.sleep(0.1)
return self._loadSuccess
# Called when playback is finished.
def _play_finished (self):
print("play finished.")
# Play sound.
def play (self):
if self._player == None:
return False
self._player.play_sound(self._filePath, None, self._play_finished, 0.0)
# Stop sound.
def stop (self):
if self._player != None:
self._player.stop_sound()
# ----------------------------------------------.
# Initialize AudioPlayer.
audio = AudioPlayer()
audio.startup()
# Load sound file.
# Specify an Audio file name that matches your environment.
audio.loadFromFile("./audio/HitWall.ogg")
if audio.isLoad():
for i in range(3):
# Play sound.
audio.play()
# Wait one seconds.
time.sleep(1.0)
# Terminate AudioPlayer.
audio.shutdown()
| 2,093 | Python | 23.348837 | 79 | 0.548973 |
ft-lab/omniverse_sample_scripts/Audio/readme.md | # Audio
Audioファイルを読み込んで再生します。
Audio自身はUSDでPrimとして指定することができます。
UsdAudio Proposal
https://graphics.pixar.com/usd/release/wp_usdaudio.html
また、OmniverseでもUIとしてAudioのStageへのインポートができます。
https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_audio.html
Audioファイルフォーマットは、wav/ogg/mp3が再生できるのを確認しています。
USDファイルにAudioを指定でき、この場合はTimelineの指定の位置での再生が可能です。
Pythonスクリプトから任意のタイミングでの再生するにはExtensionの「omni.audioplayer」を使用します。
Audioファイルは [HitWall.ogg](./audio/HitWall.ogg) をサンプルとしてアップしているため、
スクリプトから検索できる位置に配置してご利用くださいませ。
|ファイル|説明|
|---|---|
|[PlaySound.py](./PlaySound.py)|Audioファイルを読み込んで再生<br>"omni.audioplayer" ExtensionをOnにする必要があります。|
| 704 | Markdown | 26.115384 | 101 | 0.75142 |
ft-lab/omniverse_sample_scripts/Prim/IsValid.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
path = "/World"
# Get prim.
prim = stage.GetPrimAtPath(path)
# Use IsValid to check if the specified Prim exists.
print(path + " : " + str(prim.IsValid()))
| 280 | Python | 20.615383 | 63 | 0.685714 |
ft-lab/omniverse_sample_scripts/Prim/GetSingleSided.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.IsValid() == False:
continue
try:
singleSidedAttr = prim.GetAttribute("singleSided")
if singleSidedAttr != None and singleSidedAttr.IsValid():
# Get singleSided (True/False).
if singleSidedAttr.Get() != None:
print("[" + prim.GetName() + "] singleSided : " + str(singleSidedAttr.Get()))
# Set singleSided.
#if prim.GetTypeName() == 'Mesh':
# singleSidedAttr = prim.CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool)
# singleSidedAttr.Set(True)
except Exception as e:
print(e)
| 929 | Python | 29.999999 | 93 | 0.620022 |
ft-lab/omniverse_sample_scripts/Prim/CreateXform.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()
defaultPrimPath = defaultPrim.GetPath().pathString
path = defaultPrimPath + '/xform'
# Create empty node(Xform).
UsdGeom.Xform.Define(stage, path)
| 329 | Python | 20.999999 | 63 | 0.741641 |
ft-lab/omniverse_sample_scripts/Prim/readme.md | # Prim
USDのPrim(ノード相当)を操作します。
Primの操作は「[CommandsExecute](../Operation/CommandsExecute)」も便利に使用できます。
|ファイル|説明|
|---|---|
|[IsValid.py](./IsValid.py)|指定のパスのPrimが存在するかチェック(IsValid)|
|[GetPrimNamePath.py](./GetPrimNamePath.py)|指定のPrimの名前とパスを取得|
|[GetDefaultPrim.py](./GetDefaultPrim.py)|StageのルートとなるPrim(DefaultPrim)を取得|
|[SetDefaultPrim.py](./SetDefaultPrim.py)|StageのルートとなるPrim(DefaultPrim)を指定|
|[CreateXform.py](./CreateXform.py)|空のノード(Nullノード相当)を作成。<br>USDではこれを"Xform"と呼んでいます。<br>UsdGeom.Xform ( https://graphics.pixar.com/usd/release/api/class_usd_geom_xform.html )を使用します。|
|[CreateScope.py](./CreateScope.py)|Scopeを作成。<br>Scopeは移動/回転/スケール要素を持ちません。単純なグルーピング向けです。<br>UsdGeom.Scope ( https://graphics.pixar.com/usd/release/api/class_usd_geom_scope.html )を使用します。|
|[GetDoubleSided.py](./GetDoubleSided.py)|ジオメトリでのDoubleSided指定の取得、設定|
|[GetSingleSided.py](./GetSingleSided.py)|ジオメトリでのSingleSided指定の取得、設定<br>これはOmniverseでの独自の属性|
|[GetParent.py](./GetParent.py)|選択パスの親のPrimを取得|
|[GetChildren.py](./GetChildren.py)|選択パスの子のPrimを取得|
|[CalcWorldBoundingBox.py](./CalcWorldBoundingBox.py)|選択形状のワールド座標でのバウンディングボックスを計算|
|[RemovePrim.py](./RemovePrim.py)|指定のパスのPrimを削除。<br>Sdf.NamespaceEdit.Removeを使用する。|
|[RenamePrim.py](./RenamePrim.py)|指定のパスのPrim名を変更。<br>Sdf.NamespaceEdit.Renameを使用する。|
|サンプル|説明|
|---|---|
|[Visibility](./Visibility)|Primの表示/非表示|
|[Kind](./Kind)|PrimのKindを取得/設定|
|[Transform](./Transform)|Transform(scale/rotate/translate)の取得/設定|
|[TypeName](./TypeName)|PrimのTypeName(Xform/Mesh/DistantLightなど)を取得|
|[Skeleton](./Skeleton)|Skeletonでの情報を取得|
|[Reference](./Reference)|参照(Reference/Payload)を使った複製/参照のチェック|
|[PointInstancer](./PointInstancer)|アセット(USDで指定)を複数の位置/回転/スケールで複製配置(PointInstancer)|
|[Variant](./Variant)|Variantを使ったPrimの切り替え|
| 1,873 | Markdown | 51.055554 | 191 | 0.722904 |
ft-lab/omniverse_sample_scripts/Prim/GetParent.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.IsValid() == False:
continue
# Get parent prim.
parentPrim = prim.GetParent()
if parentPrim.IsValid():
print("[ " + prim.GetPath().pathString + " ]")
print(" Parent : " + parentPrim.GetPath().pathString)
| 561 | Python | 25.761904 | 63 | 0.645276 |
ft-lab/omniverse_sample_scripts/Prim/CreateScope.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()
defaultPrimPath = defaultPrim.GetPath().pathString
path = defaultPrimPath + '/scope'
# Create scope.
UsdGeom.Scope.Define(stage, path)
| 317 | Python | 20.199999 | 63 | 0.741325 |
ft-lab/omniverse_sample_scripts/Prim/SetDefaultPrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create empty node(Xform).
path = "/NewWorld"
UsdGeom.Xform.Define(stage, path)
prim = stage.GetPrimAtPath(path)
# Set default prim.
stage.SetDefaultPrim(prim)
| 285 | Python | 19.42857 | 63 | 0.729825 |
ft-lab/omniverse_sample_scripts/Prim/GetPrimNamePath.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get prim.
orgPath = "/World/defaultLight"
prim = stage.GetPrimAtPath(orgPath)
if prim.IsValid():
# Get Prim name.
name = prim.GetName()
print("Name : " + str(name))
# Get Prim path.
path = prim.GetPath()
print("Path : " + str(path))
| 383 | Python | 20.333332 | 63 | 0.634465 |
ft-lab/omniverse_sample_scripts/Prim/RemovePrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get prim.
path = "/World/Sphere"
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Remove prim.
# See here : https://graphics.pixar.com/usd/release/api/class_usd_stage.html#ac605faad8fc2673263775b1eecad2955
# For example, if Prim is used in a layer, RemovePrim will not remove it completely.
#stage.RemovePrim(path)
# Prepare specified paths as candidates for deletion.
edit = Sdf.NamespaceEdit.Remove(path)
batchE = Sdf.BatchNamespaceEdit()
batchE.Add(edit)
# Execute Deletion.
stage.GetEditTarget().GetLayer().Apply(batchE)
| 702 | Python | 28.291665 | 114 | 0.709402 |
ft-lab/omniverse_sample_scripts/Prim/GetDefaultPrim.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()
# Default prim path.
defaultPrimPath = defaultPrim.GetPath().pathString
print("DefaultPrim : " + defaultPrimPath) | 294 | Python | 23.583331 | 63 | 0.744898 |
ft-lab/omniverse_sample_scripts/Prim/GetChildren.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.IsValid() == False:
continue
# Get children.
pChildren = prim.GetChildren()
if len(pChildren) >= 1:
print("[ " + prim.GetPath().pathString + " ]")
for cPrim in pChildren:
print(" " + cPrim.GetPath().pathString)
| 585 | Python | 24.47826 | 63 | 0.623932 |
ft-lab/omniverse_sample_scripts/Prim/GetDoubleSided.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.IsValid() == False:
continue
try:
gprim = UsdGeom.Gprim(prim)
doubleSidedAttr = gprim.GetDoubleSidedAttr()
if doubleSidedAttr != None and doubleSidedAttr.IsValid():
# Get doubleSided (True/False).
# The Omniverse Viewport does not reflect "doubleSided", but "singleSided".
if doubleSidedAttr.Get() != None:
print("[" + prim.GetName() + "] doubleSided : " + str(doubleSidedAttr.Get()))
# Set DoubleSided.
#doubleSidedAttr.Set(True)
except Exception as e:
print(e)
| 937 | Python | 30.266666 | 93 | 0.602988 |
ft-lab/omniverse_sample_scripts/Prim/CalcWorldBoundingBox.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# -------------------------------------------------.
# Calculate bounding box in world coordinates.
# -------------------------------------------------.
def _calcWorldBoundingBox (prim : Usd.Prim):
# Calc world boundingBox.
bboxCache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"])
bboxD = bboxCache.ComputeWorldBound(prim).ComputeAlignedRange()
bb_min = Gf.Vec3f(bboxD.GetMin())
bb_max = Gf.Vec3f(bboxD.GetMax())
return bb_min, bb_max
# -------------------------------------------------.
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
continue
print("[ " + str(prim.GetName()) + "] ")
bbMin, bbMax = _calcWorldBoundingBox(prim)
print(" BoundingBox : " + str(bbMin) + " - " + str(bbMax))
sx = bbMax[0] - bbMin[0]
sy = bbMax[1] - bbMin[1]
sz = bbMax[2] - bbMin[2]
print(" BoundingBoxSize : " + str(sx) + " x " + str(sy) + " x " + str(sz))
| 1,225 | Python | 31.263157 | 79 | 0.553469 |
ft-lab/omniverse_sample_scripts/Prim/RenamePrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get prim.
path = "/World/Sphere"
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Rename prim.
# Prepare specified paths as candidates for rename.
# "/World/Sphere" to "/World/Sphere2"
edit = Sdf.NamespaceEdit.Rename(path, "Sphere2")
batchE = Sdf.BatchNamespaceEdit()
batchE.Add(edit)
# Execute rename.
stage.GetEditTarget().GetLayer().Apply(batchE)
| 519 | Python | 22.636363 | 63 | 0.676301 |
ft-lab/omniverse_sample_scripts/Prim/Reference/InternalReferenceTest.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()
defaultPrimPath = defaultPrim.GetPath().pathString
# Create sphere.
orgPath = defaultPrimPath + '/org'
UsdGeom.Xform.Define(stage, orgPath)
spherePath = orgPath + '/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
# Set radius.
sphereGeom.CreateRadiusAttr(2.0)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Create empty node(Xform).
path = defaultPrimPath + '/refShape'
UsdGeom.Xform.Define(stage, path)
prim = stage.GetPrimAtPath(path)
# Set position.
UsdGeom.XformCommonAPI(prim).SetTranslate((5.0, 0.0, 0.0))
# Remove references.
prim.GetReferences().ClearReferences()
# Add a internal reference.
# The Path to be added must be an Xform.
prim.GetReferences().AddInternalReference(orgPath)
| 913 | Python | 24.388888 | 63 | 0.751369 |
ft-lab/omniverse_sample_scripts/Prim/Reference/ReferenceTest2.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()
defaultPrimPath = defaultPrim.GetPath().pathString
# Create empty node(Xform).
path = defaultPrimPath + '/refShape'
UsdGeom.Xform.Define(stage, path)
prim = stage.GetPrimAtPath(path)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
#usdPath = "./cyawan/cyawan.usdc"
usdPath = "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan.usdc"
prim.GetReferences().AddReference(usdPath)
| 595 | Python | 26.090908 | 73 | 0.754622 |
ft-lab/omniverse_sample_scripts/Prim/Reference/readme.md | # Reference
参照の処理を行います。
## ReferenceとPayload
USDでは、他のUSDを参照する構造として"Reference"と"Payload"があります。
Payload は「弱い参照」となります。
Payload としてインポートした場合は、見た目上は参照と変わりません。
以下はOmniverse Createでのパラメータです(USD自身がこの構造を持っています)。

Payload したUSDはアンロードすることができ、これによりメモリ解放できます。
また、必要な時にロードできます。
対してReferenceの場合は参照のロード/アンロード機能はありません。
Payloadのほうが利便性があるため、基本的にはPayloadで参照を指定するほうがよいかもしれません。
## サンプル
|ファイル|説明|
|---|---|
|[ReferenceTest.py](./ReferenceTest.py)|作成したXformに対して外部のusdファイルを参照として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[sphere.usda](./usd/sphere.usda)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>|
|[PayloadTest.py](./PayloadTest.py)|作成したXformに対して外部のusdファイルを参照(Payload)として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[sphere.usda](./usd/sphere.usda)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>|
|[ReferenceTest2.py](./ReferenceTest2.py)|作成したXformに対して外部のテクスチャ付きのusdファイルを参照として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[./cyawan/cyawan.usdc](./usd/cyawan/cyawan.usdc)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>|
|[InternalReferenceTest.py](./InternalReferenceTest.py)|作成したXformに対して同一Stage内のPrimを参照として追加<br>|
|[HasReference.py](./HasReference.py)|選択した形状が参照を持つかチェック|
|[HasPayload.py](./HasPayload.py)|選択した形状がPayloadを持つかチェック|
|[GetReferencePayload.py](./GetReferencePayload.py)|選択した形状がReferenceまたはPayloadの場合に、参照先のパスを取得|
----
| 1,749 | Markdown | 52.030301 | 299 | 0.765009 |
ft-lab/omniverse_sample_scripts/Prim/Reference/GetReferencePayload.py | # "Pcp" added below.
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, Pcp
# 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():
# If Prim has Reference or Payload.
if prim.HasAuthoredReferences() or prim.HasPayload():
query = Usd.PrimCompositionQuery.GetDirectRootLayerArcs(prim)
qList = query.GetCompositionArcs()
if qList != None:
for arc in qList:
arcType = arc.GetArcType()
if arcType != Pcp.ArcTypeReference and arcType != Pcp.ArcTypePayload:
continue
# Get AssetPath.
editorProxy, reference = arc.GetIntroducingListEditor()
assetPath = reference.assetPath
if arcType == Pcp.ArcTypeReference:
print("[" + prim.GetName() + "] has reference > " + assetPath)
if arcType == Pcp.ArcTypePayload:
print("[" + prim.GetName() + "] has payload. > " + assetPath)
| 1,256 | Python | 32.972972 | 89 | 0.565287 |
ft-lab/omniverse_sample_scripts/Prim/Kind/readme.md | # Kind
PrimのKindを取得/設定。
|ファイル|説明|
|---|---|
|[SetComponent.py](./SetComponent.py)|選択PrimのKindをComponentに変更|
|[GetKind.py](./GetKind.py)|選択PrimのKindを取得|
| 177 | Markdown | 13.833332 | 67 | 0.610169 |
ft-lab/omniverse_sample_scripts/Prim/Kind/SetComponent.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.IsValid() == False:
continue
# Change the value of Kind in Prim to Component.
Usd.ModelAPI(prim).SetKind(Kind.Tokens.component)
| 464 | Python | 24.833332 | 63 | 0.69181 |
ft-lab/omniverse_sample_scripts/Prim/Skeleton/GetJoints.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()
# -------------------------------------------------------------------.
# Traverse.
# -------------------------------------------------------------------.
def Traverse (prim):
if prim.IsValid() == None:
return
# For Skeleton, get the Joints information.
if prim.GetTypeName() == 'Skeleton':
jointAttr = prim.GetAttribute("joints")
bindTransformsAttr = prim.GetAttribute("bindTransforms")
restTransformsAttr = prim.GetAttribute("restTransforms")
if jointAttr.IsValid() and bindTransformsAttr.IsValid() and restTransformsAttr.IsValid():
jCou = len(jointAttr.Get())
print("[ " + prim.GetPath().pathString + " ]")
for i in range(jCou):
jointName = jointAttr.Get()[i]
bindTransform = bindTransformsAttr.Get()[i]
restTransform = restTransformsAttr.Get()[i]
print(str(i) + " : " + jointName)
print(" bindTransform : " + str(bindTransform))
print(" restTransform : " + str(restTransform))
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
Traverse(cPrim)
# -------------------------------------------------------------------.
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
Traverse(prim)
| 1,621 | Python | 30.192307 | 97 | 0.530537 |
ft-lab/omniverse_sample_scripts/Prim/Skeleton/GetSkeletonTransforms.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
skel_cache = UsdSkel.Cache()
#time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond()
time_code = Usd.TimeCode.Default()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.IsValid() and prim.GetTypeName() == 'Skeleton':
# Get transform from cache.
skel_query = skel_cache.GetSkelQuery(UsdSkel.Skeleton(prim))
transforms = skel_query.ComputeJointLocalTransforms(time_code)
# joints name.
jointNames = skel_query.GetJointOrder()
# joints matrix to translate, rotations, scales.
translates, rotations, scales = UsdSkel.DecomposeTransforms(transforms)
print(jointNames)
print(" Translates : " + str(translates))
print(" Rotations : " + str(rotations))
print(" Scales : " + str(scales))
| 1,122 | Python | 31.085713 | 102 | 0.674688 |
ft-lab/omniverse_sample_scripts/Prim/Skeleton/readme.md | # Skeleton
Skeletonでの情報を取得。
|ファイル|説明|
|---|---|
|[GetJoints.py](./GetJoints.py)|選択Primの中に"Skeleton"がある場合に、ジョイント名/バインドの行列/リセットの行列を表示|
|[GetSkeletonTransforms.py](./GetSkeletonTransforms.py)|選択Primが"Skeleton"の場合に、ジョイント名と移動/回転/スケールのリストを取得|
| 261 | Markdown | 22.81818 | 107 | 0.704981 |
ft-lab/omniverse_sample_scripts/Prim/Visibility/readme.md | # Visibility
Primの表示/非表示。
|ファイル|説明|
|---|---|
|[GetShowHidePrim.py](./GetShowHidePrim.py)|選択Primの表示/非表示を取得|
|[ShowHidePrim.py](./ShowHidePrim.py)|選択Primの表示/非表示を切り替え|
| 190 | Markdown | 16.363635 | 65 | 0.631579 |
ft-lab/omniverse_sample_scripts/Prim/PointInstancer/PointInstancer_01.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import random
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
defaultPrimPath = defaultPrim.GetPath().pathString
# Create empty node(Xform).
path = defaultPrimPath + '/trees'
UsdGeom.Xform.Define(stage, path)
prim = stage.GetPrimAtPath(path)
# Create PointInstancer.
pointInstancerPath = path + '/pointInstancer'
pointInstancer = UsdGeom.PointInstancer.Define(stage, pointInstancerPath)
# Create Reference.
refPath = pointInstancerPath + '/asset'
UsdGeom.Xform.Define(stage, refPath)
prim = stage.GetPrimAtPath(refPath)
# Set Kind.
#Usd.ModelAPI(prim).SetKind(Kind.Tokens.component)
Usd.ModelAPI(prim).SetKind("component")
# Set the asset to be referenced.
pointInstancer.CreatePrototypesRel().AddTarget(refPath)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
#usdPath = "./simpleTree.usda"
usdPath = "https://ft-lab.github.io/usd/omniverse/usd/simpleTree.usda"
prim.GetReferences().AddReference(usdPath)
# Points data.
positions = []
scales = []
protoIndices = []
orientations = []
areaSize = 1000.0
treesCou = 50
for i in range(treesCou):
px = random.random() * areaSize - (areaSize * 0.5)
pz = random.random() * areaSize - (areaSize * 0.5)
scale = random.random() * 0.5 + 0.8
positions.append(Gf.Vec3f(px, 0.0, pz)) # Position.
orientations.append(Gf.Quath()) # Rotation.
scales.append(Gf.Vec3f(scale, scale, scale)) # Scale.
protoIndices.append(0) # asset index.
pointInstancer.CreatePositionsAttr(positions)
pointInstancer.CreateOrientationsAttr(orientations)
pointInstancer.CreateScalesAttr(scales)
pointInstancer.CreateProtoIndicesAttr(protoIndices)
| 1,807 | Python | 28.16129 | 73 | 0.729386 |
ft-lab/omniverse_sample_scripts/Prim/PointInstancer/readme.md | # PointInstancer
指定のアセット(USDファイルで指定)をPointInstancerを使って、位置/回転/スケールを指定して複製。
UsdGeom.PointInstancer ( https://graphics.pixar.com/usd/release/api/class_usd_geom_point_instancer.html ) を使用します。
|ファイル|説明|
|---|---|
|[PointInstancer_01.py](./PointInstancer_01.py)|木の"simpleTree.usda"をアセットとして、ランダムな位置/スケールで複製。<br>木のusdは[simpleTree.usda](./usd/simpleTree.usda)を使用しています。<br>|
| 453 | Markdown | 44.399996 | 224 | 0.739514 |
ft-lab/omniverse_sample_scripts/Prim/TypeName/readme.md | # TypeName
PrimのTypeName(Xform/Mesh/DistantLightなど)を取得。
|ファイル|説明|
|---|---|
|[GetTypeName.py](./GetTypeName.py)|PrimのTypeNameを取得|
| 151 | Markdown | 12.818181 | 57 | 0.629139 |
ft-lab/omniverse_sample_scripts/Prim/Variant/Variant_01.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Reference : https://github.com/PixarAnimationStudios/USD/blob/release/extras/usd/tutorials/authoringVariants/authorVariants.py
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
defaultPrimPath = defaultPrim.GetPath().pathString
# Create empty node(Xform).
path = defaultPrimPath + '/Chair'
UsdGeom.Xform.Define(stage, path)
prim = stage.GetPrimAtPath(path)
# Set VariantSet.
variantSet = prim.GetVariantSet('variantGroup')
variantSet.AddVariant('chair1')
variantSet.AddVariant('chair2')
variantSet.AddVariant('chair3')
# -----------------------------------------------.
# Set Chair.
# -----------------------------------------------.
def SetChair (index : int, path : str, colorV):
# Create reference.
# The USD file to be referenced should be changed to suit your environment.
usdPath = "https://ft-lab.github.io/usd/omniverse/usd/simple_chair.usda"
path2 = path + '/simple_chair_' + str(index)
UsdGeom.Xform.Define(stage, path2)
prim2 = stage.GetPrimAtPath(path2)
prim2.GetReferences().AddReference(usdPath)
path3 = path2 + '/simple_chair'
targetPrim = UsdGeom.Gprim.Get(stage, path3)
try:
# Clear Material.
UsdShade.MaterialBindingAPI(targetPrim).UnbindAllBindings()
# Set Display Color.
colorAttr = targetPrim.GetDisplayColorAttr()
colorAttr.Set([colorV])
except Exception as e:
pass
# -----------------------------------------------.
# Set 'chair1'.
variantSet.SetVariantSelection("chair1")
with variantSet.GetVariantEditContext():
SetChair(1, path, (1,0,0))
# Set 'chair2'.
variantSet.SetVariantSelection("chair2")
with variantSet.GetVariantEditContext():
SetChair(2, path, (0,1,0))
# Set 'chair3'.
variantSet.SetVariantSelection("chair3")
with variantSet.GetVariantEditContext():
SetChair(3, path, (0,0,1))
# Select current variant.
variantSet.SetVariantSelection("chair1")
| 2,026 | Python | 30.184615 | 128 | 0.670286 |
ft-lab/omniverse_sample_scripts/Prim/Variant/readme.md | # Variant
PrimのGetVariant( https://graphics.pixar.com/usd/release/api/class_usd_prim.html#a607da249e11bc4f5f3b4bf0db99861ab )を使用して、1つのPrim内で複数のPrimを「VariantSet」として登録します。
この例の場合は椅子のusdファイル([simple_chair.usda](../Reference/usd/simple_chair.usda))を参照し、色を変えて3つの形状としています。

表示されるのはVariantで指定された1つの形状のみです。
|ファイル|説明|
|---|---|
|[Variant_01.py](./Variant_01.py)|Variantを使ったPrimの切り替えのテスト|
| 467 | Markdown | 32.428569 | 163 | 0.734475 |
ft-lab/omniverse_sample_scripts/Prim/Transform/SetRotate.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.timeline
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# --------------------------------------------------.
# Set Rotate.
# --------------------------------------------------.
def _setRotate (prim : Usd.Prim, rV : Gf.Vec3f):
if prim == None:
return
# Get rotOrder.
# If rotation does not exist, rotOrder = UsdGeom.XformCommonAPI.RotationOrderXYZ.
xformAPI = UsdGeom.XformCommonAPI(prim)
time_code = Usd.TimeCode.Default()
translation, rotation, scale, pivot, rotOrder = xformAPI.GetXformVectors(time_code)
# Convert rotOrder to "xformOp:rotateXYZ" etc.
t = xformAPI.ConvertRotationOrderToOpType(rotOrder)
rotateAttrName = "xformOp:" + UsdGeom.XformOp.GetOpTypeToken(t)
# Set rotate.
rotate = prim.GetAttribute(rotateAttrName).Get()
if rotate != None:
# Specify a value for each type.
if type(rotate) == Gf.Vec3f:
prim.GetAttribute(rotateAttrName).Set(Gf.Vec3f(rV))
elif type(rotate) == Gf.Vec3d:
prim.GetAttribute(rotateAttrName).Set(Gf.Vec3d(rV))
else:
# xformOpOrder is also updated.
xformAPI.SetRotate(Gf.Vec3f(rV), rotOrder)
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
rV = Gf.Vec3f(10.0, 25.0, 12.0)
_setRotate(prim, rV)
| 1,599 | Python | 30.999999 | 87 | 0.61601 |
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransformOrder.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() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
# Order of Transform elements.
transformOrder = prim.GetAttribute('xformOpOrder').Get()
for sV in transformOrder:
print(f" {sV}")
| 558 | Python | 24.40909 | 64 | 0.636201 |
ft-lab/omniverse_sample_scripts/Prim/Transform/SetTransform.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 transform.
prim = stage.GetPrimAtPath(pathName)
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 10, 0))
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(1, 2, 1))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(120, 45, 0))
transformOrder = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False)
transformOrder.Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
| 844 | Python | 34.208332 | 101 | 0.75237 |
ft-lab/omniverse_sample_scripts/Prim/Transform/SetPivot.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.timeline
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# --------------------------------------------------.
# Set pivot.
# --------------------------------------------------.
def _setPivot (prim : Usd.Prim, pV : Gf.Vec3f):
pivot = prim.GetAttribute("xformOp:translate:pivot").Get()
if pivot != None:
# Specify a value for each type.
if type(pivot) == Gf.Vec3f:
prim.GetAttribute("xformOp:translate:pivot").Set(Gf.Vec3f(pV))
elif type(pivot) == Gf.Vec3d:
prim.GetAttribute("xformOp:translate:pivot").Set(Gf.Vec3d(pV))
else:
# xformOpOrder is also updated.
# ["xformOp:translate", "xformOp:translate:pivot", "xformOp:rotateXYZ", "xformOp:scale", "!invert!xformOp:translate:pivot"]
# The following do not work correctly?
#xformAPI = UsdGeom.XformCommonAPI(prim)
#xformAPI.SetPivot(Gf.Vec3f(pV))
prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(pV))
# ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale", "xformOp:translate:pivot", "!invert!xformOp:translate:pivot"]
transformOrder = prim.GetAttribute("xformOpOrder").Get()
orderList = []
for sV in transformOrder:
orderList.append(sV)
orderList.append("xformOp:translate:pivot")
orderList.append("!invert!xformOp:translate:pivot")
prim.GetAttribute("xformOpOrder").Set(orderList)
# --------------------------------------------------.
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
pV = Gf.Vec3f(10.0, 20.0, 0.0)
_setPivot(prim, pV)
| 1,953 | Python | 37.313725 | 131 | 0.596518 |
ft-lab/omniverse_sample_scripts/Prim/Transform/readme.md | # Transform
Transform(scale/rotate/translate)情報の取得/設定。
|ファイル|説明|
|---|---|
|[GetTransform.py](./GetTransform.py)|選択された形状のTransform要素を取得|
|[GetTransformOrder.py](./GetTransformOrder.py)|選択された形状のxformOpOrder(Transformの変換順)を取得|
|[SetTransform.py](./SetTransform.py)|Cubeを作成し、Transformを指定|
|[GetWorldTransform.py](./GetWorldTransform.py)|選択形状のTransformをワールド変換して表示|
|[GetLocalMatrix.py](./GetLocalMatrix.py)|選択形状のローカル座標での4x4変換行列を取得|
|[GetTransformVectors.py](./GetTransformVectors.py)|UsdGeom.XformCommonAPIを使用して、選択形状の移動/回転/スケール/Pivot/回転を取得|
|[SetTranslate.py](./SetTranslate.py)|選択形状の移動を指定。存在しなければxformOpOrderも考慮して追加|
|[SetScale.py](./SetScale.py)|選択形状のスケールを指定。存在しなければxformOpOrderも考慮して追加|
|[SetRotate.py](./SetRotate.py)|選択形状の回転を指定。存在しなければxformOpOrderも考慮して追加|
|[SetRotateWithQuat.py](./SetRotateWithQuat.py)|選択形状の回転をQuatで指定|
|[SetPivot.py](./SetPivot.py)|選択形状のPivotを指定。存在しなければxformOpOrderも考慮して追加|
|[DeletePivot.py](./DeletePivot.py)|選択形状のPivotを削除。一部 omni.kit.commands.execute('RemoveProperty') を使用|
| 1,041 | Markdown | 53.842102 | 112 | 0.772334 |
ft-lab/omniverse_sample_scripts/Prim/Transform/GetWorldTransform.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
xformCache = UsdGeom.XformCache(0)
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Get world Transform.
globalPose = xformCache.GetLocalToWorldTransform(prim)
print(globalPose)
# Decompose transform.
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# Conv Quat to eular angles.
# Rotate XYZ.
rV = Gf.Rotation(rotation).Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0))
rV = Gf.Vec3d(rV[2], rV[1], rV[0])
print(f"==> translate : {translate}")
print(f"==> rotation : {rV}")
print(f"==> scale : {scale}")
| 932 | Python | 28.156249 | 101 | 0.631974 |
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransform.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() == True:
# Print prim name.
print('[ ' + prim.GetName() + ' ]')
# Order of Transform elements.
transformOrder = prim.GetAttribute('xformOpOrder')
if transformOrder.IsValid() and transformOrder.Get() != None:
print(f" TransformOrder : {transformOrder.Get()}")
for transV in transformOrder.Get():
# 'xformOp:scale', 'xformOp:rotateXYZ', 'xformOp:translate', etc.
tV = prim.GetAttribute(transV)
if tV.IsValid():
print(f" {transV} ( {tV.GetTypeName()} ) : {tV.Get()}")
| 921 | Python | 30.793102 | 81 | 0.592834 |
ft-lab/omniverse_sample_scripts/Prim/Transform/SetScale.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.timeline
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# --------------------------------------------------.
# Set scale.
# --------------------------------------------------.
def _setScale (prim : Usd.Prim, sV : Gf.Vec3f):
if prim == None:
return
scale = prim.GetAttribute("xformOp:scale").Get()
if scale != None:
# Specify a value for each type.
if type(scale) == Gf.Vec3f:
prim.GetAttribute("xformOp:scale").Set(Gf.Vec3f(sV))
elif type(scale) == Gf.Vec3d:
prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(sV))
else:
# xformOpOrder is also updated.
xformAPI = UsdGeom.XformCommonAPI(prim)
xformAPI.SetScale(Gf.Vec3f(sV))
# --------------------------------------------------.
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
sV = Gf.Vec3f(1.1, 1.2, 1.3)
_setScale(prim, sV)
| 1,211 | Python | 28.560975 | 64 | 0.535095 |
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransformVectors.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.timeline
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
time_code = Usd.TimeCode.Default()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
# Get transform.
# However, the type that can be obtained here is different from the actual Type.
xformAPI = UsdGeom.XformCommonAPI(prim)
translation, rotation, scale, pivot, rotOrder = xformAPI.GetXformVectors(time_code)
print("** GetXformVectors **")
print(f"translation : {type(translation)} {translation}")
print(f"rotation : {type(rotation)} {rotation}")
print(f"scale : {type(scale)} {scale}")
print(f"pivot : {type(pivot)} {pivot}")
print(f"rotOrder : {type(rotOrder)} {rotOrder}")
print("** prim.GetAttribute **")
trans = prim.GetAttribute("xformOp:translate").Get()
print(f"trans : {type(trans)} {trans}")
# Convert rotOrder to "xformOp:rotateXYZ" etc.
t = xformAPI.ConvertRotationOrderToOpType(rotOrder)
rotateAttrName = "xformOp:" + UsdGeom.XformOp.GetOpTypeToken(t)
rotate = prim.GetAttribute(rotateAttrName).Get()
print(f"rotate ({rotateAttrName}) : {type(rotate)} {rotate}")
scale = prim.GetAttribute("xformOp:scale").Get()
print(f"scale : {type(scale)} {scale}")
pivot = prim.GetAttribute("xformOp:translate:pivot").Get()
print(f"pivot : {type(pivot)} {pivot}")
| 1,731 | Python | 33.639999 | 91 | 0.635471 |
ft-lab/omniverse_sample_scripts/Prim/Transform/SetTranslate.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.timeline
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# --------------------------------------------------.
# Set translate.
# --------------------------------------------------.
def _setTranslate (prim : Usd.Prim, tV : Gf.Vec3f):
if prim == None:
return
trans = prim.GetAttribute("xformOp:translate").Get()
if trans != None:
# Specify a value for each type.
if type(trans) == Gf.Vec3f:
prim.GetAttribute("xformOp:translate").Set(Gf.Vec3f(tV))
elif type(trans) == Gf.Vec3d:
prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(tV))
else:
# xformOpOrder is also updated.
xformAPI = UsdGeom.XformCommonAPI(prim)
xformAPI.SetTranslate(Gf.Vec3d(tV))
# -------------------------------------------------.
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print('[ ' + prim.GetName() + ' ]')
tV = Gf.Vec3f(10, 20, 30)
_setTranslate(prim, tV)
| 1,239 | Python | 29.999999 | 68 | 0.544794 |
ft-lab/omniverse_sample_scripts/Prim/Transform/DeletePivot.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.kit.commands
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# --------------------------------------------------.
# Delete pivot.
# --------------------------------------------------.
def _deletePivot (prim : Usd.Prim):
if prim == None:
return
path = prim.GetPath().pathString + ".xformOp:translate:pivot"
omni.kit.commands.execute('RemoveProperty', prop_path=path)
transformOrder = prim.GetAttribute("xformOpOrder").Get()
if transformOrder != None:
orderList = []
for sV in transformOrder:
if sV == "xformOp:translate:pivot" or sV == "!invert!xformOp:translate:pivot":
continue
orderList.append(sV)
prim.GetAttribute("xformOpOrder").Set(orderList)
# --------------------------------------------------.
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print('[ ' + prim.GetName() + ' ]')
# Delete pivot.
_deletePivot(prim)
| 1,226 | Python | 28.214285 | 90 | 0.553018 |
ft-lab/omniverse_sample_scripts/Prim/Transform/GetLocalMatrix.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()
xformCache = UsdGeom.XformCache(0)
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
# Print prim name.
print(f"[ {prim.GetName()} ]")
# Calc local matrix.
matrix = xformCache.GetLocalTransformation(prim)[0]
print(matrix)
# Decompose matrix.
# If the result is False, then reduce the value of eps and call Factor again.
eps = 1e-10
result = matrix.Factor(eps)
if result[0]:
scale = result[2]
rotate = result[3].ExtractRotation()
translation = result[4]
# Convert Rotate to Euler.
# Rotate XYZ.
rotateE = rotate.Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0))
rotateE = Gf.Vec3d(rotateE[2], rotateE[1], rotateE[0])
print(f"Translation : {translation}")
print(f"rotate : {rotateE}")
print(f"scale : {scale}")
| 1,205 | Python | 28.414633 | 95 | 0.585062 |
ft-lab/omniverse_sample_scripts/Operation/FocusPrim.py | # "omni.kit.viewport_legacy" is no longer available in kit104.
#import omni.kit.viewport_legacy
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit.commands
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
# Get stage.
stage = omni.usd.get_context().get_stage()
#time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond()
time_code = Usd.TimeCode()
# Get active camera.
cameraPrim = stage.GetPrimAtPath(cameraPath)
if cameraPrim.IsValid():
camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera
cameraV = camera.GetCamera(time_code) # Gf.Camera
# Aspect ratio.
aspect = cameraV.aspectRatio
# Taret prim path.
targetPrimPath = "/World/Sphere"
prim = stage.GetPrimAtPath(targetPrimPath)
if prim.IsValid():
# Set focus.
omni.kit.commands.execute('FramePrimsCommand',
prim_to_move=Sdf.Path(cameraPath),
prims_to_frame=[targetPrimPath],
time_code=time_code,
usd_context_name='',
aspect_ratio=aspect)
| 1,431 | Python | 30.822222 | 104 | 0.703704 |
ft-lab/omniverse_sample_scripts/Operation/readme.md | # Operation
Ominverseの操作/イベント処理を行います。
|ファイル|説明|
|---|---|
|[FocusPrim.py](./FocusPrim.py)|Kit104以上で動作。<br>指定のPrim(ここでは"/World/Sphere")にフォーカスを合わせる<br>(キーボードの[F]をプッシュした時と同じ動作)|
|サンプル|説明|
|---|---|
|[Selection](./Selection)|Stageウィンドウでの選択を取得|
|[GamePad](./GamePad)|GamePadの入力イベント取得|
|[Keyboard](./Keyboard)|Keyboardの入力イベント取得|
|[UNDO](./UNDO)|UNDO処理|
|[CommandsExecute](./CommandsExecute)|omni.kit.commandsを使用したコマンド実行|
| 473 | Markdown | 26.882351 | 121 | 0.638478 |
ft-lab/omniverse_sample_scripts/Operation/GamePad/GamePad_moveSelectPrim.py | from pxr import Usd, UsdGeom, UsdSkel, UsdPhysics, UsdShade, Sdf, Gf, Tf
import carb
import carb.input
import omni.kit.app
import omni.ext
# Reference : kit/exts/omni.kit.debug.input
# Get stage.
stage = omni.usd.get_context().get_stage()
# ------------------------------------------.
# Move the selected Prim.
# ------------------------------------------.
def moveSelectedPrim (mV : Gf.Vec3f):
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
Gf.Vec3f(0, 0, 0)
if prim.IsValid() == True:
# Get translate.
transformOrder = prim.GetAttribute('xformOpOrder')
if transformOrder.IsValid():
tV = prim.GetAttribute("xformOp:translate")
if tV.IsValid():
pos = Gf.Vec3f(tV.Get())
# Update translate.
pos += mV
tV.Set(pos)
# ------------------------------------------.
# Gamepad discription.
# ------------------------------------------.
class GamepadDesc:
def _cleanup(self):
self.name = None
self.guid = None
self.gamepad_device = None
self.input_device = None
self.is_connected = False
self.input_val = {}
def __init__(self):
self._cleanup()
def __del__(self):
self._cleanup()
# ------------------------------------------.
# Input with GamePad.
# ------------------------------------------.
class InputGamePad:
_gamepads = None
_input = None
_input_provider = None
_gamepad_connection_subs = None
_gamepad_inputs = None
_app = None
_pre_update_sub = None
def __init__(self):
pass
def _update_gamepad_connection_state(self, gamepad_device, connection_state):
for gamepad_desc in self._gamepads:
if gamepad_desc.gamepad_device == gamepad_device:
gamepad_desc.is_connected = connection_state
# gamepad connection event.
def _gamepad_connection_event(self, event):
# Gamepad created.
if event.type == carb.input.GamepadConnectionEventType.CREATED:
gamepad_desc = GamepadDesc()
gamepad_desc.name = self._input.get_gamepad_name(event.gamepad)
gamepad_desc.guid = self._input.get_gamepad_guid(event.gamepad)
gamepad_desc.gamepad_device = event.gamepad
gamepad_desc.input_device = event.device
self._gamepads.append(gamepad_desc)
print("carb.input.GamepadConnectionEventType.CREATED")
print("name : " + str(gamepad_desc.name))
print("guid : " + str(gamepad_desc.guid))
# Gamepad destroyed.
elif event.type == carb.input.GamepadConnectionEventType.DESTROYED:
for gamepad_desc in self._gamepads:
if gamepad_desc.gamepad_device == event.gamepad:
self._gamepads.remove(gamepad_desc)
print("carb.input.GamepadConnectionEventType.DESTROYED")
# Gamepad connected.
elif event.type == carb.input.GamepadConnectionEventType.CONNECTED:
self._update_gamepad_connection_state(event.gamepad, True)
print(" carb.input.GamepadConnectionEventType.CONNECTED")
# Gamepad disconnected.
elif event.type == carb.input.GamepadConnectionEventType.DISCONNECTED:
self._update_gamepad_connection_state(event.gamepad, False)
print(" carb.input.GamepadConnectionEventType.DISCONNECTED")
# gamepad update event.
def _update_gamepads_data(self, event):
gamepad_descD = None
for gamepad_desc in self._gamepads:
gamepad_descD = gamepad_desc
for gamepad_input in self._gamepad_inputs:
# Store value.
val = self._input.get_gamepad_value(gamepad_descD.gamepad_device, gamepad_input)
gamepad_descD.input_val[gamepad_input] = float(val)
# gamepad_input : DPAD (0.0 or 1.0).
# carb.input.GamepadInput.DPAD_DOWN
# carb.input.GamepadInput.DPAD_UP
# carb.input.GamepadInput.DPAD_LEFT
# carb.input.GamepadInput.DPAD_RIGHT
# gamepad_input : buttons (0.0 or 1.0).
# carb.input.GamepadInput.X
# carb.input.GamepadInput.Y
# carb.input.GamepadInput.A
# carb.input.GamepadInput.B
# carb.input.GamepadInput.MENU1 (Back)
# carb.input.GamepadInput.MENU2 (Start)
# gamepad_input : stick (0.0 - 1.0).
# carb.input.GamepadInput.LEFT_STICK_DOWN
# carb.input.GamepadInput.LEFT_STICK_UP
# carb.input.GamepadInput.LEFT_STICK_LEFT
# carb.input.GamepadInput.LEFT_STICK_RIGHT
# carb.input.GamepadInput.RIGHT_STICK_DOWN
# carb.input.GamepadInput.RIGHT_STICK_UP
# carb.input.GamepadInput.RIGHT_STICK_LEFT
# carb.input.GamepadInput.RIGHT_STICK_RIGHT
# gamepad_input : stick push (0.0 or 1.0).
# carb.input.GamepadInput.LEFT_STICK
# carb.input.GamepadInput.RIGHT_STICK
# gamepad_input : trigger (0.0 - 1.0).
# carb.input.GamepadInput.LEFT_TRIGGER
# carb.input.GamepadInput.RIGHT_TRIGGER
# gamepad_input : shoulder (0.0 or 1.0).
# carb.input.GamepadInput.LEFT_SHOULDER
# carb.input.GamepadInput.RIGHT_SHOULDER
if gamepad_descD == None:
return
# Move the selected Prim.
mV = Gf.Vec3f(0, 0, 0)
scaleV = 2.0
minV = 0.3
if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_DOWN] > minV:
mV[2] += scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_DOWN]
if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_UP] > minV:
mV[2] -= scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_UP]
if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_LEFT] > minV:
mV[0] -= scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_LEFT]
if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_RIGHT] > minV:
mV[0] += scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_RIGHT]
moveSelectedPrim(mV)
def startup (self):
self._gamepads = []
self._input = carb.input.acquire_input_interface()
self._input_provider = carb.input.acquire_input_provider()
self._gamepad_connection_subs = self._input.subscribe_to_gamepad_connection_events(self._gamepad_connection_event)
# Creating a dict of processed GamepadInput enumeration for convenience
def filter_gamepad_input_attribs(attr):
return not callable(getattr(carb.input.GamepadInput, attr)) and not attr.startswith("__") and attr != "name" and attr != "COUNT"
self._gamepad_inputs = dict((getattr(carb.input.GamepadInput, attr), attr) for attr in dir(carb.input.GamepadInput) if filter_gamepad_input_attribs(attr))
self._app = omni.kit.app.get_app()
self._pre_update_sub = self._app.get_pre_update_event_stream().create_subscription_to_pop(
self._update_gamepads_data, name="GamePad test"
)
def shutdown (self):
self._input.unsubscribe_to_gamepad_connection_events(self._gamepad_connection_subs)
self._gamepad_connection_subs = None
self._gamepad_inputs = None
self._gamepads = None
self._app = None
self._pre_update_sub = None
self._input_provider = None
self._input = None
gamePadV = InputGamePad()
gamePadV.startup()
# stop.
#gamePadV.shutdown()
| 8,017 | Python | 38.112195 | 162 | 0.583385 |
ft-lab/omniverse_sample_scripts/Operation/GamePad/readme.md | # GamePad
GamePadでの操作を取得します。
XBOX Controllerの場合は以下のような入力になります。

|入力|値|
|---|---|
|carb.input.GamepadInput.LEFT_SHOULDER|0 or 1|
|carb.input.GamepadInput.RIGHT_SHOULDER|0 or 1|
|carb.input.GamepadInput.LEFT_TRIGGER|0 - 1|
|carb.input.GamepadInput.RIGHT_TRIGGER|0 - 1|
|carb.input.GamepadInput.DPAD_DOWN<br>carb.input.GamepadInput.DPAD_UP<br>carb.input.GamepadInput.DPAD_LEFT<br>carb.input.GamepadInput.DPAD_RIGHT|0 or 1|
|carb.input.GamepadInput.X|0 or 1|
|carb.input.GamepadInput.Y|0 or 1|
|carb.input.GamepadInput.A|0 or 1|
|carb.input.GamepadInput.B|0 or 1|
|carb.input.GamepadInput.MENU1|0 or 1|
|carb.input.GamepadInput.MENU2|0 or 1|
|carb.input.GamepadInput.LEFT_STICK_DOWN<br>carb.input.GamepadInput.LEFT_STICK_UP<br>carb.input.GamepadInput.LEFT_STICK_LEFT<br>carb.input.GamepadInput.LEFT_STICK_RIGHT|0 - 1|
|carb.input.GamepadInput.RIGHT_STICK_DOWN<br>carb.input.GamepadInput.RIGHT_STICK_UP<br>carb.input.GamepadInput.RIGHT_STICK_LEFT<br>carb.input.GamepadInput.RIGHT_STICK_RIGHT|0 - 1|
|carb.input.GamepadInput.LEFT_STICK |0 or 1|
|carb.input.GamepadInput.RIGHT_STICK |0 or 1|
## サンプル
|ファイル|説明|
|---|---|
|[GamePad.py](./GamePad.py)|GamePad情報を取得(特定のボタンのみ)|
|[GamePad_moveSelectPrim.py](./GamePad_moveSelectPrim.py)|GamePadのLeftStick操作で選択形状を移動|
| 1,345 | Markdown | 42.419353 | 179 | 0.751673 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/SelectNone.py | import omni.kit
omni.kit.commands.execute("SelectNone")
| 57 | Python | 13.499997 | 39 | 0.789474 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/GetCommandsList.py | import omni.kit
# Get commands list (dict).
listA = omni.kit.commands.get_commands()
keys = listA.keys()
print(str(keys))
| 124 | Python | 14.624998 | 40 | 0.709677 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/readme.md | # Execute
omni.kit.commandsを使用して、Omniverseのコマンドを実行します。
## サンプル
|ファイル|説明|
|---|---|
|[GetCommandsList.py](./GetCommandsList.py)|コマンドのリストを一覧。|
|[SelectNone.py](./SelectNone.py)|Stageウィンドウでの選択を解除|
|[CopyPrim.py](./CopyPrim.py)|選択されたPrimの複製を作成|
|[DeletePrims.py](./DeletePrims.py)|選択されたPrimを削除|
|[MovePrim.py](./MovePrim.py)|選択されたPrimのパスを変更。<br>/World/Xform 内に選択されたPrimを移動する。|
|[RenamePrim.py](./RenamePrim.py)|選択されたPrimの名前を変更。<br>"MovePrim"でPrimの名前変更できる。|
| 500 | Markdown | 32.399998 | 86 | 0.682 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/CopyPrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
newPrimPathList = []
for path in selectedPaths:
# Duplicate Prim from specified path.
omni.kit.commands.execute("CopyPrim", path_from=path)
# Stores the path of the newly duplicated Prim.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
if len(paths) >= 1:
newPrimPathList.append(paths[0])
# Show the path of the newly duplicated Prim.
print(newPrimPathList)
| 698 | Python | 28.124999 | 63 | 0.719198 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/DeletePrims.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
# Delete prims.
omni.kit.commands.execute("DeletePrims", paths=selectedPaths)
| 337 | Python | 24.999998 | 63 | 0.750742 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/RenamePrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
for path in selectedPaths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
continue
newPathName = path + "_rename"
# Rename Prim name.
omni.kit.commands.execute("MovePrim", path_from=path, path_to=newPathName)
break
| 538 | Python | 23.499999 | 78 | 0.689591 |
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/MovePrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Create empty node(Xform).
defaultPrimPath = defaultPrim.GetPath().pathString
xformPath = defaultPrimPath + '/Xform'
UsdGeom.Xform.Define(stage, xformPath)
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
for path in selectedPaths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
continue
pathTo = xformPath + "/" + str(prim.GetName())
# Change Prim's path.
# path_from : Path of the original Prim.
# path_to : Path to move to.
omni.kit.commands.execute("MovePrim", path_from=path, path_to=pathTo)
| 839 | Python | 24.454545 | 73 | 0.697259 |
ft-lab/omniverse_sample_scripts/Operation/UNDO/CreateSphereUndo.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit.commands
import omni.kit.undo
# Get stage.
stage = omni.usd.get_context().get_stage()
# Process to create a sphere.
class MyCreateSphere (omni.kit.commands.Command):
_path = ""
def __init__ (self, path : str):
self._path = path
def do (self):
sphereGeom = UsdGeom.Sphere.Define(stage, self._path)
# 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))
def undo (self):
stage.RemovePrim(self._path)
# Create sphere.
pathName = '/World/sphere'
# Register a Class and run it.
omni.kit.commands.register(MyCreateSphere)
omni.kit.commands.execute("MyCreateSphere", path=pathName)
# UNDO.
omni.kit.undo.undo()
# REDO.
omni.kit.undo.redo()
| 952 | Python | 21.690476 | 72 | 0.656513 |
ft-lab/omniverse_sample_scripts/Operation/UNDO/readme.md | # UNDO
UNDO処理。
特にSkeleton情報を変更する場合、UNDOに対応しないと正常に動作しないケースがありました。
Omniverse Kitのドキュメントの"Bundled Extensions/omni.kit.commands"が参考になります。
|ファイル|説明|
|---|---|
|[simpleClassUNDO.py](./simpleClassUNDO.py)|classを使用してUNDO対応。|
|[CreateSphereUndo.py](./CreateSphereUndo.py)|球を生成する処理でUNDO対応して位置|
| 322 | Markdown | 23.846152 | 73 | 0.708075 |
ft-lab/omniverse_sample_scripts/Operation/UNDO/simpleClassUndo.py | # From "Bundled Extensions/omni.kit.commands" in Omniverse Kit documentation.
import omni.kit.commands
import omni.kit.undo
# Class for UNDO processing.
class MyOrange (omni.kit.commands.Command):
def __init__ (self, bar: list):
self._bar = bar
def do (self):
self._bar.append('orange')
def undo (self):
del self._bar[-1]
# Register a Class and run it.
omni.kit.commands.register(MyOrange)
my_list = []
omni.kit.commands.execute("MyOrange", bar=my_list)
print(my_list)
# UNDO.
omni.kit.undo.undo()
print(my_list)
# REDO.
omni.kit.undo.redo()
print(my_list)
| 601 | Python | 18.419354 | 77 | 0.673877 |
ft-lab/omniverse_sample_scripts/Operation/Selection/GetSelection.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
print(path)
| 218 | Python | 20.899998 | 63 | 0.711009 |
ft-lab/omniverse_sample_scripts/Operation/Selection/readme.md | # Selection
StageウィンドウでのPrimの選択を取得。
|ファイル|説明|
|---|---|
|[GetSelection.py](./GetSelection.py)|Primの選択を取得|
|[IsSelected.py](./IsSelected.py)|指定されたパスのPrimが選択されているかどうか|
|[Select.py](./Select.py)|指定されたパスのPrimを選択|
|[EventSelection.py](./EventSelection.py)|選択変更イベントを取得し、選択されたPrim名を表示|
|[EventSelection_showFacesCount.py](./EventSelection_showFacesCount.py)|選択されたPrim名、子要素も含めたMeshの面数をビューポートに表示<br>
| 510 | Markdown | 38.307689 | 191 | 0.735294 |
ft-lab/omniverse_sample_scripts/Operation/Selection/EventSelection.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get context.
context = omni.usd.get_context()
# Get stage.
stage = context.get_stage()
# ---------------------------------------------.
# Selected event.
# ---------------------------------------------.
def onStageEvent(evt):
if evt.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
# Get selection paths.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
print('Selected [ ' + prim.GetName() + ' ]')
# ------------------------------------------------.
# Register for stage events.
# Specify "subs=None" to end the event.
subs = context.get_stage_event_stream().create_subscription_to_pop(onStageEvent, name="sampleStageEvent")
| 913 | Python | 32.851851 | 105 | 0.542169 |
ft-lab/omniverse_sample_scripts/Operation/Selection/IsSelected.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get selection.
selection = omni.usd.get_context().get_selection()
pathStr = '/World'
selectedF = selection.is_prim_path_selected(pathStr)
if selectedF:
print('[' + pathStr + ' ] Selected')
else:
print('[' + pathStr + ' ] Not selected')
| 313 | Python | 23.153844 | 63 | 0.674121 |
ft-lab/omniverse_sample_scripts/Operation/Selection/EventSelection_showFacesCount.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
import omni.kit.app
# Get context.
context = omni.usd.get_context()
# Get stage.
stage = context.get_stage()
# Get main window viewport.
window = omni.ui.Window('Viewport')
# ---------------------------------------------.
# Get the number of faces in the mesh.
# ---------------------------------------------.
def GetFacesCount (prim):
if prim.IsValid() == None:
return 0
typeName = prim.GetTypeName()
allCou = 0
if typeName == 'Mesh':
m = UsdGeom.Mesh(prim)
# If it is displayed.
if m.ComputeVisibility() == 'inherited':
# Get the number of faces of Mesh.
allCou += len(m.GetFaceVertexCountsAttr().Get())
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
allCou += GetFacesCount(cPrim)
return allCou
# ---------------------------------------------.
# Update Viewport UI.
# Show the number of faces of the selected shape in the Viewport.
# ---------------------------------------------.
def UpdateViewportUI(paths):
if len(paths) == 0:
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=0):
omni.ui.Spacer(width=0, height=8)
return
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=50):
f = omni.ui.Label("--- Selection Shapes ---")
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 32})
with omni.ui.Placer(offset_x=20, offset_y=0):
omni.ui.Spacer(width=0, height=8)
# Show selection shape name.
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == True:
facesCou = GetFacesCount(prim)
with omni.ui.Placer(offset_x=28, offset_y=0):
f2 = omni.ui.Label('[ ' + prim.GetName() + ' ] faces ' + str(facesCou))
f2.visible = True
f2.set_style({"color": 0xff00ff00, "font_size": 32})
# ---------------------------------------------.
# Selected event.
# ---------------------------------------------.
def onStageEvent(evt):
if evt.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
# Get selection paths.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Show selected shapes info.
UpdateViewportUI(paths)
# ------------------------------------------------.
# Register for stage events.
# Specify "subs=None" to end the event.
subs = context.get_stage_event_stream().create_subscription_to_pop(onStageEvent, name="sampleStageEvent")
| 2,919 | Python | 32.563218 | 105 | 0.517643 |
ft-lab/omniverse_sample_scripts/Operation/Selection/Select.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get selection.
selection = omni.usd.get_context().get_selection()
# Select one.
selection.set_selected_prim_paths(['/World'], True)
# Multiple selection.
selection.set_selected_prim_paths(['/World', '/World/defaultLight'], True)
# Deselection.
selection.clear_selected_prim_paths()
| 352 | Python | 24.214284 | 74 | 0.735795 |
ft-lab/omniverse_sample_scripts/Operation/Keyboard/readme.md | # Keyboard
キーボードの入力を取得します。
## サンプル
|ファイル|説明|
|---|---|
|[InputKeyboard.py](./InputKeyboard.py)|キーボードの入力を取得。|
|[InputKeyboard_ShowViewport.py](./InputKeyboard_ShowViewport.py)|キーボードの入力を取得し、キー入力をViewportの左上に表示。|
| 240 | Markdown | 19.083332 | 105 | 0.658333 |
ft-lab/omniverse_sample_scripts/Operation/Keyboard/InputKeyboard.py | from pxr import Usd, UsdGeom, UsdSkel, UsdShade, Sdf, Gf, Tf
import carb
import carb.input
import omni.kit.app
import omni.ext
# ------------------------------------------.
# Input with Keyboard.
# ------------------------------------------.
class InputKeyboard:
_keyboard = None
_input = None
_keyboard_subs = None
def __init__(self):
pass
# Keyboard event.
def _keyboard_event (self, event : carb.input.KeyboardEvent):
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
print("KEY_PRESS : " + str(event.input))
if event.type == carb.input.KeyboardEventType.KEY_RELEASE:
print("KEY_RELEASE : " + str(event.input))
return True
def startup (self):
# Assign keyboard event.
appwindow = omni.appwindow.get_default_app_window()
self._keyboard = appwindow.get_keyboard()
self._input = carb.input.acquire_input_interface()
self._keyboard_subs = self._input.subscribe_to_keyboard_events(self._keyboard, self._keyboard_event)
def shutdown (self):
# Release keyboard event.
if self._input != None:
self._input.unsubscribe_to_keyboard_events(self._keyboard, self._keyboard_subs)
self._keyboard_subs = None
self._keyboard = None
self._input = None
# -----------------------------------------.
keyboardV = InputKeyboard()
keyboardV.startup()
# stop.
#keyboardV.shutdown()
| 1,467 | Python | 28.359999 | 108 | 0.57805 |
ft-lab/omniverse_sample_scripts/Operation/Keyboard/InputKeyboard_ShowViewport.py | from pxr import Usd, UsdGeom, UsdSkel, UsdShade, Sdf, Gf, Tf
import carb
import carb.input
import carb.events
import omni.kit.app
import omni.ext
# ------------------------------------------.
# Input with Keyboard.
# ------------------------------------------.
class InputKeyboard:
_keyboard = None
_input = None
_keyboard_subs = None
_update_subs = None
_window = None
_keyboard_input_value = None
def __init__(self):
pass
# Keyboard event.
def _keyboard_event (self, event):
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
self._keyboard_input_value = event.input
print("KEY_PRESS : " + str(event.input))
if event.type == carb.input.KeyboardEventType.KEY_RELEASE:
print("KEY_RELEASE : " + str(event.input))
return True
# UI Update event.
def _on_update (self, e: carb.events.IEvent):
with self._window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("Input : " + str(self._keyboard_input_value))
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 20})
def startup (self):
# Assign keyboard event.
appwindow = omni.appwindow.get_default_app_window()
self._keyboard = appwindow.get_keyboard()
self._input = carb.input.acquire_input_interface()
self._keyboard_subs = self._input.subscribe_to_keyboard_events(self._keyboard, self._keyboard_event)
# Get main window viewport.
self._window = omni.ui.Window('Viewport')
# Assing update event.
self._update_subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, name="update")
def shutdown (self):
# Release update event.
if self._update_subs != None:
self._update_subs.unsubscribe()
# Release keyboard event.
if self._input != None:
self._input.unsubscribe_to_keyboard_events(self._keyboard, self._keyboard_subs)
self._keyboard_subs = None
self._keyboard = None
self._input = None
self._update_subs = None
# -----------------------------------------.
keyboardV = InputKeyboard()
keyboardV.startup()
# stop.
#keyboardV.shutdown()
| 2,432 | Python | 31.013157 | 135 | 0.567845 |
ft-lab/omniverse_sample_scripts/Math/CalcMatrix.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Identity matrix.
m = Gf.Matrix4f()
print(m)
# Initialize with rotation and translate.
rotV = Gf.Rotation(Gf.Vec3d(1, 0, 0), 90.0)
transV = Gf.Vec3f(10, 5, 2.3)
m1 = Gf.Matrix4f(rotV, transV)
print(m1)
# Get data.
for i in range(4):
print(f"{m1[i,0]} , {m1[i,1]} , {m1[i,2]} , {m1[i,3]}")
# Set identity.
m1.SetIdentity()
print(m1)
# Matrix multiplication.
rot1 = Gf.Rotation(Gf.Vec3d(1, 0, 0), 90.0)
m2 = Gf.Matrix4f(rot1, Gf.Vec3f())
rot2 = Gf.Rotation(Gf.Vec3d(0, 1, 0), 30.0)
m3 = Gf.Matrix4f(rot2, Gf.Vec3f())
m4 = m2 * m3 # Gf.Matrix4f * Gf.Matrix4f
print(m4)
rot3 = rot1 * rot2 # Gf.Rotation * Gf.Rotation
print(Gf.Matrix4f(rot3, Gf.Vec3f()))
# Inverse matrix.
m4Inv = m4.GetInverse()
print(m4Inv)
# vector3 * matrix4.
rotV = Gf.Rotation(Gf.Vec3d(1, 0, 0), 90.0)
transV = Gf.Vec3f(10, 5, 2.3)
m5 = Gf.Matrix4f(rotV, transV)
v1 = Gf.Vec3f(1.2, 1.0, 2.5)
v2 = m5.Transform(v1)
print(f"{v2}")
# vector3 * matrix4 (Ignore position).
v1 = Gf.Vec3f(1.2, 1.0, 2.5)
v2 = m5.TransformDir(v1)
print(f"{v2}")
| 1,093 | Python | 20.88 | 63 | 0.638609 |
ft-lab/omniverse_sample_scripts/Math/DecomposeTransform2.py | from pxr import Usd, UsdGeom, UsdSkel, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Dump matrix.
def DumpMatrix(m : Gf.Matrix4d):
print("---------------------")
for i in range(4):
print(f"{mm[i,0]} {mm[i,1]} {mm[i,2]} {mm[i,3]}")
print("")
# Create Matrix4.
translate = Gf.Vec3d(10.5, 2.8, 6.0)
rotation = Gf.Rotation(Gf.Vec3d(0, 1, 0), 20) * Gf.Rotation(Gf.Vec3d(0, 0, 1), 45)
scale = Gf.Vec3d(2.0, 0.5, 1.0)
mm = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d(rotation, Gf.Vec3d(0)) * Gf.Matrix4d().SetTranslate(translate)
DumpMatrix(mm)
# Decompose matrix.
mm2 = mm.RemoveScaleShear()
rTrans = mm2.ExtractTranslation()
rRot = mm2.ExtractRotation()
mm3 = mm * mm2.GetInverse()
rScale = Gf.Vec3d(mm3[0][0], mm3[1][1], mm3[2][2])
rAxisX = Gf.Vec3d(1, 0, 0)
rAxisY = Gf.Vec3d(0, 1, 0)
rAxisZ = Gf.Vec3d(0, 0, 1)
rRotE = rRot.Decompose(rAxisZ, rAxisY, rAxisX)
rRotE = Gf.Vec3d(rRotE[2], rRotE[1], rRotE[0])
print(f"Trans : {rTrans}")
print(f"Rot : {rRotE}")
print(f"Scale : {rScale}")
| 1,007 | Python | 27.799999 | 111 | 0.621648 |
ft-lab/omniverse_sample_scripts/Math/CalcDotCrossProduct.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
v1 = Gf.Vec3f(1.0, 2.0, -5.0)
v2 = Gf.Vec3f(2.5, 14.0, 12.0)
# Dot : Inner product.
print(f"{v1} x {v2} = {v1 * v2}")
print(f"{v1} x {v2} = {Gf.Dot(v1, v2)}")
# Cross : Outer product.
vx = v1[1] * v2[2] - v1[2] * v2[1]
vy = v1[2] * v2[0] - v1[0] * v2[2]
vz = v1[0] * v2[1] - v1[1] * v2[0]
print(f"Cross product : ( {vx}, {vy}, {vz} )")
v1_2 = Gf.Vec4f(v1[0], v1[1], v1[2],1.0)
v2_2 = Gf.Vec4f(v2[0], v2[1], v2[2],1.0)
v3_2 = Gf.HomogeneousCross(v1_2, v2_2)
print(f"Cross product : {v3_2}")
| 558 | Python | 26.949999 | 63 | 0.543011 |
ft-lab/omniverse_sample_scripts/Math/readme.md | # Math
ベクトルや行列計算関連。
USDのベクトル/行列計算は、"Gf"にまとまっているためそれを使用します。
numpyを経由しなくても計算できます。
ベクトルはfloat型のGf.Vec3f ( https://graphics.pixar.com/usd/release/api/class_gf_vec3f.html )、
double型のGf.Vec3d ( https://graphics.pixar.com/usd/release/api/class_gf_vec3d.html )が使用されます。
行列はfloat型のGf.Matrix4f ( https://graphics.pixar.com/usd/release/api/class_gf_matrix4f.html )、
double型のGf.Matrix4d ( https://graphics.pixar.com/usd/release/api/class_gf_matrix4d.html )が使用されます。
|ファイル|説明|
|---|---|
|[CalcDotCrossProduct.py](./CalcDotCrossProduct.py)|ベクトルの内積/外積計算|
|[CalcMatrix.py](./CalcMatrix.py)|4x4行列の計算。行列とベクトルの乗算|
|[CalcVector3.py](./CalcVector3.py)|Vector3の計算.|
|[DecomposeTransform.py](./DecomposeTransform.py)|行列を移動(translate), 回転(rotation), スケール(scale)に変換。UsdSkelを使用。|
|[DecomposeTransform2.py](./DecomposeTransform2.py)|行列を移動(translate), 回転(rotation), スケール(scale)に変換|
|[GetVector3Length.py](./GetVector3Length.py)|Vector3の長さを計算|
|[VectorToRotationAngle.py](./VectorToRotationAngle.py)|指定のベクトルをXYZ軸回転の角度(度数)に変換|
|[NormalizeVector3.py](./NormalizeVector3.py)|Vector3の正規化|
|[QuatToRotation.py](./QuatToRotation.py)|クォータニオンと回転角度(度数)の変換|
|[TransRotationFrom2Vec.py](./TransRotationFrom2Vec.py)|ベクトルAをベクトルBに変換する回転を計算。|
|[ConvRGB2SRGB.py](./ConvRGB2SRGB.py)|色のsRGBとRGBの相互変換。|
| 1,350 | Markdown | 44.033332 | 114 | 0.728148 |
ft-lab/omniverse_sample_scripts/Math/TransRotationFrom2Vec.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
# No need to normalize.
dirA = Gf.Vec3f(1.0, 0.0, 0.0).GetNormalized()
dirB = Gf.Vec3f(-0.2, 12.0, 15.0).GetNormalized()
print(f"dirA : {dirA}")
print(f"dirB : {dirB}")
# Calculate the rotation to transform dirA to dirB.
rot = Gf.Rotation().SetRotateInto(Gf.Vec3d(dirA), Gf.Vec3d(dirB))
# Check that rot is correct.
# v will have the same result as dirB.
m = Gf.Matrix4f(rot, Gf.Vec3f(0, 0, 0))
v = m.Transform(dirA)
print(f"dirA * m = {v}")
| 498 | Python | 26.722221 | 65 | 0.670683 |
ft-lab/omniverse_sample_scripts/Math/NormalizeVector3.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
v1 = Gf.Vec3f(1.0, 2.0, -5.0)
v1N = v1.GetNormalized()
print(f"{v1} ==> {v1N}")
| 145 | Python | 23.333329 | 63 | 0.634483 |
ft-lab/omniverse_sample_scripts/Math/QuatToRotation.py | from pxr import Usd, UsdGeom, UsdSkel, UsdPhysics, UsdShade, Sdf, Gf, Tf
rotation = Gf.Quatf(0.7071, 0.7071, 0, 0)
print(f"quat : {rotation}")
# Convert from quaternion to Euler's rotation angles(degree).
# Rotate XYZ.
rot = Gf.Rotation(rotation)
rV = rot.Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0))
rV = Gf.Vec3d(rV[2], rV[1], rV[0])
print(f"Euler's rotation angles : {rV}")
# RotationXYZ to quaternion.
rotX = Gf.Rotation(Gf.Vec3d(1, 0, 0), 90.0)
rotY = Gf.Rotation(Gf.Vec3d(0, 1, 0), 30.0)
rotZ = Gf.Rotation(Gf.Vec3d(0, 0, 1), -10.0)
rotXYZ = rotX * rotY * rotZ
q = rotXYZ.GetQuat()
print("quaternion : " + str(q))
# Quaternion to RotateXYZ.
rV = rotXYZ.Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0))
rV = Gf.Vec3d(rV[2], rV[1], rV[0])
print(" Euler's rotation angles : " + str(rV))
| 834 | Python | 32.399999 | 78 | 0.647482 |
ft-lab/omniverse_sample_scripts/Math/GetVector3Length.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
v1 = Gf.Vec3f(1.0, 2.0, -5.0)
v2 = Gf.Vec3f(2.5, 14.0, 12.0)
print(f"{v1} : Length = {v1.GetLength()}")
print(f"{v2} : Length = {v2.GetLength()}")
| 212 | Python | 29.428567 | 63 | 0.613208 |
ft-lab/omniverse_sample_scripts/Math/VectorToRotationAngle.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
dirV = Gf.Vec3f(20.0, 5.0, -25.0)
yUp = Gf.Vec3f(0, 1, 0)
m = Gf.Matrix4f().SetLookAt(Gf.Vec3f(0, 0, 0), dirV.GetNormalized(), yUp)
# Rotate XYZ.
rV = m.ExtractRotation().Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0))
rV = Gf.Vec3d(rV[2], rV[1], rV[0])
print(f"rotateXYZ(Euler) : {rV}")
| 364 | Python | 25.071427 | 91 | 0.620879 |
ft-lab/omniverse_sample_scripts/Math/CalcVector3.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# float vector.
print("\nfloat vector ----\n")
v1 = Gf.Vec3f(1.0, 2.0, -5.0)
v2 = Gf.Vec3f(2.5, 14.0, 12.0)
v = v1 + v2
print(f"{v1} + {v2} = {v}")
v = v1 / 2
print(f"{v1} / 2 = {v}")
print(f"v.x = {v[0]} type = {type(v[0])}")
print(f"v.y = {v[1]} type = {type(v[1])}")
print(f"v.z = {v[2]} type = {type(v[2])}")
# double vector.
# It seems to be internally converted to Gf.Vec3f.
print("\ndouble vector ----\n")
v1d = Gf.Vec3d(1.0, 2.0, -5.0)
v2d = Gf.Vec3d(2.5, 14.0, 12.0)
v = v1d + v2d
print("v.x = " + str(v1d[0]) + " type = " + str(type(v1d[0])))
v = v1d / 2
print(f"{v1d} / 2 = {v}")
print(f"v.x = {v[0]} type = {type(v[0])}")
print(f"v.y = {v[1]} type = {type(v[1])}")
print(f"v.z = {v[2]} type = {type(v[2])}")
| 792 | Python | 23.030302 | 63 | 0.52399 |
ft-lab/omniverse_sample_scripts/Math/ConvRGB2SRGB.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import math
def rgb_to_srgb (v : float, quantum_max : float = 1.0):
if v <= 0.0031308:
return (v * 12.92)
v = v / quantum_max
v = math.pow(v, 1.0 / 2.4) * 1.055 - 0.055
return (v * quantum_max)
def srgb_to_rgb (v : float, quantum_max : float = 1.0):
v = v / quantum_max
if v <= 0.04045:
return (v / 12.92)
v = math.pow((v + 0.055) / 1.055, 2.4)
return (v * quantum_max)
# Conv RGB to sRGB.
def conv_RGB_to_sRGB (col : Gf.Vec3f):
retCol = Gf.Vec3f(col)
if retCol[0] > 0.0 and retCol[0] < 1.0:
retCol[0] = rgb_to_srgb(retCol[0])
if retCol[1] > 0.0 and retCol[1] < 1.0:
retCol[1] = rgb_to_srgb(retCol[1])
if retCol[2] > 0.0 and retCol[2] < 1.0:
retCol[2] = rgb_to_srgb(retCol[2])
return retCol
# Conv sRGB to RGB (Linear).
def conv_sRGB_to_RGB (col : Gf.Vec3f):
retCol = Gf.Vec3f(col)
if retCol[0] > 0.0 and retCol[0] < 1.0:
retCol[0] = srgb_to_rgb(retCol[0])
if retCol[1] > 0.0 and retCol[1] < 1.0:
retCol[1] = srgb_to_rgb(retCol[1])
if retCol[2] > 0.0 and retCol[2] < 1.0:
retCol[2] = srgb_to_rgb(retCol[2])
return retCol
# ---------------------------------------.
# Original color (sRGB).
col = Gf.Vec3f(0.5, 0.4, 0.7)
# sRGB to RGB (sRGB to linear).
col_linear = conv_sRGB_to_RGB(col)
# RGB to sRGB (linear to sRGB).
col2 = conv_RGB_to_sRGB(col_linear)
print(f"col : {col}")
print(f"col_linear : {col_linear}")
print(f"col2 : {col2}")
| 1,557 | Python | 24.129032 | 63 | 0.552344 |
ft-lab/omniverse_sample_scripts/Math/DecomposeTransform.py | from pxr import Usd, UsdGeom, UsdSkel, UsdPhysics, UsdShade, Sdf, Gf, Tf
translate = Gf.Vec3f(10.5, 2.8, 6.0)
rotation = Gf.Quatf(0.7071, 0.7071, 0, 0) # Gf.Rotation(Gf.Vec3d(1, 0, 0), 90)
scale = Gf.Vec3f(2.0, 0.5, 1.0)
print(f"translate : {translate}")
print(f"rotation : {rotation}")
print(f"scale : {scale}")
# Make transform.
transM = UsdSkel.MakeTransform(translate, rotation, Gf.Vec3h(scale))
print(f"transform : {transM}")
# Decompose transform.
translate2, rotation2, scale2 = UsdSkel.DecomposeTransform(transM)
print(f"==> translate : {translate2}")
print(f"==> rotation : {rotation2}")
print(f"==> scale : {scale2}")
| 638 | Python | 30.949998 | 80 | 0.681818 |
ft-lab/omniverse_sample_scripts/PLATEAU/divide_GeoTiff_images.py | # ---------------------------------------------------------------------.
# PLATEAU GeoTIFF images split 10x10 and saved as jpeg.
# ---------------------------------------------------------------------.
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.kit.commands
import glob
import os
from PIL import Image
# Allows handling of large size images.
Image.MAX_IMAGE_PIXELS = 1000000000
# --------------------------------------.
# Input Parameters.
# --------------------------------------.
# Source path (Root path with PLATEAU GeoTIFF).
in_plateau_obj_path = "K:\\Modeling\\PLATEAU\\Tokyo_23ku\\13100_tokyo23-ku_2020_ortho_2_op"
# Folder to save the split images.
in_save_folder_path = "K:\\Modeling\\PLATEAU\\Tokyo_23ku\\13100_tokyo23-ku_2020_ortho_2_op\\divide_images"
# --------------------------------------.
# Load image and divide (10 x 10).
# --------------------------------------.
def load_divideImage (filePath : str, savePath : str):
fName = os.path.basename(filePath)
# Remove extension.
fName2 = os.path.splitext(fName)[0]
try:
srcImage = Image.open(filePath)
# Get image size.
wid = srcImage.size[0]
hei = srcImage.size[1]
# 10x10 division.
wid_10 = (float)(wid) / 10.0
hei_10 = (float)(hei) / 10.0
index = 0
fy1 = hei_10 * 9.0
for y in range(10):
fx1 = 0.0
for x in range(10):
img = srcImage.crop(((int)(fx1 + 0.5), (int)(fy1 + 0.5), (int)(fx1 + wid_10 + 0.5), (int)(fy1 + hei_10 + 0.5)))
# Save file name ('533925' + '02' ==> '53392502.jpg').
dstName = fName2 + str(index).zfill(2) + ".jpg"
dstPath = savePath + "/" + dstName
img.save(dstPath)
index += 1
fx1 += wid_10
fy1 -= hei_10
except Exception as e:
pass
# --------------------------------------.
# Divide GeoTiff images.
# --------------------------------------.
def divide_geoTiff (savePath : str):
if os.path.exists(in_plateau_obj_path) == False:
return
# Create a save folder.
if os.path.exists(in_save_folder_path) == False:
os.makedirs(in_save_folder_path)
# Divide and save images.
for path in glob.glob(in_plateau_obj_path + "/images/*.tif"):
load_divideImage(path, savePath)
fName = os.path.basename(path)
print("Divide [" + fName + "]")
# --------------------------------------.
# --------------------------------------.
divide_geoTiff(in_save_folder_path)
print("Save success !!")
| 2,648 | Python | 29.102272 | 127 | 0.481495 |
ft-lab/omniverse_sample_scripts/PLATEAU/calcDistanceWithLatLong.py | # ------------------------------------------------------------------.
# 2点の緯度経度を指定したときの距離を計算.
# 参考 : https://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/bl2stf.html
# ------------------------------------------------------------------.
import math
# --------------------------------------.
# Input Parameters.
# --------------------------------------.
# Latitude and longitude of the starting point.
in_lat1 = 35.680908
in_longi1 = 139.767348
# Latitude and longitude of the end point.
in_lat2 = 35.666436
in_longi2 = 139.758191
# -----------------------------------------.
# 前処理.
# -----------------------------------------.
# 赤道半径 (km).
R = 6378.137
# 極半径 (km).
R2 = 6356.752
# 扁平率 (ref : https://ja.wikipedia.org/wiki/%E5%9C%B0%E7%90%83).
# 「f = 1.0 - (R2 / R)」の計算になる.
# 「f = 1.0 / 298.257222101」のほうがより正確.
f = 1.0 / 298.257222101
# 度数をラジアンに変換.
lat1R = in_lat1 * math.pi / 180.0
longi1R = in_longi1 * math.pi / 180.0
lat2R = in_lat2 * math.pi / 180.0
longi2R = in_longi2 * math.pi / 180.0
l = longi2R - longi1R
l2 = l
if l > math.pi:
l2 = l - math.pi * 2.0
elif l < -math.pi:
l2 = l + math.pi * 2.0
L = abs(l2)
L2 = math.pi - L
delta = 0.0
if l2 >= 0.0:
depta = lat2R - lat1R
else:
depta = lat1R - lat2R
sigma = lat1R + lat2R
if l2 >= 0.0:
u1 = math.atan((1.0 - f) * math.tan(lat1R))
else:
u1 = math.atan((1.0 - f) * math.tan(lat2R))
if l2 >= 0.0:
u2 = math.atan((1.0 - f) * math.tan(lat2R))
else:
u2 = math.atan((1.0 - f) * math.tan(lat1R))
sigma2 = u1 + u2
delta2 = u2 - u1
xi = math.cos(sigma2 / 2.0)
xi2 = math.sin(sigma2 / 2.0)
eta = math.sin(delta2 / 2.0)
eta2 = math.cos(delta2 / 2.0)
x = math.sin(u1) * math.sin(u2)
y = math.cos(u1) * math.cos(u2)
c = y * math.cos(L) + x
ep = f * (2.0 - f) / math.pow(1.0 - f, 2.0)
distanceV = 0.0 # 最終的な距離が返る(km).
# -----------------------------------------.
# ゾーンの判断、θの反復計算.
# -----------------------------------------.
t0 = 0.0
if c >= 0.0:
# Zone(1).
t0 = L * (1.0 + f * y)
elif c < 0.0 and c >= -math.cos((3.0 * math.pi / 180.0) * math.cos(u1)):
# Zone(2).
t0 = L2
else:
# Zone(3).
rr = 1.0 - (1.0/4.0) * f * (1.0 + f) * math.pow(math.sin(u1), 2.0)
rr += (3.0/16.0) * f * f * math.pow(math.sin(u1), 4.0)
rr = f * math.pi * math.pow(math.cos(u1), 2.0) * rr
d1 = L2 * math.cos(u1) - rr
d2 = abs(sigma2) + rr
q = L2 / (f * math.pi)
f1 = (1.0/4.0) * f * (1.0 + 0.5 * f)
gam0 = q + f1 * q - f1 * math.pow(q, 3.0)
if sigma != 0.0:
A0 = math.atan(d1 / d2)
B0 = math.asin(rr / math.sqrt(d1 * d1 + d2 * d2))
v = A0 + B0
j = gam0 / math.cos(u1)
k = (1.0 + f1) * abs(sigma2) * (1.0 - f * y) / (f * math.pi * y)
j1 = j / (1.0 + k * (1.0 / math.cos(v)))
v2 = math.asin(j1)
v3 = math.asin((math.cos(u1) / math.cos(u2)) * j1)
t0 = math.tan((v2 + v3) / 2.0) * math.sin(abs(sigma2) / 2.0)
t0 /= math.cos(delta2 / 2.0)
t0 = 2.0 * math.atan(t0)
else:
if d1 > 0.0:
t0 = L2
elif d1 == 0.0:
gam2 = math.pow(math.sin(u1), 2.0)
n0 = math.sqrt(1.0 + ep * gam2) + 1.0
n0 = (ep * gam2) / math.pow(n0, 2.0)
A = (1.0 + n0) * (1.0 + (5.0/4.0) * n0 * n0)
distanceV = (1.0 - f) * R * A * math.pi
else:
gV = gam0
gam2 = 0.0
while True:
gam2 = 1.0 - gV * gV
D = (1.0/4.0) * f * (1.0 + f) - (3.0/16.0) * f * f * gam2
gV2 = q / (1.0 - D * gam2)
if abs(gV2 - gV) < (1e-15):
break
m = 1.0 - q * (1.0 / math.cos(u1))
n = (D * gam2) / (1.0 - D * gam2)
w = m - n + m * n
n0 = math.sqrt(1.0 + ep * gam2) + 1.0
n0 = (ep * gam2) / math.pow(n0, 2.0)
A = (1.0 + n0) * (1.0 + (5.0/4.0) * n0 * n0)
distanceV = (1.0 - f) * R * A * math.pi
if distanceV == 0.0:
tV = t0
while True:
if c >= 0.0:
g = math.pow(eta, 2.0) * math.pow(math.cos(tV / 2.0), 2.0)
g += math.pow(xi, 2.0) * math.pow(math.sin(tV / 2.0), 2.0)
g = math.sqrt(g)
h = math.pow(eta2, 2.0) * math.pow(math.cos(tV / 2.0), 2.0)
h += math.pow(xi2, 2.0) * math.pow(math.sin(tV / 2.0), 2.0)
h = math.sqrt(h)
else:
g = math.pow(eta, 2.0) * math.pow(math.sin(tV / 2.0), 2.0)
g += math.pow(xi, 2.0) * math.pow(math.cos(tV / 2.0), 2.0)
g = math.sqrt(g)
h = math.pow(eta2, 2.0) * math.pow(math.sin(tV / 2.0), 2.0)
h += math.pow(xi2, 2.0) * math.pow(math.cos(tV / 2.0), 2.0)
h = math.sqrt(h)
sig = 2.0 * math.atan(g / h)
J = 2.0 * g * h
K = h * h - g * g
gam = y * math.sin(tV) / J
gam2 = 1.0 - gam * gam
v = gam2 * K - 2.0 * x
v2 = v + x
D = (1.0 / 4.0) * f * (1.0 + f) - (3.0 / 16.0) * f * f * gam2
E = (1.0 - D * gam2) * f * gam * (sig + D * J * (v + D * K * (2.0 * v * v - gam2 * gam2)))
if c >= 0.0:
F = tV - L - E
else:
F = tV - L2 + E
G = f * gam * gam * (1.0 - 2.0 * D * gam2)
G += f * v2 * (sig / J) * (1.0 - D * gam2 + 0.5 * f * gam * gam)
G += (1.0 / 4.0) * f * f * v * v2
tV = tV - F / (1.0 - G)
# -----------------------------------------.
# 測地線長の計算.
# -----------------------------------------.
if abs(F) < (1e-15):
n0 = math.sqrt(1.0 + ep * gam2) + 1.0
n0 = (ep * gam2) / math.pow(n0, 2.0)
A = (1.0 + n0) * (1.0 + (5.0/4.0) * n0 * n0)
B = ep * (1.0 - 3.0 * n0 * n0 / 8.0)
B /= math.pow(math.sqrt(1.0 + ep * gam2) + 1.0, 2.0)
s1 = (1.0/6.0) * B * v * (1.0 - 4.0 * K * K) * (3.0 * gam2 * gam2 - 4.0 * v * v)
s2 = K * (gam2 * gam2 - 2.0 * v * v) - s1
s3 = sig - B * J * (v - (1.0/4.0) * B * s2)
distanceV = (1.0 - f) * R * A * s3
break
print("Distance : " + str(distanceV * 1000.0) + " m ( " + str(distanceV) + " km )")
| 6,201 | Python | 28.393365 | 98 | 0.393646 |
ft-lab/omniverse_sample_scripts/PLATEAU/import_PLATEAU_tokyo23ku_obj.py | # ---------------------------------------------------------------------.
# Import PLATEAU obj for Tokyo23-ku in LOD1.
# Specify the path where the local "13100_tokyo23-ku_2020_obj_3_op.zip" was extracted in in_plateau_obj_path.
#
# It also assigns textures created from GeoTIFF to dem.
# Please use "divide_GeoTiff_images.py" to convert GeoTIFF into jpeg images by dividing them into 10x10 segments in advance.
# ---------------------------------------------------------------------.
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.usd
import omni.client
import glob
import carb
import os
import asyncio
import omni.kit.asset_converter
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
defaultPrimPath = defaultPrim.GetPath().pathString
if defaultPrimPath == "":
defaultPrimPath = "/World"
# --------------------------------------.
# Input Parameters.
# --------------------------------------.
# Source path (Root path with PLATEAU obj).
in_plateau_obj_path = "K:\\Modeling\\PLATEAU\\Tokyo_23ku\\13100_tokyo23-ku_2020_obj_3_op"
# dem textures path.
# See : divide_GeoTiff_images.py
in_dem_textures_path = "K:\\Modeling\\PLATEAU\\Tokyo_23ku\\13100_tokyo23-ku_2020_ortho_2_op\\divide_images"
# output folder.
# If specified, all usd and texture files are output to the specified folder.
in_output_folder = "omniverse://localhost/PLATEAU/Tokyo_23ku"
# Convert obj to USD (Skipped if already converted to USD).
in_convert_to_usd = True
# Folder to store output USD.
# If not specified, in_plateau_obj_path + "\\output_usd"
in_output_usd_folder = ""
# Load LOD2.
in_load_lod2 = False
# Load LOD1 & LOD2.
in_load_lod1_lod2 = False
# Assign texture to dem.
in_assign_dem_texture = True
# Load bridge.
in_load_bridge = False
# Load tran.
in_load_tran = False
# Load map area.
mapIndexList = [533925, 533926, 533934, 533935, 533936, 533937, 533944, 533945, 533946, 533947, 533954, 533955, 533956, 533957]
# --------------------------------------.
# Path of PLATEAU data.
# --------------------------------------.
# topographic.
dem_path = in_plateau_obj_path + "/dem"
# building.
buliding_lod1_path = in_plateau_obj_path + "/bldg/lod1"
buliding_lod2_path = in_plateau_obj_path + "/bldg/lod2"
# bridge.
bridge_path = in_plateau_obj_path + "/brid"
# tran.
tran_path = in_plateau_obj_path + "/tran"
# ----------------------------------------------------.
# Pass the process to Omniverse.
# ----------------------------------------------------.
async def _omniverse_sync_wait():
await omni.kit.app.get_app().next_update_async()
# --------------------------------------.
# Exist path (file/folder).
# Support on Nucleus.
# --------------------------------------.
async def ocl_existPath_async (path : str):
(result, entry) = await omni.client.stat_async(path)
if result == omni.client.Result.ERROR_NOT_FOUND:
return False
return True
# ----------------------------------------------------.
# Convert file name to a string that can be used in USD Prim name.
# @param[in] fName file name.
# @return USD Prim name.
# ----------------------------------------------------.
def convFileNameToUSDPrimName (fName : str):
# Remove extension.
fName2 = os.path.splitext(fName)[0]
retName = ""
for i in range(len(fName2)):
c = fName2[i]
if retName == "":
if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or c == '_':
pass
else:
retName += '_'
if (c >= '0' and c <= '9') or (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or c == '_':
retName += c
elif c == ' ':
retName += '_'
else:
retName += str(c.encode('utf-8').hex())
return retName
# --------------------------------------.
# Set rotate.
# @param[in] prim target prim.
# @param[in] (rx, ry, rz) Rotate (angle).
# --------------------------------------.
def setRotate (prim : Usd.Prim, rx : float, ry : float, rz : float):
if prim.IsValid():
tV = prim.GetAttribute("xformOp:rotateXYZ")
if tV.IsValid():
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(rx, ry, rz))
tV = prim.GetAttribute("xformOp:orient")
if tV.IsValid():
rotX = Gf.Rotation(Gf.Vec3d(1, 0, 0), rx)
rotY = Gf.Rotation(Gf.Vec3d(0, 1, 0), ry)
rotZ = Gf.Rotation(Gf.Vec3d(0, 0, 1), rz)
rotXYZ = rotZ * rotY * rotX
if type(tV.Get()) == Gf.Quatd:
tV.Set(rotXYZ.GetQuat())
elif type(tV.Get()) == Gf.Quatf:
tV.Set(Gf.Quatf(rotXYZ.GetQuat()))
# --------------------------------------.
# Set scale.
# @param[in] prim target prim.
# @param[in] (sx, sy, sz) Scale.
# --------------------------------------.
def setScale (prim : Usd.Prim, sx : float, sy : float, sz : float):
if prim.IsValid():
tV = prim.GetAttribute("xformOp:scale")
if tV.IsValid():
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(sx, sy, sz))
# --------------------------------------.
# Set translate.
# @param[in] prim target prim.
# @param[in] (tx, ty, tz) translate.
# --------------------------------------.
def setTranslate (prim : Usd.Prim, tx : float, ty : float, tz : float):
if prim.IsValid():
tV = prim.GetAttribute("xformOp:translate")
if tV.IsValid():
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(tx, ty, tz))
# --------------------------------------.
# Create new Material (OmniPBR).
# @param[in] materialPrimPath Prim path of Material
# @param[in] targetPrimPath Prim path to bind Material.
# @param[in] textureFilePath File path of Diffuse texture.
# @param[in] diffuseColor Diffuse Color.
# --------------------------------------.
def createMaterialOmniPBR (materialPrimPath : str, targetPrimPath : str = "", textureFilePath : str = "", diffuseColor : Gf.Vec3f = Gf.Vec3f(0.2, 0.2, 0.2)):
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[0], diffuseColor[1], diffuseColor[2]))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.8)
# Set Specular.
shader.CreateInput('specular_level', Sdf.ValueTypeNames.Float).Set(0.0)
# Set texture.
if textureFilePath != "":
diffTexIn = shader.CreateInput('diffuse_texture', Sdf.ValueTypeNames.Asset)
diffTexIn.Set(textureFilePath)
diffTexIn.GetAttr().SetColorSpace('sRGB')
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
if targetPrimPath != "":
tPrim = stage.GetPrimAtPath(targetPrimPath)
if tPrim.IsValid():
UsdShade.MaterialBindingAPI(tPrim).Bind(material)
return materialPrimPath
# --------------------------------------.
# Create Xform (e.g. map_533946).
# --------------------------------------.
def createXfrom_mapIndex (mapIndex : int, materialPath : str):
mapPrimPath = defaultPrimPath + "/map_" + str(mapIndex)
prim = stage.GetPrimAtPath(mapPrimPath)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, mapPrimPath)
prim = stage.GetPrimAtPath(mapPrimPath)
# Bind material.
if materialPath != "":
matPrim = stage.GetPrimAtPath(materialPath)
if matPrim.IsValid():
material = UsdShade.Material(matPrim)
UsdShade.MaterialBindingAPI(prim).Bind(material)
return mapPrimPath
# --------------------------------------.
# load dem.
# @param[in] _mapIndex map index.
# @param[in] _materialPath material prim path.
# --------------------------------------.
async def loadDem (_mapIndex : int, _materialPath : str):
if (await ocl_existPath_async(dem_path)) == False:
return
mapPrimPath = createXfrom_mapIndex(_mapIndex, _materialPath)
demPrimPath = mapPrimPath + "/dem"
UsdGeom.Xform.Define(stage, demPrimPath)
# Scope specifying the Material.
materialPrimPath = ""
if in_assign_dem_texture:
materialPrimPath = defaultPrimPath + "/Looks/map_" + str(_mapIndex)
prim = stage.GetPrimAtPath(materialPrimPath)
if prim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialPrimPath)
# Must be pre-converted if using USD.
src_dem_path = ""
if in_convert_to_usd:
path = in_output_usd_folder
if path == "":
path = in_plateau_obj_path + "/output_usd"
if (await ocl_existPath_async(path)):
path += "/dem/" + str(_mapIndex) + "*"
src_dem_path = path + "/" + str(_mapIndex) + "*.usd"
if src_dem_path == "":
src_dem_path = dem_path + "/" + str(_mapIndex) + "*.obj"
for path in glob.glob(src_dem_path, recursive=True):
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
# When usd file is output on Nucleus, check the corresponding file.
if in_output_folder != "":
fName2 = str(mapIndex) + "_dem.usd"
newPath = in_output_folder + "/data"
newPath += "/dem/" + str(mapIndex) + "/" + fName2
if (await ocl_existPath_async(newPath)):
path = newPath
# Convert Prim name.
primName = convFileNameToUSDPrimName(fName)
# Create Xform.
newPath = demPrimPath + "/" + primName
UsdGeom.Xform.Define(stage, newPath)
prim = stage.GetPrimAtPath(newPath)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
prim.GetReferences().AddReference(path)
setRotate(prim, -90.0, 0.0, 0.0)
setScale(prim, 100.0, 100.0, 100.0)
# Assign texture.
if in_assign_dem_texture and mapIndex > 0:
mapFilePath = in_dem_textures_path + "/" + str(mapIndex) + ".jpg"
if in_output_folder != "":
mapFilePath2 = in_output_folder + "/data/geotiff_images"
mapFilePath2 += "/" + str(mapIndex) + ".jpg"
if (await ocl_existPath_async(mapFilePath2)):
mapFilePath = mapFilePath2
if (await ocl_existPath_async(mapFilePath)):
# Create material.
materialName = "mat_dem_" + str(mapIndex)
matPath = materialPrimPath + "/" + materialName
createMaterialOmniPBR(matPath, newPath, mapFilePath)
# Pass the process to Omniverse.
asyncio.ensure_future(_omniverse_sync_wait())
# --------------------------------------.
# load building.
# @param[in] _mapIndex map index.
# @param[in] _useLOD2 If LOD2 is available, use LOD2.
# @param[in] _materialPath material prim path.
# --------------------------------------.
async def loadBuilding (_mapIndex : int, _useLOD2 : bool, _materialPath : str):
if (await ocl_existPath_async(buliding_lod1_path)) == False:
return
mapPrimPath = createXfrom_mapIndex(_mapIndex, _materialPath)
buildingPath = mapPrimPath + "/building"
if _useLOD2:
buildingPath += "_lod2"
else:
buildingPath += "_lod1"
UsdGeom.Xform.Define(stage, buildingPath)
# Must be pre-converted if using USD.
src_bldg_path = ""
if in_convert_to_usd:
path = in_output_usd_folder
if path == "":
path = in_plateau_obj_path + "/output_usd"
if (await ocl_existPath_async(path)):
path += "/building/lod2/" + str(_mapIndex) + "*"
src_bldg_path = path + "/" + str(_mapIndex) + "*.usd"
if src_bldg_path == "":
src_bldg_path = buliding_lod2_path + "/**/" + str(_mapIndex) + "*.obj"
# If LOD2 exists.
useLOD2Dict = dict()
if _useLOD2 and (await ocl_existPath_async(buliding_lod2_path)):
# Search subdirectories.
for path in glob.glob(src_bldg_path, recursive=True):
fName = os.path.basename(path) # e.g. 53392641_bldg_6677.obj
p1 = fName.find('_')
if p1 > 0:
s = fName[0:p1]
# When usd file is output on Nucleus, check the corresponding file.
if in_output_folder != "":
mIndex = int(s)
fName2 = str(mIndex) + "_bldg.usd"
newPath = in_output_folder + "/data"
newPath += "/building/lod2/" + str(mIndex) + "/" + fName2
if (await ocl_existPath_async(newPath)):
path = newPath
useLOD2Dict[int(s)] = path
# Must be pre-converted if using USD.
src_bldg_path = ""
if in_convert_to_usd:
path = in_output_usd_folder
if path == "":
path = in_plateau_obj_path + "/output_usd"
if (await ocl_existPath_async(path)):
path += "/building/lod1/" + str(_mapIndex) + "*"
src_bldg_path = path + "/" + str(_mapIndex) + "*.usd"
if src_bldg_path == "":
src_bldg_path = buliding_lod1_path + "/**/" + str(_mapIndex) + "*.obj"
# Search subdirectories.
for path in glob.glob(src_bldg_path, recursive=True):
fName = os.path.basename(path)
chkF = False
p1 = fName.find('_')
if p1 > 0:
s = fName[0:p1]
mIndex = int(s)
# When usd file is output on Nucleus, check the corresponding file.
if (not in_load_lod1_lod2) or (in_load_lod1_lod2 and not _useLOD2):
if in_output_folder != "":
fName2 = str(mIndex) + "_bldg.usd"
newPath = in_output_folder + "/data"
newPath += "/building/lod1/" + str(mIndex) + "/" + fName2
if (await ocl_existPath_async(newPath)):
path = newPath
chkF = True
# Refer to LOD2 path.
if mIndex in useLOD2Dict:
path = useLOD2Dict[mIndex]
fName = os.path.basename(path)
chkF = True
if not chkF:
continue
# Conv Prim name.
primName = convFileNameToUSDPrimName(fName)
# Create Xform.
newPath = buildingPath + "/" + primName
UsdGeom.Xform.Define(stage, newPath)
prim = stage.GetPrimAtPath(newPath)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
prim.GetReferences().AddReference(path)
setRotate(prim, -90.0, 0.0, 0.0)
setScale(prim, 100.0, 100.0, 100.0)
# Pass the process to Omniverse.
asyncio.ensure_future(_omniverse_sync_wait())
# --------------------------------------.
# load bridge.
# @param[in] _mapIndex map index.
# @param[in] _materialPath material prim path.
# --------------------------------------.
async def loadBridge (_mapIndex : int, _materialPath : str):
if (await ocl_existPath_async(bridge_path)) == False:
return
mapPrimPath = createXfrom_mapIndex(_mapIndex, _materialPath)
bridgePath = mapPrimPath + "/bridge"
UsdGeom.Xform.Define(stage, bridgePath)
# Must be pre-converted if using USD.
src_brid_path = ""
if in_convert_to_usd:
path = in_output_usd_folder
if path == "":
path = in_plateau_obj_path + "/output_usd"
if (await ocl_existPath_async(path)):
path += "/bridge/" + str(_mapIndex) + "*"
src_brid_path = path + "/" + str(_mapIndex) + "*.usd"
if src_brid_path == "":
src_brid_path = bridge_path + "/**/" + str(_mapIndex) + "*.obj"
# Search subdirectories.
for path in glob.glob(src_brid_path, recursive=True):
fName = os.path.basename(path)
mIndex = 0
p1 = fName.find('_')
if p1 > 0:
s = fName[0:p1]
mIndex = int(s)
if mIndex == 0:
continue
# Conv Prim name.
primName = convFileNameToUSDPrimName(fName)
# When usd file is output on Nucleus, check the corresponding file.
if in_output_folder != "":
fName2 = str(mIndex) + "_brid.usd"
newPath = in_output_folder + "/data"
newPath += "/bridge/" + str(mIndex) + "/" + fName2
if (await ocl_existPath_async(newPath)):
path = newPath
# Create Xform.
newPath = bridgePath + "/" + primName
UsdGeom.Xform.Define(stage, newPath)
prim = stage.GetPrimAtPath(newPath)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
prim.GetReferences().AddReference(path)
setRotate(prim, -90.0, 0.0, 0.0)
setScale(prim, 100.0, 100.0, 100.0)
# Pass the process to Omniverse.
asyncio.ensure_future(_omniverse_sync_wait())
# --------------------------------------.
# load tran.
# @param[in] _mapIndex map index.
# @param[in] _materialPath material prim path.
# --------------------------------------.
async def loadTran (_mapIndex : int, _materialPath : str):
if (await ocl_existPath_async(tran_path)) == False:
return
mapPrimPath = createXfrom_mapIndex(_mapIndex, _materialPath)
tranPath = mapPrimPath + "/tran"
UsdGeom.Xform.Define(stage, tranPath)
# Must be pre-converted if using USD.
src_tran_path = ""
if in_convert_to_usd:
path = in_output_usd_folder
if path == "":
path = in_plateau_obj_path + "/output_usd"
if (await ocl_existPath_async(path)):
path += "/tran/" + str(_mapIndex) + "*"
src_tran_path = path + "/" + str(_mapIndex) + "*.usd"
if src_tran_path == "":
src_tran_path = tran_path + "/**/" + str(_mapIndex) + "*.obj"
# Search subdirectories.
for path in glob.glob(src_tran_path, recursive=True):
fName = os.path.basename(path)
mIndex = 0
p1 = fName.find('_')
if p1 > 0:
s = fName[0:p1]
mIndex = int(s)
if mIndex == 0:
continue
# Conv Prim name.
primName = convFileNameToUSDPrimName(fName)
# When usd file is output on Nucleus, check the corresponding file.
if in_output_folder != "":
fName2 = str(mIndex) + "_tran.usd"
newPath = in_output_folder + "/data"
newPath += "/tran/" + str(mIndex) + "/" + fName2
if (await ocl_existPath_async(newPath)):
path = newPath
# Create Xform.
newPath = tranPath + "/" + primName
UsdGeom.Xform.Define(stage, newPath)
prim = stage.GetPrimAtPath(newPath)
# Remove references.
prim.GetReferences().ClearReferences()
# Add a reference.
prim.GetReferences().AddReference(path)
setRotate(prim, -90.0, 0.0, 0.0)
setScale(prim, 100.0, 100.0, 100.0)
heightPos = 5.0
setTranslate(prim, 0.0, heightPos, 0.0)
# Create/Set material.
matPath = "/World/Looks/mat_trans"
primM = stage.GetPrimAtPath(matPath)
if not primM.IsValid():
col = Gf.Vec3f(0, 1, 0)
createMaterialOmniPBR(matPath, "", "", col)
primM = stage.GetPrimAtPath(matPath)
material = UsdShade.Material(primM)
UsdShade.MaterialBindingAPI(prim).Bind(material)
# Pass the process to Omniverse.
asyncio.ensure_future(_omniverse_sync_wait())
# --------------------------------------.
# Convert obj files to USD.
# --------------------------------------.
# Get target path for converting dem obj to usd.
async def get_ObjToUsdDem (_mapIndex : int, _dstPath : str):
if (await ocl_existPath_async(dem_path)) == False:
return
dstPath = _dstPath + "/dem"
if (await ocl_existPath_async(dstPath)) == False:
result = omni.client.create_folder(dstPath)
if result != omni.client.Result.OK:
return
srcObjPathList = []
dstUsdPathList = []
for path in glob.glob(dem_path + "/" + str(_mapIndex) + "*.obj"):
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
dstPath2 = dstPath + "/" + str(mapIndex)
if (await ocl_existPath_async(dstPath2)) == False:
omni.client.create_folder(dstPath2)
usdPath = dstPath2 + "/" + str(mapIndex) + "_dem.usd"
if (await ocl_existPath_async(usdPath)):
continue
srcObjPathList.append(path)
dstUsdPathList.append(usdPath)
return srcObjPathList, dstUsdPathList
# Get target path for converting bldg obj to usd.
async def get_ObjToUsdBuilding (_mapIndex : int, _dstPath : str):
srcObjPathList = []
dstUsdPathList = []
if (await ocl_existPath_async(buliding_lod1_path)):
dstPath = _dstPath + "/building/lod1"
for path in glob.glob(buliding_lod1_path + "/**/" + str(_mapIndex) + "*.obj", recursive=True):
if (await ocl_existPath_async(dstPath)) == False:
omni.client.create_folder(dstPath)
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
dstPath2 = dstPath + "/" + str(mapIndex)
if (await ocl_existPath_async(dstPath2)) == False:
omni.client.create_folder(dstPath2)
usdPath = dstPath2 + "/" + str(mapIndex) + "_bldg.usd"
if (await ocl_existPath_async(usdPath)):
continue
srcObjPathList.append(path)
dstUsdPathList.append(usdPath)
if (await ocl_existPath_async(buliding_lod2_path)) and in_load_lod2:
dstPath = _dstPath + "/building/lod2"
for path in glob.glob(buliding_lod2_path + "/**/" + str(_mapIndex) + "*.obj", recursive=True):
if (await ocl_existPath_async(dstPath)) == False:
omni.client.create_folder(dstPath)
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
dstPath2 = dstPath + "/" + str(mapIndex)
if (await ocl_existPath_async(dstPath2)) == False:
omni.client.create_folder(dstPath2)
usdPath = dstPath2 + "/" + str(mapIndex) + "_bldg.usd"
if (await ocl_existPath_async(usdPath)):
continue
srcObjPathList.append(path)
dstUsdPathList.append(usdPath)
return srcObjPathList, dstUsdPathList
# Get target path for converting bridge obj to usd.
async def get_ObjToUsdBridge (_mapIndex : int, _dstPath : str):
srcObjPathList = []
dstUsdPathList = []
if (await ocl_existPath_async(bridge_path)):
dstPath = _dstPath + "/bridge"
for path in glob.glob(bridge_path + "/**/" + str(_mapIndex) + "*.obj", recursive=True):
if (await ocl_existPath_async(dstPath)) == False:
omni.client.create_folder(dstPath)
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
dstPath2 = dstPath + "/" + str(mapIndex)
if (await ocl_existPath_async(dstPath2)) == False:
omni.client.create_folder(dstPath2)
usdPath = dstPath2 + "/" + str(mapIndex) + "_brid.usd"
if (await ocl_existPath_async(usdPath)):
continue
srcObjPathList.append(path)
dstUsdPathList.append(usdPath)
return srcObjPathList, dstUsdPathList
# Get target path for converting tran obj to usd.
async def get_ObjToUsdTran (_mapIndex : int, _dstPath : str):
srcObjPathList = []
dstUsdPathList = []
if (await ocl_existPath_async(tran_path)):
dstPath = _dstPath + "/tran"
if (await ocl_existPath_async(dstPath)) == False:
omni.client.create_folder(dstPath)
for path in glob.glob(tran_path + "/**/" + str(_mapIndex) + "*.obj", recursive=True):
fName = os.path.basename(path)
# Get map index from file name.
mapIndex = 0
p1 = fName.find('_')
if p1 > 0:
mapIndex = int(fName[0:p1])
dstPath2 = dstPath + "/" + str(mapIndex)
if (await ocl_existPath_async(dstPath2)) == False:
omni.client.create_folder(dstPath2)
usdPath = dstPath2 + "/" + str(mapIndex) + "_tran.usd"
if (await ocl_existPath_async(usdPath)):
continue
srcObjPathList.append(path)
dstUsdPathList.append(usdPath)
return srcObjPathList, dstUsdPathList
# Convert asset file(obj/fbx/glTF, etc) to usd.
async def convert_asset_to_usd (input_path_list, output_path_list):
# 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()
for i in range(len(input_path_list)):
input_asset = input_path_list[i]
output_usd = output_path_list[i]
task = instance.create_converter_task(input_asset, output_usd, None, converter_context)
# Wait for completion.
success = await task.wait_until_finished()
if not success:
carb.log_error(task.get_status(), task.get_detailed_error())
break
# convert obj(dem/dldg/drid/tran) to usd.
async def convertObjToUsd ():
if (await ocl_existPath_async(in_plateau_obj_path)) == False:
return
dstPath = in_output_usd_folder
if dstPath == "":
dstPath = in_plateau_obj_path + "/output_usd"
if in_output_folder != "":
dstPath = in_output_folder + "/data"
if (await ocl_existPath_async(dstPath)) == False:
result = omni.client.create_folder(dstPath)
if result != omni.client.Result.OK:
return
srcObjPathList = []
dstUsdPathList = []
for mapIndex in mapIndexList:
##sList, dList = get_ObjToUsdDem(mapIndex, dstPath)
sList, dList = await get_ObjToUsdDem(mapIndex, dstPath)
srcObjPathList.extend(sList)
dstUsdPathList.extend(dList)
for mapIndex in mapIndexList:
#sList, dList = get_ObjToUsdBuilding(mapIndex, dstPath)
sList, dList = await get_ObjToUsdBuilding(mapIndex, dstPath)
srcObjPathList.extend(sList)
dstUsdPathList.extend(dList)
if in_load_bridge:
for mapIndex in mapIndexList:
#sList, dList = get_ObjToUsdBridge(mapIndex, dstPath)
sList, dList = await get_ObjToUsdBridge(mapIndex, dstPath)
srcObjPathList.extend(sList)
dstUsdPathList.extend(dList)
if in_load_tran:
for mapIndex in mapIndexList:
#sList, dList = get_ObjToUsdTran(mapIndex, dstPath)
sList, dList = await get_ObjToUsdTran(mapIndex, dstPath)
srcObjPathList.extend(sList)
dstUsdPathList.extend(dList)
# Wait for usd conversion.
if len(srcObjPathList) > 0:
task = asyncio.create_task(convert_asset_to_usd(srcObjPathList, dstUsdPathList))
await task
print(f"PLATEAU : convert obj to usd ({ len(srcObjPathList) })")
asyncio.ensure_future(_omniverse_sync_wait())
# Copy geoTiff images.
async def copyGEOTiffImages (srcPath : str, _mapIndex : int):
if in_output_folder == "":
return
if (await ocl_existPath_async(srcPath)) == False:
return
dstPath = in_output_folder + "/data/geotiff_images"
if (await ocl_existPath_async(dstPath)) == False:
result = omni.client.create_folder(dstPath)
if result != omni.client.Result.OK:
return
imgCou = 0
for path in glob.glob(srcPath + "/" + str(_mapIndex) + "*.*"):
fName = os.path.basename(path)
dPath = dstPath + "/" + fName
if (await ocl_existPath_async(dPath)):
continue
try:
# TODO : Warning ?
result = omni.client.copy(path, dPath)
if result == omni.client.Result.OK:
imgCou += 1
except:
pass
if imgCou > 0:
print(f"PLATEAU : copy GEOTiff images ({ imgCou })")
# --------------------------------------.
# load PLATEAU data.
# --------------------------------------.
async def load_PLATEAU ():
if (await ocl_existPath_async(in_plateau_obj_path)) == False:
return
print("PLATEAU : Start processing.")
# Convert obj to usd.
if in_convert_to_usd:
task = asyncio.create_task(convertObjToUsd())
await task
# Copy GEOTiff images.
if in_dem_textures_path != "":
for mapIndex in mapIndexList:
await copyGEOTiffImages(in_dem_textures_path, mapIndex)
# Create OmniPBR material.
materialLooksPath = defaultPrimPath + "/Looks"
prim = stage.GetPrimAtPath(materialLooksPath)
if prim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialLooksPath)
defaultMaterialPath = createMaterialOmniPBR(materialLooksPath + "/defaultMaterial")
for mapIndex in mapIndexList:
task_dem = asyncio.create_task(loadDem(mapIndex, defaultMaterialPath))
await task_dem
if not in_load_lod1_lod2:
task_building = asyncio.create_task(loadBuilding(mapIndex, in_load_lod2, defaultMaterialPath))
await task_building
else:
task_building_lod1 = asyncio.create_task(loadBuilding(mapIndex, False, defaultMaterialPath))
await task_building_lod1
task_building_lod2 = asyncio.create_task(loadBuilding(mapIndex, True, defaultMaterialPath))
await task_building_lod2
if in_load_bridge and in_load_lod2:
task_bridge = asyncio.create_task(loadBridge(mapIndex, defaultMaterialPath))
await task_bridge
if in_load_tran:
task_tran = asyncio.create_task(loadTran(mapIndex, defaultMaterialPath))
await task_tran
print(f"PLATEAU : map_index[{mapIndex}]")
print("PLATEAU : Processing is complete.")
# --------------------------------------.
# --------------------------------------.
asyncio.ensure_future(load_PLATEAU())
| 32,163 | Python | 33.734341 | 157 | 0.567049 |
ft-lab/omniverse_sample_scripts/PLATEAU/readme.md | # PLATEAU
Project PLATEAU ( https://www.mlit.go.jp/plateau/ )の都市データをOmniverseにインポートします。
G空間情報センターの「3D都市モデルポータルサイト」( https://www.geospatial.jp/ckan/dataset/plateau )の「東京都23区」より、
OBJ形式のデータを使用しています。
また、地形のテクスチャについてはGeoTIFFを分割して使用しました。
2022/06/26 : objからusdに変換して読み込むようにしました。
2022/07/11 : 変換されたusdやテクスチャをNucleus上にアップロードするようにしました(デフォルトの指定)。
## 使い方
### 「東京都23区」のobjファイル一式をダウンロード
「3D都市モデルポータルサイト」より、「東京都23区」のobjファイル一式をダウンロードします。
https://www.geospatial.jp/ckan/dataset/plateau-tokyo23ku/resource/9c8d65f1-a424-4189-92c0-d9e3f7c3d2db
「13100_tokyo23-ku_2020_obj_3_op.zip」がダウンロードされますので解凍します。
注意 : 配置パスに日本語名のフォルダがある場合は正しく動作しません。
### 「東京都23区」のGeoTIFFファイル一式をダウンロード
また、地形のテクスチャで「東京都23区」の「GeoTIFF」のオルソ画像データを用います。
これは航空写真を平行投影として地域メッシュの2次メッシュ(533926、533935など)ごとにテクスチャ化したものです。
以下より、GeoTIFFの画像をダウンロードします。
https://www.geospatial.jp/ckan/dataset/plateau-tokyo23ku/resource/2434d5b4-7dad-4286-8da5-276f68a23797
「13100_tokyo23-ku_2020_ortho_2_op.zip」がダウンロードされますので解凍します。
### GeoTIFF画像を10x10分割してjpeg形式に変換
Omniverseでは、tiff画像を扱うことができません。
そのためjpegに変換するようにしました。
また、8K解像度以上のテクスチャは読み込みに失敗するようです。
そのため、このtiffを10x10分割しそれぞれをjpegに変換します。
この処理はOmniverse上で行うことにしました。
Omniverse Createを起動します。
Omniverse Create 2022.1.2で確認しました。
[divide_GeoTiff_images.py](./divide_GeoTiff_images.py) のスクリプトの内容を、OmniverseのScript Editorにコピーします。
「in_plateau_obj_path」のパスに、「13100_tokyo23-ku_2020_ortho_2_op.zip」を解凍して展開されたフォルダのルートを指定します。
「in_save_folder_path」にそれぞれのtiff画像を10x10分割したときの画像を格納するフォルダを指定します。
スクリプトを実行します。
この処理は時間がかかります。Consoleに"Save success !!"と出ると出力完了です。
「in_save_folder_path」に指定したフォルダに53392500.jpg/53392501.jpgなどが出力されていることを確認します。
このTiffからjpeg出力を行う処理は1回だけ行えばOKです。
注意 : 配置パスに日本語名のフォルダがある場合は正しく動作しません。
### 例1 : 東京23区の地形と建物(LOD1)を読み込み
※ テクスチャは反映しません。
Omniverse Createを起動し、新規Stageを作成します。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」の内容をScript Editorにコピーします。
スクリプト上の 「in_plateau_obj_path」のパス指定を、ローカルの「13100_tokyo23-ku_2020_obj_3_op.zip」を解凍したフォルダに変更します。
スクリプト上の 「in_assign_dem_texture」をFalseにします。
これにより、demにマッピングするテクスチャは読み込まれません。
スクリプトを実行します。
この処理は時間がかかります。数分ほど待つと、StageにPLATEAUの都市データが読み込まれます。
以下は背景のEnvironmentを指定し、RTX-Interactive (Path Tracing)にしています。


このLOD1のみの都市データは、Omniverse Createで約12GBくらいのメモリを消費します。
OSのメモリは32GBあれば足ります。
2022/06/26
すべてのデータをobjからusdに変換して読み込むようにしました。
変換されたusdは、in_plateau_obj_pathの"output_usd"フォルダに格納されます。
### 例2 : 東京23区の地形と建物(LOD1)を読み込み + 地形のテクスチャを反映
Omniverse Create 2022.1.2で確認しました。
Omniverse Createで新規Stageを作成します。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」の内容をScript Editorにコピーします。
スクリプト上の 「in_plateau_obj_path」のパス指定を、ローカルの「13100_tokyo23-ku_2020_obj_3_op.zip」を解凍したフォルダに変更します。
スクリプト上の 「in_dem_textures_path」のパスは、ローカルのGeoTiffからjpeg変換したときの出力先を指定します。
スクリプト上の 「in_assign_dem_texture」がTrueになっているのを確認します。
これにより、「in_dem_textures_path」で指定したフォルダからテクスチャが読み込まれ、マテリアルとテクスチャが地形のMeshであるdemに割り当てられます。
スクリプトを実行します。
この処理は時間がかかります。数分ほど待つと、StageにPLATEAUの都市データが読み込まれます。
地形にはテクスチャが割り当てられています。
以下は背景のEnvironmentを指定し、RTX-Interactive (Path Tracing)にしています。


このLOD1のみの都市データは、Omniverse Createで約13GBくらいのメモリを消費します。
OSのメモリは32GBあれば足ります。
### 例3 : 東京23区の地形と建物(LOD1またはLOD2)を読み込み + 地形のテクスチャを反映
LOD2の建物がある場合はそれを読み込みます。
Omniverse Create 2022.1.2で確認しました。
Omniverse Createで新規Stageを作成します。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」の内容をScript Editorにコピーします。
スクリプト上の 「in_plateau_obj_path」のパス指定を、ローカルの「13100_tokyo23-ku_2020_obj_3_op.zip」を解凍したフォルダに変更します。
スクリプト上の 「in_dem_textures_path」のパスは、ローカルのGeoTiffからjpeg変換したときの出力先を指定します。
スクリプト上の 「in_assign_dem_texture」がTrueになっているのを確認します。
これにより、「in_dem_textures_path」で指定したフォルダからテクスチャが読み込まれ、マテリアルとテクスチャが地形のMeshであるdemに割り当てられます。
スクリプト上の「in_load_lod2」をTrueに変更します。
これにより、もし建物にLOD2の情報を持つ場合はそれが読み込まれます。
※ LOD2はテクスチャを伴います。これにより、読み込み速度とメモリはかなり消費します。
また、スクリプト上の「mapIndexList」に地域メッシュの2次メッシュの番号を配列で入れています。
デフォルトでは東京23区全体をいれていますが、メモリに合わせて2次メッシュの番号を調整します。
ここでは以下のように変更しました。
```
mapIndexList = [533945, 533946]
```
スクリプトを実行します。
LOD2を読み込む場合は時間がかなりかかります。
20分ほどで読み込みが完了しました。
「mapIndexList = [533945, 533946]」でOmniverse Createで約11GBくらいのメモリを消費。
続いて
```
mapIndexList = [533935, 533936]
```
として追加でスクリプトを実行し、地形データを読み込みました。
30分ほどで読み込みが完了しました。
追加の「mapIndexList = [533935, 533936]」でOmniverse Createで合計約20GBくらいのメモリを消費。
スクリプトで連続して複数の2次メッシュ分を読み込む場合、読み込み完了後にフリーズする場合がありました(マテリアルの更新でぶつかる?)。
Omniverse CreateのステータスバーでLoading Materialと出てプログレスバーのパーセントが進まない場合がありました。

これを回避するため、読み込みが完全に完了するのを待って何回かに分けてスクリプトを複数回実行するようにしています。
以下は背景のEnvironmentを指定し、RTX-Interactive (Path Tracing)にしています。


LOD2も考慮した[533945, 533946, 533935, 533936]の2次メッシュ範囲のデータは、Omniverse Createで合計で約20GBくらいのメモリを消費します。
OSのメモリは32GBでは読み込めませんでした。64GBくらい余裕を持たせたほうがよさそうです。
### 例4 : 東京23区の地形と建物(LOD1またはLOD2)、橋(LOD2)を読み込み + 地形のテクスチャを反映
LOD2の建物がある場合はそれを読み込みます。
また、LOD2の橋も読み込みます。
Omniverse Create 2022.1.2で確認しました。
Omniverse Createで新規Stageを作成します。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」の内容をScript Editorにコピーします。
スクリプト上の 「in_plateau_obj_path」のパス指定を、ローカルの「13100_tokyo23-ku_2020_obj_3_op.zip」を解凍したフォルダに変更します。
スクリプト上の 「in_dem_textures_path」のパスは、ローカルのGeoTiffからjpeg変換したときの出力先を指定します。
スクリプト上の 「in_assign_dem_texture」がTrueになっているのを確認します。
これにより、「in_dem_textures_path」で指定したフォルダからテクスチャが読み込まれ、マテリアルとテクスチャが地形のMeshであるdemに割り当てられます。
スクリプト上の「in_load_lod2」をTrueに変更します。
これにより、もし建物にLOD2の情報を持つ場合はそれが読み込まれます。
※ LOD2はテクスチャを伴います。これにより、読み込み速度とメモリはかなり消費します。
スクリプト上の「in_load_bridge」をTrueに変更します。
これにより、LOD2の橋の3Dモデルも読み込まれます。
また、スクリプト上の「mapIndexList」に2次メッシュの番号を配列で入れています。
デフォルトでは東京23区全体をいれていますが、メモリに合わせて2次メッシュの番号を調整します。
ここでは以下のように変更しました。
```
mapIndexList = [533935]
```
スクリプトを実行します。
以下は背景のEnvironmentを指定し、RTX-Interactive (Path Tracing)にしています。

LOD2で橋を追加するとさらにメモリ消費は増加することになります。
ですが、建物に比べて橋は数が少ないです。
## スクリプトを使った緯度経度の確認
いくつか緯度経度計算を行う際の確認用スクリプトを作成しました。
### 緯度経度を指定し、平面直角座標/Omniverse上のXZ位置に変換
地理院地図の「平面直角座標への換算」( https://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/bl2xyf.html )をPythonスクリプトに置き換えました。
[calcLatLongToOmniverse.py](./calcLatLongToOmniverse.py)
これはスクリプトのみの計算になります。
スクリプトの(in_lat, in_longi)に緯度経度を指定すると平面直角座標での位置を計算、Omniverse(USD)の座標系(Y-Up/右手系/cm単位)に変換します。
Omniverse上の-Z方向が北向きとします。
以下は地理院地図( https://maps.gsi.go.jp/ )での東京タワー前。

緯度 : 35.658310
経度 : 139.745243
これをこのスクリプトで計算すると、Omniverse上のXZ位置は以下のように計算できました。
x = -797587.3075871967 (cm)
z = 3790513.4729016027 (cm)
この位置に赤いマテリアルを与えたSphereを配置すると以下のようになりました。

### 2点間の距離を計算(単純な直線距離)
[calcDistance.py](./calcDistance.py)
選択された2つの形状の中心位置の距離を単純計算します。
cmとm単位の距離をConsoleに出力します。

### 2つの緯度経度を指定して距離を計算
地理院地図の「距離と方位角の計算」( https://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/bl2stf.html )をPythonスクリプトに置き換えました。
[calcDistanceWithLatLong.py](./calcDistanceWithLatLong.py)
これはスクリプトのみの計算になります。
スクリプトの(in_lat1, in_longi1)に開始位置の緯度経度を指定、(in_lat2, in_longi2)に終了位置の緯度経度を指定します。
この2つの緯度経度の距離をmとkm単位でConsoleに出力します。
## USDファイル変換について
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」を実行する際、PLATEAUのobjファイルをusdファイルに変換します。
変換されたUSDファイルは「in_plateau_obj_path + "/output_usd"」に格納されます。
東京23区全体でusdと関連テクスチャファイルは全体で4GBほどのファイル容量になりました。
また、objからusdに変換する処理は時間がかかります。
2回目以降、すでにusdファイルが存在する場合はこのusdファイル変換処理はスキップされます。
もし、改めてobjからusd変換する場合は「in_plateau_obj_path + "/output_usd"」ファイルを削除するようにしてください。
Omniverseではobj/fbxファイルを直接Referenceできますが、できるだけusdに変換して扱うほうがよいと思われます。
## Nucleus上へアップロード (2022/07/11 追加)
PLATEAUのデータをデフォルトでNucleus上にアップロードするようにしました。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」の
```
in_output_folder = "omniverse://localhost/PLATEAU/Tokyo_23ku"
```
の指定のURLに、objからusd変換されたときのファイルとGEOTiffを分割した画像を転送します。
なお、初回はobjからusdの変換、GEOTiff画像のNucleusへの転送作業が発生するため時間がかかります。
都市データを参照として読み込んだルートのusdファイルをNucleus上に保存することで、usdやテクスチャの参照は自動的に相対パスに変換されます。
Omniverseでシーンを管理する場合はNucleus上で行うほうがよさそうです。
## Collect Asset : Nucleusにアップロードするには?
※ 2022/07/11 : デフォルトで、関連するusdとテクスチャファイルをNucleus上にアップロードするようにしました。
そのため、Collect Assetは使わなくても問題ありません。
参考 : https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_collect.html
「Collect Asset」を使用することで、
対象usdファイル内からusdファイルや画像ファイルなどの参照がある場合に相対パスになるように整理して出力します。
これによりローカルの環境依存がある状態でのパスが整理され、Nucleusへのアップロードができるようになります。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」を使用して東京23区の都市データを読み込み後、
現在のStageをusdファイルに保存します。
なお、このとき参照されるファイルもすべてUSDファイルで構成されるようにしておいてください。デフォルトの「in_convert_to_usd = True」の指定でobjはUSDに変換されます。
Contentウィンドウで保存したusdを右クリックしてポップアップメニューを表示。
「Collect Asset」を選択します。

Collection Optionsウィンドウで「Collection Path」に出力先を指定します。
ここでNucleus上のパスを指定しました。
Collectボタンを押すと、指定のパスに整理した状態でusdや参照されているテクスチャなどを出力します。

### Collect Asset使用時の注意点
Omniverse Create 2022.1.3段階で、以下の点を確認しています。
* 対象のUSDファイルから参照(Reference)するAssetは、usdファイルを指定するようにしてください。
objやfbxを直接参照することもできますが、この場合はCollect Assetでマテリアルファイルやテクスチャファイルが正しく渡せませんでした。
* ~~Material Graphを使用すると、Collect AssetでMDLファイルが正しく渡せませんでした。~~ Omniverse Create 2022.1.3では問題なし。
----
## ファイル
|ファイル|説明|
|---|---|
|[divide_GeoTiff_images.py](./divide_GeoTiff_images.py)|東京23区のPLATEAUのGeoTIFFファイルを10x10分割して、jpeg形式で指定のフォルダに出力します。<br>コード内の「in_xxx」の指定を環境に合わせて書き換えるようにしてください。|
|[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)|東京23区のPLATEAUのobjファイルより、都市モデルをOmniverseにインポートします。<br>コード内の「in_xxx」の指定を環境に合わせて書き換えるようにしてください。|
|[calcDistance.py](./calcDistance.py)|選択された2つの形状の直線距離を計算します。|
|[calcDistanceWithLatLong.py](./calcDistanceWithLatLong.py)|2つの緯度経度を指定して距離を計算します。<br>コード内の「in_xxx」の指定を環境に合わせて書き換えるようにしてください。|
|[calcLatLongToOmniverse.py](./calcLatLongToOmniverse.py)|緯度経度から平面直角座標上の位置を計算、Omniverse上のXZ位置を計算します。<br>コード内の「in_xxx」の指定を環境に合わせて書き換えるようにしてください。|
## 現状の既知問題点
Omniverse Create 2022.1.3で確認。
### 大量のusdをReferenceする際にプログレスバーが止まる
※ 開発にレポート済み。
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」を使って都市データを読み込む場合、
Omniverse CreateのステータスバーでLoading Materialと出てプログレスバーのパーセントが進まない場合がありました。

これを回避するため、読み込みが完全に完了するのを待って何回かに分けてスクリプトを複数回実行するようにします。
LOD1だけの読み込みの場合は、地域メッシュ全部(14個分)を読み込む場合でも停止することはありませんでした。
LOD2を含む場合、マップを1つまたは2つずつ読み込まないとフリーズします。
### 作成されたusdファイルを保存する際にSaving layersで進まない
※ 開発にレポート済み。
東京23区全体を読み込んで保存する場合、Saving layersでずっと進まない場合がありました。
数時間待てば処理が完了します。
回避策として、マップを1つだけ読み込んでその段階でいったん保存。
マップを追加読み込んで保存、とすると時間がかからないようでした。
### 保存したusdファイルを読み込む場合にプログレスバーが止まる
※ 開発にレポート済み。
東京23区全体(LOD2)を読み込んで保存後、いったんOmniverse Createを再起動してusdを読み込みます。
この際、Loading Materialと出てプログレスバーのパーセントが進まない場合がありました。
おそらく1つめの「大量のusdをReferenceする際にプログレスバーが止まる」と同じ現象と思われます。
### objファイルをReferenceした状態で保存すると、再読み込み時にテクスチャが消える
「[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)」を使って都市データを読み込む場合に「in_convert_to_usd」をFalseにすると、
PLATEAUのobjを直接Referenceで参照します。
「in_convert_to_usd」をTrueにするとobjからusdに変換してそれを参照します。
東京23区全体(LOD2)を読み込んで保存後usdを閉じ、
再度同じシーンを開いた場合、テクスチャが消えてしまう場合があります。
これはobjで読み込んだ場合のキャッシュ(objの場合、作業ディレクトリにusd変換した際のジオメトリやテクスチャが格納される)によるものと思われます。
また、「Collect Asset」( https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_collect.html )を行ってNucleusにusd一式をアップロードする場合、
objを使っているとマテリアルのmtlやテクスチャを渡してくれないようでした。
そのため、OmniverseではStageはすべてusdを使用するほうがよさそうです。
## 更新履歴
### 2022/07/11
[import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py) を更新。
* 「in_output_folder」を指定することで、Nucleus上にusd/テクスチャファイルを送るようにした
* ファイル転送時にUIが止まる問題の緩和 (Nucleus上にアップするようにしたため?)
ただし、ステージの構築時はLOD2の場合はマテリアル処理で待ちが発生する模様。
* GEOTiffのテクスチャを地形に割り当てる際に、マテリアルのSpecularを0にした(白飛びを緩和)
### 2022/06/26
* [import_PLATEAU_tokyo23ku_obj.py](./import_PLATEAU_tokyo23ku_obj.py)でUSDに変換してインポートするようにした
### 2022/06/10
* 初回バージョン | 13,043 | Markdown | 33.599469 | 163 | 0.766848 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.