file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/simple_CartPole_actor_critic_manual_loop.py | import collections
import gym
import numpy as np
import statistics
import tensorflow as tf
import tqdm
from matplotlib import pyplot as plt
from tensorflow.keras import layers
from typing import Any, List, Sequence, Tuple
# Create the environment
env = gym.make("CartPole-v1")
# Set seed for experiment reproducibility
seed = 42
env.seed(seed)
tf.random.set_seed(seed)
np.random.seed(seed)
# Small epsilon value for stabilizing division operations
eps = np.finfo(np.float32).eps.item()
class ActorCritic(tf.keras.Model):
"""Combined actor-critic network."""
def __init__(
self,
num_actions: int,
num_hidden_units: int):
"""Initialize."""
super().__init__()
self.common = layers.Dense(num_hidden_units, activation="relu")
# self.lstm = layers.LSTM(units=num_hidden_units, activation="relu", recurrent_activation="sigmoid", stateful=True)
self.actor = layers.Dense(num_actions)
self.critic = layers.Dense(1)
def call(self, inputs: tf.Tensor, states = None) -> Tuple[tf.Tensor, tf.Tensor]:
x = inputs
x = self.common(x)
# if states is None: states = self.lstm.get_initial_state(x)
# else: states = self.lstm.states
# x = self.lstm(inputs, initial_state=states)
return self.actor(x), self.critic(x)
num_actions = env.action_space.n # 2
num_hidden_units = 128
model = ActorCritic(num_actions, num_hidden_units)
# Wrap OpenAI Gym's `env.step` call as an operation in a TensorFlow function.
# This would allow it to be included in a callable TensorFlow graph.
def env_step(action: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Returns state, reward and done flag given an action."""
state, reward, done, _ = env.step(action)
return (state.astype(np.float32),
np.array(reward, np.int32),
np.array(done, np.int32))
def tf_env_step(action: tf.Tensor) -> List[tf.Tensor]:
return tf.numpy_function(env_step, [action], [tf.float32, tf.int32, tf.int32])
def run_episode(
initial_state: tf.Tensor,
model: tf.keras.Model,
max_steps: int) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]:
"""Runs a single episode to collect training data."""
action_probs = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
values = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
rewards = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True)
initial_state_shape = initial_state.shape
state = initial_state
for t in tf.range(max_steps):
# Convert state into a batched tensor (batch size = 1)
state = tf.expand_dims(state, 0)
# Run the model and to get action probabilities and critic value
action_logits_t, value = model(state)
print("ACTION_LOGITS_T")
print(action_logits_t)
print("S.D.")
print(value)
# Sample next action from the action probability distribution
action = tf.random.categorical(action_logits_t, 1)[0, 0]
print("ACTION")
print(action)
action_probs_t = tf.nn.softmax(action_logits_t)
# Store critic values
values = values.write(t, tf.squeeze(value))
# Store log probability of the action chosen
action_probs = action_probs.write(t, action_probs_t[0, action])
# Apply action to the environment to get next state and reward
state, reward, done = tf_env_step(action)
state.set_shape(initial_state_shape)
# Store reward
rewards = rewards.write(t, reward)
if tf.cast(done, tf.bool):
break
action_probs = action_probs.stack()
values = values.stack()
rewards = rewards.stack()
return action_probs, values, rewards
def get_expected_return(
rewards: tf.Tensor,
gamma: float,
standardize: bool = True) -> tf.Tensor:
"""Compute expected returns per timestep."""
n = tf.shape(rewards)[0]
returns = tf.TensorArray(dtype=tf.float32, size=n)
# Start from the end of `rewards` and accumulate reward sums
# into the `returns` array
rewards = tf.cast(rewards[::-1], dtype=tf.float32)
discounted_sum = tf.constant(0.0)
discounted_sum_shape = discounted_sum.shape
for i in tf.range(n):
reward = rewards[i]
discounted_sum = reward + gamma * discounted_sum
discounted_sum.set_shape(discounted_sum_shape)
returns = returns.write(i, discounted_sum)
returns = returns.stack()[::-1]
if standardize:
returns = ((returns - tf.math.reduce_mean(returns)) / (tf.math.reduce_std(returns) + eps))
return returns
huber_loss = tf.keras.losses.Huber(reduction=tf.keras.losses.Reduction.SUM)
def compute_loss(
action_probs: tf.Tensor,
values: tf.Tensor,
returns: tf.Tensor) -> tf.Tensor:
"""Computes the combined actor-critic loss."""
advantage = returns - values
action_log_probs = tf.math.log(action_probs)
actor_loss = -tf.math.reduce_sum(action_log_probs * advantage)
critic_loss = huber_loss(values, returns)
return actor_loss + critic_loss
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
@tf.function
def train_step(
initial_state: tf.Tensor,
model: tf.keras.Model,
optimizer: tf.keras.optimizers.Optimizer,
gamma: float,
max_steps_per_episode: int) -> tf.Tensor:
"""Runs a model training step."""
with tf.GradientTape() as tape:
# Run the model for one episode to collect training data
action_probs, values, rewards = run_episode( initial_state, model, max_steps_per_episode)
# Calculate expected returns
returns = get_expected_return(rewards, gamma)
# Convert training data to appropriate TF tensor shapes
action_probs, values, returns = [tf.expand_dims(x, 1) for x in [action_probs, values, returns]]
# Calculating loss values to update our network
loss = compute_loss(action_probs, values, returns)
# Compute the gradients from the loss
grads = tape.gradient(loss, model.trainable_variables)
# Apply the gradients to the model's parameters
optimizer.apply_gradients(zip(grads, model.trainable_variables))
episode_reward = tf.math.reduce_sum(rewards)
return episode_reward
min_episodes_criterion = 100
max_episodes = 10000
max_steps_per_episode = 1000
# Cartpole-v0 is considered solved if average reward is >= 195 over 100
# consecutive trials
reward_threshold = 195
running_reward = 0
# Discount factor for future rewards
gamma = 0.99
# Keep last episodes reward
episodes_reward: collections.deque = collections.deque(maxlen=min_episodes_criterion)
with tqdm.trange(max_episodes) as t:
for i in t:
initial_state = tf.constant(env.reset(), dtype=tf.float32)
episode_reward = int(train_step(initial_state, model, optimizer, gamma, max_steps_per_episode))
episodes_reward.append(episode_reward)
running_reward = statistics.mean(episodes_reward)
t.set_description(f'Episode {i}')
t.set_postfix(
episode_reward=episode_reward, running_reward=running_reward)
# Show average episode reward every 10 episodes
if i % 10 == 0:
pass # print(f'Episode {i}: average reward: {avg_reward}')
if running_reward > reward_threshold and i >= min_episodes_criterion:
break
print(f'\nSolved at episode {i}: average reward: {running_reward:.2f}!')
| 7,501 | Python | 32.19469 | 123 | 0.665245 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/simple_RNN_state_reuse.py | import random
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
batch_size = 16
batch_count = 10
patience = 5 # if no improvement in N steps -> stop training
timesteps = 9
def get_train_data():
x_batch_train, y_batch_train = [], []
for i in range(batch_size):
offset = random.random()
width = random.random()*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_train.append(sequence[:timesteps])
y_batch_train.append((sequence[timesteps]+1)/2)
x_batch_train = np.array(x_batch_train).reshape((batch_size, timesteps, 1))
y_batch_train = np.array(y_batch_train).reshape((batch_size, 1))
return x_batch_train, y_batch_train
def get_val_data():
x_batch_val, y_batch_val = [], []
for i in range(batch_size):
offset = i/batch_size
width = (1+i)/batch_size*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_val.append(sequence[:timesteps])
y_batch_val.append((sequence[timesteps]+1)/2)
x_batch_val = np.array(x_batch_val).reshape((batch_size, timesteps, 1))
y_batch_val = np.array(y_batch_val).reshape((batch_size, 1))
return x_batch_val, y_batch_val
def train_step(x, y, model, optimizer, loss_fn, train_acc_metric):
with tf.GradientTape() as tape:
logits = model(x, training=True)
loss_value = loss_fn(y, logits)
grads = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_acc_metric.update_state(y, logits) # update training matric
return loss_value
def test_step(x, y, model, loss_fn, val_acc_metric):
val_logits = model(x, training=False)
loss_value = loss_fn(y, val_logits)
val_acc_metric.update_state(y, val_logits)
return loss_value
class SimpleLSTM(keras.Model):
def __init__(self, num_input, embedding_dim, lstm_units, num_output):
super().__init__(self)
# self.embedding = layers.Embedding(num_input, embedding_dim)
self.lstm1 = layers.LSTM(lstm_units, return_sequences=True, return_state=True)
self.dense = layers.Dense(num_output)
def call(self, inputs, states=None, return_state = False, training=False):
x = inputs
# x = self.embedding(x, training=training)
if states is None: states = self.lstm1.get_initial_state(x) # state shape = (2, batch_size, lstm_units)
print(x.shape)
print(len(states))
print(states[0].shape)
x, sequence, states = self.lstm1(x, initial_state=states, training=training)
x = self.dense(x, training=training)
if return_state: return x, states
else: return x
model = SimpleLSTM(num_input=9, embedding_dim=32, lstm_units=64, num_output=3)
model.build(input_shape=(1, 9))
model.summary()
optimizer = tf.optimizers.Adam(learning_rate=0.0025)
loss_fn = keras.losses.MeanSquaredError() # Instantiate a loss function.
train_mse_metric = keras.metrics.MeanSquaredError()
val_mse_metric = keras.metrics.MeanSquaredError()
test_mse_metric = keras.metrics.MeanSquaredError()
val_loss_tracker = []
for epoch in range(1000):
print("\nStart of epoch %d" % (epoch,))
train_loss = []
val_loss = []
test_loss = []
# Iterate over the batches of the dataset
for step in range(batch_count):
x_batch_train, y_batch_train = get_train_data()
loss_value = train_step(x_batch_train,
y_batch_train,
model,
optimizer,
loss_fn,
train_mse_metric)
train_loss.append(float(loss_value))
# Run a validation loop at the end of each epoch
for step in range(batch_count):
x_batch_val, y_batch_val = get_val_data()
val_loss_value = test_step(x_batch_val, y_batch_val,
model, loss_fn,
val_mse_metric)
val_loss.append(float(val_loss_value))
val_loss_tracker.append(np.mean(val_loss))
# Display metrics at the end of each epoch
train_acc = train_mse_metric.result()
print("Training mse over epoch: %.4f" % (float(train_acc),))
val_acc = val_mse_metric.result()
print("Validation mse: %.4f" % (float(val_acc),))
test_acc = test_mse_metric.result()
# Reset metrics at the end of each epoch
train_mse_metric.reset_states()
val_mse_metric.reset_states()
if len(val_loss_tracker) > patience:
still_better = False
for i in range(patience):
if val_loss_tracker[len(val_loss_tracker) - patience + i] < min(
val_loss_tracker[:len(val_loss_tracker) - patience]): still_better = True
if still_better == False: break | 4,889 | Python | 40.794871 | 111 | 0.628554 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/simple_RNN.py | import random
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
batch_size = 16
batch_count = 10
patience = 5 # if no improvement in N steps -> stop training
timesteps = 9
input_dim = 1
# Build the RNN model
def build_model():
model = keras.models.Sequential(
[
keras.layers.LSTM(32, input_shape=(timesteps, input_dim)), # (time-steps, n_features)
# keras.layers.BatchNormalization(),
keras.layers.Dense(1),
]
)
return model
def get_train_data():
x_batch_train, y_batch_train = [], []
for i in range(batch_size):
offset = random.random()
width = random.random()*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_train.append(sequence[:timesteps])
y_batch_train.append((sequence[timesteps]+1)/2)
x_batch_train = np.array(x_batch_train).reshape((batch_size, timesteps, 1))
y_batch_train = np.array(y_batch_train).reshape((batch_size, 1))
return x_batch_train, y_batch_train
def get_val_data():
x_batch_val, y_batch_val = [], []
for i in range(batch_size):
offset = i/batch_size
width = (1+i)/batch_size*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_val.append(sequence[:timesteps])
y_batch_val.append((sequence[timesteps]+1)/2)
x_batch_val = np.array(x_batch_val).reshape((batch_size, timesteps, 1))
y_batch_val = np.array(y_batch_val).reshape((batch_size, 1))
return x_batch_val, y_batch_val
def train_step(x, y, model, optimizer, loss_fn, train_acc_metric):
with tf.GradientTape() as tape:
logits = model(x, training=True)
loss_value = loss_fn(y, logits)
grads = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_acc_metric.update_state(y, logits) # update training matric
return loss_value
def test_step(x, y, model, loss_fn, val_acc_metric):
val_logits = model(x, training=False)
loss_value = loss_fn(y, val_logits)
val_acc_metric.update_state(y, val_logits)
return loss_value
# mnist = keras.datasets.mnist
# (x_train, y_train), (x_test, y_test) = mnist.load_data()
# x_train, x_test = x_train / 255.0, x_test / 255.0
# sample, sample_label = x_train[0], y_train[0]
model = build_model()
print(model.summary())
optimizer = tf.optimizers.Adam(learning_rate=0.0025)
# Instantiate a loss function.
# loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # Computes the crossentropy loss between the labels and predictions. (use one-hot) produces a category index of the most likely matching category.
# loss_fn = keras.losses.CategoricalCrossentropy(from_logits=True) # Computes the crossentropy loss between the labels and predictions. (use one-hot) produces a one-hot array containing the probable match for each category.
loss_fn = keras.losses.MeanSquaredError() # Instantiate a loss function.
# Prepare the metrics.
# train_acc_metric = keras.metrics.CategoricalAccuracy()
# val_acc_metric = keras.metrics.CategoricalAccuracy()
# test_acc_metric = keras.metrics.CategoricalAccuracy()
train_acc_metric = keras.metrics.MeanSquaredError()
val_acc_metric = keras.metrics.MeanSquaredError()
test_acc_metric = keras.metrics.MeanSquaredError()
val_loss_tracker = []
for epoch in range(1000):
print("\nStart of epoch %d" % (epoch,))
train_loss = []
val_loss = []
test_loss = []
# Iterate over the batches of the dataset
for step in range(batch_count):
x_batch_train, y_batch_train = get_train_data()
loss_value = train_step(x_batch_train,
y_batch_train,
model,
optimizer,
loss_fn,
train_acc_metric)
train_loss.append(float(loss_value))
# Run a validation loop at the end of each epoch
for step in range(batch_count):
x_batch_val, y_batch_val = get_val_data()
val_loss_value = test_step(x_batch_val, y_batch_val,
model, loss_fn,
val_acc_metric)
val_loss.append(float(val_loss_value))
val_loss_tracker.append(np.mean(val_loss))
# Display metrics at the end of each epoch
train_acc = train_acc_metric.result()
print("Training mse over epoch: %.4f" % (float(train_acc),))
val_acc = val_acc_metric.result()
print("Validation mse: %.4f" % (float(val_acc),))
test_acc = test_acc_metric.result()
# Reset metrics at the end of each epoch
train_acc_metric.reset_states()
val_acc_metric.reset_states()
if len(val_loss_tracker) > patience:
still_better = False
for i in range(patience):
if val_loss_tracker[len(val_loss_tracker) - patience + i] < min(
val_loss_tracker[:len(val_loss_tracker) - patience]): still_better = True
if still_better == False: break
# model.fit(
# x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=10
# ) | 5,220 | Python | 40.768 | 224 | 0.643295 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/wandb_RNN.py | import wandb
from wandb.keras import WandbCallback
wandb.login()
import random
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# batch_size = 16
train_batch_count = 20 # number of training batch(s) per epoch
val_batch_count = 10 # number of validation batch(s) per epoch
patience = 10 # if no improvement in N steps -> stop training
# timesteps = 9
input_dim = 1
sweep_config = {
'method': 'random', # bayes
'metric': {
'name': 'val_loss',
'goal': 'minimize'
},
'early_terminate': {
'type': 'hyperband',
'min_iter': 10
},
'parameters': {
'timesteps': {
"min": 1,
"max": 20
},
'batch_size': {
'values': [8, 16, 32, 64]
},
'learning_rate':{
"min": 0.0001,
"max": 0.1
},
'n_lstm': {
"min": 1,
"max": 64
}
}
}
# Build the RNN model
def build_model(n_lstm, timesteps):
model = keras.models.Sequential(
[
keras.layers.LSTM(n_lstm, input_shape=(timesteps, input_dim)), # (time-steps, n_features)
# keras.layers.BatchNormalization(),
keras.layers.Dense(1),
]
)
return model
def get_train_data(batch_size, timesteps):
x_batch_train, y_batch_train = [], []
for i in range(batch_size):
offset = random.random()
width = random.random()*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_train.append(sequence[:timesteps])
y_batch_train.append((sequence[timesteps]+1)/2)
x_batch_train = np.array(x_batch_train).reshape((batch_size, timesteps, 1))
y_batch_train = np.array(y_batch_train).reshape((batch_size, 1))
return x_batch_train, y_batch_train
def get_val_data(batch_size, timesteps):
x_batch_val, y_batch_val = [], []
for i in range(batch_size):
offset = i/batch_size
width = (1+i)/batch_size*3
sequence = np.cos(np.arange(offset, offset+width, width/(timesteps+1)))
x_batch_val.append(sequence[:timesteps])
y_batch_val.append((sequence[timesteps]+1)/2)
x_batch_val = np.array(x_batch_val).reshape((batch_size, timesteps, 1))
y_batch_val = np.array(y_batch_val).reshape((batch_size, 1))
return x_batch_val, y_batch_val
def train_step(x, y, model, optimizer, loss_fn, train_acc_metric):
with tf.GradientTape() as tape:
logits = model(x, training=True)
loss_value = loss_fn(y, logits)
grads = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_acc_metric.update_state(y, logits) # update training matric
return loss_value
def test_step(x, y, model, loss_fn, val_acc_metric):
val_logits = model(x, training=False)
loss_value = loss_fn(y, val_logits)
val_acc_metric.update_state(y, val_logits)
return loss_value
def train(model,
optimizer,
loss_fn,
train_mse_metric,
val_mse_metric,
batch_size,
timesteps):
val_loss_tracker = []
for epoch in range(1000):
print("\nStart of epoch %d" % (epoch,))
train_loss = []
val_loss = []
# Iterate over the batches of the dataset
for step in range(train_batch_count):
x_batch_train, y_batch_train = get_train_data(batch_size=batch_size, timesteps=timesteps)
loss_value = train_step(x_batch_train,
y_batch_train,
model,
optimizer,
loss_fn,
train_mse_metric)
train_loss.append(float(loss_value))
# Run a validation loop at the end of each epoch
for step in range(val_batch_count):
x_batch_val, y_batch_val = get_val_data(batch_size=batch_size, timesteps=timesteps)
val_loss_value = test_step(x_batch_val,
y_batch_val,
model,
loss_fn,
val_mse_metric)
val_loss.append(float(val_loss_value))
val_loss_tracker.append(np.mean(val_loss)) # track validation loss for no improvment elimination manually
# Display metrics at the end of each epoch
train_mse = train_mse_metric.result()
print("Training mse over epoch: %.4f" % (float(train_mse),))
val_mse= val_mse_metric.result()
print("Validation mse: %.4f" % (float(val_mse),))
# Reset metrics at the end of each epoch
train_mse_metric.reset_states()
val_mse_metric.reset_states()
# 3️⃣ log metrics using wandb.log
wandb.log({'epochs': epoch,
'loss': np.mean(train_loss),
'mse': float(train_mse),
'val_loss': np.mean(val_loss),
'val_mse': float(val_mse)})
if len(val_loss_tracker) > patience:
still_better = False
for i in range(patience):
if val_loss_tracker[len(val_loss_tracker) - patience + i] < min(val_loss_tracker[:len(val_loss_tracker) - patience]): still_better = True
if still_better == False: break
def sweep_train():
config_defaults = { # default hyperparameters
'batch_size': 8,
'learning_rate': 0.01
}
# Initialize wandb with a sample project name
wandb.init(config=config_defaults) # this gets over-written in the Sweep
wandb.config.architecture_name = "RNN"
wandb.config.dataset_name = "cosine_test"
model = build_model(n_lstm=wandb.config.n_lstm, timesteps=wandb.config.timesteps)
print(model.summary())
optimizer = tf.optimizers.Adam(learning_rate=wandb.config.learning_rate)
# Instantiate a loss function.
# loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # Computes the crossentropy loss between the labels and predictions. (use one-hot) produces a category index of the most likely matching category.
# loss_fn = keras.losses.CategoricalCrossentropy(from_logits=True) # Computes the crossentropy loss between the labels and predictions. (use one-hot) produces a one-hot array containing the probable match for each category.
loss_fn = keras.losses.MeanSquaredError() # Instantiate a loss function.
# Prepare the metrics.
# train_acc_metric = keras.metrics.CategoricalAccuracy()
# val_acc_metric = keras.metrics.CategoricalAccuracy()
train_mse_metric = keras.metrics.MeanSquaredError()
val_mse_metric = keras.metrics.MeanSquaredError()
train(model, optimizer, loss_fn, train_mse_metric, val_mse_metric, batch_size=wandb.config.batch_size, timesteps=wandb.config.timesteps)
sweep_id = wandb.sweep(sweep_config, project="cosine_RNN_test")
wandb.agent(sweep_id, function=sweep_train, count=20000)
| 7,089 | Python | 38.83146 | 228 | 0.598533 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/imu/mpu9250_i2c.py | import smbus
bus = smbus.SMBus(1)
# this is to be saved in the local folder under the name "mpu9250_i2c.py"
# it will be used as the I2C controller and function harbor for the project
# refer to datasheet and register map for full explanation
import smbus,time
def MPU6050_start():
# alter sample rate (stability)
samp_rate_div = 0 # sample rate = 8 kHz/(1+samp_rate_div)
bus.write_byte_data(MPU6050_ADDR, SMPLRT_DIV, samp_rate_div)
time.sleep(0.1)
# reset all sensors
bus.write_byte_data(MPU6050_ADDR,PWR_MGMT_1,0x00)
time.sleep(0.1)
# power management and crystal settings
bus.write_byte_data(MPU6050_ADDR, PWR_MGMT_1, 0x01)
time.sleep(0.1)
#Write to Configuration register
bus.write_byte_data(MPU6050_ADDR, CONFIG, 0)
time.sleep(0.1)
#Write to Gyro configuration register
gyro_config_sel = [0b00000,0b010000,0b10000,0b11000] # byte registers
gyro_config_vals = [250.0,500.0,1000.0,2000.0] # degrees/sec
gyro_indx = 0
bus.write_byte_data(MPU6050_ADDR, GYRO_CONFIG, int(gyro_config_sel[gyro_indx]))
time.sleep(0.1)
#Write to Accel configuration register
accel_config_sel = [0b00000,0b01000,0b10000,0b11000] # byte registers
accel_config_vals = [2.0,4.0,8.0,16.0] # g (g = 9.81 m/s^2)
accel_indx = 0
bus.write_byte_data(MPU6050_ADDR, ACCEL_CONFIG, int(accel_config_sel[accel_indx]))
time.sleep(0.1)
# interrupt register (related to overflow of data [FIFO])
bus.write_byte_data(MPU6050_ADDR, INT_ENABLE, 1)
time.sleep(0.1)
return gyro_config_vals[gyro_indx],accel_config_vals[accel_indx]
def read_raw_bits(register):
# read accel and gyro values
high = bus.read_byte_data(MPU6050_ADDR, register)
low = bus.read_byte_data(MPU6050_ADDR, register+1)
# combine higha and low for unsigned bit value
value = ((high << 8) | low)
# convert to +- value
if(value > 32768):
value -= 65536
return value
def mpu6050_conv():
# raw acceleration bits
acc_x = read_raw_bits(ACCEL_XOUT_H)
acc_y = read_raw_bits(ACCEL_YOUT_H)
acc_z = read_raw_bits(ACCEL_ZOUT_H)
# raw temp bits
## t_val = read_raw_bits(TEMP_OUT_H) # uncomment to read temp
# raw gyroscope bits
gyro_x = read_raw_bits(GYRO_XOUT_H)
gyro_y = read_raw_bits(GYRO_YOUT_H)
gyro_z = read_raw_bits(GYRO_ZOUT_H)
#convert to acceleration in g and gyro dps
a_x = (acc_x/(2.0**15.0))*accel_sens
a_y = (acc_y/(2.0**15.0))*accel_sens
a_z = (acc_z/(2.0**15.0))*accel_sens
w_x = (gyro_x/(2.0**15.0))*gyro_sens
w_y = (gyro_y/(2.0**15.0))*gyro_sens
w_z = (gyro_z/(2.0**15.0))*gyro_sens
## temp = ((t_val)/333.87)+21.0 # uncomment and add below in return
return a_x,a_y,a_z,w_x,w_y,w_z
def AK8963_start():
bus.write_byte_data(AK8963_ADDR,AK8963_CNTL,0x00)
time.sleep(0.1)
AK8963_bit_res = 0b0001 # 0b0001 = 16-bit
AK8963_samp_rate = 0b0110 # 0b0010 = 8 Hz, 0b0110 = 100 Hz
AK8963_mode = (AK8963_bit_res <<4)+AK8963_samp_rate # bit conversion
bus.write_byte_data(AK8963_ADDR,AK8963_CNTL,AK8963_mode)
time.sleep(0.1)
def AK8963_reader(register):
# read magnetometer values
low = bus.read_byte_data(AK8963_ADDR, register-1)
high = bus.read_byte_data(AK8963_ADDR, register)
# combine higha and low for unsigned bit value
value = ((high << 8) | low)
# convert to +- value
if(value > 32768):
value -= 65536
return value
def AK8963_conv():
# raw magnetometer bits
loop_count = 0
while 1:
mag_x = AK8963_reader(HXH)
mag_y = AK8963_reader(HYH)
mag_z = AK8963_reader(HZH)
# the next line is needed for AK8963
if bin(bus.read_byte_data(AK8963_ADDR,AK8963_ST2))=='0b10000':
break
loop_count+=1
#convert to acceleration in g and gyro dps
m_x = (mag_x/(2.0**15.0))*mag_sens
m_y = (mag_y/(2.0**15.0))*mag_sens
m_z = (mag_z/(2.0**15.0))*mag_sens
return m_x,m_y,m_z
# MPU6050 Registers
MPU6050_ADDR = 0x68
PWR_MGMT_1 = 0x6B
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
INT_ENABLE = 0x38
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
TEMP_OUT_H = 0x41
GYRO_XOUT_H = 0x43
GYRO_YOUT_H = 0x45
GYRO_ZOUT_H = 0x47
#AK8963 registers
AK8963_ADDR = 0x0C
AK8963_ST1 = 0x02
HXH = 0x04
HYH = 0x06
HZH = 0x08
AK8963_ST2 = 0x09
AK8963_CNTL = 0x0A
mag_sens = 4900.0 # magnetometer sensitivity: 4800 uT
# start I2C driver
bus = smbus.SMBus(1) # start comm with i2c bus
gyro_sens,accel_sens = MPU6050_start() # instantiate gyro/accel
# AK8963_start() # instantiate magnetometer
| 4,734 | Python | 30.151316 | 86 | 0.637093 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/examples/imu/test_sensor_visualizer.py | ###############################################
# MPU6050 9-DoF Example Printout
from mpu9250_i2c import *
time.sleep(1) # delay necessary to allow mpu9250 to settle
print('recording data')
# while 1:
# try:
# ax,ay,az,wx,wy,wz = mpu6050_conv() # read and convert mpu6050 data
# # mx,my,mz = AK8963_conv() # read and convert AK8963 magnetometer data
# except:
# continue
# print('{}'.format('-'*30))
# print('accel [g]: x = {0:2.2f}, y = {1:2.2f}, z {2:2.2f}= '.format(ax,ay,az))
# print('gyro [dps]: x = {0:2.2f}, y = {1:2.2f}, z = {2:2.2f}'.format(wx,wy,wz))
# # print('mag [uT]: x = {0:2.2f}, y = {1:2.2f}, z = {2:2.2f}'.format(mx,my,mz))
# # print('{}'.format('-'*30))
# time.sleep(0.01)
#!/usr/bin/python
"""
Update a simple plot as rapidly as possible to measure speed.
"""
import argparse
from collections import deque
from time import perf_counter
import numpy as np
import pyqtgraph as pg
import pyqtgraph.functions as fn
import pyqtgraph.parametertree as ptree
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
nsamples = 50
ax_list =[0]*nsamples
ay_list =[0]*nsamples
az_list =[0]*nsamples
gx_list =[0]*nsamples
gy_list =[0]*nsamples
gz_list =[0]*nsamples
readrate = 100
class MonkeyCurveItem(pg.PlotCurveItem):
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self.monkey_mode = ''
def setMethod(self, param, value):
self.monkey_mode = value
def paint(self, painter, opt, widget):
if self.monkey_mode not in ['drawPolyline']:
return super().paint(painter, opt, widget)
painter.setRenderHint(painter.RenderHint.Antialiasing, self.opts['antialias'])
painter.setPen(pg.mkPen(self.opts['pen']))
if self.monkey_mode == 'drawPolyline':
painter.drawPolyline(fn.arrayToQPolygonF(self.xData, self.yData))
app = pg.mkQApp("Plot Speed Test")
default_pen = pg.mkPen()
pw = pg.PlotWidget()
pw.setRange(QtCore.QRectF(0, -5, nsamples, 10))
splitter = QtWidgets.QSplitter()
splitter.addWidget(pw)
splitter.show()
pw.setWindowTitle('pyqtgraph example: PlotSpeedTest')
pw.setLabel('bottom', 'Index', units='B')
curve = MonkeyCurveItem(pen=default_pen, brush='b')
pw.addItem(curve)
rollingAverageSize = 1000
elapsed = deque(maxlen=rollingAverageSize)
def resetTimings(*args):
elapsed.clear()
# def makeData(*args):
# global data, connect_array, ptr
# # sigopts = params.child('sigopts')
# if sigopts['noise']:
# data += np.random.normal(size=data.shape)
# connect_array = np.ones(data.shape[-1], dtype=bool)
# ptr = 0
# pw.setRange(QtCore.QRectF(0, -10, nsamples, 20))
def onUseOpenGLChanged(param, enable):
pw.useOpenGL(enable)
def onEnableExperimentalChanged(param, enable):
pg.setConfigOption('enableExperimental', enable)
def onPenChanged(param, pen):
curve.setPen(pen)
def onFillChanged(param, enable):
curve.setFillLevel(0.0 if enable else None)
# params.child('sigopts').sigTreeStateChanged.connect(makeData)
# params.child('useOpenGL').sigValueChanged.connect(onUseOpenGLChanged)
# params.child('enableExperimental').sigValueChanged.connect(onEnableExperimentalChanged)
# params.child('pen').sigValueChanged.connect(onPenChanged)
# params.child('fill').sigValueChanged.connect(onFillChanged)
# params.child('plotMethod').sigValueChanged.connect(curve.setMethod)
# params.sigTreeStateChanged.connect(resetTimings)
# makeData()
fpsLastUpdate = perf_counter()
def update():
global curve, data, ptr, elapsed, fpsLastUpdate, readrate
global ax_list,ay_list,az_list,gx_list,gy_list,gz_list
t_start = perf_counter()
ax,ay,az,gx,gy,gz = mpu6050_conv() # read and convert mpu6050 data
ax_list.append(ax)
ay_list.append(ay)
az_list.append(az)
gx_list.append(gx)
gy_list.append(gy)
gz_list.append(gz)
ax_list = ax_list[1:]
ay_list = ay_list[1:]
az_list = az_list[1:]
gx_list = gx_list[1:]
gy_list = gy_list[1:]
gz_list = gz_list[1:]
# Measure
curve.setData(ax_list)
app.processEvents(QtCore.QEventLoop.ProcessEventsFlag.AllEvents)
t_end = perf_counter()
time.sleep((1/readrate)-(t_end-t_start)) # desire - currentfps
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
if __name__ == '__main__':
pg.exec()
| 4,362 | Python | 28.281879 | 89 | 0.663916 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/cfg/task/Mooncake.yaml | # used to create the object
name: Mooncake
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:32,${...num_envs}}
envSpacing: 1.0
resetDist: 3.0
maxEffort: 100
maxWheelVelocity: 0.3
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 2 # 60 Hz
# reward parameters
headingWeight: 0.5
upWeight: 0.1
# cost parameters
actionsCost: 0.01
energyCost: 0.05
dofVelocityScale: 0.1
angularVelocityScale: 0.25
contactForceScale: 0.01
jointsAtLimitCost: 0.25
deathCost: -1.0
terminationHeight: 0.25
alive_reward_scale: 2.0
sim:
dt: 0.01 # 1/100 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 33554432
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1048576
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 33554432
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
Mooncake:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,346 | YAML | 24.791209 | 71 | 0.68798 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/common.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import carb.tokens
import omni
from pxr import UsdGeom, PhysxSchema, UsdPhysics
def set_drive_parameters(drive, target_type, target_value, stiffness=None, damping=None, max_force=None):
"""Enable velocity drive for a given joint"""
if target_type == "position":
if not drive.GetTargetPositionAttr():
drive.CreateTargetPositionAttr(target_value)
else:
drive.GetTargetPositionAttr().Set(target_value)
elif target_type == "velocity":
if not drive.GetTargetVelocityAttr():
drive.CreateTargetVelocityAttr(target_value)
else:
drive.GetTargetVelocityAttr().Set(target_value)
if stiffness is not None:
if not drive.GetStiffnessAttr():
drive.CreateStiffnessAttr(stiffness)
else:
drive.GetStiffnessAttr().Set(stiffness)
if damping is not None:
if not drive.GetDampingAttr():
drive.CreateDampingAttr(damping)
else:
drive.GetDampingAttr().Set(damping)
if max_force is not None:
if not drive.GetMaxForceAttr():
drive.CreateMaxForceAttr(max_force)
else:
drive.GetMaxForceAttr().Set(max_force)
| 1,653 | Python | 34.191489 | 105 | 0.69147 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/lqr_controller.py | import numpy as np
import scipy
from scipy import linalg
import control
import math
def k_gain_calculator(Q_state,R_state):
# defined dynamics parameters
mb = 4.0
mB = 3.3155
mw = 1.098
# mB = 4.9064
# mw = 1.415
rb = 0.12
rw = 0.05
l = 0.208
Ib = 0.01165
IB = 0.3
Iw = 0.00004566491
g = -9.81
IB_xy = 0.3
Iw_xy = 0.0002770398
###############
A_mat_3_2 = -(g*(rb**4)*(l*mB + mw*rb + mw*rw)*( (mw*(rw**3)) - Iw*rb + (l*mB*(rw**2)) + (mw*rb*(rw**2)))) / ( (IB*Ib*(rw**2)) + (IB*Iw*(rb**2)) + (Ib*Iw*(rb**2)) + (Iw*mB*(rb**4)) + (Iw*mb*(rb**4)) + (Ib*mw*(rw**4)) + (4*Iw*mw*(rb**4)) + (2*Iw*l*mB*(rb**3)) + (2*Ib*mw*rb*(rw**3)) + (4*Iw*mw*(rb**3)*rw) - ((l**2)*(mB**2)*(rb**2)*(rw**2)) + (IB*mB*(rb**2)*(rw**2)) + (IB*mb*(rb**2)*(rw**2)) + (IB*mw*(rb**2)*(rw**2)) + (Ib*mw*(rb**2)*(rw**2)) + (Iw*mw*(rb**2)*(rw**2)) + (mB*mw*(rb**2)*(rw**4)) + (2*mB*mw*(rb**3)*(rw**3)) + (mB*mw*(rb**4)*(rw**2)) + (mb*mw*(rb**2)*(rw**4)) + (2*mb*mw*(rb**3)*(rw**3)) + (mb*mw*(rb**4)*(rw**2)) - (2*l*mB*mw*(rb**2)*(rw**3)) - (2*l*mB*mw*(rb**3)*(rw**2)))
A_mat_4_2 = (g*(l*mB + mw*rb + mw*rw)*( (Ib*(rw**2)) + (Iw*(rb**2)) + (mB*(rb**2)*(rw**2)) + (mb*(rb**2)*(rw**2)) + (mw*(rb**2)*(rw**2))))/( (IB*Ib*(rw**2)) + (IB*Iw*(rb**2)) + (Ib*Iw*(rb**2)) + (Iw*mB*(rb**4)) + (Iw*mb*(rb**4)) + (Ib*mw*(rw**4)) + (4*Iw*mw*(rb**4)) + (2*Iw*l*mB*(rb**3)) + (2*Ib*mw*rb*(rw**3)) + (4*Iw*mw*(rb**3)*rw) - ((l**2)*(mB**2)*(rb**2)*(rw**2)) + (IB*mB*(rb**2)*(rw**2)) + (IB*mb*(rb**2)*(rw**2)) + (IB*mw*(rb**2)*(rw**2)) + (Ib*mw*(rb**2)*(rw**2)) + (Iw*mw*(rb**2)*(rw**2)) + (mB*mw*(rb**2)*(rw**4)) + (2*mB*mw*(rb**3)*(rw**3)) + (mB*mw*(rb**4)*(rw**2)) + (mb*mw*(rb**2)*(rw**4)) + (2*mb*mw*(rb**3)*(rw**3)) + (mb*mw*(rb**4)*(rw**2)) - (2*l*mB*mw*(rb**2)*(rw**3)) - (2*l*mB*mw*(rb**3)*(rw**2)))
B_mat_3 = ((rb**2)*rw*( (2*mw*(rb**2)) + (3*mw*rb*rw) + (l*mB*rb) + (mw*rw**2) + IB))/( (IB*Ib*(rw**2)) + (IB*Iw*(rb**2)) + (Ib*Iw*(rb**2)) + (Iw*mB*(rb**4)) + (Iw*mb*(rb**4)) + (Ib*mw*(rw**4)) + (4*Iw*mw*(rb**4)) + (2*Iw*l*mB*(rb**3)) + (2*Ib*mw*rb*(rw**3)) + (4*Iw*mw*(rb**3)*rw) - ((l**2)*(mB**2)*(rb**2)*(rw**2)) + (IB*mB*(rb**2)*(rw**2)) + (IB*mb*(rb**2)*(rw**2)) + (IB*mw*(rb**2)*(rw**2)) + (Ib*mw*(rb**2)*(rw**2)) + (Iw*mw*(rb**2)*(rw**2)) + (mB*mw*(rb**2)*(rw**4)) + (2*mB*mw*(rb**3)*(rw**3)) + (mB*mw*(rb**4)*(rw**2)) + (mb*mw*rb**2*rw**4) + (2*mb*mw*(rb**3)*(rw**3)) + (mb*mw*(rb**4)*(rw**2)) - (2*l*mB*mw*(rb**2)*(rw**3)) - (2*l*mB*mw*(rb**3)*(rw**2)))
B_mat_4 = -(rb*rw*(Ib + (mB*(rb**2)) + (mb*(rb**2)) + (2*mw*rb**2) + (l*mB*rb) + (mw*rb*rw)))/((IB*Ib*(rw**2)) + (IB*Iw*(rb**2)) + (Ib*Iw*(rb**2)) + (Iw*mB*(rb**4)) + (Iw*mb*(rb**4)) + (Ib*mw*(rw**4)) + (4*Iw*mw*(rb**4)) + (2*Iw*l*mB*(rb**3)) + 2*Ib*mw*rb*rw**3 + 4*Iw*mw*rb**3*rw - l**2*mB**2*rb**2*rw**2 + IB*mB*rb**2*rw**2 + IB*mb*rb**2*rw**2 + IB*mw*rb**2*rw**2 + Ib*mw*rb**2*rw**2 + Iw*mw*rb**2*rw**2 + mB*mw*rb**2*rw**4 + 2*mB*mw*rb**3*rw**3 + mB*mw*rb**4*rw**2 + mb*mw*rb**2*rw**4 + 2*mb*mw*rb**3*rw**3 + mb*mw*rb**4*rw**2 - 2*l*mB*mw*rb**2*rw**3 - 2*l*mB*mw*rb**3*rw**2)
B_mat_xy = (-rb/( (IB_xy*rw**2) + (mw*rw**2*(rb+rw)**2 + (Iw_xy*rb**2))))
A_sys = np.array([ [0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, A_mat_3_2, 0, 0, 0, 0, 0, 0],
[A_mat_3_2, 0, 0, 0, 0, 0, 0, 0],
[0, A_mat_4_2, 0, 0, 0, 0, 0, 0],
[A_mat_4_2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0] ])
B_sys =np.array([ [0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[B_mat_3, 0, 0],
[0, B_mat_3, 0],
[B_mat_4, 0, 0],
[0, B_mat_4, 0],
[0, 0, B_mat_xy]])
C_sys = np.eye(8)
D_sys = np.zeros((8,3))
# Q_state = np.array([5, 5, 5, 30, 30, 30, 30, 30])
# R_state = np.array([10, 10, 10])
Q = np.eye(8) * Q_state
R = np.eye(3) * R_state
K, S, E = control.lqr(A_sys, B_sys, Q, R)
# print("A_sys =", A_sys)
# print("B_sys =", B_sys)
# print("C_sys =", C_sys)
# print("D_sys =", D_sys)
# print("K =", K)
# print(2*5**2*3*2)
return K
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return [roll_x, pitch_y, yaw_z] # in radians
def lqr_controller(x_ref,x_fb,K):
u= K @ (x_ref-x_fb)
return u
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return [roll_x, pitch_y, yaw_z] # in radians
def ball_velocity(pre_vel,now_vel,dt):
v = (now_vel-pre_vel)/dt
return v
def Txyz2wheel(Txyz):
alpha = 50.0*np.pi/180.0 # wheelaxis_theta
Twheels = np.array([[-np.cos(alpha) , 0 , -np.sin(alpha)],
[np.cos(alpha)/2 , -np.sqrt(3)*np.cos(alpha)/2 , -np.sin(alpha)],
[np.cos(alpha)/2 , np.sqrt(3)*np.cos(alpha)/2, -np.sin(alpha)]]) @ Txyz # -x axis
# Twheels = np.array([[ np.cos(alpha) , 0 , -np.sin(alpha)],
# [-np.cos(alpha)/2 , np.sqrt(3)*np.cos(alpha)/2 , -np.sin(alpha)],
# [-np.cos(alpha)/2 , -np.sqrt(3)*np.cos(alpha)/2, -np.sin(alpha)]]) @ Txyz # x axis
return Twheels | 6,666 | Python | 54.099173 | 724 | 0.419442 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/import_mooncake.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import torch
from torch import roll
import omni
import omni.kit.commands
import omni.usd
import omni.client
import asyncio
import math
import weakref
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
from omni.isaac.isaac_sensor import _isaac_sensor
from omni.isaac.core.prims import RigidPrimView
from .common import set_drive_parameters
from pxr import UsdLux, Sdf, Gf, UsdPhysics, Usd, UsdGeom
from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder
from omni.isaac.core.utils.prims import get_prim_at_path
EXTENSION_NAME = "Import Mooncake"
def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None):
""" Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path.
Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
"""
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
edits = Sdf.BatchNamespaceEdit()
while len(prims) > 0:
prim = prims.pop(0)
print(prim)
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform")
print(prim, new_xform)
edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0))
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
stage.GetRootLayer().Apply(edits)
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
def velocity2omega(v_x, v_y, w_z=0, d=0.105, r=0.1):
omega_0 = (v_x-d*w_z)/r
omega_1 = -(v_x-math.sqrt(3)*v_y+2*d*w_z)/(2*r)
omega_2 = -(v_x+math.sqrt(3)*v_y+2*d*w_z)/(2*r)
return [omega_0, omega_1, omega_2]
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
MenuItemDescription(name="Mooncake URDF", onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a Mooncake Robot via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This Example shows you import an NVIDIA Mooncake robot via URDF.\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a Mooncake Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Spin Robot",
"type": "button",
"text": "move",
"tooltip": "Spin the Robot in Place",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_mooncake(load_stage))
async def _load_mooncake(self, task):
done, pending = await asyncio.wait({task})
if task in done:
viewport = omni.kit.viewport_legacy.get_default_viewport_window()
viewport.set_camera_position("/OmniverseKit_Persp", -1.02, 1.26, 0.5, True)
viewport.set_camera_target("/OmniverseKit_Persp", 2.20, -2.18, -1.60, True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
result, plane_path = omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=stage,
planePath="/groundPlane",
axis="Z",
size=1500.0,
position=Gf.Vec3f(0, 0, 0),
color=Gf.Vec3f(0.5),
)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.import_inertia_tensor = False
# import_config.distance_scale = 100
import_config.fix_base = False
import_config.set_make_instanceable(True)
# import_config.set_instanceable_usd_path("./mooncake_instanceable.usd")
import_config.set_instanceable_usd_path("omniverse://localhost/Library/Robots/mooncake/mooncake_instanceable.usd")
import_config.set_default_drive_type(2) # 0=None, 1=position, 2=velocity
import_config.make_default_prim = True
import_config.create_physics_scene = True
result, robot_path = omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/mooncake/urdf/mooncake.urdf",
import_config=import_config,
dest_path="omniverse://localhost/Library/Robots/mooncake/mooncake.usd"
)
# convert_asset_instanceable(asset_usd_path=, # USD file path to the current existing USD asset
# source_prim_path=, # USD prim path of root prim of the asset
# save_as_path=None, # USD file path for modified USD stage. Defaults to None, will save in same file.
# create_xforms=True)
# create_parent_xforms(
# asset_usd_path='omniverse://localhost/Library/Robots/mooncake.usd',
# source_prim_path="/mooncake",
# save_as_path='omniverse://localhost/Library/Robots/mooncake_instanceable.usd'
# )
# make sure the ground plane is under root prim and not robot
# omni.kit.commands.execute(
# "MovePrimCommand", path_from=robot_path, path_to="/mooncake", keep_world_transform=True
# )
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# Make all rollers spin freely by removing extra drive API
for wheel_index in range(3):
for plate_index in range(2):
for roller_index in range(9):
prim_path = "/mooncake/wheel_{}/roller_{}_{}_{}_joint".format(wheel_index, wheel_index, plate_index, roller_index)
prim = stage.GetPrimAtPath(prim_path)
omni.kit.commands.execute(
"UnapplyAPISchemaCommand",
api=UsdPhysics.DriveAPI,
prim=prim,
api_prefix="drive",
multiple_api_token="angular",
)
## Attact IMU sensor ##
self._is = _isaac_sensor.acquire_imu_sensor_interface()
self.body_path = "/mooncake/base_plate"
result, sensor = omni.kit.commands.execute(
"IsaacSensorCreateImuSensor",
path="/sensor",
parent=self.body_path,
sensor_period=1 / 500.0, # 2ms
translation=Gf.Vec3d(0, 0, 17.15), # translate to surface of /mooncake/top_plate
orientation=Gf.Quatd(1, 0, 0, 0), # (x, y, z, w)
visualize=True,
)
omni.kit.commands.execute('ChangeProperty',
prop_path=Sdf.Path('/mooncake.xformOp:translate'),
value=Gf.Vec3d(0.0, 0.0, 0.3162),
prev=Gf.Vec3d(0.0, 0.0, 0.0))
# Set Damping & Stiffness
# Position Control: for position controlled joints, set a high stiffness and relatively low or zero damping.
# Velocity Control: for velocity controller joints, set a high damping and zero stiffness.
# omni.kit.commands.execute('ChangeProperty',
# prop_path=Sdf.Path(
# '/mooncake/base_plate/wheel_0_joint.drive:angular:physics:stiffness'),
# value=0.0,
# prev=10000000.0)
# omni.kit.commands.execute('ChangeProperty',
# prop_path=Sdf.Path(
# '/mooncake/base_plate/wheel_1_joint.drive:angular:physics:stiffness'),
# value=0.0,
# prev=10000000.0)
# omni.kit.commands.execute('ChangeProperty',
# prop_path=Sdf.Path('/mooncake/base_plate/wheel_2_joint.drive:angular:physics:stiffness'),
# value=0.0,
# prev=10000000.0)
###############
# Create Ball #
###############
# result, ball_path = omni.kit.commands.execute(
# "CreatePrimWithDefaultXform",
# prim_type="Sphere",
# attributes={'radius':0.12},
# select_new_prim=True
# )
# omni.kit.commands.execute("MovePrimCommand", path_from='/mooncake/Sphere', path_to='/mooncake/ball')
# omni.kit.commands.execute('ChangeProperty',
# prop_path=Sdf.Path('/mooncake/ball.xformOp:translate'),
# value=Gf.Vec3d(0.0, 0.0, -0.1962),
# prev=Gf.Vec3d(0.0, 0.0, 0.0))
# omni.kit.commands.execute('SetRigidBody',
# path=Sdf.Path('/mooncake/ball'),
# approximationShape='convexHull',
# kinematic=False)
#
# omni.kit.commands.execute('AddPhysicsComponent',
# usd_prim=get_prim_at_path('/mooncake/ball'),
# component='PhysicsMassAPI')
# # omni.kit.commands.execute('ApplyAPISchema',
# # api= 'pxr.UsdPhysics.MassAPI',
# # prim=get_prim_at_path('/mooncake/ball'))
# omni.kit.commands.execute('ChangeProperty',
# prop_path=Sdf.Path('/mooncake/ball.physics:mass'),
# value=4.0,
# prev=0.0)
## USE 3 IMUs ##
# result, sensor = omni.kit.commands.execute(
# "IsaacSensorCreateImuSensor",
# path="/sensor0",
# parent=self.body_path,
# sensor_period=1 / 500.0, # 2ms
# offset=Gf.Vec3d(0, 15, 17.15), # translate to upper surface of /mooncake/top_plate
# orientation=Gf.Quatd(1, 0, 0, 0), # (x, y, z, w)
# visualize=True,
# )
# result, sensor = omni.kit.commands.execute(
# "IsaacSensorCreateImuSensor",
# path="/sensor1",
# parent=self.body_path,
# sensor_period=1 / 500.0, # 2ms
# offset=Gf.Vec3d(15*math.sqrt(3)/2, -15/2, 17.15), # translate to surface of /mooncake/top_plate
# orientation=Gf.Quatd(1, 0, 0, 0), # (x, y, z, w)
# visualize=True,
# )
# result, sensor = omni.kit.commands.execute(
# "IsaacSensorCreateImuSensor",
# path="/sensor2",
# parent=self.body_path,
# sensor_period=1 / 500.0, # 2ms
# offset=Gf.Vec3d(-15*math.sqrt(3)/2, -15/2, 17.15), # translate to surface of /mooncake/top_plate
# orientation=Gf.Quatd(1, 0, 0, 0), # (x, y, z, w)
# visualize=True,
# )
def _on_config_drives(self):
# self._on_config_robot() # make sure drives are configured first
stage = omni.usd.get_context().get_stage()
# set each axis to spin at a rate of 1 rad/s
axle_0 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/mooncake/base_plate/wheel_0_joint"), "angular")
axle_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/mooncake/base_plate/wheel_1_joint"), "angular")
axle_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/mooncake/base_plate/wheel_2_joint"), "angular")
omega = velocity2omega(0, 0.1, 0)
print(omega)
set_drive_parameters(axle_0, "velocity", math.degrees(omega[0]), 0, math.radians(1e7))
set_drive_parameters(axle_1, "velocity", math.degrees(omega[1]), 0, math.radians(1e7))
set_drive_parameters(axle_2, "velocity", math.degrees(omega[2]), 0, math.radians(1e7))
| 15,614 | Python | 46.752293 | 152 | 0.546433 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/test.py | # import omni.isaac.core.utils.torch.rotations as torch_rot
import torch
import torch.nn.functional as f
def normalize(x, eps: float = 1e-9):
return x / x.norm(p=2, dim=-1).clamp(min=eps, max=None).unsqueeze(-1)
def quat_unit(a):
return normalize(a)
def quat_mul(a, b):
assert a.shape == b.shape
shape = a.shape
a = a.reshape(-1, 4)
b = b.reshape(-1, 4)
w1, x1, y1, z1 = a[:, 0], a[:, 1], a[:, 2], a[:, 3]
w2, x2, y2, z2 = b[:, 0], b[:, 1], b[:, 2], b[:, 3]
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
quat = torch.stack([w, x, y, z], dim=-1).view(shape)
return quat
def quat_conjugate(a):
shape = a.shape
a = a.reshape(-1, 4)
return torch.cat((a[:, 0:1], -a[:, 1:]), dim=-1).view(shape)
def quat_diff_rad(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""
Get the difference in radians between two quaternions.
Args:
a: first quaternion, shape (N, 4)
b: second quaternion, shape (N, 4)
Returns:
Difference in radians, shape (N,)
"""
b_conj = quat_conjugate(b)
mul = quat_mul(a, b_conj)
# 2 * torch.acos(torch.abs(mul[:, -1]))
return 2.0 * torch.asin(torch.clamp(torch.norm(mul[:, 1:], p=2, dim=-1), max=1.0))
def q2falling(q):
# q = f.normalize(q, p=1, dim=1)
norm_vec = f.normalize(q[:, 1:], p=1, dim=1)
print(norm_vec)
return 2 * torch.acos(q[:, 0]) * torch.sqrt((norm_vec[:, 0]*norm_vec[:, 0]+norm_vec[:, 1]*norm_vec[:, 1]))
# return 2*torch.asin(torch.norm(torch.mul(robots_orientation[:, 1:], up_vectors[:, 1:])))
# return quat_diff_rad(robots_orientation, up_vectors)
test_a = torch.zeros((1, 4))
test_a[:, 0] = 1
test_b = torch.zeros_like(test_a)
test_b[:, 0] = 0.71
test_b[:, 3] = 0.71
# print(quat_diff_rad(test_a, test_b))
print(q2falling(test_b)/3.14*180)
test_b = torch.zeros_like(test_a)
test_b[:, 0] = 0.71
test_b[:, 2] = 0.71
print(q2falling(test_b)/3.14*180)
test_b = torch.zeros_like(test_a)
test_b[:, 0] = 0.71
test_b[:, 1] = 0.71
print(q2falling(test_b)/3.14*180)
test_b = torch.zeros_like(test_a)
test_b[:, 0] = 0.64
test_b[:, 3] = 0.77
print(q2falling(test_b)/3.14*180) | 2,416 | Python | 29.987179 | 110 | 0.550083 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/import_ball.py | #launch Isaac Sim before any other imports
#default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False}) # we can also run as headless.
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicSphere
import numpy as np
world = World()
world.scene.add_default_ground_plane()
ball = world.scene.add(
DynamicSphere(
prim_path="/ball",
name="ball",
position=np.array([0, 0, 0.12]),
radius=0.12, # mediciene ball diameter 24cm.
color=np.array([1.0, 0, 0]),
mass=4,
)
)
# Resetting the world needs to be called before querying anything related to an articulation specifically.
# Its recommended to always do a reset after adding your assets, for physics handles to be propagated properly
world.reset()
while True:
# position, orientation = fancy_cube.get_world_pose()
# linear_velocity = fancy_cube.get_linear_velocity()
# # will be shown on terminal
# print("Cube position is : " + str(position))
# print("Cube's orientation is : " + str(orientation))
# print("Cube's linear velocity is : " + str(linear_velocity))
# # we have control over stepping physics and rendering in this workflow
# # things run in sync
world.step(render=True) # execute one physics step and one rendering step
simulation_app.close() # close Isaac Sim | 1,485 | Python | 40.277777 | 110 | 0.674074 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/hello_rl.py | import gym
from stable_baselines3 import A2C
env = gym.make('CartPole-v1')
model = A2C('MlpPolicy', env, verbose=1)
model.learn(total_timesteps=10000)
obs = env.reset()
for i in range(1000):
action, _state = model.predict(obs, deterministic=True)
obs, reward, done, info = env.step(action)
env.render()
if done:
obs = env.reset() | 355 | Python | 21.249999 | 59 | 0.676056 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/log2graph.py | import matplotlib.pyplot as plt
import pandas as pd
plt.xlim([0, 500000])
plt.ylim([0, 6000])
fig=plt.figure()
d = {}
for i, filename in enumerate(['log_11111', 'log_01111', 'log_10111', 'log_11011', 'log_11101', 'log_11110']):
# path = "F:/mooncake_policy_01111/log.txt"
f = open('log/'+filename+'.txt')
lines = f.readlines()
topic = lines[0][:-1]
lines = lines[1:]
ax=fig.add_subplot(6, 1, i+1)
# ax = plt.subplot(6, 1, i+1)
# ax.set_xlim(xmin=0.0, xmax=500000)
ax.set_ylim(ymin=0.0, ymax=600)
ax.xaxis.set_major_locator(plt.MaxNLocator(10))
ax.yaxis.set_major_locator(plt.MaxNLocator(10))
X, Y = [], []
for line in lines:
[x, y] = line[:-1].split('\t')
X.append(x)
Y.append(y)
ax.plot(X, Y)
d[topic+'x'] = X.copy()
d[topic+'y'] = Y.copy()
plt.show()
df = pd.DataFrame(data=d)
df.to_csv('log.csv') | 885 | Python | 27.580644 | 109 | 0.579661 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/rl_luna_lander.py | import gym
from stable_baselines3 import DQN
from stable_baselines3.common.evaluation import evaluate_policy
# Create environment
env = gym.make('LunarLander-v2')
# Instantiate the agent
model = DQN('MlpPolicy', env, verbose=1)
# Train the agent
model.learn(total_timesteps=int(2e5))
# Save the agent
model.save("dqn_lunar")
del model # delete trained model to demonstrate loading
# Load the trained agent
# NOTE: if you have loading issue, you can pass `print_system_info=True`
# to compare the system on which the model was trained vs the current one
# model = DQN.load("dqn_lunar", env=env, print_system_info=True)
model = DQN.load("dqn_lunar", env=env)
# Evaluate the agent
# NOTE: If you use wrappers with your environment that modify rewards,
# this will be reflected here. To evaluate with original rewards,
# wrap environment in a "Monitor" wrapper before other wrappers.
mean_reward, std_reward = evaluate_policy(model, model.get_env(), n_eval_episodes=10)
# Enjoy trained agent
obs = env.reset()
for i in range(1000):
action, _states = model.predict(obs, deterministic=True)
obs, rewards, dones, info = env.step(action)
env.render() | 1,174 | Python | 32.571428 | 85 | 0.739353 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/test/test2.py | import ray
from ray.rllib.agents.ppo import PPOTrainer
ray.init() # Skip or set to ignore if already called
config = {'gamma': 0.9,
'lr': 1e-2,
'num_workers': 4,
'train_batch_size': 1000,
'model': {
'fcnet_hiddens': [128, 128]
}}
trainer = PPOTrainer(env='CartPole-v0', config=config)
for i in range(100):
print(trainer.train()) | 396 | Python | 29.538459 | 54 | 0.575758 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/test/test3.py | # from env import MoonCakeEnv
import ray
import ray.rllib.agents.ppo as ppo
import shutil, os
CHECKPOINT_ROOT = "tmp/ppo/taxi"
shutil.rmtree(CHECKPOINT_ROOT, ignore_errors=True, onerror=None)
ray_results = os.getenv("HOME") + "/ray_results/"
shutil.rmtree(ray_results, ignore_errors=True, onerror=None)
ray.shutdown()
ray.init(ignore_reinit_error=True)
SELECT_ENV = "Taxi-v3"
config = ppo.DEFAULT_CONFIG.copy()
config["log_level"] = "WARN"
agent = ppo.PPOTrainer(config, env=SELECT_ENV)
N_ITER = 30
s = "{:3d} reward {:6.2f}/{:6.2f}/{:6.2f} len {:6.2f} saved {}"
for n in range(N_ITER):
result = agent.train()
file_name = agent.save(CHECKPOINT_ROOT)
print(s.format(
n + 1,
result["episode_reward_min"],
result["episode_reward_mean"],
result["episode_reward_max"],
result["episode_len_mean"],
file_name
)) | 845 | Python | 23.171428 | 64 | 0.680473 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/scripts/test/test.py | # Import the RL algorithm (Trainer) we would like to use.
from ray.rllib.agents.ppo import PPOTrainer
# Configure the algorithm.
config = {
# Environment (RLlib understands openAI gym registered strings).
"env": "Taxi-v3",
# Use 2 environment workers (aka "rollout workers") that parallelly
# collect samples from their own environment clone(s).
"num_workers": 2,
# Change this to "framework: torch", if you are using PyTorch.
# Also, use "framework: tf2" for tf2.x eager execution.
"framework": "tf",
# Tweak the default model provided automatically by RLlib,
# given the environment's observation- and action spaces.
"model": {
"fcnet_hiddens": [64, 64],
"fcnet_activation": "relu",
},
# Set up a separate evaluation worker set for the
# `trainer.evaluate()` call after training (see below).
"evaluation_num_workers": 1,
# Only for evaluation runs, render the env.
"evaluation_config": {
"render_env": True,
},
}
# Create our RLlib Trainer.
trainer = PPOTrainer(config=config)
# Run it for n training iterations. A training iteration includes
# parallel sample collection by the environment workers as well as
# loss calculation on the collected batch and a model update.
for _ in range(30):
print(trainer.train())
# Evaluate the trained Trainer (and render each timestep to the shell's
# output).
trainer.evaluate()
| 1,423 | Python | 33.731706 | 71 | 0.690794 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/mooncake/environments/env_mooncake_vector.py | import gym
from gym import spaces
import numpy as np
import math
import time
import carb
from omni.isaac.imu_sensor import _imu_sensor
| 137 | Python | 12.799999 | 45 | 0.80292 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/obike_task.py | import time
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from obike import Obike
import omni
from pxr import Gf, UsdGeom
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path, get_all_matching_child_prims
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omni.isaac.core.utils.torch.maths import torch_rand_float, tensor_clamp, unscale
from omni.isaac.isaac_sensor import _isaac_sensor
import numpy as np
import torch
import math
import random
def euler_to_quaternion(r):
(roll, pitch, yaw) = (r[0], r[1], r[2])
qx = np.sin(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) - np.cos(roll/2) * np.sin(pitch/2) * np.sin(yaw/2)
qy = np.cos(roll/2) * np.sin(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.cos(pitch/2) * np.sin(yaw/2)
qz = np.cos(roll/2) * np.cos(pitch/2) * np.sin(yaw/2) - np.sin(roll/2) * np.sin(pitch/2) * np.cos(yaw/2)
qw = np.cos(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.sin(pitch/2) * np.sin(yaw/2)
return [qx, qy, qz, qw]
def q2falling(q):
fall_angle = 2*torch.acos(q[:,0])*torch.sqrt((q[:,1]*q[:,1] + q[:,2]*q[:,2])/(q[:,1]*q[:,1]) + q[:,2]*q[:,2] + q[:,3]*q[:,3])
return fall_angle
class ObikeTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._robot_positions = torch.tensor([0.0, 0.0, 0.0167])
self._reset_dist = self._task_cfg["env"]["resetDist"]
self._max_push_effort = self._task_cfg["env"]["maxEffort"]
self._max_episode_length = 500
self._num_observations = 4
self._num_actions = 1
self._imu_buf = [{"lin_acc_x":0.0, "lin_acc_y":0.0, "lin_acc_z":0.0, "ang_vel_x":0.0, "ang_vel_y":0.0, "ang_vel_z":0.0}]*128 # default initial sensor buffer
self._is = _isaac_sensor.acquire_imu_sensor_interface() # Sensor reader
RLTask.__init__(self, name, env)
return
def set_up_scene(self, scene) -> None:
self.get_obike() # mush be called before "super().set_up_scene(scene)"
super().set_up_scene(scene)
print(get_all_matching_child_prims("/"))
self._robots = ArticulationView(prim_paths_expr="/World/envs/*/Obike/obike", name="obike_view")
scene.add(self._robots)
self.meters_per_unit = UsdGeom.GetStageMetersPerUnit(omni.usd.get_context().get_stage())
return
def get_obike(self): # must be called at very first line of set_up_scene()
obike = Obike(prim_path=self.default_zero_env_path + "/Obike", name="Obike", translation=self._robot_positions)
# applies articulation settings from the task configuration yaml file
self._sim_config.apply_articulation_settings("Obike", get_prim_at_path(obike.prim_path), self._sim_config.parse_actor_config("Obike"))
def get_robot(self):
return self._robots
def get_observations(self) -> dict:
# dof_pos = self._robots.get_joint_positions(clone=False)
dof_vel = self._robots.get_joint_velocities(clone=False)
reaction_vel = dof_vel[:, self._reaction_wheel_dof_idx]
imu_accel_y = torch.tensor([imu["lin_acc_y"] for imu in self._imu_buf])
imu_accel_z = torch.tensor([imu["lin_acc_z"] for imu in self._imu_buf])
imu_gyro_x = torch.tensor([imu["ang_vel_x"] for imu in self._imu_buf])
self.obs_buf[:, 0] = reaction_vel
self.obs_buf[:, 1] = imu_accel_y
self.obs_buf[:, 2] = imu_accel_z
self.obs_buf[:, 3] = imu_gyro_x
observations = {
self._robots.name: {
"obs_buf": self.obs_buf
}
}
# print(observations)
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
actions = actions.to(self._device)
actions = 2*(actions - 0.5)
forces = torch.zeros((self._robots.count, self._robots.num_dof), dtype=torch.float32, device=self._device)
forces[:, self._reaction_wheel_dof_idx] = self._max_push_effort * actions[:, 0]
indices = torch.arange(self._robots.count, dtype=torch.int32, device=self._device)
self._robots.set_joint_efforts(forces, indices=indices) # apply joints torque
## Read IMU & store in buffer ##
buffer = []
robots_prim_path = self._robots.prim_paths
for robot_prim_path in robots_prim_path:
reading = self._is.get_sensor_readings(robot_prim_path + "/chassic/sensor") # read from select sensor (by prim_path)
if reading.shape[0]:
buffer.append(reading[-1]) # get only lastest reading
else: buffer.append({"lin_acc_x":0.0, "lin_acc_y":0.0, "lin_acc_z":0.0, "ang_vel_x":0.0, "ang_vel_y":0.0, "ang_vel_z":0.0}) # default initial sensor buffer
self._imu_buf = buffer
def reset_idx(self, env_ids):
num_resets = len(env_ids)
# randomize DOF velocities
dof_vel = torch_rand_float(-0.1, 0.1, (num_resets, 1), device=self._device)
# apply resets
self._robots.set_joint_velocities(dof_vel, indices=env_ids)
root_pos, root_rot = self.initial_root_pos[env_ids], self.initial_root_rot[env_ids]
root_vel = torch.zeros((num_resets, 6), device=self._device)
self._robots.set_world_poses(root_pos, root_rot, indices=env_ids)
self._robots.set_velocities(root_vel, indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self): # Run only once after simulation started
# self._robots = self.get_robot()
self.initial_root_pos, self.initial_root_rot = self._robots.get_world_poses() # save initial position for reset
self.initial_dof_pos = self._robots.get_joint_positions()
# initialize some data used later on
self.start_rotation = torch.tensor([1, 0, 0, 0], device=self._device, dtype=torch.float32)
self.up_vec = torch.tensor([0, 0, 1], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.heading_vec = torch.tensor([1, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.inv_start_rot = quat_conjugate(self.start_rotation).repeat((self.num_envs, 1))
self.basis_vec0 = self.heading_vec.clone()
self.basis_vec1 = self.up_vec.clone()
self._reaction_wheel_dof_idx = self._robots.get_dof_index("reaction_wheel_joint")
self._rear_wheel_dof_idx = self._robots.get_dof_index("rear_wheel_joint")
self._steering_arm_dof_idx = self._robots.get_dof_index("front_wheel_arm_joint")
# randomize all envs
indices = torch.arange(self._robots.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None: # calculate reward for each env
reaction_vel = self.obs_buf[:, 0]
robots_position, robots_orientation = self._robots.get_world_poses()
fall_angles = q2falling(robots_orientation) # find fall angle of all robot (batched)
# cart_pos = self.obs_buf[:, 0]
# cart_vel = self.obs_buf[:, 1]
# pole_angle = self.obs_buf[:, 2]
# pole_vel = self.obs_buf[:, 3]
# reward = 1.0 - pole_angle * pole_angle - 0.01 * torch.abs(cart_vel) - 0.005 * torch.abs(pole_vel)
# reward = torch.where(torch.abs(cart_pos) > self._reset_dist, torch.ones_like(reward) * -2.0, reward)
# reward = torch.where(torch.abs(pole_angle) > np.pi / 2, torch.ones_like(reward) * -2.0, reward)
reward = 1.0 - fall_angles * fall_angles - 0.01 * torch.abs(reaction_vel)
reward = torch.where(torch.abs(fall_angles) > 25*(np.pi / 180), torch.ones_like(reward) * -2.0, reward) # fall_angle must <= 25 degree
self.rew_buf[:] = reward
def is_done(self) -> None: # check termination for each env
robots_position, robots_orientation = self._robots.get_world_poses()
fall_angles = q2falling(robots_orientation) # find fall angle of all robot (batched)
# cart_pos = self.obs_buf[:, 0]
# pole_pos = self.obs_buf[:, 2]
# resets = torch.where(torch.abs(cart_pos) > self._reset_dist, 1, 0)
# resets = torch.where(torch.abs(pole_pos) > math.pi / 2, 1, resets)
# resets = torch.where(self.progress_buf >= self._max_episode_length, 1, resets)
resets = torch.where(torch.abs(fall_angles) > 25*(np.pi / 180), 1, 0) # reset by falling
resets = torch.where(self.progress_buf >= self._max_episode_length, 1, resets) # reset by time
self.reset_buf[:] = resets
| 9,113 | Python | 45.030303 | 168 | 0.617799 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/test.py | import time
import tensorflow as tf
import random
from env_obike import ObikeEnv
env = ObikeEnv(headless=False)
state = env.reset()
print(state)
with tf.GradientTape() as tape:
while True:
state, reward, done, _ = env.step(action=0.5)
print(state, reward, done)
if done:
state = env.reset()
print(state) | 355 | Python | 24.42857 | 53 | 0.639437 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/obike.py | from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_server_path
from omni.isaac.core.utils.stage import add_reference_to_stage
import carb
class Obike(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Obike",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
server_path = get_server_path()
if server_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = server_path + "/Library/obike.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
) | 1,116 | Python | 30.027777 | 72 | 0.58871 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/train_obike_lstm_Karn.py | import gym
from gym import spaces
import numpy as np
import math
import time
import carb
from omni.isaac.kit import SimulationApp
from omni.isaac.imu_sensor import _imu_sensor
def discount_rewards(r, gamma=0.8):
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size)):
running_add = running_add * gamma + r[t]
discounted_r[t] = running_add
return discounted_r
def q2falling(q):
q[0] = 1 if q[0] > 1 else q[0]
try:
if q[1] == 0 and q[2] == 0 and q[3] == 0:
return 0
return 2*math.acos(q[0])*math.sqrt((q[1]**2 + q[2]**2)/(q[1]**2 + q[2]**2 + q[3]**2))
except:
print(q)
return 0
def omni_unit2_sensor_unit(observations):
observations[0] = observations[0] / 981.0
observations[1] = observations[1] / 981.0
observations[2] = ( observations[2] * 180.0 ) / math.pi
return observations
def sensor_unit2_omni_unit(observations):
observations[0] = observations[0] * 981.0
observations[1] = observations[1] * 981.0
observations[2] = ( observations[2] * math.pi ) / 180.0
return observations
## Specify simulation parameters ##
_physics_dt = 1/100
_rendering_dt = 1/30
_max_episode_length = 60/_physics_dt # 60 second after reset
_iteration_count = 0
_display_every_iter = 1
_update_every = 1
_headless = False
simulation_app = SimulationApp({"headless": _headless, "anti_aliasing": 0})
## Setup World ##
from omni.isaac.core import World
from obike_old import Obike
# from omni.isaac.core.objects import DynamicSphere
world = World(physics_dt=_physics_dt, rendering_dt=_rendering_dt, stage_units_in_meters=0.01)
world.scene.add_default_ground_plane()
robot = world.scene.add(
Obike(
prim_path="/obike",
name="obike_mk0",
position=np.array([0, 0.0, 1.435]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
## Setup IMU ##
imu_interface = _imu_sensor.acquire_imu_sensor_interface()
props = _imu_sensor.SensorProperties()
props.position = carb.Float3(0, 0, 10) # translate from /obike/chassic to above motor (cm.)
props.orientation = carb.Float4(0, 0, 0, 1) # (x, y, z, w)
props.sensorPeriod = 1 / 500 # 2ms
_sensor_handle = imu_interface.add_sensor_on_body("/obike/chassic", props)
## Create LSTM Model ##
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
## Train parameter ##
n_episodes = 10000
input_dim = 3
output_dim = 1
num_timesteps = 1
batch_size = 1
lstm_nodes = 32
input_layer = tf.keras.Input(shape=(num_timesteps, input_dim), batch_size=batch_size)
lstm_cell = tf.keras.layers.LSTMCell(
lstm_nodes,
kernel_initializer='glorot_uniform',
recurrent_initializer='glorot_uniform',
bias_initializer='zeros',
)
lstm_layer = tf.keras.layers.RNN(
lstm_cell,
return_state=True,
return_sequences=True,
stateful=True,
)
lstm_out, hidden_state, cell_state = lstm_layer(input_layer)
output = tf.keras.layers.Dense(output_dim)(lstm_out)
model = tf.keras.Model(
inputs=input_layer,
outputs=[hidden_state, cell_state, output]
)
# class SimpleLSTM(keras.Model):
# def __init__(self, lstm_units, num_output):
# super().__init__(self)
# cell = layers.LSTMCell(lstm_units,
# kernel_initializer='glorot_uniform',
# recurrent_initializer='glorot_uniform',
# bias_initializer='zeros')
# self.lstm = tf.keras.layers.RNN(cell,
# return_state = True,
# return_sequences=True,
# stateful=False)
# lstm_out, hidden_state, cell_state = self.lstm(input_layer)
#
#
# self.lstm1 = layers.LSTM(lstm_units, return_sequences=True, return_state=True)
# self.dense = layers.Dense(num_output)
#
# def get_zero_initial_state(self, inputs):
# return [tf.zeros((batch_size, lstm_nodes)), tf.zeros((batch_size, lstm_nodes))]
# def __call__(self, inputs, states = None):
# if states is None:
# self.lstm.get_initial_state = self.get_zero_initial_state
# def call(self, inputs, states=None, return_state = False, training=False):
# x = inputs
# if states is None: states = self.lstm1.get_initial_state(x) # state shape = (2, batch_size, lstm_units)
# print(x.shape)
# print(len(states))
# print(states[0].shape)
# x, sequence, states = self.lstm1(x, initial_state=states, training=training)
# x = self.dense(x, training=training)
#
# if return_state: return x, states
# else: return x
# @tf.function
# def train_step(self, inputs):
# inputs, labels = inputs
# with tf.GradientTape() as tape:
# predictions = self(inputs, training=True)
# loss = self.loss(labels, predictions)
# grads = tape.gradient(loss, model.trainable_variables)
# self.optimizer.apply_gradients(zip(grads, model.trainable_variables))
#
# return {'loss': loss}
# model = SimpleLSTM(lstm_units=8, num_output=1)
# model.build(input_shape=(None, 1, 3))
# model.summary()
optimizer = tf.optimizers.Adam(learning_rate=0.0025)
loss_fn = keras.losses.MeanSquaredError() # Instantiate a loss function.
# train_mse_metric = keras.metrics.MeanSquaredError()
scores = []
gradBuffer = model.trainable_variables
for ix, grad in enumerate(gradBuffer): gradBuffer[ix] = grad * 0
for e in range(n_episodes):
# print("\nStart of episodes %d" % (e,))
# Reset the environment
world.reset()
lstm_layer.reset_states(states=[np.zeros((batch_size, lstm_nodes)), np.zeros((batch_size, lstm_nodes))])
previous_states = None # reset LSTM's internal state
render_counter = 0
ep_memory = []
ep_score = 0
done = False
previous = {'robot_position': None, 'robot_rotation': None, 'fall_rotation': None}
present = {'robot_position': None, 'robot_rotation': None, 'fall_rotation': None}
while not done:
previous['robot_position'], previous['robot_rotation'] = robot.get_world_pose()
previous['fall_rotation'] = q2falling(previous['robot_rotation'])
reading = imu_interface.get_sensor_readings(_sensor_handle)
if reading.shape[0] == 0:# no valid data in buffer -> init observation wih zeros
observations = np.array([0, 0, 0])
else: # IMU will return [???, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z]
observations = np.array([reading[-1]["lin_acc_y"], # Use only lastest data in buffer
reading[-1]["lin_acc_z"],
reading[-1]["ang_vel_x"]])
## convert omniverse unit to sensor_read unit
world_sensor = omni_unit2_sensor_unit(observations)
key_gen = np.load('/home/teera/.local/share/ov/pkg/isaac_sim-2021.2.1/exts/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/mu_cov_bike.npz')
noi_accy,noi_accz,noi_ang_vel_x = np.random.default_rng().multivariate_normal(world_sensor, key_gen["cov"], 1).T
## convert sensor_read unit to omniverse unit
noisy_sensor = np.array([noi_accy,noi_accz,noi_ang_vel_x])
sim_observations = sensor_unit2_omni_unit(noisy_sensor)
## Scale accel from (-1000, 1000) -> (0, 1) for NN inputs
## Scale gyro from (-4.36, 4.36) -> (0, 1) for NN inputs (4.36 rad = 250 deg)
# print(observations)
# time.sleep(1)
sim_observations[0] = (sim_observations[0] / 2000) + 0.5
sim_observations[1] = (sim_observations[1] / 2000) + 0.5
sim_observations[2] = (sim_observations[2] / 8.72) + 0.5
sim_observations = np.array(sim_observations, dtype=np.float32).reshape((batch_size, num_timesteps, input_dim)) # add extra dimension for batch_size=1
with tf.GradientTape() as tape:
# forward pass
h_state, c_state, logits = model(sim_observations) # required input_shape=(None, 1, 3)
# logits, previous_states = model.call(inputs=observations, states=previous_states, return_state=True, training=True)
a_dist = logits.numpy()
## Choose random action with p = action dist
# print("A_DIST")
# print(a_dist)
# a = np.random.choice(a_dist[0], p=a_dist[0])
# a = np.argmax(a_dist == a)
a = a_dist + 0.1*((np.random.rand(*a_dist.shape))-0.5) # random with uniform distribution (.shape will return tuple so unpack with *)
loss = loss_fn([a], logits)
# loss = previous['fall_rotation']
## EXECUTE ACTION ##
from omni.isaac.core.utils.types import ArticulationAction
# print("LOGITS")
# print(logits)
robot.apply_wheel_actions(ArticulationAction(joint_efforts=[a*100*0.607, 0, 0]))
world.step(render=True)
present['robot_position'], present['robot_rotation'] = robot.get_world_pose()
present['fall_rotation'] = q2falling(present['robot_rotation'])
reward = previous['fall_rotation'] - present['fall_rotation'] # calculate reward from movement toward center
## Check for stop event ##
exceed_time_limit = world.current_time_step_index >= _max_episode_length
robot_fall = True if previous['fall_rotation'] > 25 / 180 * math.pi else False
done = exceed_time_limit or robot_fall
ep_score += reward
# if done: reward-= 10 # small trick to make training faster
grads = tape.gradient(loss, model.trainable_weights)
ep_memory.append([grads, reward])
scores.append(ep_score)
# Discount the rewards
ep_memory = np.array(ep_memory)
ep_memory[:, 1] = discount_rewards(ep_memory[:, 1])
for grads, reward in ep_memory:
for ix, grad in enumerate(grads):
gradBuffer[ix] += grad * reward
if e % _update_every == 0:
optimizer.apply_gradients(zip(gradBuffer, model.trainable_variables))
for ix, grad in enumerate(gradBuffer): gradBuffer[ix] = grad * 0
if e % 100 == 0:
print("Episode {} Score {}".format(e, np.mean(scores[-100:]))) | 10,253 | Python | 40.853061 | 159 | 0.619233 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/train_obike_drqn.py | import carb
from omni.isaac.kit import SimulationApp
from omni.isaac.imu_sensor import _imu_sensor
import numpy as np
import math
import time
import tensorflow as tf
def q2falling(q):
q[0] = 1 if q[0] > 1 else q[0]
try:
if q[1] == 0 and q[2] == 0 and q[3] == 0:
return 0
return 2*math.acos(q[0])*math.sqrt((q[1]**2 + q[2]**2)/(q[1]**2 + q[2]**2 + q[3]**2))
except:
print(q)
return 0
def q2falling(q):
q[0] = 1 if q[0] > 1 else q[0]
try:
if q[1] == 0 and q[2] == 0 and q[3] == 0:
return 0
return 2*math.acos(q[0])*math.sqrt((q[1]**2 + q[2]**2)/(q[1]**2 + q[2]**2 + q[3]**2))
except:
print(q)
return 0
## Specify simulation parameters ##
_physics_dt = 1/1000
_rendering_dt = 1/30
_max_episode_length = 60/_physics_dt # 60 second after reset
_iteration_count = 0
_display_every_iter = 1
_update_every = 1
_explore_every = 5
_headless = False
simulation_app = SimulationApp({"headless": _headless, "anti_aliasing": 0})
## Setup World ##
from omni.isaac.core import World
from obike_old import Obike
# from omni.isaac.core.objects import DynamicSphere
world = World(physics_dt=_physics_dt, rendering_dt=_rendering_dt, stage_units_in_meters=0.01)
world.scene.add_default_ground_plane()
robot = world.scene.add(
Obike(
prim_path="/obike",
name="obike_mk0",
position=np.array([0, 0.0, 1.435]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
## Setup IMU ##
imu_interface = _imu_sensor.acquire_imu_sensor_interface()
props = _imu_sensor.SensorProperties()
props.position = carb.Float3(0, 0, 10) # translate from /obike/chassic to above motor (cm.)
props.orientation = carb.Float4(1, 0, 0, 0) # (x, y, z, w)
props.sensorPeriod = 1 / 500 # 2ms
_sensor_handle = imu_interface.add_sensor_on_body("/obike/chassic", props)
## Create LSTM Model ##
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
| 1,996 | Python | 29.257575 | 93 | 0.623747 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/train_obike_td3.py | import tensorflow as tf
import numpy as np
import math
import time
def q2falling(q):
q[0] = 1 if q[0] > 1 else q[0]
try:
if q[1] == 0 and q[2] == 0 and q[3] == 0:
return 0
return 2*math.acos(q[0])*math.sqrt((q[1]**2 + q[2]**2)/(q[1]**2 + q[2]**2 + q[3]**2))
except:
print(q)
return 0
import carb
from omni.isaac.kit import SimulationApp
from omni.isaac.imu_sensor import _imu_sensor
print(tf.config.list_physical_devices('GPU'))
state_low = [-100, -100, -10]
state_high = [100, 100, 10]
action_low = [-1]
action_high = [1]
## Specify simulation parameters ##
_physics_dt = 1/100
_rendering_dt = 1/30
_max_episode_length = 60/_physics_dt # 60 second after reset
_iteration_count = 0
_display_every_iter = 1
_update_every = 1
_explore_every = 5
_headless = False
simulation_app = SimulationApp({"headless": _headless, "anti_aliasing": 0})
## Setup World ##
from omni.isaac.core import World
from obike_old import Obike
# from omni.isaac.core.objects import DynamicSphere
world = World(physics_dt=_physics_dt, rendering_dt=_rendering_dt, stage_units_in_meters=0.01)
world.scene.add_default_ground_plane()
robot = world.scene.add(
Obike(
prim_path="/obike",
name="obike_mk0",
position=np.array([0, 0.0, 1.435]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
## Setup IMU ##
imu_interface = _imu_sensor.acquire_imu_sensor_interface()
props = _imu_sensor.SensorProperties()
props.position = carb.Float3(0, 0, 10) # translate from /obike/chassic to above motor (cm.)
props.orientation = carb.Float4(1, 0, 0, 0) # (x, y, z, w)
props.sensorPeriod = 1 / 500 # 2ms
_sensor_handle = imu_interface.add_sensor_on_body("/obike/chassic", props)
from td3 import RBuffer, Critic, Actor, Agent
with tf.device('GPU:0'):
# tf.random.set_seed(336699)
agent = Agent(n_action=1, n_state=3, action_low=action_low, action_high=action_high)
episods = 20000
ep_reward = []
total_avgr = []
target = False
for s in range(episods):
if target == True:
break
total_reward = 0
world.reset()
done = False
previous = {'robot_position': None, 'robot_rotation': None, 'fall_rotation': None, "lin_acc_y": None, "lin_acc_z": None, "ang_vel_x": None}
present = {'robot_position': None, 'robot_rotation': None, 'fall_rotation': None, "lin_acc_y": None, "lin_acc_z": None, "ang_vel_x": None}
while not done:
if previous['robot_position'] is None: # initial state
robot_position, _ = robot.get_world_pose()
previous = {'robot_position': robot_position[0],
'robot_rotation': robot_position[1],
'fall_rotation': robot_position[2],
"lin_acc_y": 0,
"lin_acc_z": 0,
"ang_vel_x": 0}
state = np.array([previous["lin_acc_y"],
previous["lin_acc_z"],
previous["ang_vel_x"]], dtype=np.float32)
## Scale accel from (-1000, 1000) -> (0, 1) for NN inputs
## Scale gyro from (-4.36, 4.36) -> (0, 1) for NN inputs (4.36 rad = 250 deg)
# print(observations)
# time.sleep(1)
# observations[0] = (state[0] / 2000) + 0.5
# observations[1] = (state[1] / 2000) + 0.5
# observations[2] = (state[2] / 8.72) + 0.5
action = agent.act(state)
# print(action)
## EXECUTE ACTION ##
from omni.isaac.core.utils.types import ArticulationAction
robot.apply_wheel_actions(ArticulationAction(joint_efforts=[action * 100 * 0.607, 0, 0]))
world.step(render=True)
reading = imu_interface.get_sensor_readings(_sensor_handle)
if reading.shape[0] == 0: # no valid data in buffer -> init observation wih zeros
observations = np.array([0, 0, 0], dtype=np.float32)
print("Warning! no data in IMU buffer")
else: # IMU will return [???, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z]
present["lin_acc_y"], present["lin_acc_z"], present["ang_vel_x"] = reading[-1]["lin_acc_y"], reading[-1]["lin_acc_z"], reading[-1]["ang_vel_x"]
next_state = np.array([present["lin_acc_y"],
present["lin_acc_z"],
present["ang_vel_x"]])
present['robot_position'], present['robot_rotation'] = robot.get_world_pose()
present['fall_rotation'] = q2falling(present['robot_rotation'])
reward = 1
# reward = previous['fall_rotation'] - present['fall_rotation'] # calculate reward from movement toward center
## Check for stop event ##
exceed_time_limit = world.current_time_step_index >= _max_episode_length
robot_fall = True if present['fall_rotation'] > 50 / 180 * math.pi else False
done = exceed_time_limit or robot_fall
agent.savexp(state, next_state, action, done, reward)
agent.train()
## UPDATE STATE ##
previous = present.copy()
total_reward += reward
if done:
ep_reward.append(total_reward)
avg_reward = np.mean(ep_reward[-100:])
total_avgr.append(avg_reward)
print("total reward after {} steps is {} and avg reward is {}".format(s, total_reward, avg_reward))
if avg_reward == 200: target = True | 5,653 | Python | 40.270073 | 159 | 0.558995 |
teerameth/omni.isaac.fiborobotlab/omni/isaac/fiborobotlab/obike/scripts/import_obike.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni
import omni.kit.commands
import asyncio
import math
import weakref
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
from omni.isaac.isaac_sensor import _isaac_sensor
from .common import set_drive_parameters
from pxr import UsdLux, Sdf, Gf, UsdPhysics
from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder
EXTENSION_NAME = "Import O-Bike"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
MenuItemDescription(name="O-Bike URDF", onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a O-Bike Robot via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This Example shows you import an NVIDIA O-Bike robot via URDF.\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a O-Bike Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Spin Robot",
"type": "button",
"text": "move",
"tooltip": "Spin the Robot in Place",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_obike(load_stage))
async def _load_obike(self, task):
done, pending = await asyncio.wait({task})
if task in done:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.import_inertia_tensor = False
# import_config.distance_scale = 100
import_config.fix_base = False # Attact wheel to /groundPlane
import_config.make_default_prim = True
import_config.create_physics_scene = True
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/obike/urdf/obike.urdf",
import_config=import_config,
)
viewport = omni.kit.viewport_legacy.get_default_viewport_window()
viewport.set_camera_position("/OmniverseKit_Persp", -51, 63, 25, True)
viewport.set_camera_target("/OmniverseKit_Persp", 220, -218, -160, True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
result, plane_path = omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=stage,
planePath="/groundPlane",
axis="Z",
size=1500.0,
position=Gf.Vec3f(0, 0, 0),
color=Gf.Vec3f(0.5),
)
# make sure the ground plane is under root prim and not robot
omni.kit.commands.execute(
"MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True
)
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# make front wheel spin freely
prim_path = "/obike/chassic/front_wheel_joint"
prim = stage.GetPrimAtPath(prim_path)
omni.kit.commands.execute(
"UnapplyAPISchemaCommand",
api=UsdPhysics.DriveAPI,
prim=prim,
api_prefix="drive",
multiple_api_token="angular",
)
## Attact IMU sensor ##
self._is = _isaac_sensor.acquire_imu_sensor_interface()
self.body_path = "/obike/chassic"
result, sensor = omni.kit.commands.execute(
"IsaacSensorCreateImuSensor",
path="/sensor",
parent=self.body_path,
sensor_period=1 / 500.0,
offset=Gf.Vec3d(0, 0, 10),
orientation=Gf.Quatd(1, 0, 0, 0),
visualize=True,
)
def _on_config_drives(self):
# self._on_config_robot() # make sure drives are configured first
stage = omni.usd.get_context().get_stage()
# set each axis to spin at a rate of 1 rad/s
axle_steering = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/obike/chassic/front_wheel_arm_joint"), "angular")
axle_rear_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/obike/chassic/rear_wheel_joint"), "angular")
axle_reaction_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/obike/chassic/reaction_wheel_joint"), "angular")
# omega = velocity2omega(0, 0.1, 0)
# print(omega)
set_drive_parameters(axle_steering, "position", math.degrees(3), 0, math.radians(1e7))
set_drive_parameters(axle_rear_wheel, "velocity", math.degrees(-10), 0, math.radians(1e7))
set_drive_parameters(axle_reaction_wheel, "velocity", math.degrees(4), 0, math.radians(1e7))
| 8,065 | Python | 42.6 | 150 | 0.566646 |
teerameth/omni.isaac.fiborobotlab/data/urdf/robots/hanumanURDFv1/config/joint_names_hanumanURDFv1.yaml | controller_joint_names: ['', 'JR1', 'JR2', 'JR3', 'JR4', 'JR5', 'JR6', 'JL1', 'JL2', 'JL3', 'JL4', 'JL5', 'JL6', 'JAR1', 'JAR2', 'JAR3', 'JAL1', 'JAL2', 'JAL3', 'JH1', 'JH2', ]
| 177 | YAML | 87.999956 | 176 | 0.485876 |
AkaneFoundation/Omni/README.md | # Omni


[](https://t.me/AkaneDev)
## Features
- Up-to-date material 3 design
- Lightweight, no spyware or bloat
- Compass with latitude & longitude
- Gradienter (WIP)
- Barometer (WIP)
- Coin flipper (WIP)
- Ruler (WIP)
- Strength-adjustable flashlight (WIP)
## Installation
You can download the latest stable version of the app from [GitHub releases](https://github.com/AkaneFoundation/Omni/releases/latest).
## Building
To build this app, you will need the latest beta version of [Android Studio](https://developer.android.com/studio) and fast network environment.
## License
This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](https://github.com/AkaneFoundation/Omni/blob/master/LICENSE) file for details.
## Notice
- For bug reporting: [Telegram](https://t.me/AkaneDev)
| 1,217 | Markdown | 44.111109 | 165 | 0.771569 |
AkaneFoundation/Omni/app/src/main/res/values/strings.xml | <resources>
<string name="app_name">Omni</string>
<string name="north">N</string>
<string name="northeast">NE</string>
<string name="northwest">NW</string>
<string name="south">S</string>
<string name="southeast">SE</string>
<string name="southwest">SW</string>
<string name="west">W</string>
<string name="east">E</string>
<string name="direction_1" translatable="false">0</string>
<string name="direction_2" translatable="false">30</string>
<string name="direction_3" translatable="false">60</string>
<string name="direction_4" translatable="false">90</string>
<string name="direction_5" translatable="false">120</string>
<string name="direction_6" translatable="false">150</string>
<string name="direction_7" translatable="false">180</string>
<string name="direction_8" translatable="false">210</string>
<string name="direction_9" translatable="false">240</string>
<string name="direction_10" translatable="false">270</string>
<string name="direction_11" translatable="false">300</string>
<string name="direction_12" translatable="false">330</string>
<string name="degree_format" translatable="false">" %1$s°"</string>
<string name="longitude_desc">N</string>
<string name="latitude_desc">E</string>
<string name="unknown_location">Unknown location</string>
<string name="perm_dialog_title">Location</string>
<string name="decline">No</string>
<string name="accept">Yes</string>
<string name="perm_dialog_text">Omni requires your location data in order to display latitude and longitude. That may requires communications with your location provider\'s server. If you select \"no\", you still can use the basic functionalities of omni compass.</string>
<string name="position_default_text" translatable="false">__.____°</string>
<string name="settings">Settings</string>
<string name="settings_app_name">App name</string>
<string name="author" translatable="false">123Duo3, AkaneTan</string>
<string name="settings_author_name">Author</string>
<string name="version">Version</string>
<string name="settings_unknown_version">Unknown version</string>
<string name="warning_dialog_title">Warning</string>
<string name="warning_dialog_text">It looks like your device doesn\'t have an available rotation vector sensor. The compass feature of Omni will be disabled. However, you still can use the location feature.</string>
<string name="dismiss">Dismiss</string>
<string name="delimiter">,\ </string>
<string name="location_format">%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s</string>
</resources> | 2,651 | XML | 60.674417 | 276 | 0.701622 |
AkaneFoundation/Omni/app/src/main/res/values/theme_overlays.xml | <resources>
<style name="ThemeOverlay.AppTheme.MediumContrast" parent="Theme.Material3.Light.NoActionBar">
<item name="colorPrimary">@color/md_theme_primary_mediumContrast</item>
<item name="colorOnPrimary">@color/md_theme_onPrimary_mediumContrast</item>
<item name="colorPrimaryContainer">@color/md_theme_primaryContainer_mediumContrast</item>
<item name="colorOnPrimaryContainer">@color/md_theme_onPrimaryContainer_mediumContrast</item>
<item name="colorSecondary">@color/md_theme_secondary_mediumContrast</item>
<item name="colorOnSecondary">@color/md_theme_onSecondary_mediumContrast</item>
<item name="colorSecondaryContainer">@color/md_theme_secondaryContainer_mediumContrast</item>
<item name="colorOnSecondaryContainer">@color/md_theme_onSecondaryContainer_mediumContrast</item>
<item name="colorTertiary">@color/md_theme_tertiary_mediumContrast</item>
<item name="colorOnTertiary">@color/md_theme_onTertiary_mediumContrast</item>
<item name="colorTertiaryContainer">@color/md_theme_tertiaryContainer_mediumContrast</item>
<item name="colorOnTertiaryContainer">@color/md_theme_onTertiaryContainer_mediumContrast</item>
<item name="colorError">@color/md_theme_error_mediumContrast</item>
<item name="colorOnError">@color/md_theme_onError_mediumContrast</item>
<item name="colorErrorContainer">@color/md_theme_errorContainer_mediumContrast</item>
<item name="colorOnErrorContainer">@color/md_theme_onErrorContainer_mediumContrast</item>
<item name="android:colorBackground">@color/md_theme_background_mediumContrast</item>
<item name="colorOnBackground">@color/md_theme_onBackground_mediumContrast</item>
<item name="colorSurface">@color/md_theme_surface_mediumContrast</item>
<item name="colorOnSurface">@color/md_theme_onSurface_mediumContrast</item>
<item name="colorSurfaceVariant">@color/md_theme_surfaceVariant_mediumContrast</item>
<item name="colorOnSurfaceVariant">@color/md_theme_onSurfaceVariant_mediumContrast</item>
<item name="colorOutline">@color/md_theme_outline_mediumContrast</item>
<item name="colorOutlineVariant">@color/md_theme_outlineVariant_mediumContrast</item>
<item name="colorSurfaceInverse">@color/md_theme_inverseSurface_mediumContrast</item>
<item name="colorOnSurfaceInverse">@color/md_theme_inverseOnSurface_mediumContrast</item>
<item name="colorPrimaryInverse">@color/md_theme_inversePrimary_mediumContrast</item>
<item name="colorPrimaryFixed">@color/md_theme_primaryFixed_mediumContrast</item>
<item name="colorOnPrimaryFixed">@color/md_theme_onPrimaryFixed_mediumContrast</item>
<item name="colorPrimaryFixedDim">@color/md_theme_primaryFixedDim_mediumContrast</item>
<item name="colorOnPrimaryFixedVariant">@color/md_theme_onPrimaryFixedVariant_mediumContrast</item>
<item name="colorSecondaryFixed">@color/md_theme_secondaryFixed_mediumContrast</item>
<item name="colorOnSecondaryFixed">@color/md_theme_onSecondaryFixed_mediumContrast</item>
<item name="colorSecondaryFixedDim">@color/md_theme_secondaryFixedDim_mediumContrast</item>
<item name="colorOnSecondaryFixedVariant">@color/md_theme_onSecondaryFixedVariant_mediumContrast</item>
<item name="colorTertiaryFixed">@color/md_theme_tertiaryFixed_mediumContrast</item>
<item name="colorOnTertiaryFixed">@color/md_theme_onTertiaryFixed_mediumContrast</item>
<item name="colorTertiaryFixedDim">@color/md_theme_tertiaryFixedDim_mediumContrast</item>
<item name="colorOnTertiaryFixedVariant">@color/md_theme_onTertiaryFixedVariant_mediumContrast</item>
<item name="colorSurfaceDim">@color/md_theme_surfaceDim_mediumContrast</item>
<item name="colorSurfaceBright">@color/md_theme_surfaceBright_mediumContrast</item>
<item name="colorSurfaceContainerLowest">@color/md_theme_surfaceContainerLowest_mediumContrast</item>
<item name="colorSurfaceContainerLow">@color/md_theme_surfaceContainerLow_mediumContrast</item>
<item name="colorSurfaceContainer">@color/md_theme_surfaceContainer_mediumContrast</item>
<item name="colorSurfaceContainerHigh">@color/md_theme_surfaceContainerHigh_mediumContrast</item>
<item name="colorSurfaceContainerHighest">@color/md_theme_surfaceContainerHighest_mediumContrast</item>
</style>
<style name="ThemeOverlay.AppTheme.HighContrast" parent="Theme.Material3.Light.NoActionBar">
<item name="colorPrimary">@color/md_theme_primary_highContrast</item>
<item name="colorOnPrimary">@color/md_theme_onPrimary_highContrast</item>
<item name="colorPrimaryContainer">@color/md_theme_primaryContainer_highContrast</item>
<item name="colorOnPrimaryContainer">@color/md_theme_onPrimaryContainer_highContrast</item>
<item name="colorSecondary">@color/md_theme_secondary_highContrast</item>
<item name="colorOnSecondary">@color/md_theme_onSecondary_highContrast</item>
<item name="colorSecondaryContainer">@color/md_theme_secondaryContainer_highContrast</item>
<item name="colorOnSecondaryContainer">@color/md_theme_onSecondaryContainer_highContrast</item>
<item name="colorTertiary">@color/md_theme_tertiary_highContrast</item>
<item name="colorOnTertiary">@color/md_theme_onTertiary_highContrast</item>
<item name="colorTertiaryContainer">@color/md_theme_tertiaryContainer_highContrast</item>
<item name="colorOnTertiaryContainer">@color/md_theme_onTertiaryContainer_highContrast</item>
<item name="colorError">@color/md_theme_error_highContrast</item>
<item name="colorOnError">@color/md_theme_onError_highContrast</item>
<item name="colorErrorContainer">@color/md_theme_errorContainer_highContrast</item>
<item name="colorOnErrorContainer">@color/md_theme_onErrorContainer_highContrast</item>
<item name="android:colorBackground">@color/md_theme_background_highContrast</item>
<item name="colorOnBackground">@color/md_theme_onBackground_highContrast</item>
<item name="colorSurface">@color/md_theme_surface_highContrast</item>
<item name="colorOnSurface">@color/md_theme_onSurface_highContrast</item>
<item name="colorSurfaceVariant">@color/md_theme_surfaceVariant_highContrast</item>
<item name="colorOnSurfaceVariant">@color/md_theme_onSurfaceVariant_highContrast</item>
<item name="colorOutline">@color/md_theme_outline_highContrast</item>
<item name="colorOutlineVariant">@color/md_theme_outlineVariant_highContrast</item>
<item name="colorSurfaceInverse">@color/md_theme_inverseSurface_highContrast</item>
<item name="colorOnSurfaceInverse">@color/md_theme_inverseOnSurface_highContrast</item>
<item name="colorPrimaryInverse">@color/md_theme_inversePrimary_highContrast</item>
<item name="colorPrimaryFixed">@color/md_theme_primaryFixed_highContrast</item>
<item name="colorOnPrimaryFixed">@color/md_theme_onPrimaryFixed_highContrast</item>
<item name="colorPrimaryFixedDim">@color/md_theme_primaryFixedDim_highContrast</item>
<item name="colorOnPrimaryFixedVariant">@color/md_theme_onPrimaryFixedVariant_highContrast</item>
<item name="colorSecondaryFixed">@color/md_theme_secondaryFixed_highContrast</item>
<item name="colorOnSecondaryFixed">@color/md_theme_onSecondaryFixed_highContrast</item>
<item name="colorSecondaryFixedDim">@color/md_theme_secondaryFixedDim_highContrast</item>
<item name="colorOnSecondaryFixedVariant">@color/md_theme_onSecondaryFixedVariant_highContrast</item>
<item name="colorTertiaryFixed">@color/md_theme_tertiaryFixed_highContrast</item>
<item name="colorOnTertiaryFixed">@color/md_theme_onTertiaryFixed_highContrast</item>
<item name="colorTertiaryFixedDim">@color/md_theme_tertiaryFixedDim_highContrast</item>
<item name="colorOnTertiaryFixedVariant">@color/md_theme_onTertiaryFixedVariant_highContrast</item>
<item name="colorSurfaceDim">@color/md_theme_surfaceDim_highContrast</item>
<item name="colorSurfaceBright">@color/md_theme_surfaceBright_highContrast</item>
<item name="colorSurfaceContainerLowest">@color/md_theme_surfaceContainerLowest_highContrast</item>
<item name="colorSurfaceContainerLow">@color/md_theme_surfaceContainerLow_highContrast</item>
<item name="colorSurfaceContainer">@color/md_theme_surfaceContainer_highContrast</item>
<item name="colorSurfaceContainerHigh">@color/md_theme_surfaceContainerHigh_highContrast</item>
<item name="colorSurfaceContainerHighest">@color/md_theme_surfaceContainerHighest_highContrast</item>
</style>
</resources>
| 8,875 | XML | 88.656565 | 111 | 0.754254 |
AkaneFoundation/Omni/app/src/main/res/values/themes.xml | <resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.Omni" parent="Theme.Material3.DynamicColors.DayNight.NoActionBar">
<item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
<item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="o_mr1">shortEdges</item>
<item name="fontFamily">@font/hankengrotesk</item>
<item name="android:fontFamily">@font/hankengrotesk</item>
<item name="viewInflaterClass">uk.akane.omni.logic.ui.ViewCompatInflater</item>
<!-- Work around b/331383944: PreferenceFragmentCompat permanently mutates activity theme (enables vertical scrollbars) -->
<item name="android:scrollbars">none</item>
<item name="materialAlertDialogTheme">@style/ThemeOverlay.App.MaterialAlertDialog</item>
</style>
<style name="PreV31.Theme.Omni" parent="Base.Theme.Omni">
<item name="colorPrimary">@color/md_theme_primary</item>
<item name="colorOnPrimary">@color/md_theme_onPrimary</item>
<item name="colorPrimaryContainer">@color/md_theme_primaryContainer</item>
<item name="colorOnPrimaryContainer">@color/md_theme_onPrimaryContainer</item>
<item name="colorSecondary">@color/md_theme_secondary</item>
<item name="colorOnSecondary">@color/md_theme_onSecondary</item>
<item name="colorSecondaryContainer">@color/md_theme_secondaryContainer</item>
<item name="colorOnSecondaryContainer">@color/md_theme_onSecondaryContainer</item>
<item name="colorTertiary">@color/md_theme_tertiary</item>
<item name="colorOnTertiary">@color/md_theme_onTertiary</item>
<item name="colorTertiaryContainer">@color/md_theme_tertiaryContainer</item>
<item name="colorOnTertiaryContainer">@color/md_theme_onTertiaryContainer</item>
<item name="colorError">@color/md_theme_error</item>
<item name="colorOnError">@color/md_theme_onError</item>
<item name="colorErrorContainer">@color/md_theme_errorContainer</item>
<item name="colorOnErrorContainer">@color/md_theme_onErrorContainer</item>
<item name="android:colorBackground">@color/md_theme_background</item>
<item name="colorOnBackground">@color/md_theme_onBackground</item>
<item name="colorSurface">@color/md_theme_surface</item>
<item name="colorOnSurface">@color/md_theme_onSurface</item>
<item name="colorSurfaceVariant">@color/md_theme_surfaceVariant</item>
<item name="colorOnSurfaceVariant">@color/md_theme_onSurfaceVariant</item>
<item name="colorOutline">@color/md_theme_outline</item>
<item name="colorOutlineVariant">@color/md_theme_outlineVariant</item>
<item name="colorSurfaceInverse">@color/md_theme_inverseSurface</item>
<item name="colorOnSurfaceInverse">@color/md_theme_inverseOnSurface</item>
<item name="colorPrimaryInverse">@color/md_theme_inversePrimary</item>
<item name="colorPrimaryFixed">@color/md_theme_primaryFixed</item>
<item name="colorOnPrimaryFixed">@color/md_theme_onPrimaryFixed</item>
<item name="colorPrimaryFixedDim">@color/md_theme_primaryFixedDim</item>
<item name="colorOnPrimaryFixedVariant">@color/md_theme_onPrimaryFixedVariant</item>
<item name="colorSecondaryFixed">@color/md_theme_secondaryFixed</item>
<item name="colorOnSecondaryFixed">@color/md_theme_onSecondaryFixed</item>
<item name="colorSecondaryFixedDim">@color/md_theme_secondaryFixedDim</item>
<item name="colorOnSecondaryFixedVariant">@color/md_theme_onSecondaryFixedVariant</item>
<item name="colorTertiaryFixed">@color/md_theme_tertiaryFixed</item>
<item name="colorOnTertiaryFixed">@color/md_theme_onTertiaryFixed</item>
<item name="colorTertiaryFixedDim">@color/md_theme_tertiaryFixedDim</item>
<item name="colorOnTertiaryFixedVariant">@color/md_theme_onTertiaryFixedVariant</item>
<item name="colorSurfaceDim">@color/md_theme_surfaceDim</item>
<item name="colorSurfaceBright">@color/md_theme_surfaceBright</item>
<item name="colorSurfaceContainerLowest">@color/md_theme_surfaceContainerLowest</item>
<item name="colorSurfaceContainerLow">@color/md_theme_surfaceContainerLow</item>
<item name="colorSurfaceContainer">@color/md_theme_surfaceContainer</item>
<item name="colorSurfaceContainerHigh">@color/md_theme_surfaceContainerHigh</item>
<item name="colorSurfaceContainerHighest">@color/md_theme_surfaceContainerHighest</item>
<item name="materialAlertDialogTheme">@style/ThemeOverlay.App.MaterialAlertDialog</item>
</style>
<style name="ThemeOverlay.App.MaterialAlertDialog" parent="ThemeOverlay.Material3.MaterialAlertDialog.Centered">
<item name="fontFamily">sans-serif</item>
<item name="android:fontFamily">sans-serif</item>
<item name="materialAlertDialogTitleTextStyle">@style/MaterialAlertDialog.App.Title.Text</item>
<item name="materialAlertDialogBodyTextStyle">@style/MaterialAlertDialog.App.Body.Text</item>
<item name="materialAlertDialogTitleIconStyle">@style/MaterialAlertDialog.App.Icon</item>
<item name="buttonBarPositiveButtonStyle">@style/Widget.App.Button</item>
<item name="buttonBarNegativeButtonStyle">@style/Widget.App.Button</item>
</style>
<style name="MaterialAlertDialog.App.Title.Text" parent="MaterialAlertDialog.Material3.Title.Text.CenterStacked">
<item name="android:textSize">24sp</item>
</style>
<style name="MaterialAlertDialog.App.Body.Text" parent="MaterialAlertDialog.Material3.Body.Text">
<item name="android:textSize">15sp</item>
</style>
<style name="MaterialAlertDialog.App.Icon" parent="MaterialAlertDialog.Material3.Title.Icon.CenterStacked">
<item name="android:layout_height">32dp</item>
<item name="android:layout_width">32dp</item>
<item name="android:layout_marginTop">12dp</item>
</style>
<style name="Widget.App.Button" parent="Widget.Material3.Button.TextButton.Dialog">
<item name="android:textFontWeight">600</item>
</style>
<style name="CompassTextAppearance">
<item name="android:textSize">22sp</item>
<item name="android:textColor">?colorOutline</item>
<item name="android:textFontWeight">500</item>
</style>
<style name="Base.Night.Theme.Splash" parent="Theme.SplashScreen">
<item name="postSplashScreenTheme">@style/Theme.Omni</item>
</style>
<style name="Base.Day.Theme.Splash" parent="Base.Night.Theme.Splash">
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowLightNavigationBar" tools:targetApi="o_mr1">true</item>
</style>
<style name="PreV31Day.Theme.Splash" parent="Base.Day.Theme.Splash">
<item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item>
<item name="windowSplashScreenIconBackgroundColor">@color/ic_launcher_background</item>
</style>
<style name="PreV31Night.Theme.Splash" parent="Base.Night.Theme.Splash">
<item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item>
<item name="windowSplashScreenIconBackgroundColor">@color/ic_launcher_background</item>
</style>
<style name="Day.Theme.Splash" parent="PreV31Day.Theme.Splash" />
<style name="Night.Theme.Splash" parent="PreV31Night.Theme.Splash" />
<style name="Theme.Omni" parent="PreV31.Theme.Omni" />
</resources> | 7,611 | XML | 62.966386 | 131 | 0.718959 |
AkaneFoundation/Omni/app/src/main/res/values/colors.xml | <resources>
<color name="md_theme_primary">#2E6A44</color>
<color name="md_theme_onPrimary">#FFFFFF</color>
<color name="md_theme_primaryContainer">#B1F1C1</color>
<color name="md_theme_onPrimaryContainer">#00210E</color>
<color name="md_theme_secondary">#4F6353</color>
<color name="md_theme_onSecondary">#FFFFFF</color>
<color name="md_theme_secondaryContainer">#D2E8D4</color>
<color name="md_theme_onSecondaryContainer">#0D1F13</color>
<color name="md_theme_tertiary">#3A646F</color>
<color name="md_theme_onTertiary">#FFFFFF</color>
<color name="md_theme_tertiaryContainer">#BEEAF6</color>
<color name="md_theme_onTertiaryContainer">#001F26</color>
<color name="md_theme_error">#BA1A1A</color>
<color name="md_theme_onError">#FFFFFF</color>
<color name="md_theme_errorContainer">#FFDAD6</color>
<color name="md_theme_onErrorContainer">#410002</color>
<color name="md_theme_background">#F6FBF3</color>
<color name="md_theme_onBackground">#181D18</color>
<color name="md_theme_surface">#F6FBF3</color>
<color name="md_theme_onSurface">#181D18</color>
<color name="md_theme_surfaceVariant">#DDE5DB</color>
<color name="md_theme_onSurfaceVariant">#414942</color>
<color name="md_theme_outline">#717971</color>
<color name="md_theme_outlineVariant">#C1C9BF</color>
<color name="md_theme_scrim">#000000</color>
<color name="md_theme_inverseSurface">#2C322D</color>
<color name="md_theme_inverseOnSurface">#EDF2EB</color>
<color name="md_theme_inversePrimary">#96D5A6</color>
<color name="md_theme_primaryFixed">#B1F1C1</color>
<color name="md_theme_onPrimaryFixed">#00210E</color>
<color name="md_theme_primaryFixedDim">#96D5A6</color>
<color name="md_theme_onPrimaryFixedVariant">#12512E</color>
<color name="md_theme_secondaryFixed">#D2E8D4</color>
<color name="md_theme_onSecondaryFixed">#0D1F13</color>
<color name="md_theme_secondaryFixedDim">#B6CCB8</color>
<color name="md_theme_onSecondaryFixedVariant">#384B3C</color>
<color name="md_theme_tertiaryFixed">#BEEAF6</color>
<color name="md_theme_onTertiaryFixed">#001F26</color>
<color name="md_theme_tertiaryFixedDim">#A2CEDA</color>
<color name="md_theme_onTertiaryFixedVariant">#214C57</color>
<color name="md_theme_surfaceDim">#D7DBD4</color>
<color name="md_theme_surfaceBright">#F6FBF3</color>
<color name="md_theme_surfaceContainerLowest">#FFFFFF</color>
<color name="md_theme_surfaceContainerLow">#F0F5ED</color>
<color name="md_theme_surfaceContainer">#EBEFE8</color>
<color name="md_theme_surfaceContainerHigh">#E5EAE2</color>
<color name="md_theme_surfaceContainerHighest">#DFE4DC</color>
<color name="md_theme_primary_mediumContrast">#0C4D2A</color>
<color name="md_theme_onPrimary_mediumContrast">#FFFFFF</color>
<color name="md_theme_primaryContainer_mediumContrast">#458158</color>
<color name="md_theme_onPrimaryContainer_mediumContrast">#FFFFFF</color>
<color name="md_theme_secondary_mediumContrast">#344738</color>
<color name="md_theme_onSecondary_mediumContrast">#FFFFFF</color>
<color name="md_theme_secondaryContainer_mediumContrast">#657A69</color>
<color name="md_theme_onSecondaryContainer_mediumContrast">#FFFFFF</color>
<color name="md_theme_tertiary_mediumContrast">#1C4853</color>
<color name="md_theme_onTertiary_mediumContrast">#FFFFFF</color>
<color name="md_theme_tertiaryContainer_mediumContrast">#517B86</color>
<color name="md_theme_onTertiaryContainer_mediumContrast">#FFFFFF</color>
<color name="md_theme_error_mediumContrast">#8C0009</color>
<color name="md_theme_onError_mediumContrast">#FFFFFF</color>
<color name="md_theme_errorContainer_mediumContrast">#DA342E</color>
<color name="md_theme_onErrorContainer_mediumContrast">#FFFFFF</color>
<color name="md_theme_background_mediumContrast">#F6FBF3</color>
<color name="md_theme_onBackground_mediumContrast">#181D18</color>
<color name="md_theme_surface_mediumContrast">#F6FBF3</color>
<color name="md_theme_onSurface_mediumContrast">#181D18</color>
<color name="md_theme_surfaceVariant_mediumContrast">#DDE5DB</color>
<color name="md_theme_onSurfaceVariant_mediumContrast">#3D453E</color>
<color name="md_theme_outline_mediumContrast">#596159</color>
<color name="md_theme_outlineVariant_mediumContrast">#757D75</color>
<color name="md_theme_scrim_mediumContrast">#000000</color>
<color name="md_theme_inverseSurface_mediumContrast">#2C322D</color>
<color name="md_theme_inverseOnSurface_mediumContrast">#EDF2EB</color>
<color name="md_theme_inversePrimary_mediumContrast">#96D5A6</color>
<color name="md_theme_primaryFixed_mediumContrast">#458158</color>
<color name="md_theme_onPrimaryFixed_mediumContrast">#FFFFFF</color>
<color name="md_theme_primaryFixedDim_mediumContrast">#2C6741</color>
<color name="md_theme_onPrimaryFixedVariant_mediumContrast">#FFFFFF</color>
<color name="md_theme_secondaryFixed_mediumContrast">#657A69</color>
<color name="md_theme_onSecondaryFixed_mediumContrast">#FFFFFF</color>
<color name="md_theme_secondaryFixedDim_mediumContrast">#4D6151</color>
<color name="md_theme_onSecondaryFixedVariant_mediumContrast">#FFFFFF</color>
<color name="md_theme_tertiaryFixed_mediumContrast">#517B86</color>
<color name="md_theme_onTertiaryFixed_mediumContrast">#FFFFFF</color>
<color name="md_theme_tertiaryFixedDim_mediumContrast">#38626D</color>
<color name="md_theme_onTertiaryFixedVariant_mediumContrast">#FFFFFF</color>
<color name="md_theme_surfaceDim_mediumContrast">#D7DBD4</color>
<color name="md_theme_surfaceBright_mediumContrast">#F6FBF3</color>
<color name="md_theme_surfaceContainerLowest_mediumContrast">#FFFFFF</color>
<color name="md_theme_surfaceContainerLow_mediumContrast">#F0F5ED</color>
<color name="md_theme_surfaceContainer_mediumContrast">#EBEFE8</color>
<color name="md_theme_surfaceContainerHigh_mediumContrast">#E5EAE2</color>
<color name="md_theme_surfaceContainerHighest_mediumContrast">#DFE4DC</color>
<color name="md_theme_primary_highContrast">#002912</color>
<color name="md_theme_onPrimary_highContrast">#FFFFFF</color>
<color name="md_theme_primaryContainer_highContrast">#0C4D2A</color>
<color name="md_theme_onPrimaryContainer_highContrast">#FFFFFF</color>
<color name="md_theme_secondary_highContrast">#142619</color>
<color name="md_theme_onSecondary_highContrast">#FFFFFF</color>
<color name="md_theme_secondaryContainer_highContrast">#344738</color>
<color name="md_theme_onSecondaryContainer_highContrast">#FFFFFF</color>
<color name="md_theme_tertiary_highContrast">#00262E</color>
<color name="md_theme_onTertiary_highContrast">#FFFFFF</color>
<color name="md_theme_tertiaryContainer_highContrast">#1C4853</color>
<color name="md_theme_onTertiaryContainer_highContrast">#FFFFFF</color>
<color name="md_theme_error_highContrast">#4E0002</color>
<color name="md_theme_onError_highContrast">#FFFFFF</color>
<color name="md_theme_errorContainer_highContrast">#8C0009</color>
<color name="md_theme_onErrorContainer_highContrast">#FFFFFF</color>
<color name="md_theme_background_highContrast">#F6FBF3</color>
<color name="md_theme_onBackground_highContrast">#181D18</color>
<color name="md_theme_surface_highContrast">#F6FBF3</color>
<color name="md_theme_onSurface_highContrast">#000000</color>
<color name="md_theme_surfaceVariant_highContrast">#DDE5DB</color>
<color name="md_theme_onSurfaceVariant_highContrast">#1E261F</color>
<color name="md_theme_outline_highContrast">#3D453E</color>
<color name="md_theme_outlineVariant_highContrast">#3D453E</color>
<color name="md_theme_scrim_highContrast">#000000</color>
<color name="md_theme_inverseSurface_highContrast">#2C322D</color>
<color name="md_theme_inverseOnSurface_highContrast">#FFFFFF</color>
<color name="md_theme_inversePrimary_highContrast">#BBFBCA</color>
<color name="md_theme_primaryFixed_highContrast">#0C4D2A</color>
<color name="md_theme_onPrimaryFixed_highContrast">#FFFFFF</color>
<color name="md_theme_primaryFixedDim_highContrast">#003519</color>
<color name="md_theme_onPrimaryFixedVariant_highContrast">#FFFFFF</color>
<color name="md_theme_secondaryFixed_highContrast">#344738</color>
<color name="md_theme_onSecondaryFixed_highContrast">#FFFFFF</color>
<color name="md_theme_secondaryFixedDim_highContrast">#1E3123</color>
<color name="md_theme_onSecondaryFixedVariant_highContrast">#FFFFFF</color>
<color name="md_theme_tertiaryFixed_highContrast">#1C4853</color>
<color name="md_theme_onTertiaryFixed_highContrast">#FFFFFF</color>
<color name="md_theme_tertiaryFixedDim_highContrast">#00323B</color>
<color name="md_theme_onTertiaryFixedVariant_highContrast">#FFFFFF</color>
<color name="md_theme_surfaceDim_highContrast">#D7DBD4</color>
<color name="md_theme_surfaceBright_highContrast">#F6FBF3</color>
<color name="md_theme_surfaceContainerLowest_highContrast">#FFFFFF</color>
<color name="md_theme_surfaceContainerLow_highContrast">#F0F5ED</color>
<color name="md_theme_surfaceContainer_highContrast">#EBEFE8</color>
<color name="md_theme_surfaceContainerHigh_highContrast">#E5EAE2</color>
<color name="md_theme_surfaceContainerHighest_highContrast">#DFE4DC</color>
</resources>
| 9,534 | XML | 65.215277 | 81 | 0.73799 |
AkaneFoundation/Omni/app/src/main/res/values-v31/themes.xml | <resources>
<style name="Day.Theme.Splash" parent="Base.Day.Theme.Splash" />
<style name="Night.Theme.Splash" parent="Base.Night.Theme.Splash" />
<style name="Theme.Omni" parent="Base.Theme.Omni" />
</resources> | 223 | XML | 43.799991 | 72 | 0.686099 |
AkaneFoundation/Omni/app/src/main/res/values-night/colors.xml | <resources>
<color name="md_theme_primary">#96D5A6</color>
<color name="md_theme_onPrimary">#00391C</color>
<color name="md_theme_primaryContainer">#12512E</color>
<color name="md_theme_onPrimaryContainer">#B1F1C1</color>
<color name="md_theme_secondary">#B6CCB8</color>
<color name="md_theme_onSecondary">#223527</color>
<color name="md_theme_secondaryContainer">#384B3C</color>
<color name="md_theme_onSecondaryContainer">#D2E8D4</color>
<color name="md_theme_tertiary">#A2CEDA</color>
<color name="md_theme_onTertiary">#023640</color>
<color name="md_theme_tertiaryContainer">#214C57</color>
<color name="md_theme_onTertiaryContainer">#BEEAF6</color>
<color name="md_theme_error">#FFB4AB</color>
<color name="md_theme_onError">#690005</color>
<color name="md_theme_errorContainer">#93000A</color>
<color name="md_theme_onErrorContainer">#FFDAD6</color>
<color name="md_theme_background">#101510</color>
<color name="md_theme_onBackground">#DFE4DC</color>
<color name="md_theme_surface">#101510</color>
<color name="md_theme_onSurface">#DFE4DC</color>
<color name="md_theme_surfaceVariant">#414942</color>
<color name="md_theme_onSurfaceVariant">#C1C9BF</color>
<color name="md_theme_outline">#8B938A</color>
<color name="md_theme_outlineVariant">#414942</color>
<color name="md_theme_scrim">#000000</color>
<color name="md_theme_inverseSurface">#DFE4DC</color>
<color name="md_theme_inverseOnSurface">#2C322D</color>
<color name="md_theme_inversePrimary">#2E6A44</color>
<color name="md_theme_primaryFixed">#B1F1C1</color>
<color name="md_theme_onPrimaryFixed">#00210E</color>
<color name="md_theme_primaryFixedDim">#96D5A6</color>
<color name="md_theme_onPrimaryFixedVariant">#12512E</color>
<color name="md_theme_secondaryFixed">#D2E8D4</color>
<color name="md_theme_onSecondaryFixed">#0D1F13</color>
<color name="md_theme_secondaryFixedDim">#B6CCB8</color>
<color name="md_theme_onSecondaryFixedVariant">#384B3C</color>
<color name="md_theme_tertiaryFixed">#BEEAF6</color>
<color name="md_theme_onTertiaryFixed">#001F26</color>
<color name="md_theme_tertiaryFixedDim">#A2CEDA</color>
<color name="md_theme_onTertiaryFixedVariant">#214C57</color>
<color name="md_theme_surfaceDim">#101510</color>
<color name="md_theme_surfaceBright">#353A35</color>
<color name="md_theme_surfaceContainerLowest">#0A0F0B</color>
<color name="md_theme_surfaceContainerLow">#181D18</color>
<color name="md_theme_surfaceContainer">#1C211C</color>
<color name="md_theme_surfaceContainerHigh">#262B26</color>
<color name="md_theme_surfaceContainerHighest">#313631</color>
<color name="md_theme_primary_mediumContrast">#9AD9AA</color>
<color name="md_theme_onPrimary_mediumContrast">#001B0A</color>
<color name="md_theme_primaryContainer_mediumContrast">#619E73</color>
<color name="md_theme_onPrimaryContainer_mediumContrast">#000000</color>
<color name="md_theme_secondary_mediumContrast">#BAD0BD</color>
<color name="md_theme_onSecondary_mediumContrast">#081A0E</color>
<color name="md_theme_secondaryContainer_mediumContrast">#819684</color>
<color name="md_theme_onSecondaryContainer_mediumContrast">#000000</color>
<color name="md_theme_tertiary_mediumContrast">#A6D2DE</color>
<color name="md_theme_onTertiary_mediumContrast">#00191F</color>
<color name="md_theme_tertiaryContainer_mediumContrast">#6D97A3</color>
<color name="md_theme_onTertiaryContainer_mediumContrast">#000000</color>
<color name="md_theme_error_mediumContrast">#FFBAB1</color>
<color name="md_theme_onError_mediumContrast">#370001</color>
<color name="md_theme_errorContainer_mediumContrast">#FF5449</color>
<color name="md_theme_onErrorContainer_mediumContrast">#000000</color>
<color name="md_theme_background_mediumContrast">#101510</color>
<color name="md_theme_onBackground_mediumContrast">#DFE4DC</color>
<color name="md_theme_surface_mediumContrast">#101510</color>
<color name="md_theme_onSurface_mediumContrast">#F7FCF4</color>
<color name="md_theme_surfaceVariant_mediumContrast">#414942</color>
<color name="md_theme_onSurfaceVariant_mediumContrast">#C5CDC3</color>
<color name="md_theme_outline_mediumContrast">#9DA59C</color>
<color name="md_theme_outlineVariant_mediumContrast">#7D857D</color>
<color name="md_theme_scrim_mediumContrast">#000000</color>
<color name="md_theme_inverseSurface_mediumContrast">#DFE4DC</color>
<color name="md_theme_inverseOnSurface_mediumContrast">#262B27</color>
<color name="md_theme_inversePrimary_mediumContrast">#14522F</color>
<color name="md_theme_primaryFixed_mediumContrast">#B1F1C1</color>
<color name="md_theme_onPrimaryFixed_mediumContrast">#001507</color>
<color name="md_theme_primaryFixedDim_mediumContrast">#96D5A6</color>
<color name="md_theme_onPrimaryFixedVariant_mediumContrast">#003F20</color>
<color name="md_theme_secondaryFixed_mediumContrast">#D2E8D4</color>
<color name="md_theme_onSecondaryFixed_mediumContrast">#041509</color>
<color name="md_theme_secondaryFixedDim_mediumContrast">#B6CCB8</color>
<color name="md_theme_onSecondaryFixedVariant_mediumContrast">#283A2C</color>
<color name="md_theme_tertiaryFixed_mediumContrast">#BEEAF6</color>
<color name="md_theme_onTertiaryFixed_mediumContrast">#001419</color>
<color name="md_theme_tertiaryFixedDim_mediumContrast">#A2CEDA</color>
<color name="md_theme_onTertiaryFixedVariant_mediumContrast">#0B3C46</color>
<color name="md_theme_surfaceDim_mediumContrast">#101510</color>
<color name="md_theme_surfaceBright_mediumContrast">#353A35</color>
<color name="md_theme_surfaceContainerLowest_mediumContrast">#0A0F0B</color>
<color name="md_theme_surfaceContainerLow_mediumContrast">#181D18</color>
<color name="md_theme_surfaceContainer_mediumContrast">#1C211C</color>
<color name="md_theme_surfaceContainerHigh_mediumContrast">#262B26</color>
<color name="md_theme_surfaceContainerHighest_mediumContrast">#313631</color>
<color name="md_theme_primary_highContrast">#EFFFEF</color>
<color name="md_theme_onPrimary_highContrast">#000000</color>
<color name="md_theme_primaryContainer_highContrast">#9AD9AA</color>
<color name="md_theme_onPrimaryContainer_highContrast">#000000</color>
<color name="md_theme_secondary_highContrast">#EFFFEF</color>
<color name="md_theme_onSecondary_highContrast">#000000</color>
<color name="md_theme_secondaryContainer_highContrast">#BAD0BD</color>
<color name="md_theme_onSecondaryContainer_highContrast">#000000</color>
<color name="md_theme_tertiary_highContrast">#F4FCFF</color>
<color name="md_theme_onTertiary_highContrast">#000000</color>
<color name="md_theme_tertiaryContainer_highContrast">#A6D2DE</color>
<color name="md_theme_onTertiaryContainer_highContrast">#000000</color>
<color name="md_theme_error_highContrast">#FFF9F9</color>
<color name="md_theme_onError_highContrast">#000000</color>
<color name="md_theme_errorContainer_highContrast">#FFBAB1</color>
<color name="md_theme_onErrorContainer_highContrast">#000000</color>
<color name="md_theme_background_highContrast">#101510</color>
<color name="md_theme_onBackground_highContrast">#DFE4DC</color>
<color name="md_theme_surface_highContrast">#101510</color>
<color name="md_theme_onSurface_highContrast">#FFFFFF</color>
<color name="md_theme_surfaceVariant_highContrast">#414942</color>
<color name="md_theme_onSurfaceVariant_highContrast">#F5FDF3</color>
<color name="md_theme_outline_highContrast">#C5CDC3</color>
<color name="md_theme_outlineVariant_highContrast">#C5CDC3</color>
<color name="md_theme_scrim_highContrast">#000000</color>
<color name="md_theme_inverseSurface_highContrast">#DFE4DC</color>
<color name="md_theme_inverseOnSurface_highContrast">#000000</color>
<color name="md_theme_inversePrimary_highContrast">#003218</color>
<color name="md_theme_primaryFixed_highContrast">#B6F6C5</color>
<color name="md_theme_onPrimaryFixed_highContrast">#000000</color>
<color name="md_theme_primaryFixedDim_highContrast">#9AD9AA</color>
<color name="md_theme_onPrimaryFixedVariant_highContrast">#001B0A</color>
<color name="md_theme_secondaryFixed_highContrast">#D6EDD8</color>
<color name="md_theme_onSecondaryFixed_highContrast">#000000</color>
<color name="md_theme_secondaryFixedDim_highContrast">#BAD0BD</color>
<color name="md_theme_onSecondaryFixedVariant_highContrast">#081A0E</color>
<color name="md_theme_tertiaryFixed_highContrast">#C2EEFB</color>
<color name="md_theme_onTertiaryFixed_highContrast">#000000</color>
<color name="md_theme_tertiaryFixedDim_highContrast">#A6D2DE</color>
<color name="md_theme_onTertiaryFixedVariant_highContrast">#00191F</color>
<color name="md_theme_surfaceDim_highContrast">#101510</color>
<color name="md_theme_surfaceBright_highContrast">#353A35</color>
<color name="md_theme_surfaceContainerLowest_highContrast">#0A0F0B</color>
<color name="md_theme_surfaceContainerLow_highContrast">#181D18</color>
<color name="md_theme_surfaceContainer_highContrast">#1C211C</color>
<color name="md_theme_surfaceContainerHigh_highContrast">#262B26</color>
<color name="md_theme_surfaceContainerHighest_highContrast">#313631</color>
</resources>
| 9,534 | XML | 65.215277 | 81 | 0.73799 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_star_shape.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="396.96dp"
android:height="396.96dp"
android:viewportWidth="396.96"
android:viewportHeight="396.96">
<path
android:fillColor="#FF000000"
android:pathData="M247.09,28.82l21.68,39.64c13.79,25.21 34.52,45.95 59.74,59.74l39.64,21.68c38.43,21.02 38.43,76.2 0,97.22l-39.64,21.68c-25.21,13.79 -45.95,34.52 -59.74,59.74l-21.68,39.64c-21.02,38.43 -76.2,38.43 -97.22,0l-21.68,-39.64c-13.79,-25.21 -34.52,-45.95 -59.74,-59.74l-39.64,-21.68c-38.43,-21.02 -38.43,-76.2 0,-97.22l39.64,-21.68c25.21,-13.79 45.95,-34.52 59.74,-59.74l21.68,-39.64c21.02,-38.43 76.2,-38.43 97.22,0Z"
android:strokeWidth="0"/>
</vector>
| 718 | XML | 64.363631 | 433 | 0.664345 |
AkaneFoundation/Omni/app/src/main/res/drawable/location_indicator.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="37dp"
android:height="32dp"
android:viewportWidth="37"
android:viewportHeight="32">
<path
android:pathData="M25.328,27.819C22.209,32.927 14.791,32.927 11.672,27.819L2.116,12.169C-1.14,6.838 2.697,0 8.943,0L28.057,0C34.303,0 38.14,6.838 34.884,12.169L25.328,27.819Z"
android:fillColor="#000000" />
</vector>
| 419 | XML | 40.999996 | 181 | 0.694511 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_close.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorOnSurface">
<path
android:fillColor="@android:color/white"
android:pathData="M256,760L200,704L424,480L200,256L256,200L480,424L704,200L760,256L536,480L760,704L704,760L480,536L256,760Z"/>
</vector>
| 422 | XML | 37.454542 | 132 | 0.736967 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_arrow_back.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal"
android:autoMirrored="true">
<path
android:fillColor="@android:color/white"
android:pathData="M313,520L537,744L480,800L160,480L480,160L537,216L313,440L800,440L800,520L313,520Z"/>
</vector>
| 434 | XML | 35.249997 | 108 | 0.730415 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_warning.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M40,840L480,80L920,840L40,840ZM178,760L782,760L480,240L178,760ZM480,720Q497,720 508.5,708.5Q520,697 520,680Q520,663 508.5,651.5Q497,640 480,640Q463,640 451.5,651.5Q440,663 440,680Q440,697 451.5,708.5Q463,720 480,720ZM440,600L520,600L520,400L440,400L440,600ZM480,500L480,500L480,500L480,500Z"/>
</vector>
| 611 | XML | 54.636359 | 317 | 0.757774 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_conversion_path.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M760,840Q721,840 690,817.5Q659,795 647,760L440,760Q374,760 327,713Q280,666 280,600Q280,534 327,487Q374,440 440,440L520,440Q553,440 576.5,416.5Q600,393 600,360Q600,327 576.5,303.5Q553,280 520,280L313,280Q300,315 269.5,337.5Q239,360 200,360Q150,360 115,325Q80,290 80,240Q80,190 115,155Q150,120 200,120Q239,120 269.5,142.5Q300,165 313,200L520,200Q586,200 633,247Q680,294 680,360Q680,426 633,473Q586,520 520,520L440,520Q407,520 383.5,543.5Q360,567 360,600Q360,633 383.5,656.5Q407,680 440,680L647,680Q660,645 690.5,622.5Q721,600 760,600Q810,600 845,635Q880,670 880,720Q880,770 845,805Q810,840 760,840ZM200,280Q217,280 228.5,268.5Q240,257 240,240Q240,223 228.5,211.5Q217,200 200,200Q183,200 171.5,211.5Q160,223 160,240Q160,257 171.5,268.5Q183,280 200,280Z"/>
</vector>
| 1,070 | XML | 96.363628 | 776 | 0.76729 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_explorer.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M260,700L560,560L700,260L400,400L260,700ZM480,520Q463,520 451.5,508.5Q440,497 440,480Q440,463 451.5,451.5Q463,440 480,440Q497,440 508.5,451.5Q520,463 520,480Q520,497 508.5,508.5Q497,520 480,520ZM480,880Q397,880 324,848.5Q251,817 197,763Q143,709 111.5,636Q80,563 80,480Q80,397 111.5,324Q143,251 197,197Q251,143 324,111.5Q397,80 480,80Q563,80 636,111.5Q709,143 763,197Q817,251 848.5,324Q880,397 880,480Q880,563 848.5,636Q817,709 763,763Q709,817 636,848.5Q563,880 480,880ZM480,800Q614,800 707,707Q800,614 800,480Q800,346 707,253Q614,160 480,160Q346,160 253,253Q160,346 160,480Q160,614 253,707Q346,800 480,800ZM480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Z"/>
</vector>
| 1,064 | XML | 95.818173 | 770 | 0.771617 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_grid_view.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M120,440L120,120L440,120L440,440L120,440ZM120,840L120,520L440,520L440,840L120,840ZM520,440L520,120L840,120L840,440L520,440ZM520,840L520,520L840,520L840,840L520,840ZM200,360L360,360L360,200L200,200L200,360ZM600,360L760,360L760,200L600,200L600,360ZM600,760L760,760L760,600L600,600L600,760ZM200,760L360,760L360,600L200,600L200,760ZM600,360L600,360L600,360L600,360L600,360ZM600,600L600,600L600,600L600,600L600,600ZM360,600L360,600L360,600L360,600L360,600ZM360,360L360,360L360,360L360,360L360,360Z"/>
</vector>
| 813 | XML | 72.999993 | 519 | 0.805658 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_location_on.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M480,480Q513,480 536.5,456.5Q560,433 560,400Q560,367 536.5,343.5Q513,320 480,320Q447,320 423.5,343.5Q400,367 400,400Q400,433 423.5,456.5Q447,480 480,480ZM480,774Q602,662 661,570.5Q720,479 720,408Q720,299 650.5,229.5Q581,160 480,160Q379,160 309.5,229.5Q240,299 240,408Q240,479 299,570.5Q358,662 480,774ZM480,880Q319,743 239.5,625.5Q160,508 160,408Q160,258 256.5,169Q353,80 480,80Q607,80 703.5,169Q800,258 800,408Q800,508 720.5,625.5Q641,743 480,880ZM480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Z"/>
</vector>
| 906 | XML | 81.454538 | 612 | 0.759382 |
AkaneFoundation/Omni/gradle/libs.versions.toml | [versions]
agp = "8.4.1"
kotlin = "1.9.0"
coreKtx = "1.13.1"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
appcompat = "1.6.1"
material = "1.12.0"
activity = "1.9.0"
constraintlayout = "2.1.4"
preferenceKtx = "1.2.1"
coreSplashscreen = "1.0.1"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-preference-ktx = { module = "androidx.preference:preference-ktx", version.ref = "preferenceKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "coreSplashscreen" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
| 1,476 | TOML | 46.64516 | 128 | 0.687669 |
move-ai/omniverse-public-asset-library/README.md | # omniverse-public-asset-library
Omniverse extension which allows to import free animations that have been captured by the move.ai team
# Overview
This extension is designed to let you test animations processed by the Move.ai team. All of the animations are free to use allowing you to check the quality of our data.
We will continue to add new animations, stay tuned!
# How to use
- Set your `Assets Path` to where you'd like to store animations
- Click `Update Preview`
- It will take some time to update animation previews. When it's done you'll be able to import animations simply by clicking a `Import animation` button
- Activate `Skeleton Joint` extension to be able to view skeleton animations in the viewport
More info [here](https://docs.move.ai/nvidia-omniverse-extension)
| 790 | Markdown | 42.944442 | 169 | 0.78481 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/extension.py | from ctypes import alignment
import omni.ext
from .window import MoveaiAssetsMarketlaceWindow
class MoveaiAssetsMarketlace(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[moveai.assets] Move.ai Public Asset Library startup")
self._window = MoveaiAssetsMarketlaceWindow(ext_id)
def on_shutdown(self):
if self._window is not None:
self._window.destroy()
self._window = None
print("[moveai.assets] Move.ai Public Asset Library shutdown")
| 679 | Python | 36.777776 | 119 | 0.702504 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/utils.py | from urllib import request
import json
import cv2
import random
import carb
import omni.kit.asset_converter
import omni.kit.commands
import omni.usd
from PIL import Image
from pathlib import Path
def get_data(url: str):
f = request.urlopen(url)
data_json = json.loads(f.read())
return data_json
def get_random_frame(videofile: str):
vidcap = cv2.VideoCapture(videofile)
# get total number of frames
total_frames = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)
random_frame_number = random.randint(60, total_frames)
# set frame position
vidcap.set(cv2.CAP_PROP_POS_FRAMES, random_frame_number)
success, image = vidcap.read()
if success:
suffix = Path(videofile).suffix
img_path = f"{videofile.split(suffix)[0]}.jpg"
cv2.imwrite(img_path, image)
return img_path
# Progress of processing.
def progress_callback(current_step: int, total: int):
# Show progress
print(f"{current_step} of {total}")
# Convert asset file(obj/fbx/glTF, etc) to usd.
async def convert_asset_to_usd(input_asset: str, output_usd: str):
# Input options are defaults.
converter_context = omni.kit.asset_converter.AssetConverterContext()
converter_context.ignore_materials = False
converter_context.ignore_camera = False
converter_context.ignore_animations = False
converter_context.ignore_light = False
converter_context.export_preview_surface = False
converter_context.use_meter_as_world_unit = False
converter_context.create_world_as_default_root_prim = True
converter_context.embed_textures = True
converter_context.convert_fbx_to_y_up = False
converter_context.convert_fbx_to_z_up = False
converter_context.merge_all_meshes = False
converter_context.use_double_precision_to_usd_transform_op = False
converter_context.ignore_pivots = False
converter_context.keep_all_materials = True
converter_context.smooth_normals = True
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(input_asset, output_usd, progress_callback, converter_context)
# Wait for completion.
success = await task.wait_until_finished()
if not success:
carb.log_error(task.get_status(), task.get_detailed_error())
else:
print("converting done")
def download_file(url: str, download_path: Path):
request.urlretrieve(url, download_path)
def import_file_to_scene(usd_path: Path):
stage = omni.usd.get_context().get_stage()
if not stage:
return
name = usd_path.stem
prim_path = omni.usd.get_stage_next_free_path(stage, "/" + name, True)
omni.kit.commands.execute(
"CreateReferenceCommand", path_to=prim_path, asset_path=str(usd_path), usd_context=omni.usd.get_context()
)
def get_img_size(img_path: Path):
im = Image.open(img_path)
width, height = im.size
return width, height
def download_motion(asset_path: Path, name: str, file_type: str = "fbx"):
from .window import MoveaiAssetsMarketlaceWindow
download_dir = asset_path / "anim_files" / file_type
download_dir.mkdir(parents=True, exist_ok=True)
download_path = download_dir / f"{name}.{file_type}"
for motion in MoveaiAssetsMarketlaceWindow.data["motions"]:
if name == motion["title"]:
download_file(motion["files"][f"{file_type}_url"], download_path)
import_file_to_scene(download_path)
return
| 3,448 | Python | 31.847619 | 113 | 0.697506 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/window.py | from functools import partial
import omni.ui as ui
import omni.kit
from urllib import request
from pathlib import Path
from .utils import get_data, get_random_frame, get_img_size, download_motion
import webbrowser
IMG_SIZE_DEVISOR = 2
class MoveaiAssetsMarketlaceWindow(ui.Window):
data = get_data("https://molibapi.move.ai/motions")
def __init__(self, ext_id):
super().__init__("Move.ai Public Asset Library", width=500, height=600, visible=True)
self.frame.set_build_fn(self._build_ui)
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.asset_path_default: str = (
omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) + "/data"
)
self.asset_path_current: str = None
def _set_path_current(self, path: str):
self.asset_path_current = path
def _build_ui(self):
self.image_preview_width: int = None
self.image_preview_height: int = None
with self.frame:
# Assets path and get previews button
with ui.VStack():
with ui.CollapsableFrame("Settings", height=0):
with ui.VStack():
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Assets Path", width=70, height=0)
self.asset_field = ui.StringField(name="asset_path")
if not self.asset_path_current:
self.asset_field.model.set_value(self.asset_path_default)
else:
self.asset_field.model.set_value(self.asset_path_current)
self.asset_field.model.add_value_changed_fn(
lambda m: self._set_path_current(m.get_value_as_string())
)
ui.Button("Update Preview", width=0, height=0, clicked_fn=lambda: self._build_ui())
# Grid with previews and import buttons
with ui.CollapsableFrame("Preview"):
self.get_preview()
with ui.HStack(height=20, style={"Button":{"background_color": "0xFFFF7E09"}}):
ui.Button("Join iPhone beta", width=0, height=0, clicked_fn=partial(
webbrowser.open,
"https://www.move.ai/mobile-device"
))
def get_preview(self):
self.asset_path = Path(self.asset_field.model.get_value_as_string())
previews_path = self.asset_path / "previews"
previews_path.mkdir(parents=True, exist_ok=True)
with ui.HStack():
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
self.asset_grid = ui.VGrid(style={"margin": 3})
with self.asset_grid:
for motion in self.data["motions"]:
preview_path = previews_path / f"{motion['title']}.mp4"
preview = request.urlretrieve(motion["files"]["preview_url"], preview_path)
img_preview = get_random_frame(str(preview_path))
if not self.image_preview_width:
self.image_preview_width, self.image_preview_height = get_img_size(img_preview)
self.asset_grid.column_width = self.image_preview_width / IMG_SIZE_DEVISOR
with ui.VStack():
image = ui.Image(
img_preview,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER,
height=self.image_preview_height / IMG_SIZE_DEVISOR,
)
with ui.HStack():
ui.Label(motion["title"], alignment=ui.Alignment.LEFT)
button = ui.Button(
text="Import motion",
name=motion["title"],
alignment=ui.Alignment.RIGHT,
width=0,
height=0,
asset_path=self.asset_path,
clicked_fn=partial(
download_motion,
Path(self.asset_field.model.get_value_as_string()),
motion["title"],
),
)
| 4,930 | Python | 42.637168 | 107 | 0.48357 |
move-ai/omniverse-public-asset-library/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "Move.ai Public Asset Library"
description="Move.ai Public Asset Library"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
icon = "data/icon.jpeg"
preview_image = "data/preview.png"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Animation"
# Keywords for the extension
keywords = ["kit", "animation", "move"]
feature = true
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.asset_converter" = {}
# Main python module this extension provides, it will be publicly available as "import moveai.assets".
[[python.module]]
name = "moveai.assets.extension"
[python.pipapi]
# # List of additional directories with pip achives to be passed into pip using ``--find-links`` arg.
# # Relative paths are relative to extension root. Tokens can be used.
# archiveDirs = ["path/to/pip_archive"]
# Commands passed to pip install before extension gets enabled. Can also contain flags, like `--upgrade`, `--no--index`, etc.
# Refer to: https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format
requirements = [
"opencv-python"
]
# Allow going to online index if package can't be found locally (not recommended)
use_online_index = true
# Use this to specify a list of additional repositories if your pip package is hosted somewhere other
# than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument
# repositories = ["https://my.additional.pip_repo.com/"]
# [settings]
| 1,733 | TOML | 31.716981 | 125 | 0.735141 |
cadop/siborg-simulate-walk/README.md | # Python Extension [siborg.simulate.walk]
This is a simple extension that lets users select characters and assign them a goal xform to follow (while doing a walk animation).
It was initially done as a test, and the code may be useful to others. Since this was created a few days after the Beta release of the people plugin, its very likely to break soon. Please open an issue or make a PR on github if you find problems in the future.

| 466 | Markdown | 50.888883 | 262 | 0.770386 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/cust_go.py | from omni.anim.people.scripts.commands.goto import GoTo
class CustomGo(GoTo):
def __init__(self, character, command, navigation_manager):
super().__init__(character, command, navigation_manager)
def update_path(self, new_command):
''' update the path on the goto command by generating a new one
check that the current position was broadcast
Note: This is NOT related to the navigation_manager update_path
'''
self.navigation_manager.generate_goto_path(new_command)
| 533 | Python | 34.599998 | 71 | 0.681051 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/extension.py | import omni.ext
import omni.ui as ui
import omni.usd
import os
import omni.kit.commands
from pxr import Sdf
class SiborgSimulateWalkExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[siborg.simulate.walk] siborg simulate walk startup")
self._window = ui.Window("Walk to Goal Behavior", width=300, height=100)
self.stage = omni.usd.get_context().get_stage()
with self._window.frame:
with ui.VStack():
def add_walk_to_prim():
# Could also Create/Get/Set Attribute
# self._person_prim.SetCustomDataByKey("target_goal", (0,0,0,0))
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Get them as prims
prims = [self.stage.GetPrimAtPath(x) for x in selected_paths]
dir_path = os.path.dirname(os.path.realpath(__file__))
behavior_script = os.path.join(dir_path, 'cust_behavior.py')
for prim_path in selected_paths:
add_animation_graph(prim_path)
for prim in prims:
add_behavior_script(prim, behavior_script)
ui.Button("Add Walk", clicked_fn=add_walk_to_prim)
def on_shutdown(self):
print("[siborg.simulate.walk] siborg simulate walk shutdown")
def add_animation_graph(prim_path):
omni.kit.commands.execute('ApplyAnimationGraphAPICommand',
paths=[Sdf.Path(prim_path)],
animation_graph_path=Sdf.Path('/World/Biped_Setup/CharacterAnimation/AnimationGraph'))
def add_behavior_script(prim, script):
omni.kit.commands.execute('ApplyScriptingAPICommand', paths=[Sdf.Path(prim.GetPath())])
omni.kit.commands.execute('RefreshScriptingPropertyWindowCommand')
attr = prim.GetAttribute("omni:scripting:scripts")
val = attr.Get()
if val:
scripts = list(val)
scripts.append(scripts)
attr.Set(scripts)
else:
attr.Set([script])
| 2,250 | Python | 34.730158 | 94 | 0.599556 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/cust_behavior.py |
from __future__ import annotations
from pxr import Gf, UsdGeom, Usd, Sdf
import omni.usd
from omni.anim.people.scripts.character_behavior import CharacterBehavior
from .cust_go import CustomGo as GoTo
class CustomBehavior(CharacterBehavior):
def __init__(self, prim_path: Sdf.Path):
super().__init__(prim_path)
def on_init(self):
super().on_init()
# This could be simply in renew_character_state, but this is easier to follow
self.assign_goal()
def assign_goal(self):
# # Create an xform
newpath = self.prim_path.AppendPath('Goal')
# check if there is already a Goal (and if there is,
# whoever added better have a transform)
prim: Usd.Prim = self.stage.GetPrimAtPath(newpath)
# Need to set all of these to make transforms work can't just use translate
if not prim:
xform_faster = UsdGeom.Xform.Define(self.stage, newpath)
prim_trans = xform_faster.AddTranslateOp()
prim_trans.Set(Gf.Vec3f(0.0, 0.0, 0.0))
prim_rot = xform_faster.AddOrientOp()
prim_rot.Set(Gf.Quatf(0.0, 0.0, 0.0, 1.0))
prim_scale = xform_faster.AddScaleOp()
prim_scale.Set(Gf.Vec3f(1.0, 1.0, 1.0))
self.goal_prim = self.stage.GetPrimAtPath(newpath)
def on_play(self):
# Make sure we have a goal (incase someone deleted it after creating character)
super().on_play()
self.assign_goal()
def get_command(self, command):
if command[0] == "GoTo":
return GoTo(self.character, command, self.navigation_manager)
# We don't really need this right now, but just a reminder of other possible commands
return super().get_command(command)
# def read_commands_from_file(self):
# ''' Overwritten method to skip the file reading part '''
# # The command parser creates this format, so we just use it for now
# return [['GoTo', '0', '0', '0', '0']]
def get_simulation_commands(self):
''' Overwritten method to skip the file reading part '''
# The command parser creates this format, so we just use it for now
return [['GoTo', '0', '0', '0', '0']]
def on_update(self, current_time: float, delta_time: float):
"""
Called on every update. Initializes character at start,
publishes character positions and executes character commands.
:param float current_time: current time in seconds.
:param float delta_time: time elapsed since last update.
"""
if self.character is None:
if not self.init_character():
return
# Make sure we have an active goal
if not self.goal_prim.IsValid():
# This should only happen if goal prim was deleted during Play
# The existing goal will still be in memory and animation continues there
return
if self.avoidanceOn:
self.navigation_manager.publish_character_positions(delta_time, 0.5)
if self.commands:
if self.current_command:
# First get where the character currently is
# Get the current goal attribute
goal_position = omni.usd.get_world_transform_matrix(self.goal_prim).ExtractTranslation()
new_goal = (goal_position[0], goal_position[1], goal_position[2], 0)
# Two options to try `query_navmesh_path` and `validate_navmesh_point`
# For now, we pre-query the path to check if it will work, and if not, just skip trying to update
cur_pos = self.navigation_manager.character_manager.get_character_current_pos(self.prim_path.pathString)
test_path = self.navigation_manager.navigation_interface.query_navmesh_path(cur_pos, new_goal)
# If there is no path, don't go there
if test_path is None:
return
self.current_command.update_path(new_goal)
self.execute_command(self.commands, delta_time)
| 4,105 | Python | 37.018518 | 120 | 0.61827 |
cadop/ov_dhart/README.md | # DHART for Omniverse
If you have feature requests or need help with generating graphs, running algorithms, etc. please visit the main repo https://github.com/cadop/dhart. This repo is only for the omniverse extension part.
| 229 | Markdown | 37.333327 | 203 | 0.781659 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/usd_utils.py | import numpy as np
from pxr import UsdGeom, Gf, Usd
def traverse_instanced_children(prim):
"""Get every Prim child beneath `prim`, even if `prim` is instanced.
Important:
If `prim` is instanced, any child that this function yields will
be an instance proxy.
Args:
prim (`pxr.Usd.Prim`): Some Prim to check for children.
Yields:
`pxr.Usd.Prim`: The children of `prim`.
"""
for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies()):
yield child
for subchild in traverse_instanced_children(child):
yield subchild
def parent_and_children_as_mesh(parent_prim):
if parent_prim.IsA(UsdGeom.Mesh):
points, faces = get_mesh(parent_prim)
return points, faces
found_meshes = []
for x in traverse_instanced_children(parent_prim):
if x.IsA(UsdGeom.Mesh):
found_meshes.append(x)
# children = parent_prim.GetAllChildren()
# children = [child.GetPrimPath() for child in children]
# points, faces = get_mesh(children)
points, faces = get_mesh(found_meshes)
return points, faces
def children_as_mesh(stage, parent_prim):
children = parent_prim.GetAllChildren()
children = [child.GetPrimPath() for child in children]
points, faces = get_mesh(stage, children)
return points, faces
def get_all_stage_mesh(stage):
found_meshes = []
# Traverse the scene graph and print the paths of prims, including instance proxies
for x in Usd.PrimRange(stage.GetPseudoRoot(), Usd.TraverseInstanceProxies()):
if x.IsA(UsdGeom.Mesh):
found_meshes.append(x)
points, faces = get_mesh(found_meshes)
return points, faces
def get_mesh(objs):
points, faces = [],[]
for obj in objs:
f_offset = len(points)
f, p = meshconvert(obj)
if len(p) == 0: continue
points.extend(p)
faces.extend(f+f_offset)
return points, faces
def meshconvert(prim):
# Create an XformCache object to efficiently compute world transforms
xform_cache = UsdGeom.XformCache()
# Get the mesh schema
mesh = UsdGeom.Mesh(prim)
# Get verts and triangles
tris = mesh.GetFaceVertexIndicesAttr().Get()
if not tris:
return [], []
tris_cnt = mesh.GetFaceVertexCountsAttr().Get()
# Get the vertices in local space
points_attr = mesh.GetPointsAttr()
local_points = points_attr.Get()
# Convert the VtVec3fArray to a NumPy array
points_np = np.array(local_points, dtype=np.float64)
# Add a fourth component (with value 1.0) to make the points homogeneous
num_points = len(local_points)
ones = np.ones((num_points, 1), dtype=np.float64)
points_np = np.hstack((points_np, ones))
# Compute the world transform for this prim
world_transform = xform_cache.GetLocalToWorldTransform(prim)
# Convert the GfMatrix to a NumPy array
matrix_np = np.array(world_transform, dtype=np.float64).reshape((4, 4))
# Transform all vertices to world space using matrix multiplication
world_points = np.dot(points_np, matrix_np)
tri_list = convert_to_triangle_mesh(tris, tris_cnt)
# tri_list = tri_list.flatten()
world_points = world_points[:,:3]
return tri_list, world_points
def convert_to_triangle_mesh(FaceVertexIndices, FaceVertexCounts):
"""
Convert a list of vertices and a list of faces into a triangle mesh.
A list of triangle faces, where each face is a list of indices of the vertices that form the face.
"""
# Parse the face vertex indices into individual face lists based on the face vertex counts.
faces = []
start = 0
for count in FaceVertexCounts:
end = start + count
face = FaceVertexIndices[start:end]
faces.append(face)
start = end
# Convert all faces to triangles
triangle_faces = []
for face in faces:
if len(face) < 3:
newface = [] # Invalid face
elif len(face) == 3:
newface = [face] # Already a triangle
else:
# Fan triangulation: pick the first vertex and connect it to all other vertices
v0 = face[0]
newface = [[v0, face[i], face[i + 1]] for i in range(1, len(face) - 1)]
triangle_faces.extend(newface)
return np.array(triangle_faces)
| 4,394 | Python | 28.3 | 102 | 0.643605 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/extension.py | import omni.ext
import omni.ui as ui
from . import core
from . import render
from . import window
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DhartExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ov_dhart] DHART is startingup")
# Initialize DHART class and event subscription
self.initialize()
# Setup GUI
self.show_window()
def show_window(self):
self._window = window.populate_window(self.DI, render)
def initialize(self):
''' Initialization and any setup needed '''
self.DI = core.DhartInterface()
# ### Subscribe to events
# self._usd_context = omni.usd.get_context()
# self._selection = self._usd_context.get_selection()
# self._events = self._usd_context.get_stage_event_stream()
# self._stage_event_sub = self._events.create_subscription_to_pop(self._on_stage_event,
# name='my stage update'
# )
def _on_stage_event(self, event):
''' subscription to an event on the stage '''
# When a selection is changed, call our function
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
''' where we do stuff on the event that notified us a stage selection changed '''
# Gets the selected prim paths
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
# Empty list to be filled of selection prims
prim_selections = []
# Check if there is a valid selection and stage
if selection and stage:
# Make a list of the selection prims
for selected_path in selection:
prim = stage.GetPrimAtPath(selected_path)
prim_selections.append(prim)
if prim_selections:
core.DhartInterface.active_selection = prim_selections
print(f'Set DI to {prim_selections}')
def on_shutdown(self):
print("[ov_dhart] DHART is shutting down")
| 2,650 | Python | 36.871428 | 119 | 0.604906 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/__init__.py | from .extension import *
import os
def package_dir():
''' Helper to get directory of this pacckage '''
return os.path.dirname(os.path.realpath(__file__)) | 163 | Python | 22.428568 | 54 | 0.680982 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/core.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, PhysxSchema, Vt
try:
from omni.usd.utils import get_world_transform_matrix
except:
from omni.usd import get_world_transform_matrix
import omni.physx
import numpy as np
from scipy.interpolate import splprep, splev
import dhart
import dhart.geometry
import dhart.raytracer
import dhart.graphgenerator
from dhart import pathfinding
from dhart.visibilitygraph import VisibilityGraphAllToAll
from dhart.visibilitygraph import VisibilityGraphUndirectedAllToAll
from dhart.visibilitygraph import VisibilityGraphGroupToGroup
from dhart.spatialstructures.cost_algorithms import CalculateEnergyExpenditure, CostAlgorithmKeys
from dhart.spatialstructures import Graph, Direction
from . import usd_utils
import time
class DhartInterface():
# Global class variable
active_selection = None
def __init__(self):
# BVH for DHART
self.bvh = None
self.vis_bvh = None # Separate BVH for storing opaque objects
self.VG = None
self.VG_group = None
self.graph = None
# Selected Starting Location
self.start_prim = None
self.node_size = 15
self.path_size = 20
# Set 0 start
self.start_point = [0,0,0]
# Set max nodes
self.max_nodes = 400
self.grid_spacing = [20,20]
self.height = 80
self.upstep = 30
self.downstep = 30
self.upslope = 20
self.downslope = 20
self.targ_vis_path = '/World/TargetNodes'
self.path_start_path = '/World/StartPath'
self.path_end_path = '/World/EndPath'
# Track
self.gui_start = []
self.gui_end = []
def set_as_start(self):
''' Sets the DhartInterface.active_selection to the start prim '''
self.start_point = self.get_selected_as_point()
self.gui_start[0].model.set_value(self.start_point[0])
self.gui_start[1].model.set_value(self.start_point[1])
self.gui_start[2].model.set_value(self.start_point[2])
def set_as_end(self):
''' Sets the DhartInterface.active_selection to the end prim '''
self.end_point = self.get_selected_as_point()
self.gui_end[0].model.set_value(self.end_point[0])
self.gui_end[1].model.set_value(self.end_point[1])
self.gui_end[2].model.set_value(self.end_point[2])
def get_selected_as_point(self):
''' Sets the DhartInterface.active_selection to the start prim '''
# Get the current active selection of the stage
self.stage = omni.usd.get_context().get_stage()
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Expects a list, so take first selection
prim = [self.stage.GetPrimAtPath(x) for x in selected_paths][0]
# try:
# selected_point = get_world_transform_matrix(prim).ExtractTranslation()
# except:
# selected_point = omni.usd.get_world_transform_matrix(prim).ExtractTranslation()
selected_point = get_world_transform_matrix(prim).ExtractTranslation()
return selected_point
def modify_start(self,x=None,y=None,z=None):
if x: self.start_point[0] = x
if y: self.start_point[1] = y
if z: self.start_point[2] = z
print(f'START IS: {self.start_point}')
def modify_end(self,x=None,y=None,z=None):
if x: self.end_point[0] = x
if y: self.end_point[1] = y
if z: self.end_point[2] = z
print(f'END IS: {self.end_point}')
def set_as_bvh(self):
# Set the graph bvh
self.set_bvh(vis=False)
def set_as_vis_bvh(self):
# Set the visibility-based bvh
self.set_bvh(vis=True)
def set_bvh(self, vis=False):
# Get the current active selection of the stage
self.stage = omni.usd.get_context().get_stage()
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Expects a list, so take first selection
prims = [self.stage.GetPrimAtPath(x) for x in selected_paths]
# Record if a BVH was generated
made_bvh = False
for prim in prims:
MI = self.convert_to_mesh(prim)
if MI is None:
print("BVH FAILED")
continue
if not made_bvh:
if vis:
self.vis_bvh = dhart.raytracer.EmbreeBVH(MI)
print(f'VIS BVH is: {self.vis_bvh}')
else:
self.bvh = dhart.raytracer.EmbreeBVH(MI)
# self.bvh = dhart.raytracer.EmbreeBVH(MI, use_precise=True)
print(f'BVH is: {self.bvh}')
made_bvh = True
else:
if vis:
self.vis_bvh.AddMesh(MI)
print('Added to VIS BVH')
else:
self.bvh.AddMesh(MI)
print('Added to BVH')
# for prim in prims:
# prim_type = prim.GetTypeName()
# # Only add if its a mesh
# if prim_type == 'Mesh':
# MI = self.convert_to_mesh_old(prim)
# # MI = self.convert_to_mesh(prim)
# if MI is None:
# print("BVH FAILED")
# continue
# if not made_bvh:
# if vis:
# self.vis_bvh = dhart.raytracer.EmbreeBVH(MI)
# print(f'VIS BVH is: {self.vis_bvh}')
# else:
# self.bvh = dhart.raytracer.EmbreeBVH(MI)
# print(f'BVH is: {self.bvh}')
# made_bvh = True
# else:
# if vis:
# self.vis_bvh.AddMesh(MI)
# print('Added to VIS BVH')
# else:
# self.bvh.AddMesh(MI)
# print('Added to BVH')
def set_max_nodes(self, m):
self.max_nodes = m
def set_spacing(self, xy):
self.grid_spacing = [xy,xy]
def set_height(self, z):
self.height = z
def set_upstep(self, u):
self.upstep = u
def set_upslope(self, us):
self.upslope = us
def set_downstep(self, d):
self.downstep = d
def set_downslope(self, ds):
self.downslope = ds
def set_nodesize(self, s):
self.node_size = s
def set_pathsize(self, s):
self.path_size = s
def generate_graph(self):
''' use dhart to generate a graph '''
if not self.bvh:
print("No BVH")
return
self.scene_setup()
spacing = (self.grid_spacing[0], self.grid_spacing[1], self.height)
max_nodes = self.max_nodes
self.graph = dhart.graphgenerator.GenerateGraph(self.bvh,
self.start_point,
spacing,
max_nodes,
up_step = self.upstep,
down_step = self.downstep,
up_slope = self.upslope,
down_slope=self.downslope,
cores=-1)
if self.graph:
self.graph.CompressToCSR()
self.nodes = self.graph.getNodes().array[['x','y','z']]
print(f'Got {len(self.nodes)} Nodes')
else:
print("FAILED")
return
self.create_geompoints(self.nodes.tolist())
def get_to_nodes(self):
parent_prim = self.stage.GetPrimAtPath(self.targ_vis_path)
children = parent_prim.GetAllChildren()
b_nodes = []
for child in children:
t = get_world_transform_matrix(child).ExtractTranslation()
b_nodes.append(np.asarray(t))
return b_nodes
def visibility_graph_groups(self):
start_t = time.time()
nodes_a = self.nodes # Define points as the graph nodes
nodes_b = self.get_to_nodes()
self.VG_group = VisibilityGraphGroupToGroup(self.vis_bvh, nodes_a, nodes_b, self.height) # Calculate the visibility graph
if self.VG_group is None:
print('VG Failed')
return
# visibility_graph = VG.CompressToCSR() # Convert to a CSR (matrix)
scores = self.VG_group.AggregateEdgeCosts(2, True) # Aggregate the visibility graph scores
scores = scores[:-len(nodes_b)] # remove b nodes
print(f'VG group time = {time.time()-start_t}')
# add scores to node attributes
attr = "vg_group"
ids = self.graph.getNodes().array['id']
str_scores = [str(1.0/(x+0.01)) for x in scores] # we need scores to be a string for dhart. was to encode any type of node data
self.graph.add_node_attributes(attr, ids, str_scores)
self.score_vg(scores)
def visibility_graph(self):
start_t = time.time()
points = self.graph.getNodes() # Define points as the graph nodes
self.VG = VisibilityGraphUndirectedAllToAll(self.vis_bvh, points, self.height) # Calculate the visibility graph
# VG = VisibilityGraphAllToAll(self.bvh, points, self.height) # Calculate the visibility graph
scores = self.VG.AggregateEdgeCosts(2, True) # Aggregate the visibility graph scores
print(f'VG time = {time.time()-start_t}')
# add scores to node attributes
attr = "vg_all"
ids = self.graph.getNodes().array['id']
str_scores = [str(x) for x in scores] # we need scores to be a string for dhart. was to encode any type of node data
self.graph.add_node_attributes(attr, ids, str_scores)
self.score_vg(scores)
def reset_endpoints(self):
s_prim = self.stage.GetPrimAtPath(self.path_start_path)
self.start_point = get_world_transform_matrix(s_prim).ExtractTranslation()
e_prim = self.stage.GetPrimAtPath(self.path_end_path)
self.end_point = get_world_transform_matrix(e_prim).ExtractTranslation()
def get_path(self):
''' Get the shortest path by distance '''
# DHART requires passing the desired nodes (not the positions)
# So, we will allow users to select an arbitrary position and get the closest node ids to it
#### !!!! This was screwing up the graph generation because the start point was a bunch of decimals
self.reset_endpoints()
self.start_point = [int(x) for x in self.start_point]
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# nodes = self.graph.getNodes()
# matching_items = nodes[np.isin(nodes['id'], closest_nodes)]
# print(f'Start/End Nodes {matching_items}')
# self.show_nodes(matching_items[['x','y','z']].tolist())
path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1])
# print(f'Path Nodes: {path}')
if path is None:
print("No PATH Found")
return
path_xyz = np.take(self.nodes[['x','y','z']], path['id'])
print(len(path_xyz.tolist()))
path_list = path_xyz.tolist()
path_nodes = self.smooth_path(path_list)
self.create_curve(path_nodes)
# self.show_nodes(path_xyz.tolist())
def smooth_path(self, input_points):
'''
Interpolate the path and smooth the verts to be shown
'''
def interpolate_curve(points, num_points=100):
"""Interpolate the curve to produce a denser set of points."""
tck, u = splprep([[p[0] for p in points], [p[1] for p in points], [p[2] for p in points]], s=0)
u_new = np.linspace(0, 1, num_points)
x_new, y_new, z_new = splev(u_new, tck)
return list(zip(x_new, y_new, z_new))
# Re-define the moving_average function as provided by you
def moving_average(points, window_size=3):
"""Smoothen the curve using a moving average."""
if window_size < 3:
return points # Too small window, just return original points
extended_points = points[:window_size-1] + points + points[-(window_size-1):]
smoothed_points = []
for i in range(len(points)):
window = extended_points[i:i+window_size]
avg_x = sum(pt[0] for pt in window) / window_size
avg_y = sum(pt[1] for pt in window) / window_size
avg_z = sum(pt[2] for pt in window) / window_size
smoothed_points.append((avg_x, avg_y, avg_z))
return smoothed_points
# Smooth the original input points
smoothed_points = moving_average(input_points, window_size=4)
# Interpolate the smoothed curve to produce a denser set of points
interpolated_points = interpolate_curve(smoothed_points, num_points=500)
# Smooth the denser set of points
smoothed_interpolated_points = moving_average(interpolated_points, window_size=6)
return smoothed_interpolated_points
def show_nodes(self, nodes):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/Closest")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size*2])
# prim.CreateDisplayColorAttr()
# For RTX renderers, this only works for UsdGeom.Tokens.constant
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(0,0,1)])
def get_energy_path(self):
# Get the key
energy_cost_key = CostAlgorithmKeys.ENERGY_EXPENDITURE
CalculateEnergyExpenditure(self.graph)
self.reset_endpoints()
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
energy_path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], energy_cost_key)
path_xyz = np.take(self.nodes[['x','y','z']], energy_path['id'])
self.create_curve(path_xyz.tolist())
# As the cost array is numpy, simple operations to sum the total cost can be calculated
path_sum = np.sum(energy_path['cost_to_next'])
print('Total path cost: ', path_sum)
def get_visibility_path(self):
# make sure visibility graph was made
# get node ids and attrs of vg
self.reset_endpoints()
# assign new node attrs for visibility
csr = self.graph.CompressToCSR()
# Get attribute scores from the graph
# out_attrs = self.graph.get_node_attributes(attr)
self.graph.attrs_to_costs("vg_group", "vg_group_cost", Direction.INCOMING)
# self.graph.GetEdgeCost(1, 2, "vg_group_cost")
# get custom path based on vg
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
visibility_path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], 'vg_group_cost')
path_xyz = np.take(self.nodes[['x','y','z']], visibility_path['id'])
self.create_curve(path_xyz.tolist())
def get_vg_path(self):
# make sure visibility graph was made
# get node ids and attrs of vg
self.reset_endpoints()
# assign new node attrs for visibility
csr = self.graph.CompressToCSR()
# Get attribute scores from the graph
# out_attrs = self.graph.get_node_attributes(attr)
self.graph.attrs_to_costs("vg_all", "vg_all_cost", Direction.INCOMING)
# self.graph.GetEdgeCost(1, 2, "vg_group_cost")
# get custom path based on vg
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
visibility_path = DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], 'vg_all_cost')
path_xyz = np.take(self.nodes[['x','y','z']], visibility_path['id'])
self.create_curve(path_xyz.tolist())
def scene_setup(self):
# Get stage.
self.stage = omni.usd.get_context().get_stage()
def score_vg(self, scores):
scores = np.asarray(scores)
colors = calc_colors(scores)
self.create_colored_geompoints(self.nodes.tolist(), colors)
def create_colored_geompoints(self, nodes, colors=None):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/VGPoints")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.vertex)
color_primvar.Set(colors)
def create_geompoints(self, nodes):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/Points")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(1,0,0)])
def create_curve(self, nodes):
'''Create and draw a BasisCurve on the stage following the nodes'''
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.BasisCurves.Define(stage, "/World/Path")
prim.CreatePointsAttr(nodes)
# Set the number of curve verts to be the same as the number of points we have
curve_verts = prim.CreateCurveVertexCountsAttr()
curve_verts.Set([len(nodes)])
# Set the curve type to linear so that each node is connected to the next
type_attr = prim.CreateTypeAttr()
type_attr.Set('linear')
type_attr = prim.GetTypeAttr().Get()
# Set the width of the curve
width_attr = prim.CreateWidthsAttr()
# width_attr = prim.CreateWidthsAttr(UsdGeom.Tokens.varying)
width_attr.Set([self.path_size for x in range(len(nodes))])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(0,1,0)])
return
def convert_to_mesh(self,prim):
vert_list, tri_list = usd_utils.parent_and_children_as_mesh(prim)
# vert_list, tri_list = usd_utils.get_mesh([prim])
tri_list = np.array(tri_list).flatten()
vert_list = np.array(vert_list).flatten()
try:
MI = dhart.geometry.MeshInfo(tri_list, vert_list, "testmesh", 0)
return MI
except:
print(prim)
return None
def convert_to_mesh_old(self, prim):
''' convert a prim to BVH '''
# Get mesh name (prim name)
m = UsdGeom.Mesh(prim)
# Get verts and triangles
tris = m.GetFaceVertexIndicesAttr().Get()
tris_cnt = m.GetFaceVertexCountsAttr().Get()
verts = m.GetPointsAttr().Get()
tri_list = np.array(tris)
vert_list = np.array(verts)
xform = UsdGeom.Xformable(prim)
time = Usd.TimeCode.Default() # The time at which we compute the bounding box
world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time)
translation: Gf.Vec3d = world_transform.ExtractTranslation()
rotation: Gf.Rotation = world_transform.ExtractRotationMatrix()
scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix()))
vert_rotated = np.dot(vert_list, rotation) # Rotate points
vert_translated = vert_rotated + translation
vert_scaled = vert_translated
vert_scaled[:,0] *= scale[0]
vert_scaled[:,1] *= scale[1]
vert_scaled[:,2] *= scale[2]
vert_list = vert_scaled
vert_list = vert_translated.flatten()
# Check if the face counts are 4, if so, reshape and turn to triangles
if tris_cnt[0] == 4:
quad_list = tri_list.reshape(-1,4)
tri_list = quad_to_tri(quad_list)
tri_list = tri_list.flatten()
try:
MI = dhart.geometry.MeshInfo(tri_list, vert_list, "testmesh", 0)
return MI
except:
print(prim)
return None
def quad_to_tri(a):
idx = np.flatnonzero(a[:,-1] == 0)
out0 = np.empty((a.shape[0],2,3),dtype=a.dtype)
out0[:,0,1:] = a[:,1:-1]
out0[:,1,1:] = a[:,2:]
out0[...,0] = a[:,0,None]
out0.shape = (-1,3)
mask = np.ones(out0.shape[0],dtype=bool)
mask[idx*2+1] = 0
return out0[mask]
def calc_colors(scores):
filtered_scores = [score for score in scores if score>=0]
max_v = max(filtered_scores)
min_v = min(filtered_scores)
print('maxmin')
print(max_v)
print(min_v)
print('')
if (max_v == 0):
print("Max is zero!")
exit()
elif(max_v - min_v == 0):
print("All values are the same!")
return [colorbar(1.0)] * len(scores)
return [
colorbar((point-min_v)/(max_v-min_v))
if point >= 0
else None
for point in scores
]
def colorbar(val):
r = min(max(0, 1.5-abs(1-4*(val-0.5))),1)
g = min(max(0, 1.5-abs(1-4*(val-0.25))),1)
b = min(max(0, 1.5-abs(1-4*val)),1)
return np.asarray([r,g,b], dtype=float)
| 22,274 | Python | 34.07874 | 135 | 0.582203 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/render.py |
from pxr import Sdf, Usd, UsdGeom
import omni
def create_perspective_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera:
camera_path = Sdf.Path(prim_path)
usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective)
return usd_camera
def assign_camera():
''' insert actiongraph to stage (if not already there) and make a camera '''
stage = omni.usd.get_context().get_stage()
cam_path = "/World/FlyCam"
camera = create_perspective_camera(stage, cam_path)
| 596 | Python | 30.421051 | 102 | 0.713087 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/ext_with_layout.py | import os
import omni.ext
import omni.ui as ui
from omni.kit.quicklayout import QuickLayout
from . import core
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DhartExtension2():
# class DhartExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
MENU_PATH = "Analysis/DHART"
_instance = None
def on_startup(self, ext_id):
print("[omni.dhart] MyExtension startup")
# Add a window menu item so we can easily find the package
self._window = None
try:
self._menu = omni.kit.ui.get_editor_menu().add_item(
DhartExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
except Exception as e:
self._menu = None
self.initialize()
### Subscribe to events
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(self._on_stage_event,
name='my stage update'
)
DhartExtension._instance = self
def _visiblity_changed_fn(self, visible):
if self._menu:
omni.kit.ui.get_editor_menu().set_value(DhartExtension.MENU_PATH, visible)
def show_window(self, menu, value):
print('Passed Class instantiation')
if value:
# self._clean_up_window()
self.initialize()
self._window = ui.Window("DHART", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
ui.Button("Generate BVH", clicked_fn=lambda: self.DI.convert_mesh())
ui.Button("Generate Graph", clicked_fn=lambda: self.DI.graph())
with ui.HStack():
ui.Label("timesteps: ")
dt = ui.IntField(height=20)
dt.model.set_value(60)
dt.model.add_value_changed_fn(lambda m: self.Sim.set_sim_steps(m.get_value_as_int()))
# Just for fun, does it automatically
with ui.HStack():
# with ui.HStack(width=100):
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
print(workspace_filename)
ui.Button("Save Layout", clicked_fn=lambda: QuickLayout.save_file(workspace_filename))
ui.Button("Load Layout", clicked_fn=lambda: QuickLayout.load_file(workspace_filename))
# Load workspace layout
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
QuickLayout.load_file(workspace_filename)
if self._menu:
print("Setting menu")
omni.kit.ui.get_editor_menu().set_value(DhartExtension.MENU_PATH, True)
else:
print("Couldn't setup ")
def initialize(self):
''' Initializer for setting up the class reference to our other functions '''
self.DI = core.DhartInterface()
def _on_stage_event(self, event):
''' subscription to an event on the stage '''
# When a selection is changed, call our function
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
''' where we do stuff on the event that notified us a stage selection changed '''
# Gets the selected prim paths
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
print(f'== selection changed with {len(selection)} items')
prim_selections = [] # Empty list to be filled of selection prims
# Check if there is a valid selection and stage
if selection and stage:
# Make a list of the selection prims
for selected_path in selection:
print(f' item {selected_path}:')
prim = stage.GetPrimAtPath(selected_path)
prim_type = prim.GetTypeName()
print(prim_type)
if prim_type == 'Mesh':
prim_selections.append(prim)
# Call our meshinfo conversion if we have data in selection
if prim_selections:
self.DI.set_active_mesh(prim_selections)
def on_shutdown(self):
print("[omni.dhart] MyExtension shutdown")
# Save current scene layout
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
QuickLayout.save_file(workspace_filename)
try:
self._window = None
self._stage_event_sub = None
# Set the dhart interface instance to None
self.DI = None
except: pass
self._menu = None
# Run some extra cleanup for the window
self._clean_up_window()
# set this class to none as the last thing we do so it can be newly instantiated later
DhartExtension._instance = None
# print('Cleaned up')
def _clean_up_window(self):
''' make sure we cleanup the window '''
if self._window is not None:
self._window.destroy()
self._window = None | 6,041 | Python | 38.233766 | 119 | 0.577057 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/ui.py |
### Place object to set starting point
### Click to select start point
### Grid spacing, meshes to use, etc. | 117 | Python | 9.727272 | 38 | 0.65812 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/window.py | import omni.ui as ui
def populate_window(DI, render):
_window = ui.Window("DHART", width=600, height=600)
with _window.frame:
with ui.VStack():
with ui.HStack(height=5):
ui.Button("Set Start Position", clicked_fn=lambda: DI.set_as_start(), height=5)
# start_pos = ui.MultiIntField(0,0,0)
with ui.HStack():
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m : DI.modify_start(x=m.get_value_as_int()))
y = ui.IntField(height=5)
y.model.add_value_changed_fn(lambda m : DI.modify_start(y=m.get_value_as_int()))
z = ui.IntField(height=5)
z.model.add_value_changed_fn(lambda m : DI.modify_start(z=m.get_value_as_int()))
DI.gui_start = [x,y,z]
with ui.HStack(height=5):
ui.Button("Set End Position", clicked_fn=lambda: DI.set_as_end(),height=5)
# end_pos = ui.MultiIntField(0,0,0)
with ui.HStack():
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m : DI.modify_end(x=m.get_value_as_int()))
y = ui.IntField(height=5)
y.model.add_value_changed_fn(lambda m : DI.modify_end(y=m.get_value_as_int()))
z = ui.IntField(height=5)
z.model.add_value_changed_fn(lambda m : DI.modify_end(z=m.get_value_as_int()))
DI.gui_end = [x,y,z]
with ui.HStack(height=5):
ui.Label(" Max Nodes: ")
max_nodes = ui.IntField(height=5)
max_nodes.model.add_value_changed_fn(lambda m : DI.set_max_nodes(m.get_value_as_int()))
max_nodes.model.set_value(DI.max_nodes)
with ui.VStack(height=5):
with ui.HStack(height=5):
ui.Label(" Grid Spacing: ")
grid_spacing = ui.FloatField(height=5)
grid_spacing.model.add_value_changed_fn(lambda m : DI.set_spacing(m.get_value_as_float()))
grid_spacing.model.set_value(DI.grid_spacing[0])
ui.Label(" Height Spacing: ")
height_space = ui.FloatField(height=5)
height_space.model.add_value_changed_fn(lambda m : DI.set_height(m.get_value_as_float()))
height_space.model.set_value(DI.height)
with ui.HStack(height=5):
ui.Label(" Upstep: ")
upstep = ui.FloatField(height=5)
upstep.model.add_value_changed_fn(lambda m : DI.set_upstep(m.get_value_as_float()))
upstep.model.set_value(DI.upstep)
ui.Label(" Upslope: ")
upslope = ui.FloatField(height=5)
upslope.model.add_value_changed_fn(lambda m : DI.set_upslope(m.get_value_as_float()))
upslope.model.set_value(DI.upslope)
with ui.HStack(height=5):
ui.Label(" Downstep: ")
downstep = ui.FloatField(height=5)
downstep.model.add_value_changed_fn(lambda m : DI.set_downstep(m.get_value_as_float()))
downstep.model.set_value(DI.downstep)
ui.Label(" Downslope: ")
downslope = ui.FloatField(height=5)
downslope.model.add_value_changed_fn(lambda m : DI.set_downslope(m.get_value_as_float()))
downslope.model.set_value(DI.downslope)
with ui.HStack(height=5):
ui.Label(" Node Size: ")
node_size = ui.FloatField(height=5)
node_size.model.add_value_changed_fn(lambda m : DI.set_nodesize(m.get_value_as_float()))
node_size.model.set_value(DI.node_size)
ui.Label(" Path Size: ")
path_size = ui.FloatField(height=5)
path_size.model.add_value_changed_fn(lambda m : DI.set_pathsize(m.get_value_as_float()))
path_size.model.set_value(DI.path_size)
with ui.HStack(height=5):
ui.Button("Set Mesh for BVH", clicked_fn=lambda: DI.set_as_bvh(), height=50)
ui.Button("Set Mesh for Visibility BVH", clicked_fn=lambda: DI.set_as_vis_bvh(), height=50)
ui.Button("Generate Graph", clicked_fn=lambda: DI.generate_graph(), height=50)
with ui.HStack(height=5):
ui.Button("Visibility Graph", clicked_fn=lambda: DI.visibility_graph(), height=50)
ui.Button("Visibility Graph to Points", clicked_fn=lambda: DI.visibility_graph_groups(), height=50)
with ui.HStack(height=5):
ui.Button("Find Path", clicked_fn=lambda: DI.get_path(), height=50)
ui.Button("Find Energy Path", clicked_fn=lambda: DI.get_energy_path(), height=50)
ui.Button("Find Visibility Path", clicked_fn=lambda: DI.get_visibility_path(), height=50)
ui.Button("Find VG Path", clicked_fn=lambda: DI.get_vg_path(), height=50)
ui.Button("Set Camera on Path", clicked_fn=lambda: render.assign_camera(), height=30)
return _window | 5,499 | Python | 50.401869 | 115 | 0.519549 |
cadop/ov_dhart/exts/siborg.analysis.dhart/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.4"
preview_image = "preview.jpg"
# The title and description fields are primarily for displaying extension info in UI
title = "DHART for Omniverse"
description="An omniverse extension for DHART using the python API."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
icon = "icon.jpg"
# URL of the extension source repository.
repository = "github.com/cadop/ov_dhart"
# One of categories for UI.
category = "Analysis"
# Keywords for the extension
keywords = ["kit", "design","robotics"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.physx" = {}
# Main python module this extension provides, it will be publicly available as "import SiBoRG.analysis.dhart".
[[python.module]]
name = "siborg.analysis.dhart"
[python.pipapi]
use_online_index = true
# Use this to specify a list of additional repositories if your pip package is hosted somewhere other
# than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument
# repositories = ["https://test.pypi.org/simple/"]
requirements = ["dhart"] | 1,196 | TOML | 26.837209 | 110 | 0.735786 |
cadop/curvedistribute/README.md | # curvedistribute
| 20 | Markdown | 5.999998 | 17 | 0.75 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/extension.py | import omni.ext
import omni.ui as ui
from omni.ui import color as cl
from pxr import Usd, UsdGeom, Gf, Sdf
import numpy as np
from scipy.interpolate import BSpline
import omni.usd
from . import utils
from .core import CurveManager, GeomCreator
AXIS = ["+X", "+Y", "+Z", "-X", "-Y", "-Z"] # taken from motion path
CURVES = ["Bezier", "BSpline"]
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class SiborgCreateCurvedistributeExtension(omni.ext.IExt):
def __init__(self, delegate=None, **kwargs):
super().__init__(**kwargs)
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[siborg.create.curvedistribute] siborg create curvedistribute startup")
#Models
self._source_prim_model = ui.SimpleStringModel()
self._source_curve_model = ui.SimpleStringModel()
self._use_instance_model = ui.SimpleBoolModel()
#Defaults
self._count = 0
self._source_prim_model.as_string = ""
self._source_curve_model.as_string = ""
self._sampling_resolution = 0
self._use_instance_model = False
self._use_orient_model = False
self._forward_axis = [1,0,0]
self._curve_type = utils.CURVE.Bezier
#Grab Prim in Stage on Selection
def _get_prim():
self._source_prim_model.as_string = ", ".join(utils.get_selection())
def _get_curve():
self._source_curve_model.as_string = ", ".join(utils.get_selection())
self._window = ui.Window("Distribute Along Curve", width=280, height=390)
with self._window.frame:
with ui.VStack(height=10, width=260, spacing=10):
select_button_style ={"Button":{"background_color": cl.cyan,
"border_color": cl.white,
"border_width": 2.0,
"padding": 4,
"margin_height": 1,
"border_radius": 10,
"margin_width":2},
"Button.Label":{"color": cl.black},
"Button:hovered":{"background_color": cl("#E5F1FB")}}
ui.Spacer()
ui.Label("Select Curve From Stage", tooltip="Select a BasisCurves type")
with ui.HStack():
ui.StringField(height=2, model=self._source_curve_model)
ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_curve)
ui.Spacer()
ui.Label("Get Prims From Stage", width=65, tooltip="Select multiple prims to distribute in sequence")
with ui.HStack():
ui.StringField(height=2, model=self._source_prim_model)
ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_prim)
ui.Spacer()
with ui.HStack():
ui.Label("Copies", tooltip="Number of copies to distribute. Endpoints are included in the count.")
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m, self=self: setattr(self, '_count', m.get_value_as_int()))
x.model.set_value(3)
ui.Label(" Subsamples", tooltip="A sampling parameter, don't touch if you don't understand")
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m, self=self: setattr(self, '_sampling_resolution', m.get_value_as_int()))
x.model.set_value(1000)
with ui.HStack():
# ui.StringField(height=2, model=self._source_prim_model)
# ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_prim)
ui.Label(" Use instances ", width=65, tooltip="Select to use instances when copying a prim")
instancer = ui.CheckBox(width=30)
instancer.model.add_value_changed_fn(lambda m : setattr(self, '_use_instance_model', m.get_value_as_bool()))
instancer.model.set_value(False)
ui.Label(" Follow Orientation ", width=65)
instancer = ui.CheckBox(width=30)
instancer.model.add_value_changed_fn(lambda m : setattr(self, '_use_orient_model', m.get_value_as_bool()))
instancer.model.set_value(False)
with ui.HStack():
ui.Label("Spline Type",
name="label",
width=160,
tooltip="Type of curve to use for interpolating control points")
ui.Spacer(width=13)
widget = ui.ComboBox(0, *CURVES).model
widget.add_item_changed_fn(lambda m, i: setattr(self, '_curve_type',
m.get_item_value_model().get_value_as_int()
)
)
with ui.HStack():
ui.Label("Forward Axis",
name="label",
width=160,
tooltip="Forward axis of target Object")
ui.Spacer(width=13)
widget = ui.ComboBox(0, *AXIS).model
widget.add_item_changed_fn(lambda m, i: setattr(self, '_forward_axis',
utils.index_to_axis(m.get_item_value_model().get_value_as_int())
)
)
with ui.VStack():
distribute_button_style = {"Button":{"background_color": cl.cyan,
"border_color": cl.white,
"border_width": 2.0,
"padding": 10,
"margin_height": 10,
"border_radius": 10,
"margin_width":5},
"Button.Label":{"color": cl.black},
"Button:hovered":{"background_color": cl("#E5F1FB")}}
ui.Button("Distribute", clicked_fn=lambda: GeomCreator.duplicate(self._count,
self._sampling_resolution,
self._source_curve_model,
self._source_prim_model,
self._use_instance_model,
self._use_orient_model,
self._forward_axis,
self._curve_type),
style=distribute_button_style)
def on_shutdown(self):
print("[siborg.create.curvedistribute] siborg create curvedistribute shutdown")
| 8,448 | Python | 54.585526 | 136 | 0.4375 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/core.py | from pxr import Usd, UsdGeom, Gf, Sdf, Vt
import numpy as np
from scipy.interpolate import BSpline, CubicSpline
import omni.usd
from scipy.interpolate import splprep, splev
from . import utils
class CurveManager():
def __init__(self):
pass
@classmethod
def cubic_bezier(cls, p0, p1, p2, p3, t):
'''Calculate position on a cubic Bezier curve given four control points.'''
return ((1 - t)**3) * p0 + 3 * ((1 - t)**2) * t * p1 + 3 * (1 - t) * t**2 * p2 + t**3 * p3
@classmethod
def create_bezier(cls, control_points, sampling_resolution):
'''Create a continuous cubic Bezier curve from a list of control points.'''
curve_points = []
t = np.linspace(0, 1, sampling_resolution) # defaulted to 100
for i in range(0, len(control_points) - 3, 3): # Step strides 3, bezier continous shared handles with neighbors
p0, p1, p2, p3 = control_points[i], control_points[i + 1], control_points[i + 2], control_points[i + 3]
bezier_segment = np.array([CurveManager.cubic_bezier(p0, p1, p2, p3, t_) for t_ in t])
curve_points.extend(bezier_segment)
return curve_points
@classmethod
def create_bspline(cls, control_points, sampling_resolution):
'''Create a continuous cubic Bezier curve from a list of control points.'''
# Create a BSpline object
k = 3 # degree of the spline
t = np.linspace(0, 1, len(control_points) - k + 1, endpoint=True)
t = np.append(np.zeros(k), t)
t = np.append(t, np.ones(k))
spl = BSpline(t, control_points, k)
#### If not using evenly distributed points, can just return this
# tnew = np.linspace(0, 1, num_points)
# interpolated_points = spl(tnew)
# return interpolated_points
# Calculate the total arc length of the spline
fine_t = np.linspace(0, 1, sampling_resolution)
curve_points = spl(fine_t)
return curve_points
@classmethod
def interpcurve(cls, stage, curve_path, num_points, sampling_resolution, curve_type=utils.CURVE.Bspline):
'''Interpolates a bezier curve based on the input points on the usd'''
# Get the curve prim and points that define it
curveprim = stage.GetPrimAtPath(curve_path)
points = curveprim.GetAttribute('points').Get()
control_points = np.array(points)
if sampling_resolution == 0: sampling_resolution = num_points
if curve_type == utils.CURVE.Bezier:
fine_points = CurveManager.create_bezier(control_points, sampling_resolution)
elif curve_type == utils.CURVE.Bspline:
fine_points = CurveManager.create_bspline(control_points, sampling_resolution)
else:
print("CURVE TYPE NOT IMPLEMENTED")
return
distances = np.sqrt(np.sum(np.diff(fine_points, axis=0)**2, axis=1))
total_length = np.sum(distances)
# Calculate the length of each segment
segment_length = total_length / (num_points - 1)
# Create an array of target lengths
target_lengths = np.array([i * segment_length for i in range(num_points)])
# Find the points at the target lengths
spaced_points = [control_points[0]] # Start with the first control point
point_dirs = [fine_points[1]- fine_points[0]] # Store the direction for each point
current_length = 0
j = 1 # Start from the second target length
for i in range(1, len(fine_points)):
segment_length = distances[i-1]
# Create strides to find when the next point should be accepted
while j < num_points - 1 and current_length + segment_length >= target_lengths[j]:
# Assign points
point = fine_points[i]
spaced_points.append(point)
# Get directions
direction = fine_points[i + 1] - point
# Normalize the direction vector
direction /= np.linalg.norm(direction)
point_dirs.append(direction)
j += 1
current_length += segment_length
# End with the last control point
spaced_points.append(control_points[-1])
last_dir = control_points[-1] - control_points[-2]
last_dir /= np.linalg.norm(last_dir)
point_dirs.append(last_dir)
return np.array(spaced_points), np.array(point_dirs)
@classmethod
def copy_to_points(cls, stage, target_points, target_dirs, ref_prims, path_to, _forward_axis, make_instance=False,
rand_order=False, use_orient=False, follow_curve=False):
'''
path_to: str, prefix to the prim path. automatically appends Copy
TODO: rand_order =True, use randomness to determine which prim to place
TODO: follow_curve=True, set rotation axis to match curve (different than orientation when curve is 3d)
'''
# Define a path for the new scope prim
scope_name = 'Copies'
scope_path = f"/World/{scope_name}"
# Create the scope prim at the specified path
scope_prim = UsdGeom.Scope.Define(stage, scope_path)
# Get index of prims that are not None and keep track
prim_set = [p for p in ref_prims if p != None]
# print(prim_set)
# print(f'isntance? : {make_instance}')
new_prims = []
if make_instance:
# Mark the original prims as instanceable if it has no children (like for a mesh)
for prim_path in prim_set:
# print(f'{prim_path=}')
original_prim = stage.GetPrimAtPath(prim_path)
# print(f'{original_prim=}')
# If this prim is not wrapped in an xform
if not original_prim.GetChildren():
ref_prim = original_prim
ref_prim_suffix = str(ref_prim.GetPath()).split('/')[-1]
# Create a new xform inside the scope
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_Source"
new_prim_xform_wrapper = stage.DefinePrim(primpath_to, "Xform")
# Make this new xform instanceable
new_prim_xform_wrapper.SetInstanceable(True)
# print(f'xform wrap path {new_prim_xform_wrapper}')
new_ref_prim = f"{new_prim_xform_wrapper.GetPath()}/{ref_prim_suffix}"
# Duplicate the prim and put it under a new xform
omni.usd.duplicate_prim(stage, ref_prim.GetPath(), new_ref_prim)
xform = UsdGeom.Xformable(new_prim_xform_wrapper)
# Get the list of xformOps
xform_ops = xform.GetOrderedXformOps()
# Check if translate op exists
has_translate_op = any(op.GetOpType() == UsdGeom.XformOp.TypeTranslate for op in xform_ops)
if not has_translate_op:
xform.AddTranslateOp()
has_Orient_op = any(op.GetOpType() == UsdGeom.XformOp.TypeOrient for op in xform_ops)
if not has_Orient_op:
xform.AddOrientOp()
ref_prim= str(new_prim_xform_wrapper.GetPath())
original_prim = stage.GetPrimAtPath(ref_prim)
# print("finished the xform wrapper")
original_prim.SetInstanceable(True)
new_prims.append(original_prim)
prim_set = new_prims
num_prims = len(prim_set)
cur_idx = 0
# Place the prims
for i, target_point in enumerate(target_points):
ref_prim = prim_set[cur_idx]
if make_instance:
prim_type = ref_prim.GetTypeName()
ref_prim_suffix = str(ref_prim.GetPath()).split('/')[-1]
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_{i}"
# Create a new prim and add a reference to the original prim
instance_prim = stage.DefinePrim(primpath_to, prim_type)
references = instance_prim.GetReferences()
references.AddInternalReference(ref_prim.GetPath())
# Move prim to desired location
cur_prim = instance_prim
else:
# Directly duplicate the prim
ref_prim_suffix = str(ref_prim).split('/')[-1]
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_{i}"
omni.usd.duplicate_prim(stage, ref_prim, primpath_to)
new_prim = stage.GetPrimAtPath(primpath_to)
cur_prim = new_prim
# Move prim to desired location
target_pos = Gf.Vec3d(tuple(target_point))
cur_prim.GetAttribute('xformOp:translate').Set(target_pos)
if use_orient:
# Make the forward vector face desired direction
target_direction = tuple(target_dirs[i])
# Ensure the target direction is a normalized Gf.Vec3f
target_direction = Gf.Vec3f(target_direction).GetNormalized()
target_direction = np.asarray(target_direction)
# Forward vector, assuming -Z is forward; change as per your convention
forward_vector = np.array(_forward_axis)
# Compute the cross product (rotation axis)
rotation_axis = np.cross(forward_vector, target_direction)
# Compute the dot product and then the angle
dot_product = np.dot(forward_vector, target_direction)
rotation_angle = np.arccos(np.clip(dot_product, -1.0, 1.0)) # Clipping for numerical stability
rot_ax = Vt.Vec3fArray.FromNumpy(rotation_axis)[0]
# Create a rotation quaternion
rotation_quat = Gf.Quatf(rotation_angle, rot_ax).GetNormalized()
# @TODO fix stupid hack
# Apply the rotation
try: cur_prim.GetAttribute('xformOp:orient').Set(Gf.Quatd(rotation_quat))
except: cur_prim.GetAttribute('xformOp:orient').Set(Gf.Quatf(rotation_quat))
if cur_idx < num_prims-1: cur_idx +=1
else: cur_idx = 0
class GeomCreator():
def __init__(self):
pass
@classmethod
def duplicate(cls, _count, _sampling_resolution, _source_curve_model, _source_prim_model,
_use_instance, _use_orient, _forward_axis, _curve_type):
'''
## All of these should work (assuming the named prim is there)
# ref_prims = ['/World/Cube']
# ref_prims = ['/World/Cube', None]
# ref_prims = ['/World/Cube', '/World/Cone']
'''
stage = omni.usd.get_context().get_stage()
curve_path = _source_curve_model.as_string
ref_prims = [_source_prim_model.as_string]
ref_prims = _source_prim_model.as_string.replace(' ','').split(',')
# _use_instance = _use_instance.as_bool
path_to = f'/Copy'
sampling_resolution = _sampling_resolution
num_points = _count
# Default to 3x the number of points to distribute? Actually might be handled already by interp
num_samples = _count
# TODO: make this setting for the resolution to sample the curve defined by user
interpolated_points, target_dirs = CurveManager.interpcurve(stage, curve_path, num_samples, sampling_resolution, _curve_type)
indices = np.linspace(0, len(interpolated_points) - 1, num_points, dtype=int)
target_points = interpolated_points[indices]
CurveManager.copy_to_points(stage, target_points, target_dirs, ref_prims, path_to, _forward_axis,
make_instance=_use_instance, use_orient=_use_orient)
| 12,324 | Python | 43.334532 | 133 | 0.566375 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/utils.py | import omni.usd
from typing import List
from pxr import Sdf
from enum import IntEnum
class CURVE(IntEnum):
Bezier = 0
Bspline = 1
Linear = 2
def get_selection() -> List[str]:
"""Get the list of currently selected prims"""
return omni.usd.get_context().get_selection().get_selected_prim_paths()
def index_to_axis(idx):
# AXIS = ["+X", "+Y", "+Z", "-X", "-Y", "-Z"] # taken from motion path
xp = [1,0,0]
yp = [0,1,0]
zp = [0,0,1]
xn = [-1,0,0]
yn = [0,-1,0]
zn = [0,0,-1]
axis_vecs = [xp,yp,zp,xn,yn,zn]
return axis_vecs[idx] | 598 | Python | 21.185184 | 75 | 0.556856 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/config.py | import codecs
import pickle
from typing import List
from pxr import Sdf, Usd
class Config:
path_glob: str
expanded_glob: List[str]
ppi: int
gap_pct: float
curve_pct: float
images_per_row: int
def set_config_metadata(prim: Usd.Prim, config: Config) -> None:
if not prim.IsValid():
return
config_str = codecs.encode(pickle.dumps(config), 'base64')
attribute: Usd.Attribute= prim.GetAttribute("imageseq:config")
if not attribute.IsValid():
attribute = prim.CreateAttribute("imageseq:config", Sdf.ValueTypeNames.String)
attribute.Set(config_str)
def get_config_metadata(prim: Usd.Prim) -> Config:
if not prim.IsValid():
raise Exception("programming error")
attribute: Usd.Attribute = prim.GetAttribute("imageseq:config")
if not attribute.IsValid():
return None
config_str = attribute.Get()
config_bytes = codecs.decode(config_str.encode(), 'base64')
config = pickle.loads(config_bytes)
return config
| 1,006 | Python | 26.972221 | 86 | 0.685885 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/extension.py | import asyncio
from functools import partial
import omni.ext
import omni.kit.app
import omni.kit.ui
import omni.ui
import omni.usd
from .window import KitImageSequenceWindow
class KitImageSequenceExtension(omni.ext.IExt):
WINDOW_NAME = "Image Sequence Importer"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
self._window = None
omni.ui.Workspace.set_show_window_fn(KitImageSequenceExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
KitImageSequenceExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
omni.ui.Workspace.show_window(KitImageSequenceExtension.WINDOW_NAME)
def on_shutdown(self):
if self._window:
self._window.destroy()
self._window = None
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.remove_item(KitImageSequenceExtension.MENU_PATH)
self._menu = None
# Deregister the function that shows the window from omni.ui
omni.ui.Workspace.set_show_window_fn(KitImageSequenceExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(KitImageSequenceExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visibility_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
if value:
self._window = KitImageSequenceWindow(KitImageSequenceExtension.WINDOW_NAME, width=300, height=365)
self._window.set_visibility_changed_fn(self._visibility_changed_fn)
elif self._window:
self._window.visible = False
| 2,611 | Python | 34.780821 | 116 | 0.644964 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/core.py | import math
from pathlib import Path
from typing import Dict, List
import carb
from PIL import Image
from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade
from .config import Config, set_config_metadata
def create_textured_quad_prim(
stage: Usd.Stage, prim_path: Sdf.Path, translate: Gf.Vec3d, scale: Gf.Vec3d, rotate: Gf.Vec3d, image_path: str
) -> Usd.Prim:
prim: UsdGeom.Xform = UsdGeom.Xform.Define(stage, prim_path)
Usd.ModelAPI(prim).SetKind(Kind.Tokens.subcomponent)
translate_op: UsdGeom.XformOp = prim.AddTranslateOp()
rotate_op: UsdGeom.XformOp = prim.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = prim.AddScaleOp()
translate_op.Set(translate)
rotate_op.Set(rotate)
scale_op.Set(Gf.Vec3d(1, 1, 1))
mesh = create_quad_mesh(stage, scale, prim_path.AppendChild("ImageSequenceMesh"))
material = create_texture_material(stage, prim_path.AppendChild("ImageSequenceMaterial"), image_path)
UsdShade.MaterialBindingAPI(mesh).Bind(material)
return prim
def create_quad_mesh(stage: Usd.Stage, scale: Gf.Vec3d, prim_path: Sdf.Path) -> UsdGeom.Mesh:
# See https://graphics.pixar.com/usd/dev/tut_simple_shading.html#adding-a-mesh-billboard
mesh: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, prim_path)
translate_op: UsdGeom.XformOp = mesh.AddTranslateOp()
rotate_op: UsdGeom.XformOp = mesh.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = mesh.AddScaleOp()
translate_op.Set(Gf.Vec3d(0, 0, 0))
rotate_op.Set(Gf.Vec3d(0, 0, 0))
scale_op.Set(scale)
mesh.CreatePointsAttr([(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)])
mesh.CreateFaceVertexCountsAttr([4])
mesh.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
mesh.CreateExtentAttr([(-0.5, 0.0, -0.5), (0.5, 0.0, 0.5)])
texCoords = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying)
texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])
return mesh
def create_texture_material(stage: Usd.Stage, material_prim_path: Sdf.Path, image_path: str) -> UsdShade.Material:
# See https://graphics.pixar.com/usd/dev/tut_simple_shading.html#adding-a-mesh-billboard
shader_prim_path = material_prim_path.AppendChild("ImageSequenceShader")
material: UsdShade.Material = UsdShade.Material.Define(stage, material_prim_path)
shader: UsdShade.Shader = UsdShade.Shader.Define(stage, shader_prim_path)
shader.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset)
shader.SetSourceAsset("OmniPBR.mdl", "mdl")
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
material.CreateSurfaceOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out")
shader_prim: Usd.Prim = stage.GetPrimAtPath(shader_prim_path)
shader_prim.CreateAttribute("inputs:diffuse_texture", Sdf.ValueTypeNames.Asset).Set(image_path)
shader_prim.CreateAttribute("inputs:emissive_color_texture", Sdf.ValueTypeNames.Asset).Set(image_path)
shader_prim.CreateAttribute("inputs:reflection_roughness_constant", Sdf.ValueTypeNames.Float).Set(1.0)
shader_prim.CreateAttribute("inputs:metallic_constant", Sdf.ValueTypeNames.Float).Set(0.0)
return material
class Transform:
translate: Gf.Vec2d = Gf.Vec3d(0, 0, 0)
scale: Gf.Vec2d = Gf.Vec3d(1, 1, 1)
rotate: Gf.Vec2d = Gf.Vec3d(0, 0, 0)
def calculate_transforms(config: Config) -> Dict[str, Transform]:
INCHES_TO_CM = 1.54
images: List[Image.Image] = [Image.open(image_path_str) for image_path_str in config.expanded_glob]
image_count = len(images)
if image_count == 0:
return {}
# Calculate the largest image width in cm
max_image_width_px = max([image.size[0] for image in images])
max_image_width_in = max_image_width_px / config.ppi
max_image_width_cm = max_image_width_in * INCHES_TO_CM
# Calculate the largest image height in cm
max_image_height_px = max([image.size[1] for image in images])
max_image_height_in = max_image_height_px / config.ppi
max_image_height_cm = max_image_height_in * INCHES_TO_CM
# Calculate the number of images per row
images_per_row = image_count if config.images_per_row < 1 else config.images_per_row
# Calculate the total number of rows
total_rows = math.ceil(image_count / images_per_row)
#print(f"Images per row: {images_per_row}, Total Rows: {total_rows}")
image_gap_cm = config.gap_pct * max_image_width_cm
# Calculate total extents
total_width_cm = max(max_image_width_cm * (images_per_row - 1) + image_gap_cm * max(images_per_row - 1, 0), 0)
total_height_cm = (total_rows - 1) * max_image_height_cm + image_gap_cm * max(total_rows - 1, 0)
#print(f"Total Width: {total_width_cm}, Total Height: {total_height_cm}")
# max_height_px = max([image.size[1] for image in images])
left_most_cm = -0.5 * total_width_cm
top_most_cm = 0.5 * total_height_cm
left_current_cm = left_most_cm
top_current_cm = top_most_cm
transforms: Dict[str, Transform] = {}
seen = 0
for count, image in enumerate(images):
if seen > images_per_row - 1:
left_current_cm = left_most_cm
top_current_cm -= max_image_height_cm + image_gap_cm
seen = 0
image_width_px = image.size[0]
image_height_px = image.size[1]
image_width_in = image_width_px / config.ppi
image_height_in = image_height_px / config.ppi
image_width_cm = image_width_in * INCHES_TO_CM
image_height_cm = image_height_in * INCHES_TO_CM
transform = Transform()
transform.scale = Gf.Vec3d(image_width_cm, image_height_cm, 1)
# Lerp between the line and the arc positioning
t = (left_current_cm - left_most_cm) / total_width_cm if total_width_cm > 0 else 0
turns = 0.5 * math.tau
phase = (1.0 - t) * turns + 0.25 * math.tau
amp = 0.5 * total_width_cm
x = left_current_cm * (1.0 - config.curve_pct) + (config.curve_pct) * amp * math.sin(phase)
z = 0 + config.curve_pct * amp * math.cos(phase)
transform.translate = Gf.Vec3d(x, top_current_cm, z)
angle = -config.curve_pct * math.degrees(-phase + 0.5 * math.tau)
# print(t, phase, angle)
transform.rotate = Gf.Vec3d(0, angle, 0)
transforms[image.filename] = transform
left_current_cm += max_image_width_cm + image_gap_cm
seen += 1
return transforms
def create_image_sequence_group_prim(stage: Usd.Stage, root_prim_path: Sdf.Path, config: Config) -> Usd.Prim:
# Create the root prim
prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
if not prim.IsValid():
xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, root_prim_path)
Usd.ModelAPI(xform).SetKind(Kind.Tokens.component)
translate_op: UsdGeom.XformOp = xform.AddTranslateOp()
rotate_op: UsdGeom.XformOp = xform.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = xform.AddScaleOp()
translate_op.Set(Gf.Vec3d(0, 0, 0))
rotate_op.Set(Gf.Vec3d(0, 0, 0))
scale_op.Set(Gf.Vec3d(1, 1, 1))
# Persist the config data in the top-level USD prim
prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
set_config_metadata(prim, config)
# Create a child prim for each image
transforms = calculate_transforms(config)
for asset_path in config.expanded_glob:
image_path = Path(asset_path)
transform: Transform = transforms[asset_path]
# Create the prim
image_prim_path = root_prim_path.AppendChild(make_safe_prim_name(image_path.stem))
create_textured_quad_prim(
stage=stage,
prim_path=image_prim_path,
translate=transform.translate,
scale=transform.scale,
rotate=transform.rotate,
image_path=asset_path,
)
return prim
def update_image_sequence_prims(stage: Usd.Stage, root_prim_path: Sdf.Path, config: Config) -> None:
if stage is None:
carb.log_warn("Unexpected: stage is none")
return
top_prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
if not top_prim.IsValid():
carb.log_warn("Unexpected: prim is invalid")
return
set_config_metadata(top_prim, config)
transforms = calculate_transforms(config)
# Create a child prim for each image
for image in config.expanded_glob:
image_path = Path(image)
transform: Transform = transforms[image]
image_prim_path: Sdf.Path = root_prim_path.AppendChild(make_safe_prim_name(image_path.stem))
mesh_prim_path: Sdf.Path = image_prim_path.AppendChild("ImageSequenceMesh")
image_prim: Usd.Prim = stage.GetPrimAtPath(image_prim_path)
mesh_prim: Usd.Prim = stage.GetPrimAtPath(mesh_prim_path)
if not image_prim.IsValid():
carb.log_warn(f"Unexpected: {image_prim_path} is invalid")
return
if not mesh_prim.IsValid():
carb.log_warn(f"Unexpected: {mesh_prim_path} is invalid")
return
image_prim.GetAttribute("xformOp:translate").Set(transform.translate)
mesh_prim.GetAttribute("xformOp:scale").Set(transform.scale)
image_prim.GetAttribute("xformOp:rotateXYZ").Set(transform.rotate)
return
def make_safe_prim_name(name: str, replace: str = "_") -> str:
for c in ["-", ".", "?"]:
name = name.replace(c, replace)
return name
| 9,377 | Python | 44.086538 | 114 | 0.666098 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["KitImageSequenceWindow"]
import os
from glob import glob
import carb
import omni.ui
from pxr import Usd
from .config import *
from .core import *
class KitImageSequenceWindow(omni.ui.Window):
"""
Extension window
"""
def __init__(self, title: str, delegate=None, **kwargs):
super().__init__(title, **kwargs)
# Set the function that is called to build widgets when the window is
# visible
self._asset_path_model = omni.ui.SimpleStringModel("")
self._ppi_model = omni.ui.SimpleIntModel(100)
self._gap_model = omni.ui.SimpleFloatModel(0.1)
self._curve_model = omni.ui.SimpleFloatModel(0.0)
self._images_per_row_model = omni.ui.SimpleIntModel(1)
self._image_sequence_is_selected = omni.ui.SimpleBoolModel(False)
self._asset_path_model.add_end_edit_fn(lambda _: self._on_asset_path_change())
self._ppi_model.add_value_changed_fn(lambda _: self._on_change())
self._gap_model.add_value_changed_fn(lambda _: self._on_change())
self._curve_model.add_value_changed_fn(lambda _: self._on_change())
self._images_per_row_model.add_value_changed_fn(lambda _: self._on_change())
self._image_sequence_is_selected.add_value_changed_fn(lambda _: self._on_image_seq_selection_change())
self.frame.set_build_fn(self._build_fn)
stage_event_stream = omni.usd.get_context().get_stage_event_stream()
self._stage_event_sub = stage_event_stream.create_subscription_to_pop(self._on_stage_event, name="kit-imageseq-event-stream")
def destroy(self):
super().destroy()
self._stage_event_sub.unsubscribe()
def _on_stage_event(self, event):
stage: Usd.Stage = omni.usd.get_context().get_stage()
if stage is None:
return
SELECTION_CHANGED = int(omni.usd.StageEventType.SELECTION_CHANGED)
if event.type == SELECTION_CHANGED:
self._image_sequence_is_selected.set_value(False)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
if len(paths) == 0:
return
first_path = paths[0]
first_prim: Usd.Prim = stage.GetPrimAtPath(first_path)
if not first_prim.IsValid():
return
# Populate the UI Model with the config values
config = get_config_metadata(first_prim)
if config is None:
return
self._selected_prim_path = first_path
self._set_models_from_config(config)
def _config_from_models(self) -> Config:
config = Config()
config.path_glob = self._asset_path_model.get_value_as_string()
config.expanded_glob = glob(config.path_glob)
config.expanded_glob.sort()
config.ppi = self._ppi_model.get_value_as_int()
config.gap_pct = self._gap_model.get_value_as_float()
config.curve_pct = self._curve_model.get_value_as_float()
config.images_per_row = self._images_per_row_model.get_value_as_int()
return config
def _set_models_from_config(self, config: Config) -> None:
self._asset_path_model.set_value(config.path_glob)
self._ppi_model.set_value(config.ppi)
self._gap_model.set_value(config.gap_pct)
self._curve_model.set_value(config.curve_pct)
self._images_per_row_model.set_min(0)
self._images_per_row_model.set_max(len(config.expanded_glob))
self._images_per_row_model.set_value(config.images_per_row)
self._image_sequence_is_selected.set_value(True)
def _on_image_seq_selection_change(self) -> None:
self._frame.visible = self._image_sequence_is_selected.get_value_as_bool()
def _on_create_new_image_sequence(self) -> None:
stage: Usd.Stage = omni.usd.get_context().get_stage()
#
root_prim: Usd.Prim = stage.GetDefaultPrim()
root_prim_path: Sdf.Path = root_prim.GetPath()
root_image_seq_prim_path = root_prim_path.AppendChild("ImageSequences")
image_seq_count = 0
root_image_seq_prim: Usd.Prim = stage.GetPrimAtPath(root_image_seq_prim_path)
if root_image_seq_prim.IsValid():
image_seq_count = len(root_image_seq_prim.GetChildren())
while True:
image_seq_prim_path = root_image_seq_prim_path.AppendChild(f"ImageSequence{image_seq_count}")
if not stage.GetPrimAtPath(image_seq_prim_path).IsValid():
break
else:
image_seq_count += 1
# Default config
config = Config()
config.path_glob = ""
config.expanded_glob = []
config.ppi = 300
config.gap_pct = 0.0
config.curve_pct = 0.0
config.images_per_row = 0
prim = create_image_sequence_group_prim(stage, image_seq_prim_path, config)
# Select the created prim
selected_prim_path = str(prim.GetPath())
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([selected_prim_path], True)
self._selected_prim_path = selected_prim_path
return
def _on_asset_path_change(self) -> None:
# Validate user input
config = self._config_from_models()
if len(config.expanded_glob) == 0:
carb.log_error(f"No assets found for {config.path_glob}")
for asset_path in config.expanded_glob:
if not os.path.exists(asset_path):
carb.log_error(f"Specified asset {asset_path} does not exist")
return
stage: Usd.Stage = omni.usd.get_context().get_stage()
prim_path = Sdf.Path(self._selected_prim_path)
prim: Usd.Prim = stage.GetPrimAtPath(prim_path)
if prim.IsValid():
children = prim.GetChildren()
for child in children:
child: Usd.Prim
stage.RemovePrim(child.GetPath())
prim: Usd.Prim = create_image_sequence_group_prim(stage, prim_path, config)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([str(prim.GetPath())], True)
self._set_models_from_config(config)
return
def _on_change(self):
selected_prim_path = self._selected_prim_path
config = self._config_from_models()
stage = omni.usd.get_context().get_stage()
update_image_sequence_prims(stage, Sdf.Path(selected_prim_path), config)
def _build_fn(self):
with omni.ui.VStack():
with omni.ui.VStack(height=20):
with omni.ui.HStack():
omni.ui.Button("Create New Image Sequence", width=40, clicked_fn=self._on_create_new_image_sequence)
self._frame = omni.ui.Frame(visible=self._image_sequence_is_selected.get_value_as_bool())
with self._frame:
with omni.ui.VStack(height=20):
with omni.ui.HStack():
omni.ui.Label(
"Asset Path", tooltip="Absolute path to an image asset or a glob like C:\dir\*.png"
)
omni.ui.StringField(self._asset_path_model)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("PPI", tooltip="Desired pixels per inch")
omni.ui.IntField(self._ppi_model)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Gap", tooltip="In units of percentage of the max image width")
omni.ui.FloatSlider(self._gap_model, min=0.0, max=1.0)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Curve", tooltip="0.0 -> straight line, 1.0 -> circle")
omni.ui.FloatSlider(self._curve_model, min=0.0, max=1.0)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Images Per Row", tooltip="Images per row")
omni.ui.IntSlider(self._images_per_row_model, min=1)
omni.ui.Spacer(height=2) | 8,794 | Python | 44.569948 | 133 | 0.602343 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.0.1] - 2022-10-27
- Initial release
| 139 | Markdown | 14.555554 | 80 | 0.669065 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/docs/README.md | # Image Sequence Importer
Omniverse Kit extension to import and layout image sequences. | 88 | Markdown | 28.666657 | 61 | 0.829545 |
alankent/ordinary-consolidator/README.md | # Omniverse Extension to Consolidate vertices on a mesh
This extension lets you pick a mesh in an OpenUSD scene that may not
be using `interpolation = "FaceVerying"` and it generates a new mesh
deduplicating vertices. This is necessary to make Audio2Face happy.
https://youtu.be/vv7vp3O_mh8?si=dHCA3kH3WVFwxXLC
| 314 | Markdown | 33.999996 | 68 | 0.799363 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/extension.py | import omni.ext
import omni.ui as ui
from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade
from .MeshMaker import MeshMaker
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryMeshConsolidatorExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = ui.Window("Mesh Consolidator", width=300, height=300)
with self._window.frame:
# TODO: Clean up the UI... one day.
with ui.VStack():
def on_click():
self.consolidate_prim()
with ui.HStack():
ui.Button("Consolidate", clicked_fn=on_click)
# The main body of the clean up code for VRoid Studio characters.
def consolidate_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
selections = ctx.get_selection().get_selected_prim_paths()
# Patch the skeleton structure, if not done already. Add "Root" to the joint list.
for prim_path in selections:
mesh_prim = stage.GetPrimAtPath(prim_path)
if mesh_prim and mesh_prim.IsA(UsdGeom.Mesh):
mesh: UsdGeom.Mesh = UsdGeom.Mesh(mesh_prim)
self.perform_consolidation(stage, mesh, prim_path + "_consolidated")
def perform_consolidation(self, stage: Usd.Stage, old_mesh: UsdGeom.Mesh, new_mesh_path):
faceVertexIndices = old_mesh.GetFaceVertexIndicesAttr().Get()
faceVertexCounts = old_mesh.GetFaceVertexCountsAttr().Get()
points = old_mesh.GetPointsAttr().Get()
normals = old_mesh.GetNormalsAttr().Get()
normalsInterpolation = UsdGeom.Primvar(old_mesh.GetNormalsAttr()).GetInterpolation()
stAttr = old_mesh.GetPrim().GetAttribute('primvars:st0')
stInterpolation = UsdGeom.Primvar(stAttr).GetInterpolation()
st = stAttr.Get()
material = UsdShade.MaterialBindingAPI(old_mesh.GetPrim()).GetDirectBindingRel().GetTargets()
new_mesh = MeshMaker(stage, material)
# Assumes faceVertexCounts are all '3'
for face_index in range(len(faceVertexIndices) // 3):
pi1 = faceVertexIndices[face_index * 3 + 0]
pi2 = faceVertexIndices[face_index * 3 + 1]
pi3 = faceVertexIndices[face_index * 3 + 2]
p1 = points[pi1]
p2 = points[pi2]
p3 = points[pi3]
if normalsInterpolation == UsdGeom.Tokens.faceVarying:
n1 = normals[face_index * 3 + 0]
n2 = normals[face_index * 3 + 1]
n3 = normals[face_index * 3 + 2]
else:
n1 = normals[pi1]
n2 = normals[pi2]
n3 = normals[pi3]
if stInterpolation == UsdGeom.Tokens.faceVarying:
st1 = st[face_index * 3 + 0]
st2 = st[face_index * 3 + 1]
st3 = st[face_index * 3 + 2]
else:
st1 = st[pi1]
st2 = st[pi2]
st3 = st[pi3]
new_mesh.add_face(p1, p2, p3, n1, n2, n3, st1, st2, st3)
new_mesh.create_at_path(new_mesh_path)
| 3,506 | Python | 37.538461 | 119 | 0.599544 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/MeshMaker.py | from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade, UsdSkel
# This class creates a new Mesh by adding faces one at a time.
# When don, you ask it to create a new Mesh prim.
class MeshMaker:
def __init__(self, stage: Usd.Stage, material):
self.stage = stage
self.material = material
self.faceVertexCounts = []
self.faceVertexIndices = []
self.normals = []
self.st = []
self.points = []
# Create a Mesh prim at the given prim path.
def create_at_path(self, prim_path) -> UsdGeom.Mesh:
# https://stackoverflow.com/questions/74462822/python-for-usd-map-a-texture-on-a-cube-so-every-face-have-the-same-image
mesh: UsdGeom.Mesh = UsdGeom.Mesh.Define(self.stage, prim_path)
mesh.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
mesh.CreatePointsAttr(self.points)
mesh.CreateExtentAttr(UsdGeom.PointBased(mesh).ComputeExtent(mesh.GetPointsAttr().Get()))
mesh.CreateNormalsAttr(self.normals)
mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
mesh.CreateFaceVertexCountsAttr(self.faceVertexCounts)
mesh.CreateFaceVertexIndicesAttr(self.faceVertexIndices)
UsdGeom.PrimvarsAPI(mesh.GetPrim()).CreatePrimvar('st', Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(self.st)
UsdShade.MaterialBindingAPI(mesh).GetDirectBindingRel().SetTargets(self.material)
return mesh
# Add a new face (3 points with normals and mappings to part of the texture)
def add_face(self, p1, p2, p3, normal1, normal2, normal3, st1, st2, st3):
self.faceVertexCounts.append(3)
self.faceVertexIndices.append(self.add_point(p1))
self.faceVertexIndices.append(self.add_point(p2))
self.faceVertexIndices.append(self.add_point(p3))
self.normals.append(normal1)
self.normals.append(normal2)
self.normals.append(normal3)
self.st.append(st1)
self.st.append(st2)
self.st.append(st3)
# Given a point, find an existing points array entry and return its index, otherwise add another point
# and return the index of the new point.
def add_point(self, point):
for i in range(0, len(self.points)):
if self.points[i] == point:
return i
self.points.append(point)
return len(self.points) - 1
| 2,396 | Python | 41.052631 | 140 | 0.674457 |
alankent/ordinary-windy-blendshapes/README.md | # Create Blend Shapes for Windy Scenes
This project is designed for foliage such as grass, flowers, or trees so
it can sway in the wind in NVIDIA Omniverse. It is designed for models
that are static (unmoving).
It is a work in progress, but sharing where up to. I will probably potter
along with this in my spare time.
It works by creating blend shapes the move points in the mesh by an amount
proportional (with a bit of a curve) to the height of the point off the ground.
So points at (or below) ground level do not move. Points half way up move a
bit, points at the top move the most.
To use it,
* Create a new empty stage for your model, click the first "create skeleton" button which will define SkelRoot, Skeleton, and SkelAnimation prims.
* Add a reference to your model from under SkelRoot. It must be under this prim for it to animate.
* Click the second button which will create a blendshape for each mesh in the model.
## Plans
* Have 2 blend shapes for the model bending east and south. I want to create an animation graph that has two variables controlling the strength of the two blendshapes.
* I want to create an action graph that given wind direction, strength, sway speed etc animations the east and south weights (with negative values for west and north) so the foliage can sway in a specified direction
* I also want a central "wind" script that updates all of the individual models, so you can set the wind direction and strength centrally and everything in the stage will get updated
* I want to add another blendshape for a slight ripple, to make leaves flutter. This would be applied to selected meshes (leaves, not trunks or branches).
# Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "ordinary.windy.blendshapes" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 3,719 | Markdown | 45.499999 | 258 | 0.767948 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/ordinary/windy/blendshapes/extension.py | import omni.ext
import omni.ui as ui
from pxr import Usd, Sdf, Gf, UsdGeom, UsdSkel
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryWindyBlendshapesExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ordinary.windy.blendshapes] ordinary windy blendshapes startup")
self._window = ui.Window("Ordinary Windy Blendshapes", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("Instructions\n\n" +
"- Create a new stage\n" +
"- Click 'Create Skeleton'\n" +
"- Drop your model under SkelRoot\n" +
"- Click 'Add Blend Shapes'\n" +
"- Save and reload the file (to flush the skeleton cache)")
def on_create_skeleton():
self.create_skeleton()
def on_add_blend_shapes():
self.add_blend_shapes()
with ui.HStack():
ui.Button("Create Skeleton", clicked_fn=on_create_skeleton)
ui.Button("Add Blend Shapes", clicked_fn=on_add_blend_shapes)
def on_shutdown(self):
print("[ordinary.windy.blendshapes] ordinary windy blendshapes shutdown")
def create_skeleton(self):
ctx = omni.usd.get_context()
stage: Usd.Stage = ctx.get_stage()
root: Usd.Prim = stage.GetDefaultPrim()
# Create a skeleton under which the user will have to add a reference to the model.
skel_root: UsdSkel.Root = UsdSkel.Root.Define(stage, root.GetPath().AppendChild("SkelRoot"))
skeleton: UsdSkel.Skeleton = UsdSkel.Skeleton.Define(stage, skel_root.GetPath().AppendChild("Skeleton"))
UsdSkel.BindingAPI.Apply(skeleton.GetPrim())
skeleton.CreateBindTransformsAttr().Set([])
skeleton.CreateRestTransformsAttr().Set([])
skeleton.CreateJointsAttr().Set([])
skeleton.CreateJointNamesAttr().Set([])
# Add a SkelAnimation referring to the blend shapes to simplify animation.
default_wind_anim = self.add_skel_animation(stage, skeleton, "defaultWindAnimation", [0, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "noWindAnimation", [0, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "eastWindAnimation", [1, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "westWindAnimation", [0, 1, 0, 0])
self.add_skel_animation(stage, skeleton, "southWindAnimation", [0, 0, 1, 0])
self.add_skel_animation(stage, skeleton, "northWindAnimation", [0, 0, 0, 1])
self.add_skel_animation(stage, skeleton, "testWindAnimation", {
0: [0, 0, 0, 0],
10: [0.2, 0, 0.2, 0],
25: [1, 0, 1, 0],
40: [0.2, 0, 0.2, 0],
50: [0, 0, 0, 0],
60: [0, 0.2, 0, 0.2],
75: [0, 1, 0, 1],
90: [0, 0.2, 0, 0.2],
100: [0, 0, 0, 0],
})
# Point the skeleton to the no wind animation.
skel_binding: UsdSkel.BindingAPI = UsdSkel.BindingAPI(skeleton)
skel_binding.CreateAnimationSourceRel().SetTargets([default_wind_anim.GetPath()])
def add_skel_animation(self, stage: Usd.Stage, skeleton: UsdSkel.Skeleton, animation_name, weights):
print(animation_name)
print(skeleton.GetPath().name)
skel_animation: UsdSkel.Animation = UsdSkel.Animation.Define(stage, skeleton.GetPath().AppendChild(animation_name))
skel_animation.CreateBlendShapesAttr().Set(["eastWindBlendShape", "westWindBlendShape", "southWindBlendShape", "northWindBlendShape"])
skel_animation.CreateJointsAttr().Set([])
skel_animation.CreateRotationsAttr().Set([])
skel_animation.CreateScalesAttr().Set([])
skel_animation.CreateTranslationsAttr().Set([])
x: Usd.Prim = None
UsdSkel.Animation.GetBlendShapeWeightsAttr
if type(weights) is dict:
attr = skel_animation.CreateBlendShapeWeightsAttr()
skel_animation.GetBlendShapeWeightsAttr
for time, value in weights.items():
attr.Set(time=time, value=value)
else:
skel_animation.CreateBlendShapeWeightsAttr().Set(weights)
return skel_animation
def add_blend_shapes(self):
ctx = omni.usd.get_context()
stage: Usd.Stage = ctx.get_stage()
root: Usd.Prim = stage.GetDefaultPrim()
skel_root = root.GetChild("SkelRoot")
if not skel_root.IsValid():
print("SkelRoot not found - did you create the skeleton first?")
return
skeleton = skel_root.GetChild("Skeleton")
if not skeleton.IsValid():
print("Skeleton not found - did you create the skeleton first?")
return
# Cannot use Traverse unfortunately, as it is not restricted to under a specific prim.
#for prim in stage.Traverse():
# if prim.IsA(UsdGeom.Mesh):
# print("Mesh: " + prim.GetPath().pathString)
self.look_for_meshes(stage, root, skeleton)
def look_for_meshes(self, stage, prim, skeleton):
if prim.IsA(UsdGeom.Mesh):
self.add_blend_shapes_for_mesh(stage, prim, skeleton)
for child_prim in prim.GetChildren():
self.look_for_meshes(stage, child_prim, skeleton)
def add_blend_shapes_for_mesh(self, stage: Usd.Stage, meshPrim, skeleton):
# Work out which way is up for the model.
up = "Y"
units_resolve_attr = meshPrim.GetParent().GetAttribute("xformOp:rotateX:unitsResolve")
if units_resolve_attr:
units_resolve = units_resolve_attr.Get()
if units_resolve == 0:
pass
elif units_resolve == -90:
up = "Z"
else:
print("I don't know what up is!")
# Create child blend shapes for +X (east) and +Z (south)
mesh = UsdGeom.Mesh(meshPrim)
east_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "eastWindBlendShape", 1, 0)
west_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "westWindBlendShape", -1, 0)
south_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "southWindBlendShape", 0, 1)
north_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "northWindBlendShape", 0, -1)
# TODO: Add a blend shape for fluttering leaves
# Add skel:blendShapes property to list the blendshape names.
# https://openusd.org/dev/api/class_usd_skel_binding_a_p_i.html
binding: UsdSkel.BindingAPI = UsdSkel.BindingAPI(meshPrim)
binding.CreateBlendShapesAttr().Set(["eastWindBlendShape", "westWindBlendShape", "southWindBlendShape", "northWindBlendShape"])
binding.CreateBlendShapeTargetsRel().SetTargets([east_blend_shape.GetPath(), west_blend_shape.GetPath(), south_blend_shape.GetPath(), north_blend_shape.GetPath()])
UsdSkel.BindingAPI.Apply(meshPrim)
binding.CreateSkeletonRel().SetTargets([skeleton.GetPath()])
def add_blendshape_in_one_direction(self, stage: Usd.Stage, up, mesh: UsdGeom.Mesh, blend_shape_name, east_scale, south_scale):
# Work out how many points in blendshape we need.
# We specify all points (0..n), normal offsets are all zero. Point offsets are the most complex.
mesh_points = mesh.GetPointsAttr().Get()
num_points = len(mesh_points)
point_indices = range(0, num_points)
normal_offsets = [(0, 0, 0) for i in point_indices]
# To work out how far to bend the object, we need to know its height.
height = 0
offsets = []
# TODO: I don't really like this - probably a smarter way to do it by computing a base vector
# then rotating it appropriately. But just get it going for now by duplicating the code.
if up == "Y":
for x, y, z in mesh_points:
if y > height:
height = y
for x, y, z in mesh_points:
if y <= 0:
offsets.append((0, 0, 0))
else:
horizontal_delta = self.compute_horizontal_delta(height, y)
vertical_delta = self.compute_vertical_delta(height, y)
offsets.append((horizontal_delta * east_scale, vertical_delta, horizontal_delta * south_scale))
if up == "Z":
for x, y, z in mesh_points:
if z > height:
height = z
for x, y, z in mesh_points:
if z <= 0:
offsets.append((0, 0, 0))
else:
horizontal_delta = self.compute_horizontal_delta(height, z)
vertical_delta = self.compute_vertical_delta(height, z)
offsets.append((horizontal_delta * east_scale, horizontal_delta * south_scale, vertical_delta))
# Create the blendshape! https://openusd.org/dev/api/class_usd_skel_blend_shape.html
blend_shape: UsdSkel.BlendShape = UsdSkel.BlendShape.Define(stage, mesh.GetPath().AppendChild(blend_shape_name))
blend_shape.CreatePointIndicesAttr().Set(point_indices)
blend_shape.CreateOffsetsAttr().Set(offsets)
blend_shape.CreateNormalOffsetsAttr().Set(normal_offsets)
return blend_shape
def compute_horizontal_delta(self, max, value):
# Scale to 0 to 1 fraction, square it for a curve, then scale to up to sway at most 1/4 height.
return ((value / max) ** 2) * max / 8
def compute_vertical_delta(self, max, value):
# When leaning reduce the height a bit so it does not look like its stretching too much.
# TODO: Would have to do a few inbetweens to do a nice curve, and it jumps badly at the top, so just skip it for now.
return 0
#return -abs(self.compute_horizontal_delta(max, value) / 2) | 10,500 | Python | 48.533019 | 171 | 0.609048 |
alankent/ordinary-depthmap-projection/exts/ordinary.depthmap.projection/ordinary/depthmap/projection/extension.py | from typing import List, Tuple, Callable, Dict
from functools import partial
import os
import math
import carb.settings
import carb.windowing
import omni.appwindow
from carb import log_warn, events
import omni.ext
import omni.ui as ui
#from omni.kit.window.file_importer import get_file_importer
from omni.kit.window.filepicker import FilePickerDialog, UI_READY_EVENT
from omni.kit.widget.filebrowser import FileBrowserItem
from pxr import Usd, UsdShade, UsdGeom, Sdf, Gf
import omni.usd
import numpy as np
from PIL import Image
DEFAULT_FILE_EXTENSION_TYPES = [
("*.png, *.jpg", "Image Files"),
("*.*", "All files"),
]
def default_filter_handler(filename: str, filter_postfix: str, filter_ext: str) -> bool:
if not filename:
return True
# Show only files whose names end with: *<postfix>.<ext>
if filter_ext:
# split comma separated string into a list:
filter_exts = filter_ext.split(",") if isinstance(filter_ext, str) else filter_ext
filter_exts = [x.replace(" ", "") for x in filter_exts]
filter_exts = [x for x in filter_exts if x]
# check if the file extension matches anything in the list:
if not (
"*.*" in filter_exts or
any(filename.endswith(f.replace("*", "")) for f in filter_exts)
):
# match failed:
return False
if filter_postfix:
# strip extension and check postfix:
filename = os.path.splitext(filename)[0]
return filename.endswith(filter_postfix)
return True
def on_filter_item(filter_fn: Callable[[str], bool], dialog: FilePickerDialog, item: FileBrowserItem, show_only_folders: bool = False) -> bool:
if item and not item.is_folder:
# OM-96626: Add show_only_folders option to file importer
if show_only_folders:
return False
if filter_fn:
return filter_fn(item.path or '', dialog.get_file_postfix(), dialog.get_file_extension())
return True
def _save_default_settings(default_settings: Dict):
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_importer/appSettings")
settings.set_string(f"{default_settings_path}/directory", default_settings['directory'] or "")
def on_import(import_fn: Callable[[str, str, List[str]], None], dialog: FilePickerDialog, filename: str, dirname: str, hide_window_on_import: bool = True):
_save_default_settings({'directory': dirname})
selections = dialog.get_current_selections() or []
if hide_window_on_import:
dialog.hide()
if import_fn:
import_fn(filename, dirname, selections=selections)
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryDepthmapProjectionExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ordinary.depthmap.projection] ordinary depthmap projection startup")
self.stage = omni.usd.get_context().get_stage()
self._window = ui.Window("Ordinary Depth Map Projection", width=300, height=300)
with self._window.frame:
with ui.VStack():
with ui.HStack():
def on_texture_click():
def import_handler(filename, dirname, selections = []):
self.texture_filename = os.path.join(dirname, filename)
self.texture_label.text = self.texture_filename
self.texture_dialog = FilePickerDialog(
'Select texture file',
apply_button_label = 'Open',
click_apply_handler = import_handler,
file_extension_options = DEFAULT_FILE_EXTENSION_TYPES
)
self.texture_dialog.set_item_filter_fn(partial(on_filter_item, default_filter_handler, self.texture_dialog, show_only_folders=False))
self.texture_dialog.set_click_apply_handler(partial(on_import, import_handler, self.texture_dialog, hide_window_on_import=True))
#self.texture_dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self.texture_dialog.show()
self.texture_dialog._widget.file_bar.focus_filename_input()
ui.Button("Select Texture File", width=150, clicked_fn=on_texture_click)
self.texture_filename = ''
self.texture_label = ui.Label(self.texture_filename)
with ui.HStack():
def on_depthmap_click():
def import_handler(filename, dirname, selections = []):
self.depthmap_filename = os.path.join(dirname, filename)
self.depthmap_label.text = self.depthmap_filename
self.depthmap_dialog = FilePickerDialog(
'Select depthmap file',
apply_button_label = 'Open',
click_apply_handler = import_handler,
file_extension_options = DEFAULT_FILE_EXTENSION_TYPES
)
self.depthmap_dialog.set_item_filter_fn(partial(on_filter_item, default_filter_handler, self.depthmap_dialog, show_only_folders=False))
self.depthmap_dialog.set_click_apply_handler(partial(on_import, import_handler, self.depthmap_dialog, hide_window_on_import=True))
#self.depthmap_dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self.depthmap_dialog.show()
ui.Button("Select Depth Map File", width=150, clicked_fn=on_depthmap_click)
self.depthmap_filename = ''
self.depthmap_label = ui.Label(self.depthmap_filename)
with ui.HStack():
def on_generate_click():
self.generate_new_mesh()
ui.Button("Generate", clicked_fn=on_generate_click)
def generate_new_mesh(self):
print("GENERATE", self.texture_filename, self.depthmap_filename)
# Create the mesh
xform = UsdGeom.Xform.Define(self.stage, "/my_plane")
mesh = UsdGeom.Mesh.Define(self.stage, xform.GetPath().AppendChild("mesh"))
mesh.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
texture_image = Image.open(self.texture_filename)
texture_width, texture_height = texture_image.size
mesh_width = texture_width // 16
mesh_height = texture_height // 16
depthmap_image = Image.open(self.depthmap_filename)
# datatype is optional, but can be useful for type conversion
depthmap_data = np.asarray(depthmap_image, dtype=np.uint8)
depthmap_height, depthmap_width, depthmap_colors = depthmap_data.shape
points = []
normals = []
st = []
normal = (0, 1, 0)
vertex_counts = []
vertex_indicies = []
def clamp(value, min_value, max_value):
return max(min(int(value), max_value), min_value)
for y in range(mesh_height + 1):
for x in range(mesh_width + 1):
dmx = clamp(x / mesh_width * depthmap_width, 0, depthmap_width - 1)
dmy = clamp((mesh_height - y) / mesh_height * depthmap_height, 0, depthmap_height - 1)
distance = depthmap_data[dmy, dmx, 0] / 256 * mesh_height
points.append(Gf.Vec3f(x - mesh_width/2, y - mesh_height/2, distance))
for y in range(mesh_height):
for x in range(mesh_width):
vertex_counts.append(3)
vertex_indicies.append(y * (mesh_width + 1) + x) # LL
vertex_indicies.append(y * (mesh_width + 1) + x + 1) # LR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x) # UL
st.append((x / mesh_width, y / mesh_height)) # LL
st.append(((x + 1) / mesh_width, y / mesh_height)) # LR
st.append((x / mesh_width, (y + 1) / mesh_height)) # UL
normals.append(normal)
normals.append(normal)
normals.append(normal)
vertex_counts.append(3)
vertex_indicies.append(y * (mesh_width + 1) + x + 1) # LR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x + 1) # UR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x) # UL
st.append(((x + 1) / mesh_width, y / mesh_height)) # LR
st.append(((x + 1) / mesh_width, (y + 1) / mesh_height)) # UR
st.append((x / mesh_width, (y + 1) / mesh_height)) # UL
normals.append(normal)
normals.append(normal)
normals.append(normal)
mesh.CreatePointsAttr(points)
mesh.CreateExtentAttr(UsdGeom.PointBased(mesh).ComputeExtent(mesh.GetPointsAttr().Get()))
mesh.CreateFaceVertexCountsAttr(vertex_counts)
mesh.CreateFaceVertexIndicesAttr(vertex_indicies)
mesh.CreateNormalsAttr(normals)
mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
primvar_api = UsdGeom.PrimvarsAPI(mesh.GetPrim())
primvar_api.CreatePrimvar('st', Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(st)
# Apply texture to the plane
material = UsdShade.Material.Define(self.stage, xform.GetPath().AppendChild("material"))
shader = UsdShade.Shader.Define(self.stage, material.GetPath().AppendChild("texture_shader"))
shader.CreateIdAttr("UsdPreviewSurface")
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 1.0, 1.0))
shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5)
shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
diffuse_tx = UsdShade.Shader.Define(self.stage, material.GetPath().AppendChild("DiffuseColorTx"))
diffuse_tx.CreateIdAttr('UsdUVTexture')
diffuse_tx.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(self.texture_filename)
diffuse_tx.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuse_tx.ConnectableAPI(), 'rgb')
material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
#stInput = shader.CreateInput("st", Sdf.ValueTypeNames.TexCoord2fArray)
# Create a texture and connect it to the shader's diffuse color
#diffuseTexture = UsdShade.TextureInput(shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f))
#diffuseTexture.SetTextureFile(texture_filename)
#stInput.ConnectToSource(diffuseTexture.GetOutput())
#material.CreateSurfaceOutput().ConnectToSource(shader.GetOutput("surface"))
#shader.CreateIdAttr("UsdUVTexture")
#shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_filename)
#st_input = material.CreateInput("st", Sdf.ValueTypeNames.TexCoord2fArray)
#shader_output = shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3)
#st_input.ConnectToSource(shader_output)
#shader_connection = material.CreateShaderIdAttr().ConnectToSource(shader.GetIdAttr())
material_binding = UsdShade.MaterialBindingAPI(mesh.GetPrim())
material_binding.Bind(material)
def on_shutdown(self):
print("[ordinary.depthmap.projection] ordinary depthmap projection shutdown")
| 12,030 | Python | 44.57197 | 159 | 0.621031 |
alankent/ordinary-vrm-clean/README.md | # VRM Importer for NVIDIA Omniverse
This repository is a work in progress, but making it available in its
current messy form regardless. I hope to clean this up and improve it
over the coming months.
## What is NVIDIA Omniverse
You can download NVIDIA Omniverse for free if you have a NVIDIA GPU.
You can create 3D scenes using USD (Universal Scene Description) originally
from Pixar, now open source (https://openusd.org/).
Omniverse uses USD as its native file format.
## What is this repo?
This repo contains a Omniverse Kit extension. Almost all the Omniverse
tools are built using Kit, their framework for app building.
See [README-ext.md](./README-ext.md) for more information.
This extension is not in a good or final place, but I got it to do something
so sharing with the world in case anyone else wants to give it a go.
## The UI looks like the default template extension UI
Well spotted. I have put no effort into the UI at this stage. I just wanted
to get it to do something. So there is a button called "Clean" which runs
the code and "Dump" which walks the current Stage and prints out the length
of all properties that hold arrays. (I was use the latter to work out the
lengths of all the point mesh details as part of my learnings.)
## So how do I use it?
I grab a `.vrm` file exported from [VRoid Studio](https://vroid.com/en/studio),
rename it to `.glb`, open in Omniverse USD Composer (formerly "Create"),
right click and "Convert to USD". I then open the USD file and click the
"Clean" button. It restructures things in the currently opened character
USD file.
[VRM](https://github.com/vrm-c) files are in GLB format (the binary form of
glTF) but follow some additional standards to help with interchange in VR apps
(like VR Chat and some VTuber software like [VSeeFace](https://vseeface.icu).
Ultimately, I could imagine this extension becoming a `.vrm` file importer
extension for Omniverse. One day...
## Why is it necessary?
Using the above approach to import a GLB file has worked the best but
still suffers from problems in Omniverse:
* The root bone is lost during the GLB import process, making animation clips not work correctly
* [Audio2Face](https://www.nvidia.com/en-us/omniverse/apps/audio2face/) does not like the meshes VRoid Studio generates
* Need to add hair physics (not started)
* Need to add cloth physics for clothes, like skirts (not started)
## Why am I doing this?
I tell people I am trying to create an animated cartoon series to publish
on YouTube. What really happens is I get distracted geeking out on technology.
* I created a few episodes originally with 2D animation in Adobe Character Animator.
* I then created a few episodes using Unity as the rendering pipeline (HDRP).
* I am now exploring NVIDIA Omniverse for rendering.
I am trying to stick to free tools so others can give it a go and see if
they like it before investing money into commercial tools.
## When can I learn more?
I blog at [extra-ordinary.tv/blog](https://extra-ordinary.tv/blog/)
* [First Steps for VRoid Studio characters in NVIDIA Omniverse](https://extra-ordinary.tv/2023/05/28/2902/)
* [VRoid Studio, meet NVIDIA Omniverse](https://extra-ordinary.tv/2023/05/10/vroid-studio-meet-nvidia-omniverse/)
| 3,249 | Markdown | 42.918918 | 119 | 0.768544 |
alankent/ordinary-vrm-clean/exts/ordinary/ordinary/extension.py | # Made using: https://youtu.be/eGxV_PGNpOg
# Lessons learned
# - work out your package name first (it affects directory structure)
# - DeletePrims references Sdf which is not imported for you
import omni.ext
import omni.ui as ui
import omni.kit.commands
from pxr import Usd, Sdf, Gf, UsdGeom
from .ExtractMeshes import ExtractMeshes
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[ordinary] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = ui.Window("VRM Import Cleanup v1", width=300, height=300)
with self._window.frame:
# TODO: Clean up the UI... one day.
with ui.VStack():
label = ui.Label("")
def on_click():
self.clean_up_prim()
label.text = "clicked"
def on_dump():
label.text = "empty"
# Debugging: Print hierarchy of all prims in stage, all attributes of prims that are arrays
self.dump_stage()
label.text = "dump"
with ui.HStack():
ui.Button("Clean", clicked_fn=on_click)
ui.Button("Dump", clicked_fn=on_dump)
def on_shutdown(self):
print("[ordinary] ordinary shutdown")
# The main body of the clean up code for VRoid Studio characters.
def clean_up_prim(self):
# VRoid Studio dependent code. This code has hard coded path names used by VRoid Studio characters.
# If needed, could clean this up to make more generic.
# But I am also hoping NVIDIA fix their GLB import code, so trying to minimize my effort.
# The problem is the bone structure is it picks one level too deep for the bone hierarchy.
# /World/Root/J_Bip_C_Hips0/Skeleton/J_Bip_C_Hips/... should have been one node higher, so Root was
# included under Skeleton. Without this, it thinks the Hips are the root bone (at height zero).
# To work around the problem, I go through all the joint lists and insert "Root/" at the start
# of the joint paths.
ctx = omni.usd.get_context()
stage = ctx.get_stage()
# TODO: May have a go at this again, moving everything up so its Root/Skeleton without the hips.
# root_prim = stage.GetPrimAtPath('/World/Root')
# root_prim.SetTypeName('SkelRoot')
# Move Skeleton directly under Root layer
# self.move_if_necessary(stage, '/World/Root/J_Bip_C_Hips0/Skeleton', '/World/Root/Skeleton')
# Move meshes directly under Root layer, next to Skeleton
# self.move_if_necessary(stage, '/World/Root/J_Bip_C_Hips0/Face_baked', '/World/Root/Face_baked')
# self.move_if_necessary(stage, '/World/Root/J_Bip_C_Hips0/Body_baked', '/World/Root/Body_baked')
# self.move_if_necessary(stage, '/World/Root/J_Bip_C_Hips0/Hair001_baked', '/World/Root/Hair001_baked')
# Patch the skeleton structure, if not done already. Add "Root" to the joint list.
skeleton_prim = stage.GetPrimAtPath('/World/Root/J_Bip_C_Hips0/Skeleton')
if skeleton_prim:
self.add_parent_to_skeleton_joint_list(skeleton_prim, 'Root')
for child in stage.GetPrimAtPath('/World/Root/J_Bip_C_Hips0').GetChildren():
if child.IsA(UsdGeom.Mesh):
self.add_parent_to_mesh_joint_list(child, 'Root')
# self.split_disconnected_meshes(stage, child)
if child.GetName().startswith("Face_"):
e = ExtractMeshes(stage)
e.extract_face_meshes(child)
if child.GetName().startswith("Hair"):
e = ExtractMeshes(stage)
e.extract_hair_meshes(child)
if child.GetName().startswith("Body_"):
e = ExtractMeshes(stage)
e.extract_body_meshes(child)
# Delete the dangling node (was old SkelRoot)
# self.delete_if_no_children(stage, '/World/Root/J_Bip_C_Hips0')
# Delete old skeleton if present.
if stage.GetPrimAtPath('/World/Root/J_Bip_C_Hips0/Skeleton/J_Bip_C_Hips'):
omni.kit.commands.execute('DeletePrims', paths=[Sdf.Path('/World/Root/J_Bip_C_Hips0/Skeleton/J_Bip_C_Hips')])
# If a prim exists at the source path, move it to the target path.
# Returns true if moved, false otherwise.
def move_if_necessary(self, stage, source_path, target_path):
if stage.GetPrimAtPath(source_path):
omni.kit.commands.execute(
'MovePrim',
path_from=source_path,
path_to=target_path,
keep_world_transform=False,
destructive=False)
return True
return False
# Delete the prim at the specified path if it exists and has no children.
# Returns true if deleted, false otherwise.
def delete_if_no_children(self, stage, path):
prim = stage.GetPrimAtPath(path)
if prim:
if not prim.GetChildren():
omni.kit.commands.execute(
'DeletePrims',
paths=[Sdf.Path(path)],
destructive=False)
return True
return False
def add_parent_to_skeleton_joint_list(self, skeleton_prim: Usd.Prim, parent_name):
"""
A skeleton has 3 attributes:
- uniform matrix4d[] bindTransforms = [( (1, 0, -0, 0), ...]
- uniform token[] joints = ["J_Bip_C_Hips", ...]
- uniform matrix4d[] restTransforms = [( (1, 0, -0, 0), ...]
In Omniverse Code etc, you can hover over the names in the "Raw USD Property" panel to get
more documentation on the above properties.
We need to insert the new parent at the front of the three lists, and prepend the name to the join paths.
"""
# Get the attributes
joints: Usd.Attribute = skeleton_prim.GetAttribute('joints')
bindTransforms: Usd.Attribute = skeleton_prim.GetAttribute('bindTransforms')
restTransforms: Usd.Attribute = skeleton_prim.GetAttribute('restTransforms')
# If first join is the parent name already, nothing to do.
if joints.Get()[0] == parent_name:
return False
# TODO: I use raw USD functions here, but there is also omni.kit.commands.execute("ChangeProperty",...)
# if want undo...
# https://docs.omniverse.nvidia.com/prod_kit/prod_kit/programmer_ref/usd/properties/set-attribute.html#omniverse-kit-commands
joints.Set([parent_name] + [parent_name + '/' + jp for jp in joints.Get()])
# Insert unity matrix at the start for the root node we added.
# ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
unity_matrix = Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
if bindTransforms.IsValid():
bindTransforms.Set([unity_matrix] + [x for x in bindTransforms.Get()])
if restTransforms.IsValid():
restTransforms.Set([unity_matrix] + [x for x in restTransforms.Get()])
# The meshes have paths to bones as well - add "Root" to their paths as well.
def add_parent_to_mesh_joint_list(self, mesh_prim, parent_name):
if mesh_prim:
joints: Usd.Attribute = mesh_prim.GetAttribute('skel:joints')
# Don't touch empty string. Don't add if already added. First value might be empty string.
if not joints.Get()[1].startswith(parent_name):
joints.Set([jp if jp == "" else parent_name + '/' + jp for jp in joints.Get()])
return True
return False
# Going to delete this - ended up creating a separate class for this. It got tricky.
#def split_disconnected_meshes(self, stage: Usd.Stage, mesh_prim: UsdGeom.Mesh):
# """
# Look for child GeomSubset prims and see if they have discontiguous meshes.
# Audio2Face cannot work with such meshes, so we need to split them into separate
# GeomSubset prims.
# """
# mesh_indices = mesh_prim.GetAttribute('faceVertexIndices')
# for child in mesh_prim.GetChildren():
# if child.IsA(UsdGeom.Subset):
# subset_prim: UsdGeom.Subset = child
# subset_indices = child.GetAttribute('indices').Get()
# split = self.split_subset(mesh_indices, subset_indices)
# if len(split) > 1:
# print("Create new meshes for " + subset_prim)
# i = 0
# for split_subset in split:
# subset_path = subset_prim.GetPath() + "_" + i
# new_prim: UsdGeom.Subset = stage.DefinePrim(subset_path, usdType=UsdGeom.Subset)
# new_prim.CreateElementTypeAttr().Set(subset_prim.GetElementTypeAttr().Get())
# new_prim.CreateFamilyNameAttr().Set(subset_prim.GetFamilyNameAttr().Get())
# new_prim.CreateIndicesAttr().Set(split_subset)
# material_binding: UsdShade.MaterialBindingAPI = UsdShade.MaterialBindingAPI(new_prim)
# binding_targets = material_binding.GetMaterialBindSubsets()
# material_binding.CreateMaterialBindSubset().Set(UsdShade.MaterialBindingAPI(subset_prim).GetMaterialBindingTargets())
# i += 1
#
#def split_subset(self, mesh_indices, subset_indices):
# """
# Given an array of mesh face vertex indicies (multiply them by 3 to get the points index)
# and an array of subset indices into the mesh indicies array, return an array of
# disconnected submeshes.
# """
# Traverse the tree of prims, printing out selected attribute information.
# Useful for debugging.
def dump_stage(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
for prim in stage.Traverse():
for attr in prim.GetAttributes():
try:
if len(attr.Get()) >= 50:
print(attr.GetPath(), len(attr.Get()))
except Exception:
pass
| 10,842 | Python | 47.40625 | 142 | 0.606069 |
alankent/ordinary-vrm-clean/exts/ordinary/ordinary/MeshMaker.py | from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade, UsdSkel
# This class creates a new Mesh by adding faces one at a time.
# When don, you ask it to create a new Mesh prim.
class MeshMaker:
def __init__(self, stage: Usd.Stage, material, skeleton, skelJoints):
self.stage = stage
self.material = material
self.faceVertexCounts = []
self.faceVertexIndices = []
self.normals = []
self.st = []
self.points = []
self.skeleton = skeleton
self.skelJoints = skelJoints
self.skelJointIndices = []
self.skelJointWeights = []
# Create a Mesh prim at the given prim path.
def create_at_path(self, prim_path) -> UsdGeom.Mesh:
# https://stackoverflow.com/questions/74462822/python-for-usd-map-a-texture-on-a-cube-so-every-face-have-the-same-image
mesh: UsdGeom.Mesh = UsdGeom.Mesh.Define(self.stage, prim_path)
mesh.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
mesh.CreatePointsAttr(self.points)
mesh.CreateExtentAttr(UsdGeom.PointBased(mesh).ComputeExtent(mesh.GetPointsAttr().Get()))
mesh.CreateNormalsAttr(self.normals)
mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
mesh.CreateFaceVertexCountsAttr(self.faceVertexCounts)
mesh.CreateFaceVertexIndicesAttr(self.faceVertexIndices)
mesh.CreatePrimvar('st', Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(self.st)
ba: UsdSkel.BindingAPI = UsdSkel.BindingAPI(mesh)
ba.Apply(mesh.GetPrim())
ba.CreateGeomBindTransformAttr(Gf.Matrix4d(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1))
ba.CreateSkeletonRel().SetTargets(self.skeleton)
ba.CreateJointsAttr(self.skelJoints)
ba.CreateJointIndicesPrimvar(False, elementSize=4).Set(self.skelJointIndices)
ba.CreateJointWeightsPrimvar(False, elementSize=4).Set(self.skelJointWeights)
UsdShade.MaterialBindingAPI(mesh).GetDirectBindingRel().SetTargets(self.material)
return mesh
# Add a new face (3 points with normals and mappings to part of the texture)
def add_face(self, points, jointIndices, jointWeights, pi1, pi2, pi3, normal1, normal2, normal3, st1, st2, st3):
self.faceVertexCounts.append(3)
self.faceVertexIndices.append(self.new_index_of_point(points, jointIndices, jointWeights, pi1))
self.faceVertexIndices.append(self.new_index_of_point(points, jointIndices, jointWeights, pi2))
self.faceVertexIndices.append(self.new_index_of_point(points, jointIndices, jointWeights, pi3))
self.normals.append(normal1)
self.normals.append(normal2)
self.normals.append(normal3)
self.st.append(st1)
self.st.append(st2)
self.st.append(st3)
# Given a point, find an existing points array entry and return its index, otherwise add another point
# and return the index of the new point.
# If adding a new point, also copy across the skeleton joint index and joint weight from the old point.
# TODO: This could be optimized with a lookup table of point->index.
def new_index_of_point(self, points, jointIndices, jointWeights, point_index):
point = points[point_index]
for i in range(0, len(self.points)):
if self.points[i] == point:
return i
self.points.append(point)
# Copy across the old joint information. This assumes element_size = 4.
self.skelJointIndices.append(jointIndices[point_index * 4])
self.skelJointIndices.append(jointIndices[point_index * 4 + 1])
self.skelJointIndices.append(jointIndices[point_index * 4 + 2])
self.skelJointIndices.append(jointIndices[point_index * 4 + 3])
self.skelJointWeights.append(jointWeights[point_index * 4])
self.skelJointWeights.append(jointWeights[point_index * 4 + 1])
self.skelJointWeights.append(jointWeights[point_index * 4 + 2])
self.skelJointWeights.append(jointWeights[point_index * 4 + 3])
return len(self.points) - 1
| 4,081 | Python | 50.024999 | 127 | 0.688312 |
alankent/ordinary-vrm-clean/exts/ordinary/ordinary/ExtractMeshes.py | import typing
import omni.ext
import omni.ui as ui
import omni.kit.commands
from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade, UsdSkel
from .MeshMaker import MeshMaker
import math
# Good resource https://github.com/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/usd_introduction.ipynb
# Also https://docs.omniverse.nvidia.com/prod_kit/prod_kit/programmer_ref/usd/transforms/get-world-transforms.html
#def get_world_translate(prim: Usd.Prim) -> Gf.Vec3d:
# """
# Get the local transformation of a prim using Xformable.
# See https://graphics.pixar.com/usd/release/api/class_usd_geom_xformable.html
# Args:
# prim: The prim to calculate the world transformation.
# Returns:
# - Translation vector.
# """
# xform = UsdGeom.Xformable(prim)
# time = Usd.TimeCode.Default() # The time at which we compute the bounding box
# world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time)
# translation: Gf.Vec3d = world_transform.ExtractTranslation()
# return translation
class ExtractMeshes:
def __init__(self, stage: Usd.Stage):
self.stage = stage
self.segment_map = None
# Return true if this Mesh is the Face mesh we want to convert.
# Names are like "Face_baked" and "Face__merged__Clone_".
#def mesh_is_face_mesh(mesh: UsdGeom.Mesh):
# name: str = mesh.GetName()
# if name.startswith("Face_"):
# return True
# else:
# return False
def extract_face_meshes(self, mesh: UsdGeom.Mesh):
# Run through the children sub-meshes
# "F00_000_00_FaceMouth_00_FACE" -- Needs splitting into upper teeth, lower teeth, mouth cavity, toungue
# "F00_000_00_EyeWhite_00_EYE"
# "F00_000_00_FaceEyeline_00_FACE"
# "F00_000_00_FaceEyelash_00_FACE"
# "F00_000_00_FaceBrow_00_FACE"
# "F00_000_00_EyeIris_00_EYE"
# "F00_000_00_EyeHighlight_00_EYE" -- Drop? Gone in new version.
# "F00_000_00_Face_00_SKIN" or "N00_000_00_Face_00_SKIN__Instance_"
# "F00_000_00_Face_00_SKIN_1"
# "F00_000_00_EyeExtra_01_EYE" -- Drop? Gone in new version.
for child in mesh.GetChildren():
if child.IsA(UsdGeom.Subset):
name: str = child.GetName()
if "_Face_" in name and "SKIN" in name:
self.extract_face_skin(mesh, child)
elif "_FaceMouth_" in name:
self.extract_mouth(mesh, child)
elif "_FaceEyeline_" in name:
self.extract_eyeline(mesh, child)
elif "_FaceEyelash_" in name:
self.extract_eyelash(mesh, child)
elif "_FaceBrow_" in name:
self.extract_eyebrow(mesh, child)
elif "_EyeWhite_" in name:
self.extract_eyewhites(mesh, child)
elif "_EyeIris" in name:
self.extract_irises(mesh, child)
def extract_hair_meshes(self, old_mesh: UsdGeom.Mesh):
# Run through the children sub-meshes and copy them to their own Mesh
n = 0
for child in old_mesh.GetChildren():
if child.IsA(UsdGeom.Subset):
material = UsdShade.MaterialBindingAPI(child).GetDirectBindingRel().GetTargets()
skeleton = UsdSkel.BindingAPI(old_mesh).GetSkeletonRel().GetTargets()
skelJoints = UsdSkel.BindingAPI(old_mesh).GetJointsAttr().Get()
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, child)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild('hair_' + str(n)))
n += 1
def extract_body_meshes(self, old_mesh: UsdGeom.Mesh):
# Run through the children sub-meshes and copy them to their own Mesh
n = 0
for child in old_mesh.GetChildren():
if child.IsA(UsdGeom.Subset):
material = UsdShade.MaterialBindingAPI(child).GetDirectBindingRel().GetTargets()
skeleton = UsdSkel.BindingAPI(old_mesh).GetSkeletonRel().GetTargets()
skelJoints = UsdSkel.BindingAPI(old_mesh).GetJointsAttr().Get()
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, child)
name: str = child.GetName()
if "_Body_" in name:
new_name = 'bodyskin'
elif "_Tops_" in name:
new_name = 'clothes_upper'
elif "_Bottoms_" in name:
new_name = 'clothes_lower'
elif "_Shoes_" in name:
new_name = 'shoes'
else:
new_name = 'body_' + str(n)
n += 1
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild(new_name))
# Copy the whole mesh across for the face.
# The original mesh in VRoid points that are not used in any face.
def extract_face_skin(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.make_mesh_from_subset(old_mesh, old_subset, 'face_skin')
# Extract multiple meshes from the mouth: upper teeth (needs joining), lower teeth (needs joining),
# tounge, and mouth cavity.
def extract_mouth(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
# This one is the most tricky case. There is one "subset" for the mouth, which includes upper
# and lower teeth, as well as the mouth cavity. We need upper and lower teeth in their own
# meshes for Audio2Face to work.
# So, we segment the mesh, ignoring points that are not actually used by faces (there are lot!).
# The first two connected meshes are for the inside and outside of the teeth.
# The next two are the lower teeth.
# Then there is a single connected mesh for the mouth cavity.
# Finally there are another two meshes for the top and bottom of the tongue.
num_segments = self.segment_mesh(old_mesh, old_subset)
if num_segments == 7:
material = UsdShade.MaterialBindingAPI(old_subset).GetDirectBindingRel().GetTargets()
skeleton = UsdSkel.BindingAPI(old_mesh).GetSkeletonRel().GetTargets()
skelJoints = UsdSkel.BindingAPI(old_mesh).GetJointsAttr().Get()
# 0 = inner upper teeth, 1 = outer upper teeth
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset, 0, 1)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild('upper_teeth'))
# 2 = inner lower teeth, 3 = outer lower teeth
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset, 2, 3)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild('lower_teeth'))
# 4 = mouth cavity
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset, 4, 4)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild('mouth_cavity'))
# 5 = upper tongue, 6 = lower tongue
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset, 5, 6)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild('tongue'))
self.clear_segment_map()
# Eyeline we could split into left and right eyes, but we don't need to.
# It uses a separate mesh with its own material.
def extract_eyeline(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.make_mesh_from_subset(old_mesh, old_subset, 'eyeline')
# Eyelash we could split into left and right eyes, but we don't need to.
# It uses a separate mesh with its own material.
def extract_eyelash(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.make_mesh_from_subset(old_mesh, old_subset, 'eyelash')
# Eyebrows we could split into left and right eyes, but we don't need to.
# It uses a separate mesh with its own material.
def extract_eyebrow(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.make_mesh_from_subset(old_mesh, old_subset, 'eyebrow')
# Eyewhites are interesting. Rather than be a sphere or similar, there is actually a gap
# behind the irises, which causes shadows. Might want to adjust these one day, but they
# stop from being able to look inside the head when the eyes move (the whites do not move).
def extract_eyewhites(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.make_mesh_from_subset(old_mesh, old_subset, 'eyewhites')
# We need to extract the left and right eye irises. There is lots of other points and things
# that are not actually used, so we want to toss them.
def extract_irises(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
self.segment_mesh(old_mesh, old_subset)
eyes = ["left_eye", "right_eye"]
for i in range(len(eyes)):
material = UsdShade.MaterialBindingAPI(old_subset).GetDirectBindingRel().GetTargets()
skeleton = UsdSkel.BindingAPI(old_mesh).GetSkeletonRel().GetTargets()
skelJoints = UsdSkel.BindingAPI(old_mesh).GetJointsAttr().Get()
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset, i, i)
# We do a bit more work because eyes need to rotate. So we insert an Xform about the
# Mesh for the two eyes. Its a bit behind the eyes, moved a bit towards the center of the head
# as the front of the characters is more rounded than a real head.
# We use the size of the iris to estimate how far behind the iris the pivot point needs to go.
pivot_prim_path = old_mesh.GetPath().GetParentPath().AppendChild(eyes[i] + "_pivot")
xformPrim = UsdGeom.Xform.Define(self.stage, pivot_prim_path)
eye_mesh: UsdGeom.Mesh = new_mesh.create_at_path(pivot_prim_path.AppendChild(eyes[i]))
extent = eye_mesh.GetExtentAttr().Get()
(x1,y1,z1) = extent[0]
(x2,y2,z2) = extent[1]
(dx,dy,dz) = ((x1+x2)/4.0, (y1+y2)/2.0, z2 - (y2-y1) * 2.0)
UsdGeom.XformCommonAPI(xformPrim).SetTranslate((dx, dy, dz))
UsdGeom.XformCommonAPI(eye_mesh).SetTranslate((-dx, -dy, -dz))
self.clear_segment_map()
# Create a new mesh from the given submesh (copy it all to a new Mesh)
def make_mesh_from_subset(self, old_mesh, old_subset, prim_name):
material = UsdShade.MaterialBindingAPI(old_subset).GetDirectBindingRel().GetTargets()
skeleton = UsdSkel.BindingAPI(old_mesh).GetSkeletonRel().GetTargets()
skelJoints = UsdSkel.BindingAPI(old_mesh).GetJointsAttr().Get()
new_mesh = MeshMaker(self.stage, material, skeleton, skelJoints)
self.copy_subset(new_mesh, old_mesh, old_subset)
new_mesh.create_at_path(old_mesh.GetPath().GetParentPath().AppendChild(prim_name))
# A GeomSubset holds an array of indicies of which faces are used by this subset.
# But we need it in a separate Mesh for Audio2Face to be happy.
# So we run down the list of referenced faces, and add them to a completely new Mesh.
# This drops lots of unused points and cleans up the model.
def copy_subset(self, new_mesh: MeshMaker, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset, segment1=None, segment2=None):
faceVertexIndices = old_mesh.GetAttribute('faceVertexIndices').Get()
points = old_mesh.GetAttribute('points').Get() # GetPointsAttr().Get()
normals = old_mesh.GetAttribute('normals').Get() # GetNormalsAttr().Get()
st = old_mesh.GetAttribute('primvars:st').Get()
jointIndices = old_mesh.GetAttribute('primvars:skel:jointIndices').Get()
jointWeights = old_mesh.GetAttribute('primvars:skel:jointWeights').Get()
for face_index in old_subset.GetAttribute('indices').Get(): # GetIndicesAttr().Get():
if self.segment_map is None or self.segment_map[face_index] == segment1 or self.segment_map[face_index] == segment2:
# This is hard coded for VRoid Studio in that it assumes each face is a triangle with 3 points.
# Pull the details of each triangle on the surface and add it to a new mesh, building it up from scratch.
pi1 = faceVertexIndices[face_index * 3]
pi2 = faceVertexIndices[face_index * 3 + 1]
pi3 = faceVertexIndices[face_index * 3 + 2]
n1 = normals[face_index * 3]
n2 = normals[face_index * 3 + 1]
n3 = normals[face_index * 3 + 2]
st1 = st[face_index * 3]
st2 = st[face_index * 3 + 1]
st3 = st[face_index * 3 + 2]
new_mesh.add_face(points, jointIndices, jointWeights, pi1, pi2, pi3, n1, n2, n3, st1, st2, st3)
# Clear the segment map.
def clear_segment_map(self):
self.segment_map = None
# Create a segment map by running through all the faces (and their verticies), then any other face
# that shares a point with the same mesh is also considered to be part of the same segment.
def segment_mesh(self, old_mesh: UsdGeom.Mesh, old_subset: UsdGeom.Subset):
# Work out some commonly used attributes.
faceVertexIndices = old_mesh.GetAttribute('faceVertexIndices').Get()
subset_indices = old_subset.GetAttribute('indices').Get()
num_faces = math.ceil(len(faceVertexIndices) / 3)
self.segment_map = [None] * num_faces
segment = 0
# Loop until we fail to find a face that has not been marked with a segment number.
while True:
i = 0
while i < len(subset_indices) and self.segment_map[subset_indices[i]] is not None:
i += 1
if i == len(subset_indices):
# Nothing found, so we are all done!
break
first_face = i
# Rather than adding the 3D coordinates, we add the index to the array of "points".
# If anything reuses the same index, then its in the same continuous mesh.
seen = set()
seen.add(faceVertexIndices[subset_indices[i] * 3])
seen.add(faceVertexIndices[subset_indices[i] * 3 + 1])
seen.add(faceVertexIndices[subset_indices[i] * 3 + 2])
self.segment_map[i] = segment
# We have no guarantee on the order of faces, so we do a pass from front to end.
# If a face was added to the current segment, we retry until we fail to find anything.
found_one = True
while found_one:
found_one = False
i = first_face
while i < len(subset_indices):
face = subset_indices[i]
if self.segment_map[face] is None:
if faceVertexIndices[face * 3] in seen or faceVertexIndices[face * 3 + 1] in seen or faceVertexIndices[face * 3 + 2] in seen:
# One of the 3 points of the current Face shares a vertex with the current mesh,
# so add all 3 points as belonging to the mesh and mark that we did find at least one more.
seen.add(faceVertexIndices[face * 3])
seen.add(faceVertexIndices[face * 3 + 1])
seen.add(faceVertexIndices[face * 3 + 2])
self.segment_map[face] = segment
found_one = True
i += 1
segment += 1
return segment
| 16,123 | Python | 52.926421 | 149 | 0.616076 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/docs/CHANGELOG.md | [no changelog]
| 15 | Markdown | 6.999997 | 14 | 0.733333 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/docs/README.md | # Fabricator Extension
| 23 | Markdown | 10.999995 | 22 | 0.826087 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/auth_service.py | import requests
class AuthService:
SIGN_IN_URL = 'https://gateway.vmod.com/library/customers/sign_in'
AUTHENTICATE_URL = 'https://gateway.vmod.com/library/customers/me'
WORKSPACES_URL = 'https://gateway.vmod.com/library/members/all_workspaces'
def __init__(self):
self.access_token = None
def sign_in(self, email: str, password: str) -> None:
try:
response = requests.post(AuthService.SIGN_IN_URL, json = { "email": email, "password": password })
response.raise_for_status()
self.access_token = response.json()['token']
except:
raise Exception('Invalid credentials')
def is_authenticated(self) -> bool:
try:
response = requests.get(AuthService.AUTHENTICATE_URL, headers = { 'Authorization': f'Bearer {self.access_token}' })
response.raise_for_status()
return True
except:
return False
def get_workspaces(self):
try:
response = requests.get(AuthService.WORKSPACES_URL, headers = { 'Authorization': f'Bearer {self.access_token}' })
response.raise_for_status()
return list(map(lambda x: { "id": x["workspace"]["id"], "name": x["workspace"]["name"] }, filter(lambda x: x["status"] == "active", response.json())))
except:
raise Exception('Invalid workspaces') | 1,403 | Python | 41.545453 | 162 | 0.601568 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/extension.py | import omni.ext
import omni.ui as ui
from .auth_service import AuthService
from .fabricator_service import FabricatorService
from .file_service import FileService
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print(f"[fabricator.extension] some_public_function was called with {x}")
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class FabricatorExtension(omni.ext.IExt):
DEFAULT_WIDTH = 600
PER_PAGE = 15
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[fabricator.extension] fabricator extensiohn startup")
self._window = ui.Window("Fabricator", width=FabricatorExtension.DEFAULT_WIDTH)
self.file_service = FileService()
self.file_service.create_dir()
self.auth_service = AuthService()
self.signin_email_input = None
self.signin_password_input = None
self._signin_error_msg = None
self.workspaces = []
self.current_workspace_idx = 0
self.workspace_combobox = None
self.fabricator_service = FabricatorService()
self.page_search_input = None
self.page = 1
self.max_page = 1
self.render_signin_page()
def on_shutdown(self):
print("[fabricator.extension] fabricator extensiohn shutdown")
self.file_service.remove_dir()
def current_workspace_id(self):
return self.workspaces[self.current_workspace_idx]["id"]
def render_signin_page(self):
def signin_btn_clicked():
email = self.signin_email_input.model.get_value_as_string()
password = self.signin_password_input.model.get_value_as_string()
try:
self.auth_service.sign_in(email, password)
self.fabricator_service.set_access_token(self.auth_service.access_token)
self.workspaces = self.auth_service.get_workspaces()
self.render_assets_page()
except Exception as e:
print(f"[fabricator.extension] {e}")
self._signin_error_msg = "Invalid Email or Password"
self.render_signin_page()
with self._window.frame:
with ui.VStack(width=FabricatorExtension.DEFAULT_WIDTH, spacing=10):
ui.Label("Sign In", alignment=ui.Alignment.CENTER, height=80, style={"font_size": 40})
ui.Label("with your VMOD account", alignment=ui.Alignment.CENTER_TOP, height=10)
ui.Label("If you don't have an account, create one at visit vmod.xyz", alignment=ui.Alignment.CENTER_TOP, height=40)
if self._signin_error_msg is not None:
ui.Label(self._signin_error_msg, alignment=ui.Alignment.CENTER, height=10, style={"color": "red"})
ui.Label("Email:", alignment=ui.Alignment.CENTER_BOTTOM, height=10)
self.signin_email_input = ui.StringField(placeholder="Email", height=20, style={"margin_width": 40})
ui.Label("Password:", alignment=ui.Alignment.CENTER_BOTTOM, height=10)
self.signin_password_input = ui.StringField(password_mode=True, height=20, style={"margin_width": 40})
ui.Button("Sign In", height=80, style={"margin_width": 100, "margin_height": 20}, clicked_fn=signin_btn_clicked)
def workspace_selector_component(self):
self.workspace_combobox = ui.ComboBox(self.current_workspace_idx, *list(map(lambda ws: ws["name"], self.workspaces)), height=10).model
def workspace_changed(model, item):
self.current_workspace_idx = model.get_item_value_model().as_int
self.page = 1
self.render_assets_page()
self.workspace_combobox.add_item_changed_fn(workspace_changed)
def render_assets_page(self):
try:
print(f"[fabricator.extension] render_assets_page")
assets, count = self.fabricator_service.load_assets(self.current_workspace_id(), self.page, FabricatorExtension.PER_PAGE)
self.max_page = count
with self._window.frame:
with ui.VStack(spacing=10, width=FabricatorExtension.DEFAULT_WIDTH, height=400):
self.workspace_selector_component()
with ui.VGrid(column_width=100, row_height=120, column_count=5, row_count=3):
for asset in assets:
file_path = self.file_service.save_file(f'{asset["code"]}.usda', asset["asset_url"])
self.asset_component(asset, file_path)
self.page_search_component()
except Exception as e:
print(f"[fabricator.extension] {e}")
self.render_signin_page()
def library_page(self):
with self._window.frame:
with ui.VStack(spacing=10, width=FabricatorExtension.DEFAULT_WIDTH, height=400):
self.gnb_component()
ui.Label("library!!")
def asset_component(self, asset, file_path):
def drag_fn(asset):
asset_name = asset["code"]
image_url = asset["thumbnail_url"]
asset_url = asset["asset_url"]
with ui.VStack():
ui.Image(image_url, width=100, height=100)
return file_path
with ui.VStack():
asset_name = asset["code"]
image_url = asset["thumbnail_url"]
ui.ImageWithProvider(image_url, width=100, height=100, style={"margin_width": 5},
drag_fn=lambda: drag_fn(asset))
ui.Label(asset_name, alignment=ui.Alignment.CENTER_TOP, width=100, height=20, style={"font_size": 15}, elided_text=True)
def page_search_component(self):
curr_page = self.page
def search_btn_handler():
m = self.page_search_input.model
search_page = m.get_value_as_int()
# if search_page == curr_page:
# return
if search_page < 1 or search_page > self.max_page:
print("[fabricator.extension] Invalid search range")
m.set_value(curr_page)
return
self.page = search_page
self.render_assets_page()
WIDTH = 100
HEIGHT = 20
with ui.Placer(offset_x=FabricatorExtension.DEFAULT_WIDTH / 2 - WIDTH / 2):
with ui.HStack(width=WIDTH, height=HEIGHT):
self.page_search_input = ui.IntField()
self.page_search_input.model.set_value(curr_page)
ui.Label(f" / {self.max_page}")
ui.Button("search", clicked_fn=search_btn_handler)
| 7,073 | Python | 42.937888 | 142 | 0.61346 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/file_service.py | import os, requests, shutil, uuid
from io import BytesIO
from PIL import Image
from pathlib import Path
class FileService:
image_ext = "png"
model_ext = "usdz"
def __init__(self) -> None:
self.dir_path = (Path.home() / 'temp').as_posix()
def create_dir(self):
if not os.path.exists(self.dir_path):
os.makedirs(self.dir_path)
def remove_dir(self):
if os.path.exists(self.dir_path):
shutil.rmtree(self.dir_path)
def save_file(self, file_name: str, url: str) -> str:
file_path = os.path.join(self.dir_path, f'{file_name}')
if os.path.exists(file_path):
return file_path
binary_data = requests.get(url).content
with open(file_path, 'wb') as file_object:
file_object.write(binary_data)
return file_path | 848 | Python | 27.299999 | 63 | 0.596698 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/mock_auth_service.py | class MockAuthService:
def __init__(self):
self.access_token = None
def sign_in(self, email, password) -> None:
return "mock_token"
def is_authenticated(self) -> bool:
return True
def get_workspaces(self):
return [{ "id": 1, "name": "workspace1" }, { "id": 2, "name": "workspace2" }] | 346 | Python | 27.916664 | 85 | 0.552023 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/mock_fabricator_service.py | from pathlib import Path
import json
import math
class MockFabricatorService:
mock_data_path = Path(__file__).parent / 'mock.json'
mock2_data_path = Path(__file__).parent / 'mock2.json'
def __init__(self):
self.data = []
self.data2 = []
with open(MockFabricatorService.mock_data_path, 'r') as file:
self.data = json.load(file)
with open(MockFabricatorService.mock2_data_path, 'r') as file:
self.data2 = json.load(file)
def set_access_token(self, access_token):
self.access_token = access_token
def load_assets(self, workspace_id, page, limit):
data = self.data if (workspace_id == 1) else self.data2
assets = data[((page - 1) * limit):(page * limit)]
count = math.ceil(len(data) / limit)
return [assets, count]
| 843 | Python | 28.103447 | 70 | 0.60261 |
swatchoncompany/fabricator-omniverse-extension/exts/fabricator.extension/fabricator/extension/fabricator_service.py | import requests
import math
class FabricatorService:
ASSETS_URL = 'https://gateway.vmod.com/library/texture_generations/omniverse/list'
def set_access_token(self, access_token):
self.access_token = access_token
def load_assets(self, workspace_id, page, limit):
headers = { 'Authorization': f'Bearer {self.access_token}', 'current-workspace-id': workspace_id }
if page < 1:
page = 1
offset = (page - 1) * limit
try:
response = requests.get(f'{FabricatorService.ASSETS_URL}?offset={offset}&limit={limit}', headers = headers)
response.raise_for_status()
body = response.json()
count = max(math.ceil(body['count'] / limit), 1)
return [list(map(lambda d: { 'id': d['id'], 'code': d['code'], 'asset_url': d['usdaUrl'], 'thumbnail_url': d['thumbnail']['blackSmallUrl']}, body['data'])), count]
except:
raise Exception('Invalid credentials') | 982 | Python | 39.958332 | 175 | 0.606925 |
aniketrajnish/Omniverse-Shakespeare-Project/exts/makra.omniverse.shakespeare.project/makra/omniverse/shakespeare/project/extension.py | import os
import omni.ext
import omni.ui as ui
from omni.kit.window.file_importer import get_file_importer
from .gemini import gemini
from .convai import convai
class ShakespeareProjectExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[Shakespeare Project] Startup")
self.initUI()
def initUI(self):
self._window = ui.Window("Shakespeare Project", width=400, height=300)
with self._window.frame:
with ui.VStack():
self.selectImgBtn = ui.Button("Select Image", clicked_fn=self.selectImage, width=100, height=30)
ui.Spacer(height=10)
self.imgWidget = ui.Image(width=320, height=180, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT)
def selectImage(self):
fileImporter = get_file_importer()
fileImporter.show_window(
title="Import File",
import_handler=self.onFileSelected,
file_extension_types=[
("jpg", "JPEG image"),
("jpeg", "JPEG image"),
("png", "PNG image"),
("webp", "WebP image"),
("heic", "HEIC image"),
("heif", "HEIF image")
],
import_button_label="Select"
)
def onFileSelected(self, filename, dirname, selections):
if selections:
filepath = os.path.join(dirname, selections[0])
print(f"Selected file: {filepath}")
self.processImage(filepath)
convai.appendToCharBackstory(self.geminiResponse)
def processImage(self, imgPath):
self.imgWidget.source_url = f"file:///{imgPath.replace(os.sep, '/')}"
self.geminiResponse = gemini.getGeminiResponse(imgPath)
print(f"Gemini Response: {self.geminiResponse}")
def on_shutdown(self):
print("[Shakespeare Project] Shutdown")
if self._window:
self._window.destroy()
| 1,935 | Python | 35.528301 | 112 | 0.595349 |
aniketrajnish/Omniverse-Shakespeare-Project/exts/makra.omniverse.shakespeare.project/makra/omniverse/shakespeare/project/convai/convai.py | import os
import requests
import json
import configparser
def loadConvaiConfig():
configPath = os.path.join(os.path.dirname(__file__), 'convai.env')
if not os.path.exists(configPath):
raise FileNotFoundError("Convai configuration file not found.")
config = configparser.ConfigParser()
config.read(configPath)
try:
convaiConfig = {
'apiKey': config.get('CONVAI', 'API_KEY'),
'characterId': config.get('CONVAI', 'CHARACTER_ID'),
'channel': config.get('CONVAI', 'CHANNEL'),
'actions': config.get('CONVAI', 'ACTIONS'),
'sessionId': config.get('CONVAI', 'SESSION_ID'),
'baseBackstory' : config.get('CONVAI', 'BASE_BACKSTORY').replace("\\n", "\n")
}
except configparser.NoOptionError as e:
raise KeyError(f"Missing configuration key in convai.env: {e}")
return convaiConfig
# def fetchCurrCharBackstory():
# config = loadConvaiConfig()
# url = "https://api.convai.com/character/get"
# payload = json.dumps({
# "charID": config['characterId']
# })
# headers = {
# 'CONVAI-API-KEY': config['apiKey'],
# 'Content-Type': 'application/json'
# }
# response = requests.post(url, headers=headers, data=payload)
# if response.status_code == 200:
# data = response.json()
# return data.get('backstory', "No backstory found.")
# else:
# print(f"Failed to fetch character details: {response.status_code} - {response.text}")
# return None
def updateCharBackstory(newBackstory):
config = loadConvaiConfig()
url = "https://api.convai.com/character/update"
payload = json.dumps({
"charID": config['characterId'],
"backstory": newBackstory
})
headers = {
'CONVAI-API-KEY': config['apiKey'],
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=payload)
if response.status_code == 200:
print("Character updated successfully.")
else:
print(f"Failed to update character: {response.status_code} - {response.text}")
def appendToCharBackstory(backstoryUpdate):
config = loadConvaiConfig()
currBackstory = config['baseBackstory']
if currBackstory:
newBackstory = f"{currBackstory}\n{backstoryUpdate}"
updateCharBackstory(newBackstory) | 2,409 | Python | 33.428571 | 95 | 0.62308 |
aniketrajnish/Omniverse-Shakespeare-Project/exts/makra.omniverse.shakespeare.project/makra/omniverse/shakespeare/project/gemini/helpers.py | import os
import json
from pathlib import Path
def loadConfig(file):
try:
with open(file, 'r') as f:
return json.load(f)
except FileNotFoundError:
raise Exception(f"Could not find config file: {file}")
except json.JSONDecodeError:
raise Exception(f"Could not parse config file: {file}")
def currPath():
return os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
def determineMimeType(fileName):
ext = fileName.split(".")[-1].lower()
if ext == 'jpg':
return 'image/jpeg'
supportedExts = ["jpg", "jpeg", "png", "webp", "heic", "heif"]
if ext not in supportedExts:
raise Exception(f"Unsupported file extension: {ext}")
else:
return f"image/{ext}"
| 777 | Python | 25.827585 | 81 | 0.616474 |
aniketrajnish/Omniverse-Shakespeare-Project/exts/makra.omniverse.shakespeare.project/makra/omniverse/shakespeare/project/gemini/image.py | import base64
class ImageHandler:
@staticmethod
def encodeImg(imgPath):
with open(imgPath, "rb") as imgFile:
return base64.b64encode(imgFile.read()).decode("utf-8") | 193 | Python | 26.714282 | 67 | 0.663212 |
aniketrajnish/Omniverse-Shakespeare-Project/exts/makra.omniverse.shakespeare.project/makra/omniverse/shakespeare/project/gemini/gemini.py | import requests
import json
import os
import configparser
from . import image
from . import helpers
def loadGeminiConfig():
configPath = os.path.join(helpers.currPath(), 'gemini.env')
if not os.path.exists(configPath):
raise FileNotFoundError("Gemini configuration file not found.")
config = configparser.ConfigParser()
config.read(configPath)
try:
geminiConfig = {
'baseUrl': config.get('GEMINI', 'BASE_URL'),
'apiKey': config.get('GEMINI', 'API_KEY'),
'model': config.get('GEMINI', 'MODEL'),
'prompt': config.get('GEMINI', 'PROMPT')
}
except configparser.NoOptionError as e:
raise KeyError(f"Missing configuration key in gemini.env: {e}")
return geminiConfig
def getGeminiResponse(imgPath):
geminiConfig = loadGeminiConfig()
url = f"{geminiConfig['baseUrl']}/{geminiConfig['model']}:generateContent?key={geminiConfig['apiKey']}"
base64Img = image.ImageHandler.encodeImg(imgPath)
headers = {
"Content-Type": "application/json"
}
data = json.dumps({
"contents": [
{
"parts": [
{"text": geminiConfig["prompt"]},
{
"inline_data": {
"mime_type": helpers.determineMimeType(imgPath),
"data": base64Img
}
}
]
}
]
})
try:
response = requests.post(url, headers=headers, data=data)
if response.status_code != 200:
return f"Error: {response.status_code} - {response.text}"
result = response.json()
return result["candidates"][0]["content"]["parts"][0]["text"]
except requests.exceptions.RequestException as e:
return f"Request failed: {str(e)}" | 1,910 | Python | 28.859375 | 107 | 0.551309 |
NVIDIA/warp/build_lib.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# This script is an 'offline' build of the core warp runtime libraries
# designed to be executed as part of CI / developer workflows, not
# as part of the user runtime (since it requires CUDA toolkit, etc)
import sys
if sys.version_info < (3, 7):
raise Exception("Warp requires Python 3.7 minimum")
import argparse
import glob
import os
import shutil
from warp.build_dll import build_dll, find_host_compiler, set_msvc_env, verbose_cmd
from warp.context import export_builtins
parser = argparse.ArgumentParser(description="Warp build script")
parser.add_argument("--msvc_path", type=str, help="Path to MSVC compiler (optional if already on PATH)")
parser.add_argument("--sdk_path", type=str, help="Path to WinSDK (optional if already on PATH)")
parser.add_argument("--cuda_path", type=str, help="Path to CUDA SDK")
parser.add_argument(
"--mode",
type=str,
default="release",
help="Build configuration, default 'release'",
choices=["release", "debug"],
)
# Note argparse.BooleanOptionalAction can be used here when Python 3.9+ becomes the minimum supported version
parser.add_argument("--verbose", action="store_true", help="Verbose building output, default enabled")
parser.add_argument("--no_verbose", dest="verbose", action="store_false")
parser.set_defaults(verbose=True)
parser.add_argument(
"--verify_fp",
action="store_true",
help="Verify kernel inputs and outputs are finite after each launch, default disabled",
)
parser.add_argument("--no_verify_fp", dest="verify_fp", action="store_false")
parser.set_defaults(verify_fp=False)
parser.add_argument("--fast_math", action="store_true", help="Enable fast math on library, default disabled")
parser.add_argument("--no_fast_math", dest="fast_math", action="store_false")
parser.set_defaults(fast_math=False)
parser.add_argument("--quick", action="store_true", help="Only generate PTX code, disable CUTLASS ops")
parser.add_argument("--build_llvm", action="store_true", help="Build Clang/LLVM compiler from source, default disabled")
parser.add_argument("--no_build_llvm", dest="build_llvm", action="store_false")
parser.set_defaults(build_llvm=False)
parser.add_argument(
"--llvm_source_path", type=str, help="Path to the LLVM project source code (optional, repo cloned if not set)"
)
parser.add_argument("--debug_llvm", action="store_true", help="Enable LLVM compiler code debugging, default disabled")
parser.add_argument("--no_debug_llvm", dest="debug_llvm", action="store_false")
parser.set_defaults(debug_llvm=False)
parser.add_argument("--standalone", action="store_true", help="Use standalone LLVM-based JIT compiler, default enabled")
parser.add_argument("--no_standalone", dest="standalone", action="store_false")
parser.set_defaults(standalone=True)
args = parser.parse_args()
# set build output path off this file
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, "warp")
print(args)
verbose_cmd = args.verbose
def find_cuda_sdk():
# check environment variables
for env in ["WARP_CUDA_PATH", "CUDA_HOME", "CUDA_PATH"]:
cuda_sdk = os.environ.get(env)
if cuda_sdk is not None:
print(f"Using CUDA Toolkit path '{cuda_sdk}' provided through the '{env}' environment variable")
return cuda_sdk
# use which/where to locate the nvcc compiler program
nvcc = shutil.which("nvcc")
if nvcc is not None:
cuda_sdk = os.path.dirname(os.path.dirname(nvcc)) # strip the executable name and bin folder
print(f"Using CUDA Toolkit path '{cuda_sdk}' found through 'which nvcc'")
return cuda_sdk
# check default paths
if os.name == "nt":
cuda_paths = glob.glob("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*.*")
if len(cuda_paths) >= 1:
cuda_sdk = cuda_paths[0]
print(f"Using CUDA Toolkit path '{cuda_sdk}' found at default path")
return cuda_sdk
else:
usr_local_cuda = "/usr/local/cuda"
if os.path.exists(usr_local_cuda):
cuda_sdk = usr_local_cuda
print(f"Using CUDA Toolkit path '{cuda_sdk}' found at default path")
return cuda_sdk
return None
# setup CUDA Toolkit path
if sys.platform == "darwin":
args.cuda_path = None
else:
if not args.cuda_path:
args.cuda_path = find_cuda_sdk()
# setup MSVC and WinSDK paths
if os.name == "nt":
if args.msvc_path or args.sdk_path:
# user provided MSVC and Windows SDK
assert args.msvc_path and args.sdk_path, "--msvc_path and --sdk_path must be used together."
args.host_compiler = set_msvc_env(msvc_path=args.msvc_path, sdk_path=args.sdk_path)
else:
# attempt to find MSVC in environment (will set vcvars)
args.host_compiler = find_host_compiler()
if not args.host_compiler:
print("Warp build error: Could not find MSVC compiler")
sys.exit(1)
# return platform specific shared library name
def lib_name(name):
if sys.platform == "win32":
return f"{name}.dll"
elif sys.platform == "darwin":
return f"lib{name}.dylib"
else:
return f"{name}.so"
def generate_exports_header_file():
"""Generates warp/native/exports.h, which lets built-in functions be callable from outside kernels"""
# set build output path off this file
export_path = os.path.join(base_path, "warp", "native", "exports.h")
try:
with open(export_path, "w") as f:
export_builtins(f)
print(f"Finished writing {export_path}")
except FileNotFoundError:
print(f"Error: The file '{export_path}' was not found.")
except PermissionError:
print(f"Error: Permission denied. Unable to write to '{export_path}'.")
except OSError as e:
print(f"Error: An OS-related error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
try:
# Generate warp/native/export.h
generate_exports_header_file()
# build warp.dll
cpp_sources = [
"native/warp.cpp",
"native/crt.cpp",
"native/error.cpp",
"native/cuda_util.cpp",
"native/mesh.cpp",
"native/hashgrid.cpp",
"native/reduce.cpp",
"native/runlength_encode.cpp",
"native/sort.cpp",
"native/sparse.cpp",
"native/volume.cpp",
"native/marching.cpp",
"native/cutlass_gemm.cpp",
]
warp_cpp_paths = [os.path.join(build_path, cpp) for cpp in cpp_sources]
if args.cuda_path is None:
print("Warning: CUDA toolchain not found, building without CUDA support")
warp_cu_path = None
else:
warp_cu_path = os.path.join(build_path, "native/warp.cu")
warp_dll_path = os.path.join(build_path, f"bin/{lib_name('warp')}")
build_dll(args, dll_path=warp_dll_path, cpp_paths=warp_cpp_paths, cu_path=warp_cu_path)
# build warp-clang.dll
if args.standalone:
import build_llvm
if args.build_llvm:
build_llvm.build_from_source(args)
build_llvm.build_warp_clang(args, lib_name("warp-clang"))
except Exception as e:
# output build error
print(f"Warp build error: {e}")
# report error
sys.exit(1)
| 7,690 | Python | 34.118721 | 120 | 0.673602 |
NVIDIA/warp/build_llvm.py | import os
import subprocess
import sys
from warp.build_dll import *
# set build output path off this file
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, "warp")
llvm_project_path = os.path.join(base_path, "external/llvm-project")
llvm_build_path = os.path.join(llvm_project_path, "out/build/")
llvm_install_path = os.path.join(llvm_project_path, "out/install/")
# Fetch prebuilt Clang/LLVM libraries
def fetch_prebuilt_libraries(arch):
if os.name == "nt":
packman = "tools\\packman\\packman.cmd"
packages = {"x86_64": "15.0.7-windows-x86_64-ptx-vs142"}
else:
packman = "./tools/packman/packman"
if sys.platform == "darwin":
packages = {
"aarch64": "15.0.7-darwin-aarch64-macos11",
"x86_64": "15.0.7-darwin-x86_64-macos11",
}
else:
packages = {
"aarch64": "15.0.7-linux-aarch64-gcc7.5",
"x86_64": "18.1.3-linux-x86_64-gcc9.4",
}
subprocess.check_call(
[
packman,
"install",
"-l",
f"./_build/host-deps/llvm-project/release-{arch}",
"clang+llvm-warp",
packages[arch],
]
)
def build_from_source_for_arch(args, arch, llvm_source):
# Check out the LLVM project Git repository, unless it already exists
if not os.path.exists(llvm_source):
# Install dependencies
subprocess.check_call([sys.executable, "-m", "pip", "install", "gitpython"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "cmake"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "ninja"])
from git import Repo
repo_url = "https://github.com/llvm/llvm-project.git"
print(f"Cloning LLVM project from {repo_url}...")
shallow_clone = True # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/
version = "18.1.3"
if shallow_clone:
repo = Repo.clone_from(
repo_url,
to_path=llvm_source,
single_branch=True,
branch=f"llvmorg-{version}",
depth=1,
)
else:
repo = Repo.clone_from(repo_url, to_path=llvm_source)
repo.git.checkout(f"tags/llvmorg-{version}", "-b", f"llvm-{version}")
print(f"Using LLVM project source from {llvm_source}")
# CMake supports Debug, Release, RelWithDebInfo, and MinSizeRel builds
if args.mode == "release":
msvc_runtime = "MultiThreaded"
# prefer smaller size over aggressive speed
cmake_build_type = "MinSizeRel"
else:
msvc_runtime = "MultiThreadedDebug"
# When args.mode == "debug" we build a Debug version of warp.dll but
# we generally don't want warp-clang.dll to be a slow Debug version.
if args.debug_llvm:
cmake_build_type = "Debug"
else:
# The GDB/LLDB debugger observes the __jit_debug_register_code symbol
# defined by the LLVM JIT, for which it needs debug info.
cmake_build_type = "RelWithDebInfo"
# Location of cmake and ninja installed through pip (see build.bat / build.sh)
python_bin = "python/Scripts" if sys.platform == "win32" else "python/bin"
os.environ["PATH"] = os.path.join(base_path, "_build/target-deps/" + python_bin) + os.pathsep + os.environ["PATH"]
if arch == "aarch64":
target_backend = "AArch64"
else:
target_backend = "X86"
if sys.platform == "darwin":
host_triple = f"{arch}-apple-macos11"
osx_architectures = arch # build one architecture only
abi_version = ""
elif os.name == "nt":
host_triple = f"{arch}-pc-windows"
osx_architectures = ""
abi_version = ""
else:
host_triple = f"{arch}-pc-linux"
osx_architectures = ""
abi_version = "-fabi-version=13" # GCC 8.2+
llvm_path = os.path.join(llvm_source, "llvm")
build_path = os.path.join(llvm_build_path, f"{args.mode}-{arch}")
install_path = os.path.join(llvm_install_path, f"{args.mode}-{arch}")
# Build LLVM and Clang
# fmt: off
cmake_gen = [
"cmake",
"-S", llvm_path,
"-B", build_path,
"-G", "Ninja",
"-D", f"CMAKE_BUILD_TYPE={cmake_build_type}",
"-D", f"CMAKE_MSVC_RUNTIME_LIBRARY={msvc_runtime}",
"-D", f"LLVM_TARGETS_TO_BUILD={target_backend};NVPTX",
"-D", "LLVM_ENABLE_PROJECTS=clang",
"-D", "LLVM_ENABLE_ZLIB=FALSE",
"-D", "LLVM_ENABLE_ZSTD=FALSE",
"-D", "LLVM_ENABLE_TERMINFO=FALSE",
"-D", "LLVM_BUILD_LLVM_C_DYLIB=FALSE",
"-D", "LLVM_BUILD_RUNTIME=FALSE",
"-D", "LLVM_BUILD_RUNTIMES=FALSE",
"-D", "LLVM_BUILD_TOOLS=FALSE",
"-D", "LLVM_BUILD_UTILS=FALSE",
"-D", "LLVM_INCLUDE_BENCHMARKS=FALSE",
"-D", "LLVM_INCLUDE_DOCS=FALSE",
"-D", "LLVM_INCLUDE_EXAMPLES=FALSE",
"-D", "LLVM_INCLUDE_RUNTIMES=FALSE",
"-D", "LLVM_INCLUDE_TESTS=FALSE",
"-D", "LLVM_INCLUDE_TOOLS=TRUE", # Needed by Clang
"-D", "LLVM_INCLUDE_UTILS=FALSE",
"-D", f"CMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0 {abi_version}", # The pre-C++11 ABI is still the default on the CentOS 7 toolchain
"-D", f"CMAKE_INSTALL_PREFIX={install_path}",
"-D", f"LLVM_HOST_TRIPLE={host_triple}",
"-D", f"CMAKE_OSX_ARCHITECTURES={osx_architectures}",
# Disable unused tools and features
"-D", "CLANG_BUILD_TOOLS=FALSE",
"-D", "LLVM_ENABLE_PLUGINS=FALSE",
"-D", "CLANG_PLUGIN_SUPPORT=FALSE",
"-D", "CLANG_ENABLE_ARCMT=FALSE",
"-D", "CLANG_ENABLE_STATIC_ANALYZER=FALSE",
"-D", "CLANG_TOOLING_BUILD_AST_INTROSPECTION=FALSE",
"-D", "CLANG_TOOL_AMDGPU_ARCH_BUILD=FALSE",
"-D", "CLANG_TOOL_APINOTES_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_ARCMT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_CHECK_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_DIFF_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_EXTDEF_MAPPING_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FORMAT_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FORMAT_VS_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FUZZER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_IMPORT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_LINKER_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_NVLINK_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_PACKAGER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_REFACTOR_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_RENAME_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_REPL_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_SCAN_DEPS_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_SHLIB_BUILD=FALSE",
"-D", "CLANG_TOOL_C_ARCMT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_C_INDEX_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_DIAGTOOL_BUILD=FALSE",
"-D", "CLANG_TOOL_DRIVER_BUILD=FALSE",
"-D", "CLANG_TOOL_LIBCLANG_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_BUILD_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_BUILD_PY_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_VIEW_BUILD=FALSE",
"-D", "LLVM_ENABLE_BINDINGS=FALSE",
"-D", "LLVM_ENABLE_OCAMLDOC=FALSE",
"-D", "LLVM_TOOL_BUGPOINT_BUILD=FALSE",
"-D", "LLVM_TOOL_BUGPOINT_PASSES_BUILD=FALSE",
"-D", "LLVM_TOOL_CLANG_BUILD=FALSE",
"-D", "LLVM_TOOL_DSYMUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_DXIL_DIS_BUILD=FALSE",
"-D", "LLVM_TOOL_GOLD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLDB_BUILD=FALSE",
"-D", "LLVM_TOOL_LLI_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AR_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AS_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_BCANALYZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CAT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CFI_VERIFY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CONFIG_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_COV_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CVTRES_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXFILT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXMAP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_C_TEST_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DEBUGINFOD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DEBUGINFOD_FIND_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIS_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DLANG_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWARFDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWARFUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_EXEGESIS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_EXTRACT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_GO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_GSYMUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_IFS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ISEL_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ITANIUM_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_JITLINK_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_JITLISTENER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LIBTOOL_DARWIN_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LINK_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LIPO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LTO2_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LTO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MCA_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_ASSEMBLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_DISASSEMBLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MICROSOFT_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ML_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MODEXTRACT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_NM_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OBJCOPY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OBJDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OPT_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OPT_REPORT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PDBUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PROFDATA_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PROFGEN_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_READOBJ_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_REDUCE_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_REMARK_SIZE_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RTDYLD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RUST_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SHLIB_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SIM_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SIZE_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SPECIAL_CASE_LIST_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SPLIT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_STRESS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_STRINGS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SYMBOLIZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_TAPI_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_TLI_CHECKER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_UNDNAME_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_XRAY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_YAML_NUMERIC_PARSER_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_YAML_PARSER_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LTO_BUILD=FALSE",
"-D", "LLVM_TOOL_OBJ2YAML_BUILD=FALSE",
"-D", "LLVM_TOOL_OPT_BUILD=FALSE",
"-D", "LLVM_TOOL_OPT_VIEWER_BUILD=FALSE",
"-D", "LLVM_TOOL_REMARKS_SHLIB_BUILD=FALSE",
"-D", "LLVM_TOOL_SANCOV_BUILD=FALSE",
"-D", "LLVM_TOOL_SANSTATS_BUILD=FALSE",
"-D", "LLVM_TOOL_SPLIT_FILE_BUILD=FALSE",
"-D", "LLVM_TOOL_VERIFY_USELISTORDER_BUILD=FALSE",
"-D", "LLVM_TOOL_VFABI_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_XCODE_TOOLCHAIN_BUILD=FALSE",
"-D", "LLVM_TOOL_YAML2OBJ_BUILD=FALSE",
]
# fmt: on
subprocess.check_call(cmake_gen, stderr=subprocess.STDOUT)
cmake_build = ["cmake", "--build", build_path]
subprocess.check_call(cmake_build, stderr=subprocess.STDOUT)
cmake_install = ["cmake", "--install", build_path]
subprocess.check_call(cmake_install, stderr=subprocess.STDOUT)
def build_from_source(args):
print("Building Clang/LLVM from source...")
if args.llvm_source_path is not None:
llvm_source = args.llvm_source_path
else:
llvm_source = llvm_project_path
# build for the machine's architecture
build_from_source_for_arch(args, machine_architecture(), llvm_source)
# for Apple systems also cross-compile for building a universal binary
if sys.platform == "darwin":
if machine_architecture() == "x86_64":
build_from_source_for_arch(args, "aarch64", llvm_source)
else:
build_from_source_for_arch(args, "x86_64", llvm_source)
# build warp-clang.dll
def build_warp_clang_for_arch(args, lib_name, arch):
try:
cpp_sources = [
"native/clang/clang.cpp",
"native/crt.cpp",
]
clang_cpp_paths = [os.path.join(build_path, cpp) for cpp in cpp_sources]
clang_dll_path = os.path.join(build_path, f"bin/{lib_name}")
if args.build_llvm:
# obtain Clang and LLVM libraries from the local build
install_path = os.path.join(llvm_install_path, f"{args.mode}-{arch}")
libpath = os.path.join(install_path, "lib")
else:
# obtain Clang and LLVM libraries from packman
fetch_prebuilt_libraries(arch)
libpath = os.path.join(base_path, f"_build/host-deps/llvm-project/release-{arch}/lib")
libs = []
for _, _, libraries in os.walk(libpath):
libs.extend(libraries)
break # just the top level contains library files
if os.name == "nt":
libs.append("Version.lib")
libs.append("Ws2_32.lib")
libs.append(f'/LIBPATH:"{libpath}"')
else:
libs = [f"-l{lib[3:-2]}" for lib in libs if os.path.splitext(lib)[1] == ".a"]
if sys.platform == "darwin":
libs += libs # prevents unresolved symbols due to link order
else:
libs.insert(0, "-Wl,--start-group")
libs.append("-Wl,--end-group")
libs.append(f"-L{libpath}")
libs.append("-lpthread")
libs.append("-ldl")
if sys.platform != "darwin":
libs.append("-lrt")
build_dll_for_arch(
args,
dll_path=clang_dll_path,
cpp_paths=clang_cpp_paths,
cu_path=None,
libs=libs,
arch=arch,
mode=args.mode if args.build_llvm else "release",
)
except Exception as e:
# output build error
print(f"Warp Clang/LLVM build error: {e}")
# report error
sys.exit(1)
def build_warp_clang(args, lib_name):
if sys.platform == "darwin":
# create a universal binary by combining x86-64 and AArch64 builds
build_warp_clang_for_arch(args, lib_name + "-x86_64", "x86_64")
build_warp_clang_for_arch(args, lib_name + "-aarch64", "aarch64")
dylib_path = os.path.join(build_path, f"bin/{lib_name}")
run_cmd(f"lipo -create -output {dylib_path} {dylib_path}-x86_64 {dylib_path}-aarch64")
os.remove(f"{dylib_path}-x86_64")
os.remove(f"{dylib_path}-aarch64")
else:
build_warp_clang_for_arch(args, lib_name, machine_architecture())
| 16,081 | Python | 40.989556 | 142 | 0.577763 |
NVIDIA/warp/PACKAGING.md | # Release Instructions
## Versioning
Versions take the format X.Y.Z, similar to [Python itself](https://devguide.python.org/developer-workflow/development-cycle/#devcycle):
- Increments in X are reserved for major reworks of the project causing disruptive incompatibility (or reaching the 1.0 milestone).
- Increments in Y are for regular releases with a new set of features.
- Increments in Z are for bug fixes. In principle there are no new features. Can be omitted if 0 or not relevant.
This is similar to [Semantic Versioning](https://semver.org/) but less strict around backward compatibility.
Like with Python, some breaking changes can be present between minor versions if well documented and gradually introduced.
Note that prior to 0.11.0 this schema was not strictly adhered to.
## Repositories
Development happens internally on a GitLab repository (part of the Omniverse group), while releases are made public on GitHub.
This document uses the following Git remote names:
- **omniverse**: `git remote add omniverse https://gitlab-master.nvidia.com/omniverse/warp.git`
- **github**: `git remote add github https://github.com/NVIDIA/warp.git`
Currently, all feature branches get merged into the `main` branch of the **omniverse** repo and then GitLab push-mirrors
the changes over to GitHub (nominally within five minutes). This mirroring process also pushes all tags
(only tags beginning with `v` are allowed to be created) and branches beginning with `release-`.
The status of push mirroring can be checked under **Settings** :arrow_right: **Repository** on GitLab.
## GitLab Release Branch
1) Create a branch in your fork repository from which a merge-request will be opened to bump the version string
and create the public-facing changelogs for the release.
2) Search & replace the current version string from `VERSION.md`.
We want to keep the Omniverse extensions' version in sync with the library so update the strings found in the `exts` folder as well.
The version string currently appears in the following two files, but there could be more in the future:
- `omni.warp/config/extension.toml`
- `omni.warp.core/config/extension.toml`
Be sure *not* to update previous strings in `CHANGELOG.md`.
3) Update `CHANGELOG.md` from Git history (since the last release branch). Only list user-facing changes.
The entire development team should all be helping to keep this file up-to-date, so verify that all changes users
should know about are included.
The changelogs from the Omniverse extensions found in `exts` are kept in sync with the one from the library, so update them all at the same time and list any change made to the extensions.
4) Open a MR on GitLab to merge this branch into `main`. Send a message in `#omni-warp-dev` to the `@warp-team`
asking for a review of the merge request's changes.
5) Merge the branch into `main` after waiting a reasonable amount of time for the team to review and approve the MR.
6) For new `X.Y` versions, create a release branch (note `.Z` maintenance versions remain on the same branch):
`git checkout -b release-X.Y [<start-point>]`
If branching from an older revision or reusing a branch, make sure to cherry-pick the version and changelog update.
7) Make any release-specific changes (e.g. disable/remove features not ready yet).
8) :warning: Keep in mind that branches pushed to the **omniverse** repository beginning with `release-` are
automatically mirrored to GitLab. :warning:
Push the new release branch to **omniverse** when it is in a state ready for CI testing.
9) Check that the last revision on the release branch passes GitLab CI tests. A pipeline should have been automatically
created after pushing the branch in the previous step:
<https://gitlab-master.nvidia.com/omniverse/warp/-/pipelines>
Fix issues until all tests pass. Cherry-pick fixes for `main` where applicable.
## Creating a GitHub Release Package
1) Wait for the (latest) packages to appear in:
<https://gitlab-master.nvidia.com/omniverse/warp/-/packages/>
2) Download the `.whl` files for each supported platform and move them into an empty folder.
3) Run tests for at least one platform:
- Run `python -m pip install warp_lang-<version>-<platform-tag>.whl`
- Run `python -m warp.tests`
Check that the correct version number gets printed.
4) If tests fail, make fixes on `release-X.Y` and where necessary cherry-pick to `main` before repeating from step (1).
5) Tag the release with `vX.Y.Z` on `release-X.Y` and push to `omniverse`.
Both the tag and the release branch will be automatically mirrored to GitLab.
It is safest to push *just* the new tag using `git push omniverse vX.Y.Z`.
In case of a mistake, a tag already pushed to `omniverse` can be deleted from the GitLab UI.
The bad tag must also be deleted from the GitHub UI if it was mirrored there.
6) Create a new release on [GitHub](https://github.com/NVIDIA/warp) with a tag and title of `vX.Y.Z` and
upload the `.whl` artifacts as attachments. Use the changelog updates as the description.
## Upload a PyPI Release
First time:
- Create a [PyPI](https://pypi.org/) account.
- [Create a Token](https://pypi.org/manage/account/#api-tokens) for uploading to the `warp-lang` project (store it somewhere safe).
- Get an admin (<[email protected]>) to give you write access to the project.
Per release:
Run `python -m twine upload *` from the `.whl` packages folder (on Windows make sure to use `cmd` shell; Git Bash doesn't work).
- username: `__token__`
- password: `(your token string from PyPI)`
## Publishing the Omniverse Extensions
1) Ensure that the version strings and `CHANGELOG.md` files in the `exts` folder are in sync with the ones from the library.
2) Wait for the (latest) packages to appear in:
<https://gitlab-master.nvidia.com/omniverse/warp/-/packages/>
3) Download `kit-extensions.zip` to your computer.
4) Extract it to a clean folder and check the extensions inside of Kit:
- Run `omni.create.sh --ext-folder /path/to/artifacts/exts --enable omni.warp-X.Y.Z --enable omni.warp.core-X.Y.Z`
- Ensure that the example scenes are working as expected
- Run test suites for both extensions
5) If tests fail, make fixes on `release-X.Y` and where necessary cherry-pick to `main` before repeating from step (2).
6) If all tests passed:
- `kit --ext-folder /path/to/artifacts/exts --publish omni-warp.core-X.Y.Z`
- `kit --ext-folder /path/to/artifacts/exts --publish omni-warp-X.Y.Z`
7) Ensure that the release is tagged with `vX.Y.Z` on both `omniverse/release-X.Y` and `github/release-X.Y`.
## Automated processes
The following is just for your information. These steps should run automatically by CI/CD pipelines, but can be replicated manually if needed:
### Building the documentation
The contents of <https://nvidia.github.io/warp/> is generated by a GitHub pipeline which runs `python build_docs.py` (prerequisites: `pip install docs/requirements.txt`).
### Building pip wheels
The GitLab pipeline's `create pypi wheels` Job (part of the `package` Stage) combines artifacts from each platform build, moving the contents of `warp/bin` to platform- and architecture-specific
subfolders; e.g. `warp/bin/linux-x86_64` and `warp/bin/linux-aarch64` both contain `warp.so` and `warp-clang.so` files.
Pip wheels are then built using:
```bash
python -m build --wheel -C--build-option=-Pwindows-x86_64
python -m build --wheel -C--build-option=-Plinux-x86_64
python -m build --wheel -C--build-option=-Plinux-aarch64
python -m build --wheel -C--build-option=-Pmacos-universal
```
Selecting the correct library files for each wheel happens in [`setup.py`](setup.py).
| 7,743 | Markdown | 44.552941 | 194 | 0.74816 |
NVIDIA/warp/pyproject.toml | [build-system]
requires = ["setuptools>=61", "build", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "warp-lang"
requires-python = ">=3.7" # 3.9 recommended
authors = [{ name = "NVIDIA", email = "[email protected]" }]
description = "A Python framework for high-performance simulation and graphics programming"
license = { text = "NVIDIA Software License" }
classifiers = [
"Programming Language :: Python :: 3.7", # Deprecated
"Programming Language :: Python :: 3.8", # Deprecated
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"License :: Other/Proprietary License",
"Operating System :: OS Independent",
]
dependencies = ["numpy"]
dynamic = ["version", "readme"]
[project.urls]
GitHub = "https://github.com/NVIDIA/warp"
Documentation = "https://nvidia.github.io/warp"
Changelog = "https://github.com/NVIDIA/warp/blob/main/CHANGELOG.md"
[project.optional-dependencies]
dev = ["pre-commit", "ruff", "nvtx", "furo", "sphinx-copybutton", "coverage[toml]"]
extras = ['usd-core', 'matplotlib', 'pyglet']
[tool.setuptools.packages.find]
include = ["warp*"]
[tool.setuptools.dynamic]
version = { attr = "warp.config.version" }
readme = { file = ["README.md"], content-type = "text/markdown" }
[tool.ruff]
cache-dir = ".cache/ruff"
line-length = 120
indent-width = 4
extend-exclude = [
"warp/native/cutlass/",
"warp/thirdparty/appdirs.py",
"warp/thirdparty/dlpack.py",
"tools",
"stubs.py",
]
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"I", # isort
"F", # pyflakes
"W", # pycodestyle warnings
"B", # flake8-bugbear
"C4", # flake8-comprehensions
]
ignore = [
"E501", # Many lines are over 120 characters already
"E741", # Warp often uses l as a variable name
"F403", # Allow wildcard imports
"F405", # Related to use of wildcard imports
"F811", # Warp often uses overloads
]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
"warp/tests/*.py" = ["F841"]
[tool.ruff.lint.pydocstyle]
convention = "google"
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"
docstring-code-format = true
[tool.coverage.run]
source = ["warp", "warp.sim", "warp.render"]
disable_warnings = [
"module-not-measured",
"module-not-imported",
"no-data-collected",
"couldnt-parse",
]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"@wp",
"@warp",
"if 0:",
"if __name__ == .__main__.:",
]
omit = [
"*/warp/thirdparty/*",
"*/warp/examples/*",
"*/warp/tests/*",
"*/warp/fem/*",
"appdirs.py",
"render_opengl.py",
"build_dll.py",
"config.py",
"stubs.py",
]
| 2,800 | TOML | 24.463636 | 91 | 0.633571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.