file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ColorWidget"]
from ctypes import Union
from typing import List, Optional
import omni.ui as ui
COLOR_PICKER_WIDTH = 20
SPACING = 4
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__model = None
self.__multifield = None
self.__colorpicker = None
self.__frame = None
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__root_frame, attr)
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifield:
return self.__multifield.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__multifield.model = value
self.__colorpicker.model = value
def _build_fn(self):
with ui.HStack(spacing=SPACING):
# The construction of multi field depends on what the user provided,
# defaults or a model
if self.__model:
# the user provided a model
self.__multifield = ui.MultiFloatDragField(
min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color"
)
model = self.__model
else:
# the user provided a list of default values
self.__multifield = ui.MultiFloatDragField(
*self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color"
)
model = self.__multifield.model
self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
| 2,600 | Python | 33.223684 | 95 | 0.611538 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ExampleWindow"]
import omni.ui as ui
from .style import example_window_style
from .color_widget import ColorWidget
LABEL_WIDTH = 120
SPACING = 4
class ExampleWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=20, height=20)
def _build_calculations(self):
"""Build the widgets of the "Calculations" group"""
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Precision", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int")
with ui.HStack():
ui.Label("Iterations", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int", min=0, max=5)
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Value", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("i", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("j", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("k", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("Theta", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
def _build_light_1(self):
"""Build the widgets of the "Light 1" group"""
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("Color", name="attribute_name", width=self.label_width)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
with ui.HStack():
ui.Label("Shadow", name="attribute_name", width=self.label_width)
ui.CheckBox(name="attribute_bool")
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_calculations()
self._build_parameters()
self._build_light_1()
| 5,056 | Python | 39.13492 | 111 | 0.584256 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/README.md |
# Generic Window (omni.example.ui_window)

## Overview
This extension provides an end-to-end example and general recommendations on creating a
simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style.
## [Tutorial](../tutorial/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own
Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md)
## Usage
This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application.
## Explanations
### Extension
When the extension starts up, we register a new menu item that controls the
window and shows the window.
A very important part is using `ui.Workspace.set_show_window_fn` to register the
window in `omni.ui`. It will help to save and load the layout of Kit.
```
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
```
When the extension shuts down, we remove the menu item and deregister the window
callback.
### Window
It's handy to derive a custom window from the class `ui.Window`. The UI can be
defined right in __init__, so it's created immediately. Or it can be defined in
a callback and it will be created when the window is visible.
```
class ExampleWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
```
### Custom Widget
A custom widget can be a class or a function. It's not required to derive
anything. It's only necessary to create sub-widgets.
```
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
```
### Style
Although the style can be applied to any widget, we recommend keeping the style
dictionary in one location.
There is an exception to this recommendation. It's recommended to use styles
directly on the widgets to hide a part of the widget. For example, it's OK to
set {"color": cl.transparent} on a slider to hide the text. Or
"background_color": cl.transparent to disable background on a field.
| 3,040 | Markdown | 35.202381 | 155 | 0.715789 |
NVIDIA-Omniverse/USD-Tutorials-And-Examples/README.md | # USD Tutorials and Examples
## About
This project showcases educational material for [Pixar's Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html) (USD).
For convenience, the Jupyter notebook from the GTC session is available on Google Colaboratory, which offers an interactive environment from the comfort of your web browser. Colaboratory makes it possible to:
* Try code snippets without building or installing USD on your machine
* Run the samples on any device
* Share code experiments with others
Should you prefer to run the notebook on your local machine instead, simply download and execute it after [installing Jupyter](https://jupyter.org).
## Sample Notebook
Follow along the tutorial using the sample notebook from the GTC session, or get acquainted with USD using other examples:
|Notebook|Google Colab link|
|--------|:----------------:|
|Introduction to USD|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/usd_introduction.ipynb)|
|Opening USD Stages|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/opening_stages.ipynb)|
|Prims, Attributes and Metadata|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/prims_attributes_and_metadata.ipynb)|
|Hierarchy and Traversal|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/hierarchy_and_traversal.ipynb)|
## Additional Resources
* [Pixar's USD](https://graphics.pixar.com/usd)
* [USD at NVIDIA](https://usd.nvidia.com)
* [USD training content on _NVIDIA On-Demand_](https://www.nvidia.com/en-us/on-demand/playlist/playList-911c5614-4b7f-4668-b9eb-37f627ac8d17/)
| 2,140 | Markdown | 78.296293 | 263 | 0.784112 |
NVIDIA-Omniverse/kit-project-template/repo.toml | ########################################################################################################################
# Repo tool base settings
########################################################################################################################
[repo]
# Use the Kit Template repo configuration as a base. Only override things specific to the repo.
import_configs = [
"${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml",
"${root}/_repo/deps/repo_kit_tools/kit-template/repo-external.toml",
]
extra_tool_paths = [
"${root}/kit/dev",
]
########################################################################################################################
# Extensions precacher
########################################################################################################################
[repo_precache_exts]
# Apps to run and precache
apps = [
"${root}/source/apps/my_name.my_app.kit"
]
| 949 | TOML | 31.75862 | 120 | 0.33509 |
NVIDIA-Omniverse/kit-project-template/README.md | # *Omniverse Kit* Project Template
This project is a template for developing apps and extensions for *Omniverse Kit*.
# Important Links
- [Omniverse Documentation Site](https://docs.omniverse.nvidia.com/kit/docs/kit-project-template)
- [Github Repo for this Project Template](https://github.com/NVIDIA-Omniverse/kit-project-template)
- [Extension System](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html)
# Getting Started
1. Fork/Clone the Kit Project Template repo [link](https://github.com/NVIDIA-Omniverse/kit-project-template) to a local folder, for example in `C:\projects\kit-project-template`
2. (Optional) Open this cloned repo using Visual Studio Code: `code C:\projects\kit-project-template`. It will likely suggest installing a few extensions to improve python experience. None are required, but they may be helpful.
3. In a CLI terminal (if in VS Code, CTRL + \` or choose Terminal->New Terminal from the menu) run `pull_kit_kernel.bat` (windows) / `pull_kit_kernel.sh` (linux) to pull the *Omniverse Kit Kernel*. `kit` folder link will be created under the main folder in which your project is located.
4. Run the example app that includes example extensions: `source/apps/my_name.my_app.bat` (windows) / `./source/apps/my_name.my_app.sh` (linux) to ensure everything is working. The first start will take a while as it will pull all the extensions from the extension registry and build various caches. Subsequent starts will be much faster. Once finished, you should see a "Kit Base Editor" window and a welcome screen. Feel free to browse through the base application and exit when finished. You are now ready to begin development!
## An Omniverse App
If you look inside a `source/apps/my_name.my_app.bat` or any other *Omniverse App*, they all run off of an SDK we call *Omniverse Kit* . The base application for *Omniverse Kit* (`kit.exe`) is the runtime that powers *Apps* build out of extensions.
Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **All other functionality is provided by extensions.**
To start an app we pass a `kit` file, which is a configuration file with a `kit` extension. It describes which extensions to pull and load, and which settings to apply. One kit file fully describes an app, but you may find value in having several for different methods to run and test your application.
Notice that it includes `omni.hello.world` extension; that is an example extension found in this repo. All the other extensions are pulled from the `extension registry` on first startup.
More info on building kit files: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html)
### Packaging an App
Once you have developed, tested, and documented your app or extension, you will want to publish it. Before publishing the app, we must first assemble all its components into a single deliverable. This step is called "packaging".
To package an app run `tools/package.bat` (or `repo package`). The package will be created in the `_build/packages` folder.
To use the package, unzip the package that was created by the above step into its own separate folder. Then, run `pull_kit_kernel.bat` inside the new folder once before running the app.
### Version Lock
An app `kit` file fully defines all the extensions, but their versions are not `locked`, which is to say that by default the latest versions of a given extension will be used. Also, many extensions have dependencies themselves which cause kit to download and enable other extensions.
This said, for the final app it is important that it always gets the same extensions and the same versions on each run. This is meant to provide reliable and reproducible builds. This is called a *version lock* and we have a separate section at the end of `kit` file to lock versions of all extensions and all their dependencies.
It is also important to update the version lock section when adding new extensions or updating existing ones. To update version lock the `precache_exts` tool is used.
**To update version lock run:** `tools/update_version_lock.bat`.
Once you've done this, use your source control methods to commit any changes to a kit file as part of the source necessary to reproduce the build.
The packaging tool will verify that version locks exist and will fail if they do not.
More info on dependency management: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html#application-dependencies-management)
## An Omniverse Extension
This template includes one simple extension: `omni.hello.world`. It is loaded in the example app, but can also be loaded and tested in any other *Omniverse App*. You should feel free to copy or rename this extension to one that you wish to create. Please refer to Omniverse Documentation for more information on developing extensions.
### Using Omniverse Launcher
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*.
### Add a new extension to your *Omniverse App*
If you want to add extensions from this repo to your other existing Omniverse App.
1. In the *Omniverse App* open extension manager: *Window* → *Extensions*.
2. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar.
3. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `source/extensions` subfolder there as another search path: `C:/projects/kit-project-template/source/extensions`

4. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it.
5. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload.
### Adding a new extension
* Now that `source/extensions` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*.
* Look at the *Console* window for warnings and errors. It also has a small button to open current log file.
* All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`.
* Extension name is a folder name in `source/extensions`, in this example: `omni.hello.world`. This is most often the same name as the "Extension ID".
* The most important thing that an extension has is its config file: `extension.toml`. You should familiarize yourself with its contents.
* In the *Extensions* window, press *Burger* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be by displaying all its dependencies.
* Extensions system documentation can be found [here](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html)
### Alternative way to add a new extension
To get a better understanding of the extension topology, we recommend following:
1. Run bare `kit.exe` with `source/extensions` folder added as an extensions search path and new extension enabled:
```bash
> kit\kit.exe --ext-folder source/extensions --enable omni.hello.world
```
- `--ext-folder [path]` - adds new folder to the search path
- `--enable [extension]` - enables an extension on startup.
Use `-h` for help:
```bash
> kit\kit.exe -h
```
2. After the *App* starts you should see:
* new "My Window" window popup.
* extension search paths in *Extensions* window as in the previous section.
* extension enabled in the list of extensions.
It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!):
```bash
> kit\kit.exe --ext-folder source/extensions --enable omni.hello.world --enable omni.kit.window.extensions
```
You should see a menu in the top left. From this UI you can browse and enable more extensions. It is important to note that these enabled extensions are NOT added to your kit file, but instead live in a local "user" file as an addendum. If you want the extension to be a part of your app, you must add its name to the list of dependencies in the `[dependencies]` section.
# A third way to add an extension
Here is how to add an extension by copying the "hello world" extension as a template:
1. copy `source/extensions/omni.hello.world` to `source/extensions/[new extension id]`
2. rename python module (namespace) in `source/extensions/[new extension id]/omni/hello/world` to `source/extensions/[new extension id]/[new python module]`
3. update `source/extensions/[new extension name]/config/extension.toml`, most importantly specify new python module to load:
4. Optionally, add the `[extension id]` to the `[dependencies]` section of the app's kit file.
[[python.module]]
name = "[new python module]"
# Running Tests
To run tests we run a new configuration where only the tested extension (and its dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests:
1. Run: `tools\test_ext.bat omni.hello.world`
That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code!
2. Alternatively, in *Extension Manager* (*Window → Extensions*) find your extension, click on *TESTS* tab, click *Run Test*
For more information about testing refer to: [testing doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/testing_exts_python.html).
No restart is needed, you should be able to find and enable `[new extension name]` in extension manager.
# Sharing extensions
To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository).
1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery.
2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes.
# Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
# License
By using any part of the files in the KIT-PROJECT-TEMPLATE repo you agree to the terms of the NVIDIA Omniverse License Agreement, the most recent version of which is available [here](https://docs.omniverse.nvidia.com/composer/latest/common/NVIDIA_Omniverse_License_Agreement.html). | 11,077 | Markdown | 69.560509 | 533 | 0.769613 |
NVIDIA-Omniverse/kit-project-template/tools/deps/repo-deps.packman.xml | <project toolsVersion="5.0">
<dependency name="repo_build" linkPath="../../_repo/deps/repo_build">
<package name="repo_build" version="0.40.0"/>
</dependency>
<dependency name="repo_ci" linkPath="../../_repo/deps/repo_ci">
<package name="repo_ci" version="0.5.1" />
</dependency>
<dependency name="repo_changelog" linkPath="../../_repo/deps/repo_changelog">
<package name="repo_changelog" version="0.3.0" />
</dependency>
<dependency name="repo_format" linkPath="../_repo/deps/repo_format">
<package name="repo_format" version="2.7.0" />
</dependency>
<dependency name="repo_kit_tools" linkPath="../../_repo/deps/repo_kit_tools">
<package name="repo_kit_tools" version="0.12.18"/>
</dependency>
<dependency name="repo_licensing" linkPath="../../_repo/deps/repo_licensing">.
<package name="repo_licensing" version="1.11.2" />
</dependency>
<dependency name="repo_man" linkPath="../../_repo/deps/repo_man">
<package name="repo_man" version="1.32.1"/>
</dependency>
<dependency name="repo_package" linkPath="../../_repo/deps/repo_package">
<package name="repo_package" version="5.8.5" />
</dependency>
<dependency name="repo_source" linkPath="../../_repo/deps/repo_source">
<package name="repo_source" version="0.4.2"/>
</dependency>
<dependency name="repo_test" linkPath="../../_repo/deps/repo_test">
<package name="repo_test" version="2.5.6"/>
</dependency>
</project>
| 1,448 | XML | 42.90909 | 80 | 0.649171 |
NVIDIA-Omniverse/kit-project-template/tools/deps/kit-sdk.packman.xml | <project toolsVersion="5.0">
<dependency name="kit_sdk_${config}" linkPath="../../kit" tags="${config} non-redist">
<package name="kit-kernel" version="105.1+release.127680.dd92291b.tc.${platform}.${config}"/>
</dependency>
</project>
| 243 | XML | 39.66666 | 97 | 0.666667 |
NVIDIA-Omniverse/kit-project-template/source/package/description.toml | # Description of the application for the Omniverse Launcher
name = "My App" # displayed application name
shortName = "My App" # displayed application name in smaller card and library view
version = "${version}" # version must be semantic
kind = "app" # enum of "app", "connector" and "experience" for now
latest = true # boolean for if this version is the latest version
slug = "my_app" # unique identifier for component, all lower case, persists between versions
productArea = "My Company" # displayed before application name in launcher
category = "Apps" # category of content
channel = "release" # 3 filter types [ "alpha", "beta", "release "]
enterpriseStatus = false # Set true if you want this package to show in enterprise launcher
# values for filtering content
tags = [
"Media & Entertainment",
"Manufacturing",
"Product Design",
"Scene Composition",
"Visualization",
"Rendering"
]
# string array, each line is a new line, keep lines under 256 char and keep lines under 4
description = [
"My App is an application to showcase how to build an Omniverse App. ",
"FEATURES:",
"- Small and simple.",
"- Easy to change."
]
# array of links for more info on product
[[links]]
title = "Release Notes"
url = "https://google.com"
[[links]]
title = "Documentation"
url = "https://google.com"
| 1,398 | TOML | 34.871794 | 104 | 0.67525 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/README.md | # AI Room Generator Extension Sample

### About
This extension allows user's to generate 3D content using Generative AI, ChatGPT. Providing an area in the stage and a prompt the user can generate a room configuration designed by ChatGPT. This in turn can help end users automatically generate and place objects within their scene, saving hours of time that would typically be required to create a complex scene.
### [README](exts/omni.example.airoomgenerator)
See the [README for this extension](exts/omni.example.airoomgenerator) to learn more about it including how to use it.
> This sample is for educational purposes. For production please consider best security practices and scalability.
## Adding This Extension
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-airoomgenerator?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
## Linking with an Omniverse app
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,140 | Markdown | 40.173076 | 363 | 0.775701 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}
}
| 946 | Python | 32.821427 | 98 | 0.726216 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from .window import DeepSearchPickerWindow
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = DeepSearchPickerWindow("DeepSearch Swap", width=300, height=300)
def on_shutdown(self):
self._window.destroy()
self._window = None
| 1,423 | Python | 44.935482 | 119 | 0.747013 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/deep_search.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from omni.kit.ngsearch.client import NGSearchClient
import carb
import asyncio
class deep_search():
async def query_items(queries, url: str, paths):
result = list(tuple())
for query in queries:
query_result = await deep_search._query_first(query, url, paths)
if query_result is not None:
result.append(query_result)
return result
async def _query_first(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
SearchResult = await NGSearchClient.get_instance().find2(
query=filtered_query, url=url)
if len(SearchResult.paths) > 0:
return (query, SearchResult.paths[0].uri)
else:
return None
async def query_all(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
| 2,185 | Python | 32.121212 | 98 | 0.632494 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
from .style import gen_ai_style
from .deep_search import deep_search
import asyncio
from pxr import UsdGeom, Usd, Sdf, Gf
class DeepSearchPickerWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self.frame.set_build_fn(self._build_fn)
self._index = 0
self._query_results = None
self._selected_prim = None
self._prim_path_model = ui.SimpleStringModel()
def _build_fn(self):
async def replace_prim():
self._index = 0
ctx = omni.usd.get_context()
prim_paths = ctx.get_selection().get_selected_prim_paths()
if len(prim_paths) != 1:
carb.log_warn("You must select one and only one prim")
return
prim_path = prim_paths[0]
stage = ctx.get_stage()
self._selected_prim = stage.GetPrimAtPath(prim_path)
query = self._selected_prim.GetAttribute("DeepSearch:Query").Get()
prop_paths = ["/Projects/simready_content/common_assets/props/",
"/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/",
"/NVIDIA/Assets/Isaac/2022.1/NVIDIA/Assets/ArchVis/Residential/Furniture/"]
self._query_results = await deep_search.query_all(query, "omniverse://ov-simready/", paths=prop_paths)
self._prim_path_model.set_value(prim_path)
def increment_prim_index():
if self._query_results is None:
return
self._index = self._index + 1
if self._index >= len(self._query_results.paths):
self._index = 0
self.replace_reference()
def decrement_prim_index():
if self._query_results is None:
return
self._index = self._index - 1
if self._index <= 0:
self._index = len(self._query_results.paths) - 1
self.replace_reference()
with self.frame:
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Spacer()
ui.StringField(model=self._prim_path_model, width=365, height=30)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: asyncio.ensure_future(replace_prim()))
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Button("<", width=200, clicked_fn=lambda: decrement_prim_index())
ui.Button(">", width=200, clicked_fn=lambda: increment_prim_index())
ui.Spacer()
def replace_reference(self):
references: Usd.references = self._selected_prim.GetReferences()
references.ClearReferences()
references.AddReference(
assetPath="omniverse://ov-simready" + self._query_results.paths[self._index].uri)
carb.log_info("Got it?")
def destroy(self):
super().destroy() | 3,815 | Python | 36.048543 | 123 | 0.589253 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "AI Room Generator Sample"
description="Generates Rooms using ChatGPT"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/preview_icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.ngsearch" = {}
"omni.kit.window.popup_dialog" = {}
# Main python module this extension provides, it will be publicly available as "import company.hello.world".
[[python.module]]
name = "omni.example.airoomgenerator"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,091 | TOML | 24.999999 | 108 | 0.731439 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Gf
class PrimInfo:
# Class that stores the prim info
def __init__(self, prim: Usd.Prim, name: str = "") -> None:
self.prim = prim
self.child = prim.GetAllChildren()[0]
self.length = self.GetLengthOfPrim()
self.width = self.GetWidthOfPrim()
self.origin = self.GetPrimOrigin()
self.area_name = name
def GetLengthOfPrim(self) -> str:
# Returns the X value
attr = self.child.GetAttribute('xformOp:scale')
x_scale = attr.Get()[0]
return str(x_scale)
def GetWidthOfPrim(self) -> str:
# Returns the Z value
attr = self.child.GetAttribute('xformOp:scale')
z_scale = attr.Get()[2]
return str(z_scale)
def GetPrimOrigin(self) -> str:
attr = self.prim.GetAttribute('xformOp:translate')
origin = Gf.Vec3d(0,0,0)
if attr:
origin = attr.Get()
phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2])
return phrase | 1,706 | Python | 36.108695 | 98 | 0.651817 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from omni.ui import color as cl
import asyncio
import omni
import carb
class ProgressBar:
def __init__(self):
self.progress_bar_window = None
self.left = None
self.right = None
self._build_fn()
async def play_anim_forever(self):
fraction = 0.0
while True:
fraction = (fraction + 0.01) % 1.0
self.left.width = ui.Fraction(fraction)
self.right.width = ui.Fraction(1.0-fraction)
await omni.kit.app.get_app().next_update_async()
def _build_fn(self):
with ui.VStack():
self.progress_bar_window = ui.HStack(height=0, visible=False)
with self.progress_bar_window:
ui.Label("Processing", width=0, style={"margin_width": 3})
self.left = ui.Spacer(width=ui.Fraction(0.0))
ui.Rectangle(width=50, style={"background_color": cl("#76b900")})
self.right = ui.Spacer(width=ui.Fraction(1.0))
def show_bar(self, to_show):
self.progress_bar_window.visible = to_show
| 1,770 | Python | 34.419999 | 98 | 0.655367 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import carb
import aiohttp
import asyncio
from .prompts import system_input, user_input, assistant_input
from .deep_search import query_items
from .item_generator import place_greyboxes, place_deepsearch_results
async def chatGPT_call(prompt: str):
# Load your API key from an environment variable or secret management service
settings = carb.settings.get_settings()
apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
my_prompt = prompt.replace("\n", " ")
# Send a request API
try:
parameters = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
{"role": "assistant", "content": assistant_input},
{"role": "user", "content": my_prompt}
]
}
chatgpt_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": "Bearer %s" % apikey}
# Create a completion using the chatGPT model
async with aiohttp.ClientSession() as session:
async with session.post(chatgpt_url, headers=headers, json=parameters) as r:
response = await r.json()
text = response["choices"][0]["message"]['content']
except Exception as e:
carb.log_error("An error as occurred")
return None, str(e)
# Parse data that was given from API
try:
#convert string to object
data = json.loads(text)
except ValueError as e:
carb.log_error(f"Exception occurred: {e}")
return None, text
else:
# Get area_objects_list
object_list = data['area_objects_list']
return object_list, text
async def call_Generate(prim_info, prompt, use_chatgpt, use_deepsearch, response_label, progress_widget):
run_loop = asyncio.get_event_loop()
progress_widget.show_bar(True)
task = run_loop.create_task(progress_widget.play_anim_forever())
response = ""
#chain the prompt
area_name = prim_info.area_name.split("/World/Layout/")
concat_prompt = area_name[-1].replace("_", " ") + ", " + prim_info.length + "x" + prim_info.width + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt
root_prim_path = "/World/Layout/GPT/"
if prim_info.area_name != "":
root_prim_path= prim_info.area_name + "/items/"
if use_chatgpt: #when calling the API
objects, response = await chatGPT_call(concat_prompt)
else: #when testing and you want to skip the API call
data = json.loads(assistant_input)
objects = data['area_objects_list']
if objects is None:
response_label.text = response
return
if use_deepsearch:
settings = carb.settings.get_settings()
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path")
filter_paths = filter_path.split(',')
queries = list()
for item in objects:
queries.append(item['object_name'])
query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths)
if query_result is not None:
place_deepsearch_results(
gpt_results=objects,
query_result=query_result,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
task.cancel()
await asyncio.sleep(1)
response_label.text = response
progress_widget.show_bar(False)
| 4,729 | Python | 39.775862 | 204 | 0.623176 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976},
"Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898},
"Line": {
"margin": 3
},
"Label": {
"margin_width": 5
}
}
guide = """
Step 1: Create a Floor
- You can draw a floor outline using the pencil tool. Right click in the viewport then `Create>BasicCurves>From Pencil`
- OR Create a prim and scale it to the size you want. i.e. Right click in the viewport then `Create>Mesh>Cube`.
- Next, with the floor selected type in a name into "Area Name". Make sure the area name is relative to the room you want to generate.
For example, if you inputted the name as "bedroom" ChatGPT will be prompted that the room is a bedroom.
- Then click the '+' button. This will generate the floor and add the option to our combo box.
Step 2: Prompt
- Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room.
For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down".
Step 3: Generate
- Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response.
- Select 'use Deepsearch' if you want to use the deepsearch functionality. (ENTERPRISE USERS ONLY)
When deepsearch is false it will spawn in cubes that greybox the scene.
- Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made.
Step 4: More Rooms
- To add another room you can repeat Steps 1-3. To regenerate a previous room just select it from the 'Current Room' in the dropdown menu.
- The dropdown menu will remember the last prompt you used to generate the items.
- If you do not like the items it generated, you can hit the generate button until you are satisfied with the items.
""" | 2,792 | Python | 45.549999 | 138 | 0.731734 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/prompts.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
system_input='''You are an area generator expert. Given an area of a certain size, you can generate a list of items that are appropriate to that area, in the right place, and with a representative material.
You operate in a 3D Space. You work in a X,Y,Z coordinate system. X denotes width, Y denotes height, Z denotes depth. 0.0,0.0,0.0 is the default space origin.
You receive from the user the name of the area, the size of the area on X and Z axis in centimetres, the origin point of the area (which is at the center of the area).
You answer by only generating JSON files that contain the following information:
- area_name: name of the area
- X: coordinate of the area on X axis
- Y: coordinate of the area on Y axis
- Z: coordinate of the area on Z axis
- area_size_X: dimension in cm of the area on X axis
- area_size_Z: dimension in cm of the area on Z axis
- area_objects_list: list of all the objects in the area
For each object you need to store:
- object_name: name of the object
- X: coordinate of the object on X axis
- Y: coordinate of the object on Y axis
- Z: coordinate of the object on Z axis
- Length: dimension in cm of the object on X axis
- Width: dimension in cm of the object on Y axis
- Height: dimension in cm of the object on Z axis
- Material: a reasonable material of the object using an exact name from the following list: Plywood, Leather_Brown, Leather_Pumpkin, Leather_Black, Aluminum_Cast, Birch, Beadboard, Cardboard, Cloth_Black, Cloth_Gray, Concrete_Polished, Glazed_Glass, CorrugatedMetal, Cork, Linen_Beige, Linen_Blue, Linen_White, Mahogany, MDF, Oak, Plastic_ABS, Steel_Carbon, Steel_Stainless, Veneer_OU_Walnut, Veneer_UX_Walnut_Cherry, Veneer_Z5_Maple.
Each object name should include an appropriate adjective.
Keep in mind, objects should be disposed in the area to create the most meaningful layout possible, and they shouldn't overlap.
All objects must be within the bounds of the area size; Never place objects further than 1/2 the length or 1/2 the depth of the area from the origin.
Also keep in mind that the objects should be disposed all over the area in respect to the origin point of the area, and you can use negative values as well to display items correctly, since origin of the area is always at the center of the area.
Remember, you only generate JSON code, nothing else. It's very important.
'''
user_input="Warehouse, 1000x1000, origin at (0.0,0.0,0.0), generate a list of appropriate items in the correct places. Generate warehouse objects"
assistant_input='''{
"area_name": "Warehouse_Area",
"X": 0.0,
"Y": 0.0,
"Z": 0.0,
"area_size_X": 1000,
"area_size_Z": 1000,
"area_objects_list": [
{
"object_name": "Parts_Pallet_1",
"X": -150,
"Y": 0.0,
"Z": 250,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Boxes_Pallet_2",
"X": -150,
"Y": 0.0,
"Z": 150,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Industrial_Storage_Rack_1",
"X": -150,
"Y": 0.0,
"Z": 50,
"Length": 200,
"Width": 50,
"Height": 300,
"Material": "Steel_Carbon"
},
{
"object_name": "Empty_Pallet_3",
"X": -150,
"Y": 0.0,
"Z": -50,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Yellow_Forklift_1",
"X": 50,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Plastic_ABS"
},
{
"object_name": "Heavy_Duty_Forklift_2",
"X": 150,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Steel_Stainless"
}
]
}'''
| 4,898 | Python | 37.880952 | 435 | 0.612903 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/materials.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
MaterialPresets = {
"Leather_Brown":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Pumpkin_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Pumpkin.mdl',
"Leather_Brown_02":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Black_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Black.mdl',
"Aluminum_cast":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Aluminum_Cast.mdl',
"Birch":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Birch.mdl',
"Beadboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Beadboard.mdl',
"Cardboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl',
"Cloth_Black":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Black.mdl',
"Cloth_Gray":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Gray.mdl',
"Concrete_Polished":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl',
"Glazed_Glass":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Glass/Glazed_Glass.mdl',
"CorrugatedMetal":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/CorrugatedMetal.mdl',
"Cork":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Cork.mdl',
"Linen_Beige":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Beige.mdl',
"Linen_Blue":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Blue.mdl',
"Linen_White":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_White.mdl',
"Mahogany":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Mahogany.mdl',
"MDF":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/MDF.mdl',
"Oak":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Oak.mdl',
"Plastic_ABS":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Plastic_ABS.mdl',
"Steel_Carbon":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Carbon.mdl',
"Steel_Stainless":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Stainless.mdl',
"Veneer_OU_Walnut":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_OU_Walnut.mdl',
"Veneer_UX_Walnut_Cherry":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl',
"Veneer_Z5_Maple":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_Z5_Maple.mdl',
"Plywood":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Plywood.mdl',
"Concrete_Rough_Dirty":
'http://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/vMaterials_2/Concrete/Concrete_Rough.mdl'
} | 4,323 | Python | 58.232876 | 121 | 0.743234 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.kit.commands
from pxr import Gf, Sdf, UsdGeom
from .materials import *
import carb
def CreateCubeFromCurve(curve_path: str, area_name: str = ""):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
min_coords, max_coords = get_coords_from_bbox(curve_path)
x,y,z = get_bounding_box_dimensions(curve_path)
xForm_scale = Gf.Vec3d(x, 1, z)
cube_scale = Gf.Vec3d(0.01, 0.01, 0.01)
prim = stage.GetPrimAtPath(curve_path)
origin = prim.GetAttribute('xformOp:translate').Get()
if prim.GetTypeName() == "BasisCurves":
origin = Gf.Vec3d(min_coords[0]+x/2, 0, min_coords[2]+z/2)
area_path = '/World/Layout/Area'
if len(area_name) != 0:
area_path = '/World/Layout/' + area_name.replace(" ", "_")
new_area_path = omni.usd.get_stage_next_free_path(stage, area_path, False)
new_cube_xForm_path = new_area_path + "/" + "Floor"
new_cube_path = new_cube_xForm_path + "/" + "Cube"
# Create xForm to hold all items
item_container = create_prim(new_area_path)
set_transformTRS_attrs(item_container, translate=origin)
# Create Scale Xform for floor
xform = create_prim(new_cube_xForm_path)
set_transformTRS_attrs(xform, scale=xForm_scale)
# Create Floor Cube
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
prim_path=new_cube_path,
select_new_prim=True
)
cube = stage.GetPrimAtPath(new_cube_path)
set_transformTRS_attrs(cube, scale=cube_scale)
cube.CreateAttribute("primvar:area_name", Sdf.ValueTypeNames.String, custom=True).Set(area_name)
omni.kit.commands.execute('DeletePrims',
paths=[curve_path],
destructive=False)
apply_material_to_prim('Concrete_Rough_Dirty', new_area_path)
return new_area_path
def apply_material_to_prim(material_name: str, prim_path: str):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
looks_path = '/World/Looks/'
mat_path = looks_path + material_name
mat_prim = stage.GetPrimAtPath(mat_path)
if MaterialPresets.get(material_name, None) is not None:
if not mat_prim.IsValid():
omni.kit.commands.execute('CreateMdlMaterialPrimCommand',
mtl_url=MaterialPresets[material_name],
mtl_name=material_name,
mtl_path=mat_path)
omni.kit.commands.execute('BindMaterialCommand',
prim_path=prim_path,
material_path=mat_path)
def create_prim(prim_path, prim_type='Xform'):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.DefinePrim(prim_path)
if prim_type == 'Xform':
xform = UsdGeom.Xform.Define(stage, prim_path)
else:
xform = UsdGeom.Cube.Define(stage, prim_path)
create_transformOps_for_xform(xform)
return prim
def create_transformOps_for_xform(xform):
xform.AddTranslateOp()
xform.AddRotateXYZOp()
xform.AddScaleOp()
def set_transformTRS_attrs(prim, translate: Gf.Vec3d = Gf.Vec3d(0,0,0), rotate: Gf.Vec3d=Gf.Vec3d(0,0,0), scale: Gf.Vec3d=Gf.Vec3d(1,1,1)):
prim.GetAttribute('xformOp:translate').Set(translate)
prim.GetAttribute('xformOp:rotateXYZ').Set(rotate)
prim.GetAttribute('xformOp:scale').Set(scale)
def get_bounding_box_dimensions(prim_path: str):
min_coords, max_coords = get_coords_from_bbox(prim_path)
length = max_coords[0] - min_coords[0]
width = max_coords[1] - min_coords[1]
height = max_coords[2] - min_coords[2]
return length, width, height
def get_coords_from_bbox(prim_path: str):
ctx = omni.usd.get_context()
bbox = ctx.compute_path_world_bounding_box(prim_path)
min_coords, max_coords = bbox
return min_coords, max_coords
def scale_object_if_needed(prim_path):
stage = omni.usd.get_context().get_stage()
length, width, height = get_bounding_box_dimensions(prim_path)
largest_dimension = max(length, width, height)
if largest_dimension < 10:
prim = stage.GetPrimAtPath(prim_path)
# HACK: All Get Attribute Calls need to check if the attribute exists and add it if it doesn't
if prim.IsValid():
scale_attr = prim.GetAttribute('xformOp:scale')
if scale_attr.IsValid():
current_scale = scale_attr.Get()
new_scale = (current_scale[0] * 100, current_scale[1] * 100, current_scale[2] * 100)
scale_attr.Set(new_scale)
carb.log_info(f"Scaled object by 100 times: {prim_path}")
else:
carb.log_info(f"Scale attribute not found for prim at path: {prim_path}")
else:
carb.log_info(f"Invalid prim at path: {prim_path}")
else:
carb.log_info(f"No scaling needed for object: {prim_path}") | 5,463 | Python | 38.594203 | 139 | 0.663738 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#hotkey
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Sdf, Gf
from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs
def place_deepsearch_results(gpt_results, query_result, root_prim_path):
index = 0
for item in query_result:
item_name = item[0]
item_path = item[1]
# Define Prim
prim_parent_path = root_prim_path + item_name.replace(" ", "_")
prim_path = prim_parent_path + "/" + item_name.replace(" ", "_")
parent_prim = create_prim(prim_parent_path)
next_prim = create_prim(prim_path)
# Add reference to USD Asset
references: Usd.references = next_prim.GetReferences()
# TODO: The query results should returnt he full path of the prim
references.AddReference(
assetPath="omniverse://ov-simready" + item_path)
# Add reference for future search refinement
config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String)
config.Set(item_name)
# HACK: All "GetAttribute" calls should need to check if the attribute exists
# translate prim
next_object = gpt_results[index]
index = index + 1
x = next_object['X']
y = next_object['Y']
z = next_object['Z']
set_transformTRS_attrs(parent_prim, Gf.Vec3d(x,y,z), Gf.Vec3d(0,-90,-90), Gf.Vec3d(1.0,1.0,1.0))
scale_object_if_needed(prim_parent_path)
def place_greyboxes(gpt_results, root_prim_path):
index = 0
for item in gpt_results:
# Define Prim
prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_")
prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_")
# Define Dimensions and material
length = item['Length']/100
width = item['Width']/100
height = item['Height']/100
x = item['X']
y = item['Y']+height*100*.5 #shift bottom of object to y=0
z = item['Z']
material = item['Material']
# Create Prim
parent_prim = create_prim(prim_parent_path)
set_transformTRS_attrs(parent_prim)
prim = create_prim(prim_path, 'Cube')
set_transformTRS_attrs(prim, translate=Gf.Vec3d(x,y,z), scale=Gf.Vec3d(length, height, width))
prim.GetAttribute('extent').Set([(-50.0, -50.0, -50.0), (50.0, 50.0, 50.0)])
prim.GetAttribute('size').Set(100)
index = index + 1
# Add Attribute and Material
attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String)
attr.Set(item['object_name'])
apply_material_to_prim(material, prim_path)
| 3,365 | Python | 38.139534 | 104 | 0.63477 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
import asyncio
import omni.kit.commands
from omni.kit.window.popup_dialog.form_dialog import FormDialog
from .utils import CreateCubeFromCurve
from .style import gen_ai_style, guide
from .chatgpt_apiconnect import call_Generate
from .priminfo import PrimInfo
from pxr import Sdf
from .widgets import ProgressBar
class GenAIWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self._path_model = ui.SimpleStringModel()
self._prompt_model = ui.SimpleStringModel("generate warehouse objects")
self._area_name_model = ui.SimpleStringModel()
self._use_deepsearch = ui.SimpleBoolModel()
self._use_chatgpt = ui.SimpleBoolModel()
self._areas = []
self.response_log = None
self.current_index = -1
self.current_area = None
self._combo_changed_sub = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.ScrollingFrame():
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Label("Content Generatation with ChatGPT", style={"font_size": 18})
ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings())
with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True):
ui.Label(guide, word_wrap=True)
ui.Line()
with ui.HStack(height=0):
ui.Label("Area Name", width=ui.Percent(30))
ui.StringField(model=self._area_name_model)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._create_new_area(self.get_area_name()))
with ui.HStack(height=0):
ui.Label("Current Room", width=ui.Percent(30))
self._build_combo_box()
ui.Line()
with ui.HStack(height=ui.Percent(50)):
ui.Label("Prompt", width=0)
ui.StringField(model=self._prompt_model, multiline=True)
ui.Line()
self._build_ai_section()
def _save_settings(self, dialog):
values = dialog.get_values()
carb.log_info(values)
settings = carb.settings.get_settings()
settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"])
dialog.hide()
def _open_settings(self):
settings = carb.settings.get_settings()
apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter")
if apikey_value == "":
apikey_value = "Enter API Key Here"
if nucleus_path == "":
nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here"
if path_filter == "":
path_filter = ""
field_defs = [
FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value),
FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path),
FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter)
]
dialog = FormDialog(
title="Settings",
message="Your Settings: ",
field_defs = field_defs,
ok_handler=lambda dialog: self._save_settings(dialog))
dialog.show()
def _build_ai_section(self):
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Use ChatGPT: ")
ui.CheckBox(model=self._use_chatgpt)
ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY")
ui.CheckBox(model=self._use_deepsearch)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=ui.Percent(10))
ui.Button("Generate", height=40,
clicked_fn=lambda: self._generate())
ui.Spacer(width=ui.Percent(10))
self.progress = ProgressBar()
with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True):
self.response_log = ui.Label("", word_wrap=True)
def _build_combo_box(self):
self.combo_model = ui.ComboBox(self.current_index, *[str(x) for x in self._areas] ).model
def combo_changed(item_model, item):
index_value_model = item_model.get_item_value_model(item)
self.current_area = self._areas[index_value_model.as_int]
self.current_index = index_value_model.as_int
self.rebuild_frame()
self._combo_changed_sub = self.combo_model.subscribe_item_changed_fn(combo_changed)
def _create_new_area(self, area_name: str):
if area_name == "":
carb.log_warn("No area name provided")
return
new_area_name = CreateCubeFromCurve(self.get_prim_path(), area_name)
self._areas.append(new_area_name)
self.current_index = len(self._areas) - 1
index_value_model = self.combo_model.get_item_value_model()
index_value_model.set_value(self.current_index)
def rebuild_frame(self):
# we do want to update the area name and possibly last prompt?
area_name = self.current_area.split("/World/Layout/")
self._area_name_model.set_value(area_name[-1].replace("_", " "))
attr_prompt = self.get_prim().GetAttribute('genai:prompt')
if attr_prompt.IsValid():
self._prompt_model.set_value(attr_prompt.Get())
else:
self._prompt_model.set_value("")
self.frame.rebuild()
def _generate(self):
prim = self.get_prim()
attr = prim.GetAttribute('genai:prompt')
if not attr.IsValid():
attr = prim.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String)
attr.Set(self.get_prompt())
items_path = self.current_area + "/items"
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(items_path).IsValid():
omni.kit.commands.execute('DeletePrims',
paths=[items_path],
destructive=False)
# asyncio.ensure_future(self.progress.fill_bar(0,100))
run_loop = asyncio.get_event_loop()
run_loop.create_task(call_Generate(self.get_prim_info(),
self.get_prompt(),
self._use_chatgpt.as_bool,
self._use_deepsearch.as_bool,
self.response_log,
self.progress
))
# Returns a PrimInfo object containing the Length, Width, Origin and Area Name
def get_prim_info(self) -> PrimInfo:
prim = self.get_prim()
prim_info = None
if prim.IsValid():
prim_info = PrimInfo(prim, self.current_area)
return prim_info
# # Get the prim path specified
def get_prim_path(self):
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
return str(selection[0])
carb.log_warn("No Prim Selected")
return ""
# Get the area name specified
def get_area_name(self):
if self._area_name_model == "":
carb.log_warn("No Area Name Provided")
return self._area_name_model.as_string
# Get the prompt specified
def get_prompt(self):
if self._prompt_model == "":
carb.log_warn("No Prompt Provided")
return self._prompt_model.as_string
# Get the prim based on the Prim Path
def get_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.GetPrimAtPath(self.current_area)
if prim.IsValid() is None:
carb.log_warn("No valid prim in the scene")
return prim
def destroy(self):
super().destroy()
self._combo_changed_sub = None
self._path_model = None
self._prompt_model = None
self._area_name_model = None
self._use_deepsearch = None
self._use_chatgpt = None | 9,607 | Python | 41.892857 | 161 | 0.595503 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/docs/README.md | # AI Room Generator Sample Extension (omni.sample.airoomgenerator)

## Overview
The AI Room Generator Sample Extension allows users to generate 3D content to populate a room using Generative AI. The user will specify what area that defines the room and a prompt that will get passed to ChatGPT.
> NOTE: To enable the extension you will need to have ngsearch module. By default it is already avaliable in Omniverse USD Composer. If using Omniverse Code follow these [instructions](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/client/using_deepsearch_ui.html#using-deepsearch-beta-in-usd-composer) to get ngsearch
This Sample Extension utilizes Omniverse's [Deepsearch](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/overview.html) functionality to search for models within a nucleus server. (ENTERPRISE USERS ONLY)
## UI Overview

1. Settings (Cog Button)
- Where the user can input their API Key from [OpenAI](https://platform.openai.com/account/api-keys)
- Enterprise users can input their Deepsearch Enabled Nucleus Path
2. Area Name
- The name that will be applied to the Area once added.
3. Add Area (Plus Button)
- With an area selected and an Area Name provided, it will remove the selected object and spawn in a cube resembling the dimensions of the selected area prim.
4. Current Room
- By default this will be empty. As you add rooms this combo box will populate and allow you to switch between each generated room maintaining the prompt (if the room items have been generated). This allows users to adjust their prompt later for an already generated room.
5. Prompt
- The prompt that will be sent to ChatGPT.
- Here is an example prompt for a reception area:
- "This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa, and a coffee table"
6. Use ChatGPT
- This enables the extension to call ChatGPT, otherwise it will use a default assistant prompt which will be the same every time.
7. Use Deepsearch (ENTERPRISE USERS ONLY)
- This enables the extension to use Deepsearch
8. Generate
- With a room selected and a prompt, this will send all the related information to ChatGPT. A progress bar will show up indicating if the response is still going.
9. ChatGPT Reponse / Log
- Once you have hit *Generate* this collapsable frame will contain the output recieved from ChatGPT. Here you can view the JSON data or if any issues arise with ChatGPT.
## How it works
### Getting information about the 3D Scene
Everything starts with the USD scene in Omniverse. Users can easily circle an area using the Pencil tool in Omniverse or create a cube and scale it in the scene, type in the kind of room/environment they want to generate - for example, a warehouse, or a reception room - and with one click that area is created.

### Creating the Prompt for ChatGPT
The ChatGPT prompt is composed of four pieces; system input, user input example, assistant output example, and user prompt.
Let’s start with the aspects of the prompt that tailor to the user’s scenario. This includes text that the user inputs plus data from the scene.
For example, if the user wants to create a reception room, they specify something like “This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa and a coffee table”. Or, if they want to add a certain number of items they could add “make sure to include a minimum of 10 items”.
This text is combined with scene information like the size and name of the area where we will place items as the User Prompt.
### Passing the results from ChatGPT

The items from the ChatGPT JSON response are then parsed by the extension and passed to the Omnivere DeepSearch API. DeepSearch allows users to search 3D models stored within an Omniverse Nucleus server using natural language queries.
This means that even if we don’t know the exact file name of a model of a sofa, for example, we can retrieve it just by searching for “Comfortable Sofa” which is exactly what we got from ChatGPT.
DeepSearch understands natural language and by asking it for a “Comfortable Sofa” we get a list of items that our helpful AI librarian has decided are best suited from the selection of assets we have in our current asset library. It is surprisingly good at this and so we often can use the first item it returns, but of course we build in choice in case the user wants to select something from the list.
### When not using Deepsearch

For those who are not Enterprise users or users that want to use greyboxing, by default as long as `use Deepsearch` is turned off the extension will generate cube of various shapes and sizes to best suit the response from ChatGPT. | 4,975 | Markdown | 73.268656 | 404 | 0.776482 |
NVIDIA-Omniverse/AnariUsdDevice/UsdParameterizedObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <map>
#include <string>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <vector>
#include "UsdAnari.h"
#include "UsdSharedObjects.h"
#include "UsdMultiTypeParameter.h"
#include "helium/utility/IntrusivePtr.h"
#include "anari/frontend/type_utility.h"
class UsdDevice;
class UsdBridge;
// When deriving from UsdParameterizedObject<T>, define a a struct T::Data and
// a static void T::registerParams() that registers any member of T::Data using REGISTER_PARAMETER_MACRO()
template<typename T, typename D>
class UsdParameterizedObject
{
public:
struct UsdAnariDataTypeStore
{
ANARIDataType type0 = ANARI_UNKNOWN;
ANARIDataType type1 = ANARI_UNKNOWN;
ANARIDataType type2 = ANARI_UNKNOWN;
ANARIDataType singleType() const { return type0; }
bool isMultiType() const { return type1 != ANARI_UNKNOWN; }
bool typeMatches(ANARIDataType inType) const
{
return inType == type0 ||
(isMultiType() && (inType == type1 || inType == type2));
}
};
struct ParamTypeInfo
{
size_t dataOffset = 0; // offset of data, within paramDataSet D
size_t typeOffset = 0; // offset of type, from data
size_t size = 0; // Total size of data+type
UsdAnariDataTypeStore types;
};
using ParameterizedClassType = UsdParameterizedObject<T, D>;
using ParamContainer = std::map<std::string, ParamTypeInfo>;
void* getParam(const char* name, ANARIDataType& returnType)
{
// Check if name registered
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
returnType, destAddress);
return destAddress;
}
return nullptr;
}
protected:
helium::RefCounted** ptrToRefCountedPtr(void* address) { return reinterpret_cast<helium::RefCounted**>(address); }
ANARIDataType* toAnariDataTypePtr(void* address) { return reinterpret_cast<ANARIDataType*>(address); }
bool isRefCounted(ANARIDataType type) const { return anari::isObject(type) || type == ANARI_STRING; }
void safeRefInc(void* paramPtr) // Pointer to the parameter address which holds a helium::RefCounted*
{
helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr);
if (*refCountedPP)
(*refCountedPP)->refInc(helium::RefType::INTERNAL);
}
void safeRefDec(void* paramPtr, ANARIDataType paramType) // Pointer to the parameter address which holds a helium::RefCounted*
{
helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr);
if (*refCountedPP)
{
helium::RefCounted*& refCountedP = *refCountedPP;
#ifdef CHECK_MEMLEAKS
logDeallocationThroughDevice(allocDevice, refCountedP, paramType);
#endif
assert(refCountedP->useCount(helium::RefType::INTERNAL) > 0);
refCountedP->refDec(helium::RefType::INTERNAL);
refCountedP = nullptr; // Explicitly clear the pointer (see destructor)
}
}
void* paramAddress(D& paramData, const ParamTypeInfo& typeInfo)
{
return reinterpret_cast<char*>(¶mData) + typeInfo.dataOffset;
}
ANARIDataType paramType(void* paramAddress, const ParamTypeInfo& typeInfo)
{
if(typeInfo.types.isMultiType())
return *toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset);
else
return typeInfo.types.singleType();
}
void setMultiParamType(void* paramAddress, const ParamTypeInfo& typeInfo, ANARIDataType newType)
{
if(typeInfo.types.isMultiType())
*toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset) = newType;
}
void getParamTypeAndAddress(D& paramData, const ParamTypeInfo& typeInfo,
ANARIDataType& returnType, void*& returnAddress)
{
returnAddress = paramAddress(paramData, typeInfo);
returnType = paramType(returnAddress, typeInfo);
}
// Convenience function for usd-compatible parameters
void formatUsdName(UsdSharedString* nameStr)
{
char* name = const_cast<char*>(UsdSharedString::c_str(nameStr));
assert(strlen(name) > 0);
auto letter = [](unsigned c) { return ((c - 'A') < 26) || ((c - 'a') < 26); };
auto number = [](unsigned c) { return (c - '0') < 10; };
auto under = [](unsigned c) { return c == '_'; };
unsigned x = *name;
if (!letter(x) && !under(x)) { *name = '_'; }
x = *(++name);
while (x != '\0')
{
if(!letter(x) && !number(x) && !under(x))
*name = '_';
x = *(++name);
};
}
public:
UsdParameterizedObject()
{
static ParamContainer* reg = ParameterizedClassType::registerParams();
registeredParams = reg;
}
~UsdParameterizedObject()
{
// Manually decrease the references on all objects in the read and writeparam datasets
// (since the pointers are relinquished)
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
ANARIDataType readParamType, writeParamType;
void* readParamAddress = nullptr;
void* writeParamAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo,
readParamType, readParamAddress);
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
writeParamType, writeParamAddress);
// Works even if two parameters point to the same object, as the object pointers are set to null
if(isRefCounted(readParamType))
safeRefDec(readParamAddress, readParamType);
if(isRefCounted(writeParamType))
safeRefDec(writeParamAddress, writeParamType);
++it;
}
}
const D& getReadParams() const { return paramDataSets[paramReadIdx]; }
D& getWriteParams() { return paramDataSets[paramWriteIdx]; }
protected:
void setParam(const char* name, ANARIDataType srcType, const void* rawSrc, UsdDevice* device)
{
#ifdef CHECK_MEMLEAKS
allocDevice = device;
#endif
if(srcType == ANARI_UNKNOWN)
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"Attempting to set param %s with type %s", name, AnariTypeToString(srcType));
return;
}
else if(anari::isArray(srcType))
{
// Flatten the source type in case of array
srcType = ANARI_ARRAY;
}
// Check if name registered
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
// Check if type matches
if (typeInfo.types.typeMatches(srcType))
{
ANARIDataType destType;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
destType, destAddress);
const void* srcAddress = rawSrc; //temporary src
size_t numBytes = anari::sizeOf(srcType); // Size is determined purely by source data
bool contentUpdate = srcType != destType; // Always do a content update if types differ (in case of multitype params)
// Update data for all the different types
if (srcType == ANARI_BOOL)
{
bool* destBool_p = reinterpret_cast<bool*>(destAddress);
bool srcBool = *(reinterpret_cast<const uint32_t*>(srcAddress));
contentUpdate = contentUpdate || (*destBool_p != srcBool);
*destBool_p = srcBool;
}
else
{
UsdSharedString* sharedStr = nullptr;
if (srcType == ANARI_STRING)
{
// Wrap strings to make them refcounted,
// from that point they are considered normal RefCounteds.
UsdSharedString* destStr = reinterpret_cast<UsdSharedString*>(*ptrToRefCountedPtr(destAddress));
const char* srcCstr = reinterpret_cast<const char*>(srcAddress);
contentUpdate = contentUpdate || !destStr || !strEquals(destStr->c_str(), srcCstr); // Note that execution of strEquals => (srcType == destType)
if(contentUpdate)
{
sharedStr = new UsdSharedString(srcCstr); // Remember to refdec
numBytes = sizeof(void*);
srcAddress = &sharedStr;
#ifdef CHECK_MEMLEAKS
logAllocationThroughDevice(allocDevice, sharedStr, ANARI_STRING);
#endif
}
}
else
contentUpdate = contentUpdate || bool(std::memcmp(destAddress, srcAddress, numBytes));
if(contentUpdate)
{
if(isRefCounted(destType))
safeRefDec(destAddress, destType);
std::memcpy(destAddress, srcAddress, numBytes);
if(isRefCounted(srcType))
safeRefInc(destAddress);
}
// If a string object has been created, decrease its public refcount (1 at creation)
if (sharedStr)
{
assert(sharedStr->useCount() == 2); // Single public and internal reference
sharedStr->refDec();
}
}
// Update the type for multitype params (so far only data has been updated)
if(contentUpdate)
setMultiParamType(destAddress, typeInfo, srcType);
if(!strEquals(name, "usd::time")) // Allow for re-use of object as reference at different timestep, without triggering a full re-commit of the referenced object
{
#ifdef TIME_BASED_CACHING
paramChanged = true; //For time-varying parameters, comparisons between content of potentially different timesteps is meaningless
#else
paramChanged = paramChanged || contentUpdate;
#endif
}
}
else
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"Param %s is not of an accepted type. For example, use %s instead.", name, AnariTypeToString(typeInfo.types.type0));
}
}
void resetParam(const ParamTypeInfo& typeInfo)
{
size_t paramSize = typeInfo.size;
// Copy to existing write param location
ANARIDataType destType;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
destType, destAddress);
// Create temporary default-constructed parameter set and find source param address ((multi-)type is of no concern)
D defaultParamData;
void* srcAddress = paramAddress(defaultParamData, typeInfo);
// Make sure to dec existing ptr, as it will be relinquished
if(isRefCounted(destType))
safeRefDec(destAddress, destType);
// Just replace contents of the whole parameter structure, single or multiparam
std::memcpy(destAddress, srcAddress, paramSize);
}
void resetParam(const char* name)
{
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
resetParam(typeInfo);
if(!strEquals(name, "usd::time"))
{
paramChanged = true;
}
}
}
void resetParams()
{
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
resetParam(it->second);
++it;
}
paramChanged = true;
}
void transferWriteToReadParams()
{
// Make sure object references are removed for
// the overwritten readparams, and increased for the source writeparams
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
ANARIDataType srcType, destType;
void* srcAddress = nullptr;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
srcType, srcAddress);
getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo,
destType, destAddress);
// SrcAddress and destAddress are not the same, but they may specifically contain the same object pointers.
// Branch out on that situation (may also be disabled, which results in a superfluous inc/dec)
if(std::memcmp(destAddress, srcAddress, typeInfo.size))
{
// First inc, then dec (in case branch is taken out and the pointed to object is the same)
if (isRefCounted(srcType))
safeRefInc(srcAddress);
if (isRefCounted(destType))
safeRefDec(destAddress, destType);
// Perform assignment immediately; there may be multiple parameters with the same object target,
// which will be branched out at the compare the second time around
std::memcpy(destAddress, srcAddress, typeInfo.size);
}
++it;
}
}
static ParamContainer* registerParams();
ParamContainer* registeredParams;
typedef T DerivedClassType;
typedef D DataType;
D paramDataSets[2];
constexpr static unsigned int paramReadIdx = 0;
constexpr static unsigned int paramWriteIdx = 1;
bool paramChanged = false;
#ifdef CHECK_MEMLEAKS
UsdDevice* allocDevice = nullptr;
#endif
};
#define DEFINE_PARAMETER_MAP(DefClass, Params) template<> UsdParameterizedObject<DefClass,DefClass::DataType>::ParamContainer* UsdParameterizedObject<DefClass,DefClass::DataType>::registerParams() { static ParamContainer registeredParams; Params return ®isteredParams; }
#define REGISTER_PARAMETER_MACRO(ParamName, ParamType, ParamData) \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
std::string(ParamName), \
{offsetof(DataType, ParamData), 0, sizeof(DataType::ParamData), {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \
)); \
static_assert(ParamType == anari::ANARITypeFor<decltype(DataType::ParamData)>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type");
#define REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, ParamType1, ParamType2, ParamData) \
{ \
static_assert(ParamType0 == decltype(DataType::ParamData)::AnariType0, "MultiTypeParams registration: ParamType0 " #ParamType0 " of member '" #ParamData "' doesn't match AnariType0"); \
static_assert(ParamType1 == decltype(DataType::ParamData)::AnariType1, "MultiTypeParams registration: ParamType1 " #ParamType1 " of member '" #ParamData "' doesn't match AnariType1"); \
static_assert(ParamType2 == decltype(DataType::ParamData)::AnariType2, "MultiTypeParams registration: ParamType2 " #ParamType2 " of member '" #ParamData "' doesn't match AnariType2"); \
size_t dataOffset = offsetof(DataType, ParamData); \
size_t typeOffset = offsetof(DataType, ParamData.type); \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
std::string(ParamName), \
{dataOffset, typeOffset - dataOffset, sizeof(DataType::ParamData), {ParamType0, ParamType1, ParamType2}} \
)); \
}
// Static assert explainer: gets the element type of the array via the decltype of *std::begin(), which in turn accepts an array
#define REGISTER_PARAMETER_ARRAY_MACRO(ParamName, ParamNameSuffix, ParamType, ParamData, NumEntries) \
{ \
using element_type_t = std::remove_reference_t<decltype(*std::begin(std::declval<decltype(DataType::ParamData)&>()))>; \
static_assert(ParamType == anari::ANARITypeFor<element_type_t>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type"); \
static_assert(sizeof(decltype(DataType::ParamData)) == sizeof(element_type_t)*NumEntries, "Number of elements of member '" #ParamData "' does not correspond with member declaration."); \
size_t offset0 = offsetof(DataType, ParamData[0]); \
size_t offset1 = offsetof(DataType, ParamData[1]); \
size_t paramSize = offset1-offset0; \
for(int i = 0; i < NumEntries; ++i) \
{ \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
ParamName + std::to_string(i) + ParamNameSuffix, \
{offset0+paramSize*i, 0, paramSize, {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \
)); \
} \
}
| 16,145 | C | 35.947368 | 273 | 0.679282 |
NVIDIA-Omniverse/AnariUsdDevice/UsdRenderer.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
struct UsdRendererData
{
};
class UsdRenderer : public UsdParameterizedBaseObject<UsdRenderer, UsdRendererData>
{
public:
UsdRenderer();
~UsdRenderer();
void remove(UsdDevice* device) override {}
int getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
UsdBridge* usdBridge;
};
| 681 | C | 20.999999 | 114 | 0.737151 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <memory>
#include <limits>
class UsdDataArray;
struct UsdBridgeMeshData;
static constexpr int MAX_ATTRIBS = 16;
enum class UsdGeometryComponents
{
POSITION = 0,
NORMAL,
COLOR,
INDEX,
SCALE,
ORIENTATION,
ID,
ATTRIBUTE0,
ATTRIBUTE1,
ATTRIBUTE2,
ATTRIBUTE3
};
struct UsdGeometryData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0xFFFFFFFF; // TimeVarying bits
const UsdDataArray* vertexPositions = nullptr;
const UsdDataArray* vertexNormals = nullptr;
const UsdDataArray* vertexColors = nullptr;
const UsdDataArray* vertexAttributes[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* primitiveNormals = nullptr;
const UsdDataArray* primitiveColors = nullptr;
const UsdDataArray* primitiveAttributes[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* primitiveIds = nullptr;
const UsdSharedString* attributeNames[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* indices = nullptr;
// Spheres
const UsdDataArray* vertexRadii = nullptr;
float radiusConstant = 1.0f;
bool UseUsdGeomPoints =
#ifdef USE_USD_GEOM_POINTS
true;
#else
false;
#endif
// Cylinders
const UsdDataArray* primitiveRadii = nullptr;
// Curves
// Glyphs
const UsdDataArray* vertexScales = nullptr;
const UsdDataArray* primitiveScales = nullptr;
const UsdDataArray* vertexOrientations = nullptr;
const UsdDataArray* primitiveOrientations = nullptr;
UsdFloat3 scaleConstant = {1.0f, 1.0f, 1.0f};
UsdQuaternion orientationConstant;
UsdSharedString* shapeType = nullptr;
UsdGeometry* shapeGeometry = nullptr;
UsdFloatMat4 shapeTransform;
double shapeGeometryRefTimeStep = std::numeric_limits<float>::quiet_NaN();
};
struct UsdGeometryTempArrays;
class UsdGeometry : public UsdBridgedBaseObject<UsdGeometry, UsdGeometryData, UsdGeometryHandle, UsdGeometryComponents>
{
public:
enum GeomType
{
GEOM_UNKNOWN = 0,
GEOM_TRIANGLE,
GEOM_QUAD,
GEOM_SPHERE,
GEOM_CYLINDER,
GEOM_CONE,
GEOM_CURVE,
GEOM_GLYPH
};
typedef std::vector<UsdBridgeAttribute> AttributeArray;
typedef std::vector<std::vector<char>> AttributeDataArraysType;
UsdGeometry(const char* name, const char* type, UsdDevice* device);
~UsdGeometry();
void remove(UsdDevice* device) override;
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
bool isInstanced() const
{
return geomType == GEOM_SPHERE
|| geomType == GEOM_CONE
|| geomType == GEOM_CYLINDER
|| geomType == GEOM_GLYPH;
}
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdGeometryComponents::POSITION, "position"),
ComponentPair(UsdGeometryComponents::NORMAL, "normal"),
ComponentPair(UsdGeometryComponents::COLOR, "color"),
ComponentPair(UsdGeometryComponents::INDEX, "index"),
ComponentPair(UsdGeometryComponents::SCALE, "scale"),
ComponentPair(UsdGeometryComponents::SCALE, "radius"),
ComponentPair(UsdGeometryComponents::ORIENTATION, "orientation"),
ComponentPair(UsdGeometryComponents::ID, "id"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE0, "attribute0"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE1, "attribute1"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE2, "attribute2"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE3, "attribute3")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
void initializeGeomData(UsdBridgeMeshData& geomData);
void initializeGeomData(UsdBridgeInstancerData& geomData);
void initializeGeomData(UsdBridgeCurveData& geomData);
void initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData);
bool checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray,
const char* paramName, UsdDevice* device, const char* debugName, int attribIndex = -1);
bool checkGeomParams(UsdDevice* device);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew);
template<typename UsdGeomType>
bool commitTemplate(UsdDevice* device);
void commitPrototypes(UsdBridge* usdBridge);
template<typename GeomDataType>
void setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying);
void syncAttributeArrays();
template<typename GeomDataType>
void copyAttributeArraysToData(GeomDataType& geomData);
void assignTempDataToAttributes(bool perPrimInterpolation);
GeomType geomType = GEOM_UNKNOWN;
bool protoShapeChanged = false; // Do not automatically commit shapes (the object may have been recreated onto an already existing USD prim)
std::unique_ptr<UsdGeometryTempArrays> tempArrays;
AttributeArray attributeArray;
}; | 5,365 | C | 29.83908 | 144 | 0.741473 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include "UsdBridgeNumerics.h"
#include "UsdDeviceUtils.h"
#include <limits>
class UsdSampler;
template<typename ValueType>
using UsdMaterialMultiTypeParameter = UsdMultiTypeParameter<ValueType, UsdSampler*, UsdSharedString*>;
enum class UsdMaterialDataComponents
{
COLOR = 0,
OPACITY,
EMISSIVE,
EMISSIVEFACTOR,
ROUGHNESS,
METALLIC,
IOR
};
struct UsdMaterialData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = std::numeric_limits<float>::quiet_NaN();
int timeVarying = 0; // Bitmask indicating which attributes are time-varying.
// Standard parameters
UsdMaterialMultiTypeParameter<UsdFloat3> color = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3};
UsdMaterialMultiTypeParameter<float> opacity = {1.0f, ANARI_FLOAT32};
UsdSharedString* alphaMode = nullptr; // Timevarying state linked to opacity
float alphaCutoff = 0.5f; // Timevarying state linked to opacity
// Possible PBR parameters
UsdMaterialMultiTypeParameter<UsdFloat3> emissiveColor = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3};
UsdMaterialMultiTypeParameter<float> emissiveIntensity = {0.0f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> roughness = {0.5f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> metallic = {0.0f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> ior = {1.0f, ANARI_FLOAT32};
double colorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double opacitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double emissiveSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double emissiveIntensitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double roughnessSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double metallicSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double iorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
};
class UsdMaterial : public UsdBridgedBaseObject<UsdMaterial, UsdMaterialData, UsdMaterialHandle, UsdMaterialDataComponents>
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
UsdMaterial(const char* name, const char* type, UsdDevice* device);
~UsdMaterial();
void remove(UsdDevice* device) override;
bool isPerInstance() const { return perInstance; }
void updateBoundParameters(bool boundToInstance, UsdDevice* device);
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdMaterialDataComponents::COLOR, "color"),
ComponentPair(UsdMaterialDataComponents::COLOR, "baseColor"),
ComponentPair(UsdMaterialDataComponents::OPACITY, "opacity"),
ComponentPair(UsdMaterialDataComponents::EMISSIVE, "emissive"),
ComponentPair(UsdMaterialDataComponents::EMISSIVEFACTOR, "emissiveIntensity"),
ComponentPair(UsdMaterialDataComponents::ROUGHNESS, "roughness"),
ComponentPair(UsdMaterialDataComponents::METALLIC, "metallic"),
ComponentPair(UsdMaterialDataComponents::IOR, "ior")};
protected:
using MaterialInputAttribNamePair = std::pair<MaterialDMI, const char*>;
template<typename ValueType>
bool getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param,
MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo);
template<typename ValueType>
bool getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep,
MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo);
template<typename ValueType>
void assignParameterToMaterialInput(
const UsdMaterialMultiTypeParameter<ValueType>& param,
UsdBridgeMaterialData::MaterialInput<ValueType>& matInput,
const UsdLogInfo& logInfo);
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
void setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying);
bool isPbr = false;
bool perInstance = false; // Whether material is attached to a point instancer
bool instanceAttributeAttached = false; // Whether a value to any parameter has been set which in USD is different between per-instance and regular geometries
OptionalList<MaterialInputAttribNamePair> materialInputAttributes;
OptionalList<UsdSamplerHandle> samplerHandles;
OptionalList<UsdSamplerRefData> samplerRefDatas;
}; | 4,548 | C | 39.981982 | 162 | 0.769789 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdMaterial.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdSampler.h"
#include "UsdDataArray.h"
#define SamplerType ANARI_SAMPLER
using SamplerUsdType = AnariToUsdBridgedObject<SamplerType>::Type;
#define REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO(ParamName, ParamType0, ParamData) \
REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, SamplerType, ANARI_STRING, ParamData)
DEFINE_PARAMETER_MAP(UsdMaterial,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::time.sampler.color", ANARI_FLOAT64, colorSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.baseColor", ANARI_FLOAT64, colorSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.opacity", ANARI_FLOAT64, opacitySamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.emissive", ANARI_FLOAT64, emissiveSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.emissiveIntensity", ANARI_FLOAT64, emissiveIntensitySamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.roughness", ANARI_FLOAT64, roughnessSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.metallic", ANARI_FLOAT64, metallicSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.ior", ANARI_FLOAT64, iorSamplerTimeStep)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("color", ANARI_FLOAT32_VEC3, color)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("baseColor", ANARI_FLOAT32_VEC3, color)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("opacity", ANARI_FLOAT32, opacity)
REGISTER_PARAMETER_MACRO("alphaMode", ANARI_STRING, alphaMode)
REGISTER_PARAMETER_MACRO("alphaCutoff", ANARI_FLOAT32, alphaCutoff)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissive", ANARI_FLOAT32_VEC3, emissiveColor)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissiveIntensity", ANARI_FLOAT32, emissiveIntensity)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("roughness", ANARI_FLOAT32, roughness)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("metallic", ANARI_FLOAT32, metallic)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("ior", ANARI_FLOAT32, ior)
)
constexpr UsdMaterial::ComponentPair UsdMaterial::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
using DMI = UsdMaterial::MaterialDMI;
UsdMaterial::UsdMaterial(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_MATERIAL, name, device)
{
if (strEquals(type, "matte"))
{
isPbr = false;
}
else if (strEquals(type, "physicallyBased"))
{
isPbr = true;
}
else
{
device->reportStatus(this, ANARI_MATERIAL, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdMaterial '%s' intialization error: unknown material type", getName());
}
}
UsdMaterial::~UsdMaterial()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteMaterial(usdHandle);
#endif
}
void UsdMaterial::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteMaterial);
}
template<typename ValueType>
bool UsdMaterial::getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo)
{
bool hasPositionAttrib = false;
UsdSharedString* anariAttribStr = nullptr;
param.Get(anariAttribStr);
const char* anariAttrib = UsdSharedString::c_str(anariAttribStr);
if(anariAttrib)
{
hasPositionAttrib = strEquals(anariAttrib, "objectPosition");
if( hasPositionAttrib && instanceAttributeAttached)
{
// In case of a per-instance specific attribute name, there can be only one change of the attribute name.
// Otherwise there is a risk of the material attribute being used for two differently named attributes.
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdMaterial '%s' binds one of its parameters to %s, but is transitively bound to both an instanced geometry (cones, spheres, cylinders) and regular geometry. \
This is incompatible with USD, which demands a differently bound name for those categories. \
Please create two different samplers and bind each to only one of both categories of geometry. \
The parameter value will be updated, but may therefore invalidate previous bindings to the objectPosition attribute.", logInfo.sourceName, "'objectPosition'");
}
const char* usdAttribName = AnariAttributeToUsdName(anariAttrib, perInstance, logInfo);
materialInputAttributes.push_back(UsdBridge::MaterialInputAttribName(dataMemberId, usdAttribName));
}
return hasPositionAttrib;
}
template<typename ValueType>
bool UsdMaterial::getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo)
{
UsdSampler* sampler = nullptr;
param.Get(sampler);
if(sampler)
{
const UsdSamplerData& samplerParamData = sampler->getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
double samplerObjTimeStep = samplerParamData.timeStep;
double samplerRefTime = selectRefTime(refTimeStep, samplerObjTimeStep, worldTimeStep);
// Reading child (sampler) data in the material has the consequence that the sampler's parameters as they were last committed are in effect "part of" the material parameter set, at this point of commit.
// So in case a sampler at a particular timestep is referenced from a material at two different world timesteps
// - ie. for this world timestep, a particular timestep of an image already committed and subsequently referenced at some other previous world timestep is reused -
// the user needs to make sure that not only the timestep is set correctly on the sampler for the commit (which is by itself lightweight, as it does not trigger a full commit),
// but also that the parameters read here have been re-set on the sampler to the values belonging to the referenced timestep, as if there is no USD representation of a sampler object.
// Setting those parameters will in turn trigger a full commit of the sampler object, which is in theory inefficient.
// However, in case of a sampler this is not a problem in practice; data transfer is only a concern when the filename is *not* set, at which point a relative file corresponding
// to the sampler timestep will be automatically chosen and set for the material, without the sampler object requiring any updates.
// In case a filename *is* set, only the filename is used and no data transfer/file io operations are performed.
//const char* imageUrl = UsdSharedString::c_str(samplerParamData.imageUrl); // not required anymore since all materials are a graph
int imageNumComponents = 4;
if(samplerParamData.imageData)
{
imageNumComponents = static_cast<int>(anari::componentsOf(samplerParamData.imageData->getType()));
}
UsdSamplerRefData samplerRefData = {imageNumComponents, samplerRefTime, dataMemberId};
samplerHandles.push_back(sampler->getUsdHandle());
samplerRefDatas.push_back(samplerRefData);
}
return false;
}
template<typename ValueType>
void UsdMaterial::assignParameterToMaterialInput(const UsdMaterialMultiTypeParameter<ValueType>& param,
UsdBridgeMaterialData::MaterialInput<ValueType>& matInput, const UsdLogInfo& logInfo)
{
param.Get(matInput.Value);
UsdSharedString* anariAttribStr = nullptr;
matInput.SrcAttrib = param.Get(anariAttribStr) ?
AnariAttributeToUsdName(anariAttribStr->c_str(), perInstance, logInfo) :
nullptr;
UsdSampler* sampler = nullptr;
matInput.Sampler = param.Get(sampler);
}
void UsdMaterial::updateBoundParameters(bool boundToInstance, UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdMaterialData& paramData = getReadParams();
if(perInstance != boundToInstance)
{
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
// Fix up any parameters that have a geometry-type-dependent name set as source attribute
materialInputAttributes.clear();
bool hasPositionAttrib =
getMaterialInputSourceName(paramData.color, DMI::DIFFUSE, device, logInfo) ||
getMaterialInputSourceName(paramData.opacity, DMI::OPACITY, device, logInfo) ||
getMaterialInputSourceName(paramData.emissiveColor, DMI::EMISSIVECOLOR, device, logInfo) ||
getMaterialInputSourceName(paramData.emissiveIntensity, DMI::EMISSIVEINTENSITY, device, logInfo) ||
getMaterialInputSourceName(paramData.roughness, DMI::ROUGHNESS, device, logInfo) ||
getMaterialInputSourceName(paramData.metallic, DMI::METALLIC, device, logInfo) ||
getMaterialInputSourceName(paramData.ior, DMI::IOR, device, logInfo);
DMI timeVarying;
setMaterialTimeVarying(timeVarying);
// Fixup attribute name and type depending on the newly bound geometry
if(materialInputAttributes.size())
usdBridge->ChangeMaterialInputAttributes(usdHandle, materialInputAttributes.data(), materialInputAttributes.size(), dataTimeStep, timeVarying);
if(hasPositionAttrib)
instanceAttributeAttached = true; // As soon as any parameter is set to a position attribute, the geometry type for this material is 'locked-in'
perInstance = boundToInstance;
}
if(paramData.color.type == SamplerType)
{
UsdSampler* colorSampler = nullptr;
if (paramData.color.Get(colorSampler))
{
colorSampler->updateBoundParameters(boundToInstance, device);
}
}
}
bool UsdMaterial::deferCommit(UsdDevice* device)
{
//const UsdMaterialData& paramData = getReadParams();
//if(UsdObjectNotInitialized<SamplerUsdType>(paramData.color.type == SamplerType))
//{
// return true;
//}
return false;
}
bool UsdMaterial::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!device->getReadParams().outputMaterial)
return false;
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateMaterial(getName(), usdHandle);
if (paramChanged || isNew)
{
const UsdMaterialData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
UsdBridgeMaterialData matData;
matData.IsPbr = isPbr;
matData.AlphaMode = AnariToUsdAlphaMode(UsdSharedString::c_str(paramData.alphaMode));
matData.AlphaCutoff = paramData.alphaCutoff;
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
assignParameterToMaterialInput(paramData.color, matData.Diffuse, logInfo);
assignParameterToMaterialInput(paramData.opacity, matData.Opacity, logInfo);
assignParameterToMaterialInput(paramData.emissiveColor, matData.Emissive, logInfo);
assignParameterToMaterialInput(paramData.emissiveIntensity, matData.EmissiveIntensity, logInfo);
assignParameterToMaterialInput(paramData.roughness, matData.Roughness, logInfo);
assignParameterToMaterialInput(paramData.metallic, matData.Metallic, logInfo);
assignParameterToMaterialInput(paramData.ior, matData.Ior, logInfo);
setMaterialTimeVarying(matData.TimeVarying);
usdBridge->SetMaterialData(usdHandle, matData, dataTimeStep);
paramChanged = false;
return paramData.color.type == SamplerType; // Only commit refs when material actually contains a texture (filename param from diffusemap is required)
}
return false;
}
void UsdMaterial::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdMaterialData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
samplerHandles.clear();
samplerRefDatas.clear();
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
getSamplerRefData(paramData.color, paramData.colorSamplerTimeStep, DMI::DIFFUSE, device, logInfo);
getSamplerRefData(paramData.opacity, paramData.opacitySamplerTimeStep, DMI::OPACITY, device, logInfo);
getSamplerRefData(paramData.emissiveColor, paramData.emissiveSamplerTimeStep, DMI::EMISSIVECOLOR, device, logInfo);
getSamplerRefData(paramData.emissiveIntensity, paramData.emissiveIntensitySamplerTimeStep, DMI::EMISSIVEINTENSITY, device, logInfo);
getSamplerRefData(paramData.roughness, paramData.roughnessSamplerTimeStep, DMI::ROUGHNESS, device, logInfo);
getSamplerRefData(paramData.metallic, paramData.metallicSamplerTimeStep, DMI::METALLIC, device, logInfo);
getSamplerRefData(paramData.ior, paramData.iorSamplerTimeStep, DMI::IOR, device, logInfo);
if(samplerHandles.size())
usdBridge->SetSamplerRefs(usdHandle, samplerHandles.data(), samplerHandles.size(), worldTimeStep, samplerRefDatas.data());
else
usdBridge->DeleteSamplerRefs(usdHandle, worldTimeStep);
}
void UsdMaterial::setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying)
{
timeVarying = DMI::ALL
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::DIFFUSE)
& (isTimeVarying(CType::OPACITY) ? DMI::ALL : ~DMI::OPACITY)
& (isTimeVarying(CType::EMISSIVE) ? DMI::ALL : ~DMI::EMISSIVECOLOR)
& (isTimeVarying(CType::EMISSIVEFACTOR) ? DMI::ALL : ~DMI::EMISSIVEINTENSITY)
& (isTimeVarying(CType::ROUGHNESS) ? DMI::ALL : ~DMI::ROUGHNESS)
& (isTimeVarying(CType::METALLIC) ? DMI::ALL : ~DMI::METALLIC)
& (isTimeVarying(CType::IOR) ? DMI::ALL : ~DMI::IOR);
} | 13,810 | C++ | 45.190635 | 207 | 0.767343 |
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdDataArray;
enum class UsdWorldComponents
{
INSTANCES = 0,
SURFACES,
VOLUMES
};
struct UsdWorldData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdDataArray* instances = nullptr;
UsdDataArray* surfaces = nullptr;
UsdDataArray* volumes = nullptr;
};
class UsdWorld : public UsdBridgedBaseObject<UsdWorld, UsdWorldData, UsdWorldHandle, UsdWorldComponents>
{
public:
UsdWorld(const char* name, UsdDevice* device);
~UsdWorld();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdWorldComponents::INSTANCES, "instance"),
ComponentPair(UsdWorldComponents::SURFACES, "surface"),
ComponentPair(UsdWorldComponents::VOLUMES, "volume")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
std::vector<UsdInstanceHandle> instanceHandles; // for convenience
std::vector<UsdSurfaceHandle> surfaceHandles; // for convenience
std::vector<UsdVolumeHandle> volumeHandles; // for convenience
}; | 1,375 | C | 26.519999 | 104 | 0.749818 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLight.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
struct UsdLightData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
};
class UsdLight : public UsdBridgedBaseObject<UsdLight, UsdLightData, UsdLightHandle>
{
public:
UsdLight(const char* name,
UsdDevice* device);
~UsdLight();
void remove(UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
};
| 612 | C | 20.892856 | 84 | 0.73366 |
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdFrame.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "anari/frontend/type_utility.h"
DEFINE_PARAMETER_MAP(UsdFrame,
REGISTER_PARAMETER_MACRO("world", ANARI_WORLD, world)
REGISTER_PARAMETER_MACRO("renderer", ANARI_RENDERER, renderer)
REGISTER_PARAMETER_MACRO("size", ANARI_UINT32_VEC2, size)
REGISTER_PARAMETER_MACRO("channel.color", ANARI_DATA_TYPE, color)
REGISTER_PARAMETER_MACRO("channel.depth", ANARI_DATA_TYPE, depth)
)
UsdFrame::UsdFrame(UsdBridge* bridge)
: UsdParameterizedBaseObject<UsdFrame, UsdFrameData>(ANARI_FRAME)
{
}
UsdFrame::~UsdFrame()
{
delete[] mappedColorMem;
delete[] mappedDepthMem;
}
bool UsdFrame::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdFrame::doCommitData(UsdDevice* device)
{
return false;
}
const void* UsdFrame::mapBuffer(const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType)
{
const UsdFrameData& paramData = getReadParams();
*width = paramData.size.Data[0];
*height = paramData.size.Data[1];
*pixelType = ANARI_UNKNOWN;
if (strEquals(channel, "channel.color"))
{
mappedColorMem = ReserveBuffer(paramData.color);
*pixelType = paramData.color;
return mappedColorMem;
}
else if (strEquals(channel, "channel.depth"))
{
mappedDepthMem = ReserveBuffer(paramData.depth);
*pixelType = paramData.depth;
return mappedDepthMem;
}
*width = 0;
*height = 0;
return nullptr;
}
void UsdFrame::unmapBuffer(const char *channel)
{
if (strEquals(channel, "channel.color"))
{
delete[] mappedColorMem;
mappedColorMem = nullptr;
}
else if (strEquals(channel, "channel.depth"))
{
delete[] mappedDepthMem;
mappedDepthMem = nullptr;
}
}
char* UsdFrame::ReserveBuffer(ANARIDataType format)
{
const UsdFrameData& paramData = getReadParams();
size_t formatSize = anari::sizeOf(format);
size_t memSize = formatSize * paramData.size.Data[0] * paramData.size.Data[1];
return new char[memSize];
}
void UsdFrame::saveUsd(UsdDevice* device)
{
device->getUsdBridge()->SaveScene();
}
| 2,184 | C++ | 22 | 80 | 0.717491 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSampler.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
enum class UsdSamplerComponents
{
DATA = 0,
WRAPS,
WRAPT,
WRAPR
};
struct UsdSamplerData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0; // Bitmask indicating which attributes are time-varying.
const UsdDataArray* imageData = nullptr;
UsdSharedString* inAttribute = nullptr;
UsdSharedString* imageUrl = nullptr;
UsdSharedString* wrapS = nullptr;
UsdSharedString* wrapT = nullptr;
UsdSharedString* wrapR = nullptr;
};
class UsdSampler : public UsdBridgedBaseObject<UsdSampler, UsdSamplerData, UsdSamplerHandle, UsdSamplerComponents>
{
protected:
enum SamplerType
{
SAMPLER_UNKNOWN = 0,
SAMPLER_1D,
SAMPLER_2D,
SAMPLER_3D
};
public:
UsdSampler(const char* name, const char* type, UsdDevice* device);
~UsdSampler();
void remove(UsdDevice* device) override;
bool isPerInstance() const { return perInstance; }
void updateBoundParameters(bool boundToInstance, UsdDevice* device);
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(CType::DATA, "image"),
ComponentPair(CType::DATA, "imageUrl"),
ComponentPair(CType::WRAPS, "wrapMode"),
ComponentPair(CType::WRAPS, "wrapMode1"),
ComponentPair(CType::WRAPT, "wrapMode2"),
ComponentPair(CType::WRAPR, "wrapMode3")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void setSamplerTimeVarying(UsdBridgeSamplerData::DataMemberId& timeVarying);
SamplerType samplerType = SAMPLER_UNKNOWN;
bool perInstance = false; // Whether sampler is attached to a point instancer
bool instanceAttributeAttached = false; // Whether a value to inAttribute has been set which in USD is different between per-instance and regular geometries
}; | 2,050 | C | 27.486111 | 160 | 0.725854 |
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdGroup;
enum class UsdInstanceComponents
{
GROUP = 0,
TRANSFORM
};
struct UsdInstanceData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdGroup* group = nullptr;
UsdFloatMat4 transform;
};
class UsdInstance : public UsdBridgedBaseObject<UsdInstance, UsdInstanceData, UsdInstanceHandle, UsdInstanceComponents>
{
public:
UsdInstance(const char* name,
UsdDevice* device);
~UsdInstance();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdInstanceComponents::GROUP, "group"),
ComponentPair(UsdInstanceComponents::TRANSFORM, "transform")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
}; | 1,070 | C | 23.906976 | 119 | 0.750467 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
#include "anari/frontend/anari_enums.h"
class UsdDevice;
struct UsdDataLayout
{
bool isDense() const { return byteStride1 == typeSize && byteStride2 == numItems1*byteStride1 && byteStride3 == numItems2*byteStride2; }
bool isOneDimensional() const { return numItems2 == 1 && numItems3 == 1; }
void copyDims(uint64_t dims[3]) const { std::memcpy(dims, &numItems1, sizeof(uint64_t)*3); }
void copyStride(int64_t stride[3]) const { std::memcpy(stride, &byteStride1, sizeof(int64_t)*3); }
uint64_t typeSize = 0;
uint64_t numItems1 = 0;
uint64_t numItems2 = 0;
uint64_t numItems3 = 0;
int64_t byteStride1 = 0;
int64_t byteStride2 = 0;
int64_t byteStride3 = 0;
};
struct UsdDataArrayParams
{
// Even though we are not dealing with a usd-backed object, the data array can still have an identifying name.
// The pointer can then be used as id for resources (plus defining their filenames) such as textures,
// so they can be shared and still removed during garbage collection (after an UsdAnari object has already been destroyed).
// The persistence reason is why these strings have to be added to the string list of the device on construction.
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
};
class UsdDataArray : public UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>
{
public:
UsdDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3,
UsdDevice* device
);
UsdDataArray(ANARIDataType dataType,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3,
UsdDevice* device
);
~UsdDataArray();
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override;
void commit(UsdDevice* device) override;
void remove(UsdDevice* device) override {}
void* map(UsdDevice* device);
void unmap(UsdDevice* device);
void privatize();
const char* getName() const override { return UsdSharedString::c_str(getReadParams().usdName); }
const void* getData() const { return data; }
ANARIDataType getType() const { return type; }
const UsdDataLayout& getLayout() const { return layout; }
size_t getDataSizeInBytes() const { return dataSizeInBytes; }
protected:
bool deferCommit(UsdDevice* device) override { return false; }
bool doCommitData(UsdDevice* device) override { return false; }
void doCommitRefs(UsdDevice* device) override {}
void setLayoutAndSize(uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3);
bool CheckFormatting(UsdDevice* device);
// Ref manipulation on arrays of anariobjects
void incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects);
void decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects);
// Private memory management
void allocPrivateData();
void freePrivateData(bool mappedCopy = false);
void freePublicData(const void* appMemory);
void publicToPrivateData();
// Mapped memory management
void CreateMappedObjectCopy();
void TransferAndRemoveMappedObjectCopy();
const void* data = nullptr;
ANARIMemoryDeleter dataDeleter = nullptr;
const void* deleterUserData = nullptr;
ANARIDataType type;
UsdDataLayout layout;
size_t dataSizeInBytes;
bool isPrivate;
const void* mappedObjectCopy;
#ifdef CHECK_MEMLEAKS
UsdDevice* allocDevice;
#endif
}; | 4,032 | C | 30.263566 | 138 | 0.708829 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceQueries.h | // Copyright 2021 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
// This file was generated by generate_queries.py
// Don't make changes to this directly
#include <anari/anari.h>
namespace anari {
namespace usd {
#define ANARI_INFO_required 0
#define ANARI_INFO_default 1
#define ANARI_INFO_minimum 2
#define ANARI_INFO_maximum 3
#define ANARI_INFO_description 4
#define ANARI_INFO_elementType 5
#define ANARI_INFO_value 6
#define ANARI_INFO_sourceExtension 7
#define ANARI_INFO_extension 8
#define ANARI_INFO_parameter 9
#define ANARI_INFO_channel 10
#define ANARI_INFO_use 11
const int extension_count = 17;
const char ** query_extensions();
const char ** query_object_types(ANARIDataType type);
const ANARIParameter * query_params(ANARIDataType type, const char *subtype);
const void * query_param_info_enum(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, int infoName, ANARIDataType infoType);
const void * query_param_info(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, const char *infoNameString, ANARIDataType infoType);
const void * query_object_info_enum(ANARIDataType type, const char *subtype, int infoName, ANARIDataType infoType);
const void * query_object_info(ANARIDataType type, const char *subtype, const char *infoNameString, ANARIDataType infoType);
}
}
| 1,368 | C | 41.781249 | 171 | 0.790205 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDevice.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "anari/backend/DeviceImpl.h"
#include "anari/backend/LibraryImpl.h"
#include "UsdBaseObject.h"
#include <vector>
#include <memory>
#ifdef _WIN32
#ifdef anari_library_usd_EXPORTS
#define USDDevice_INTERFACE __declspec(dllexport)
#else
#define USDDevice_INTERFACE __declspec(dllimport)
#endif
#endif
extern "C"
{
#ifdef WIN32
USDDevice_INTERFACE void __cdecl anari_library_usd_init();
#else
void anari_library_usd_init();
#endif
}
class UsdDevice;
class UsdDeviceInternals;
class UsdBaseObject;
class UsdVolume;
struct UsdDeviceData
{
UsdSharedString* hostName = nullptr;
UsdSharedString* outputPath = nullptr;
bool createNewSession = true;
bool outputBinary = false;
bool writeAtCommit = false;
double timeStep = 0.0;
bool outputMaterial = true;
bool outputPreviewSurfaceShader = true;
bool outputMdlShader = true;
};
class UsdDevice : public anari::DeviceImpl, public UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>
{
public:
UsdDevice();
UsdDevice(ANARILibrary library);
~UsdDevice();
///////////////////////////////////////////////////////////////////////////
// Main virtual interface to accepting API calls
///////////////////////////////////////////////////////////////////////////
// Data Arrays ////////////////////////////////////////////////////////////
ANARIArray1D newArray1D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1) override;
ANARIArray2D newArray2D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1,
uint64_t numItems2) override;
ANARIArray3D newArray3D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3) override;
void* mapArray(ANARIArray) override;
void unmapArray(ANARIArray) override;
// Renderable Objects /////////////////////////////////////////////////////
ANARILight newLight(const char *type) override { return nullptr; }
ANARICamera newCamera(const char *type) override;
ANARIGeometry newGeometry(const char *type);
ANARISpatialField newSpatialField(const char *type) override;
ANARISurface newSurface() override;
ANARIVolume newVolume(const char *type) override;
// Model Meta-Data ////////////////////////////////////////////////////////
ANARIMaterial newMaterial(const char *material_type) override;
ANARISampler newSampler(const char *type) override;
// Instancing /////////////////////////////////////////////////////////////
ANARIGroup newGroup() override;
ANARIInstance newInstance(const char *type) override;
// Top-level Worlds ///////////////////////////////////////////////////////
ANARIWorld newWorld() override;
// Query functions ////////////////////////////////////////////////////////
const char ** getObjectSubtypes(ANARIDataType objectType) override;
const void* getObjectInfo(ANARIDataType objectType,
const char* objectSubtype,
const char* infoName,
ANARIDataType infoType) override;
const void* getParameterInfo(ANARIDataType objectType,
const char* objectSubtype,
const char* parameterName,
ANARIDataType parameterType,
const char* infoName,
ANARIDataType infoType) override;
// Object + Parameter Lifetime Management /////////////////////////////////
void setParameter(ANARIObject object,
const char *name,
ANARIDataType type,
const void *mem) override;
void unsetParameter(ANARIObject object, const char *name) override;
void unsetAllParameters(ANARIObject o) override;
void* mapParameterArray1D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t *elementStride) override;
void* mapParameterArray2D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t *elementStride) override;
void* mapParameterArray3D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t numElements3,
uint64_t *elementStride) override;
void unmapParameterArray(ANARIObject o,
const char* name) override;
void commitParameters(ANARIObject object) override;
void release(ANARIObject _obj) override;
void retain(ANARIObject _obj) override;
// Object Query Interface /////////////////////////////////////////////////
int getProperty(ANARIObject object,
const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
uint32_t mask) override;
// FrameBuffer Manipulation ///////////////////////////////////////////////
ANARIFrame newFrame() override;
const void *frameBufferMap(ANARIFrame fb,
const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType) override;
void frameBufferUnmap(ANARIFrame fb, const char *channel) override;
// Frame Rendering ////////////////////////////////////////////////////////
ANARIRenderer newRenderer(const char *type) override;
void renderFrame(ANARIFrame frame) override;
int frameReady(ANARIFrame, ANARIWaitMask) override { return 1; }
void discardFrame(ANARIFrame) override {}
// UsdParameterizedBaseObject interface ///////////////////////////////////////////////////////////
void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
void filterResetParam(
const char *name) override;
void commit(UsdDevice* device) override;
void remove(UsdDevice* device) override {}
// USD Specific ///////////////////////////////////////////////////////////
bool isInitialized() { return getUsdBridge() != nullptr; }
UsdBridge* getUsdBridge();
bool nameExists(const char* name);
void addToCommitList(UsdBaseObject* object, bool commitData);
bool isFlushingCommitList() const { return lockCommitList; }
void addToVolumeList(UsdVolume* volume);
void removeFromVolumeList(UsdVolume* volume);
// Allows for selected strings to persist,
// so their pointers can be cached beyond their containing objects' lifetimes,
// to be used for garbage collecting resource files.
void addToResourceStringList(UsdSharedString* sharedString);
#ifdef CHECK_MEMLEAKS
// Memleak checking
void LogObjAllocation(const UsdBaseObject* ptr);
void LogObjDeallocation(const UsdBaseObject* ptr);
std::vector<const UsdBaseObject*> allocatedObjects;
void LogStrAllocation(const UsdSharedString* ptr);
void LogStrDeallocation(const UsdSharedString* ptr);
std::vector<const UsdSharedString*> allocatedStrings;
void LogRawAllocation(const void* ptr);
void LogRawDeallocation(const void* ptr);
std::vector<const void*> allocatedRawMemory;
#endif
void reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format, ...);
void reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format,
va_list& arglist);
protected:
UsdBaseObject* getBaseObjectPtr(ANARIObject object);
// UsdParameterizedBaseObject interface ///////////////////////////////////////////////////////////
bool deferCommit(UsdDevice* device) { return false; };
bool doCommitData(UsdDevice* device) { return false; };
void doCommitRefs(UsdDevice* device) {};
// USD Specific Cleanup /////////////////////////////////////////////////////////////
void clearCommitList();
void flushCommitList();
void clearDeviceParameters();
void clearResourceStringList();
void initializeBridge();
const char* makeUniqueName(const char* name);
ANARIArray CreateDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3);
template<int typeInt>
void writeTypeToUsd();
void removePrimsFromUsd(bool onlyRemoveHandles = false);
std::unique_ptr<UsdDeviceInternals> internals;
bool bridgeInitAttempt = false;
// Using object pointers as basis for deferred commits; another option would be to traverse
// the bridge's internal cache handles, but a handle may map to multiple objects (with the same name)
// so that's not 1-1 with the effects of a non-deferred commit order.
using CommitListType = std::pair<helium::IntrusivePtr<UsdBaseObject>, bool>;
std::vector<CommitListType> commitList;
std::vector<UsdBaseObject*> removeList;
std::vector<UsdVolume*> volumeList; // Tracks all volumes to auto-commit when child fields have been committed
bool lockCommitList = false;
std::vector<helium::IntrusivePtr<UsdSharedString>> resourceStringList;
ANARIStatusCallback statusFunc = nullptr;
const void* statusUserData = nullptr;
ANARIStatusCallback userSetStatusFunc = nullptr;
const void* userSetStatusUserData = nullptr;
std::vector<char> lastStatusMessage;
};
| 9,712 | C | 30.031949 | 114 | 0.643637 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdBridgedBaseObject.h"
enum class UsdCameraComponents
{
VIEW = 0,
PROJECTION
};
struct UsdCameraData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // TimeVarying bits
UsdFloat3 position = {0.0f, 0.0f, 0.0f};
UsdFloat3 direction = {0.0f, 0.0f, -1.0f};
UsdFloat3 up = {0.0f, 1.0f, 0.0f};
UsdFloatBox2 imageRegion = {0.0f, 0.0f, 1.0f, 1.0f};
// perspective/orthographic
float aspect = 1.0f;
float near = 1.0f;
float far = 10000;
float fovy = M_PI/3.0f;
float height = 1.0f;
};
class UsdCamera : public UsdBridgedBaseObject<UsdCamera, UsdCameraData, UsdCameraHandle, UsdCameraComponents>
{
public:
UsdCamera(const char* name, const char* type, UsdDevice* device);
~UsdCamera();
void remove(UsdDevice* device) override;
enum CameraType
{
CAMERA_UNKNOWN = 0,
CAMERA_PERSPECTIVE,
CAMERA_ORTHOGRAPHIC
};
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdCameraComponents::VIEW, "view"),
ComponentPair(UsdCameraComponents::PROJECTION, "projection")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void copyParameters(UsdBridgeCameraData& camData);
CameraType cameraType = CAMERA_UNKNOWN;
}; | 1,521 | C | 23.548387 | 109 | 0.702827 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceUtils.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <vector>
#include <memory>
template<typename ValueType, typename ContainerType = std::vector<ValueType>>
struct OptionalList
{
void ensureList()
{
if(!list)
list = std::make_unique<ContainerType>();
}
void clear()
{
if(list)
list->resize(0);
}
void push_back(const ValueType& value)
{
ensureList();
list->push_back(value);
}
void emplace_back(const ValueType& value)
{
ensureList();
list->emplace_back(value);
}
const ValueType* data()
{
if(list)
return list->data();
return nullptr;
}
size_t size()
{
if(list)
return list->size();
return 0;
}
std::unique_ptr<ContainerType> list;
}; | 796 | C | 14.627451 | 77 | 0.614322 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <limits>
class UsdGeometry;
class UsdMaterial;
struct UsdSurfaceData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
// No timevarying data: geometry and material reference always set over all timesteps
UsdGeometry* geometry = nullptr;
UsdMaterial* material = nullptr;
double geometryRefTimeStep = std::numeric_limits<float>::quiet_NaN();
double materialRefTimeStep = std::numeric_limits<float>::quiet_NaN();
};
class UsdSurface : public UsdBridgedBaseObject<UsdSurface, UsdSurfaceData, UsdSurfaceHandle>
{
public:
UsdSurface(const char* name, UsdDevice* device);
~UsdSurface();
void remove(UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
}; | 980 | C | 24.153846 | 92 | 0.753061 |
NVIDIA-Omniverse/AnariUsdDevice/UsdVolume.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <limits>
class UsdSpatialField;
class UsdDevice;
class UsdDataArray;
enum class UsdVolumeComponents
{
COLOR = 0,
OPACITY,
VALUERANGE
};
struct UsdVolumeData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying. (field reference always set over all timesteps)
UsdSpatialField* field = nullptr;
double fieldRefTimeStep = std::numeric_limits<float>::quiet_NaN();
bool preClassified = false;
//TF params
const UsdDataArray* color = nullptr;
const UsdDataArray* opacity = nullptr;
UsdFloatBox1 valueRange = { 0.0f, 1.0f };
float unitDistance = 1.0f;
};
class UsdVolume : public UsdBridgedBaseObject<UsdVolume, UsdVolumeData, UsdVolumeHandle, UsdVolumeComponents>
{
public:
UsdVolume(const char* name, UsdDevice* device);
~UsdVolume();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdVolumeComponents::COLOR, "color"),
ComponentPair(UsdVolumeComponents::OPACITY, "opacity"),
ComponentPair(UsdVolumeComponents::VALUERANGE, "valueRange")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
bool CheckTfParams(UsdDevice* device);
bool UpdateVolume(UsdDevice* device, const char* debugName);
UsdSpatialField* prevField = nullptr;
UsdDevice* usdDevice = nullptr;
}; | 1,669 | C | 25.507936 | 136 | 0.742361 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdAnari.h"
#include "anari/frontend/type_utility.h"
DEFINE_PARAMETER_MAP(UsdDataArray,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
)
#define TO_OBJ_PTR reinterpret_cast<const ANARIObject*>
UsdDataArray::UsdDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3,
UsdDevice* device
)
: UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY)
, data(appMemory)
, dataDeleter(deleter)
, deleterUserData(userData)
, type(dataType)
, isPrivate(false)
#ifdef CHECK_MEMLEAKS
, allocDevice(device)
#endif
{
setLayoutAndSize(numItems1, byteStride1, numItems2, byteStride2, numItems3, byteStride3);
if (CheckFormatting(device))
{
// Make sure to incref all anari objects in case of object array
if (anari::isObject(type))
{
incRef(TO_OBJ_PTR(data), layout.numItems1);
}
}
}
UsdDataArray::UsdDataArray(ANARIDataType dataType, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3, UsdDevice* device)
: UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY)
, type(dataType)
, isPrivate(true)
#ifdef CHECK_MEMLEAKS
, allocDevice(device)
#endif
{
setLayoutAndSize(numItems1, 0, numItems2, 0, numItems3, 0);
if (CheckFormatting(device))
{
allocPrivateData();
}
}
UsdDataArray::~UsdDataArray()
{
// Decref anari objects in case of object array
if (anari::isObject(type))
{
decRef(TO_OBJ_PTR(data), layout.numItems1);
}
if (isPrivate)
{
freePrivateData();
}
else
{
freePublicData(data);
}
}
void UsdDataArray::filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if(setNameParam(name, type, mem, device))
device->addToResourceStringList(getWriteParams().usdName); //Name is kept for the lifetime of the device (to allow using pointer for caching resource's names)
}
int UsdDataArray::getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device)
{
int nameResult = getNameProperty(name, type, mem, size, device);
return nameResult;
}
void UsdDataArray::commit(UsdDevice* device)
{
if (anari::isObject(type) && (layout.numItems2 != 1 || layout.numItems3 != 1))
device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdDataArray only supports one-dimensional ANARI_OBJECT arrays");
UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>::commit(device);
}
void * UsdDataArray::map(UsdDevice * device)
{
if (anari::isObject(type))
{
CreateMappedObjectCopy();
}
return const_cast<void *>(data);
}
void UsdDataArray::unmap(UsdDevice * device)
{
if (anari::isObject(type))
{
TransferAndRemoveMappedObjectCopy();
}
}
void UsdDataArray::privatize()
{
if(!isPrivate)
{
publicToPrivateData();
isPrivate = true;
}
}
void UsdDataArray::setLayoutAndSize(uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3)
{
size_t typeSize = anari::sizeOf(type);
if (byteStride1 == 0)
byteStride1 = typeSize;
if (byteStride2 == 0)
byteStride2 = byteStride1 * numItems1;
if (byteStride3 == 0)
byteStride3 = byteStride2 * numItems2;
dataSizeInBytes = byteStride3 * numItems3 - (byteStride1 - typeSize);
layout = { typeSize, numItems1, numItems2, numItems3, byteStride1, byteStride2, byteStride3 };
}
bool UsdDataArray::CheckFormatting(UsdDevice* device)
{
if (anari::isObject(type))
{
if (!layout.isDense() || !layout.isOneDimensional())
{
device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdDataArray construction failed: arrays with object type have to be one dimensional and without stride.");
layout.numItems1 = layout.numItems2 = layout.numItems3 = 0;
data = nullptr;
type = ANARI_UNKNOWN;
return false;
}
}
return true;
}
void UsdDataArray::incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects)
{
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i]));
if (baseObj)
baseObj->refInc(helium::RefType::INTERNAL);
}
}
void UsdDataArray::decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects)
{
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i]));
#ifdef CHECK_MEMLEAKS
allocDevice->LogObjDeallocation(baseObj);
#endif
if (baseObj)
{
assert(baseObj->useCount(helium::RefType::INTERNAL) > 0);
baseObj->refDec(helium::RefType::INTERNAL);
}
}
}
void UsdDataArray::allocPrivateData()
{
// Alloc the owned memory
char* newData = new char[dataSizeInBytes];
memset(newData, 0, dataSizeInBytes);
data = newData;
#ifdef CHECK_MEMLEAKS
allocDevice->LogRawAllocation(newData);
#endif
}
void UsdDataArray::freePrivateData(bool mappedCopy)
{
const void*& memToFree = mappedCopy ? mappedObjectCopy : data;
#ifdef CHECK_MEMLEAKS
allocDevice->LogRawDeallocation(memToFree);
#endif
// Deallocate owned memory
delete[](char*)memToFree;
memToFree = nullptr;
}
void UsdDataArray::freePublicData(const void* appMemory)
{
if (dataDeleter)
{
dataDeleter(deleterUserData, appMemory);
dataDeleter = nullptr;
}
}
void UsdDataArray::publicToPrivateData()
{
// Alloc private dest, copy appMemory src to it
const void* appMemory = data;
allocPrivateData();
std::memcpy(const_cast<void *>(data), appMemory, dataSizeInBytes); // In case of object array, Refcount 'transfers' to the copy (splits off user-managed public refcount)
// Delete appMemory if appropriate
freePublicData(appMemory);
// No refcount modification necessary, public refcount managed by user
}
void UsdDataArray::CreateMappedObjectCopy()
{
// Move the original array to a different spot and allocate new memory for the mapped object array.
mappedObjectCopy = data;
allocPrivateData();
// Transfer contents over to new memory, keep old one for managing references later on.
std::memcpy(const_cast<void *>(data), mappedObjectCopy, dataSizeInBytes);
}
void UsdDataArray::TransferAndRemoveMappedObjectCopy()
{
const ANARIObject* newAnariObjects = TO_OBJ_PTR(data);
const ANARIObject* oldAnariObjects = TO_OBJ_PTR(mappedObjectCopy);
uint64_t numAnariObjects = layout.numItems1;
// First, increase reference counts of all objects that different in the new object array
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i]));
const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i]));
if (newObj != oldObj && newObj)
newObj->refInc(helium::RefType::INTERNAL);
}
// Then, decrease reference counts of all objects that are different in the original array (which will delete those that not referenced anymore)
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i]));
const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i]));
if (newObj != oldObj && oldObj)
{
#ifdef CHECK_MEMLEAKS
allocDevice->LogObjDeallocation(oldObj);
#endif
oldObj->refDec(helium::RefType::INTERNAL);
}
}
// Release the mapped object copy's allocated memory
freePrivateData(true);
}
| 7,904 | C++ | 26.258621 | 207 | 0.721407 |
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdInstance.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdGroup.h"
#define GroupType ANARI_GROUP
using GroupUsdType = AnariToUsdBridgedObject<GroupType>::Type;
DEFINE_PARAMETER_MAP(UsdInstance,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("group", GroupType, group)
REGISTER_PARAMETER_MACRO("transform", ANARI_FLOAT32_MAT4, transform)
)
constexpr UsdInstance::ComponentPair UsdInstance::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdInstance::UsdInstance(const char* name,
UsdDevice* device)
: BridgedBaseObjectType(ANARI_INSTANCE, name, device)
{
}
UsdInstance::~UsdInstance()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteInstance(usdHandle);
#endif
}
void UsdInstance::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteInstance);
}
bool UsdInstance::deferCommit(UsdDevice* device)
{
const UsdInstanceData& paramData = getReadParams();
if(UsdObjectNotInitialized<GroupUsdType>(paramData.group))
{
return true;
}
return false;
}
bool UsdInstance::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const char* instanceName = getName();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateInstance(instanceName, usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdInstance::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdInstanceData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
bool groupTimeVarying = isTimeVarying(UsdInstanceComponents::GROUP);
bool transformTimeVarying = isTimeVarying(UsdInstanceComponents::TRANSFORM);
if (paramData.group)
{
usdBridge->SetGroupRef(usdHandle, paramData.group->getUsdHandle(), groupTimeVarying, timeStep);
}
else
{
usdBridge->DeleteGroupRef(usdHandle, groupTimeVarying, timeStep);
}
usdBridge->SetInstanceTransform(usdHandle, paramData.transform.Data, transformTimeVarying, timeStep);
} | 2,456 | C++ | 25.706521 | 132 | 0.757329 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdGeometry.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdBridgeUtils.h"
#include "anari/frontend/type_utility.h"
#include <cmath>
DEFINE_PARAMETER_MAP(UsdGeometry,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::time.shapeGeometry", ANARI_FLOAT64, shapeGeometryRefTimeStep)
REGISTER_PARAMETER_MACRO("usd::useUsdGeomPoints", ANARI_BOOL, UseUsdGeomPoints)
REGISTER_PARAMETER_MACRO("primitive.index", ANARI_ARRAY, indices)
REGISTER_PARAMETER_MACRO("primitive.normal", ANARI_ARRAY, primitiveNormals)
REGISTER_PARAMETER_MACRO("primitive.color", ANARI_ARRAY, primitiveColors)
REGISTER_PARAMETER_MACRO("primitive.radius", ANARI_ARRAY, primitiveRadii)
REGISTER_PARAMETER_MACRO("primitive.scale", ANARI_ARRAY, primitiveScales)
REGISTER_PARAMETER_MACRO("primitive.orientation", ANARI_ARRAY, primitiveOrientations)
REGISTER_PARAMETER_ARRAY_MACRO("primitive.attribute", "", ANARI_ARRAY, primitiveAttributes, MAX_ATTRIBS)
REGISTER_PARAMETER_MACRO("primitive.id", ANARI_ARRAY, primitiveIds)
REGISTER_PARAMETER_MACRO("vertex.position", ANARI_ARRAY, vertexPositions)
REGISTER_PARAMETER_MACRO("vertex.normal", ANARI_ARRAY, vertexNormals)
REGISTER_PARAMETER_MACRO("vertex.color", ANARI_ARRAY, vertexColors)
REGISTER_PARAMETER_MACRO("vertex.radius", ANARI_ARRAY, vertexRadii)
REGISTER_PARAMETER_MACRO("vertex.scale", ANARI_ARRAY, vertexScales)
REGISTER_PARAMETER_MACRO("vertex.orientation", ANARI_ARRAY, vertexOrientations)
REGISTER_PARAMETER_ARRAY_MACRO("vertex.attribute", "", ANARI_ARRAY, vertexAttributes, MAX_ATTRIBS)
REGISTER_PARAMETER_ARRAY_MACRO("usd::attribute", ".name", ANARI_STRING, attributeNames, MAX_ATTRIBS)
REGISTER_PARAMETER_MACRO("radius", ANARI_FLOAT32, radiusConstant)
REGISTER_PARAMETER_MACRO("scale", ANARI_FLOAT32_VEC3, scaleConstant)
REGISTER_PARAMETER_MACRO("orientation", ANARI_FLOAT32_QUAT_IJKW, orientationConstant)
REGISTER_PARAMETER_MACRO("shapeType", ANARI_STRING, shapeType)
REGISTER_PARAMETER_MACRO("shapeGeometry", ANARI_GEOMETRY, shapeGeometry)
REGISTER_PARAMETER_MACRO("shapeTransform", ANARI_FLOAT32_MAT4, shapeTransform)
) // See .h for usage.
constexpr UsdGeometry::ComponentPair UsdGeometry::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
struct UsdGeometryTempArrays
{
UsdGeometryTempArrays(const UsdGeometry::AttributeArray& attributes)
: Attributes(attributes)
{}
std::vector<int> CurveLengths;
std::vector<float> PointsArray;
std::vector<float> NormalsArray;
std::vector<float> RadiiArray;
std::vector<float> ScalesArray;
std::vector<float> OrientationsArray;
std::vector<int64_t> IdsArray;
std::vector<int64_t> InvisIdsArray;
std::vector<char> ColorsArray; // generic byte array
ANARIDataType ColorsArrayType;
UsdGeometry::AttributeDataArraysType AttributeDataArrays;
const UsdGeometry::AttributeArray& Attributes;
void resetColorsArray(size_t numElements, ANARIDataType type)
{
ColorsArray.resize(numElements*anari::sizeOf(type));
ColorsArrayType = type;
}
void reserveColorsArray(size_t numElements)
{
ColorsArray.reserve(numElements*anari::sizeOf(ColorsArrayType));
}
size_t expandColorsArray(size_t numElements)
{
size_t startByte = ColorsArray.size();
size_t typeSize = anari::sizeOf(ColorsArrayType);
ColorsArray.resize(startByte+numElements*typeSize);
return startByte/typeSize;
}
void copyToColorsArray(const void* source, size_t srcIdx, size_t destIdx, size_t numElements)
{
size_t typeSize = anari::sizeOf(ColorsArrayType);
size_t srcStart = srcIdx*typeSize;
size_t dstStart = destIdx*typeSize;
size_t numBytes = numElements*typeSize;
assert(dstStart+numBytes <= ColorsArray.size());
memcpy(ColorsArray.data()+dstStart, reinterpret_cast<const char*>(source)+srcStart, numBytes);
}
void resetAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
AttributeDataArrays[attribIdx].resize(numElements*eltSize);
}
else
AttributeDataArrays[attribIdx].resize(0);
}
void reserveAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
AttributeDataArrays[attribIdx].reserve(numElements*eltSize);
}
}
size_t expandAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
size_t startByte = AttributeDataArrays[attribIdx].size();
AttributeDataArrays[attribIdx].resize(startByte+numElements*eltSize);
return startByte/eltSize;
}
return 0;
}
void copyToAttributeDataArray(size_t attribIdx, size_t srcIdx, size_t destIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
const void* attribSrc = reinterpret_cast<const char*>(Attributes[attribIdx].Data) + srcIdx*eltSize;
size_t dstStart = destIdx*eltSize;
size_t numBytes = numElements*eltSize;
assert(dstStart+numBytes <= AttributeDataArrays[attribIdx].size());
void* attribDest = &AttributeDataArrays[attribIdx][dstStart];
memcpy(attribDest, attribSrc, numElements*eltSize);
}
}
};
namespace
{
struct UsdGeometryDebugData
{
UsdDevice* device = nullptr;
UsdGeometry* geometry = nullptr;
const char* debugName = nullptr;
};
UsdGeometry::GeomType GetGeomType(const char* type)
{
UsdGeometry::GeomType geomType;
if (strEquals(type, "sphere"))
geomType = UsdGeometry::GEOM_SPHERE;
else if (strEquals(type, "cylinder"))
geomType = UsdGeometry::GEOM_CYLINDER;
else if (strEquals(type, "cone"))
geomType = UsdGeometry::GEOM_CONE;
else if (strEquals(type, "curve"))
geomType = UsdGeometry::GEOM_CURVE;
else if(strEquals(type, "triangle"))
geomType = UsdGeometry::GEOM_TRIANGLE;
else if (strEquals(type, "quad"))
geomType = UsdGeometry::GEOM_QUAD;
else if (strEquals(type, "glyph"))
geomType = UsdGeometry::GEOM_GLYPH;
else
geomType = UsdGeometry::GEOM_UNKNOWN;
return geomType;
}
uint64_t GetNumberOfPrims(bool hasIndices, const UsdDataLayout& indexLayout, UsdGeometry::GeomType geomType)
{
if(geomType == UsdGeometry::GEOM_CURVE)
return indexLayout.numItems1 - 1;
else if(hasIndices)
return indexLayout.numItems1;
int perPrimVertexCount = 1;
switch(geomType)
{
case UsdGeometry::GEOM_CYLINDER:
case UsdGeometry::GEOM_CONE:
perPrimVertexCount = 2;
break;
case UsdGeometry::GEOM_TRIANGLE:
perPrimVertexCount = 3;
break;
case UsdGeometry::GEOM_QUAD:
perPrimVertexCount = 4;
break;
default: break;
};
return indexLayout.numItems1 / perPrimVertexCount;
}
bool isBitSet(int value, int bit)
{
return (bool)(value & (1 << bit));
}
size_t getIndex(const void* indices, ANARIDataType type, size_t elt)
{
size_t result;
switch (type)
{
case ANARI_INT32:
case ANARI_INT32_VEC2:
result = (reinterpret_cast<const int*>(indices))[elt];
break;
case ANARI_UINT32:
case ANARI_UINT32_VEC2:
result = (reinterpret_cast<const uint32_t*>(indices))[elt];
break;
case ANARI_INT64:
case ANARI_INT64_VEC2:
result = (reinterpret_cast<const int64_t*>(indices))[elt];
break;
case ANARI_UINT64:
case ANARI_UINT64_VEC2:
result = (reinterpret_cast<const uint64_t*>(indices))[elt];
break;
default:
result = 0;
break;
}
return result;
}
void getValues1(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx];
}
else if (type == ANARI_FLOAT64)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx];
}
}
void getValues2(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC2)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 2];
result[1] = vertf[idx * 2 + 1];
}
else if (type == ANARI_FLOAT64_VEC2)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 2];
result[1] = (float)vertd[idx * 2 + 1];
}
}
void getValues3(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC3)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 3];
result[1] = vertf[idx * 3 + 1];
result[2] = vertf[idx * 3 + 2];
}
else if (type == ANARI_FLOAT64_VEC3)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 3];
result[1] = (float)vertd[idx * 3 + 1];
result[2] = (float)vertd[idx * 3 + 2];
}
}
void getValues4(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC4)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 4];
result[1] = vertf[idx * 4 + 1];
result[2] = vertf[idx * 4 + 2];
result[3] = vertf[idx * 4 + 3];
}
else if (type == ANARI_FLOAT64_VEC4)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 4];
result[1] = (float)vertd[idx * 4 + 1];
result[2] = (float)vertd[idx * 4 + 2];
result[3] = (float)vertd[idx * 4 + 3];
}
}
void generateIndexedSphereData(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
if (paramData.indices)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
uint64_t numVertices = paramData.vertexPositions->getLayout().numItems1;
ANARIDataType scaleType = paramData.vertexScales ? paramData.vertexScales->getType()
: (paramData.primitiveScales ? paramData.primitiveScales->getType() : ANARI_UNKNOWN);
size_t scaleComps = anari::componentsOf(scaleType);
bool perPrimNormals = !paramData.vertexNormals && paramData.primitiveNormals;
bool perPrimRadii = !paramData.vertexRadii && paramData.primitiveRadii;
bool perPrimScales = !paramData.vertexScales && paramData.primitiveScales;
bool perPrimColors = !paramData.vertexColors && paramData.primitiveColors;
bool perPrimOrientations = !paramData.vertexOrientations && paramData.primitiveOrientations;
ANARIDataType colorType = perPrimColors ? paramData.primitiveColors->getType() : ANARI_UINT8; // Vertex colors aren't reordered
// Effectively only has to reorder if the source array is perPrim, otherwise this function effectively falls through and the source array is assigned directly at parent scope.
tempArrays->NormalsArray.resize(perPrimNormals ? numVertices*3 : 0);
tempArrays->RadiiArray.resize(perPrimScales ? numVertices : 0);
tempArrays->ScalesArray.resize(perPrimScales ? numVertices*scaleComps : 0);
tempArrays->OrientationsArray.resize(perPrimOrientations ? numVertices*4 : 0);
tempArrays->IdsArray.resize(numVertices, -1); // Always filled, since indices implies necessity for invisibleIds, and therefore also an Id array
tempArrays->resetColorsArray(perPrimColors ? numVertices : 0, colorType);
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, attributeArray[attribIdx].PerPrimData ? numVertices : 0);
}
const void* indices = paramData.indices->getData();
uint64_t numIndices = paramData.indices->getLayout().numItems1;
ANARIDataType indexType = paramData.indices->getType();
int64_t maxId = -1;
for (uint64_t primIdx = 0; primIdx < numIndices; ++primIdx)
{
size_t vertIdx = getIndex(indices, indexType, primIdx);
// Normals
if (perPrimNormals)
{
float* normalsDest = &tempArrays->NormalsArray[vertIdx * 3];
getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normalsDest);
}
// Orientations
if (perPrimOrientations)
{
float* orientsDest = &tempArrays->OrientationsArray[vertIdx*4];
getValues4(paramData.primitiveOrientations->getData(), paramData.primitiveOrientations->getType(), primIdx, orientsDest);
}
// Radii
if (perPrimRadii)
{
float* radiiDest = &tempArrays->RadiiArray[vertIdx];
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, radiiDest);
}
// Scales
if (perPrimScales)
{
float* scalesDest = &tempArrays->ScalesArray[vertIdx*scaleComps];
if(scaleComps == 1)
getValues1(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest);
else if(scaleComps == 3)
getValues3(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest);
}
// Colors
if (perPrimColors)
{
assert(primIdx < paramData.primitiveColors->getLayout().numItems1);
tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, vertIdx, 1);
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(attributeArray[attribIdx].PerPrimData)
{
tempArrays->copyToAttributeDataArray(attribIdx, primIdx, vertIdx, 1);
}
}
// Ids
if (paramData.primitiveIds)
{
int64_t id = static_cast<int64_t>(getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx));
tempArrays->IdsArray[vertIdx] = id;
if (id > maxId)
maxId = id;
}
else
{
int64_t id = static_cast<int64_t>(vertIdx);
maxId = tempArrays->IdsArray[vertIdx] = id;
}
}
// Assign unused ids to untouched vertices, then add those ids to invisible array
tempArrays->InvisIdsArray.resize(0);
tempArrays->InvisIdsArray.reserve(numVertices);
for (uint64_t vertIdx = 0; vertIdx < numVertices; ++vertIdx)
{
if (tempArrays->IdsArray[vertIdx] == -1)
{
tempArrays->IdsArray[vertIdx] = ++maxId;
tempArrays->InvisIdsArray.push_back(maxId);
}
}
}
}
void convertLinesToSticks(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
// Converts arrays of vertex endpoint 2-tuples (optionally obtained via index 2-tuples) into center vertices with correct seglengths.
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
const UsdDataArray* vertexArray = paramData.vertexPositions;
uint64_t numVertices = vertexArray->getLayout().numItems1;
const void* vertices = vertexArray->getData();
ANARIDataType vertexType = vertexArray->getType();
const UsdDataArray* indexArray = paramData.indices;
uint64_t numSticks = indexArray ? indexArray->getLayout().numItems1 : numVertices/2;
uint64_t numIndices = numSticks * 2; // Indices are 2-element vectors in ANARI
const void* indices = indexArray ? indexArray->getData() : nullptr;
ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32;
tempArrays->PointsArray.resize(numSticks * 3);
tempArrays->ScalesArray.resize(numSticks * 3); // Scales are always present
tempArrays->OrientationsArray.resize(numSticks * 4);
tempArrays->IdsArray.resize(paramData.primitiveIds ? numSticks : 0);
// Only reorder per-vertex arrays, per-prim is already in order of the output stick center vertices
ANARIDataType colorType = paramData.vertexColors ? paramData.vertexColors->getType() : ANARI_UINT8;
tempArrays->resetColorsArray(paramData.vertexColors ? numSticks : 0, colorType);
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, !attributeArray[attribIdx].PerPrimData ? numSticks : 0);
}
for (size_t i = 0; i < numIndices; i += 2)
{
size_t primIdx = i / 2;
size_t vertIdx0 = indices ? getIndex(indices, indexType, i) : i;
size_t vertIdx1 = indices ? getIndex(indices, indexType, i + 1) : i + 1;
assert(vertIdx0 < numVertices);
assert(vertIdx1 < numVertices);
float point0[3], point1[3];
getValues3(vertices, vertexType, vertIdx0, point0);
getValues3(vertices, vertexType, vertIdx1, point1);
tempArrays->PointsArray[primIdx * 3] = (point0[0] + point1[0]) * 0.5f;
tempArrays->PointsArray[primIdx * 3 + 1] = (point0[1] + point1[1]) * 0.5f;
tempArrays->PointsArray[primIdx * 3 + 2] = (point0[2] + point1[2]) * 0.5f;
float scaleVal = paramData.radiusConstant;
if (paramData.vertexRadii)
{
getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), vertIdx0, &scaleVal);
}
else if (paramData.primitiveRadii)
{
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &scaleVal);
}
float segDir[3] = {
point1[0] - point0[0],
point1[1] - point0[1],
point1[2] - point0[2],
};
float segLength = sqrtf(segDir[0] * segDir[0] + segDir[1] * segDir[1] + segDir[2] * segDir[2]);
tempArrays->ScalesArray[primIdx * 3] = scaleVal;
tempArrays->ScalesArray[primIdx * 3 + 1] = scaleVal;
tempArrays->ScalesArray[primIdx * 3 + 2] = segLength * 0.5f;
// Rotation
// USD shapes are always lengthwise-oriented along the z axis
usdbridgenumerics::DirectionToQuaternionZ(segDir, segLength, tempArrays->OrientationsArray.data() + primIdx*4);
//Colors
if (paramData.vertexColors)
{
assert(vertIdx0 < paramData.vertexColors->getLayout().numItems1);
tempArrays->copyToColorsArray(paramData.vertexColors->getData(), vertIdx0, primIdx, 1);
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(!attributeArray[attribIdx].PerPrimData)
{
tempArrays->copyToAttributeDataArray(attribIdx, vertIdx0, primIdx, 1);
}
}
// Ids
if (paramData.primitiveIds)
{
tempArrays->IdsArray[primIdx] = (int64_t)getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx);
}
}
}
void pushVertex(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays,
const void* vertices, ANARIDataType vertexType,
bool hasNormals, bool hasColors, bool hasRadii,
size_t segStart, size_t primIdx)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
float point[3];
getValues3(vertices, vertexType, segStart, point);
tempArrays->PointsArray.push_back(point[0]);
tempArrays->PointsArray.push_back(point[1]);
tempArrays->PointsArray.push_back(point[2]);
// Normals
if (hasNormals)
{
float normals[3];
if (paramData.vertexNormals)
{
getValues3(paramData.vertexNormals->getData(), paramData.vertexNormals->getType(), segStart, normals);
}
else if (paramData.primitiveNormals)
{
getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normals);
}
tempArrays->NormalsArray.push_back(normals[0]);
tempArrays->NormalsArray.push_back(normals[1]);
tempArrays->NormalsArray.push_back(normals[2]);
}
// Radii
if (hasRadii)
{
float radii;
if (paramData.vertexRadii)
{
getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), segStart, &radii);
}
else if (paramData.primitiveRadii)
{
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &radii);
}
tempArrays->ScalesArray.push_back(radii);
}
// Colors
if (hasColors)
{
size_t destIdx = tempArrays->expandColorsArray(1);
if (paramData.vertexColors)
{
tempArrays->copyToColorsArray(paramData.vertexColors->getData(), segStart, destIdx, 1);
}
else if (paramData.primitiveColors)
{
tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, destIdx, 1);
}
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
size_t srcIdx = attributeArray[attribIdx].PerPrimData ? primIdx : segStart;
size_t destIdx = tempArrays->expandAttributeDataArray(attribIdx, 1);
tempArrays->copyToAttributeDataArray(attribIdx, srcIdx, destIdx, 1);
}
}
#define PUSH_VERTEX(x, y) \
pushVertex(paramData, attributeArray, tempArrays, \
vertices, vertexType, \
hasNormals, hasColors, hasRadii, \
x, y)
void reorderCurveGeometry(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
const UsdDataArray* vertexArray = paramData.vertexPositions;
uint64_t numVertices = vertexArray->getLayout().numItems1;
const void* vertices = vertexArray->getData();
ANARIDataType vertexType = vertexArray->getType();
const UsdDataArray* indexArray = paramData.indices;
uint64_t numSegments = indexArray ? indexArray->getLayout().numItems1 : numVertices-1;
const void* indices = indexArray ? indexArray->getData() : nullptr;
ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32;
uint64_t maxNumVerts = numSegments*2;
tempArrays->CurveLengths.resize(0);
tempArrays->PointsArray.resize(0);
tempArrays->PointsArray.reserve(maxNumVerts * 3); // Conservative max number of points
bool hasNormals = paramData.vertexNormals || paramData.primitiveNormals;
if (hasNormals)
{
tempArrays->NormalsArray.resize(0);
tempArrays->NormalsArray.reserve(maxNumVerts * 3);
}
bool hasColors = paramData.vertexColors || paramData.primitiveColors;
if (hasColors)
{
tempArrays->resetColorsArray(0, paramData.vertexColors ? paramData.vertexColors->getType() : paramData.primitiveColors->getType());
tempArrays->reserveColorsArray(maxNumVerts);
}
bool hasRadii = paramData.vertexRadii || paramData.primitiveRadii;
if (hasRadii)
{
tempArrays->ScalesArray.resize(0);
tempArrays->ScalesArray.reserve(maxNumVerts);
}
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, 0);
tempArrays->reserveAttributeDataArray(attribIdx, maxNumVerts);
}
size_t prevSegEnd = 0;
int curveLength = 0;
for (size_t primIdx = 0; primIdx < numSegments; ++primIdx)
{
size_t segStart = indices ? getIndex(indices, indexType, primIdx) : primIdx;
if (primIdx != 0 && prevSegEnd != segStart)
{
PUSH_VERTEX(prevSegEnd, primIdx - 1);
curveLength += 1;
tempArrays->CurveLengths.push_back(curveLength);
curveLength = 0;
}
assert(segStart+1 < numVertices); // begin and end vertex should be in range
PUSH_VERTEX(segStart, primIdx);
curveLength += 1;
prevSegEnd = segStart + 1;
}
if (curveLength != 0)
{
PUSH_VERTEX(prevSegEnd, numSegments - 1);
curveLength += 1;
tempArrays->CurveLengths.push_back(curveLength);
}
}
template<typename T>
void setInstancerDataArray(const char* arrayName, const UsdDataArray* vertArray, const UsdDataArray* primArray, const std::vector<T>& tmpArray, UsdBridgeType tmpArrayType,
void const*& instancerDataArray, UsdBridgeType& instancerDataArrayType, const UsdGeometryData& paramData, const UsdGeometryDebugData& dbgData)
{
// Normals
if (paramData.indices && tmpArray.size())
{
instancerDataArray = tmpArray.data();
instancerDataArrayType = tmpArrayType;
}
else
{
const UsdDataArray* normals = vertArray;
if (normals)
{
instancerDataArray = normals->getData();
instancerDataArrayType = AnariToUsdBridgeType(normals->getType());
}
else if(primArray)
{
dbgData.device->reportStatus(dbgData.geometry, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdGeometry '%s' primitive.%s not transferred: per-primitive arrays provided without setting primitive.index", dbgData.debugName, arrayName);
}
}
}
}
UsdGeometry::UsdGeometry(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_GEOMETRY, name, device)
{
bool createTempArrays = false;
geomType = GetGeomType(type);
if(isInstanced() || geomType == GEOM_CURVE)
createTempArrays = true;
if(geomType == GEOM_UNKNOWN)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' construction failed: type %s not supported", getName(), type);
if(createTempArrays)
tempArrays = std::make_unique<UsdGeometryTempArrays>(attributeArray);
}
UsdGeometry::~UsdGeometry()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGeometry(usdHandle);
#endif
}
void UsdGeometry::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteGeometry);
}
void UsdGeometry::filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if(geomType == GEOM_GLYPH && strEquals(name, "shapeType") || strEquals(name, "shapeGeometry") || strEquals(name, "shapeTransform"))
protoShapeChanged = true;
if(usdHandle.value && strEquals(name, "usd::useUsdGeomPoints"))
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' filterSetParam failed: 'usd::useUsdGeomPoints' parameter cannot be changed after the first commit", getName());
return;
}
BridgedBaseObjectType::filterSetParam(name, type, mem, device);
}
template<typename GeomDataType>
void UsdGeometry::setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying)
{
typedef typename GeomDataType::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
static constexpr int attribStartBit = static_cast<int>(UsdGeometryComponents::ATTRIBUTE0);
for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx)
{
DMI attributeId = DMI::ATTRIBUTE0 + attribIdx;
timeVarying = timeVarying &
(isBitSet(paramData.timeVarying, attribStartBit+(int)attribIdx) ? DMI::ALL : ~attributeId);
}
}
void UsdGeometry::syncAttributeArrays()
{
const UsdGeometryData& paramData = getReadParams();
// Find the max index of the last attribute that still contains an array
int attribCount = 0;
for(int i = 0; i < MAX_ATTRIBS; ++i)
{
if(paramData.primitiveAttributes[i] != nullptr || paramData.vertexAttributes[i] != nullptr)
attribCount = i+1;
}
// Set the attribute arrays and related info, resize temporary attribute array data for reordering
if(attribCount)
{
attributeArray.resize(attribCount);
for(int i = 0; i < attribCount; ++i)
{
const UsdDataArray* attribArray = paramData.vertexAttributes[i] ? paramData.vertexAttributes[i] : paramData.primitiveAttributes[i];
if (attribArray)
{
attributeArray[i].Data = attribArray->getData();
attributeArray[i].DataType = AnariToUsdBridgeType(attribArray->getType());
attributeArray[i].PerPrimData = paramData.vertexAttributes[i] ? false : true;
attributeArray[i].EltSize = static_cast<uint32_t>(anari::sizeOf(attribArray->getType()));
attributeArray[i].Name = UsdSharedString::c_str(paramData.attributeNames[i]);
}
else
{
attributeArray[i].Data = nullptr;
attributeArray[i].DataType = UsdBridgeType::UNDEFINED;
}
}
if(tempArrays)
tempArrays->AttributeDataArrays.resize(attribCount);
}
}
template<typename GeomDataType>
void UsdGeometry::copyAttributeArraysToData(GeomDataType& geomData)
{
geomData.Attributes = attributeArray.data();
geomData.NumAttributes = static_cast<uint32_t>(attributeArray.size());
}
void UsdGeometry::assignTempDataToAttributes(bool perPrimInterpolation)
{
const AttributeDataArraysType& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attributeArray.size() == attribDataArrays.size());
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(attribDataArrays[attribIdx].size()) // Always > 0 if attributeArray[attribIdx].Data is set
attributeArray[attribIdx].Data = attribDataArrays[attribIdx].data();
attributeArray[attribIdx].PerPrimData = perPrimInterpolation; // Already converted to per-vertex (or per-prim)
}
}
void UsdGeometry::initializeGeomData(UsdBridgeMeshData& geomData)
{
typedef UsdBridgeMeshData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INDICES);
setAttributeTimeVarying<UsdBridgeMeshData>(geomData.TimeVarying);
geomData.FaceVertexCount = geomType == GEOM_QUAD ? 4 : 3;
}
void UsdGeometry::initializeGeomData(UsdBridgeInstancerData& geomData)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (( ((geomType == GEOM_CYLINDER || geomType == GEOM_CONE)
&& (isTimeVarying(CType::NORMAL) || isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX)))
|| ((geomType == GEOM_GLYPH) && isTimeVarying(CType::ORIENTATION))
) ? DMI::ALL : ~DMI::ORIENTATIONS)
& (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES)
& (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INVISIBLEIDS)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& (isTimeVarying(CType::ID) ? DMI::ALL : ~DMI::INSTANCEIDS)
& ~DMI::SHAPEINDICES; // Shapeindices are always the same, and USD clients typically do not support timevarying shapes
setAttributeTimeVarying<UsdBridgeInstancerData>(geomData.TimeVarying);
geomData.UseUsdGeomPoints = geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints;
}
void UsdGeometry::initializeGeomData(UsdBridgeCurveData& geomData)
{
typedef UsdBridgeCurveData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
// Turn off what is not timeVarying
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS)
& (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& ((isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX)) ? DMI::ALL : ~DMI::CURVELENGTHS);
setAttributeTimeVarying<UsdBridgeCurveData>(geomData.TimeVarying);
}
void UsdGeometry::initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData)
{
const UsdGeometryData& paramData = getReadParams();
// The anari side currently only supports only one shape, so just set DefaultShape
bool isGlyph = geomType == GEOM_GLYPH;
if(isGlyph && paramData.shapeGeometry)
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_MESH;
else
{
UsdGeometry::GeomType defaultShape = (isGlyph && paramData.shapeType) ? GetGeomType(paramData.shapeType->c_str()) : geomType;
switch (defaultShape)
{
case GEOM_CYLINDER:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CYLINDER;
break;
case GEOM_CONE:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CONE;
break;
default:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_SPHERE;
break;
};
}
geomRefData.ShapeTransform = paramData.shapeTransform;
}
bool UsdGeometry::checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray,
const char* paramName, UsdDevice* device, const char* debugName, int attribIndex)
{
const UsdGeometryData& paramData = getReadParams();
UsdLogInfo logInfo(device, this, ANARI_GEOMETRY, debugName);
const UsdDataArray* vertices = paramData.vertexPositions;
const UsdDataLayout& vertLayout = vertices->getLayout();
const UsdDataArray* indices = paramData.indices;
const UsdDataLayout& indexLayout = indices ? indices->getLayout() : vertLayout;
const UsdDataLayout& perVertLayout = vertexArray ? vertexArray->getLayout() : vertLayout;
const UsdDataLayout& perPrimLayout = primArray ? primArray->getLayout() : indexLayout;
const UsdDataLayout& attrLayout = vertexArray ? perVertLayout : perPrimLayout;
if (!AssertOneDimensional(attrLayout, logInfo, paramName)
|| !AssertNoStride(attrLayout, logInfo, paramName)
)
{
return false;
}
if (vertexArray && vertexArray->getLayout().numItems1 < vertLayout.numItems1)
{
if(attribIndex == -1)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.X' array elements should at least be the size of vertex.positions", debugName);
else
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.attribute%i' array elements should at least be the size of vertex.positions", debugName, attribIndex);
return false;
}
uint64_t numPrims = GetNumberOfPrims(indices, indexLayout, geomType);
if (primArray && primArray->getLayout().numItems1 < numPrims)
{
if(attribIndex == -1)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.X' array too small", debugName);
else
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.attribute%i' array too small", debugName, attribIndex);
return false;
}
return true;
}
bool UsdGeometry::checkGeomParams(UsdDevice* device)
{
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
bool success = true;
success = success && checkArrayConstraints(paramData.vertexPositions, nullptr, "vertex.position", device, debugName);
success = success && checkArrayConstraints(nullptr, paramData.indices, "primitive.index", device, debugName);
success = success && checkArrayConstraints(paramData.vertexNormals, paramData.primitiveNormals, "vertex/primitive.normal", device, debugName);
for(int i = 0; i < MAX_ATTRIBS; ++i)
success = success && checkArrayConstraints(paramData.vertexAttributes[i], paramData.primitiveAttributes[i], "vertex/primitive.attribute", device, debugName, i);
success = success && checkArrayConstraints(paramData.vertexColors, paramData.primitiveColors, "vertex/primitive.color", device, debugName);
success = success && checkArrayConstraints(paramData.vertexRadii, paramData.primitiveRadii, "vertex/primitive.radius", device, debugName);
success = success && checkArrayConstraints(paramData.vertexScales, paramData.primitiveScales, "vertex/primitive.scale", device, debugName);
success = success && checkArrayConstraints(paramData.vertexOrientations, paramData.primitiveOrientations, "vertex/primitive.orientation", device, debugName);
success = success && checkArrayConstraints(nullptr, paramData.primitiveIds, "primitive.id", device, debugName);
if (!success)
return false;
ANARIDataType vertType = paramData.vertexPositions->getType();
if (vertType != ANARI_FLOAT32_VEC3 && vertType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex.position' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName);
return false;
}
if (paramData.indices)
{
ANARIDataType indexType = paramData.indices->getType();
UsdBridgeType flattenedType = AnariToUsdBridgeType_Flattened(indexType);
if( (geomType == GEOM_TRIANGLE || geomType == GEOM_QUAD) &&
(flattenedType == UsdBridgeType::UINT || flattenedType == UsdBridgeType::ULONG || flattenedType == UsdBridgeType::LONG))
{
static bool reported = false; // Hardcode this to show only once to make sure developers get to see it, without spamming the console.
if(!reported)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' has 'primitive.index' of type other than ANARI_INT32, which may result in an overflow for FaceVertexIndicesAttr of UsdGeomMesh.", debugName);
reported = true;
}
}
if (geomType == GEOM_SPHERE || geomType == GEOM_CURVE || geomType == GEOM_GLYPH)
{
if(geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' is a sphere geometry with indices, but the usd::useUsdGeomPoints parameter is not set, so all vertices will show as spheres.", debugName);
if (indexType != ANARI_INT32 && indexType != ANARI_UINT32 && indexType != ANARI_INT64 && indexType != ANARI_UINT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT32/64.", debugName);
return false;
}
}
else if (geomType == GEOM_CYLINDER || geomType == GEOM_CONE)
{
if (indexType != ANARI_UINT32_VEC2 && indexType != ANARI_INT32_VEC2 && indexType != ANARI_UINT64_VEC2 && indexType != ANARI_INT64_VEC2)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC2.", debugName);
return false;
}
}
else if (geomType == GEOM_TRIANGLE)
{
if (indexType != ANARI_UINT32_VEC3 && indexType != ANARI_INT32_VEC3 && indexType != ANARI_UINT64_VEC3 && indexType != ANARI_INT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC3.", debugName);
return false;
}
}
else if (geomType == GEOM_QUAD)
{
if (indexType != ANARI_UINT32_VEC4 && indexType != ANARI_INT32_VEC4 && indexType != ANARI_UINT64_VEC4 && indexType != ANARI_INT64_VEC4)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC4.", debugName);
return false;
}
}
}
const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals;
if (normals)
{
ANARIDataType arrayType = normals->getType();
if (arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.normal' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName);
return false;
}
}
const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors;
if (colors)
{
ANARIDataType arrayType = colors->getType();
if ((int)arrayType < (int)ANARI_INT8 || (int)arrayType > (int)ANARI_UFIXED8_R_SRGB)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.color' parameter should be of Color type (see ANARI standard)", debugName);
return false;
}
}
const UsdDataArray* radii = paramData.vertexRadii ? paramData.vertexRadii : paramData.primitiveRadii;
if (radii)
{
ANARIDataType arrayType = radii->getType();
if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.radius' parameter should be of type ANARI_FLOAT32 or ANARI_FLOAT64.", debugName);
return false;
}
}
const UsdDataArray* scales = paramData.vertexScales ? paramData.vertexScales : paramData.primitiveScales;
if (scales)
{
ANARIDataType arrayType = scales->getType();
if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64 && arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.scale' parameter should be of type ANARI_FLOAT32(_VEC3) or ANARI_FLOAT64(_VEC3).", debugName);
return false;
}
}
const UsdDataArray* orientations = paramData.vertexOrientations ? paramData.vertexOrientations : paramData.primitiveOrientations;
if (orientations)
{
ANARIDataType arrayType = orientations->getType();
if (arrayType != ANARI_FLOAT32_QUAT_IJKW)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.orientation' parameter should be of type ANARI_FLOAT32_QUAT_IJKW.", debugName);
return false;
}
}
if (paramData.primitiveIds)
{
ANARIDataType idType = paramData.primitiveIds->getType();
if (idType != ANARI_INT32 && idType != ANARI_UINT32 && idType != ANARI_INT64 && idType != ANARI_UINT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.id' parameter should be of type ANARI_(U)INT or ANARI_(U)LONG.", debugName);
return false;
}
}
return true;
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
const UsdDataArray* vertices = paramData.vertexPositions;
meshData.NumPoints = vertices->getLayout().numItems1;
meshData.Points = vertices->getData();
meshData.PointsType = AnariToUsdBridgeType(vertices->getType());
const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals;
if (normals)
{
meshData.Normals = normals->getData();
meshData.NormalsType = AnariToUsdBridgeType(normals->getType());
meshData.PerPrimNormals = paramData.vertexNormals ? false : true;
}
const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors;
if (colors)
{
meshData.Colors = colors->getData();
meshData.ColorsType = AnariToUsdBridgeType(colors->getType());
meshData.PerPrimColors = paramData.vertexColors ? false : true;
}
const UsdDataArray* indices = paramData.indices;
if (indices)
{
ANARIDataType indexType = indices->getType();
meshData.NumIndices = indices->getLayout().numItems1 * anari::componentsOf(indexType);
meshData.Indices = indices->getData();
meshData.IndicesType = AnariToUsdBridgeType_Flattened(indexType);
}
else
{
meshData.NumIndices = meshData.NumPoints; // Vertices are implicitly indexed consecutively (FaceVertexCount determines how many prims)
}
//meshData.UpdatesToPerform = Still to be implemented
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, meshData, dataTimeStep);
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
if (geomType == GEOM_SPHERE || geomType == GEOM_GLYPH)
{
// A paramData.indices (primitive-indexed spheres) array, is not supported in USD, also duplicate spheres make no sense.
// Instead, Ids/InvisibleIds are assigned to emulate sparsely indexed spheres (sourced from paramData.primitiveIds if available),
// with the per-vertex arrays remaining intact. Any per-prim arrays are explicitly converted to per-vertex via the tempArrays.
generateIndexedSphereData(paramData, attributeArray, tempArrays.get());
const UsdDataArray* vertices = paramData.vertexPositions;
instancerData.NumPoints = vertices->getLayout().numItems1;
instancerData.Points = vertices->getData();
instancerData.PointsType = AnariToUsdBridgeType(vertices->getType());
UsdGeometryDebugData dbgData = { device, this, debugName };
// Orientations
// are a bit extended beyond the spec: even spheres can set them, and the use of normals is also supported
if(paramData.vertexOrientations || paramData.primitiveOrientations)
{
setInstancerDataArray("orientation", paramData.vertexOrientations, paramData.primitiveOrientations, tempArrays->OrientationsArray, UsdBridgeType::FLOAT4,
instancerData.Orientations, instancerData.OrientationsType,
paramData, dbgData);
}
else
{
setInstancerDataArray("normal", paramData.vertexNormals, paramData.primitiveNormals, tempArrays->NormalsArray, UsdBridgeType::FLOAT3,
instancerData.Orientations, instancerData.OrientationsType,
paramData, dbgData);
}
// Scales
if(geomType == GEOM_SPHERE)
{
setInstancerDataArray("radius", paramData.vertexRadii, paramData.primitiveRadii,
tempArrays->RadiiArray, UsdBridgeType::FLOAT,
instancerData.Scales, instancerData.ScalesType,
paramData, dbgData);
}
else
{
size_t numTmpScales = tempArrays->ScalesArray.size();
bool scalarScale = (numTmpScales == instancerData.NumPoints);
assert(!numTmpScales || scalarScale || numTmpScales == instancerData.NumPoints*3);
setInstancerDataArray("scale", paramData.vertexScales, paramData.primitiveScales,
tempArrays->ScalesArray, scalarScale ? UsdBridgeType::FLOAT : UsdBridgeType::FLOAT3,
instancerData.Scales, instancerData.ScalesType,
paramData, dbgData);
}
// Colors
setInstancerDataArray("color", paramData.vertexColors, paramData.primitiveColors,
tempArrays->ColorsArray, AnariToUsdBridgeType(tempArrays->ColorsArrayType),
instancerData.Colors, instancerData.ColorsType,
paramData, dbgData);
// Attributes
// By default, syncAttributeArrays and initializeGeomData already set up instancerData.Attributes
// Just set attributeArray's data to tempArrays where necessary
if(paramData.indices)
{
// Type remains the same, everything per-vertex (as explained above)
assignTempDataToAttributes(false);
}
else
{
// Check whether any perprim attributes exist
for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx)
{
if(attributeArray[attribIdx].Data && attributeArray[attribIdx].PerPrimData)
{
attributeArray[attribIdx].Data = nullptr;
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdGeometry '%s' primitive.attribute%i not transferred: per-primitive arrays provided without setting primitive.index", debugName, static_cast<int>(attribIdx));
}
}
}
// Ids
if (paramData.indices && tempArrays->IdsArray.size())
{
instancerData.InstanceIds = tempArrays->IdsArray.data();
instancerData.InstanceIdsType = UsdBridgeType::LONG;
}
else
{
const UsdDataArray* ids = paramData.primitiveIds;
if (ids)
{
instancerData.InstanceIds = ids->getData();
instancerData.InstanceIdsType = AnariToUsdBridgeType(ids->getType());
}
}
// Invisible Ids
if (paramData.indices && tempArrays->InvisIdsArray.size())
{
instancerData.InvisibleIds = tempArrays->InvisIdsArray.data();
instancerData.InvisibleIdsType = UsdBridgeType::LONG;
instancerData.NumInvisibleIds = tempArrays->InvisIdsArray.size();
}
for(int i = 0; i < 3; ++i)
instancerData.Scale.Data[i] = (geomType == GEOM_SPHERE) ? paramData.radiusConstant : paramData.scaleConstant.Data[i];
instancerData.Orientation = paramData.orientationConstant;
}
else
{
convertLinesToSticks(paramData, attributeArray, tempArrays.get());
instancerData.NumPoints = tempArrays->PointsArray.size()/3;
if (instancerData.NumPoints > 0)
{
instancerData.Points = tempArrays->PointsArray.data();
instancerData.PointsType = UsdBridgeType::FLOAT3;
instancerData.Scales = tempArrays->ScalesArray.data();
instancerData.ScalesType = UsdBridgeType::FLOAT3;
instancerData.Orientations = tempArrays->OrientationsArray.data();
instancerData.OrientationsType = UsdBridgeType::FLOAT4;
// Colors
if (tempArrays->ColorsArray.size())
{
instancerData.Colors = tempArrays->ColorsArray.data();
instancerData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType);
}
else if(const UsdDataArray* colors = paramData.primitiveColors)
{ // Per-primitive color array corresponds to per-vertex stick output
instancerData.Colors = colors->getData();
instancerData.ColorsType = AnariToUsdBridgeType(colors->getType());
}
// Attributes
assignTempDataToAttributes(false);
// Ids
if (tempArrays->IdsArray.size())
{
instancerData.InstanceIds = tempArrays->IdsArray.data();
instancerData.InstanceIdsType = UsdBridgeType::LONG;
}
}
}
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, instancerData, dataTimeStep);
if(isNew && geomType != GEOM_GLYPH && !instancerData.UseUsdGeomPoints)
commitPrototypes(usdBridge); // Also initialize the prototype shape on the instancer geom
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
reorderCurveGeometry(paramData, attributeArray, tempArrays.get());
curveData.NumPoints = tempArrays->PointsArray.size() / 3;
if (curveData.NumPoints > 0)
{
curveData.Points = tempArrays->PointsArray.data();
curveData.PointsType = UsdBridgeType::FLOAT3;
curveData.CurveLengths = tempArrays->CurveLengths.data();
curveData.NumCurveLengths = tempArrays->CurveLengths.size();
if (tempArrays->NormalsArray.size())
{
curveData.Normals = tempArrays->NormalsArray.data();
curveData.NormalsType = UsdBridgeType::FLOAT3;
}
curveData.PerPrimNormals = false;// Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless
// Attributes
assignTempDataToAttributes(false);
// Copy colors
if (tempArrays->ColorsArray.size())
{
curveData.Colors = tempArrays->ColorsArray.data();
curveData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType);
}
curveData.PerPrimColors = false; // Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless
// Assign scales
if (tempArrays->ScalesArray.size())
{
curveData.Scales = tempArrays->ScalesArray.data();
curveData.ScalesType = UsdBridgeType::FLOAT;
}
curveData.UniformScale = paramData.radiusConstant;
}
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, curveData, dataTimeStep);
}
template<typename UsdGeomType>
bool UsdGeometry::commitTemplate(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
UsdGeomType geomData;
syncAttributeArrays();
initializeGeomData(geomData);
copyAttributeArraysToData(geomData);
bool isNew = false;
if (!usdHandle.value)
{
isNew = usdBridge->CreateGeometry(debugName, usdHandle, geomData);
}
if (paramChanged || isNew)
{
if (paramData.vertexPositions)
{
if(checkGeomParams(device))
updateGeomData(device, usdBridge, geomData, isNew);
}
else
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: missing 'vertex.position'.", debugName);
}
paramChanged = false;
}
return isNew;
}
void UsdGeometry::commitPrototypes(UsdBridge* usdBridge)
{
UsdBridgeInstancerRefData instancerRefData;
initializeGeomRefData(instancerRefData);
usdBridge->SetPrototypeData(usdHandle, instancerRefData);
}
bool UsdGeometry::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdGeometry::doCommitData(UsdDevice* device)
{
if(geomType == GEOM_UNKNOWN)
return false;
bool isNew = false;
switch (geomType)
{
case GEOM_TRIANGLE: isNew = commitTemplate<UsdBridgeMeshData>(device); break;
case GEOM_QUAD: isNew = commitTemplate<UsdBridgeMeshData>(device); break;
case GEOM_SPHERE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CYLINDER: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CONE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_GLYPH: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CURVE: isNew = commitTemplate<UsdBridgeCurveData>(device); break;
default: break;
}
return geomType == GEOM_GLYPH && (isNew || protoShapeChanged); // Defer commit of prototypes until the geometry refs are in place
}
void UsdGeometry::doCommitRefs(UsdDevice* device)
{
assert(geomType == GEOM_GLYPH && protoShapeChanged);
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGeometryData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.shapeGeometry)
{
double geomObjTimeStep = paramData.shapeGeometry->getReadParams().timeStep;
UsdGeometryHandle protoGeomHandle = paramData.shapeGeometry->getUsdHandle();
size_t numHandles = 1;
double protoTimestep = selectRefTime(paramData.shapeGeometryRefTimeStep, geomObjTimeStep, worldTimeStep);
usdBridge->SetPrototypeRefs(usdHandle,
&protoGeomHandle,
numHandles,
worldTimeStep,
&protoTimestep
);
}
else
{
usdBridge->DeletePrototypeRefs(usdHandle, worldTimeStep);
}
// Now set the prototype relations to the reference paths (Bridge uses paths from SetPrototypeRefs)
commitPrototypes(usdBridge);
protoShapeChanged = false;
}
| 56,898 | C++ | 38.431046 | 265 | 0.704049 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGroup.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdGroup.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#define SurfaceType ANARI_SURFACE
#define VolumeType ANARI_VOLUME
using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type;
using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type;
DEFINE_PARAMETER_MAP(UsdGroup,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces)
REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes)
)
constexpr UsdGroup::ComponentPair UsdGroup::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdGroup::UsdGroup(const char* name,
UsdDevice* device)
: BridgedBaseObjectType(ANARI_GROUP, name, device)
{
}
UsdGroup::~UsdGroup()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGroup(usdHandle);
#endif
}
void UsdGroup::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteGroup);
}
bool UsdGroup::deferCommit(UsdDevice* device)
{
const UsdGroupData& paramData = getReadParams();
if(UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) ||
UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes))
{
return true;
}
return false;
}
bool UsdGroup::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateGroup(getName(), usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdGroup::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGroupData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
UsdLogInfo logInfo(device, this, ANARI_GROUP, this->getName());
bool surfacesTimeVarying = isTimeVarying(UsdGroupComponents::SURFACES);
bool volumesTimeVarying = isTimeVarying(UsdGroupComponents::VOLUMES);
ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep,
surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE");
ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep,
volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME");
} | 2,925 | C++ | 30.462365 | 126 | 0.764103 |
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
class UsdRenderer;
class UsdWorld;
struct UsdFrameData
{
UsdWorld* world = nullptr;
UsdRenderer* renderer = nullptr;
UsdUint2 size = {0, 0};
ANARIDataType color = ANARI_UNKNOWN;
ANARIDataType depth = ANARI_UNKNOWN;
};
class UsdFrame : public UsdParameterizedBaseObject<UsdFrame, UsdFrameData>
{
public:
UsdFrame(UsdBridge* bridge);
~UsdFrame();
void remove(UsdDevice* device) override {}
const void* mapBuffer(const char* channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType);
void unmapBuffer(const char* channel);
void saveUsd(UsdDevice* device);
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
char* ReserveBuffer(ANARIDataType format);
char* mappedColorMem = nullptr;
char* mappedDepthMem = nullptr;
};
| 1,070 | C | 21.787234 | 74 | 0.718692 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdCamera.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
DEFINE_PARAMETER_MAP(UsdCamera,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("position", ANARI_FLOAT32_VEC3, position)
REGISTER_PARAMETER_MACRO("direction", ANARI_FLOAT32_VEC3, direction)
REGISTER_PARAMETER_MACRO("up", ANARI_FLOAT32_VEC3, up)
REGISTER_PARAMETER_MACRO("imageRegion", ANARI_FLOAT32_BOX2, imageRegion)
REGISTER_PARAMETER_MACRO("aspect", ANARI_FLOAT32, aspect)
REGISTER_PARAMETER_MACRO("near", ANARI_FLOAT32, near)
REGISTER_PARAMETER_MACRO("far", ANARI_FLOAT32, far)
REGISTER_PARAMETER_MACRO("fovy", ANARI_FLOAT32, fovy)
REGISTER_PARAMETER_MACRO("height", ANARI_FLOAT32, height)
)
constexpr UsdCamera::ComponentPair UsdCamera::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdCamera::UsdCamera(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_CAMERA, name, device)
{
if(strEquals(type, "perspective"))
cameraType = CAMERA_PERSPECTIVE;
else if(strEquals(type, "orthographic"))
cameraType = CAMERA_ORTHOGRAPHIC;
}
UsdCamera::~UsdCamera()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGroup(usdHandle);
#endif
}
void UsdCamera::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteCamera);
}
bool UsdCamera::deferCommit(UsdDevice* device)
{
return false;
}
void UsdCamera::copyParameters(UsdBridgeCameraData& camData)
{
typedef UsdBridgeCameraData::DataMemberId DMI;
const UsdCameraData& paramData = getReadParams();
camData.Position = paramData.position;
camData.Direction = paramData.direction;
camData.Up = paramData.up;
camData.ImageRegion = paramData.imageRegion;
camData.Aspect = paramData.aspect;
camData.Near = paramData.near;
camData.Far = paramData.far;
camData.Fovy = paramData.fovy;
camData.Height = paramData.height;
camData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::VIEW) ? DMI::ALL : ~DMI::VIEW)
& (isTimeVarying(CType::PROJECTION) ? DMI::ALL : ~DMI::PROJECTION);
}
bool UsdCamera::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdCameraData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateCamera(getName(), usdHandle);
if (paramChanged || isNew)
{
UsdBridgeCameraData camData;
copyParameters(camData);
usdBridge->SetCameraData(usdHandle, camData, timeStep);
paramChanged = false;
}
return false;
} | 2,864 | C++ | 29.478723 | 128 | 0.745461 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBaseObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "helium/utility/IntrusivePtr.h"
#include "UsdCommonMacros.h"
#include "UsdParameterizedObject.h"
class UsdDevice;
// Base parameterized class without being derived as such - nontemplated to allow for polymorphic use
class UsdBaseObject : public helium::RefCounted
{
public:
// If device != 0, the object is added to the commit list
UsdBaseObject(ANARIDataType t, UsdDevice* device = nullptr);
virtual void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) = 0;
virtual void filterResetParam(
const char *name) = 0;
virtual void resetAllParams() = 0;
virtual void* getParameter(const char* name, ANARIDataType& returnType) = 0;
virtual int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) = 0;
virtual void commit(UsdDevice* device) = 0;
virtual void remove(UsdDevice* device) = 0; // Remove any committed data and refs
ANARIDataType getType() const { return type; }
protected:
virtual bool deferCommit(UsdDevice* device) = 0; // Returns whether data commit has to be deferred
virtual bool doCommitData(UsdDevice* device) = 0; // Data commit, execution can be immediate, returns whether doCommitRefs has to be performed
virtual void doCommitRefs(UsdDevice* device) = 0; // For updates with dependencies on referenced object's data, is always executed deferred
ANARIDataType type;
friend class UsdDevice;
};
// Templated base implementation of parameterized object
template<typename T, typename D>
class UsdParameterizedBaseObject : public UsdBaseObject, public UsdParameterizedObject<T, D>
{
public:
typedef UsdParameterizedObject<T, D> ParamClass;
UsdParameterizedBaseObject(ANARIDataType t, UsdDevice* device = nullptr)
: UsdBaseObject(t, device)
{}
void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override
{
ParamClass::setParam(name, type, mem, device);
}
void filterResetParam(
const char *name) override
{
ParamClass::resetParam(name);
}
void resetAllParams() override
{
ParamClass::resetParams();
}
void* getParameter(const char* name, ANARIDataType& returnType) override
{
return ParamClass::getParam(name, returnType);
}
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override
{
return 0;
}
void commit(UsdDevice* device) override
{
ParamClass::transferWriteToReadParams();
UsdBaseObject::commit(device);
}
// Convenience functions for commonly used name property
virtual const char* getName() const { return ""; }
protected:
// Convenience functions for commonly used name property
bool setNameParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
const char* objectName = static_cast<const char*>(mem);
if (type == ANARI_STRING)
{
if (strEquals(name, "name"))
{
if (!objectName || strEquals(objectName, ""))
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s: ANARI object %s cannot be an empty string, using auto-generated name instead.", getName(), "name");
}
else
{
ParamClass::setParam(name, type, mem, device);
ParamClass::setParam("usd::name", type, mem, device);
this->formatUsdName(this->getWriteParams().usdName);
}
return true;
}
else if (strEquals(name, "usd::name"))
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s parameter '%s' cannot be set, only read with getProperty().", getName(), "usd::name");
return true;
}
}
return false;
}
int getNameProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device)
{
if (type == ANARI_STRING && strEquals(name, "usd::name"))
{
snprintf((char*)mem, size, "%s", UsdSharedString::c_str(this->getReadParams().usdName));
return 1;
}
else if (type == ANARI_UINT64 && strEquals(name, "usd::name.size"))
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(device, this, ANARI_ARRAY, this->getName()), "usd::name.size"))
{
uint64_t nameLen = this->getReadParams().usdName ? strlen(this->getReadParams().usdName->c_str())+1 : 0;
memcpy(mem, &nameLen, size);
}
return 1;
}
return 0;
}
}; | 5,007 | C | 29.168675 | 146 | 0.641901 |
NVIDIA-Omniverse/AnariUsdDevice/UsdAnari.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgeData.h"
#include "UsdCommonMacros.h"
#include "anari/frontend/anari_enums.h"
#include "anari/anari_cpp/Traits.h"
#include <cstring>
class UsdDevice;
class UsdDataArray;
class UsdFrame;
class UsdGeometry;
class UsdGroup;
class UsdInstance;
class UsdLight;
class UsdMaterial;
class UsdRenderer;
class UsdSurface;
class UsdSampler;
class UsdSpatialField;
class UsdVolume;
class UsdWorld;
class UsdCamera;
class UsdSharedString;
class UsdBaseObject;
struct UsdDataLayout;
namespace anari
{
ANARI_TYPEFOR_SPECIALIZATION(UsdUint2, ANARI_UINT32_VEC2);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat2, ANARI_FLOAT32_VEC2);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat3, ANARI_FLOAT32_VEC3);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat4, ANARI_FLOAT32_VEC4);
ANARI_TYPEFOR_SPECIALIZATION(UsdQuaternion, ANARI_FLOAT32_QUAT_IJKW);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatMat4, ANARI_FLOAT32_MAT4);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox1, ANARI_FLOAT32_BOX1);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox2, ANARI_FLOAT32_BOX2);
ANARI_TYPEFOR_SPECIALIZATION(UsdSharedString*, ANARI_STRING);
ANARI_TYPEFOR_SPECIALIZATION(UsdDataArray*, ANARI_ARRAY);
ANARI_TYPEFOR_SPECIALIZATION(UsdFrame*, ANARI_FRAME);
ANARI_TYPEFOR_SPECIALIZATION(UsdGeometry*, ANARI_GEOMETRY);
ANARI_TYPEFOR_SPECIALIZATION(UsdGroup*, ANARI_GROUP);
ANARI_TYPEFOR_SPECIALIZATION(UsdInstance*, ANARI_INSTANCE);
ANARI_TYPEFOR_SPECIALIZATION(UsdLight*, ANARI_LIGHT);
ANARI_TYPEFOR_SPECIALIZATION(UsdMaterial*, ANARI_MATERIAL);
ANARI_TYPEFOR_SPECIALIZATION(UsdRenderer*, ANARI_RENDERER);
ANARI_TYPEFOR_SPECIALIZATION(UsdSampler*, ANARI_SAMPLER);
ANARI_TYPEFOR_SPECIALIZATION(UsdSpatialField*, ANARI_SPATIAL_FIELD);
ANARI_TYPEFOR_SPECIALIZATION(UsdSurface*, ANARI_SURFACE);
ANARI_TYPEFOR_SPECIALIZATION(UsdVolume*, ANARI_VOLUME);
ANARI_TYPEFOR_SPECIALIZATION(UsdWorld*, ANARI_WORLD);
}
// Shared convenience functions
namespace
{
inline bool strEquals(const char* arg0, const char* arg1)
{
return strcmp(arg0, arg1) == 0;
}
template <typename T>
inline void writeToVoidP(void *_p, T v)
{
T *p = (T *)_p;
*p = v;
}
}
// Standard log info
struct UsdLogInfo
{
UsdLogInfo(UsdDevice* dev, void* src, ANARIDataType srcType, const char* srcName)
: device(dev)
, source(src)
, sourceType(srcType)
, sourceName(srcName)
{}
UsdDevice* device = nullptr;
void* source = nullptr;
ANARIDataType sourceType = ANARI_VOID_POINTER;
const char* sourceName = nullptr;
};
void reportStatusThroughDevice(const UsdLogInfo& logInfo, ANARIStatusSeverity severity, ANARIStatusCode statusCode,
const char *format, const char* firstArg, const char* secondArg); // In case #include <UsdDevice.h> is undesired
#ifdef CHECK_MEMLEAKS
void logAllocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType);
void logDeallocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType);
#endif
// Anari <=> USD conversions
UsdBridgeType AnariToUsdBridgeType(ANARIDataType anariType);
UsdBridgeType AnariToUsdBridgeType_Flattened(ANARIDataType anariType);
const char* AnariTypeToString(ANARIDataType anariType);
const char* AnariAttributeToUsdName(const char* param, bool perInstance, const UsdLogInfo& logInfo);
UsdBridgeMaterialData::AlphaModes AnariToUsdAlphaMode(const char* alphaMode);
ANARIStatusSeverity UsdBridgeLogLevelToAnariSeverity(UsdBridgeLogLevel level);
bool Assert64bitStringLengthProperty(uint64_t size, const UsdLogInfo& logInfo, const char* propName);
bool AssertOneDimensional(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName);
bool AssertNoStride(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName);
bool AssertArrayType(UsdDataArray* dataArray, ANARIDataType dataType, const UsdLogInfo& logInfo, const char* errorMessage);
// Template definitions
template<typename AnariType>
class AnariToUsdObject {};
template<int AnariType>
class AnariToUsdBridgedObject {};
template<int AnariType>
class AnariToUsdBaseObject {};
#define USDBRIDGE_DEFINE_OBJECT_MAPPING(AnariType, UsdType) \
template<>\
class AnariToUsdObject<AnariType>\
{\
public:\
using Type = UsdType;\
};
#define USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(AnariType, UsdType) \
template<>\
class AnariToUsdBaseObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};
#define USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(AnariType, UsdType)\
template<>\
class AnariToUsdBridgedObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};\
template<>\
class AnariToUsdBaseObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIObject, UsdBaseObject)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIDevice, UsdDevice)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray1D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray2D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray3D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIFrame, UsdFrame)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGeometry, UsdGeometry)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGroup, UsdGroup)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIInstance, UsdInstance)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARILight, UsdLight)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIMaterial, UsdMaterial)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISampler, UsdSampler)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISurface, UsdSurface)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIRenderer, UsdRenderer)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISpatialField, UsdSpatialField)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIVolume, UsdVolume)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIWorld, UsdWorld)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARICamera, UsdCamera)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_DEVICE, UsdDevice)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY1D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY2D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY3D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_FRAME, UsdFrame)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_RENDERER, UsdRenderer)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GEOMETRY, UsdGeometry)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GROUP, UsdGroup)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_INSTANCE, UsdInstance)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_LIGHT, UsdLight)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_MATERIAL, UsdMaterial)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SURFACE, UsdSurface)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SAMPLER, UsdSampler)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SPATIAL_FIELD, UsdSpatialField)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_VOLUME, UsdVolume)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_WORLD, UsdWorld)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_CAMERA, UsdCamera)
template<typename AnariType>
typename AnariToUsdObject<AnariType>::Type* AnariToUsdObjectPtr(AnariType object) { return (typename AnariToUsdObject<AnariType>::Type*) object; }
| 7,214 | C | 36.38342 | 146 | 0.804963 |
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdWorld.h"
#include "UsdAnari.h"
#include "UsdInstance.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include "UsdGroup.h"
#define InstanceType ANARI_INSTANCE
#define SurfaceType ANARI_SURFACE
#define VolumeType ANARI_VOLUME
using InstanceUsdType = AnariToUsdBridgedObject<InstanceType>::Type;
using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type;
using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type;
DEFINE_PARAMETER_MAP(UsdWorld,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("instance", ANARI_ARRAY, instances)
REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces)
REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes)
)
constexpr UsdWorld::ComponentPair UsdWorld::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdWorld::UsdWorld(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_WORLD, name, device)
{
}
UsdWorld::~UsdWorld()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteWorld(usdHandle);
#endif
}
void UsdWorld::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteWorld);
}
bool UsdWorld::deferCommit(UsdDevice* device)
{
const UsdWorldData& paramData = getReadParams();
if(UsdObjectNotInitialized<InstanceUsdType>(paramData.instances) ||
UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) ||
UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes))
{
return true;
}
return false;
}
bool UsdWorld::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const char* objName = getName();
bool isNew = false;
if(!usdHandle.value)
isNew = usdBridge->CreateWorld(objName, usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdWorld::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdWorldData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
const char* objName = getName();
bool instancesTimeVarying = isTimeVarying(UsdWorldComponents::INSTANCES);
bool surfacesTimeVarying = isTimeVarying(UsdWorldComponents::SURFACES);
bool volumesTimeVarying = isTimeVarying(UsdWorldComponents::VOLUMES);
UsdLogInfo logInfo(device, this, ANARI_WORLD, this->getName());
ManageRefArray<InstanceType, ANARIInstance, UsdInstance>(usdHandle, paramData.instances, instancesTimeVarying, timeStep,
instanceHandles, &UsdBridge::SetInstanceRefs, &UsdBridge::DeleteInstanceRefs,
usdBridge, logInfo, "UsdWorld commit failed: 'instance' array elements should be of type ANARI_INSTANCE");
ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep,
surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE");
ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep,
volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME");
} | 3,668 | C++ | 33.289719 | 126 | 0.771538 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSurface.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdMaterial.h"
#include "UsdGeometry.h"
#define GeometryType ANARI_GEOMETRY
#define MaterialType ANARI_MATERIAL
using GeometryUsdType = AnariToUsdBridgedObject<GeometryType>::Type;
using MaterialUsdType = AnariToUsdBridgedObject<MaterialType>::Type;
DEFINE_PARAMETER_MAP(UsdSurface,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time.geometry", ANARI_FLOAT64, geometryRefTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.material", ANARI_FLOAT64, materialRefTimeStep)
REGISTER_PARAMETER_MACRO("geometry", GeometryType, geometry)
REGISTER_PARAMETER_MACRO("material", MaterialType, material)
)
UsdSurface::UsdSurface(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SURFACE, name, device)
{
}
UsdSurface::~UsdSurface()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
// Given that the object is destroyed, none of its references to other objects
// has to be updated anymore.
if(cachedBridge)
cachedBridge->DeleteSurface(usdHandle);
#endif
}
void UsdSurface::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSurface);
}
bool UsdSurface::deferCommit(UsdDevice* device)
{
// Given that all handles/data are used in doCommitRefs, which is always executed deferred, we don't need to check for initialization
//const UsdSurfaceData& paramData = getReadParams();
//if(UsdObjectNotInitialized<GeometryUsdType>(paramData.geometry) || UsdObjectNotInitialized<MaterialUsdType>(paramData.material))
//{
// return true;
//}
return false;
}
bool UsdSurface::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateSurface(getName(), usdHandle);
if (paramChanged || isNew)
{
paramChanged = false;
return true; // In this case a doCommitRefs is required, with data (timesteps, handles) from children
}
return false;
}
void UsdSurface::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdSurfaceData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.geometry)
{
double geomObjTimeStep = paramData.geometry->getReadParams().timeStep;
if(device->getReadParams().outputMaterial && paramData.material)
{
double matObjTimeStep = paramData.material->getReadParams().timeStep;
// The geometry to which a material binds has an effect on attribute reader (geom primvar) names, and output types
paramData.material->updateBoundParameters(paramData.geometry->isInstanced(), device);
usdBridge->SetGeometryMaterialRef(usdHandle,
paramData.geometry->getUsdHandle(),
paramData.material->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep),
selectRefTime(paramData.materialRefTimeStep, matObjTimeStep, worldTimeStep)
);
}
else
{
usdBridge->SetGeometryRef(usdHandle,
paramData.geometry->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep)
);
usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep);
}
}
else
{
usdBridge->DeleteGeometryRef(usdHandle, worldTimeStep);
if (!paramData.material && device->getReadParams().outputMaterial)
{
usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep);
}
}
} | 3,776 | C++ | 30.475 | 135 | 0.739142 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCommonMacros.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridge/Common/UsdBridgeMacros.h"
//#define OBJECT_LIFETIME_EQUALS_USD_LIFETIME
#ifndef NDEBUG
// This is now handled in CMake
//#define CHECK_MEMLEAKS //asserts at ~UsdDevice() if memleak found
#endif
| 306 | C | 20.92857 | 67 | 0.761438 |
NVIDIA-Omniverse/AnariUsdDevice/UsdVolume.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdVolume.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdSpatialField.h"
#include "UsdDataArray.h"
DEFINE_PARAMETER_MAP(UsdVolume,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::preClassified", ANARI_BOOL, preClassified)
REGISTER_PARAMETER_MACRO("usd::time.value", ANARI_FLOAT64, fieldRefTimeStep)
REGISTER_PARAMETER_MACRO("value", ANARI_SPATIAL_FIELD, field)
REGISTER_PARAMETER_MACRO("color", ANARI_ARRAY, color)
REGISTER_PARAMETER_MACRO("opacity", ANARI_ARRAY, opacity)
REGISTER_PARAMETER_MACRO("valueRange", ANARI_FLOAT32_BOX1, valueRange)
REGISTER_PARAMETER_MACRO("unitDistance", ANARI_FLOAT32, unitDistance)
)
constexpr UsdVolume::ComponentPair UsdVolume::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
namespace
{
void GatherTfData(const UsdVolumeData& paramData, UsdBridgeTfData& tfData)
{
// Get transfer function data
const UsdDataArray* tfColor = paramData.color;
const UsdDataArray* tfOpacity = paramData.opacity;
UsdBridgeType tfColorType = AnariToUsdBridgeType(tfColor->getType());
UsdBridgeType tfOpacityType = AnariToUsdBridgeType(tfOpacity->getType());
// Write to struct
tfData.TfColors = tfColor->getData();
tfData.TfColorsType = tfColorType;
tfData.TfNumColors = (int)(tfColor->getLayout().numItems1);
tfData.TfOpacities = tfOpacity->getData();
tfData.TfOpacitiesType = tfOpacityType;
tfData.TfNumOpacities = (int)(tfOpacity->getLayout().numItems1);
tfData.TfValueRange[0] = paramData.valueRange.Data[0];
tfData.TfValueRange[1] = paramData.valueRange.Data[1];
}
}
UsdVolume::UsdVolume(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_VOLUME, name, device)
, usdDevice(device)
{
usdDevice->addToVolumeList(this);
}
UsdVolume::~UsdVolume()
{
usdDevice->removeFromVolumeList(this);
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
// Given that the object is destroyed, none of its references to other objects
// has to be updated anymore.
if(cachedBridge)
cachedBridge->DeleteVolume(usdHandle);
#endif
}
void UsdVolume::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteVolume);
}
bool UsdVolume::CheckTfParams(UsdDevice* device)
{
const UsdVolumeData& paramData = getReadParams();
const char* debugName = getName();
UsdLogInfo logInfo(device, this, ANARI_VOLUME, debugName);
// Only perform data(type) checks, data upload along with field in UsdVolume::commit()
const UsdDataArray* tfColor = paramData.color;
if (paramData.color == nullptr)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array not set.", debugName);
return false;
}
const UsdDataArray* tfOpacity = paramData.opacity;
if (tfOpacity == nullptr)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity not set.", debugName);
return false;
}
if (!AssertOneDimensional(tfColor->getLayout(), logInfo, "tfColor"))
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array not one-dimensional.", debugName);
return false;
}
if (!AssertOneDimensional(tfOpacity->getLayout(), logInfo, "tfOpacity"))
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity array not one-dimensional.", debugName);
return false;
}
if (paramData.preClassified && tfColor->getType() != ANARI_FLOAT32_VEC3)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array needs to be of type ANARI_FLOAT32_VEC3 when preClassified is set.", debugName);
return false;
}
if (tfOpacity->getType() != ANARI_FLOAT32)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity array needs to be of type ANARI_FLOAT32.", debugName);
return false;
}
if (tfColor->getLayout().numItems1 != tfOpacity->getLayout().numItems1)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit warning: transferfunction output merges colors and opacities into one array, so they should contain the same number of elements.", debugName);
}
return true;
}
bool UsdVolume::UpdateVolume(UsdDevice* device, const char* debugName)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdVolumeData& paramData = getReadParams();
UsdSpatialField* field = paramData.field;
if (!CheckTfParams(device))
return false;
// Get field data
const UsdSpatialFieldData& fieldParams = field->getReadParams();
const UsdDataArray* fieldDataArray = fieldParams.data;
if(!fieldDataArray) return false; // Enforced in field commit()
const UsdDataLayout& posLayout = fieldDataArray->getLayout();
UsdBridgeType fieldDataType = AnariToUsdBridgeType(fieldDataArray->getType());
//Set bridge volumedata
UsdBridgeVolumeData volumeData;
volumeData.Data = fieldDataArray->getData();
volumeData.DataType = fieldDataType;
size_t* elts = volumeData.NumElements;
float* ori = volumeData.Origin;
float* celldims = volumeData.CellDimensions;
elts[0] = posLayout.numItems1; elts[1] = posLayout.numItems2; elts[2] = posLayout.numItems3;
ori[0] = fieldParams.gridOrigin[0]; ori[1] = fieldParams.gridOrigin[1]; ori[2] = fieldParams.gridOrigin[2];
celldims[0] = fieldParams.gridSpacing[0]; celldims[1] = fieldParams.gridSpacing[1]; celldims[2] = fieldParams.gridSpacing[2];
GatherTfData(paramData, volumeData.TfData);
// Set whether we want to output source data or preclassified colored volumes
volumeData.preClassified = paramData.preClassified;
typedef UsdBridgeVolumeData::DataMemberId DMI;
volumeData.TimeVarying = DMI::ALL
& (field->isTimeVarying(UsdSpatialFieldComponents::DATA) ? DMI::ALL : ~DMI::DATA)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::TFCOLORS)
& (isTimeVarying(CType::OPACITY) ? DMI::ALL : ~DMI::TFOPACITIES)
& (isTimeVarying(CType::VALUERANGE) ? DMI::ALL : ~DMI::TFVALUERANGE);
double worldTimeStep = device->getReadParams().timeStep;
double fieldTimeStep = selectRefTime(paramData.fieldRefTimeStep, fieldParams.timeStep, worldTimeStep); // use the link time, as there is no such thing as separate field data
usdBridge->SetSpatialFieldData(field->getUsdHandle(), volumeData, fieldTimeStep);
return true;
}
bool UsdVolume::deferCommit(UsdDevice* device)
{
// The spatial field may not yet have been committed, but the volume reads data from its params during commit. So always defer until flushing of commit list.
return !device->isFlushingCommitList();
}
bool UsdVolume::doCommitData(UsdDevice* device)
{
const UsdVolumeData& paramData = getReadParams();
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateVolume(getName(), usdHandle);
const char* debugName = getName();
if (prevField != paramData.field)
{
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.field)
{
const UsdSpatialFieldData& fieldParams = paramData.field->getReadParams();
usdBridge->SetSpatialFieldRef(usdHandle,
paramData.field->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.fieldRefTimeStep, fieldParams.timeStep, worldTimeStep)
);
}
else
{
usdBridge->DeleteSpatialFieldRef(usdHandle, worldTimeStep);
}
prevField = paramData.field;
}
// Regardless of whether tf param changes, field params or the vol reference itself, UpdateVolume is required.
if (paramChanged || paramData.field->paramChanged)
{
if(paramData.field)
{
UpdateVolume(device, debugName);
paramChanged = false;
paramData.field->paramChanged = false;
}
else
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: field reference missing.", debugName);
}
}
return false;
} | 8,778 | C++ | 35.127572 | 175 | 0.733424 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridgedBaseObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include <cmath>
#include <utility>
enum class UsdEmptyComponents
{
};
template<typename T, typename D, typename H, typename C = UsdEmptyComponents>
class UsdBridgedBaseObject : public UsdParameterizedBaseObject<T, D>
{
protected:
using CType = C;
// Timevarying helper functions (classes workaround to allow for partial specialization)
template<typename IT, typename ID, typename IH, typename IC>
class TimeVaryingClass
{
public:
bool findTimeVarying(const char* name, IC& component)
{
for(auto& cmpName : IT::componentParamNames)
{
if(strEquals(name, cmpName.second))
{
component = cmpName.first;
return true;
}
}
return false;
}
void setTimeVarying(UsdBridgedBaseObject<IT,ID,IH,IC>* bridgedObj, IC component, bool value)
{
ID& params = bridgedObj->getWriteParams();
int bit = (1 << static_cast<int>(component));
params.timeVarying = value ? (params.timeVarying | bit) : (params.timeVarying & ~bit);
}
};
template<typename IT, typename ID, typename IH>
class TimeVaryingClass<IT, ID, IH, UsdEmptyComponents>
{
public:
bool findTimeVarying(const char* name, UsdEmptyComponents& component)
{
return false;
}
void setTimeVarying(UsdBridgedBaseObject<IT,ID,IH,UsdEmptyComponents>* bridgedObj, UsdEmptyComponents component, bool value)
{
}
};
bool setTimeVaryingParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
static const char* paramName = "usd::timeVarying.";
bool value = *(reinterpret_cast<const uint32_t*>(mem));
if (type == ANARI_BOOL)
{
if (strcmp(name, paramName) > 0)
{
const char* secondPart = name + strlen(paramName);
C component;
TimeVaryingClass<T,D,H,C> timevarHelper;
if(timevarHelper.findTimeVarying(secondPart, component))
{
timevarHelper.setTimeVarying(this, component, value);
return true;
}
}
}
return false;
}
bool isTimeVarying(C component) const
{
const D& params = this->getReadParams();
return params.timeVarying & (1 << static_cast<int>(component));
}
bool setRemovePrimParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if (type == ANARI_BOOL)
{
if (strcmp(name, "usd::removePrim") == 0)
{
removePrim = true;
return true;
}
}
return false;
}
public:
using ComponentPair = std::pair<C, const char*>; // Used to define a componentParamNames
UsdBridgedBaseObject(ANARIDataType t, const char* name, UsdDevice* device)
: UsdParameterizedBaseObject<T, D>(t, device)
, uniqueName(name)
{
}
H getUsdHandle() const { return usdHandle; }
const char* getName() const override { return this->getReadParams().usdName ? this->getReadParams().usdName->c_str() : uniqueName; }
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override
{
if(!this->setTimeVaryingParam(name, type, mem, device))
if (!this->setNameParam(name, type, mem, device))
if(!this->setRemovePrimParam(name, type, mem, device))
this->setParam(name, type, mem, device);
}
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override
{
int nameResult = this->getNameProperty(name, type, mem, size, device);
if(!nameResult)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!usdBridge)
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s parameter '%s' cannot be read with getProperty(); it requires a succesful device parameter commit.", getName(), name);
}
if (type == ANARI_STRING && strEquals(name, "usd::primPath"))
{
const char* primPath = usdBridge->GetPrimPath(&usdHandle);
snprintf((char*)mem, size, "%s", primPath);
return 1;
}
else if (type == ANARI_UINT64 && strEquals(name, "usd::primPath.size"))
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(device, this, ANARI_OBJECT, this->getName()), "usd::primPath.size"))
{
const char* primPath = usdBridge->GetPrimPath(&usdHandle);
uint64_t nameLen = strlen(primPath)+1;
memcpy(mem, &nameLen, size);
}
return 1;
}
}
return nameResult;
}
virtual void commit(UsdDevice* device) override
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
cachedBridge = device->getUsdBridge();
#endif
UsdParameterizedBaseObject<T, D>::commit(device);
}
double selectObjTime(double objTimeStep, double worldTimeStep)
{
return
#ifdef VALUE_CLIP_RETIMING
!std::isnan(objTimeStep) ? objTimeStep :
#endif
worldTimeStep;
}
double selectRefTime(double refTimeStep, double objTimeStep, double worldTimeStep)
{
return
#ifdef VALUE_CLIP_RETIMING
!std::isnan(refTimeStep) ? refTimeStep :
(!std::isnan(objTimeStep) ? objTimeStep : worldTimeStep);
#else
worldTimeStep;
#endif
}
bool getRemovePrim() const { return removePrim; }
protected:
typedef UsdBridgedBaseObject<T,D,H,C> BridgedBaseObjectType;
typedef void (UsdBridge::*UsdBridgeMemFn)(H handle);
void applyRemoveFunc(UsdDevice* device, UsdBridgeMemFn func)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(usdBridge && usdHandle.value)
(usdBridge->*func)(usdHandle);
}
const char* uniqueName;
H usdHandle;
bool removePrim = false;
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
UsdBridge* cachedBridge = nullptr;
#endif
};
template<typename T, typename D, typename H, typename C>
inline bool UsdObjectNotInitialized(const UsdBridgedBaseObject<T,D,H,C>* obj)
{
return obj && !obj->getUsdHandle().value;
}
template<typename T>
inline bool UsdObjectNotInitialized(UsdDataArray* objects)
{
if (!objects)
return false;
bool notInitialized = false;
if(anari::isObject(objects->getType()))
{
const T* const * object = reinterpret_cast<const T* const *>(objects->getData());
uint64_t numObjects = objects->getLayout().numItems1;
for(int i = 0; i < numObjects; ++i)
{
notInitialized = notInitialized || UsdObjectNotInitialized(object[i]);
}
}
return notInitialized;
} | 7,017 | C | 27.644898 | 136 | 0.629899 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGroup.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include "UsdBridge.h"
class UsdDevice;
class UsdDataArray;
enum class UsdGroupComponents
{
SURFACES = 0,
VOLUMES
};
struct UsdGroupData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdDataArray* surfaces = nullptr;
UsdDataArray* volumes = nullptr;
};
class UsdGroup : public UsdBridgedBaseObject<UsdGroup, UsdGroupData, UsdGroupHandle, UsdGroupComponents>
{
public:
UsdGroup(const char* name, UsdDevice* device);
~UsdGroup();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdGroupComponents::SURFACES, "surface"),
ComponentPair(UsdGroupComponents::VOLUMES, "volume")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
std::vector<UsdSurfaceHandle> surfaceHandles; // for convenience
std::vector<UsdVolumeHandle> volumeHandles; // for convenience
};
typedef void (UsdBridge::*SetRefFunc)(UsdGroupHandle, const UsdSurfaceHandle*, uint64_t, bool, double);
template<int ChildAnariTypeEnum, typename ChildAnariType, typename ChildUsdType,
typename ParentHandleType, typename ChildHandleType>
void ManageRefArray(ParentHandleType parentHandle, UsdDataArray* childArray, bool refsTimeVarying, double timeStep, std::vector<ChildHandleType>& tempChildHandles,
void (UsdBridge::*SetRefFunc)(ParentHandleType, const ChildHandleType*, uint64_t, bool, double), void (UsdBridge::*DeleteRefFunc)(ParentHandleType, bool, double),
UsdBridge* usdBridge, UsdLogInfo& logInfo, const char* typeErrorMsg)
{
bool validRefs = AssertArrayType(childArray, ChildAnariTypeEnum, logInfo, typeErrorMsg);
if(validRefs)
{
if (childArray)
{
const ChildAnariType* children = reinterpret_cast<const ChildAnariType*>(childArray->getData());
uint64_t numChildren = childArray->getLayout().numItems1;
tempChildHandles.resize(numChildren);
for (uint64_t i = 0; i < numChildren; ++i)
{
const ChildUsdType* usdChild = reinterpret_cast<const ChildUsdType*>(children[i]);
tempChildHandles[i] = usdChild->getUsdHandle();
}
(usdBridge->*SetRefFunc)(parentHandle, tempChildHandles.data(), numChildren, refsTimeVarying, timeStep);
}
else
{
(usdBridge->*DeleteRefFunc)(parentHandle, refsTimeVarying, timeStep);
}
}
} | 2,658 | C | 32.2375 | 165 | 0.743416 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLibrary.cpp | // Copyright 2023 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDevice.h"
#include "anari/backend/LibraryImpl.h"
#ifndef USDDevice_INTERFACE
#define USDDevice_INTERFACE
#endif
namespace anari {
namespace usd {
const char **query_extensions();
struct UsdLibrary : public anari::LibraryImpl {
UsdLibrary(void *lib, ANARIStatusCallback defaultStatusCB,
const void *statusCBPtr);
ANARIDevice newDevice(const char *subtype) override;
const char **getDeviceExtensions(const char *deviceType) override;
};
// Definitions ////////////////////////////////////////////////////////////////
UsdLibrary::UsdLibrary(void *lib, ANARIStatusCallback defaultStatusCB,
const void *statusCBPtr)
: anari::LibraryImpl(lib, defaultStatusCB, statusCBPtr) {}
ANARIDevice UsdLibrary::newDevice(const char * /*subtype*/) {
return (ANARIDevice) new UsdDevice(this_library());
}
const char **UsdLibrary::getDeviceExtensions(const char * /*deviceType*/) {
return query_extensions();
}
} // namespace usd
} // namespace anari
// Define library entrypoint //////////////////////////////////////////////////
extern "C" USDDevice_INTERFACE
ANARI_DEFINE_LIBRARY_ENTRYPOINT(usd, handle, scb, scbPtr) {
return (ANARILibrary) new anari::usd::UsdLibrary(handle, scb, scbPtr);
}
| 1,328 | C++ | 27.276595 | 79 | 0.670934 |
NVIDIA-Omniverse/AnariUsdDevice/UsdAnari.cpp | #include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include "anari/frontend/type_utility.h"
UsdBridgeType AnariToUsdBridgeType(ANARIDataType anariType)
{
switch (anariType)
{
case ANARI_UINT8: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC2: return UsdBridgeType::UCHAR2;
case ANARI_UINT8_VEC3: return UsdBridgeType::UCHAR3;
case ANARI_UINT8_VEC4: return UsdBridgeType::UCHAR4;
case ANARI_INT8: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC2: return UsdBridgeType::CHAR2;
case ANARI_INT8_VEC3: return UsdBridgeType::CHAR3;
case ANARI_INT8_VEC4: return UsdBridgeType::CHAR4;
case ANARI_UFIXED8: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC2: return UsdBridgeType::UCHAR2;
case ANARI_UFIXED8_VEC3: return UsdBridgeType::UCHAR3;
case ANARI_UFIXED8_VEC4: return UsdBridgeType::UCHAR4;
case ANARI_FIXED8: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC2: return UsdBridgeType::CHAR2;
case ANARI_FIXED8_VEC3: return UsdBridgeType::CHAR3;
case ANARI_FIXED8_VEC4: return UsdBridgeType::CHAR4;
case ANARI_UFIXED8_R_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RA_SRGB: return UsdBridgeType::UCHAR_SRGB_RA;
case ANARI_UFIXED8_RGB_SRGB: return UsdBridgeType::UCHAR_SRGB_RGB;
case ANARI_UFIXED8_RGBA_SRGB: return UsdBridgeType::UCHAR_SRGB_RGBA;
case ANARI_UINT16: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC2: return UsdBridgeType::USHORT2;
case ANARI_UINT16_VEC3: return UsdBridgeType::USHORT3;
case ANARI_UINT16_VEC4: return UsdBridgeType::USHORT4;
case ANARI_INT16: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC2: return UsdBridgeType::SHORT2;
case ANARI_INT16_VEC3: return UsdBridgeType::SHORT3;
case ANARI_INT16_VEC4: return UsdBridgeType::SHORT4;
case ANARI_UFIXED16: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC2: return UsdBridgeType::USHORT2;
case ANARI_UFIXED16_VEC3: return UsdBridgeType::USHORT3;
case ANARI_UFIXED16_VEC4: return UsdBridgeType::USHORT4;
case ANARI_FIXED16: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC2: return UsdBridgeType::SHORT2;
case ANARI_FIXED16_VEC3: return UsdBridgeType::SHORT3;
case ANARI_FIXED16_VEC4: return UsdBridgeType::SHORT4;
case ANARI_UINT32: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC2: return UsdBridgeType::UINT2;
case ANARI_UINT32_VEC3: return UsdBridgeType::UINT3;
case ANARI_UINT32_VEC4: return UsdBridgeType::UINT4;
case ANARI_INT32: return UsdBridgeType::INT;
case ANARI_INT32_VEC2: return UsdBridgeType::INT2;
case ANARI_INT32_VEC3: return UsdBridgeType::INT3;
case ANARI_INT32_VEC4: return UsdBridgeType::INT4;
case ANARI_UFIXED32: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC2: return UsdBridgeType::UINT2;
case ANARI_UFIXED32_VEC3: return UsdBridgeType::UINT3;
case ANARI_UFIXED32_VEC4: return UsdBridgeType::UINT4;
case ANARI_FIXED32: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC2: return UsdBridgeType::INT2;
case ANARI_FIXED32_VEC3: return UsdBridgeType::INT3;
case ANARI_FIXED32_VEC4: return UsdBridgeType::INT4;
case ANARI_UINT64: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC2: return UsdBridgeType::ULONG2;
case ANARI_UINT64_VEC3: return UsdBridgeType::ULONG3;
case ANARI_UINT64_VEC4: return UsdBridgeType::ULONG4;
case ANARI_INT64: return UsdBridgeType::LONG;
case ANARI_INT64_VEC2: return UsdBridgeType::LONG2;
case ANARI_INT64_VEC3: return UsdBridgeType::LONG3;
case ANARI_INT64_VEC4: return UsdBridgeType::LONG4;
case ANARI_FLOAT32: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC2: return UsdBridgeType::FLOAT2;
case ANARI_FLOAT32_VEC3: return UsdBridgeType::FLOAT3;
case ANARI_FLOAT32_VEC4: return UsdBridgeType::FLOAT4;
case ANARI_FLOAT64: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC2: return UsdBridgeType::DOUBLE2;
case ANARI_FLOAT64_VEC3: return UsdBridgeType::DOUBLE3;
case ANARI_FLOAT64_VEC4: return UsdBridgeType::DOUBLE4;
case ANARI_INT32_BOX1: return UsdBridgeType::INT_PAIR;
case ANARI_INT32_BOX2: return UsdBridgeType::INT_PAIR2;
case ANARI_INT32_BOX3: return UsdBridgeType::INT_PAIR3;
case ANARI_INT32_BOX4: return UsdBridgeType::INT_PAIR4;
case ANARI_FLOAT32_BOX1: return UsdBridgeType::FLOAT_PAIR;
case ANARI_FLOAT32_BOX2: return UsdBridgeType::FLOAT_PAIR2;
case ANARI_FLOAT32_BOX3: return UsdBridgeType::FLOAT_PAIR3;
case ANARI_FLOAT32_BOX4: return UsdBridgeType::FLOAT_PAIR4;
case ANARI_UINT64_REGION1: return UsdBridgeType::ULONG_PAIR;
case ANARI_UINT64_REGION2: return UsdBridgeType::ULONG_PAIR2;
case ANARI_UINT64_REGION3: return UsdBridgeType::ULONG_PAIR3;
case ANARI_UINT64_REGION4: return UsdBridgeType::ULONG_PAIR4;
case ANARI_FLOAT32_MAT2: return UsdBridgeType::FLOAT_MAT2;
case ANARI_FLOAT32_MAT3: return UsdBridgeType::FLOAT_MAT3;
case ANARI_FLOAT32_MAT4: return UsdBridgeType::FLOAT_MAT4;
case ANARI_FLOAT32_MAT2x3: return UsdBridgeType::FLOAT_MAT2x3;
case ANARI_FLOAT32_MAT3x4: return UsdBridgeType::FLOAT_MAT3x4;
case ANARI_FLOAT32_QUAT_IJKW: return UsdBridgeType::FLOAT4;
default: return UsdBridgeType::UNDEFINED;
}
}
UsdBridgeType AnariToUsdBridgeType_Flattened(ANARIDataType anariType)
{
switch (anariType)
{
case ANARI_UINT8: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC2: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC3: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC4: return UsdBridgeType::UCHAR;
case ANARI_INT8: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC2: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC3: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC4: return UsdBridgeType::CHAR;
case ANARI_UFIXED8: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC2: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC3: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC4: return UsdBridgeType::UCHAR;
case ANARI_FIXED8: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC2: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC3: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC4: return UsdBridgeType::CHAR;
case ANARI_UFIXED8_R_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RA_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RGB_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RGBA_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UINT16: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC2: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC3: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC4: return UsdBridgeType::USHORT;
case ANARI_INT16: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC2: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC3: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC4: return UsdBridgeType::SHORT;
case ANARI_UFIXED16: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC2: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC3: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC4: return UsdBridgeType::USHORT;
case ANARI_FIXED16: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC2: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC3: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC4: return UsdBridgeType::SHORT;
case ANARI_UINT32: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC2: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC3: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC4: return UsdBridgeType::UINT;
case ANARI_INT32: return UsdBridgeType::INT;
case ANARI_INT32_VEC2: return UsdBridgeType::INT;
case ANARI_INT32_VEC3: return UsdBridgeType::INT;
case ANARI_INT32_VEC4: return UsdBridgeType::INT;
case ANARI_UFIXED32: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC2: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC3: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC4: return UsdBridgeType::UINT;
case ANARI_FIXED32: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC2: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC3: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC4: return UsdBridgeType::INT;
case ANARI_UINT64: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC2: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC3: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC4: return UsdBridgeType::ULONG;
case ANARI_INT64: return UsdBridgeType::LONG;
case ANARI_INT64_VEC2: return UsdBridgeType::LONG;
case ANARI_INT64_VEC3: return UsdBridgeType::LONG;
case ANARI_INT64_VEC4: return UsdBridgeType::LONG;
case ANARI_FLOAT32: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC4: return UsdBridgeType::FLOAT;
case ANARI_FLOAT64: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC2: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC3: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC4: return UsdBridgeType::DOUBLE;
case ANARI_INT32_BOX1: return UsdBridgeType::INT;
case ANARI_INT32_BOX2: return UsdBridgeType::INT;
case ANARI_INT32_BOX3: return UsdBridgeType::INT;
case ANARI_INT32_BOX4: return UsdBridgeType::INT;
case ANARI_FLOAT32_BOX1: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX4: return UsdBridgeType::FLOAT;
case ANARI_UINT64_REGION1: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION2: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION3: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION4: return UsdBridgeType::ULONG;
case ANARI_FLOAT32_MAT2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT4: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT2x3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT3x4: return UsdBridgeType::FLOAT;
default: return UsdBridgeType::UNDEFINED;
}
}
template<int T>
struct AnariTypeStringConverter : public anari::ANARITypeProperties<T>
{
const char* operator()(){ return anari::ANARITypeProperties<T>::enum_name; }
};
const char* AnariTypeToString(ANARIDataType anariType)
{
return anari::anariTypeInvoke<const char*, AnariTypeStringConverter>(anariType);
}
const char* AnariAttributeToUsdName(const char* param, bool perInstance, const UsdLogInfo& logInfo)
{
if(strEquals(param, "worldPosition")
|| strEquals(param, "worldNormal"))
{
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' inAttribute %s not supported, use inTransform parameter on object-space attribute instead.", logInfo.sourceName, param);
}
if(strEquals(param, "objectPosition"))
{
if(perInstance)
return "positions";
else
return "points";
}
else if(strEquals(param, "objectNormal"))
{
return "normals";
}
//else if(!strncmp(param, "attribute", 9))
//{
// return param;
//}
return param; // The generic case just returns the param itself
}
UsdBridgeMaterialData::AlphaModes AnariToUsdAlphaMode(const char* alphaMode)
{
if(alphaMode)
{
if(strEquals(alphaMode, "blend"))
{
return UsdBridgeMaterialData::AlphaModes::BLEND;
}
else if(strEquals(alphaMode, "mask"))
{
return UsdBridgeMaterialData::AlphaModes::MASK;
}
}
return UsdBridgeMaterialData::AlphaModes::NONE;
}
ANARIStatusSeverity UsdBridgeLogLevelToAnariSeverity(UsdBridgeLogLevel level)
{
ANARIStatusSeverity severity = ANARI_SEVERITY_INFO;
switch (level)
{
case UsdBridgeLogLevel::STATUS: severity = ANARI_SEVERITY_INFO; break;
case UsdBridgeLogLevel::WARNING: severity = ANARI_SEVERITY_WARNING; break;
case UsdBridgeLogLevel::ERR: severity = ANARI_SEVERITY_ERROR; break;
default: severity = ANARI_SEVERITY_INFO; break;
}
return severity;
}
void reportStatusThroughDevice(const UsdLogInfo& logInfo, ANARIStatusSeverity severity, ANARIStatusCode statusCode,
const char *format, const char* firstArg, const char* secondArg)
{
if(logInfo.device)
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, severity, statusCode, format, firstArg, secondArg);
}
#ifdef CHECK_MEMLEAKS
void logAllocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType)
{
if(anari::isObject(ptrType))
device->LogObjAllocation((const UsdBaseObject*)ptr);
else if(ptrType == ANARI_STRING)
device->LogStrAllocation((const UsdSharedString*)ptr);
else
device->LogRawAllocation(ptr);
}
void logDeallocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType)
{
if(anari::isObject(ptrType))
device->LogObjDeallocation((const UsdBaseObject*)ptr);
else if(ptrType == ANARI_STRING)
device->LogStrDeallocation((const UsdSharedString*)ptr);
else
device->LogRawDeallocation(ptr);
}
#endif
bool Assert64bitStringLengthProperty(uint64_t size, const UsdLogInfo& logInfo, const char* name)
{
if (size != sizeof(uint64_t) && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, ANARI_OBJECT, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"On object '%s', getProperty() on %s, size parameter differs from sizeof(uint64_t)", logInfo.sourceName, name);
return false;
}
return true;
}
bool AssertOneDimensional(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName)
{
if (!layout.isOneDimensional() && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s' array has to be 1-dimensional.", logInfo.sourceName, arrayName);
return false;
}
return true;
}
bool AssertNoStride(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName)
{
if (!layout.isDense() && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s' layout strides should all be 0.", logInfo.sourceName, arrayName);
return false;
}
return true;
}
bool AssertArrayType(UsdDataArray* dataArray, ANARIDataType dataType, const UsdLogInfo& logInfo, const char* errorMessage)
{
if (dataArray && dataArray->getType() != dataType && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s'", logInfo.sourceName, errorMessage);
return false;
}
return true;
} | 14,507 | C++ | 39.638655 | 209 | 0.766044 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSpatialField.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSpatialField.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdVolume.h"
#include <algorithm>
DEFINE_PARAMETER_MAP(UsdSpatialField,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("data", ANARI_ARRAY, data)
REGISTER_PARAMETER_MACRO("spacing", ANARI_FLOAT32_VEC3, gridSpacing)
REGISTER_PARAMETER_MACRO("origin", ANARI_FLOAT32_VEC3, gridOrigin)
) // See .h for usage.
constexpr UsdSpatialField::ComponentPair UsdSpatialField::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdSpatialField::UsdSpatialField(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SPATIAL_FIELD, name, device)
{
}
UsdSpatialField::~UsdSpatialField()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteSpatialField(usdHandle);
#endif
}
void UsdSpatialField::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSpatialField);
}
bool UsdSpatialField::deferCommit(UsdDevice* device)
{
// Always defer until flushing of commit list, to give parent volumes the possibility to detect which of its child fields have been committed,
// such that those volumes with committed children are also automatically committed.
return !device->isFlushingCommitList();
}
bool UsdSpatialField::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdSpatialFieldData& paramData = getReadParams();
const char* debugName = getName();
UsdLogInfo logInfo(device, this, ANARI_SPATIAL_FIELD, debugName);
bool isNew = false;
if(!usdHandle.value)
isNew = usdBridge->CreateSpatialField(debugName, usdHandle);
// Only perform type checks, actual data gets uploaded during UsdVolume::commit()
const UsdDataArray* fieldDataArray = paramData.data;
if (!fieldDataArray)
{
device->reportStatus(this, ANARI_SPATIAL_FIELD, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION,
"UsdSpatialField '%s' commit failed: data missing.", debugName);
return false;
}
const UsdDataLayout& dataLayout = fieldDataArray->getLayout();
if (!AssertNoStride(dataLayout, logInfo, "data"))
return false;
switch (fieldDataArray->getType())
{
case ANARI_INT8:
case ANARI_UINT8:
case ANARI_INT16:
case ANARI_UINT16:
case ANARI_INT32:
case ANARI_UINT32:
case ANARI_INT64:
case ANARI_UINT64:
case ANARI_FLOAT32:
case ANARI_FLOAT64:
break;
default:
device->reportStatus(this, ANARI_SPATIAL_FIELD, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSpatialField '%s' commit failed: incompatible data type.", debugName);
return false;
}
// Make sure that parameters are set a first time
paramChanged = paramChanged || isNew;
return false;
} | 3,105 | C++ | 30.693877 | 144 | 0.750725 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSpatialField.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdDataArray;
class UsdVolume;
enum class UsdSpatialFieldComponents
{
DATA = 0 // includes spacing and origin
};
struct UsdSpatialFieldData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
const UsdDataArray* data = nullptr;
float gridSpacing[3] = {1.0f, 1.0f, 1.0f};
float gridOrigin[3] = {1.0f, 1.0f, 1.0f};
//int filter = 0;
//int gradientFilter = 0;
};
class UsdSpatialField : public UsdBridgedBaseObject<UsdSpatialField, UsdSpatialFieldData, UsdSpatialFieldHandle, UsdSpatialFieldComponents>
{
public:
UsdSpatialField(const char* name, const char* type, UsdDevice* device);
~UsdSpatialField();
void remove(UsdDevice* device) override;
friend class UsdVolume;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdSpatialFieldComponents::DATA, "data")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void toBridge(UsdDevice* device, const char* debugName);
}; | 1,335 | C | 24.692307 | 139 | 0.734831 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSampler.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSampler.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
DEFINE_PARAMETER_MAP(UsdSampler,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::imageUrl", ANARI_STRING, imageUrl)
REGISTER_PARAMETER_MACRO("inAttribute", ANARI_STRING, inAttribute)
REGISTER_PARAMETER_MACRO("image", ANARI_ARRAY, imageData)
REGISTER_PARAMETER_MACRO("wrapMode", ANARI_STRING, wrapS)
REGISTER_PARAMETER_MACRO("wrapMode1", ANARI_STRING, wrapS)
REGISTER_PARAMETER_MACRO("wrapMode2", ANARI_STRING, wrapT)
REGISTER_PARAMETER_MACRO("wrapMode3", ANARI_STRING, wrapR)
)
constexpr UsdSampler::ComponentPair UsdSampler::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
namespace
{
UsdBridgeSamplerData::WrapMode ANARIToUsdBridgeWrapMode(const char* anariWrapMode)
{
UsdBridgeSamplerData::WrapMode usdWrapMode = UsdBridgeSamplerData::WrapMode::BLACK;
if(anariWrapMode)
{
if (strEquals(anariWrapMode, "clampToEdge"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::CLAMP;
}
else if (strEquals(anariWrapMode, "repeat"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::REPEAT;
}
else if (strEquals(anariWrapMode, "mirrorRepeat"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::MIRROR;
}
}
return usdWrapMode;
}
}
UsdSampler::UsdSampler(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SAMPLER, name, device)
{
if (strEquals(type, "image1D"))
samplerType = SAMPLER_1D;
else if (strEquals(type, "image2D"))
samplerType = SAMPLER_2D;
else if (strEquals(type, "image3D"))
samplerType = SAMPLER_3D;
else
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdSampler '%s' construction failed: type %s not supported", getName(), name);
}
UsdSampler::~UsdSampler()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteSampler(usdHandle);
#endif
}
void UsdSampler::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSampler);
}
void UsdSampler::updateBoundParameters(bool boundToInstance, UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!usdHandle.value)
return;
if(perInstance != boundToInstance)
{
// Fix up the position attribute
const UsdSamplerData& paramData = getReadParams();
const char* inAttribName = UsdSharedString::c_str(paramData.inAttribute);
if(inAttribName && strEquals(inAttribName, "objectPosition"))
{
// In case of a per-instance specific attribute name, there can be only one change of the attribute name.
UsdLogInfo logInfo(device, this, ANARI_SAMPLER, getName());
if(instanceAttributeAttached)
{
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' binds its inAttribute parameter to %s, but is transitively bound to both an instanced geometry (cones, spheres, cylinders) and regular geometry. \
This is incompatible with USD, which demands a differently bound name for those categories. \
Please create two different samplers and bind each to only one of both categories of geometry. \
The inAttribute value will be updated, but may therefore invalidate previous bindings to the objectPosition attribute.", logInfo.sourceName, "'objectPosition'");
}
instanceAttributeAttached = true;
const char* usdAttribName = AnariAttributeToUsdName(inAttribName, perInstance, logInfo);
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
UsdBridgeSamplerData::DataMemberId timeVarying;
setSamplerTimeVarying(timeVarying);
usdBridge->ChangeInAttribute(usdHandle, usdAttribName, dataTimeStep, timeVarying);
}
perInstance = boundToInstance;
}
}
bool UsdSampler::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdSampler::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!device->getReadParams().outputMaterial ||
samplerType == SAMPLER_UNKNOWN)
return false;
const UsdSamplerData& paramData = getReadParams();
UsdBridgeSamplerData::SamplerType type =
(samplerType == SAMPLER_1D ? UsdBridgeSamplerData::SamplerType::SAMPLER_1D :
(samplerType == SAMPLER_2D ? UsdBridgeSamplerData::SamplerType::SAMPLER_2D :
UsdBridgeSamplerData::SamplerType::SAMPLER_3D
)
);
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateSampler(getName(), usdHandle, type);
if (paramChanged || isNew)
{
if (paramData.inAttribute && (std::strlen(UsdSharedString::c_str(paramData.inAttribute)) > 0)
&& (paramData.imageUrl || paramData.imageData))
{
bool supportedImage = true;
int numComponents = 0;
if(paramData.imageData)
{
numComponents = static_cast<int>(anari::componentsOf(paramData.imageData->getType()));
if(numComponents > 4)
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' image data has more than 4 components. Anything above the 4th component will be ignored.", paramData.imageData->getName());
}
if(supportedImage)
{
UsdLogInfo logInfo(device, this, ANARI_SAMPLER, getName());
UsdBridgeSamplerData samplerData;
samplerData.Type = type;
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
samplerData.InAttribute = AnariAttributeToUsdName(UsdSharedString::c_str(paramData.inAttribute), perInstance, logInfo);
if(paramData.imageUrl)
{
samplerData.ImageUrl = UsdSharedString::c_str(paramData.imageUrl);
}
if(paramData.imageData)
{
samplerData.Data = paramData.imageData->getData();
samplerData.ImageName = paramData.imageData->getName();
samplerData.ImageNumComponents = numComponents;
samplerData.DataType = AnariToUsdBridgeType(paramData.imageData->getType());
paramData.imageData->getLayout().copyDims(samplerData.ImageDims);
paramData.imageData->getLayout().copyStride(samplerData.ImageStride);
}
samplerData.WrapS = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapS));
samplerData.WrapT = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapT));
samplerData.WrapR = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapR));
setSamplerTimeVarying(samplerData.TimeVarying);
usdBridge->SetSamplerData(usdHandle, samplerData, dataTimeStep);
}
}
else
{
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' commit failed: missing either the 'inAttribute', or both the 'image' and 'usd::imageUrl' parameter", getName());
}
paramChanged = false;
}
return false;
}
void UsdSampler::setSamplerTimeVarying(UsdBridgeSamplerData::DataMemberId& timeVarying)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
timeVarying = DMI::ALL
& (isTimeVarying(CType::DATA) ? DMI::ALL : ~DMI::DATA)
& (isTimeVarying(CType::WRAPS) ? DMI::ALL : ~DMI::WRAPS)
& (isTimeVarying(CType::WRAPT) ? DMI::ALL : ~DMI::WRAPT)
& (isTimeVarying(CType::WRAPR) ? DMI::ALL : ~DMI::WRAPR);
}
| 7,952 | C++ | 35.649769 | 178 | 0.709633 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMultiTypeParameter.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdAnari.h"
#include "anari/anari_cpp/Traits.h"
template<typename T0, typename T1, typename T2>
struct UsdMultiTypeParameter
{
static constexpr int AnariType0 = anari::ANARITypeFor<T0>::value;
static constexpr int AnariType1 = anari::ANARITypeFor<T1>::value;
static constexpr int AnariType2 = anari::ANARITypeFor<T2>::value;
union DataUnion
{
T0 type0;
T1 type1;
T2 type2;
};
DataUnion data;
ANARIDataType type;
// Helper functions
T0& Get(T0& arg) const
{
if(AnariType0 == type) { arg = data.type0; }
return arg;
}
T1& Get(T1& arg) const
{
if(AnariType1 == type) { arg = data.type1; }
return arg;
}
T2& Get(T2& arg) const
{
if(AnariType2 == type) { arg = data.type2; }
return arg;
}
};
| 876 | C | 17.659574 | 67 | 0.64726 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLight.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdLight.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
DEFINE_PARAMETER_MAP(UsdLight,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
)
UsdLight::UsdLight(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_LIGHT, name, device)
{}
UsdLight::~UsdLight()
{}
void UsdLight::remove(UsdDevice* device)
{
//applyRemoveFunc(device, &UsdBridge::DeleteLight);
}
bool UsdLight::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdLight::doCommitData(UsdDevice* device)
{
return false;
} | 672 | C++ | 19.393939 | 62 | 0.735119 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDevice.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDevice.h"
#include "UsdBridgedBaseObject.h"
#include "UsdDataArray.h"
#include "UsdGeometry.h"
#include "UsdSpatialField.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#include "UsdInstance.h"
#include "UsdGroup.h"
#include "UsdMaterial.h"
#include "UsdSampler.h"
#include "UsdWorld.h"
#include "UsdRenderer.h"
#include "UsdFrame.h"
#include "UsdLight.h"
#include "UsdCamera.h"
#include "UsdDeviceQueries.h"
#include <cstdarg>
#include <cstdio>
#include <set>
#include <memory>
#include <sstream>
#include <algorithm>
#include <limits>
static char deviceName[] = "usd";
class UsdDeviceInternals
{
public:
UsdDeviceInternals()
{
}
bool CreateNewBridge(const UsdDeviceData& deviceParams, UsdBridgeLogCallback bridgeStatusFunc, void* userData)
{
if (bridge.get())
bridge->CloseSession();
UsdBridgeSettings bridgeSettings = {
UsdSharedString::c_str(deviceParams.hostName),
outputLocation.c_str(),
deviceParams.createNewSession,
deviceParams.outputBinary,
deviceParams.outputPreviewSurfaceShader,
deviceParams.outputMdlShader
};
bridge = std::make_unique<UsdBridge>(bridgeSettings);
bridge->SetExternalSceneStage(externalSceneStage);
bridge->SetEnableSaving(this->enableSaving);
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "Initializing UsdBridge Session");
bool createSuccess = bridge->OpenSession(bridgeStatusFunc, userData);
if (!createSuccess)
{
bridge = nullptr;
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "UsdBridge Session initialization failed.");
}
else
{
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "UsdBridge Session initialization successful.");
}
return createSuccess;
}
std::string outputLocation;
bool enableSaving = true;
std::unique_ptr<UsdBridge> bridge;
SceneStagePtr externalSceneStage{nullptr};
std::set<std::string> uniqueNames;
};
//---- Make sure to update clearDeviceParameters() on refcounted objects
DEFINE_PARAMETER_MAP(UsdDevice,
REGISTER_PARAMETER_MACRO("usd::serialize.hostName", ANARI_STRING, hostName)
REGISTER_PARAMETER_MACRO("usd::serialize.location", ANARI_STRING, outputPath)
REGISTER_PARAMETER_MACRO("usd::serialize.newSession", ANARI_BOOL, createNewSession)
REGISTER_PARAMETER_MACRO("usd::serialize.outputBinary", ANARI_BOOL, outputBinary)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::writeAtCommit", ANARI_BOOL, writeAtCommit)
REGISTER_PARAMETER_MACRO("usd::output.material", ANARI_BOOL, outputMaterial)
REGISTER_PARAMETER_MACRO("usd::output.previewSurfaceShader", ANARI_BOOL, outputPreviewSurfaceShader)
REGISTER_PARAMETER_MACRO("usd::output.mdlShader", ANARI_BOOL, outputMdlShader)
)
void UsdDevice::clearDeviceParameters()
{
filterResetParam("usd::serialize.hostName");
filterResetParam("usd::serialize.location");
transferWriteToReadParams();
}
//----
UsdDevice::UsdDevice()
: UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>(ANARI_DEVICE)
, internals(std::make_unique<UsdDeviceInternals>())
{}
UsdDevice::UsdDevice(ANARILibrary library)
: DeviceImpl(library)
, UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>(ANARI_DEVICE)
, internals(std::make_unique<UsdDeviceInternals>())
{}
UsdDevice::~UsdDevice()
{
// Make sure no more references are held before cleaning up the device (and checking for memleaks)
clearCommitList();
clearDeviceParameters(); // Release device parameters with object references
clearResourceStringList(); // Do the same for resource string references
//internals->bridge->SaveScene(); //Uncomment to test cleanup of usd files.
#ifdef CHECK_MEMLEAKS
if(!allocatedObjects.empty() || !allocatedStrings.empty() || !allocatedRawMemory.empty())
{
std::stringstream errstream;
errstream << "USD Device memleak reported for: ";
for(auto ptr : allocatedObjects)
errstream << "Object ptr: 0x" << std::hex << ptr << " of type: " << std::dec << ptr->getType() << "; ";
for(auto ptr : allocatedStrings)
errstream << "String ptr: 0x" << std::hex << ptr << " with content: " << std::dec << ptr->c_str() << "; ";
for(auto ptr : allocatedRawMemory)
errstream << "Raw ptr: 0x" << std::hex << ptr << std::dec << "; ";
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
else
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_INFO, ANARI_STATUS_NO_ERROR, "Reference memleak check complete, no issues found.");
}
assert(allocatedObjects.empty());
#endif
}
void UsdDevice::reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format, ...)
{
va_list arglist;
va_start(arglist, format);
reportStatus(source, sourceType, severity, statusCode, format, arglist);
va_end(arglist);
}
static void reportBridgeStatus(UsdBridgeLogLevel level, void* device, const char *message)
{
ANARIStatusSeverity severity = UsdBridgeLogLevelToAnariSeverity(level);
va_list arglist;
((UsdDevice*)device)->reportStatus(nullptr, ANARI_UNKNOWN, severity, ANARI_STATUS_NO_ERROR, message, arglist);
}
void UsdDevice::reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format,
va_list& arglist)
{
va_list arglist_copy;
va_copy(arglist_copy, arglist);
int count = std::vsnprintf(nullptr, 0, format, arglist);
lastStatusMessage.resize(count + 1);
std::vsnprintf(lastStatusMessage.data(), count + 1, format, arglist_copy);
va_end(arglist_copy);
if (statusFunc != nullptr)
{
statusFunc(
statusUserData,
(ANARIDevice)this,
(ANARIObject)source,
sourceType,
severity,
statusCode,
lastStatusMessage.data());
}
}
void UsdDevice::filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if (strEquals(name, "usd::garbageCollect"))
{
// Perform garbage collection on usd objects (needs to move into the user interface)
if(internals->bridge)
internals->bridge->GarbageCollect();
}
else if(strEquals(name, "usd::removeUnusedNames"))
{
internals->uniqueNames.clear();
}
else if (strEquals(name, "usd::connection.logVerbosity")) // 0 <= verbosity <= 4, with 4 being the loudest
{
if(type == ANARI_INT32)
UsdBridge::SetConnectionLogVerbosity(*(reinterpret_cast<const int*>(mem)));
}
else if(strEquals(name, "usd::sceneStage"))
{
if(type == ANARI_VOID_POINTER)
internals->externalSceneStage = const_cast<void *>(mem);
}
else if (strEquals(name, "usd::enableSaving"))
{
if(type == ANARI_BOOL)
{
internals->enableSaving = *(reinterpret_cast<const bool*>(mem));
if(internals->bridge)
internals->bridge->SetEnableSaving(internals->enableSaving);
}
}
else if (strEquals(name, "statusCallback") && type == ANARI_STATUS_CALLBACK)
{
userSetStatusFunc = (ANARIStatusCallback)mem;
}
else if (strEquals(name, "statusCallbackUserData") && type == ANARI_VOID_POINTER)
{
userSetStatusUserData = const_cast<void *>(mem);
}
else
{
setParam(name, type, mem, this);
}
}
void UsdDevice::filterResetParam(const char * name)
{
if (strEquals(name, "statusCallback"))
{
userSetStatusFunc = nullptr;
}
else if (strEquals(name, "statusCallbackUserData"))
{
userSetStatusUserData = nullptr;
}
else if (!strEquals(name, "usd::garbageCollect")
&& !strEquals(name, "usd::removeUnusedNames"))
{
resetParam(name);
}
}
void UsdDevice::commit(UsdDevice* device)
{
transferWriteToReadParams();
if(!bridgeInitAttempt)
{
initializeBridge();
}
else
{
const UsdDeviceData& paramData = getReadParams();
internals->bridge->UpdateBeginEndTime(paramData.timeStep);
}
}
void UsdDevice::initializeBridge()
{
const UsdDeviceData& paramData = getReadParams();
bridgeInitAttempt = true;
statusFunc = userSetStatusFunc ? userSetStatusFunc : defaultStatusCallback();
statusUserData = userSetStatusUserData ? userSetStatusUserData : defaultStatusCallbackUserPtr();
if(paramData.outputPath)
internals->outputLocation = paramData.outputPath->c_str();
if(internals->outputLocation.empty()) {
auto *envLocation = getenv("ANARI_USD_SERIALIZE_LOCATION");
if (envLocation) {
internals->outputLocation = envLocation;
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_INFO, ANARI_STATUS_NO_ERROR,
"Usd Device parameter 'usd::serialize.location' using ANARI_USD_SERIALIZE_LOCATION value");
}
}
if (internals->outputLocation.empty())
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"Usd Device parameter 'usd::serialize.location' not set, defaulting to './'");
internals->outputLocation = "./";
}
if (!internals->CreateNewBridge(paramData, &reportBridgeStatus, this))
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_ERROR, ANARI_STATUS_UNKNOWN_ERROR, "Usd Bridge failed to load");
}
}
ANARIArray UsdDevice::CreateDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3)
{
if (!appMemory)
{
UsdDataArray* object = new UsdDataArray(dataType, numItems1, numItems2, numItems3, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIArray)(object);
}
else
{
UsdDataArray* object = new UsdDataArray(appMemory, deleter, userData,
dataType, numItems1, byteStride1, numItems2, byteStride2, numItems3, byteStride3,
this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIArray)(object);
}
}
ANARIArray1D UsdDevice::newArray1D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems)
{
return (ANARIArray1D)CreateDataArray(appMemory, deleter, userData,
type, numItems, 0, 1, 0, 1, 0);
}
ANARIArray2D UsdDevice::newArray2D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems1,
uint64_t numItems2)
{
return (ANARIArray2D)CreateDataArray(appMemory, deleter, userData,
type, numItems1, 0, numItems2, 0, 1, 0);
}
ANARIArray3D UsdDevice::newArray3D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3)
{
return (ANARIArray3D)CreateDataArray(appMemory, deleter, userData,
type, numItems1, 0, numItems2, 0, numItems3, 0);
}
void * UsdDevice::mapArray(ANARIArray array)
{
return array ? AnariToUsdObjectPtr(array)->map(this) : nullptr;
}
void UsdDevice::unmapArray(ANARIArray array)
{
if(array)
AnariToUsdObjectPtr(array)->unmap(this);
}
ANARISampler UsdDevice::newSampler(const char *type)
{
const char* name = makeUniqueName("Sampler");
UsdSampler* object = new UsdSampler(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISampler)(object);
}
ANARIMaterial UsdDevice::newMaterial(const char *material_type)
{
const char* name = makeUniqueName("Material");
UsdMaterial* object = new UsdMaterial(name, material_type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIMaterial)(object);
}
ANARIGeometry UsdDevice::newGeometry(const char *type)
{
const char* name = makeUniqueName("Geometry");
UsdGeometry* object = new UsdGeometry(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIGeometry)(object);
}
ANARISpatialField UsdDevice::newSpatialField(const char * type)
{
const char* name = makeUniqueName("SpatialField");
UsdSpatialField* object = new UsdSpatialField(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISpatialField)(object);
}
ANARISurface UsdDevice::newSurface()
{
const char* name = makeUniqueName("Surface");
UsdSurface* object = new UsdSurface(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISurface)(object);
}
ANARIVolume UsdDevice::newVolume(const char *type)
{
const char* name = makeUniqueName("Volume");
UsdVolume* object = new UsdVolume(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIVolume)(object);
}
ANARIGroup UsdDevice::newGroup()
{
const char* name = makeUniqueName("Group");
UsdGroup* object = new UsdGroup(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIGroup)(object);
}
ANARIInstance UsdDevice::newInstance(const char */*type*/)
{
const char* name = makeUniqueName("Instance");
UsdInstance* object = new UsdInstance(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIInstance)(object);
}
ANARIWorld UsdDevice::newWorld()
{
const char* name = makeUniqueName("World");
UsdWorld* object = new UsdWorld(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIWorld)(object);
}
ANARICamera UsdDevice::newCamera(const char *type)
{
const char* name = makeUniqueName("Camera");
UsdCamera* object = new UsdCamera(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARICamera)(object);
}
const char **UsdDevice::getObjectSubtypes(ANARIDataType objectType)
{
return anari::usd::query_object_types(objectType);
}
const void *UsdDevice::getObjectInfo(ANARIDataType objectType,
const char *objectSubtype,
const char *infoName,
ANARIDataType infoType)
{
return anari::usd::query_object_info(
objectType, objectSubtype, infoName, infoType);
}
const void *UsdDevice::getParameterInfo(ANARIDataType objectType,
const char *objectSubtype,
const char *parameterName,
ANARIDataType parameterType,
const char *infoName,
ANARIDataType infoType)
{
return anari::usd::query_param_info(objectType,
objectSubtype,
parameterName,
parameterType,
infoName,
infoType);
}
ANARIRenderer UsdDevice::newRenderer(const char *type)
{
UsdRenderer* object = new UsdRenderer();
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIRenderer)(object);
}
UsdBridge* UsdDevice::getUsdBridge()
{
return internals->bridge.get();
}
void UsdDevice::renderFrame(ANARIFrame frame)
{
// Always commit device changes if not initialized, otherwise no conversion can be performed.
if(!bridgeInitAttempt)
initializeBridge();
if(!isInitialized())
return;
flushCommitList();
internals->bridge->ResetResourceUpdateState(); // Reset the modified flags for committed shared resources
if(frame)
AnariToUsdObjectPtr(frame)->saveUsd(this);
}
const char* UsdDevice::makeUniqueName(const char* name)
{
std::string proposedBaseName(name);
proposedBaseName.append("_");
int postFix = 0;
std::string proposedName = proposedBaseName + std::to_string(postFix);
auto empRes = internals->uniqueNames.emplace(proposedName);
while (!empRes.second)
{
++postFix;
proposedName = proposedBaseName + std::to_string(postFix);
empRes = internals->uniqueNames.emplace(proposedName);
}
return empRes.first->c_str();
}
bool UsdDevice::nameExists(const char* name)
{
return internals->uniqueNames.find(name) != internals->uniqueNames.end();
}
void UsdDevice::addToCommitList(UsdBaseObject* object, bool commitData)
{
if(!object)
return;
if(lockCommitList)
{
this->reportStatus(object, object->getType(), ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION,
"Usd device internal error; addToCommitList called while list is locked");
}
else
{
auto it = std::find_if(commitList.begin(), commitList.end(),
[&object](const CommitListType& entry) -> bool { return entry.first.ptr == object; });
if(it == commitList.end())
commitList.emplace_back(CommitListType(object, commitData));
}
}
void UsdDevice::clearCommitList()
{
removePrimsFromUsd(true); // removeList pointers are taken from commitlist
#ifdef CHECK_MEMLEAKS
for(auto& commitEntry : commitList)
{
LogObjDeallocation(commitEntry.first.ptr);
}
#endif
commitList.resize(0);
}
void UsdDevice::flushCommitList()
{
// Automatically perform a new commitdata/commitrefs on volumes which are not committed,
// but for which their (readdata) spatial field is in commitlist. (to update the previous commit)
for(UsdVolume* volume : volumeList)
{
const UsdVolumeData& readParams = volume->getReadParams();
if(readParams.field)
{
//volume not in commitlist
auto volEntry = std::find_if(commitList.begin(), commitList.end(),
[&volume](const CommitListType& entry) -> bool { return entry.first.ptr == volume; });
if(volEntry == commitList.end())
{
auto fieldEntry = std::find_if(commitList.begin(), commitList.end(),
[&readParams](const CommitListType& entry) -> bool { return entry.first.ptr == readParams.field; });
// spatialfield from readParams is in commit list
if(fieldEntry != commitList.end())
{
UsdBaseObject* baseObject = static_cast<UsdBaseObject*>(volume);
bool commitRefs = baseObject->doCommitData(this);
if(commitRefs)
baseObject->doCommitRefs(this);
}
}
}
}
lockCommitList = true;
writeTypeToUsd<(int)ANARI_SAMPLER>();
writeTypeToUsd<(int)ANARI_SPATIAL_FIELD>();
writeTypeToUsd<(int)ANARI_GEOMETRY>();
writeTypeToUsd<(int)ANARI_LIGHT>();
writeTypeToUsd<(int)ANARI_MATERIAL>();
writeTypeToUsd<(int)ANARI_SURFACE>();
writeTypeToUsd<(int)ANARI_VOLUME>();
writeTypeToUsd<(int)ANARI_GROUP>();
writeTypeToUsd<(int)ANARI_INSTANCE>();
writeTypeToUsd<(int)ANARI_WORLD>();
writeTypeToUsd<(int)ANARI_CAMERA>();
removePrimsFromUsd();
clearCommitList();
lockCommitList = false;
}
void UsdDevice::addToVolumeList(UsdVolume* volume)
{
auto it = std::find(volumeList.begin(), volumeList.end(), volume);
if(it == volumeList.end())
volumeList.emplace_back(volume);
}
void UsdDevice::addToResourceStringList(UsdSharedString* string)
{
resourceStringList.push_back(helium::IntrusivePtr<UsdSharedString>(string));
}
void UsdDevice::clearResourceStringList()
{
resourceStringList.resize(0);
}
void UsdDevice::removeFromVolumeList(UsdVolume* volume)
{
auto it = std::find(volumeList.begin(), volumeList.end(), volume);
if(it == volumeList.end())
{
*it = volumeList.back();
volumeList.pop_back();
}
}
template<int typeInt>
void UsdDevice::writeTypeToUsd()
{
for(auto objCommitPair : commitList)
{
auto object = objCommitPair.first;
bool commitData = objCommitPair.second;
if((int)object->getType() == typeInt)
{
using ObjectType = typename AnariToUsdBridgedObject<typeInt>::Type;
ObjectType* typedObj = reinterpret_cast<ObjectType*>(object.ptr);
if(!object->deferCommit(this))
{
bool commitRefs = true;
if(commitData)
commitRefs = object->doCommitData(this);
if(commitRefs)
object->doCommitRefs(this);
}
else
{
this->reportStatus(object.ptr, object->getType(), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION,
"User forgot to at least once commit an ANARI child object of parent object '%s'", typedObj->getName());
}
if(typedObj->getRemovePrim())
{
removeList.push_back(object.ptr); // Just raw pointer, removeList is purged upon commitList clear
}
}
}
}
void UsdDevice::removePrimsFromUsd(bool onlyRemoveHandles)
{
if(!onlyRemoveHandles)
{
for(auto baseObj : removeList)
{
baseObj->remove(this);
}
}
removeList.resize(0);
}
int UsdDevice::getProperty(ANARIObject object,
const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
uint32_t mask)
{
if ((void *)object == (void *)this)
{
if (strEquals(name, "version") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_BUILD);
return 1;
}
if (strEquals(name, "version.major") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_MAJOR);
return 1;
}
if (strEquals(name, "version.minor") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_MINOR);
return 1;
}
if (strEquals(name, "version.patch") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_PATCH);
return 1;
}
if (strEquals(name, "version.name") && type == ANARI_STRING)
{
snprintf((char*)mem, size, "%s", DEVICE_VERSION_NAME);
return 1;
}
else if (strEquals(name, "version.name.size") && type == ANARI_UINT64)
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(this, this, ANARI_DEVICE, "UsdDevice"), "version.name.size"))
{
uint64_t nameLen = strlen(DEVICE_VERSION_NAME)+1;
memcpy(mem, &nameLen, size);
}
return 1;
}
else if (strEquals(name, "geometryMaxIndex") && type == ANARI_UINT64)
{
uint64_t maxIndex = std::numeric_limits<uint64_t>::max(); // Only restricted to int for UsdGeomMesh: GetFaceVertexIndicesAttr() takes a VtArray<int>
writeToVoidP(mem, maxIndex);
return 1;
}
else if (strEquals(name, "extension") && type == ANARI_STRING_LIST)
{
writeToVoidP(mem, anari::usd::query_extensions());
return 1;
}
}
else if(object)
return AnariToUsdObjectPtr(object)->getProperty(name, type, mem, size, this);
return 0;
}
ANARIFrame UsdDevice::newFrame()
{
UsdFrame* object = new UsdFrame(internals->bridge.get());
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIFrame)(object);
}
const void * UsdDevice::frameBufferMap(
ANARIFrame fb,
const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType)
{
if (fb)
return AnariToUsdObjectPtr(fb)->mapBuffer(channel, width, height, pixelType);
return nullptr;
}
void UsdDevice::frameBufferUnmap(ANARIFrame fb, const char *channel)
{
if (fb)
return AnariToUsdObjectPtr(fb)->unmapBuffer(channel);
}
UsdBaseObject* UsdDevice::getBaseObjectPtr(ANARIObject object)
{
return handleIsDevice(object) ? this : (UsdBaseObject*)object;
}
void UsdDevice::setParameter(ANARIObject object,
const char *name,
ANARIDataType type,
const void *mem)
{
if(object)
getBaseObjectPtr(object)->filterSetParam(name, type, mem, this);
}
void UsdDevice::unsetParameter(ANARIObject object, const char * name)
{
if(object)
getBaseObjectPtr(object)->filterResetParam(name);
}
void UsdDevice::unsetAllParameters(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->resetAllParams();
}
void *UsdDevice::mapParameterArray1D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t *elementStride)
{
auto array = newArray1D(nullptr, nullptr, nullptr, dataType, numElements1);
setParameter(object, name, ANARI_ARRAY1D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void *UsdDevice::mapParameterArray2D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t *elementStride)
{
auto array = newArray2D(nullptr, nullptr, nullptr, dataType, numElements1, numElements2);
setParameter(object, name, ANARI_ARRAY2D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void *UsdDevice::mapParameterArray3D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t numElements3,
uint64_t *elementStride)
{
auto array = newArray3D(nullptr,
nullptr,
nullptr,
dataType,
numElements1,
numElements2,
numElements3);
setParameter(object, name, ANARI_ARRAY3D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void UsdDevice::unmapParameterArray(ANARIObject object, const char *name)
{
if(!object)
return;
ANARIDataType paramType = ANARI_UNKNOWN;
void* paramAddress = getBaseObjectPtr(object)->getParameter(name, paramType);
if(paramAddress && paramType == ANARI_ARRAY)
{
auto arrayAddress = (ANARIArray*)paramAddress;
if(*arrayAddress)
AnariToUsdObjectPtr(*arrayAddress)->unmap(this);
}
}
void UsdDevice::release(ANARIObject object)
{
if(!object)
return;
UsdBaseObject* baseObject = getBaseObjectPtr(object);
bool privatizeArray = baseObject->getType() == ANARI_ARRAY
&& baseObject->useCount(helium::RefType::INTERNAL) > 0
&& baseObject->useCount(helium::RefType::PUBLIC) == 1;
#ifdef CHECK_MEMLEAKS
if(!handleIsDevice(object))
LogObjDeallocation(baseObject);
#endif
if (baseObject)
baseObject->refDec(helium::RefType::PUBLIC);
if (privatizeArray)
AnariToUsdObjectPtr((ANARIArray)object)->privatize();
}
void UsdDevice::retain(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->refInc(helium::RefType::PUBLIC);
}
void UsdDevice::commitParameters(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->commit(this);
}
#ifdef CHECK_MEMLEAKS
namespace
{
template<typename T>
void SharedLogDeallocation(const T* ptr, std::vector<const T*>& allocations, UsdDevice* device)
{
if (ptr)
{
auto it = std::find(allocations.begin(), allocations.end(), ptr);
if(it == allocations.end())
{
std::stringstream errstream;
errstream << "USD Device release of nonexisting or already released/deleted object: 0x" << std::hex << ptr;
device->reportStatus(device, ANARI_DEVICE, ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
if(ptr->useCount() == 1)
{
assert(it != allocations.end());
allocations.erase(it);
}
}
}
}
void UsdDevice::LogObjAllocation(const UsdBaseObject* ptr)
{
allocatedObjects.push_back(ptr);
}
void UsdDevice::LogObjDeallocation(const UsdBaseObject* ptr)
{
SharedLogDeallocation(ptr, allocatedObjects, this);
}
void UsdDevice::LogStrAllocation(const UsdSharedString* ptr)
{
allocatedStrings.push_back(ptr);
}
void UsdDevice::LogStrDeallocation(const UsdSharedString* ptr)
{
SharedLogDeallocation(ptr, allocatedStrings, this);
}
void UsdDevice::LogRawAllocation(const void* ptr)
{
allocatedRawMemory.push_back(ptr);
}
void UsdDevice::LogRawDeallocation(const void* ptr)
{
if (ptr)
{
auto it = std::find(allocatedRawMemory.begin(), allocatedRawMemory.end(), ptr);
if(it == allocatedRawMemory.end())
{
std::stringstream errstream;
errstream << "USD Device release of nonexisting or already released/deleted raw memory: 0x" << std::hex << ptr;
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
else
allocatedRawMemory.erase(it);
}
}
#endif
| 27,549 | C++ | 25.695736 | 154 | 0.705652 |
NVIDIA-Omniverse/AnariUsdDevice/UsdRenderer.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdRenderer.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDeviceQueries.h"
DEFINE_PARAMETER_MAP(UsdRenderer,
)
UsdRenderer::UsdRenderer()
: UsdParameterizedBaseObject<UsdRenderer, UsdRendererData>(ANARI_RENDERER)
{
}
UsdRenderer::~UsdRenderer()
{
}
int UsdRenderer::getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device)
{
if (strEquals(name, "extension") && type == ANARI_STRING_LIST)
{
writeToVoidP(mem, anari::usd::query_extensions());
return 1;
}
return 0;
}
bool UsdRenderer::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdRenderer::doCommitData(UsdDevice* device)
{
return false;
}
| 803 | C++ | 18.142857 | 113 | 0.728518 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSharedObjects.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "helium/utility/IntrusivePtr.h"
#include "UsdCommonMacros.h"
#include <string>
template<typename BaseType, typename InitType>
class UsdRefCountWrapped : public helium::RefCounted
{
public:
UsdRefCountWrapped(InitType i)
: data(i)
{}
BaseType data;
};
class UsdSharedString : public UsdRefCountWrapped<std::string, const char*>
{
public:
UsdSharedString(const char* cStr)
: UsdRefCountWrapped<std::string, const char*>(cStr)
{}
static const char* c_str(const UsdSharedString* string) { return string ? string->c_str() : nullptr; }
const char* c_str() const { return data.c_str(); }
}; | 733 | C | 22.677419 | 106 | 0.699864 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBaseObject.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBaseObject.h"
#include "UsdDevice.h"
UsdBaseObject::UsdBaseObject(ANARIDataType t, UsdDevice* device)
: type(t)
{
// The object will not be committed (as in, user-written write params will not be set to read params),
// but handles will be initialized and the object with its default data/refs will be written out to USD
// (but only if the prim wasn't yet written to USD before, see 'isNew' in doCommit implementations).
if(device)
device->addToCommitList(this, true);
}
void UsdBaseObject::commit(UsdDevice* device)
{
bool deferDataCommit = !device->isInitialized() || !device->getReadParams().writeAtCommit || deferCommit(device);
if(!deferDataCommit)
{
bool commitRefs = doCommitData(device);
if(commitRefs)
device->addToCommitList(this, false); // Commit refs, but no more data
}
else
device->addToCommitList(this, true); // Commit data and refs
}
| 1,008 | C++ | 33.793102 | 115 | 0.709325 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
typedef enum TestType
{
TEST_MESH,
TEST_CONES,
TEST_GLYPHS
} TestType_t;
typedef struct TestParameters
{
int writeAtCommit;
int useVertexColors;
int useTexture;
int useIndices;
int isTransparent;
TestType_t testType;
int useGlyphMesh;
} TestParameters_t;
typedef struct TexData
{
uint8_t* textureData;
uint8_t* opacityTextureData;
int textureSize[2];
} TexData_t;
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = { -1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f };
float normal[] = { 0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f
};
float color[] = { 0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f };
float opacities[] = {
0.5f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f };
int32_t index[] = { 0, 1, 2, 2, 1, 3 };
float protoVertex[] = {-3.0f,
-1.0f,
-1.0f,
3.0f,
-1.0f,
-1.0f,
-3.0f,
1.0f,
-1.0f,
3.0f,
1.0f,
-1.0f,
-3.0f,
-1.0f,
1.0f,
3.0f,
-1.0f,
1.0f,
-3.0f,
1.0f,
1.0f,
3.0f,
1.0f,
1.0f};
float protoColor[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f,
0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
int32_t protoIndex[] = {0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1};
float protoTransform[16] = {
0.75f, 0.0f, 0.0f, 0.0f,
0.0f, 1.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
float kd[] = { 0.0f, 0.0f, 1.0f };
ANARIInstance createMeshInstance(ANARIDevice dev, TestParameters_t testParams, TexData_t testData)
{
int useVertexColors = testParams.useVertexColors;
int useTexture = testParams.useTexture;
int isTransparent = testParams.isTransparent;
// create and setup mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
array = anariNewArray1D(dev, normal, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.normal", ANARI_ARRAY, &array);
anariRelease(dev, array);
// Set the vertex colors
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::attribute0.name", ANARI_STRING, "customTexcoordName");
if(isTransparent)
{
array = anariNewArray1D(dev, opacities, 0, 0, ANARI_FLOAT32, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.attribute1", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, mesh);
// Create a sampler
ANARISampler sampler = 0;
if(useTexture)
{
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler");
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "customTexcoordName");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
array = anariNewArray2D(dev, testData.textureData, 0, 0, ANARI_UINT8_VEC3, testData.textureSize[0], testData.textureSize[1]); // Make sure this matches numTexComponents
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &array);
anariCommitParameters(dev, sampler);
anariRelease(dev, array);
}
ANARISampler opacitySampler = 0;
if(isTransparent && useTexture)
{
opacitySampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, opacitySampler, "name", ANARI_STRING, "tutorialSamplerOpacity");
anariSetParameter(dev, opacitySampler, "inAttribute", ANARI_STRING, "customTexcoordName");
anariSetParameter(dev, opacitySampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, opacitySampler, "wrapMode2", ANARI_STRING, wrapT);
array = anariNewArray2D(dev, testData.opacityTextureData, 0, 0, ANARI_UINT8, testData.textureSize[0], testData.textureSize[1]);
anariSetParameter(dev, opacitySampler, "image", ANARI_ARRAY, &array);
anariCommitParameters(dev, opacitySampler);
anariRelease(dev, array);
}
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = isTransparent ? 0.65f : 1.0f;
if(isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else if(useTexture)
anariSetParameter(dev, mat, "opacity", ANARI_SAMPLER, &opacitySampler);
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
int timevaryEmissive = 1; // Set emissive to timevarying (should appear in material stage under primstages/)
anariSetParameter(dev, mat, "usd::timeVarying.emissive", ANARI_BOOL, &timevaryEmissive);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
anariRelease(dev, opacitySampler);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
return instance;
}
ANARIInstance createConesInstance(ANARIDevice dev, TestParameters_t testParams, GridData_t testData)
{
// create and setup geom
ANARIGeometry cones = anariNewGeometry(dev, "cone");
anariSetParameter(dev, cones, "name", ANARI_STRING, "tutorialMesh");
int sizeX = testData.gridSize[0], sizeY = testData.gridSize[1];
int numVertices = sizeX*sizeY;
// Create a snake pattern through the vertices
int numIndexTuples = sizeY*sizeX-1;
int* indices = (int*)malloc(2*(numIndexTuples+1)*sizeof(int)); // Extra space for a dummy tuple
int vertIdxTo = 0;
for(int i = 0; i < sizeX; ++i)
{
for(int j = 0; j < sizeY; ++j)
{
int vertIdxFrom = vertIdxTo;
vertIdxTo = vertIdxFrom + ((j == sizeY-1) ? sizeY : ((i%2) ? -1 : 1));
int idxAddr = 2*(sizeY*i+j);
indices[idxAddr] = vertIdxFrom;
indices[idxAddr+1] = vertIdxTo;
}
}
ANARIArray1D array = anariNewArray1D(dev, testData.gridVertex, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if(testParams.useIndices)
{
array = anariNewArray1D(dev, indices, 0, 0, ANARI_INT32_VEC2, numIndexTuples);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
// Set the vertex colors
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, testData.gridColor, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
if(testParams.isTransparent)
{
array = anariNewArray1D(dev, testData.gridOpacity, 0, 0, ANARI_FLOAT32, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
// Use per-primitive radii when not using indices, to test that codepath too
array = anariNewArray1D(dev, testData.gridRadius, 0, 0, ANARI_FLOAT32, testParams.useIndices ? numVertices : numVertices/2); // per-primitive is half the vertex count
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, testParams.useIndices ? "vertex.radius" : "primitive.radius", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, cones);
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (testParams.useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = testParams.isTransparent ? 0.65f : 1.0f;
if(testParams.isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(testParams.useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
anariCommitParameters(dev, mat);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &cones);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, cones);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
free(indices);
return instance;
}
ANARIInstance createGlyphsInstance(ANARIDevice dev, TestParameters_t testParams, GridData_t testData)
{
int sizeX = testData.gridSize[0], sizeY = testData.gridSize[1];
int numVertices = sizeX*sizeY;
ANARIArray1D array;
ANARIGeometry protoMesh;
// The prototype mesh (instanced geometry)
if(testParams.useGlyphMesh)
{
protoMesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, protoMesh, "name", ANARI_STRING, "tutorialProtoMesh");
array = anariNewArray1D(dev, protoVertex, 0, 0, ANARI_FLOAT32_VEC3, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, protoColor, 0, 0, ANARI_FLOAT32_VEC4, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, protoIndex, 0, 0, ANARI_INT32_VEC3, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, protoMesh);
}
// The glyph geometry
ANARIGeometry glyphs = anariNewGeometry(dev, "glyph");
if(testParams.useGlyphMesh)
anariSetParameter(dev, glyphs, "shapeGeometry", ANARI_GEOMETRY, &protoMesh);
else
anariSetParameter(dev, glyphs, "shapeType", ANARI_STRING, "cylinder");
anariSetParameter(dev, glyphs, "shapeTransform", ANARI_FLOAT32_MAT4, protoTransform);
if(testParams.useGlyphMesh)
anariRelease(dev, protoMesh);
array = anariNewArray1D(dev, testData.gridVertex, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, testData.gridColor, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, testData.gridRadius, 0, 0, ANARI_FLOAT32, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, testData.gridOrientation, 0, 0, ANARI_FLOAT32_QUAT_IJKW, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.orientation", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, glyphs);
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (testParams.useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = testParams.isTransparent ? 0.65f : 1.0f;
if(testParams.isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(testParams.useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
anariCommitParameters(dev, mat);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &glyphs);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, glyphs);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
return instance;
}
void doTest(TestParameters_t testParams)
{
printf("\n\n-------------- Starting new test iteration \n\n");
printf("Parameters: writeatcommit %d, useVertexColors %d, useTexture %d, transparent %d, geom type %s \n",
testParams.writeAtCommit, testParams.useVertexColors, testParams.useTexture, testParams.isTransparent,
((testParams.testType == TEST_MESH) ? "mesh" : ((testParams.testType == TEST_CONES) ? "cones" : "glyphs")));
stbi_flip_vertically_on_write(1);
// image sizes
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
int gridSize[2] = { 100, 100 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
uint8_t* opacityTextureData = 0;
opacityTextureData = generateTexture(textureSize, 1);
GridData_t gridData;
createSineWaveGrid(gridSize, &gridData);
TexData_t texData;
texData.textureData = textureData;
texData.opacityTextureData = opacityTextureData;
texData.textureSize[0] = textureSize[0];
texData.textureSize[1] = textureSize[1];
// camera
float cam_pos[] = { 0.f, 0.f, 0.f };
float cam_up[] = { 0.f, 1.f, 0.f };
float cam_view[] = { 0.1f, 0.f, 1.f };
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
int outputMaterial = 1;
int outputPreviewSurface = 1;
int outputMdl = 1;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "localhost");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
anariSetParameter(dev, dev, "usd::output.material", ANARI_BOOL, &outputMaterial);
anariSetParameter(dev, dev, "usd::output.previewSurfaceShader", ANARI_BOOL, &outputPreviewSurface);
anariSetParameter(dev, dev, "usd::output.mdlShader", ANARI_BOOL, &outputMdl);
anariSetParameter(dev, dev, "usd::writeAtCommit", ANARI_BOOL, &testParams.writeAtCommit);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
printf("done!\n");
printf("setting up scene...");
ANARIWorld world = anariNewWorld(dev);
ANARIInstance instance;
switch(testParams.testType)
{
case TEST_MESH:
instance = createMeshInstance(dev, testParams, texData);
break;
case TEST_CONES:
instance = createConesInstance(dev, testParams, gridData);
break;
case TEST_GLYPHS:
instance = createGlyphsInstance(dev, testParams, gridData);
break;
default:
break;
};
if(!instance)
return;
anariCommitParameters(dev, instance);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
ANARIArray1D array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
printf("done!\n");
// print out world bounds
float worldBounds[6];
if (anariGetProperty(dev,
world,
"bounds",
ANARI_FLOAT32_BOX3,
worldBounds,
sizeof(worldBounds),
ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0],
worldBounds[1],
worldBounds[2],
worldBounds[3],
worldBounds[4],
worldBounds[5]);
}
else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, camera);
anariRelease(dev, frame);
anariRelease(dev, world);
anariRelease(dev, dev);
anariUnloadLibrary(lib);
freeTexture(textureData);
freeSineWaveGrid(&gridData);
printf("done!\n");
}
int main(int argc, const char **argv)
{
TestParameters_t testParams;
testParams.testType = TEST_MESH;
testParams.writeAtCommit = 0;
testParams.isTransparent = 0;
// Test standard flow with textures
testParams.useVertexColors = 0;
testParams.useTexture = 1;
doTest(testParams);
// With vertex colors
testParams.useVertexColors = 1;
testParams.useTexture = 0;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
testParams.useTexture = 0;
doTest(testParams);
// Transparency
testParams.useVertexColors = 0;
testParams.useTexture = 0;
testParams.isTransparent = 1;
doTest(testParams);
// Transparency (vertex)
testParams.useVertexColors = 1;
testParams.useTexture = 0;
doTest(testParams);
// Transparency (sampler)
testParams.useVertexColors = 0;
testParams.useTexture = 1;
doTest(testParams);
// Test immediate mode writing
testParams.writeAtCommit = 1;
testParams.useVertexColors = 0;
testParams.useTexture = 1;
testParams.isTransparent = 0;
doTest(testParams);
// Cones tests
testParams.testType = TEST_CONES;
testParams.writeAtCommit = 0;
testParams.useTexture = 0;
testParams.useIndices = 0;
// With vertex colors
testParams.useVertexColors = 1;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
doTest(testParams);
// Using indices (and vertex colors)
testParams.useIndices = 1;
testParams.useVertexColors = 1;
doTest(testParams);
// Glyphs tests
testParams.testType = TEST_GLYPHS;
testParams.writeAtCommit = 0;
testParams.useTexture = 0;
testParams.useIndices = 0;
testParams.useGlyphMesh = 0;
// With vertex colors
testParams.useVertexColors = 1;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
doTest(testParams);
// Using indices (and vertex colors)
testParams.useGlyphMesh = 1;
doTest(testParams);
return 0;
}
| 25,558 | C | 29.069412 | 172 | 0.698294 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_recreate.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
int main(int argc, const char **argv)
{
stbi_flip_vertically_on_write(1);
// image size
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
// camera
float cam_pos[] = {0.f, 0.f, 0.f};
float cam_up[] = {0.f, 1.f, 0.f};
float cam_view[] = {0.1f, 0.f, 1.f};
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = {-1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f};
float normal[] = { 0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f
};
float color[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f };
float sphereSizes[] = { 0.1f,
2.0f,
0.3f,
0.05f };
int32_t index[] = {0, 1, 2, 2, 1, 3};
float kd[] = { 0.0f, 0.0f, 1.0f };
for(int anariPass = 0; anariPass < 2; ++anariPass)
{
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return 1;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
int outputMaterial = 1;
int createNewSession = (anariPass == 0) ? 1 : 0;
int useVertexColors = (anariPass == 0);
int useTexture = 1;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "ov-test");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
anariSetParameter(dev, dev, "usd::serialize.newSession", ANARI_BOOL, &createNewSession);
anariSetParameter(dev, dev, "usd::output.material", ANARI_BOOL, &outputMaterial);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
int deleteCam = 1;
if(anariPass == 0)
anariSetParameter(dev, camera, "usd::removePrim", ANARI_BOOL, &deleteCam);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
printf("done!\n");
printf("setting up scene...");
ANARIWorld world = anariNewWorld(dev);
// create and setup mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
array = anariNewArray1D(dev, normal, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.normal", ANARI_ARRAY, &array);
anariRelease(dev, array);
// Set the vertex colors
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
//array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariRelease(dev, array);
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, mesh);
ANARIMaterial mat;
// The second iteration should not create samplers/materials and not add it to the surface,
// so the material prim itself will remain untouched in the pre-existing stage,
// while its reference will be removed from the newly committed surface prim
if(anariPass == 0)
{
mat = anariNewMaterial(dev, "matte");
ANARISampler sampler = anariNewSampler(dev, "image2D");
// Create a sampler
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
array = anariNewArray2D(dev, textureData, 0, 0, ANARI_UINT8_VEC3, textureSize[0], textureSize[1]); // Make sure this matches numTexComponents
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &array);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
anariRelease(dev, array);
// Create a material
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
float opacity = 1.0f;
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacity);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
}
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
if (anariPass == 0)
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
if (anariPass == 0)
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
anariCommitParameters(dev, instance);
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
printf("done!\n");
// print out world bounds
float worldBounds[6];
if (anariGetProperty(dev,
world,
"bounds",
ANARI_FLOAT32_BOX3,
worldBounds,
sizeof(worldBounds),
ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0],
worldBounds[1],
worldBounds[2],
worldBounds[3],
worldBounds[4],
worldBounds[5]);
}
else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, camera);
anariRelease(dev, frame);
anariRelease(dev, world);
anariRelease(dev, dev);
anariUnloadLibrary(lib);
printf("done!\n");
for(int vIdx = 0; vIdx < sizeof(vertex)/sizeof(float); ++vIdx)
{
vertex[vIdx] += 1.0f;
}
}
freeTexture(textureData);
return 0;
}
| 11,313 | C | 30.254144 | 147 | 0.644745 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd.cpp | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <array>
// anari
#define ANARI_EXTENSION_UTILITY_IMPL
#include "anari/anari_cpp.hpp"
#include "anari/anari_cpp/ext/std.h"
// stb_image
#include "stb_image_write.h"
using uvec2 = std::array<unsigned int, 2>;
using ivec3 = std::array<int, 3>;
using vec3 = std::array<float, 3>;
using vec4 = std::array<float, 4>;
using box3 = std::array<vec3, 2>;
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
(void)device;
(void)source;
(void)sourceType;
(void)code;
if (severity == ANARI_SEVERITY_FATAL_ERROR) {
fprintf(stderr, "[FATAL] %s\n", message);
} else if (severity == ANARI_SEVERITY_ERROR) {
fprintf(stderr, "[ERROR] %s\n", message);
} else if (severity == ANARI_SEVERITY_WARNING) {
fprintf(stderr, "[WARN ] %s\n", message);
} else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING) {
fprintf(stderr, "[PERF ] %s\n", message);
} else if (severity == ANARI_SEVERITY_INFO) {
fprintf(stderr, "[INFO ] %s\n", message);
} else if (severity == ANARI_SEVERITY_DEBUG) {
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
int main(int argc, const char **argv)
{
(void)argc;
(void)argv;
stbi_flip_vertically_on_write(1);
// image size
uvec2 imgSize = {1024 /*width*/, 768 /*height*/};
// camera
vec3 cam_pos = {0.f, 0.f, 0.f};
vec3 cam_up = {0.f, 1.f, 0.f};
vec3 cam_view = {0.1f, 0.f, 1.f};
// triangle mesh array
vec3 vertex[] = {{-1.0f, -1.0f, 3.0f},
{-1.0f, 1.0f, 3.0f},
{1.0f, -1.0f, 3.0f},
{0.1f, 0.1f, 0.3f}};
vec4 color[] = {{0.9f, 0.0f, 0.0f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.0f, 0.9f, 0.0f, 1.0f}};
ivec3 index[] = {{0, 1, 2}, {1, 2, 3}};
printf("initialize ANARI...");
anari::Library lib = anari::loadLibrary("usd", statusFunc);
anari::Extensions extensions =
anari::extension::getDeviceExtensionStruct(lib, "default");
if (!extensions.ANARI_KHR_GEOMETRY_TRIANGLE)
printf("WARNING: device doesn't support ANARI_KHR_GEOMETRY_TRIANGLE\n");
if (!extensions.ANARI_KHR_CAMERA_PERSPECTIVE)
printf("WARNING: device doesn't support ANARI_KHR_CAMERA_PERSPECTIVE\n");
if (!extensions.ANARI_KHR_LIGHT_DIRECTIONAL)
printf("WARNING: device doesn't support ANARI_KHR_LIGHT_DIRECTIONAL\n");
if (!extensions.ANARI_KHR_MATERIAL_MATTE)
printf("WARNING: device doesn't support ANARI_KHR_MATERIAL_MATTE\n");
ANARIDevice d = anariNewDevice(lib, "default");
printf("done!\n");
printf("setting up camera...");
// create and setup camera
auto camera = anari::newObject<anari::Camera>(d, "perspective");
anari::setParameter(
d, camera, "aspect", (float)imgSize[0] / (float)imgSize[1]);
anari::setParameter(d, camera, "position", cam_pos);
anari::setParameter(d, camera, "direction", cam_view);
anari::setParameter(d, camera, "up", cam_up);
anari::commitParameters(
d, camera); // commit objects to indicate setting parameters is done
printf("done!\n");
printf("setting up scene...");
// The world to be populated with renderable objects
auto world = anari::newObject<anari::World>(d);
// create and setup surface and mesh
auto mesh = anari::newObject<anari::Geometry>(d, "triangle");
anari::setAndReleaseParameter(
d, mesh, "vertex.position", anari::newArray1D(d, vertex, 4));
anari::setAndReleaseParameter(
d, mesh, "vertex.color", anari::newArray1D(d, color, 4));
anari::setAndReleaseParameter(
d, mesh, "primitive.index", anari::newArray1D(d, index, 2));
anari::commitParameters(d, mesh);
auto mat = anari::newObject<anari::Material>(d, "matte");
anari::setParameter(d, mat, "color", "color");
anari::commitParameters(d, mat);
// put the mesh into a surface
auto surface = anari::newObject<anari::Surface>(d);
anari::setAndReleaseParameter(d, surface, "geometry", mesh);
anari::setAndReleaseParameter(d, surface, "material", mat);
anari::commitParameters(d, surface);
// put the surface directly onto the world
anari::setAndReleaseParameter(
d, world, "surface", anari::newArray1D(d, &surface));
anari::release(d, surface);
// create and setup light
auto light = anari::newObject<anari::Light>(d, "directional");
anari::commitParameters(d, light);
anari::setAndReleaseParameter(
d, world, "light", anari::newArray1D(d, &light));
anari::release(d, light);
anari::commitParameters(d, world);
printf("done!\n");
// print out world bounds
box3 worldBounds;
if (anari::getProperty(d, world, "bounds", worldBounds, ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0][0],
worldBounds[0][1],
worldBounds[0][2],
worldBounds[1][0],
worldBounds[1][1],
worldBounds[1][2]);
} else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
auto renderer = anari::newObject<anari::Renderer>(d, "default");
// objects can be named for easier identification in debug output etc.
anari::setParameter(d, renderer, "name", "MainRenderer");
printf("done!\n");
// complete setup of renderer
vec4 bgColor = {1.f, 1.f, 1.f, 1.f};
anari::setParameter(d, renderer, "backgroundColor", bgColor); // white
anari::commitParameters(d, renderer);
// create and setup frame
auto frame = anari::newObject<anari::Frame>(d);
anari::setParameter(d, frame, "size", imgSize);
anari::setParameter(d, frame, "channel.color", ANARI_UFIXED8_RGBA_SRGB);
anari::setAndReleaseParameter(d, frame, "renderer", renderer);
anari::setAndReleaseParameter(d, frame, "camera", camera);
anari::setAndReleaseParameter(d, frame, "world", world);
anari::commitParameters(d, frame);
printf("rendering out USD objects via anari::renderFrame()...");
// render one frame
anari::render(d, frame);
anari::wait(d, frame);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anari::release(d, frame);
anari::release(d, d);
anari::unloadLibrary(lib);
printf("done!\n");
return 0;
}
| 6,357 | C++ | 29.27619 | 77 | 0.654554 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_common.h | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <math.h>
#define PI 3.14159265
const char *g_libraryType = "usd";
#ifdef _WIN32
const char* texFile = "d:/models/texture.png";
#else
const char* texFile = "/home/<username>/models/texture.png"; // Point this to any png
#endif
const char* wrapS = "repeat";
const char* wrapT = "repeat";
/******************************************************************/
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
if (severity == ANARI_SEVERITY_FATAL_ERROR)
{
fprintf(stderr, "[FATAL] %s\n", message);
}
else if (severity == ANARI_SEVERITY_ERROR)
{
fprintf(stderr, "[ERROR] %s\n", message);
}
else if (severity == ANARI_SEVERITY_WARNING)
{
fprintf(stderr, "[WARN ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING)
{
fprintf(stderr, "[PERF ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_INFO)
{
fprintf(stderr, "[INFO ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_DEBUG)
{
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
void writePNG(const char *fileName, ANARIDevice d, ANARIFrame frame)
{
uint32_t size[2] = {0, 0};
ANARIDataType type = ANARI_UNKNOWN;
uint32_t *pixel = (uint32_t *)anariMapFrame(d, frame, "channel.color", &size[0], &size[1], &type);
if (type == ANARI_UFIXED8_RGBA_SRGB)
stbi_write_png(fileName, size[0], size[1], 4, pixel, 4 * size[0]);
else
printf("Incorrectly returned color buffer pixel type, image not saved.\n");
anariUnmapFrame(d, frame, "channel.color");
}
uint8_t touint8t(float val)
{
return (uint8_t)floorf((val + 1.0f)*127.5f); // 0.5*255
}
uint8_t* generateTexture(int* size, int numComps)
{
uint8_t* texData = (uint8_t*)malloc(size[0]*size[1]*numComps);
for(int i = 0; i < size[0]; ++i)
{
for(int j = 0; j < size[1]; ++j)
{
int pixIdx = i*size[1]+j;
int offset = pixIdx*numComps;
float rVal = sin((float)i/size[0] * 2.0f * PI);
float gVal = cos((float)i/size[0] * 8.0f * PI);
float bVal = cos((float)j/size[1] * 20.0f * PI);
texData[offset] = touint8t(rVal);
if(numComps >= 2)
texData[offset+1] = touint8t(gVal);
if(numComps >= 3)
texData[offset+2] = touint8t(bVal);
if(numComps == 4)
texData[offset+3] = 255;
}
}
return texData;
}
void freeTexture(uint8_t* data)
{
free(data);
}
typedef struct GridData
{
float* gridVertex;
float* gridColor;
float* gridOpacity;
float* gridRadius;
float* gridOrientation;
int gridSize[2];
} GridData_t;
void createSineWaveGrid(int* size, GridData_t* gridData)
{
int baseSize = size[0]*size[1]*sizeof(float);
float* vertData = (float*)malloc(baseSize*3);
float* colorData = (float*)malloc(baseSize*3);
float* opacityData = (float*)malloc(baseSize);
float* radiusData = (float*)malloc(baseSize);
float* orientData = (float*)malloc(baseSize*4);
for(int i = 0; i < size[0]; ++i)
{
for(int j = 0; j < size[1]; ++j)
{
int vertIdx = i*size[1]+j;
int vertAddr = vertIdx*3;
float iFrac = (float)i/size[0];
float jFrac = (float)j/size[1];
// Vertex
float amp = sin((iFrac+jFrac) * 8.0f * PI) + cos(jFrac * 5.5f * PI);
vertData[vertAddr] = ((float)i)*5.0f;
vertData[vertAddr+1] = ((float)j)*5.0f;
vertData[vertAddr+2] = amp*10.0f;
// Color
float rVal = sin(iFrac * 2.0f * PI);
float gVal = cos(iFrac * 8.0f * PI);
float bVal = cos(jFrac * 20.0f * PI);
colorData[vertAddr] = rVal;
colorData[vertAddr+1] = gVal;
colorData[vertAddr+2] = bVal;
// Opacity
float opacity = 0.3f + 0.3f*(cos(iFrac * 1.0f * PI) + sin(jFrac * 7.0f * PI));
opacityData[vertIdx] = opacity;
// Radius
//spacing is 5.0, so make sure not to go over 2.5
float radius = 1.25f + 0.5f*(cos(iFrac * 5.0f * PI) + sin(jFrac * 2.0f * PI));
radiusData[vertIdx] = radius;
// Orientation
int orientAddr = vertIdx*4;
float roll = iFrac*PI*7.3, pitch = jFrac*PI*4.9, yaw = -(jFrac+0.45f)*PI*3.3;
float sinRoll = sin(roll), sinPitch = sin(pitch), sinYaw = sin(yaw);
float cosRoll = cos(roll), cosPitch = cos(pitch), cosYaw = cos(yaw);
orientData[orientAddr] = cosRoll*cosPitch*cosYaw+sinRoll*sinPitch*sinYaw;
orientData[orientAddr+1] = sinRoll*cosPitch*cosYaw-cosRoll*sinPitch*sinYaw;
orientData[orientAddr+2] = cosRoll*sinPitch*cosYaw+sinRoll*cosPitch*sinYaw;
orientData[orientAddr+3] = cosRoll*cosPitch*sinYaw-sinRoll*sinPitch*cosYaw;
}
}
gridData->gridVertex = vertData;
gridData->gridColor = colorData;
gridData->gridOpacity = opacityData;
gridData->gridRadius = radiusData;
gridData->gridOrientation = orientData;
gridData->gridSize[0] = size[0];
gridData->gridSize[1] = size[1];
}
void freeSineWaveGrid(GridData_t* gridData)
{
free(gridData->gridVertex);
free(gridData->gridColor);
free(gridData->gridOpacity);
free(gridData->gridRadius);
free(gridData->gridOrientation);
} | 5,257 | C | 26.385417 | 100 | 0.62355 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_volume.cpp | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <array>
#include <random>
// anari
#define ANARI_EXTENSION_UTILITY_IMPL
#include "anari/anari_cpp.hpp"
#include "anari/anari_cpp/ext/std.h"
// stb_image
#include "stb_image_write.h"
using uvec2 = std::array<unsigned int, 2>;
using uvec3 = std::array<unsigned int, 3>;
using ivec3 = std::array<int, 3>;
using vec3 = std::array<float, 3>;
using vec4 = std::array<float, 4>;
using box3 = std::array<vec3, 2>;
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
(void)device;
(void)source;
(void)sourceType;
(void)code;
if (severity == ANARI_SEVERITY_FATAL_ERROR) {
fprintf(stderr, "[FATAL] %s\n", message);
} else if (severity == ANARI_SEVERITY_ERROR) {
fprintf(stderr, "[ERROR] %s\n", message);
} else if (severity == ANARI_SEVERITY_WARNING) {
fprintf(stderr, "[WARN ] %s\n", message);
} else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING) {
fprintf(stderr, "[PERF ] %s\n", message);
} else if (severity == ANARI_SEVERITY_INFO) {
fprintf(stderr, "[INFO ] %s\n", message);
} else if (severity == ANARI_SEVERITY_DEBUG) {
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
struct ParameterInfo
{
const char* m_name;
bool m_param;
const char* m_description;
};
struct GravityVolume
{
GravityVolume(anari::Device d);
~GravityVolume();
std::vector<ParameterInfo> parameters();
anari::World world();
void commit();
private:
anari::Device m_device{nullptr};
anari::World m_world{nullptr};
};
struct Point
{
vec3 center;
float weight;
};
static std::vector<Point> generatePoints(size_t numPoints)
{
// create random number distributions for point center and weight
std::mt19937 gen(0);
std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);
// populate the points
std::vector<Point> points(numPoints);
for (auto &p : points) {
p.center[0] = centerDistribution(gen);
p.center[1] = centerDistribution(gen);
p.center[2] = centerDistribution(gen);
p.weight = weightDistribution(gen);
}
return points;
}
static std::vector<float> generateVoxels(
const std::vector<Point> &points, ivec3 dims)
{
// get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
// volumeDimension)
auto logicalToWorldCoordinates = [&](int i, int j, int k) {
vec3 result = {-1.f + float(i) / float(dims[0] - 1) * 2.f,
-1.f + float(j) / float(dims[1] - 1) * 2.f,
-1.f + float(k) / float(dims[2] - 1) * 2.f};
return result;
};
// generate voxels
std::vector<float> voxels(size_t(dims[0]) * size_t(dims[1]) * size_t(dims[2]));
for (int k = 0; k < dims[2]; k++) {
for (int j = 0; j < dims[1]; j++) {
for (int i = 0; i < dims[0]; i++) {
// index in array
size_t index = size_t(k) * size_t(dims[2]) * size_t(dims[1])
+ size_t(j) * size_t(dims[0]) + size_t(i);
// compute volume value
float value = 0.f;
for (auto &p : points) {
vec3 pointCoordinate = logicalToWorldCoordinates(i, j, k);
const float distanceSq =
std::pow(pointCoordinate[0] - p.center[0], 2.0f) +
std::pow(pointCoordinate[1] - p.center[1], 2.0f) +
std::pow(pointCoordinate[2] - p.center[2], 2.0f);
// contribution proportional to weighted inverse-square distance
// (i.e. gravity)
value += p.weight / distanceSq;
}
voxels[index] = value;
}
}
}
return voxels;
}
GravityVolume::GravityVolume(anari::Device d)
{
m_device = d;
m_world = anari::newObject<anari::World>(m_device);
}
GravityVolume::~GravityVolume()
{
anari::release(m_device, m_world);
}
std::vector<ParameterInfo> GravityVolume::parameters()
{
return {
{"withGeometry", false, "Include geometry inside the volume?"}
//
};
}
anari::World GravityVolume::world()
{
return m_world;
}
void GravityVolume::commit()
{
anari::Device d = m_device;
const bool withGeometry = false;//getParam<bool>("withGeometry", false);
const int volumeDims = 128;
const size_t numPoints = 10;
const float voxelRange[2] = {0.f, 10.f};
ivec3 volumeDims3 = {volumeDims,volumeDims,volumeDims};
vec3 fieldOrigin = {-1.f, -1.f, -1.f};
vec3 fieldSpacing = {2.f / volumeDims, 2.f / volumeDims, 2.f / volumeDims};
auto points = generatePoints(numPoints);
auto voxels = generateVoxels(points, volumeDims3);
auto field = anari::newObject<anari::SpatialField>(d, "structuredRegular");
anari::setParameter(d, field, "origin", fieldOrigin);
anari::setParameter(d, field, "spacing", fieldSpacing);
anari::setAndReleaseParameter(d,
field,
"data",
anari::newArray3D(d, voxels.data(), volumeDims, volumeDims, volumeDims));
anari::commitParameters(d, field);
auto volume = anari::newObject<anari::Volume>(d, "scivis");
anari::setAndReleaseParameter(d, volume, "value", field);
{
std::vector<vec3> colors;
std::vector<float> opacities;
colors.emplace_back(vec3{0.f, 0.f, 1.f});
colors.emplace_back(vec3{0.f, 1.f, 0.f});
colors.emplace_back(vec3{1.f, 0.f, 0.f});
opacities.emplace_back(0.f);
opacities.emplace_back(0.05f);
opacities.emplace_back(0.1f);
anari::setAndReleaseParameter(
d, volume, "color", anari::newArray1D(d, colors.data(), colors.size()));
anari::setAndReleaseParameter(d,
volume,
"opacity",
anari::newArray1D(d, opacities.data(), opacities.size()));
anariSetParameter(d, volume, "valueRange", ANARI_FLOAT32_BOX1, voxelRange);
}
anari::commitParameters(d, volume);
if (withGeometry) {
std::vector<vec3> positions(numPoints);
std::transform(
points.begin(), points.end(), positions.begin(), [](const Point &p) {
return p.center;
});
ANARIGeometry geom = anari::newObject<anari::Geometry>(d, "sphere");
anari::setAndReleaseParameter(d,
geom,
"vertex.position",
anari::newArray1D(d, positions.data(), positions.size()));
anari::setParameter(d, geom, "radius", 0.05f);
anari::commitParameters(d, geom);
auto mat = anari::newObject<anari::Material>(d, "matte");
anari::commitParameters(d, mat);
auto surface = anari::newObject<anari::Surface>(d);
anari::setAndReleaseParameter(d, surface, "geometry", geom);
anari::setAndReleaseParameter(d, surface, "material", mat);
anari::commitParameters(d, surface);
anari::setAndReleaseParameter(
d, m_world, "surface", anari::newArray1D(d, &surface));
anari::release(d, surface);
} else {
anari::unsetParameter(d, m_world, "surface");
}
anari::setAndReleaseParameter(
d, m_world, "volume", anari::newArray1D(d, &volume));
anari::release(d, volume);
// create and setup light
auto light = anari::newObject<anari::Light>(d, "directional");
anari::commitParameters(d, light);
anari::setAndReleaseParameter(
d, m_world, "light", anari::newArray1D(d, &light));
anari::release(d, light);
anari::commitParameters(d, m_world);
}
int main(int argc, const char **argv)
{
(void)argc;
(void)argv;
stbi_flip_vertically_on_write(1);
// image size
uvec2 imgSize = {1024 /*width*/, 768 /*height*/};
// camera
vec3 cam_pos = {0.f, 0.f, 0.f};
vec3 cam_up = {0.f, 1.f, 0.f};
vec3 cam_view = {0.1f, 0.f, 1.f};
// triangle mesh array
vec3 vertex[] = {{-1.0f, -1.0f, 3.0f},
{-1.0f, 1.0f, 3.0f},
{1.0f, -1.0f, 3.0f},
{0.1f, 0.1f, 0.3f}};
vec4 color[] = {{0.9f, 0.5f, 0.5f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.5f, 0.9f, 0.5f, 1.0f}};
uvec3 index[] = {{0, 1, 2}, {1, 2, 3}};
printf("initialize ANARI...");
anari::Library lib = anari::loadLibrary("usd", statusFunc);
anari::Extensions extensions =
anari::extension::getDeviceExtensionStruct(lib, "default");
if (!extensions.ANARI_KHR_GEOMETRY_TRIANGLE)
printf("WARNING: device doesn't support ANARI_KHR_GEOMETRY_TRIANGLE\n");
if (!extensions.ANARI_KHR_CAMERA_PERSPECTIVE)
printf("WARNING: device doesn't support ANARI_KHR_CAMERA_PERSPECTIVE\n");
if (!extensions.ANARI_KHR_LIGHT_DIRECTIONAL)
printf("WARNING: device doesn't support ANARI_KHR_LIGHT_DIRECTIONAL\n");
if (!extensions.ANARI_KHR_MATERIAL_MATTE)
printf("WARNING: device doesn't support ANARI_KHR_MATERIAL_MATTE\n");
ANARIDevice d = anariNewDevice(lib, "default");
printf("done!\n");
printf("setting up camera...");
// create and setup camera
auto camera = anari::newObject<anari::Camera>(d, "perspective");
anari::setParameter(
d, camera, "aspect", (float)imgSize[0] / (float)imgSize[1]);
anari::setParameter(d, camera, "position", cam_pos);
anari::setParameter(d, camera, "direction", cam_view);
anari::setParameter(d, camera, "up", cam_up);
anari::commitParameters(d, camera); // commit objects to indicate setting parameters is done
printf("done!\n");
printf("setting up scene...");
GravityVolume* volumeScene = new GravityVolume(d);
volumeScene->commit();
anari::World world = volumeScene->world();
printf("setting up renderer...");
// create renderer
auto renderer = anari::newObject<anari::Renderer>(d, "default");
// objects can be named for easier identification in debug output etc.
anari::setParameter(d, renderer, "name", "MainRenderer");
printf("done!\n");
// complete setup of renderer
vec4 bgColor = {1.f, 1.f, 1.f, 1.f};
anari::setParameter(d, renderer, "backgroundColor", bgColor); // white
anari::commitParameters(d, renderer);
// create and setup frame
auto frame = anari::newObject<anari::Frame>(d);
anari::setParameter(d, frame, "size", imgSize);
anari::setParameter(d, frame, "channel.color", ANARI_UFIXED8_RGBA_SRGB);
anari::setAndReleaseParameter(d, frame, "renderer", renderer);
anari::setAndReleaseParameter(d, frame, "camera", camera);
anari::setParameter(d, frame, "world", world);
anari::commitParameters(d, frame);
printf("rendering out USD objects via anari::renderFrame()...");
// render one frame
anari::render(d, frame);
anari::wait(d, frame);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anari::release(d, frame);
delete volumeScene;
anari::release(d, d);
anari::unloadLibrary(lib);
printf("done!\n");
return 0;
}
| 10,686 | C++ | 27.422872 | 94 | 0.644582 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_time.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
int main(int argc, const char **argv)
{
stbi_flip_vertically_on_write(1);
// image size
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
// camera
float cam_pos[] = {0.f, 0.f, 0.f};
float cam_up[] = {0.f, 1.f, 0.f};
float cam_view[] = {0.1f, 0.f, 1.f};
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = {-1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f};
float color[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f};
float sphereSizes[] = { 0.1f,
2.0f,
0.3f,
0.05f };
int32_t index[] = {0, 1, 2, 1, 2, 3};
float protoVertex[] = {-3.0f,
-1.0f,
-1.0f,
3.0f,
-1.0f,
-1.0f,
-3.0f,
1.0f,
-1.0f,
3.0f,
1.0f,
-1.0f,
-3.0f,
-1.0f,
1.0f,
3.0f,
-1.0f,
1.0f,
-3.0f,
1.0f,
1.0f,
3.0f,
1.0f,
1.0f};
float protoColor[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f,
0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float protoTexcoord[] = {
0.0f,
0.0f,
0.0f,
1.0f,
0.25f,
0.0f,
0.25f,
1.0f,
0.5f,
0.0f,
0.5f,
1.0f,
0.75f,
0.0f,
0.75f,
1.0f};
int32_t protoIndex[] = {0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1};
float protoTransform[16] = {
0.2f, 0.0f, 0.0f, 0.0f,
0.0f, 0.2f, 0.0f, 0.0f,
0.0f, 0.0f, 0.2f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
float kd[] = { 0.0f, 0.0f, 1.0f };
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return 1;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "ov-test");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
// Setup texture array
ANARIArray2D texArray = anariNewArray2D(dev, textureData, 0, 0, ANARI_UINT8_VEC3, textureSize[0], textureSize[1]); // Make sure this matches numTexComponents
printf("done!\n");
printf("setting up scene...");
double timeValues[] = { 1, 0, 2, 3, 5, 8, 4, 6, 7, 9, 10 };
double geomTimeValues[] = { 3, 0, 4, 9, 7, 8, 6, 5, 1, 2, 10 };
double matTimeValues[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int numTimeSteps = sizeof(timeValues) / sizeof(double);
int useVertexColors = 0;
int useTexture = 1;
int useUsdGeomPoints = 0;
// CREATE ALL TIMESTEPS:
for (int timeIdx = 0; timeIdx < numTimeSteps; ++timeIdx)
{
int doubleNodes = ((timeIdx % 3) == 1);
anariSetParameter(dev, dev, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, dev);
ANARIWorld world = anariNewWorld(dev);
// create and setup model and mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
float scaledVertex[12];
for (int v = 0; v < 12; ++v)
{
scaledVertex[v] = vertex[v] * (1.0f + timeIdx);
}
ANARIArray1D array = anariNewArray1D(dev, scaledVertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
int timevaryTexcoord = 0; // Texcoords are not timeVarying (should now appear in fullscene stage)
anariSetParameter(dev, mesh, "usd::timeVarying.attribute0", ANARI_BOOL, &timevaryTexcoord);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, geomTimeValues + timeIdx);
anariCommitParameters(dev, mesh);
ANARISampler sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_0");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_0");
float opacity = 1.0;// -timeIdx * 0.1f;
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacity);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, matTimeValues + timeIdx);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
ANARISurface surface;
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_0");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group;
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_0");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance[2];
instance[0] = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance[0], "name", ANARI_STRING, "tutorialInstance_0");
anariSetParameter(dev, instance[0], "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance[0], "group", ANARI_GROUP, &group);
anariRelease(dev, group);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
anariCommitParameters(dev, instance[0]);
if (doubleNodes)
{
//ANARIGeometry protoMesh = anariNewGeometry(dev, "triangle");
//anariSetParameter(dev, protoMesh, "name", ANARI_STRING, "tutorialProtoMesh");
//
//ANARIArray1D array = anariNewArray1D(dev, protoVertex, 0, 0, ANARI_FLOAT32_VEC3, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "vertex.position", ANARI_ARRAY, &array);
//anariRelease(dev, array); // we are done using this handle
//
//if (useVertexColors)
//{
// array = anariNewArray1D(dev, protoColor, 0, 0, ANARI_FLOAT32_VEC4, 8);
// anariCommitParameters(dev, array);
// anariSetParameter(dev, protoMesh, "vertex.color", ANARI_ARRAY, &array);
// anariRelease(dev, array);
//}
//
//array = anariNewArray1D(dev, protoTexcoord, 0, 0, ANARI_FLOAT32_VEC2, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "vertex.attribute0", ANARI_ARRAY, &array);
//anariRelease(dev, array);
//
//array = anariNewArray1D(dev, protoIndex, 0, 0, ANARI_INT32_VEC3, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "primitive.index", ANARI_ARRAY, &array);
//anariRelease(dev, array);
//
//anariCommitParameters(dev, protoMesh);
mesh = anariNewGeometry(dev, "sphere");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialPoints");
anariSetParameter(dev, mesh, "usd::useUsdGeomPoints", ANARI_BOOL, &useUsdGeomPoints);
//anariSetParameter(dev, mesh, "shapeType", ANARI_STRING, "cylinder");
//anariSetParameter(dev, mesh, "shapeGeometry", ANARI_GEOMETRY, &protoMesh);
//anariSetParameter(dev, mesh, "shapeTransform", ANARI_FLOAT32_MAT4, protoTransform);
//anariRelease(dev, protoMesh);
array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariSetParameter(dev, mesh, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, mesh);
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_1");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_1");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
// Only colors and opacities are timevarying
int timeVaryingMetallic = 1;
int timeVaryingOpacities = 1;
anariSetParameter(dev, mat, "usd::timeVarying.metallic", ANARI_BOOL, &timeVaryingMetallic);
anariSetParameter(dev, mat, "usd::timeVarying.opacity", ANARI_BOOL, &timeVaryingOpacities);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_1");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_1");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
instance[1] = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance[1], "name", ANARI_STRING, "tutorialInstance_1");
anariSetParameter(dev, instance[1], "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance[1], "group", ANARI_GROUP, &group);
anariRelease(dev, group);
anariCommitParameters(dev, instance[1]);
}
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, instance, 0, 0, ANARI_INSTANCE, (doubleNodes ? 2 : 1));
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance[0]);
if (doubleNodes)
anariRelease(dev, instance[1]);
anariRelease(dev, array);
anariCommitParameters(dev, world);
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, frame);
anariRelease(dev, world);
// USD-SPECIFIC RUNTIME:
// Remove unused prims in usd
// Only useful when objects are possibly removed over the whole timeline
anariSetParameter(dev, dev, "usd::garbageCollect", ANARI_VOID_POINTER, 0);
// Reset generation of unique names for next frame
// Only necessary when relying upon auto-generation of names instead of manual creation, AND not retaining ANARI objects over timesteps
anariSetParameter(dev, dev, "usd::removeUnusedNames", ANARI_VOID_POINTER, 0);
// ~
// Constant color get a bit more red every step
kd[0] = timeIdx / (float)numTimeSteps;
}
// CHANGE THE SCENE: Attach only the instance_1 to the world, so instance_0 gets removed.
for (int timeIdx = 0; timeIdx < numTimeSteps/2; ++timeIdx)
{
anariSetParameter(dev, dev, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, dev);
ANARIWorld world = anariNewWorld(dev);
ANARIArray1D array;
ANARIInstance instance;
ANARIGeometry mesh;
ANARISampler sampler;
ANARIMaterial mat;
ANARISurface surface;
ANARIGroup group;
{
mesh = anariNewGeometry(dev, "sphere");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialPoints");
anariSetParameter(dev, mesh, "usd::useUsdGeomPoints", ANARI_BOOL, &useUsdGeomPoints);
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariSetParameter(dev, mesh, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, timeValues + timeIdx*2); // Switch the child timestep for something else
anariCommitParameters(dev, mesh);
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_1");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_1");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, timeValues + timeIdx*2);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_1");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_1");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance_1");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
anariCommitParameters(dev, instance);
}
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, frame);
anariRelease(dev, world);
// USD-SPECIFIC RUNTIME:
// Remove unused prims in usd
// Only useful when objects are possibly removed over the whole timeline
anariSetParameter(dev, dev, "usd::garbageCollect", ANARI_VOID_POINTER, 0);
// Reset generation of unique names for next frame
// Only necessary when relying upon auto-generation of names instead of manual creation, AND not retaining ANARI objects over timesteps
anariSetParameter(dev, dev, "usd::removeUnusedNames", ANARI_VOID_POINTER, 0);
// ~
}
anariRelease(dev, camera);
anariRelease(dev, texArray);
anariRelease(dev, dev);
freeTexture(textureData);
printf("done!\n");
return 0;
}
| 24,190 | C | 34.315328 | 159 | 0.653989 |
NVIDIA-Omniverse/AnariUsdDevice/superbuild/README.md | # CMake superbuild for USD ANARI Device
This CMake script runs stand alone to optionally build together any of:
- ANARIUsd Device (parent directory)
- ANARI-SDK
- USD + dependencies
The result of building this project is all the contents of the above (if built)
installed to `CMAKE_INSTALL_PREFIX`.
## Build setup
Run CMake (3.16+) on this directory from an empty build directory. This might
look like:
```bash
% mkdir _build
% cd _build
% cmake /path/to/superbuild
```
You can use tools like `ccmake` or `cmake-gui` to see what options you have. The
following variables control which items are to be built, and with which capabilities:
- `BUILD_ANARI_SDK` : build the [ANARI-SDK](https://github.com/KhronosGroup/ANARI-SDK)
- `BUILD_ANARI_USD_DEVICE`: build the root
- `BUILD_USD`: build USD + its dependencies (experimental, `OFF` by default)
- Requires preinstalled boost + tbb in `CMAKE_PREFIX_PATH`
- `USD_DEVICE_USE_OPENVDB`: Add OpenVDB output capability for ANARI volumes to the USD device
- Introduces `USE_USD_OPENVDB_BUILD`: If `ON` (default), OpenVDB is included within the USD installation
- `USD_DEVICE_USE_OMNIVERSE`: Add Omniverse output capability for generated USD output
If `BUILD_USD` or `BUILD_ANARI_SDK` are set to `OFF`, then those dependencies
will need to be found in the host environment. Use `CMAKE_PREFIX_PATH` to
point to your USD + ANARI-SDK (+ OpenVDB + Omniverse) installations respectively. Alternatively,
one can use explicit install dir variables which support `debug/` and `release/` subdirs:
- `ANARI_ROOT_DIR`: for the ANARI-SDK install directory
- `USD_ROOT_DIR`: for the USD install directory
- `OpenVDB_ROOT`: for the OpenVDB install directory (if not `USE_USD_OPENVDB_BUILD`)
- `OMNICLIENT_ROOT_DIR`: for the OmniClient install directory (typically `omni_client_library` from the connect sample deps). Requires:
- `OMNIUSDRESOLVER_ROOT_DIR`: the Omniverse Resolver install directory (typically `omni_usd_resolver` from the connect sample deps).
- `ZLIB_ROOT`: for the ZLIB install directory, required for Linux builds
For ease of use, if you want the USD and Omniverse libraries to be copied into the installation's `bin`
directory, make sure `USD_DEVICE_INSTALL_DEPS` is turned on. Otherwise, all dependency folders have to
be manually included into the path before executing the device binaries.
Lastly, the `BUILD_ANARI_USD_DEVICE` option lets you turn off building the device if you
only want to build the device's dependencies (mostly this is for developers).
## Build
Once you have set up the variables according to your situation, you can invoke the build (Linux) with:
```bash
% cmake --build .
```
or open `_build/anari_usd_superbuild.sln` (Windows) and build/install any configuration from there.
The resulting `install/` directory will contain everything that was built. You
can change the location of this install by setting `CMAKE_INSTALL_PREFIX`.
| 2,931 | Markdown | 44.107692 | 136 | 0.761515 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeCaches.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef OmniBridgeCaches_h
#define OmniBridgeCaches_h
#include <string>
#include <map>
#include <vector>
#include <memory>
#include "UsdBridgeData.h"
#include "UsdBridgeUtils_Internal.h"
struct UsdBridgePrimCache;
class UsdBridgeUsdWriter;
class UsdBridgePrimCacheManager;
typedef std::pair<std::string, UsdStageRefPtr> UsdStagePair; //Stage ptr and filename
typedef std::pair<std::pair<bool,bool>, UsdBridgePrimCache*> BoolEntryPair; // Prim exists in stage, prim exists in cache, result cache entry ptr
typedef void (*ResourceCollectFunc)(UsdBridgePrimCache*, UsdBridgeUsdWriter&);
typedef std::function<void(UsdBridgePrimCache*)> AtRemoveFunc;
typedef std::vector<UsdBridgePrimCache*> UsdBridgePrimCacheList;
typedef std::vector<SdfPath> SdfPrimPathList;
struct UsdBridgeResourceKey
{
UsdBridgeResourceKey() = default;
~UsdBridgeResourceKey() = default;
UsdBridgeResourceKey(const UsdBridgeResourceKey& key) = default;
UsdBridgeResourceKey(const char* n, double t)
{
name = n;
#ifdef TIME_BASED_CACHING
timeStep = t;
#endif
}
const char* name;
#ifdef TIME_BASED_CACHING
double timeStep;
#endif
bool operator==(const UsdBridgeResourceKey& rhs) const
{
return ( name ? (rhs.name ? (strEquals(name, rhs.name)
#ifdef TIME_BASED_CACHING
&& timeStep == rhs.timeStep
#endif
) : false ) : !rhs.name);
}
};
struct UsdBridgeRefCache
{
public:
friend class UsdBridgePrimCacheManager;
protected:
void IncRef() { ++RefCount; }
void DecRef() { --RefCount; }
unsigned int RefCount = 0;
};
struct UsdBridgePrimCache : public UsdBridgeRefCache
{
public:
friend class UsdBridgePrimCacheManager;
using ResourceContainer = std::vector<UsdBridgeResourceKey>;
//Constructors
UsdBridgePrimCache(const SdfPath& pp, const SdfPath& nm, ResourceCollectFunc cf);
UsdBridgePrimCache* GetChildCache(const TfToken& nameToken);
bool AddResourceKey(UsdBridgeResourceKey key);
SdfPath PrimPath;
SdfPath Name;
ResourceCollectFunc ResourceCollect;
std::unique_ptr<ResourceContainer> ResourceKeys; // Referenced resources
#ifdef TIME_BASED_CACHING
void SetChildVisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode);
bool SetChildInvisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode); // Returns whether timeCode has been removed AND the visible timeset is empty.
#endif
#ifdef VALUE_CLIP_RETIMING
static constexpr double PrimStageTimeCode = 0.0; // Prim stages are stored in ClipStages under specified time code
const UsdStagePair& GetPrimStagePair() const;
template<typename DataMemberType>
bool TimeVarBitsUpdate(DataMemberType newTimeVarBits);
UsdStagePair ManifestStage; // Holds the manifest
std::unordered_map<double, UsdStagePair> ClipStages; // Holds the stage(s) to the timevarying data
uint32_t LastTimeVaryingBits = 0; // Used to detect changes in timevarying status of parameters
#endif
#ifndef NDEBUG
std::string Debug_Name;
#endif
protected:
void AddChild(UsdBridgePrimCache* child);
void RemoveChild(UsdBridgePrimCache* child);
void RemoveUnreferencedChildTree(AtRemoveFunc atRemove);
std::vector<UsdBridgePrimCache*> Children;
#ifdef TIME_BASED_CACHING
// For each child, hold a vector of timesteps where it's visible (mimicks visibility attribute on the referencing prim)
std::vector<std::vector<double>> ChildVisibleAtTimes;
#endif
};
class UsdBridgePrimCacheManager
{
public:
typedef std::unordered_map<std::string, std::unique_ptr<UsdBridgePrimCache>> PrimCacheContainer;
typedef PrimCacheContainer::iterator PrimCacheIterator;
typedef PrimCacheContainer::const_iterator ConstPrimCacheIterator;
inline UsdBridgePrimCache* ConvertToPrimCache(const UsdBridgeHandle& handle) const
{
#ifndef NDEBUG
auto primCacheIt = FindPrimCache(handle);
assert(ValidIterator(primCacheIt));
#endif
return handle.value;
}
ConstPrimCacheIterator FindPrimCache(const std::string& name) const { return UsdPrimCaches.find(name); }
ConstPrimCacheIterator FindPrimCache(const UsdBridgeHandle& handle) const;
inline bool ValidIterator(ConstPrimCacheIterator it) const { return it != UsdPrimCaches.end(); }
ConstPrimCacheIterator CreatePrimCache(const std::string& name, const std::string& fullPath, ResourceCollectFunc collectFunc = nullptr);
void RemovePrimCache(ConstPrimCacheIterator it, UsdBridgeLogObject& LogObject);
void RemoveUnreferencedPrimCaches(AtRemoveFunc atRemove);
void AddChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child);
void RemoveChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child);
void AttachTopLevelPrim(UsdBridgePrimCache* primCache);
void DetachTopLevelPrim(UsdBridgePrimCache* primCache);
protected:
PrimCacheContainer UsdPrimCaches;
};
#ifdef VALUE_CLIP_RETIMING
template<typename DataMemberType>
bool UsdBridgePrimCache::TimeVarBitsUpdate(DataMemberType newTimeVarBits)
{
uint32_t newBits = static_cast<uint32_t>(newTimeVarBits);
bool hasChanged = (LastTimeVaryingBits != newBits);
LastTimeVaryingBits = newBits;
return hasChanged;
}
#endif
#endif | 5,182 | C | 30.035928 | 165 | 0.780973 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Material.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
#include "stb_image_write.h"
#include <limits>
_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)::_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)()
: roughness(TfToken("inputs:roughness", TfToken::Immortal))
, opacity(TfToken("inputs:opacity", TfToken::Immortal))
, metallic(TfToken("inputs:metallic", TfToken::Immortal))
, ior(TfToken("inputs:ior", TfToken::Immortal))
, diffuseColor(TfToken("inputs:diffuseColor", TfToken::Immortal))
, specularColor(TfToken("inputs:specularColor", TfToken::Immortal))
, emissiveColor(TfToken("inputs:emissiveColor", TfToken::Immortal))
, file(TfToken("inputs:file", TfToken::Immortal))
, WrapS(TfToken("inputs:WrapS", TfToken::Immortal))
, WrapT(TfToken("inputs:WrapT", TfToken::Immortal))
, WrapR(TfToken("inputs:WrapR", TfToken::Immortal))
, varname(TfToken("inputs:varname", TfToken::Immortal))
, reflection_roughness_constant(TfToken("inputs:reflection_roughness_constant", TfToken::Immortal))
, opacity_constant(TfToken("inputs:opacity_constant", TfToken::Immortal))
, metallic_constant(TfToken("inputs:metallic_constant", TfToken::Immortal))
, ior_constant(TfToken("inputs:ior_constant"))
, diffuse_color_constant(TfToken("inputs:diffuse_color_constant", TfToken::Immortal))
, emissive_color(TfToken("inputs:emissive_color", TfToken::Immortal))
, emissive_intensity(TfToken("inputs:emissive_intensity", TfToken::Immortal))
, enable_emission(TfToken("inputs:enable_emission", TfToken::Immortal))
, name(TfToken("inputs:name", TfToken::Immortal))
, tex(TfToken("inputs:tex", TfToken::Immortal))
, wrap_u(TfToken("inputs:wrap_u", TfToken::Immortal))
, wrap_v(TfToken("inputs:wrap_v", TfToken::Immortal))
, wrap_w(TfToken("inputs:wrap_w", TfToken::Immortal))
{}
_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)::~_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)() = default;
TfStaticData<_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)> QualifiedInputTokens;
_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)::_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)()
: r(TfToken("outputs:r", TfToken::Immortal))
, rg(TfToken("outputs:rg", TfToken::Immortal))
, rgb(TfToken("outputs:rgb", TfToken::Immortal))
, a(TfToken("outputs:a", TfToken::Immortal))
, out(TfToken("outputs:out", TfToken::Immortal))
{}
_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)::~_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)() = default;
TfStaticData<_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)> QualifiedOutputTokens;
namespace
{
struct StbWriteOutput
{
StbWriteOutput() = default;
~StbWriteOutput()
{
delete[] imageData;
}
char* imageData = nullptr;
size_t imageSize = 0;
};
void StbWriteToBuffer(void *context, void *data, int size)
{
if(data)
{
StbWriteOutput* output = reinterpret_cast<StbWriteOutput*>(context);
output->imageData = new char[size];
output->imageSize = size;
memcpy(output->imageData, data, size);
}
}
template<typename CType>
void ConvertSamplerData_Inner(const UsdBridgeSamplerData& samplerData, double normFactor, std::vector<unsigned char>& imageData)
{
int numComponents = samplerData.ImageNumComponents;
uint64_t imageDimX = samplerData.ImageDims[0];
uint64_t imageDimY = samplerData.ImageDims[1];
int64_t yStride = samplerData.ImageStride[1];
const char* samplerDataPtr = reinterpret_cast<const char*>(samplerData.Data);
int64_t baseAddr = 0;
for(uint64_t pY = 0; pY < imageDimY; ++pY, baseAddr += yStride)
{
const CType* lineAddr = reinterpret_cast<const CType*>(samplerDataPtr + baseAddr);
for(uint64_t flatX = 0; flatX < imageDimX*numComponents; ++flatX) //flattened X index
{
uint64_t dstElt = numComponents*pY*imageDimX + flatX;
double result = *(lineAddr+flatX)*normFactor;
result = (result < 0.0) ? 0.0 : ((result > 255.0) ? 255.0 : result);
imageData[dstElt] = static_cast<unsigned char>(result);
}
}
}
void ConvertSamplerDataToImage(const UsdBridgeSamplerData& samplerData, std::vector<unsigned char>& imageData)
{
UsdBridgeType flattenedType = ubutils::UsdBridgeTypeFlatten(samplerData.DataType);
int numComponents = samplerData.ImageNumComponents;
uint64_t imageDimX = samplerData.ImageDims[0];
uint64_t imageDimY = samplerData.ImageDims[1];
bool normalizedFp = (flattenedType == UsdBridgeType::FLOAT) || (flattenedType == UsdBridgeType::DOUBLE);
bool fixedPoint = (flattenedType == UsdBridgeType::USHORT) || (flattenedType == UsdBridgeType::UINT);
if(normalizedFp || fixedPoint)
{
imageData.resize(numComponents*imageDimX*imageDimY);
switch(flattenedType)
{
case UsdBridgeType::FLOAT: ConvertSamplerData_Inner<float>(samplerData, 255.0, imageData); break;
case UsdBridgeType::DOUBLE: ConvertSamplerData_Inner<double>(samplerData, 255.0, imageData); break;
case UsdBridgeType::USHORT: ConvertSamplerData_Inner<unsigned short>(samplerData,
255.0 / static_cast<double>(std::numeric_limits<unsigned short>::max()), imageData); break;
case UsdBridgeType::UINT: ConvertSamplerData_Inner<unsigned int>(samplerData,
255.0 / static_cast<double>(std::numeric_limits<unsigned int>::max()), imageData); break;
default: break;
}
}
}
template<typename DataType>
void CreateShaderInput(UsdShadeShader& shader, const TimeEvaluator<DataType>* timeEval, typename DataType::DataMemberId dataMemberId,
const TfToken& inputToken, const TfToken& qualifiedInputToken, const SdfValueTypeName& valueType)
{
if(!timeEval || timeEval->IsTimeVarying(dataMemberId))
shader.CreateInput(inputToken, valueType);
else
shader.GetPrim().RemoveProperty(qualifiedInputToken);
}
template<bool PreviewSurface>
void CreateMaterialShaderInput(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval,
typename UsdBridgeMaterialData::DataMemberId dataMemberId, const SdfValueTypeName& valueType)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
const TfToken& qualifiedInputToken = GetMaterialShaderInputQualifiedToken<PreviewSurface>(dataMemberId);
CreateShaderInput(shader, timeEval, dataMemberId, inputToken, qualifiedInputToken, valueType);
}
template<typename ValueType, typename DataType>
void SetShaderInput(UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const TimeEvaluator<DataType>& timeEval,
const TfToken& inputToken, typename DataType::DataMemberId dataMemberId, ValueType value)
{
using DMI = typename DataType::DataMemberId;
bool timeVaryingUpdate = timeEval.IsTimeVarying(dataMemberId);
UsdShadeInput timeVarInput, uniformInput;
UsdAttribute uniformAttrib, timeVarAttrib;
if(timeVarShadPrim) // Allow for non-existing prims (based on timeVaryingUpdate)
{
timeVarInput = timeVarShadPrim.GetInput(inputToken);
assert(timeVarInput);
timeVarAttrib = timeVarInput.GetAttr();
}
if(uniformShadPrim)
{
uniformInput = uniformShadPrim.GetInput(inputToken);
assert(uniformInput);
uniformAttrib = uniformInput.GetAttr();
}
// Clear the attributes that are not set (based on timeVaryingUpdate)
ClearUsdAttributes(uniformAttrib, timeVarAttrib, timeVaryingUpdate);
// Set the input that requires an update
SET_TIMEVARYING_ATTRIB(timeVaryingUpdate, timeVarInput, uniformInput, value);
}
UsdShadeOutput InitializeMdlGraphNode(UsdShadeShader& graphNode, const TfToken& assetSubIdent, const SdfValueTypeName& returnType,
const char* sourceAssetPath = constring::mdlSupportAssetName)
{
graphNode.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
graphNode.SetSourceAsset(SdfAssetPath(sourceAssetPath), UsdBridgeTokens->mdl);
graphNode.SetSourceAssetSubIdentifier(assetSubIdent, UsdBridgeTokens->mdl);
return graphNode.CreateOutput(UsdBridgeTokens->out, returnType);
}
struct ShadeGraphTypeConversionNodeContext
{
ShadeGraphTypeConversionNodeContext(UsdStageRefPtr sceneStage,
const SdfPath& matPrimPath,
const char* connectionIdentifier)
: SceneStage(sceneStage)
, MatPrimPath(matPrimPath)
, ConnectionIdentifier(connectionIdentifier)
{
}
// sourceOutput is set to the new node's output upon return
UsdShadeShader CreateAndConnectMdlTypeConversionNode(UsdShadeOutput& sourceOutput, const char* primNamePf, const TfToken& assetSubIdent,
const SdfValueTypeName& inType, const SdfValueTypeName& outType, const char* sourceAssetPath = constring::mdlSupportAssetName) const
{
SdfPath nodePrimPath = this->MatPrimPath.AppendPath(SdfPath(std::string(this->ConnectionIdentifier)+primNamePf));
UsdShadeShader conversionNode = UsdShadeShader::Get(this->SceneStage, nodePrimPath);
UsdShadeOutput nodeOut;
if(!conversionNode)
{
conversionNode = UsdShadeShader::Define(this->SceneStage, nodePrimPath);
assert(conversionNode);
nodeOut = InitializeMdlGraphNode(conversionNode, assetSubIdent, outType, sourceAssetPath);
conversionNode.CreateInput(UsdBridgeTokens->a, inType);
}
else
nodeOut = conversionNode.GetOutput(UsdBridgeTokens->out);
conversionNode.GetInput(UsdBridgeTokens->a).ConnectToSource(sourceOutput);
sourceOutput = nodeOut;
return conversionNode;
}
void InsertMdlShaderTypeConversionNodes(const UsdShadeInput& shadeInput, UsdShadeOutput& nodeOutput) const
{
if(shadeInput.GetTypeName() == SdfValueTypeNames->Color3f)
{
// Introduce new nodes until the type matches color3f.
// Otherwise, just connect any random output type to the input.
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float4)
{
// Changes nodeOutput to the output of the new node
CreateAndConnectMdlTypeConversionNode(nodeOutput, constring::mdlGraphXYZPrimPf,
UsdBridgeTokens->xyz, SdfValueTypeNames->Float4, SdfValueTypeNames->Float3, constring::mdlAuxAssetName);
}
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float3)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, constring::mdlGraphColorPrimPf,
UsdBridgeTokens->construct_color, SdfValueTypeNames->Float3, SdfValueTypeNames->Color3f, constring::mdlAuxAssetName);
}
}
if(shadeInput.GetTypeName() == SdfValueTypeNames->Float)
{
const char* componentPrimPf = constring::mdlGraphWPrimPf;
TfToken componentAssetIdent = (nodeOutput.GetTypeName() == SdfValueTypeNames->Float4) ? UsdBridgeTokens->w : UsdBridgeTokens->x;
switch(ChannelSelector)
{
case 0: componentPrimPf = constring::mdlGraphXPrimPf; componentAssetIdent = UsdBridgeTokens->x; break;
case 1: componentPrimPf = constring::mdlGraphYPrimPf; componentAssetIdent = UsdBridgeTokens->y; break;
case 2: componentPrimPf = constring::mdlGraphZPrimPf; componentAssetIdent = UsdBridgeTokens->z; break;
default: break;
}
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float4)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, componentPrimPf,
componentAssetIdent, SdfValueTypeNames->Float4, SdfValueTypeNames->Float, constring::mdlAuxAssetName);
}
else if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float3)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, componentPrimPf,
componentAssetIdent, SdfValueTypeNames->Float3, SdfValueTypeNames->Float, constring::mdlAuxAssetName);
}
}
}
UsdStageRefPtr SceneStage;
const SdfPath& MatPrimPath;
const char* ConnectionIdentifier = nullptr;
// Optional
int ChannelSelector = 0;
};
void InitializePsShaderUniform(UsdShadeShader& shader)
{
shader.CreateIdAttr(VtValue(UsdBridgeTokens->UsdPreviewSurface));
shader.CreateInput(UsdBridgeTokens->useSpecularWorkflow, SdfValueTypeNames->Int).Set(0);
}
void InitializePsShaderTimeVar(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
CreateMaterialShaderInput<true>(shader, timeEval, DMI::DIFFUSE, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::EMISSIVECOLOR, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::ROUGHNESS, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::OPACITY, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::METALLIC, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::IOR, SdfValueTypeNames->Float);
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->opacityThreshold, QualifiedInputTokens->opacityThreshold, SdfValueTypeNames->Float);
}
void InitializeMdlShaderUniform(UsdShadeShader& shader)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
shader.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
shader.SetSourceAsset(SdfAssetPath(constring::mdlShaderAssetName), UsdBridgeTokens->mdl);
shader.SetSourceAssetSubIdentifier(UsdBridgeTokens->OmniPBR, UsdBridgeTokens->mdl);
shader.CreateInput(GetMaterialShaderInputToken<false>(DMI::OPACITY), SdfValueTypeNames->Float); // Opacity is handled by the opacitymul node
}
void InitializeMdlShaderTimeVar(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
CreateMaterialShaderInput<false>(shader, timeEval, DMI::DIFFUSE, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::EMISSIVECOLOR, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::EMISSIVEINTENSITY, SdfValueTypeNames->Float);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::ROUGHNESS, SdfValueTypeNames->Float);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::METALLIC, SdfValueTypeNames->Float);
//CreateMaterialShaderInput<false>(shader, timeEval, DMI::IOR, SdfValueTypeNames->Float); // not supported in OmniPBR.mdl
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->enable_opacity, QualifiedInputTokens->enable_opacity, SdfValueTypeNames->Bool);
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->opacity_threshold, QualifiedInputTokens->opacity_threshold, SdfValueTypeNames->Float);
CreateShaderInput(shader, timeEval, DMI::EMISSIVEINTENSITY, UsdBridgeTokens->enable_emission, QualifiedInputTokens->enable_emission, SdfValueTypeNames->Bool);
}
UsdShadeOutput InitializePsAttributeReaderUniform(UsdShadeShader& attributeReader, const TfToken& readerId, const SdfValueTypeName& returnType)
{
attributeReader.CreateIdAttr(VtValue(readerId));
// Input name and output type are tightly coupled; output type cannot be timevarying, so neither can the name
attributeReader.CreateInput(UsdBridgeTokens->varname, SdfValueTypeNames->Token);
return attributeReader.CreateOutput(UsdBridgeTokens->result, returnType);
}
template<typename DataType>
void InitializePsAttributeReaderTimeVar(UsdShadeShader& attributeReader, typename DataType::DataMemberId dataMemberId, const TimeEvaluator<DataType>* timeEval)
{
//CreateShaderInput(attributeReader, timeEval, dataMemberId, UsdBridgeTokens->varname, QualifiedInputTokens->varname, SdfValueTypeNames->Token);
}
UsdShadeOutput InitializeMdlAttributeReaderUniform(UsdShadeShader& attributeReader, const TfToken& readerId, const SdfValueTypeName& returnType)
{
attributeReader.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
attributeReader.SetSourceAsset(SdfAssetPath(constring::mdlSupportAssetName), UsdBridgeTokens->mdl);
attributeReader.SetSourceAssetSubIdentifier(readerId, UsdBridgeTokens->mdl);
// Input name and output type are tightly coupled; output type cannot be timevarying, so neither can the name
attributeReader.CreateInput(UsdBridgeTokens->name, SdfValueTypeNames->String);
return attributeReader.CreateOutput(UsdBridgeTokens->out, returnType);
}
template<typename DataType>
void InitializeMdlAttributeReaderTimeVar(UsdShadeShader& attributeReader, typename DataType::DataMemberId dataMemberId, const TimeEvaluator<DataType>* timeEval)
{
//CreateShaderInput(attributeReader, timeEval, dataMemberId, UsdBridgeTokens->name, QualifiedInputTokens->name, SdfValueTypeNames->String);
}
void InitializePsSamplerUniform(UsdShadeShader& sampler, const SdfValueTypeName& coordType, const UsdShadeOutput& tcrOutput)
{
sampler.CreateIdAttr(VtValue(UsdBridgeTokens->UsdUVTexture));
sampler.CreateOutput(UsdBridgeTokens->rgb, SdfValueTypeNames->Float3); // Input images with less components are automatically expanded, see usd docs
sampler.CreateOutput(UsdBridgeTokens->a, SdfValueTypeNames->Float);
sampler.CreateInput(UsdBridgeTokens->fallback, SdfValueTypeNames->Float4).Set(GfVec4f(1.0f, 0.0f, 0.0f, 1.0f));
// Bind the texcoord reader's output to the sampler's st input
sampler.CreateInput(UsdBridgeTokens->st, coordType).ConnectToSource(tcrOutput);
}
void InitializePsSamplerTimeVar(UsdShadeShader& sampler, UsdBridgeSamplerData::SamplerType type, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
CreateShaderInput(sampler, timeEval, DMI::DATA, UsdBridgeTokens->file, QualifiedInputTokens->file, SdfValueTypeNames->Asset);
CreateShaderInput(sampler, timeEval, DMI::WRAPS, UsdBridgeTokens->WrapS, QualifiedInputTokens->WrapS, SdfValueTypeNames->Token);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
CreateShaderInput(sampler, timeEval, DMI::WRAPT, UsdBridgeTokens->WrapT, QualifiedInputTokens->WrapT, SdfValueTypeNames->Token);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
CreateShaderInput(sampler, timeEval, DMI::WRAPR, UsdBridgeTokens->WrapR, QualifiedInputTokens->WrapR, SdfValueTypeNames->Token);
}
void InitializeMdlSamplerUniform(UsdShadeShader& sampler, const SdfValueTypeName& coordType, const UsdShadeOutput& tcrOutput)
{
sampler.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
sampler.SetSourceAsset(SdfAssetPath(constring::mdlSupportAssetName), UsdBridgeTokens->mdl);
sampler.SetSourceAssetSubIdentifier(UsdBridgeTokens->lookup_float4, UsdBridgeTokens->mdl);
sampler.CreateOutput(UsdBridgeTokens->out, SdfValueTypeNames->Float4);
// Bind the texcoord reader's output to the sampler's coord input
sampler.CreateInput(UsdBridgeTokens->coord, coordType).ConnectToSource(tcrOutput);
}
void InitializeMdlSamplerTimeVar(UsdShadeShader& sampler, UsdBridgeSamplerData::SamplerType type, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
CreateShaderInput(sampler, timeEval, DMI::DATA, UsdBridgeTokens->tex, QualifiedInputTokens->tex, SdfValueTypeNames->Asset);
CreateShaderInput(sampler, timeEval, DMI::WRAPS, UsdBridgeTokens->wrap_u, QualifiedInputTokens->wrap_u, SdfValueTypeNames->Int);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
CreateShaderInput(sampler, timeEval, DMI::WRAPT, UsdBridgeTokens->wrap_v, QualifiedInputTokens->wrap_v, SdfValueTypeNames->Int);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
CreateShaderInput(sampler, timeEval, DMI::WRAPR, UsdBridgeTokens->wrap_w, QualifiedInputTokens->wrap_w, SdfValueTypeNames->Int);
}
UsdShadeOutput InitializePsShader(UsdStageRefPtr shaderStage, const SdfPath& matPrimPath, bool uniformPrim
, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
// Create the shader
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader shader = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath);
assert(shader);
if (uniformPrim)
{
InitializePsShaderUniform(shader);
}
InitializePsShaderTimeVar(shader, timeEval);
if(uniformPrim)
return shader.CreateOutput(UsdBridgeTokens->surface, SdfValueTypeNames->Token);
else
return UsdShadeOutput();
}
UsdShadeOutput InitializeMdlShader(UsdStageRefPtr shaderStage, const SdfPath& matPrimPath, bool uniformPrim
, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
// Create the shader
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
UsdShadeShader shader = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath);
assert(shader);
// Create a mul shader node (for connection to opacity)
SdfPath shadPrimPath_opmul = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader opacityMul = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath_opmul);
assert(opacityMul);
UsdShadeOutput opacityMulOut;
if(uniformPrim)
{
opacityMulOut = InitializeMdlGraphNode(opacityMul, UsdBridgeTokens->mul_float, SdfValueTypeNames->Float);
opacityMul.CreateInput(UsdBridgeTokens->a, SdfValueTypeNames->Float); // Input a is either connected (to sampler/vc opacity) or 1.0, so never timevarying
InitializeMdlShaderUniform(shader);
}
CreateShaderInput(opacityMul, timeEval, DMI::OPACITY, UsdBridgeTokens->b, QualifiedInputTokens->b, SdfValueTypeNames->Float);
InitializeMdlShaderTimeVar(shader, timeEval);
// Connect the opacity mul node to the shader
if(uniformPrim)
{
shader.GetInput(GetMaterialShaderInputToken<false>(DMI::OPACITY)).ConnectToSource(opacityMulOut);
}
if(uniformPrim)
return shader.CreateOutput(UsdBridgeTokens->out, SdfValueTypeNames->Token);
else
return UsdShadeOutput();
}
void BindShaderToMaterial(const UsdShadeMaterial& matPrim, const UsdShadeOutput& shadOut, TfToken* renderContext)
{
// Bind the material to the shader reference subprim.
if(renderContext)
matPrim.CreateSurfaceOutput(*renderContext).ConnectToSource(shadOut);
else
matPrim.CreateSurfaceOutput().ConnectToSource(shadOut);
}
UsdShadeMaterial InitializeUsdMaterial_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
// Create the material
UsdShadeMaterial matPrim = GetOrDefinePrim<UsdShadeMaterial>(materialStage, matPrimPath);
assert(matPrim);
if(settings.EnablePreviewSurfaceShader)
{
// Create a shader
UsdShadeOutput shaderOutput = InitializePsShader(materialStage, matPrimPath, uniformPrim, timeEval);
if(uniformPrim)
BindShaderToMaterial(matPrim, shaderOutput, nullptr);
}
if(settings.EnableMdlShader)
{
// Create an mdl shader
UsdShadeOutput shaderOutput = InitializeMdlShader(materialStage, matPrimPath, uniformPrim, timeEval);
if(uniformPrim)
BindShaderToMaterial(matPrim, shaderOutput, &UsdBridgeTokens->mdl);
}
return matPrim;
}
UsdPrim InitializePsSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
UsdShadeShader sampler = GetOrDefinePrim<UsdShadeShader>(samplerStage, samplerPrimPath);
assert(sampler);
if(uniformPrim)
{
SdfPath texCoordReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader texCoordReader = UsdShadeShader::Define(samplerStage, texCoordReaderPrimPath);
assert(texCoordReader);
// USD does not yet allow for anything but 2D coords, but let's try anyway
TfToken idAttrib;
SdfValueTypeName valueType;
if(type == UsdBridgeSamplerData::SamplerType::SAMPLER_1D)
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float;
valueType = SdfValueTypeNames->Float;
}
else if (type == UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float2;
valueType = SdfValueTypeNames->Float2;
}
else
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float3;
valueType = SdfValueTypeNames->Float3;
}
UsdShadeOutput tcrOutput = InitializePsAttributeReaderUniform(texCoordReader, idAttrib, valueType);
InitializePsSamplerUniform(sampler, valueType, tcrOutput);
}
//InitializePsAttributeReaderTimeVar(texCoordReader, DMI::INATTRIBUTE, timeEval); // timevar attribute reader disabled
InitializePsSamplerTimeVar(sampler, type, timeEval);
return sampler.GetPrim();
}
UsdPrim InitializeMdlSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
UsdShadeShader sampler = GetOrDefinePrim<UsdShadeShader>(samplerStage, samplerPrimPath);
assert(sampler);
if(uniformPrim)
{
SdfPath texCoordReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader texCoordReader = UsdShadeShader::Define(samplerStage, texCoordReaderPrimPath);
assert(texCoordReader);
// USD does not yet allow for anything but 2D coords, but let's try anyway
TfToken idAttrib;
SdfValueTypeName valueType;
if(type == UsdBridgeSamplerData::SamplerType::SAMPLER_1D)
{
idAttrib = UsdBridgeTokens->data_lookup_float2; // Currently, there is no 1D lookup
valueType = SdfValueTypeNames->Float2;
}
else if (type == UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
{
idAttrib = UsdBridgeTokens->data_lookup_float2;
valueType = SdfValueTypeNames->Float2;
}
else
{
idAttrib = UsdBridgeTokens->data_lookup_float3;
valueType = SdfValueTypeNames->Float3;
}
UsdShadeOutput tcrOutput = InitializeMdlAttributeReaderUniform(texCoordReader, idAttrib, valueType);
InitializeMdlSamplerUniform(sampler, valueType, tcrOutput);
}
//InitializeMdlAttributeReaderTimeVar(texCoordReader, DMI::INATTRIBUTE, timeEval); // timevar attribute reader disabled
InitializeMdlSamplerTimeVar(sampler, type, timeEval);
if(uniformPrim)
{
sampler.GetInput(UsdBridgeTokens->tex).GetAttr().SetMetadata(UsdBridgeTokens->colorSpace, VtValue("sRGB"));
}
return sampler.GetPrim();
}
void InitializeSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const UsdBridgeSettings& settings, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
if(settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
InitializePsSampler_Impl(samplerStage, usdSamplerPrimPath, type, uniformPrim, timeEval);
}
if(settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
InitializeMdlSampler_Impl(samplerStage, usdSamplerPrimPath, type, uniformPrim, timeEval);
}
}
template<bool PreviewSurface>
UsdShadeShader InitializeAttributeReader_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim,
UsdBridgeMaterialData::DataMemberId dataMemberId, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
if(!uniformPrim) // timevar attribute reader disabled
return UsdShadeShader();
// Create a vertexcolorreader
SdfPath attributeReaderPath = matPrimPath.AppendPath(GetAttributeReaderPathPf<PreviewSurface>(dataMemberId));
UsdShadeShader attributeReader = UsdShadeShader::Get(materialStage, attributeReaderPath);
// Allow for uniform and timevar prims to return already existing prim without triggering re-initialization
// manifest <==> timeEval, and will always take this branch
if(!attributeReader || timeEval)
{
if(!attributeReader) // Currently no need for timevar properties on attribute readers
attributeReader = UsdShadeShader::Define(materialStage, attributeReaderPath);
if(PreviewSurface)
{
if(uniformPrim) // Implies !timeEval, so initialize
{
InitializePsAttributeReaderUniform(attributeReader, GetPsAttributeReaderId(dataMemberId), GetAttributeOutputType(dataMemberId));
}
// Create attribute reader varname, and if timeEval (manifest), can also remove the input
//InitializePsAttributeReaderTimeVar(attributeReader, dataMemberId, timeEval);
}
else
{
if(uniformPrim) // Implies !timeEval, so initialize
{
InitializeMdlAttributeReaderUniform(attributeReader, GetMdlAttributeReaderSubId(dataMemberId), GetAttributeOutputType(dataMemberId));
}
//InitializeMdlAttributeReaderTimeVar(attributeReader, dataMemberId, timeEval);
}
}
return attributeReader;
}
#define INITIALIZE_ATTRIBUTE_READER_MACRO(srcAttrib, dmi) \
if(srcAttrib) InitializeAttributeReader_Impl<PreviewSurface>(materialStage, matPrimPath, false, dmi, timeEval);
template<bool PreviewSurface>
void InitializeAttributeReaderSet(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const UsdBridgeSettings& settings,
const UsdBridgeMaterialData& matData, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Diffuse.SrcAttrib, DMI::DIFFUSE); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Opacity.SrcAttrib, DMI::OPACITY); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Emissive.SrcAttrib, DMI::EMISSIVECOLOR); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.EmissiveIntensity.SrcAttrib, DMI::EMISSIVEINTENSITY); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Roughness.SrcAttrib, DMI::ROUGHNESS);
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Metallic.SrcAttrib, DMI::METALLIC);
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Ior.SrcAttrib, DMI::IOR);
}
void InitializeAttributeReaders_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const UsdBridgeSettings& settings,
const UsdBridgeMaterialData& matData, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
// So far, only used for manifest, so no uniform path required for initialization of attribute readers.
// Instead, uniform and timevar attrib readers are created on demand per-attribute in GetOrCreateAttributeReaders().
if(settings.EnablePreviewSurfaceShader)
{
InitializeAttributeReaderSet<true>(materialStage, matPrimPath, settings, matData, timeEval);
}
if(settings.EnableMdlShader)
{
InitializeAttributeReaderSet<false>(materialStage, matPrimPath, settings, matData, timeEval);
}
}
template<bool PreviewSurface>
void GetOrCreateAttributeReaders(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, UsdBridgeMaterialData::DataMemberId dataMemberId,
UsdShadeShader& uniformReaderPrim)
{
uniformReaderPrim = InitializeAttributeReader_Impl<PreviewSurface>(sceneStage, matPrimPath, true, dataMemberId, nullptr);
//if(timeVarStage && (timeVarStage != sceneStage))
// timeVarReaderPrim = InitializeAttributeReader_Impl<PreviewSurface>(timeVarStage, matPrimPath, false, dataMemberId, nullptr);
}
template<bool PreviewSurface>
void UpdateAttributeReaderName(UsdShadeShader& uniformReaderPrim, const TfToken& nameToken)
{
// Set the correct attribute token for the reader varname
if(PreviewSurface)
{
uniformReaderPrim.GetInput(UsdBridgeTokens->varname).Set(nameToken);
}
else
{
uniformReaderPrim.GetInput(UsdBridgeTokens->name).Set(nameToken.GetString());
}
}
template<bool PreviewSurface>
void UpdateAttributeReaderOutput(UsdShadeShader& uniformReaderPrim, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TfToken& attribNameToken)
{
const TfToken& outAttribToken = PreviewSurface ? UsdBridgeTokens->result : UsdBridgeTokens->out;
UsdGeomPrimvar geomPrimvar = boundGeomPrimvars.GetPrimvar(attribNameToken);
UsdShadeOutput readerOutput = uniformReaderPrim.GetOutput(outAttribToken);
if(geomPrimvar)
{
const SdfValueTypeName& geomPrimTypeName = geomPrimvar.GetTypeName();
if(geomPrimTypeName != readerOutput.GetTypeName())
{
boundGeomPrimvars.GetPrim().RemoveProperty(PreviewSurface ? QualifiedOutputTokens->result : QualifiedOutputTokens->out);
uniformReaderPrim.CreateOutput(outAttribToken, geomPrimTypeName);
// Also change the asset subidentifier based on the outAttribToken
uniformReaderPrim.SetSourceAssetSubIdentifier(GetMdlAttributeReaderSubId(geomPrimTypeName), UsdBridgeTokens->mdl);
}
}
}
template<bool PreviewSurface>
void UpdateShaderInput_ShadeNode( const UsdShadeShader& uniformShaderIn, const UsdShadeShader& timeVarShaderIn, const TfToken& inputToken,
const UsdShadeShader& shadeNodeOut, const TfToken& outputToken,
const ShadeGraphTypeConversionNodeContext& conversionContext)
{
//Bind the shade node to the input of the uniform shader, so remove any existing values from the timeVar prim
UsdShadeInput timeVarInput = timeVarShaderIn.GetInput(inputToken);
if(timeVarInput)
timeVarInput.GetAttr().Clear();
// Connect shadeNode output to uniformShad input
UsdShadeOutput nodeOutput = shadeNodeOut.GetOutput(outputToken);
assert(nodeOutput);
UsdShadeInput shadeInput = uniformShaderIn.GetInput(inputToken);
if(!PreviewSurface)
{
conversionContext.InsertMdlShaderTypeConversionNodes(shadeInput, nodeOutput);
}
uniformShaderIn.GetInput(inputToken).ConnectToSource(nodeOutput);
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_Constant(UsdStageRefPtr sceneStage, const SdfPath& matPrimPath)
{
if(!PreviewSurface)
{
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMul = UsdShadeShader::Get(sceneStage, opMulPrimPath);
UsdShadeInput uniformOpMulInput = uniformOpMul.GetInput(UsdBridgeTokens->a);
assert(uniformOpMulInput);
uniformOpMulInput.Set(1.0f);
}
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_AttributeReader(UsdStageRefPtr materialStage,
const UsdShadeShader& outputNode, const ShadeGraphTypeConversionNodeContext& conversionContext)
{
// No PreviewSurface implementation to connect a 4 component attrib reader to a 1 component opacity input.
if(!PreviewSurface)
{
SdfPath opMulPrimPath = conversionContext.MatPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMul = UsdShadeShader::Get(conversionContext.SceneStage, opMulPrimPath);
UsdShadeShader timeVarOpMul = UsdShadeShader::Get(materialStage, opMulPrimPath);
// Input 'a' of the multiply node the target for connecting opacity to; see InitializeMdlShader
TfToken opacityInputToken = UsdBridgeTokens->a;
TfToken opacityOutputToken = UsdBridgeTokens->out;
UpdateShaderInput_ShadeNode<false>(uniformOpMul, timeVarOpMul, opacityInputToken, outputNode, opacityOutputToken, conversionContext);
}
}
template<bool PreviewSurface, typename InputValueType, typename ValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars,
const TimeEvaluator<UsdBridgeMaterialData>& timeEval, UsdBridgeMaterialData::DataMemberId dataMemberId,
const UsdBridgeMaterialData::MaterialInput<InputValueType>& param, const TfToken& inputToken, const ValueType& inputValue)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
// Handle the case where a geometry attribute reader is connected
if (param.SrcAttrib != nullptr)
{
//bool isTimeVarying = timeEval.IsTimeVarying(dataMemberId);
// Create attribute reader(s) to connect to the material shader input
UsdShadeShader uniformReaderPrim;
GetOrCreateAttributeReaders<PreviewSurface>(sceneStage,
sceneStage, matPrimPath, dataMemberId, uniformReaderPrim);
assert(uniformReaderPrim);
const TfToken& attribNameToken = writer->AttributeNameToken(param.SrcAttrib);
UpdateAttributeReaderName<PreviewSurface>(uniformReaderPrim, writer->AttributeNameToken(param.SrcAttrib));
UpdateAttributeReaderOutput<PreviewSurface>(uniformReaderPrim, boundGeomPrimvars, attribNameToken);
// Connect the reader to the material shader input
ShadeGraphTypeConversionNodeContext conversionContext(
sceneStage, matPrimPath, GetAttributeReaderPathPf<PreviewSurface>(dataMemberId).GetString().c_str());
const TfToken& outputToken = PreviewSurface ? UsdBridgeTokens->result : UsdBridgeTokens->out;
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShadPrim, timeVarShadPrim, inputToken, uniformReaderPrim, outputToken, conversionContext);
// Diffuse attrib also has to connect to the opacitymul 'a' input. The color primvar (and therefore attrib reader out) is always a float4.
if(dataMemberId == DMI::DIFFUSE)
{
conversionContext.ConnectionIdentifier = PreviewSurface ? "" : constring::mdlDiffuseOpacityPrimPf;
conversionContext.ChannelSelector = 3; // Select the w channel from the float4 input
UpdateShaderInputColorOpacity_AttributeReader<PreviewSurface>(timeVarStage, uniformReaderPrim, conversionContext);
}
}
else if(!param.Sampler)
{
// Handle the case for normal direct values
UsdShadeInput uniformDiffInput = uniformShadPrim.GetInput(inputToken);
if(uniformDiffInput.HasConnectedSource())
uniformDiffInput.DisconnectSource();
// Just treat like regular time-varying inputs
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, inputToken, dataMemberId, inputValue);
// The diffuse input owns the opacitymul's 'a' input.
if(dataMemberId == DMI::DIFFUSE)
UpdateShaderInputColorOpacity_Constant<PreviewSurface>(sceneStage, matPrimPath);
}
}
// Variation for standard material shader input tokens
template<bool PreviewSurface, typename InputValueType, typename ValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TimeEvaluator<UsdBridgeMaterialData>& timeEval,
UsdBridgeMaterialData::DataMemberId dataMemberId, const UsdBridgeMaterialData::MaterialInput<InputValueType>& param, const ValueType& inputValue)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
UpdateShaderInput<PreviewSurface>(writer, sceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval,
dataMemberId, param, inputToken, inputValue);
}
// Convenience for when param.Value is simply the intended value to be set
template<bool PreviewSurface, typename InputValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TimeEvaluator<UsdBridgeMaterialData>& timeEval,
UsdBridgeMaterialData::DataMemberId dataMemberId, const UsdBridgeMaterialData::MaterialInput<InputValueType>& param)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
UpdateShaderInput<PreviewSurface>(writer, sceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval,
dataMemberId, param, inputToken, param.Value);
}
template<bool PreviewSurface>
void UpdateShaderInput_Sampler(const UsdShadeShader& uniformShader, const UsdShadeShader& timeVarShader,
const UsdShadeShader& refSampler, const UsdSamplerRefData& samplerRefData, const ShadeGraphTypeConversionNodeContext& conversionContext)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
DMI samplerDMI = samplerRefData.DataMemberId;
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(samplerDMI);
const TfToken& outputToken = GetSamplerOutputColorToken<PreviewSurface>(samplerRefData.ImageNumComponents);
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShader, timeVarShader, inputToken, refSampler, outputToken, conversionContext);
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_Sampler(const UsdShadeShader& uniformShader, const UsdShadeShader& timeVarShader,
const UsdShadeShader& refSampler, ShadeGraphTypeConversionNodeContext& conversionContext)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
TfToken opacityInputToken;
TfToken opacityOutputToken;
if(PreviewSurface)
{
opacityInputToken = GetMaterialShaderInputToken<PreviewSurface>(DMI::OPACITY);
opacityOutputToken = UsdBridgeTokens->a;
}
else
{
// Input 'a' of the multiply node the target for connecting opacity to; see InitializeMdlShader
opacityInputToken = UsdBridgeTokens->a;
opacityOutputToken = UsdBridgeTokens->out;
}
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShader, timeVarShader, opacityInputToken, refSampler, opacityOutputToken, conversionContext);
}
template<bool PreviewSurface>
void UpdateSamplerInputs(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const UsdBridgeSamplerData& samplerData,
const char* imgFileName, const TfToken& attributeNameToken, const TimeEvaluator<UsdBridgeSamplerData>& timeEval)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
// Collect the various prims
SdfPath tcReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader uniformTcReaderPrim = UsdShadeShader::Get(sceneStage, tcReaderPrimPath);
assert(uniformTcReaderPrim);
UsdShadeShader uniformSamplerPrim = UsdShadeShader::Get(sceneStage, samplerPrimPath);
assert(uniformSamplerPrim);
UsdShadeShader timeVarSamplerPrim = UsdShadeShader::Get(timeVarStage, samplerPrimPath);
assert(timeVarSamplerPrim);
SdfAssetPath texFile(imgFileName);
if(PreviewSurface)
{
// Set all the inputs
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->file, DMI::DATA, texFile);
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapS, DMI::WRAPS, TextureWrapToken(samplerData.WrapS));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapT, DMI::WRAPT, TextureWrapToken(samplerData.WrapT));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapR, DMI::WRAPR, TextureWrapToken(samplerData.WrapR));
// Check whether the output type is still correct
// (Experimental: assume the output type doesn't change over time, this just gives it a chance to match the image type)
int numComponents = samplerData.ImageNumComponents;
const TfToken& outputToken = GetSamplerOutputColorToken<true>(numComponents);
if(!uniformSamplerPrim.GetOutput(outputToken))
{
// As the previous output type isn't cached, just remove everything:
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->r);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->rg);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->rgb);
uniformSamplerPrim.CreateOutput(outputToken, GetSamplerOutputColorType<true>(numComponents));
}
}
else
{
// Set all the inputs
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->tex, DMI::DATA, texFile);
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_u, DMI::WRAPS, TextureWrapInt(samplerData.WrapS));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_v, DMI::WRAPT, TextureWrapInt(samplerData.WrapT));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_w, DMI::WRAPR, TextureWrapInt(samplerData.WrapR));
// Check whether the output type is still correct
int numComponents = samplerData.ImageNumComponents;
const TfToken& assetIdent = GetSamplerAssetSubId(numComponents);
const SdfValueTypeName& outputType = GetSamplerOutputColorType<false>(numComponents);
if(uniformSamplerPrim.GetOutput(UsdBridgeTokens->out).GetTypeName() != outputType)
{
uniformSamplerPrim.SetSourceAssetSubIdentifier(assetIdent, UsdBridgeTokens->mdl);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->out);
uniformSamplerPrim.CreateOutput(UsdBridgeTokens->out, outputType);
}
}
UpdateAttributeReaderName<PreviewSurface>(uniformTcReaderPrim, attributeNameToken);
}
void GetMaterialCoreShader(UsdStageRefPtr sceneStage, UsdStageRefPtr materialStage, const SdfPath& shaderPrimPath,
UsdShadeShader& uniformShader, UsdShadeShader& timeVarShader)
{
uniformShader = UsdShadeShader::Get(sceneStage, shaderPrimPath);
assert(uniformShader);
timeVarShader = UsdShadeShader::Get(materialStage, shaderPrimPath);
assert(timeVarShader);
}
template<bool PreviewSurface>
void GetRefSamplerPrim(UsdStageRefPtr sceneStage, const SdfPath& refSamplerPrimPath, UsdShadeShader& refSampler)
{
SdfPath refSamplerPrimPath_Child = refSamplerPrimPath.AppendPath(SdfPath(PreviewSurface ? constring::psSamplerPrimPf : constring::mdlSamplerPrimPf)); // type inherited from sampler prim (in AddRef)
refSampler = UsdShadeShader::Get(sceneStage, refSamplerPrimPath_Child);
assert(refSampler);
}
}
UsdShadeMaterial UsdBridgeUsdWriter::InitializeUsdMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim) const
{
return InitializeUsdMaterial_Impl(materialStage, matPrimPath, uniformPrim, Settings);
}
void UsdBridgeUsdWriter::InitializeUsdSampler(UsdStageRefPtr samplerStage,const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim) const
{
InitializeSampler_Impl(samplerStage, samplerPrimPath, type, uniformPrim, Settings);
}
#ifdef USE_INDEX_MATERIALS
namespace
{
UsdShadeOutput InitializeIndexShaderUniform(UsdStageRefPtr volumeStage, UsdShadeShader& indexShader, UsdPrim& colorMapPrim)
{
UsdShadeConnectableAPI colorMapConn(colorMapPrim);
UsdShadeOutput colorMapShadOut = colorMapConn.CreateOutput(UsdBridgeTokens->colormap, SdfValueTypeNames->Token);
colorMapPrim.CreateAttribute(UsdBridgeTokens->domainBoundaryMode , SdfValueTypeNames->Token).Set(UsdBridgeTokens->clampToEdge);
colorMapPrim.CreateAttribute(UsdBridgeTokens->colormapSource , SdfValueTypeNames->Token).Set(UsdBridgeTokens->colormapValues);
indexShader.CreateInput(UsdBridgeTokens->colormap, SdfValueTypeNames->Token).ConnectToSource(colorMapShadOut);
return indexShader.CreateOutput(UsdBridgeTokens->volume, SdfValueTypeNames->Token);
}
void InitializeIndexShaderTimeVar(UsdPrim& colorMapPrim, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
// Value range
CREATE_REMOVE_TIMEVARYING_ATTRIB(colorMapPrim, DMI::TFVALUERANGE, UsdBridgeTokens->domain, SdfValueTypeNames->Float2);
// Colors and opacities are grouped into the same attrib
CREATE_REMOVE_TIMEVARYING_ATTRIB(colorMapPrim, (DMI::TFCOLORS | DMI::TFOPACITIES), UsdBridgeTokens->colormapValues, SdfValueTypeNames->Float4Array);
}
}
UsdShadeMaterial UsdBridgeUsdWriter::InitializeIndexVolumeMaterial_Impl(UsdStageRefPtr volumeStage,
const SdfPath& volumePath, bool uniformPrim, const TimeEvaluator<UsdBridgeVolumeData>* timeEval) const
{
SdfPath indexMatPath = volumePath.AppendPath(SdfPath(constring::indexMaterialPf));
SdfPath indexShadPath = indexMatPath.AppendPath(SdfPath(constring::indexShaderPf));
SdfPath colorMapPath = indexMatPath.AppendPath(SdfPath(constring::indexColorMapPf));
UsdShadeMaterial indexMaterial = GetOrDefinePrim<UsdShadeMaterial>(volumeStage, indexMatPath);
assert(indexMaterial);
UsdPrim colorMapPrim = volumeStage->GetPrimAtPath(colorMapPath);
if(!colorMapPrim)
colorMapPrim = volumeStage->DefinePrim(colorMapPath, UsdBridgeTokens->Colormap);
assert(colorMapPrim);
if(uniformPrim)
{
UsdShadeShader indexShader = GetOrDefinePrim<UsdShadeShader>(volumeStage, indexShadPath);
assert(indexShader);
UsdShadeOutput indexShaderOutput = InitializeIndexShaderUniform(volumeStage, indexShader, colorMapPrim);
indexMaterial.CreateVolumeOutput(UsdBridgeTokens->nvindex).ConnectToSource(indexShaderOutput);
}
InitializeIndexShaderTimeVar(colorMapPrim, timeEval);
return indexMaterial;
}
#endif
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdMaterialManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMaterialData& matData)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData);
InitializeUsdMaterial_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath, false,
Settings, &timeEval);
InitializeAttributeReaders_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath,
Settings, matData, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdSamplerManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData)
{
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData);
InitializeSampler_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath, samplerData.Type,
false, Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
void UsdBridgeUsdWriter::ConnectSamplersToMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const SdfPrimPathList& refSamplerPrimPaths,
const UsdBridgePrimCacheList& samplerCacheEntries, const UsdSamplerRefData* samplerRefDatas, size_t numSamplers, double worldTimeStep)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
// Essentially, this is an extension of UpdateShaderInput() for the case of param.Sampler
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath shaderPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader uniformShad, timeVarShad;
GetMaterialCoreShader(this->SceneStage, materialStage, shaderPrimPath,
uniformShad, timeVarShad);
for(int i = 0; i < numSamplers; ++i)
{
const char* samplerPrimName = samplerCacheEntries[i]->Name.GetString().c_str();
UsdShadeShader refSampler;
GetRefSamplerPrim<true>(this->SceneStage, refSamplerPrimPaths[i], refSampler);
ShadeGraphTypeConversionNodeContext conversionContext(
this->SceneStage, matPrimPath, samplerPrimName);
UpdateShaderInput_Sampler<true>(uniformShad, timeVarShad, refSampler, samplerRefDatas[i], conversionContext);
bool affectsOpacity = samplerRefDatas[i].DataMemberId == DMI::DIFFUSE && samplerRefDatas[i].ImageNumComponents == 4;
if(affectsOpacity)
UpdateShaderInputColorOpacity_Sampler<true>(uniformShad, timeVarShad, refSampler, conversionContext);
}
}
if(Settings.EnableMdlShader)
{
// Get shader prims
SdfPath shaderPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformShad, timeVarShad;
GetMaterialCoreShader(this->SceneStage, materialStage, shaderPrimPath,
uniformShad, timeVarShad);
UsdShadeShader uniformOpMul = UsdShadeShader::Get(this->SceneStage, opMulPrimPath);
UsdShadeShader timeVarOpMul = UsdShadeShader::Get(materialStage, opMulPrimPath);
for(int i = 0; i < numSamplers; ++i)
{
const char* samplerPrimName = samplerCacheEntries[i]->Name.GetString().c_str();
UsdShadeShader refSampler;
GetRefSamplerPrim<false>(this->SceneStage, refSamplerPrimPaths[i], refSampler);
ShadeGraphTypeConversionNodeContext conversionContext(
this->SceneStage, matPrimPath, samplerPrimName);
if(samplerRefDatas[i].DataMemberId != DMI::OPACITY)
{
UpdateShaderInput_Sampler<false>(uniformShad, timeVarShad, refSampler, samplerRefDatas[i], conversionContext);
bool affectsOpacity = samplerRefDatas[i].DataMemberId == DMI::DIFFUSE;
if(affectsOpacity)
{
if(samplerRefDatas[i].ImageNumComponents == 4)
{
conversionContext.ConnectionIdentifier = constring::mdlDiffuseOpacityPrimPf;
conversionContext.ChannelSelector = 3; // Select the w channel from the float4 input
// Connect diffuse sampler to the opacity mul node instead of the main shader; see InitializeMdlShader
UpdateShaderInputColorOpacity_Sampler<false>(uniformOpMul, timeVarOpMul, refSampler, conversionContext);
}
else
UpdateShaderInputColorOpacity_Constant<false>(this->SceneStage, matPrimPath); // Since a sampler was bound, the constant is not set during UpdateShaderInput()
}
}
else
{
// Connect opacity sampler to the 'b' input of opacity mul node, similar to UpdateMdlShader (for attribute readers)
UpdateShaderInput_ShadeNode<false>(uniformOpMul, timeVarOpMul, UsdBridgeTokens->b, refSampler, UsdBridgeTokens->out, conversionContext);
}
}
}
}
void UsdBridgeUsdWriter::UpdateUsdMaterial(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
// Update usd shader
if(Settings.EnablePreviewSurfaceShader)
{
this->UpdatePsShader(timeVarStage, matPrimPath, matData, boundGeomPrimvars, timeStep);
}
if(Settings.EnableMdlShader)
{
// Update mdl shader
this->UpdateMdlShader(timeVarStage, matPrimPath, matData, boundGeomPrimvars, timeStep);
}
}
#define UPDATE_USD_SHADER_INPUT_MACRO(...) \
UpdateShaderInput<true>(this, SceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval, __VA_ARGS__)
void UsdBridgeUsdWriter::UpdatePsShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData, timeStep);
typedef UsdBridgeMaterialData::DataMemberId DMI;
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader uniformShadPrim = UsdShadeShader::Get(SceneStage, shadPrimPath);
assert(uniformShadPrim);
UsdShadeShader timeVarShadPrim = UsdShadeShader::Get(timeVarStage, shadPrimPath);
assert(timeVarShadPrim);
GfVec3f difColor(GetValuePtr(matData.Diffuse));
GfVec3f emColor(GetValuePtr(matData.Emissive));
emColor *= matData.EmissiveIntensity.Value; // This multiplication won't translate to vcr/sampler usage
//uniformShadPrim.GetInput(UsdBridgeTokens->useSpecularWorkflow).Set(
// (matData.Metallic.Value > 0.0 || matData.Metallic.SrcAttrib || matData.Metallic.Sampler) ? 0 : 1);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::DIFFUSE, matData.Diffuse, difColor);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::EMISSIVECOLOR, matData.Emissive, emColor);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::ROUGHNESS, matData.Roughness);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::OPACITY, matData.Opacity);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::METALLIC, matData.Metallic);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::IOR, matData.Ior);
// Just a value, not connected to attribreaders or samplers
float opacityCutoffValue = (matData.AlphaMode == UsdBridgeMaterialData::AlphaModes::MASK) ? matData.AlphaCutoff : 0.0f; // don't enable cutoff when not explicitly specified
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->opacityThreshold, DMI::OPACITY, opacityCutoffValue);
}
#define UPDATE_MDL_SHADER_INPUT_MACRO(...) \
UpdateShaderInput<false>(this, SceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval, __VA_ARGS__)
void UsdBridgeUsdWriter::UpdateMdlShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData, timeStep);
typedef UsdBridgeMaterialData::DataMemberId DMI;
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
UsdShadeShader uniformShadPrim = UsdShadeShader::Get(SceneStage, shadPrimPath);
assert(uniformShadPrim);
UsdShadeShader timeVarShadPrim = UsdShadeShader::Get(timeVarStage, shadPrimPath);
assert(timeVarShadPrim);
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMulPrim = UsdShadeShader::Get(SceneStage, opMulPrimPath);
assert(uniformOpMulPrim);
UsdShadeShader timeVarOpMulPrim = UsdShadeShader::Get(timeVarStage, opMulPrimPath);
assert(timeVarOpMulPrim);
GfVec3f difColor(GetValuePtr(matData.Diffuse));
GfVec3f emColor(GetValuePtr(matData.Emissive));
bool enableEmission = (matData.EmissiveIntensity.Value >= 0.0 || matData.EmissiveIntensity.SrcAttrib || matData.EmissiveIntensity.Sampler);
// Only set values on either timevar or uniform prim
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::DIFFUSE, matData.Diffuse, difColor);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::EMISSIVECOLOR, matData.Emissive, emColor);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::EMISSIVEINTENSITY, matData.EmissiveIntensity);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::ROUGHNESS, matData.Roughness);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::METALLIC, matData.Metallic);
//UPDATE_MDL_SHADER_INPUT_MACRO(DMI::IOR, matData.Ior);
UpdateShaderInput<false>(this, SceneStage, timeVarStage, uniformOpMulPrim, timeVarOpMulPrim, matPrimPath, boundGeomPrimvars,
timeEval, DMI::OPACITY, matData.Opacity, UsdBridgeTokens->b, matData.Opacity.Value); // Connect to the mul shader 'b' input, instead of the opacity input directly
// Just a value, not connected to attribreaders or samplers
float opacityCutoffValue = (matData.AlphaMode == UsdBridgeMaterialData::AlphaModes::MASK) ? matData.AlphaCutoff : 0.0f; // don't enable cutoff when not explicitly specified
bool enableOpacity = matData.AlphaMode != UsdBridgeMaterialData::AlphaModes::NONE;
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->opacity_threshold, DMI::OPACITY, opacityCutoffValue);
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->enable_opacity, DMI::OPACITY, enableOpacity);
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->enable_emission, DMI::EMISSIVEINTENSITY, enableEmission);
#ifdef CUSTOM_PBR_MDL
if (!enableOpacity)
uniformShadPrim.SetSourceAsset(this->MdlOpaqueRelFilePath, UsdBridgeTokens->mdl);
else
uniformShadPrim.SetSourceAsset(this->MdlTranslucentRelFilePath, UsdBridgeTokens->mdl);
#endif
}
void UsdBridgeUsdWriter::UpdateUsdSampler(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData, double timeStep)
{
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData, timeStep);
typedef UsdBridgeSamplerData::DataMemberId DMI;
const SdfPath& samplerPrimPath = cacheEntry->PrimPath;
// Generate an image url
const std::string& defaultName = cacheEntry->Name.GetString();
const std::string& generatedFileName = GetResourceFileName(constring::imgFolder, samplerData.ImageName, defaultName, timeStep, constring::imageExtension);
const char* imgFileName = samplerData.ImageUrl;
bool writeFile = false; // No resource key is stored if no file is written
if(!imgFileName)
{
imgFileName = generatedFileName.c_str();
writeFile = true;
}
const TfToken& attribNameToken = AttributeNameToken(samplerData.InAttribute);
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
UpdateSamplerInputs<true>(SceneStage, timeVarStage, usdSamplerPrimPath, samplerData, imgFileName, attribNameToken, timeEval);
}
if(Settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
UpdateSamplerInputs<false>(SceneStage, timeVarStage, usdSamplerPrimPath, samplerData, imgFileName, attribNameToken, timeEval);
}
// Update resources
if(writeFile)
{
// Create a resource reference representing the file write
const char* resourceName = samplerData.ImageName ? samplerData.ImageName : defaultName.c_str();
UsdBridgeResourceKey key(resourceName, timeStep);
bool newEntry = cacheEntry->AddResourceKey(key);
bool isSharedResource = samplerData.ImageName;
if(newEntry && isSharedResource)
AddSharedResourceRef(key);
// Upload as image to texFile (in case this hasn't yet been performed)
assert(samplerData.Data);
if(!isSharedResource || !SetSharedResourceModified(key))
{
TempImageData.resize(0);
const void* convertedSamplerData = nullptr;
int64_t convertedSamplerStride = samplerData.ImageStride[1];
int numComponents = samplerData.ImageNumComponents;
UsdBridgeType flattenedType = ubutils::UsdBridgeTypeFlatten(samplerData.DataType);
if( !(flattenedType == UsdBridgeType::UCHAR || flattenedType == UsdBridgeType::UCHAR_SRGB_R))
{
// Convert to 8-bit image data
ConvertSamplerDataToImage(samplerData, TempImageData);
if(TempImageData.size())
{
convertedSamplerData = TempImageData.data();
convertedSamplerStride = samplerData.ImageDims[0]*numComponents;
}
}
else
{
convertedSamplerData = samplerData.Data;
}
if(numComponents <= 4 && convertedSamplerData)
{
StbWriteOutput writeOutput;
stbi_write_png_to_func(StbWriteToBuffer, &writeOutput,
static_cast<int>(samplerData.ImageDims[0]), static_cast<int>(samplerData.ImageDims[1]),
numComponents, convertedSamplerData, convertedSamplerStride);
// Filename, relative from connection working dir
std::string wdRelFilename(SessionDirectory + imgFileName);
Connect->WriteFile(writeOutput.imageData, writeOutput.imageSize, wdRelFilename.c_str(), true);
}
else
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Image file not written out, format not supported (should be 1-4 component unsigned char/short/int or float/double): " << samplerData.ImageName);
}
}
}
}
namespace
{
template<bool PreviewSurface>
void UpdateAttributeReader_Impl(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath,
UsdBridgeMaterialData::DataMemberId dataMemberId, const TfToken& newNameToken, const UsdGeomPrimvarsAPI& boundGeomPrimvars,
const TimeEvaluator<UsdBridgeMaterialData>& timeEval, const UsdBridgeLogObject& logObj)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
if(PreviewSurface && dataMemberId == DMI::EMISSIVEINTENSITY)
return; // Emissive intensity is not represented as a shader input in the USD preview surface model
// Collect the various prims
SdfPath attributeReaderPath = matPrimPath.AppendPath(GetAttributeReaderPathPf<PreviewSurface>(dataMemberId));
UsdShadeShader uniformAttribReader = UsdShadeShader::Get(sceneStage, attributeReaderPath);
if(!uniformAttribReader)
{
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "In UpdateAttributeReader_Impl(): requesting an attribute reader that hasn't been created during fixup of name token.");
return;
}
UpdateAttributeReaderName<PreviewSurface>(uniformAttribReader, newNameToken);
UpdateAttributeReaderOutput<PreviewSurface>(uniformAttribReader, boundGeomPrimvars, newNameToken);
}
template<bool PreviewSurface>
void UpdateSamplerTcReader(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const TfToken& newNameToken, const TimeEvaluator<UsdBridgeSamplerData>& timeEval)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
// Collect the various prims
SdfPath tcReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader uniformTcReaderPrim = UsdShadeShader::Get(sceneStage, tcReaderPrimPath);
assert(uniformTcReaderPrim);
// Set the new Inattribute
UpdateAttributeReaderName<PreviewSurface>(uniformTcReaderPrim, newNameToken);
}
}
void UsdBridgeUsdWriter::UpdateAttributeReader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, MaterialDMI dataMemberId, const char* newName, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep, MaterialDMI timeVarying)
{
// Time eval with dummy data
UsdBridgeMaterialData materialData;
materialData.TimeVarying = timeVarying;
TimeEvaluator<UsdBridgeMaterialData> timeEval(materialData, timeStep);
const TfToken& newNameToken = AttributeNameToken(newName);
if(Settings.EnablePreviewSurfaceShader)
{
UpdateAttributeReader_Impl<true>(SceneStage, timeVarStage, matPrimPath, dataMemberId, newNameToken, boundGeomPrimvars, timeEval, this->LogObject);
}
if(Settings.EnableMdlShader)
{
UpdateAttributeReader_Impl<false>(SceneStage, timeVarStage, matPrimPath, dataMemberId, newNameToken, boundGeomPrimvars, timeEval, this->LogObject);
}
}
void UsdBridgeUsdWriter::UpdateInAttribute(UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const char* newName, double timeStep, SamplerDMI timeVarying)
{
// Time eval with dummy data
UsdBridgeSamplerData samplerData;
samplerData.TimeVarying = timeVarying;
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData, timeStep);
const TfToken& newNameToken = AttributeNameToken(newName);
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
UpdateSamplerTcReader<true>(SceneStage, timeVarStage, usdSamplerPrimPath, newNameToken, timeEval);
}
if(Settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
UpdateSamplerTcReader<false>(SceneStage, timeVarStage, usdSamplerPrimPath, newNameToken, timeEval);
}
}
#ifdef USE_INDEX_MATERIALS
void UsdBridgeUsdWriter::UpdateIndexVolumeMaterial(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& volumePath, const UsdBridgeVolumeData& volumeData, double timeStep)
{
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData, timeStep);
typedef UsdBridgeVolumeData::DataMemberId DMI;
SdfPath indexMatPath = volumePath.AppendPath(SdfPath(constring::indexMaterialPf));
SdfPath colorMapPath = indexMatPath.AppendPath(SdfPath(constring::indexColorMapPf));
// Renormalize the value range based on the volume data type (see CopyToGrid in the volumewriter)
GfVec2f valueRange(GfVec2d(volumeData.TfData.TfValueRange));
// Set the transfer function value array from opacities and colors
assert(volumeData.TfData.TfOpacitiesType == UsdBridgeType::FLOAT);
const float* tfOpacities = static_cast<const float*>(volumeData.TfData.TfOpacities);
// Set domain and colormap values
UsdPrim uniformColorMap = sceneStage->GetPrimAtPath(colorMapPath);
assert(uniformColorMap);
UsdPrim timeVarColorMap = timeVarStage->GetPrimAtPath(colorMapPath);
assert(timeVarColorMap);
UsdAttribute uniformDomainAttr = uniformColorMap.GetAttribute(UsdBridgeTokens->domain);
UsdAttribute timeVarDomainAttr = timeVarColorMap.GetAttribute(UsdBridgeTokens->domain);
UsdAttribute uniformTfValueAttr = uniformColorMap.GetAttribute(UsdBridgeTokens->colormapValues);
UsdAttribute timeVarTfValueAttr = timeVarColorMap.GetAttribute(UsdBridgeTokens->colormapValues);
// Timevarying colormaps/domains are currently not supported by index, so keep this switched off
bool rangeTimeVarying = false;//timeEval.IsTimeVarying(DMI::TFVALUERANGE);
bool valuesTimeVarying = false;//timeEval.IsTimeVarying(DMI::TFCOLORS) || timeEval.IsTimeVarying(DMI::TFOPACITIES);
// Clear timevarying attributes if necessary
ClearUsdAttributes(uniformDomainAttr, timeVarDomainAttr, rangeTimeVarying);
ClearUsdAttributes(uniformTfValueAttr, timeVarTfValueAttr, valuesTimeVarying);
// Set the attributes
UsdAttribute& outAttrib = valuesTimeVarying ? timeVarTfValueAttr : uniformTfValueAttr;
UsdTimeCode outTimeCode = valuesTimeVarying ? timeEval.TimeCode : timeEval.Default();
VtVec4fArray* outArray = AssignColorArrayToPrimvar(LogObject, volumeData.TfData.TfColors, volumeData.TfData.TfNumColors, volumeData.TfData.TfColorsType,
outTimeCode,
outAttrib,
false); // Get the pointer, set the data manually here
for(size_t i = 0; i < outArray->size() && i < volumeData.TfData.TfNumOpacities; ++i)
(*outArray)[i][3] = tfOpacities[i]; // Set the alpha channel
if(outArray)
outAttrib.Set(*outArray, outTimeCode);
SET_TIMEVARYING_ATTRIB(rangeTimeVarying, timeVarDomainAttr, uniformDomainAttr, valueRange);
}
#endif
void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter)
{
RemoveResourceFiles(cache, usdWriter, constring::imgFolder, constring::imageExtension);
}
| 71,332 | C++ | 46.587058 | 237 | 0.769514 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridge.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridge_h
#define UsdBridge_h
#include "UsdBridgeData.h"
struct UsdBridgeInternals;
typedef void* SceneStagePtr; // Placeholder for UsdStage*
class UsdBridge
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
using SamplerDMI = UsdBridgeSamplerData::DataMemberId;
using MaterialInputAttribName = std::pair<MaterialDMI, const char*>;
UsdBridge(const UsdBridgeSettings& settings);
~UsdBridge();
void SetExternalSceneStage(SceneStagePtr sceneStage);
void SetEnableSaving(bool enableSaving);
bool OpenSession(UsdBridgeLogCallback logCallback, void* logUserData);
bool GetSessionValid() const { return SessionValid; }
void CloseSession();
bool CreateWorld(const char* name, UsdWorldHandle& handle);
bool CreateInstance(const char* name, UsdInstanceHandle& handle);
bool CreateGroup(const char* name, UsdGroupHandle& handle);
bool CreateSurface(const char* name, UsdSurfaceHandle& handle);
bool CreateVolume(const char* name, UsdVolumeHandle& handle);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeMeshData& meshData);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeInstancerData& instancerData);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeCurveData& curveData);
bool CreateSpatialField(const char* name, UsdSpatialFieldHandle& handle);
bool CreateMaterial(const char* name, UsdMaterialHandle& handle);
bool CreateSampler(const char* name, UsdSamplerHandle& handle, UsdBridgeSamplerData::SamplerType type);
bool CreateCamera(const char* name, UsdCameraHandle& handle);
void DeleteWorld(UsdWorldHandle handle);
void DeleteInstance(UsdInstanceHandle handle);
void DeleteGroup(UsdGroupHandle handle);
void DeleteSurface(UsdSurfaceHandle handle);
void DeleteVolume(UsdVolumeHandle handle);
void DeleteGeometry(UsdGeometryHandle handle);
void DeleteSpatialField(UsdSpatialFieldHandle handle);
void DeleteMaterial(UsdMaterialHandle handle);
void DeleteSampler(UsdSamplerHandle handle);
void DeleteCamera(UsdCameraHandle handle);
void SetInstanceRefs(UsdWorldHandle world, const UsdInstanceHandle* instances, uint64_t numInstances, bool timeVarying, double timeStep);
void SetGroupRef(UsdInstanceHandle instance, UsdGroupHandle group, bool timeVarying, double timeStep);
void SetSurfaceRefs(UsdWorldHandle world, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep);
void SetSurfaceRefs(UsdGroupHandle group, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep);
void SetVolumeRefs(UsdWorldHandle world, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep);
void SetVolumeRefs(UsdGroupHandle group, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep);
void SetGeometryRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, double timeStep, double geomTimeStep);
void SetGeometryMaterialRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, UsdMaterialHandle material, double timeStep, double geomTimeStep, double matTimeStep);
void SetSpatialFieldRef(UsdVolumeHandle volume, UsdSpatialFieldHandle field, double timeStep, double fieldTimeStep);
void SetSamplerRefs(UsdMaterialHandle material, const UsdSamplerHandle* samplers, size_t numSamplers, double timeStep, const UsdSamplerRefData* samplerRefData);
void SetPrototypeRefs(UsdGeometryHandle geometry, const UsdGeometryHandle* protoGeometries, size_t numProtoGeometries, double timeStep, double* protoTimeSteps);
void DeleteInstanceRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteGroupRef(UsdInstanceHandle instance, bool timeVarying, double timeStep);
void DeleteSurfaceRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteSurfaceRefs(UsdGroupHandle group, bool timeVarying, double timeStep);
void DeleteVolumeRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteVolumeRefs(UsdGroupHandle group, bool timeVarying, double timeStep);
void DeleteGeometryRef(UsdSurfaceHandle surface, double timeStep);
void DeleteSpatialFieldRef(UsdVolumeHandle volume, double timeStep);
void DeleteMaterialRef(UsdSurfaceHandle surface, double timeStep);
void DeleteSamplerRefs(UsdMaterialHandle material, double timeStep);
void DeletePrototypeRefs(UsdGeometryHandle geometry, double timeStep);
void UpdateBeginEndTime(double timeStep);
void SetInstanceTransform(UsdInstanceHandle instance, const float* transform, bool timeVarying, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeMeshData& meshData, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeInstancerData& instancerData, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeCurveData& curveData, double timeStep);
void SetSpatialFieldData(UsdSpatialFieldHandle field, const UsdBridgeVolumeData& volumeData, double timeStep);
void SetMaterialData(UsdMaterialHandle material, const UsdBridgeMaterialData& matData, double timeStep);
void SetSamplerData(UsdSamplerHandle sampler, const UsdBridgeSamplerData& samplerData, double timeStep);
void SetCameraData(UsdCameraHandle camera, const UsdBridgeCameraData& cameraData, double timeStep);
void SetPrototypeData(UsdGeometryHandle geometry, const UsdBridgeInstancerRefData& instancerRefData); // UsdBridgeInstancerRefData::Shapes used to index into refs from last SetPrototypeRefs (if SHAPE_MESH)
void ChangeMaterialInputAttributes(UsdMaterialHandle material, const MaterialInputAttribName* inputAttribs, size_t numInputAttribs, double timeStep, MaterialDMI timeVarying);
void ChangeInAttribute(UsdSamplerHandle sampler, const char* newName, double timeStep, SamplerDMI timeVarying);
void SaveScene();
void ResetResourceUpdateState(); // Eg. clears all dirty flags on shared resources
void GarbageCollect(); // Deletes all handles without parents (from Set<X>Refs)
const char* GetPrimPath(UsdBridgeHandle* handle);
//
// Static parameter interface
//
static void SetConnectionLogVerbosity(int logVerbosity); // 0 <= logVerbosity <= 4, 0 is quietest
protected:
template<typename GeomDataType>
bool CreateGeometryTemplate(const char* name, UsdGeometryHandle& handle, const GeomDataType& geomData);
template<typename GeomDataType>
void SetGeometryDataTemplate(UsdGeometryHandle geometry, const GeomDataType& geomData, double timeStep);
template<typename ParentHandleType, typename ChildHandleType>
void SetNoClipRefs(ParentHandleType parentHandle, const ChildHandleType* childHandles, uint64_t numChildren,
const char* refPathExt, bool timeVarying, double timeStep, bool instanceable = false);
template<typename ParentHandleType>
void DeleteAllRefs(ParentHandleType parentHandle, const char* refPathExt, bool timeVarying, double timeStep);
void CreateRootPrimAndAttach(UsdBridgePrimCache* cacheEntry, const char* primPathCp, const char* layerId = nullptr);
void RemoveRootPrimAndDetach(UsdBridgePrimCache* cacheEntry, const char* primPathCp);
UsdBridgeInternals* Internals;
bool EnableSaving;
bool SessionValid;
};
#endif
| 7,571 | C | 57.246153 | 209 | 0.799498 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeDiagnosticMgrDelegate.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeDiagnosticMgrDelegate_h
#define UsdBridgeDiagnosticMgrDelegate_h
#include "UsdBridgeData.h"
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
class UsdBridgeDiagnosticMgrDelegate : public TfDiagnosticMgr::Delegate
{
public:
UsdBridgeDiagnosticMgrDelegate(void* logUserData,
UsdBridgeLogCallback logCallback);
void IssueError(TfError const& err) override;
void IssueFatalError(TfCallContext const& context,
std::string const& msg) override;
void IssueStatus(TfStatus const& status) override;
void IssueWarning(TfWarning const& warning) override;
static void SetOutputEnabled(bool enable){ OutputEnabled = enable; }
protected:
void LogTfMessage(UsdBridgeLogLevel level, TfDiagnosticBase const& diagBase);
void LogMessage(UsdBridgeLogLevel level, const std::string& message);
void* LogUserData;
UsdBridgeLogCallback LogCallback;
static bool OutputEnabled;
};
#endif | 1,026 | C | 24.674999 | 81 | 0.769981 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/usd.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#pragma warning(push)
#pragma warning(disable:4244) // = Conversion from double to float / int to float
#pragma warning(disable:4305) // argument truncation from double to float
#pragma warning(disable:4800) // int to bool
#pragma warning(disable:4996) // call to std::copy with parameters that may be unsafe
#define NOMINMAX // Make sure nobody #defines min or max
// Python must be included first because it monkeys with macros that cause
// TBB to fail to compile in debug mode if TBB is included before Python
#include <boost/python/object.hpp>
#include <pxr/pxr.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/tf/diagnosticMgr.h>
#include <pxr/base/trace/reporter.h>
#include <pxr/base/trace/trace.h>
#include <pxr/base/vt/array.h>
#include <pxr/base/gf/range3f.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usd/notice.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usd/clipsAPI.h>
#include <pxr/usd/usd/inherits.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/points.h>
#include <pxr/usd/usdGeom/sphere.h>
#include <pxr/usd/usdGeom/cylinder.h>
#include <pxr/usd/usdGeom/cone.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/pointInstancer.h>
#include <pxr/usd/usdGeom/primvarsAPI.h>
#include <pxr/usd/usdGeom/basisCurves.h>
#include <pxr/usd/usdGeom/camera.h>
#include <pxr/usd/usdGeom/scope.h>
#include <pxr/usd/usdVol/volume.h>
#include <pxr/usd/usdVol/openVDBAsset.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/materialBindingAPI.h>
#include <pxr/usd/kind/registry.h>
#pragma warning(pop)
| 1,825 | C | 36.265305 | 85 | 0.753425 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeCaches.h"
#include "UsdBridgeMdlStrings.h"
#include "UsdBridgeUsdWriter_Common.h"
#include "UsdBridgeDiagnosticMgrDelegate.h"
TF_DEFINE_PUBLIC_TOKENS(
UsdBridgeTokens,
ATTRIB_TOKEN_SEQ
USDPREVSURF_TOKEN_SEQ
USDPREVSURF_INPUT_TOKEN_SEQ
MDL_TOKEN_SEQ
MDL_INPUT_TOKEN_SEQ
VOLUME_TOKEN_SEQ
INDEX_TOKEN_SEQ
MISC_TOKEN_SEQ
);
namespace constring
{
const char* const sessionPf = "Session_";
const char* const rootClassName = "/RootClass";
const char* const rootPrimName = "/Root";
const char* const manifestFolder = "manifests/";
const char* const clipFolder = "clips/";
const char* const primStageFolder = "primstages/";
const char* const imgFolder = "images/";
const char* const volFolder = "volumes/";
const char* const texCoordReaderPrimPf = "texcoordreader";
const char* const psShaderPrimPf = "psshader";
const char* const mdlShaderPrimPf = "mdlshader";
const char* const psSamplerPrimPf = "pssampler";
const char* const mdlSamplerPrimPf = "mdlsampler";
const char* const mdlOpacityMulPrimPf = "opacitymul_mdl";
const char* const mdlDiffuseOpacityPrimPf = "diffuseopacity_mdl";
const char* const mdlGraphXYZPrimPf = "_xyz_f";
const char* const mdlGraphColorPrimPf = "_ftocolor";
const char* const mdlGraphXPrimPf = "_x";
const char* const mdlGraphYPrimPf = "_y";
const char* const mdlGraphZPrimPf = "_z";
const char* const mdlGraphWPrimPf = "_w";
const char* const openVDBPrimPf = "ovdbfield";
const char* const protoShapePf = "proto_";
const char* const imageExtension = ".png";
const char* const vdbExtension = ".vdb";
const char* const fullSceneNameBin = "FullScene.usd";
const char* const fullSceneNameAscii = "FullScene.usda";
const char* const mdlShaderAssetName = "OmniPBR.mdl";
const char* const mdlSupportAssetName = "nvidia/support_definitions.mdl";
const char* const mdlAuxAssetName = "nvidia/aux_definitions.mdl";
#ifdef CUSTOM_PBR_MDL
const char* const mdlFolder = "mdls/";
const char* const opaqueMaterialFile = "PBR_Opaque.mdl";
const char* const transparentMaterialFile = "PBR_Transparent.mdl";
#endif
#ifdef USE_INDEX_MATERIALS
const char* const indexMaterialPf = "indexmaterial";
const char* const indexShaderPf = "indexshader";
const char* const indexColorMapPf = "indexcolormap";
#endif
}
#define ATTRIB_TOKENS_ADD(r, data, elem) AttributeTokens.push_back(UsdBridgeTokens->elem);
UsdBridgeUsdWriter::UsdBridgeUsdWriter(const UsdBridgeSettings& settings)
: Settings(settings)
, VolumeWriter(Create_VolumeWriter(), std::mem_fn(&UsdBridgeVolumeWriterI::Release))
{
// Initialize AttributeTokens with common known attribute names
BOOST_PP_SEQ_FOR_EACH(ATTRIB_TOKENS_ADD, ~, ATTRIB_TOKEN_SEQ)
if(Settings.HostName)
ConnectionSettings.HostName = Settings.HostName;
if(Settings.OutputPath)
ConnectionSettings.WorkingDirectory = Settings.OutputPath;
FormatDirName(ConnectionSettings.WorkingDirectory);
}
UsdBridgeUsdWriter::~UsdBridgeUsdWriter()
{
}
void UsdBridgeUsdWriter::SetExternalSceneStage(UsdStageRefPtr sceneStage)
{
this->ExternalSceneStage = sceneStage;
}
void UsdBridgeUsdWriter::SetEnableSaving(bool enableSaving)
{
this->EnableSaving = enableSaving;
}
int UsdBridgeUsdWriter::FindSessionNumber()
{
int sessionNr = Connect->MaxSessionNr();
sessionNr = std::max(0, sessionNr + Settings.CreateNewSession);
return sessionNr;
}
bool UsdBridgeUsdWriter::CreateDirectories()
{
bool valid = true;
valid = Connect->CreateFolder("", true, true);
//Connect->RemoveFolder(SessionDirectory.c_str(), true, true);
bool folderMayExist = !Settings.CreateNewSession;
valid = valid && Connect->CreateFolder(SessionDirectory.c_str(), true, folderMayExist);
#ifdef VALUE_CLIP_RETIMING
valid = valid && Connect->CreateFolder((SessionDirectory + constring::manifestFolder).c_str(), true, folderMayExist);
valid = valid && Connect->CreateFolder((SessionDirectory + constring::primStageFolder).c_str(), true, folderMayExist);
#endif
#ifdef TIME_CLIP_STAGES
valid = valid && Connect->CreateFolder((SessionDirectory + constring::clipFolder).c_str(), true, folderMayExist);
#endif
#ifdef CUSTOM_PBR_MDL
if(Settings.EnableMdlShader)
{
valid = valid && Connect->CreateFolder((SessionDirectory + constring::mdlFolder).c_str(), true, folderMayExist);
}
#endif
valid = valid && Connect->CreateFolder((SessionDirectory + constring::imgFolder).c_str(), true, folderMayExist);
valid = valid && Connect->CreateFolder((SessionDirectory + constring::volFolder).c_str(), true, folderMayExist);
if (!valid)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::ERR, "Something went wrong in the filesystem creating the required output folders (permissions?).");
}
return valid;
}
#ifdef CUSTOM_PBR_MDL
namespace
{
void WriteMdlFromStrings(const char* string0, const char* string1, const char* fileName, const UsdBridgeConnection* Connect)
{
size_t strLen0 = std::strlen(string0);
size_t strLen1 = std::strlen(string1);
size_t totalStrLen = strLen0 + strLen1;
char* Mdl_Contents = new char[totalStrLen];
std::memcpy(Mdl_Contents, string0, strLen0);
std::memcpy(Mdl_Contents + strLen0, string1, strLen1);
Connect->WriteFile(Mdl_Contents, totalStrLen, fileName, true, false);
delete[] Mdl_Contents;
}
}
bool UsdBridgeUsdWriter::CreateMdlFiles()
{
//Write PBR opacity file contents
{
std::string relMdlPath = constring::mdlFolder + std::string(constring::opaqueMaterialFile);
this->MdlOpaqueRelFilePath = SdfAssetPath(relMdlPath);
std::string mdlFileName = SessionDirectory + relMdlPath;
WriteMdlFromStrings(Mdl_PBRBase_string, Mdl_PBRBase_string_opaque, mdlFileName.c_str(), Connect.get());
}
{
std::string relMdlPath = constring::mdlFolder + std::string(constring::transparentMaterialFile);
this->MdlTranslucentRelFilePath = SdfAssetPath(relMdlPath);
std::string mdlFileName = SessionDirectory + relMdlPath;
WriteMdlFromStrings(Mdl_PBRBase_string, Mdl_PBRBase_string_translucent, mdlFileName.c_str(), Connect.get());
}
return true;
}
#endif
bool UsdBridgeUsdWriter::InitializeSession()
{
if (ConnectionSettings.HostName.empty())
{
if(ConnectionSettings.WorkingDirectory.compare("void") == 0)
Connect = std::make_unique<UsdBridgeVoidConnection>();
else
Connect = std::make_unique<UsdBridgeLocalConnection>();
}
else
Connect = std::make_unique<UsdBridgeRemoteConnection>();
Connect->Initialize(ConnectionSettings, this->LogObject);
SessionNumber = FindSessionNumber();
SessionDirectory = constring::sessionPf + std::to_string(SessionNumber) + "/";
bool valid = true;
valid = CreateDirectories();
valid = valid && VolumeWriter->Initialize(this->LogObject);
#ifdef CUSTOM_PBR_MDL
if(Settings.EnableMdlShader)
{
valid = valid && CreateMdlFiles();
}
#endif
return valid;
}
void UsdBridgeUsdWriter::ResetSession()
{
this->SessionNumber = -1;
this->SceneStage = nullptr;
}
bool UsdBridgeUsdWriter::OpenSceneStage()
{
bool binary = this->Settings.BinaryOutput;
this->SceneFileName = this->SessionDirectory;
this->SceneFileName += (binary ? constring::fullSceneNameBin : constring::fullSceneNameAscii);
#ifdef REPLACE_SCENE_BY_EXTERNAL_STAGE
if (this->ExternalSceneStage)
{
this->SceneStage = this->ExternalSceneStage;
}
#endif
const char* absSceneFile = Connect->GetUrl(this->SceneFileName.c_str());
if (!this->SceneStage && !Settings.CreateNewSession)
this->SceneStage = UsdStage::Open(absSceneFile);
if (!this->SceneStage)
this->SceneStage = UsdStage::CreateNew(absSceneFile);
if (!this->SceneStage)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::ERR, "Scene UsdStage cannot be created or opened. Maybe a filesystem issue?");
return false;
}
#ifndef REPLACE_SCENE_BY_EXTERNAL_STAGE
else if (this->ExternalSceneStage)
{
// Set the scene stage as a sublayer of the external stage
ExternalSceneStage->GetRootLayer()->InsertSubLayerPath(
this->SceneStage->GetRootLayer()->GetIdentifier());
}
#endif
this->RootClassName = constring::rootClassName;
UsdPrim rootClassPrim = this->SceneStage->CreateClassPrim(SdfPath(this->RootClassName));
assert(rootClassPrim);
this->RootName = constring::rootPrimName;
UsdPrim rootPrim = this->SceneStage->DefinePrim(SdfPath(this->RootName));
assert(rootPrim);
#ifndef REPLACE_SCENE_BY_EXTERNAL_STAGE
if (!this->ExternalSceneStage)
#endif
{
this->SceneStage->SetDefaultPrim(rootPrim);
UsdModelAPI(rootPrim).SetKind(KindTokens->assembly);
}
if(!this->SceneStage->HasAuthoredTimeCodeRange())
{
this->SceneStage->SetStartTimeCode(StartTime);
this->SceneStage->SetEndTimeCode(EndTime);
}
else
{
StartTime = this->SceneStage->GetStartTimeCode();
EndTime = this->SceneStage->GetEndTimeCode();
}
if(this->EnableSaving)
this->SceneStage->Save();
return true;
}
UsdStageRefPtr UsdBridgeUsdWriter::GetSceneStage() const
{
return this->SceneStage;
}
UsdStageRefPtr UsdBridgeUsdWriter::GetTimeVarStage(UsdBridgePrimCache* cache
#ifdef TIME_CLIP_STAGES
, bool useClipStage, const char* clipPf, double timeStep
, std::function<void (UsdStageRefPtr)> initFunc
#endif
) const
{
#ifdef VALUE_CLIP_RETIMING
#ifdef TIME_CLIP_STAGES
if (useClipStage)
{
bool exists;
UsdStageRefPtr clipStage = this->FindOrCreateClipStage(cache, clipPf, timeStep, exists).second;
if(!exists)
initFunc(clipStage);
return clipStage;
}
else
return cache->GetPrimStagePair().second;
#else
return cache->GetPrimStagePair().second;
#endif
#else
return this->SceneStage;
#endif
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::CreateManifestStage(const char* name, const char* primPostfix, UsdBridgePrimCache* cacheEntry)
{
bool binary = this->Settings.BinaryOutput;
cacheEntry->ManifestStage.first = constring::manifestFolder + std::string(name) + primPostfix + (binary ? ".usd" : ".usda");
std::string absoluteFileName = Connect->GetUrl((this->SessionDirectory + cacheEntry->ManifestStage.first).c_str());
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(false);
cacheEntry->ManifestStage.second = UsdStage::CreateNew(absoluteFileName);
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(true);
if (!cacheEntry->ManifestStage.second)
cacheEntry->ManifestStage.second = UsdStage::Open(absoluteFileName);
assert(cacheEntry->ManifestStage.second);
cacheEntry->ManifestStage.second->DefinePrim(SdfPath(this->RootClassName));
}
void UsdBridgeUsdWriter::RemoveManifestAndClipStages(const UsdBridgePrimCache* cacheEntry)
{
// May be superfluous
if(cacheEntry->ManifestStage.second)
{
cacheEntry->ManifestStage.second->RemovePrim(SdfPath(RootClassName));
// Remove ManifestStage file itself
assert(!cacheEntry->ManifestStage.first.empty());
Connect->RemoveFile((SessionDirectory + cacheEntry->ManifestStage.first).c_str(), true);
}
// remove all clipstage files
for (auto& x : cacheEntry->ClipStages)
{
Connect->RemoveFile((SessionDirectory + x.second.first).c_str(), true);
}
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreatePrimStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix) const
{
bool exists;
return FindOrCreatePrimClipStage(cacheEntry, namePostfix, false, UsdBridgePrimCache::PrimStageTimeCode, exists);
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreateClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, double timeStep, bool& exists) const
{
return FindOrCreatePrimClipStage(cacheEntry, namePostfix, true, timeStep, exists);
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreatePrimClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, bool isClip, double timeStep, bool& exists) const
{
exists = true;
bool binary = this->Settings.BinaryOutput;
auto it = cacheEntry->ClipStages.find(timeStep);
if (it == cacheEntry->ClipStages.end())
{
// Create a new Clipstage
const char* folder = constring::primStageFolder;
std::string fullNamePostfix(namePostfix);
if(isClip)
{
folder = constring::clipFolder;
fullNamePostfix += std::to_string(timeStep);
}
std::string relativeFileName = folder + cacheEntry->Name.GetString() + fullNamePostfix + (binary ? ".usd" : ".usda");
std::string absoluteFileName = Connect->GetUrl((this->SessionDirectory + relativeFileName).c_str());
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(false);
UsdStageRefPtr primClipStage = UsdStage::CreateNew(absoluteFileName);
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(true);
exists = !primClipStage;
SdfPath rootPrimPath(this->RootClassName);
if (exists)
{
primClipStage = UsdStage::Open(absoluteFileName); //Could happen if written folder is reused
assert(primClipStage->GetPrimAtPath(rootPrimPath));
}
else
primClipStage->DefinePrim(rootPrimPath);
it = cacheEntry->ClipStages.emplace(timeStep, UsdStagePair(std::move(relativeFileName), primClipStage)).first;
}
return it->second;
}
#endif
void UsdBridgeUsdWriter::AddRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp, const char* layerId)
{
SdfPath primPath(this->RootName + "/" + primPathCp);
primPath = primPath.AppendPath(primCache->Name);
UsdPrim sceneGraphPrim = SceneStage->DefinePrim(primPath);
assert(sceneGraphPrim);
UsdReferences primRefs = sceneGraphPrim.GetReferences();
primRefs.ClearReferences();
#ifdef VALUE_CLIP_RETIMING
if(layerId)
{
primRefs.AddReference(layerId, primCache->PrimPath);
}
#endif
// Always add a ref to the internal prim, which is represented by the cache
primRefs.AddInternalReference(primCache->PrimPath);
}
void UsdBridgeUsdWriter::RemoveRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp)
{
SdfPath primPath(this->RootName + "/" + primPathCp);
primPath = primPath.AppendPath(primCache->Name);
this->SceneStage->RemovePrim(primPath);
}
const std::string& UsdBridgeUsdWriter::CreatePrimName(const char * name, const char * category)
{
(this->TempNameStr = this->RootClassName).append("/").append(category).append("/").append(name);
return this->TempNameStr;
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const std::string& basePath, double timeStep, const char* fileExtension)
{
this->TempNameStr = basePath;
#ifdef TIME_BASED_CACHING
this->TempNameStr += "_";
this->TempNameStr += std::to_string(timeStep);
#endif
this->TempNameStr += fileExtension;
return this->TempNameStr;
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const char* folderName, const std::string& objectName, double timeStep, const char* fileExtension)
{
return GetResourceFileName(folderName + objectName, timeStep, fileExtension);
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const char* folderName, const char* optionalObjectName, const std::string& defaultObjectName, double timeStep, const char* fileExtension)
{
return GetResourceFileName(folderName, (optionalObjectName ? std::string(optionalObjectName) : defaultObjectName), timeStep, fileExtension);
}
bool UsdBridgeUsdWriter::CreatePrim(const SdfPath& path)
{
UsdPrim classPrim = SceneStage->GetPrimAtPath(path);
if(!classPrim)
{
classPrim = SceneStage->DefinePrim(path);
assert(classPrim);
return true;
}
return false;
}
void UsdBridgeUsdWriter::DeletePrim(const UsdBridgePrimCache* cacheEntry)
{
if(SceneStage->GetPrimAtPath(cacheEntry->PrimPath))
SceneStage->RemovePrim(cacheEntry->PrimPath);
#ifdef VALUE_CLIP_RETIMING
RemoveManifestAndClipStages(cacheEntry);
#endif
}
#ifdef TIME_BASED_CACHING
void UsdBridgeUsdWriter::InitializePrimVisibility(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr(); // in case MakeVisible fails
if(!visAttrib)
visAttrib = imageable.CreateVisibilityAttr(VtValue(UsdGeomTokens->invisible)); // default is invisible
double startTime = stage->GetStartTimeCode();
double endTime = stage->GetEndTimeCode();
if (startTime < timeCode)
visAttrib.Set(VtValue(UsdGeomTokens->invisible), startTime);//imageable.MakeInvisible(startTime);
if (endTime > timeCode)
visAttrib.Set(VtValue(UsdGeomTokens->invisible), endTime);//imageable.MakeInvisible(endTime);
visAttrib.Set(VtValue(UsdGeomTokens->inherited), timeCode);//imageable.MakeVisible(timeCode);
parentCache->SetChildVisibleAtTime(childCache, timeCode.GetValue());
}
}
void UsdBridgeUsdWriter::SetPrimVisible(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr();
assert(visAttrib);
visAttrib.Set(VtValue(UsdGeomTokens->inherited), timeCode);//imageable.MakeVisible(timeCode);
parentCache->SetChildVisibleAtTime(childCache, timeCode.GetValue());
}
}
void UsdBridgeUsdWriter::PrimRemoveIfInvisibleAnytime(UsdStageRefPtr stage, const UsdPrim& prim, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* primCache)
{
const SdfPath& primPath = prim.GetPath();
bool removePrim = true; // TimeVarying is not automatically removed
if (timeVarying)
{
if(primCache)
{
// Remove prim only if there are no more visible children AND the timecode has actually been removed
// (so if the timecode wasn't found in the cache, do not remove the prim)
removePrim = parentCache->SetChildInvisibleAtTime(primCache, timeCode.GetValue());
// If prim is still visible at other times, make sure to explicitly set this timeCode as invisible
if(!removePrim)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr();
if (visAttrib)
visAttrib.Set(UsdGeomTokens->invisible, timeCode);
}
}
}
else
removePrim = false; // If no cache is available, just don't remove, for possibility of previous timesteps (opposite from when !timeVarying)
}
if (removePrim)
{
// Decrease the ref on the representing cache entry
if(primCache)
atRemoveRef(parentCache, primCache);
// Remove the prim
stage->RemovePrim(primPath);
}
}
void UsdBridgeUsdWriter::ChildrenRemoveIfInvisibleAnytime(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const SdfPath& parentPath, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef, const SdfPath& exceptPath)
{
UsdPrim parentPrim = stage->GetPrimAtPath(parentPath);
if (parentPrim)
{
UsdPrimSiblingRange children = parentPrim.GetAllChildren();
for (UsdPrim child : children)
{
UsdBridgePrimCache* childCache = parentCache->GetChildCache(child.GetName());
if (child.GetPath() != exceptPath)
PrimRemoveIfInvisibleAnytime(stage, child, timeVarying, timeCode, atRemoveRef,
parentCache, childCache);
}
}
}
#endif
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::InitializeClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix)
{
UsdClipsAPI clipsApi(clipPrim);
clipsApi.SetClipPrimPath(childCache->PrimPath.GetString());
const std::string& manifestPath = childCache->ManifestStage.first;
const std::string* refStagePath;
#ifdef TIME_CLIP_STAGES
if (clipStages)
{
//set interpolatemissingclipvalues?
bool exists;
const UsdStagePair& childStagePair = FindOrCreateClipStage(childCache, clipPostfix, childTimeStep, exists);
//assert(exists); // In case prim creation succeeds but an update is not attempted, no clip stage is generated, so exists will be false
if(!exists)
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Child clip stage not found while setting clip metadata, using generated stage instead. Probably the child data has not been properly updated.");
refStagePath = &childStagePair.first;
}
else
#endif
{
refStagePath = &childCache->GetPrimStagePair().first;
}
clipsApi.SetClipManifestAssetPath(SdfAssetPath(manifestPath));
VtArray<SdfAssetPath> assetPaths;
assetPaths.push_back(SdfAssetPath(*refStagePath));
clipsApi.SetClipAssetPaths(assetPaths);
VtVec2dArray clipActives;
clipActives.push_back(GfVec2d(parentTimeStep, 0));
clipsApi.SetClipActive(clipActives);
VtVec2dArray clipTimes;
clipTimes.push_back(GfVec2d(parentTimeStep, childTimeStep));
clipsApi.SetClipTimes(clipTimes);
}
void UsdBridgeUsdWriter::UpdateClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix)
{
// Add parent-child timestep or update existing relationship
UsdClipsAPI clipsApi(clipPrim);
#ifdef TIME_CLIP_STAGES
if (clipStages)
{
bool exists;
const UsdStagePair& childStagePair = FindOrCreateClipStage(childCache, clipPostfix, childTimeStep, exists);
// At this point, exists should be true, but if clip stage creation failed earlier due to user error,
// exists will be false and we'll just link to the empty new stage created by FindOrCreatePrimClipStage()
const std::string& refStagePath = childStagePair.first;
VtVec2dArray clipActives;
clipsApi.GetClipActive(&clipActives);
VtArray<SdfAssetPath> assetPaths;
clipsApi.GetClipAssetPaths(&assetPaths);
// Find the asset path
SdfAssetPath refStageSdf(refStagePath);
auto assetIt = std::find_if(assetPaths.begin(), assetPaths.end(), [&refStageSdf](const SdfAssetPath& entry) -> bool { return refStageSdf.GetAssetPath() == entry.GetAssetPath(); });
int assetIndex = int(assetIt - assetPaths.begin());
bool newAsset = (assetIndex == assetPaths.size()); // Gives the opportunity to garbage collect unused asset references
{
// Find the parentTimeStep
int timeFindIdx = 0;
for (; timeFindIdx < clipActives.size() && clipActives[timeFindIdx][0] != parentTimeStep; ++timeFindIdx)
{}
bool replaceAsset = false;
// If timestep not found, just add (time, asset ref idx) to actives
if (timeFindIdx == clipActives.size())
clipActives.push_back(GfVec2d(parentTimeStep, assetIndex));
else
{
// Find out whether to update existing active entry with new asset ref idx, or let the entry unchanged and replace the asset itself
double prevAssetIndex = clipActives[timeFindIdx][1];
if (newAsset)
{
//Find prev asset index
int assetIdxFindIdx = 0;
for (; assetIdxFindIdx < clipActives.size() &&
(assetIdxFindIdx == timeFindIdx || clipActives[assetIdxFindIdx][1] != prevAssetIndex);
++assetIdxFindIdx)
{}
// replacement occurs when prevAssetIndex hasn't been found in other entries
replaceAsset = (assetIdxFindIdx == clipActives.size());
}
if(replaceAsset)
assetPaths[int(prevAssetIndex)] = refStageSdf;
else
clipActives[timeFindIdx][1] = assetIndex;
}
// If new asset and not put in place of an old asset, add to assetPaths
if (newAsset && !replaceAsset)
assetPaths.push_back(refStageSdf);
// Send the result through to usd
clipsApi.SetClipAssetPaths(assetPaths);
clipsApi.SetClipActive(clipActives);
}
}
#endif
// Find the parentTimeStep, and change its child (or add the pair if nonexistent)
VtVec2dArray clipTimes;
clipsApi.GetClipTimes(&clipTimes);
{
int findIdx = 0;
for (; findIdx < clipTimes.size(); ++findIdx)
{
if (clipTimes[findIdx][0] == parentTimeStep)
{
clipTimes[findIdx][1] = childTimeStep;
break;
}
}
if (findIdx == clipTimes.size())
clipTimes.push_back(GfVec2d(parentTimeStep, childTimeStep));
clipsApi.SetClipTimes(clipTimes);
}
}
#endif
SdfPath UsdBridgeUsdWriter::AddRef_NoClip(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, double parentTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
return AddRef_Impl(parentCache, childCache, refPathExt, timeVarying, false, false, nullptr, parentTimeStep, parentTimeStep, instanceable, refModCallbacks);
}
SdfPath UsdBridgeUsdWriter::AddRef(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostfix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
// Value clip-enabled references have to be defined on the scenestage, as usd does not re-time recursively.
return AddRef_Impl(parentCache, childCache, refPathExt, timeVarying, valueClip, clipStages, clipPostfix, parentTimeStep, childTimeStep, instanceable, refModCallbacks);
}
SdfPath UsdBridgeUsdWriter::AddRef_Impl(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, // Timevarying existence (visible or not) of the reference itself
bool valueClip, // Retiming through a value clip
bool clipStages, // Separate stages for separate time slots (can only exist in usd if valueClip enabled)
const char* clipPostfix, double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
UsdTimeCode parentTimeCode(parentTimeStep);
SdfPath childBasePath = parentCache->PrimPath;
if (refPathExt)
childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
SdfPath referencingPrimPath = childBasePath.AppendPath(childCache->Name);
UsdPrim referencingPrim = SceneStage->GetPrimAtPath(referencingPrimPath);
if (!referencingPrim)
{
referencingPrim = SceneStage->DefinePrim(referencingPrimPath);
assert(referencingPrim);
#ifdef VALUE_CLIP_RETIMING
if (valueClip)
InitializeClipMetaData(referencingPrim, childCache, parentTimeStep, childTimeStep, clipStages, clipPostfix);
#endif
{
UsdReferences references = referencingPrim.GetReferences(); //references or inherits?
references.ClearReferences();
references.AddInternalReference(childCache->PrimPath);
//referencingPrim.SetInstanceable(true);
}
refModCallbacks.AtNewRef(parentCache, childCache);
#ifdef TIME_BASED_CACHING
// If time domain of the stage extends beyond timestep in either direction, set visibility false for extremes.
if (timeVarying)
InitializePrimVisibility(SceneStage, referencingPrimPath, parentTimeCode,
parentCache, childCache);
#endif
}
else
{
#ifdef TIME_BASED_CACHING
if (timeVarying)
SetPrimVisible(SceneStage, referencingPrimPath, parentTimeCode,
parentCache, childCache);
#ifdef VALUE_CLIP_RETIMING
// Cliptimes are added as additional info, not actively removed (visibility values remain leading in defining existing relationships over timesteps)
// Also, clip stages at childTimeSteps which are not referenced anymore, are not removed; they could still be referenced from other parents!
if (valueClip)
UpdateClipMetaData(referencingPrim, childCache, parentTimeStep, childTimeStep, clipStages, clipPostfix);
#endif
#endif
}
referencingPrim.SetInstanceable(instanceable);
return referencingPrimPath;
}
void UsdBridgeUsdWriter::RemoveAllRefs(UsdBridgePrimCache* parentCache, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
SdfPath childBasePath = parentCache->PrimPath;
if (refPathExt)
childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
RemoveAllRefs(SceneStage, parentCache, childBasePath, timeVarying, timeStep, atRemoveRef);
}
void UsdBridgeUsdWriter::RemoveAllRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, SdfPath childBasePath, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
#ifdef TIME_BASED_CACHING
UsdTimeCode timeCode(timeStep);
// Make refs just for this timecode invisible and possibly remove,
// but leave refs which are still visible in other timecodes intact.
ChildrenRemoveIfInvisibleAnytime(stage, parentCache, childBasePath, timeVarying, timeCode, atRemoveRef);
#else
UsdPrim parentPrim = stage->GetPrimAtPath(childBasePath);
if(parentPrim)
{
UsdPrimSiblingRange children = parentPrim.GetAllChildren();
for (UsdPrim child : children)
{
UsdBridgePrimCache* childCache = parentCache->GetChildCache(child.GetName());
if(childCache)
{
atRemoveRef(parentCache, childCache); // Decrease reference count in caches
stage->RemovePrim(child.GetPath()); // Remove reference prim
}
}
}
#endif
}
void UsdBridgeUsdWriter::ManageUnusedRefs(UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
ManageUnusedRefs(SceneStage, parentCache, newChildren, refPathExt, timeVarying, timeStep, atRemoveRef);
}
void UsdBridgeUsdWriter::ManageUnusedRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
UsdTimeCode timeCode(timeStep);
UsdPrim basePrim;
if (refPathExt)
{
SdfPath childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
basePrim = stage->GetPrimAtPath(childBasePath);
}
else
basePrim = stage->GetPrimAtPath(parentCache->PrimPath);
if (basePrim)
{
// For each old (referencing) child prim, find it among the new ones, otherwise
// possibly delete the referencing prim.
UsdPrimSiblingRange children = basePrim.GetAllChildren();
for (UsdPrim oldChild : children)
{
bool found = false;
for (size_t newChildIdx = 0; newChildIdx < newChildren.size() && !found; ++newChildIdx)
{
found = (oldChild.GetName() == newChildren[newChildIdx]->PrimPath.GetNameToken());
}
UsdBridgePrimCache* oldChildCache = parentCache->GetChildCache(oldChild.GetName());
// Not an assert: allow the case where child prims in a stage aren't cached, ie. when the bridge is destroyed and recreated
if (!found)
#ifdef TIME_BASED_CACHING
{
// Remove *referencing* prim if no visible timecode exists anymore
PrimRemoveIfInvisibleAnytime(stage, oldChild, timeVarying, timeCode, atRemoveRef,
parentCache, oldChildCache);
}
#else
{// remove the whole referencing prim
if(oldChildCache)
atRemoveRef(parentCache, oldChildCache);
stage->RemovePrim(oldChild.GetPath());
}
#endif
}
}
}
void UsdBridgeUsdWriter::InitializeUsdTransform(const UsdBridgePrimCache* cacheEntry)
{
SdfPath transformPath = cacheEntry->PrimPath;
UsdGeomXform transform = GetOrDefinePrim<UsdGeomXform>(SceneStage, transformPath);
assert(transform);
}
void UsdBridgeUsdWriter::InitializeUsdCamera(UsdStageRefPtr cameraStage, const SdfPath& cameraPath)
{
UsdGeomCamera cameraPrim = GetOrDefinePrim<UsdGeomCamera>(cameraStage, cameraPath);
assert(cameraPrim);
cameraPrim.CreateProjectionAttr();
cameraPrim.CreateHorizontalApertureAttr();
cameraPrim.CreateVerticalApertureAttr();
cameraPrim.CreateFocalLengthAttr();
cameraPrim.CreateClippingRangeAttr();
}
void UsdBridgeUsdWriter::BindMaterialToGeom(const SdfPath & refGeomPath, const SdfPath & refMatPath)
{
UsdPrim refGeomPrim = this->SceneStage->GetPrimAtPath(refGeomPath);
assert(refGeomPrim);
// Bind the material to the mesh (use paths existing fully within the surface class definition, not the inherited geometry/material)
UsdShadeMaterial refMatPrim = UsdShadeMaterial::Get(this->SceneStage, refMatPath);
assert(refMatPrim);
UsdShadeMaterialBindingAPI(refGeomPrim).Bind(refMatPrim);
}
void UsdBridgeUsdWriter::UnbindMaterialFromGeom(const SdfPath & refGeomPath)
{
UsdPrim refGeomPrim = this->SceneStage->GetPrimAtPath(refGeomPath);
assert(refGeomPrim);
UsdShadeMaterialBindingAPI(refGeomPrim).UnbindDirectBinding();
}
void UsdBridgeUsdWriter::UpdateUsdTransform(const SdfPath& transPrimPath, const float* transform, bool timeVarying, double timeStep)
{
TimeEvaluator<bool> timeEval(timeVarying, timeStep);
// Note: USD employs left-multiplication (vector in row-space)
GfMatrix4d transMat; // Transforms can only be double, see UsdGeomXform::AddTransformOp (UsdGeomXformable)
transMat.SetRow(0, GfVec4d(GfVec4f(&transform[0])));
transMat.SetRow(1, GfVec4d(GfVec4f(&transform[4])));
transMat.SetRow(2, GfVec4d(GfVec4f(&transform[8])));
transMat.SetRow(3, GfVec4d(GfVec4f(&transform[12])));
//Note that instance transform nodes have already been created.
UsdGeomXform tfPrim = UsdGeomXform::Get(this->SceneStage, transPrimPath);
assert(tfPrim);
tfPrim.ClearXformOpOrder();
UsdGeomXformOp xformOp = tfPrim.AddTransformOp();
ClearAndSetUsdAttribute(xformOp.GetAttr(), transMat, timeEval.Eval(), !timeEval.TimeVarying);
}
void UsdBridgeUsdWriter::UpdateUsdCamera(UsdStageRefPtr timeVarStage, const SdfPath& cameraPrimPath,
const UsdBridgeCameraData& cameraData, double timeStep, bool timeVarHasChanged)
{
const TimeEvaluator<UsdBridgeCameraData> timeEval(cameraData, timeStep);
typedef UsdBridgeCameraData::DataMemberId DMI;
UsdGeomCamera cameraPrim = UsdGeomCamera::Get(timeVarStage, cameraPrimPath);
assert(cameraPrim);
// Set the view matrix
GfVec3d eyePoint(cameraData.Position.Data);
GfVec3d fwdDir(cameraData.Direction.Data);
GfVec3d upDir(cameraData.Up.Data);
GfVec3d lookAtPoint = eyePoint+fwdDir;
GfMatrix4d viewMatrix;
viewMatrix.SetLookAt(eyePoint, lookAtPoint, upDir);
cameraPrim.ClearXformOpOrder();
UsdGeomXformOp xformOp = cameraPrim.AddTransformOp();
ClearAndSetUsdAttribute(xformOp.GetAttr(), viewMatrix, timeEval.Eval(DMI::VIEW),
timeVarHasChanged && !timeEval.IsTimeVarying(DMI::VIEW));
// Helper function for the projection matrix
GfCamera gfCam;
gfCam.SetPerspectiveFromAspectRatioAndFieldOfView(cameraData.Aspect, cameraData.Fovy, GfCamera::FOVVertical);
// Update all attributes affected by SetPerspectiveFromAspectRatioAndFieldOfView (see implementation)
UsdTimeCode projectTime = timeEval.Eval(DMI::PROJECTION);
bool clearProjAttrib = timeVarHasChanged && !timeEval.IsTimeVarying(DMI::PROJECTION);
ClearAndSetUsdAttribute(cameraPrim.GetProjectionAttr(),
gfCam.GetProjection() == GfCamera::Perspective ?
UsdGeomTokens->perspective : UsdGeomTokens->orthographic,
projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetHorizontalApertureAttr(), gfCam.GetHorizontalAperture(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetVerticalApertureAttr(), gfCam.GetVerticalAperture(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetFocalLengthAttr(), gfCam.GetFocalLength(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetClippingRangeAttr(), GfVec2f(cameraData.Near, cameraData.Far), projectTime, clearProjAttrib);
}
void UsdBridgeUsdWriter::UpdateBeginEndTime(double timeStep)
{
if (timeStep < StartTime)
{
StartTime = timeStep;
SceneStage->SetStartTimeCode(timeStep);
}
if (timeStep > EndTime)
{
EndTime = timeStep;
SceneStage->SetEndTimeCode(timeStep);
}
}
TfToken& UsdBridgeUsdWriter::AttributeNameToken(const char* attribName)
{
int i = 0;
for(; i < AttributeTokens.size(); ++i)
{
if(AttributeTokens[i] == attribName) // Overloaded == operator on TfToken
break;
}
if(i == AttributeTokens.size())
AttributeTokens.emplace_back(TfToken(attribName));
return AttributeTokens[i];
}
void UsdBridgeUsdWriter::AddSharedResourceRef(const UsdBridgeResourceKey& key)
{
bool found = false;
for(auto& entry : SharedResourceCache)
{
if(entry.first == key)
{
++entry.second.first;
found = true;
}
}
if(!found)
SharedResourceCache.push_back(SharedResourceKV(key, SharedResourceValue(1, false)));
}
bool UsdBridgeUsdWriter::RemoveSharedResourceRef(const UsdBridgeResourceKey& key)
{
bool removed = false;
SharedResourceContainer::iterator it = SharedResourceCache.begin();
while(it != SharedResourceCache.end())
{
if(it->first == key)
--it->second.first;
if(it->second.first == 0)
{
it = SharedResourceCache.erase(it);
removed = true;
}
else
++it;
}
return removed;
}
bool UsdBridgeUsdWriter::SetSharedResourceModified(const UsdBridgeResourceKey& key)
{
bool modified = false;
for(auto& entry : SharedResourceCache)
{
if(entry.first == key)
{
modified = entry.second.second;
entry.second.second = true;
}
}
return modified;
}
void UsdBridgeUsdWriter::ResetSharedResourceModified()
{
for(auto& entry : SharedResourceCache)
{
entry.second.second = false;
}
}
void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* fileExtension)
{
// Directly from usd is inaccurate, as timesteps may have been cleared without file removal
//// Assuming prim without clip stages.
//const UsdStageRefPtr volumeStage = usdWriter.GetTimeVarStage(cache);
//const UsdStageRefPtr volumeStage = usdWriter.GetTimeVarStage(cache);
//const SdfPath& volPrimPath = cache->PrimPath;
//
//UsdVolVolume volume = UsdVolVolume::Get(volumeStage, volPrimPath);
//assert(volume);
//
//SdfPath ovdbFieldPath = volPrimPath.AppendPath(SdfPath(constring::openVDBPrimPf));
//UsdVolOpenVDBAsset ovdbField = UsdVolOpenVDBAsset::Get(volumeStage, ovdbFieldPath);
//
//UsdAttribute fileAttr = ovdbField.GetFilePathAttr();
//
//std::vector<double> fileTimes;
//fileAttr.GetTimeSamples(&fileTimes);
assert(cache->ResourceKeys);
UsdBridgePrimCache::ResourceContainer& keys = *(cache->ResourceKeys);
std::string basePath = usdWriter.SessionDirectory; basePath.append(resourceFolder);
for (const UsdBridgeResourceKey& key : keys)
{
bool removeFile = true;
if(key.name)
removeFile = usdWriter.RemoveSharedResourceRef(key);
if(removeFile)
{
double timeStep =
#ifdef TIME_BASED_CACHING
key.timeStep;
#else
0.0;
#endif
const std::string& resFileName = usdWriter.GetResourceFileName(basePath.c_str(), key.name, timeStep, fileExtension);
usdWriter.Connect->RemoveFile(resFileName.c_str(), true);
}
}
keys.resize(0);
} | 39,261 | C++ | 33.806738 | 242 | 0.744912 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeUsdWriter_h
#define UsdBridgeUsdWriter_h
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
#include "UsdBridgeData.h"
#include "UsdBridgeCaches.h"
#include "UsdBridgeVolumeWriter.h"
#include "UsdBridgeConnection.h"
#include "UsdBridgeTimeEvaluator.h"
#include <memory>
#include <functional>
//Includes detailed usd translation interface of Usd Bridge
class UsdBridgeUsdWriter
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
using SamplerDMI = UsdBridgeSamplerData::DataMemberId;
using AtNewRefFunc = std::function<void(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)>;
using AtRemoveRefFunc = std::function<void(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)>;
struct RefModFuncs
{
AtNewRefFunc AtNewRef;
AtRemoveRefFunc AtRemoveRef;
};
UsdBridgeUsdWriter(const UsdBridgeSettings& settings);
~UsdBridgeUsdWriter();
void SetExternalSceneStage(UsdStageRefPtr sceneStage);
void SetEnableSaving(bool enableSaving);
int FindSessionNumber();
bool CreateDirectories();
#ifdef CUSTOM_PBR_MDL
bool CreateMdlFiles();
#endif
bool InitializeSession();
void ResetSession();
bool OpenSceneStage();
UsdStageRefPtr GetSceneStage() const;
UsdStageRefPtr GetTimeVarStage(UsdBridgePrimCache* cache
#ifdef TIME_CLIP_STAGES
, bool useClipStage = false, const char* clipPf = nullptr, double timeStep = 0.0
, std::function<void (UsdStageRefPtr)> initFunc = [](UsdStageRefPtr){}
#endif
) const;
#ifdef VALUE_CLIP_RETIMING
void CreateManifestStage(const char* name, const char* primPostfix, UsdBridgePrimCache* cacheEntry);
void RemoveManifestAndClipStages(const UsdBridgePrimCache* cacheEntry);
const UsdStagePair& FindOrCreatePrimStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix) const;
const UsdStagePair& FindOrCreateClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, double timeStep, bool& exists) const;
const UsdStagePair& FindOrCreatePrimClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, bool isClip, double timeStep, bool& exists) const;
#endif
void AddRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp, const char* layerId = nullptr);
void RemoveRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp);
const std::string& CreatePrimName(const char* name, const char* category);
const std::string& GetResourceFileName(const std::string& basePath, double timeStep, const char* fileExtension);
const std::string& GetResourceFileName(const char* folderName, const std::string& objectName, double timeStep, const char* fileExtension);
const std::string& GetResourceFileName(const char* folderName, const char* optionalObjectName, const std::string& defaultObjectName, double timeStep, const char* fileExtension);
bool CreatePrim(const SdfPath& path);
void DeletePrim(const UsdBridgePrimCache* cacheEntry);
#ifdef TIME_BASED_CACHING
void InitializePrimVisibility(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache);
void SetPrimVisible(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache);
void PrimRemoveIfInvisibleAnytime(UsdStageRefPtr stage, const UsdPrim& prim, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* primCache);
void ChildrenRemoveIfInvisibleAnytime(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const SdfPath& parentPath, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef, const SdfPath& exceptPath = SdfPath());
#endif
#ifdef VALUE_CLIP_RETIMING
void InitializeClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix);
void UpdateClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix);
#endif
SdfPath AddRef_NoClip(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, double parentTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
SdfPath AddRef(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostFix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
// Timevarying means that the existence of a reference between prim A and B can differ over time, valueClip denotes the addition of clip metadata for re-timing,
// and clipStages will carve up the referenced clip asset files into one for each timestep (stages are created as necessary). clipPostFix is irrelevant if !clipStages.
// Returns the path to the parent's subprim which represents/holds the reference to the child's main class prim.
SdfPath AddRef_Impl(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostFix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
void RemoveAllRefs(UsdBridgePrimCache* parentCache, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void RemoveAllRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, SdfPath childBasePath, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void ManageUnusedRefs(UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void ManageUnusedRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void InitializeUsdTransform(const UsdBridgePrimCache* cacheEntry);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim);
UsdPrim InitializeUsdVolume(UsdStageRefPtr volumeStage, const SdfPath& volumePath, bool uniformPrim) const;
UsdShadeMaterial InitializeUsdMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim) const;
void InitializeUsdSampler(UsdStageRefPtr samplerStage,const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim) const;
void InitializeUsdCamera(UsdStageRefPtr cameraStage, const SdfPath& geomPath);
UsdShadeShader GetOrCreateAttributeReader() const;
#ifdef USE_INDEX_MATERIALS
UsdShadeMaterial InitializeIndexVolumeMaterial_Impl(UsdStageRefPtr volumeStage,
const SdfPath& volumePath, bool uniformPrim, const UsdBridgeTimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr) const;
#endif
#ifdef VALUE_CLIP_RETIMING
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMeshData& meshData);
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeInstancerData& instancerData);
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeCurveData& curveData);
void UpdateUsdVolumeManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData);
void UpdateUsdMaterialManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMaterialData& matData);
void UpdateUsdSamplerManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData);
#endif
void BindMaterialToGeom(const SdfPath& refGeomPath, const SdfPath& refMatPath);
void ConnectSamplersToMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const SdfPrimPathList& refSamplerPrimPaths,
const UsdBridgePrimCacheList& samplerCacheEntries, const UsdSamplerRefData* samplerRefDatas, size_t numSamplers, double worldTimeStep); // Disconnect happens automatically at parameter overwrite
void UnbindMaterialFromGeom(const SdfPath & refGeomPath);
void UpdateUsdTransform(const SdfPath& transPrimPath, const float* transform, bool timeVarying, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& meshPath, const UsdBridgeMeshData& geomData, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& instancerPath, const UsdBridgeInstancerData& geomData, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& curvePath, const UsdBridgeCurveData& geomData, double timeStep);
void UpdateUsdMaterial(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdatePsShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdateMdlShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdateUsdVolume(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData, double timeStep);
void UpdateUsdSampler(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData, double timeStep);
void UpdateUsdCamera(UsdStageRefPtr timeVarStage, const SdfPath& cameraPrimPath,
const UsdBridgeCameraData& cameraData, double timeStep, bool timeVarHasChanged);
void UpdateUsdInstancerPrototypes(const SdfPath& instancerPath, const UsdBridgeInstancerRefData& geomRefData, const SdfPrimPathList& refProtoGeomPrimPaths, const char* protoShapePathRp);
void UpdateAttributeReader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, MaterialDMI dataMemberId, const char* newName, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep, MaterialDMI timeVarying);
void UpdateInAttribute(UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const char* newName, double timeStep, SamplerDMI timeVarying);
void UpdateBeginEndTime(double timeStep);
#ifdef USE_INDEX_MATERIALS
void UpdateIndexVolumeMaterial(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& volumePath, const UsdBridgeVolumeData& volumeData, double timeStep);
#endif
void ResetSharedResourceModified();
TfToken& AttributeNameToken(const char* attribName);
friend void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
friend void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
friend void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* extension);
// Settings
UsdBridgeSettings Settings;
UsdBridgeConnectionSettings ConnectionSettings;
UsdBridgeLogObject LogObject;
protected:
// Connect
std::unique_ptr<UsdBridgeConnection> Connect = nullptr;
// Volume writer
std::shared_ptr<UsdBridgeVolumeWriterI> VolumeWriter; // shared - requires custom deleter
// Shared resource cache (ie. resources shared between UsdBridgePrimCache entries)
// Maps keys to a refcount and modified flag
using SharedResourceValue = std::pair<int, bool>;
using SharedResourceKV = std::pair<UsdBridgeResourceKey, SharedResourceValue>;
using SharedResourceContainer = std::vector<SharedResourceKV>;
SharedResourceContainer SharedResourceCache;
void AddSharedResourceRef(const UsdBridgeResourceKey& key);
bool RemoveSharedResourceRef(const UsdBridgeResourceKey& key);
// Sets modified flag and returns whether the shared resource has been modified since ResetSharedResourceModified()
bool SetSharedResourceModified(const UsdBridgeResourceKey& key);
// Token cache for attribute names
std::vector<TfToken> AttributeTokens;
// Session specific info
int SessionNumber = -1;
UsdStageRefPtr SceneStage;
UsdStageRefPtr ExternalSceneStage;
bool EnableSaving = true;
std::string SceneFileName;
std::string SessionDirectory;
std::string RootName;
std::string RootClassName;
#ifdef CUSTOM_PBR_MDL
SdfAssetPath MdlOpaqueRelFilePath; // relative from Scene Folder
SdfAssetPath MdlTranslucentRelFilePath; // relative from Scene Folder
#endif
double StartTime = 0.0;
double EndTime = 0.0;
std::string TempNameStr;
std::vector<unsigned char> TempImageData;
};
void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* fileExtension);
void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
#endif | 13,391 | C | 59.597285 | 237 | 0.821074 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Volume.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
namespace
{
void InitializeUsdVolumeTimeVar(UsdVolVolume& volume, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
}
void InitializeUsdVolumeAssetTimeVar(UsdVolOpenVDBAsset& volAsset, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
UsdVolOpenVDBAsset& attribCreatePrim = volAsset;
UsdPrim attribRemovePrim = volAsset.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::DATA, CreateFilePathAttr, UsdBridgeTokens->filePath);
}
UsdPrim InitializeUsdVolume_Impl(UsdStageRefPtr volumeStage, const SdfPath & volumePath, bool uniformPrim,
TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
UsdVolVolume volume = GetOrDefinePrim<UsdVolVolume>(volumeStage, volumePath);
SdfPath ovdbFieldPath = volumePath.AppendPath(SdfPath(constring::openVDBPrimPf));
UsdVolOpenVDBAsset volAsset = GetOrDefinePrim<UsdVolOpenVDBAsset>(volumeStage, ovdbFieldPath);
if (uniformPrim)
{
volume.CreateFieldRelationship(UsdBridgeTokens->density, ovdbFieldPath);
volAsset.CreateFieldNameAttr(VtValue(UsdBridgeTokens->density));
}
InitializeUsdVolumeTimeVar(volume, timeEval);
InitializeUsdVolumeAssetTimeVar(volAsset, timeEval);
return volume.GetPrim();
}
void UpdateUsdVolumeAttributes(UsdVolVolume& uniformVolume, UsdVolVolume& timeVarVolume, UsdVolOpenVDBAsset& uniformField, UsdVolOpenVDBAsset& timeVarField,
const UsdBridgeVolumeData& volumeData, double timeStep, const std::string& relVolPath)
{
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData, timeStep);
typedef UsdBridgeVolumeData::DataMemberId DMI;
SdfAssetPath volAsset(relVolPath);
// Set extents in usd
float minX = volumeData.Origin[0];
float minY = volumeData.Origin[1];
float minZ = volumeData.Origin[2];
float maxX = ((float)volumeData.NumElements[0] * volumeData.CellDimensions[0]) + minX;
float maxY = ((float)volumeData.NumElements[1] * volumeData.CellDimensions[1]) + minY;
float maxZ = ((float)volumeData.NumElements[2] * volumeData.CellDimensions[2]) + minZ;
VtVec3fArray extentArray(2);
extentArray[0].Set(minX, minY, minZ);
extentArray[1].Set(maxX, maxY, maxZ);
UsdAttribute uniformFileAttr = uniformField.GetFilePathAttr();
UsdAttribute timeVarFileAttr = timeVarField.GetFilePathAttr();
UsdAttribute uniformExtentAttr = uniformVolume.GetExtentAttr();
UsdAttribute timeVarExtentAttr = timeVarVolume.GetExtentAttr();
bool dataTimeVarying = timeEval.IsTimeVarying(DMI::DATA);
// Clear timevarying attributes if necessary
ClearUsdAttributes(uniformFileAttr, timeVarFileAttr, dataTimeVarying);
ClearUsdAttributes(uniformExtentAttr, timeVarExtentAttr, dataTimeVarying);
// Set the attributes
SET_TIMEVARYING_ATTRIB(dataTimeVarying, timeVarFileAttr, uniformFileAttr, volAsset);
SET_TIMEVARYING_ATTRIB(dataTimeVarying, timeVarExtentAttr, uniformExtentAttr, extentArray);
}
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdVolume(UsdStageRefPtr volumeStage, const SdfPath & volumePath, bool uniformPrim) const
{
UsdPrim volumePrim = InitializeUsdVolume_Impl(volumeStage, volumePath, uniformPrim);
#ifdef USE_INDEX_MATERIALS
UsdShadeMaterial matPrim = InitializeIndexVolumeMaterial_Impl(volumeStage, volumePath, uniformPrim);
UsdShadeMaterialBindingAPI(volumePrim).Bind(matPrim);
#endif
return volumePrim;
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdVolumeManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData)
{
const SdfPath & volumePath = cacheEntry->PrimPath;
UsdStageRefPtr volumeStage = cacheEntry->ManifestStage.second;
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData);
InitializeUsdVolume_Impl(volumeStage, volumePath,
false, &timeEval);
#ifdef USE_INDEX_MATERIALS
InitializeIndexVolumeMaterial_Impl(volumeStage, volumePath, false, &timeEval);
#endif
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
void UsdBridgeUsdWriter::UpdateUsdVolume(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData, double timeStep)
{
const SdfPath& volPrimPath = cacheEntry->PrimPath;
// Get the volume and ovdb field prims
UsdVolVolume uniformVolume = UsdVolVolume::Get(SceneStage, volPrimPath);
assert(uniformVolume);
UsdVolVolume timeVarVolume = UsdVolVolume::Get(timeVarStage, volPrimPath);
assert(timeVarVolume);
SdfPath ovdbFieldPath = volPrimPath.AppendPath(SdfPath(constring::openVDBPrimPf));
UsdVolOpenVDBAsset uniformField = UsdVolOpenVDBAsset::Get(SceneStage, ovdbFieldPath);
assert(uniformField);
UsdVolOpenVDBAsset timeVarField = UsdVolOpenVDBAsset::Get(timeVarStage, ovdbFieldPath);
assert(timeVarField);
// Set the file path reference in usd
const std::string& relVolPath = GetResourceFileName(constring::volFolder, cacheEntry->Name.GetString(), timeStep, constring::vdbExtension);
UpdateUsdVolumeAttributes(uniformVolume, timeVarVolume, uniformField, timeVarField, volumeData, timeStep, relVolPath);
#ifdef USE_INDEX_MATERIALS
UpdateIndexVolumeMaterial(SceneStage, timeVarStage, volPrimPath, volumeData, timeStep);
#endif
// Output stream path (relative from connection working dir)
std::string wdRelVolPath(SessionDirectory + relVolPath);
// Write VDB data to stream
VolumeWriter->ToVDB(volumeData);
// Flush stream out to storage
const char* volumeStreamData; size_t volumeStreamDataSize;
VolumeWriter->GetSerializedVolumeData(volumeStreamData, volumeStreamDataSize);
Connect->WriteFile(volumeStreamData, volumeStreamDataSize, wdRelVolPath.c_str(), true);
// Record file write for timestep
cacheEntry->AddResourceKey(UsdBridgeResourceKey(nullptr, timeStep));
}
void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter)
{
RemoveResourceFiles(cache, usdWriter, constring::volFolder, constring::vdbExtension);
} | 6,214 | C++ | 38.335443 | 158 | 0.78822 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeTimeEvaluator.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeTimeEvaluator.h"
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
const UsdTimeCode UsdBridgeTimeEvaluator<bool>::DefaultTime = UsdTimeCode::Default(); | 245 | C++ | 29.749996 | 85 | 0.795918 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Geometry.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
namespace
{
template<typename UsdGeomType>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomType& usdGeom) { return UsdAttribute(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomMesh& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomPoints& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomBasisCurves& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomPointInstancer& usdGeom) { return usdGeom.GetPositionsAttr(); }
template<typename GeomDataType>
void CreateUsdGeomColorPrimvars(UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const UsdBridgeSettings& settings, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
bool timeVarChecked = true;
if(timeEval)
{
timeVarChecked = timeEval->IsTimeVarying(DMI::COLORS);
}
if (timeVarChecked)
{
primvarApi.CreatePrimvar(UsdBridgeTokens->color, SdfValueTypeNames->Float4Array);
}
else
{
primvarApi.RemovePrimvar(UsdBridgeTokens->color);
}
}
template<typename GeomDataType>
void CreateUsdGeomTexturePrimvars(UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const UsdBridgeSettings& settings, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
bool timeVarChecked = true;
if(timeEval)
{
timeVarChecked = timeEval->IsTimeVarying(DMI::ATTRIBUTE0);
}
if (timeVarChecked)
primvarApi.CreatePrimvar(UsdBridgeTokens->st, SdfValueTypeNames->TexCoord2fArray);
else if (timeEval)
primvarApi.RemovePrimvar(UsdBridgeTokens->st);
}
template<typename GeomDataType>
void CreateUsdGeomAttributePrimvar(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, uint32_t attribIndex, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
const UsdBridgeAttribute& attrib = geomData.Attributes[attribIndex];
if(attrib.DataType != UsdBridgeType::UNDEFINED)
{
bool timeVarChecked = true;
if(timeEval)
{
DMI attributeId = DMI::ATTRIBUTE0 + attribIndex;
timeVarChecked = timeEval->IsTimeVarying(attributeId);
}
TfToken attribToken = attrib.Name ? writer->AttributeNameToken(attrib.Name) : AttribIndexToToken(attribIndex);
if(timeVarChecked)
{
SdfValueTypeName primvarType = GetPrimvarArrayType(attrib.DataType);
if(primvarType == SdfValueTypeNames->BoolArray)
{
UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::WARNING, "UsdGeom Attribute<" << attribIndex << "> primvar does not support source data type: " << attrib.DataType);
}
// Allow for attrib primvar types to change
UsdGeomPrimvar primvar = primvarApi.GetPrimvar(attribToken);
if(primvar && primvar.GetTypeName() != primvarType)
{
primvarApi.RemovePrimvar(attribToken);
}
primvarApi.CreatePrimvar(attribToken, primvarType);
}
else if(timeEval)
{
primvarApi.RemovePrimvar(attribToken);
}
}
}
template<typename GeomDataType>
void CreateUsdGeomAttributePrimvars(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
for(uint32_t attribIndex = 0; attribIndex < geomData.NumAttributes; ++attribIndex)
{
CreateUsdGeomAttributePrimvar(writer, primvarApi, geomData, attribIndex, timeEval);
}
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomMesh& meshGeom, const UsdBridgeMeshData& meshData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeMeshData>* timeEval = nullptr)
{
typedef UsdBridgeMeshData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(meshGeom);
UsdGeomMesh& attribCreatePrim = meshGeom;
UsdPrim attribRemovePrim = meshGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->points);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INDICES, CreateFaceVertexIndicesAttr, UsdBridgeTokens->faceVertexCounts);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INDICES, CreateFaceVertexCountsAttr, UsdBridgeTokens->faceVertexIndices);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::NORMALS, CreateNormalsAttr, UsdBridgeTokens->normals);
CreateUsdGeomColorPrimvars(primvarApi, meshData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, meshData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, meshData, timeEval);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomPoints& pointsGeom, const UsdBridgeInstancerData& instancerData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(pointsGeom);
UsdGeomPoints& attribCreatePrim = pointsGeom;
UsdPrim attribRemovePrim = pointsGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->points);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INSTANCEIDS, CreateIdsAttr, UsdBridgeTokens->ids);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ORIENTATIONS, CreateNormalsAttr, UsdBridgeTokens->normals);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateWidthsAttr, UsdBridgeTokens->widths);
CreateUsdGeomColorPrimvars(primvarApi, instancerData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, instancerData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, instancerData, timeEval);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomPointInstancer& pointsGeom, const UsdBridgeInstancerData& instancerData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(pointsGeom);
UsdGeomPointInstancer& attribCreatePrim = pointsGeom;
UsdPrim attribRemovePrim = pointsGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePositionsAttr, UsdBridgeTokens->positions);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SHAPEINDICES, CreateProtoIndicesAttr, UsdBridgeTokens->protoIndices);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INSTANCEIDS, CreateIdsAttr, UsdBridgeTokens->ids);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ORIENTATIONS, CreateOrientationsAttr, UsdBridgeTokens->orientations);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateScalesAttr, UsdBridgeTokens->scales);
CreateUsdGeomColorPrimvars(primvarApi, instancerData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, instancerData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, instancerData, timeEval);
//CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::LINEARVELOCITIES, CreateVelocitiesAttr, UsdBridgeTokens->velocities);
//CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ANGULARVELOCITIES, CreateAngularVelocitiesAttr, UsdBridgeTokens->angularVelocities);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INVISIBLEIDS, CreateInvisibleIdsAttr, UsdBridgeTokens->invisibleIds);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomBasisCurves& curveGeom, const UsdBridgeCurveData& curveData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeCurveData>* timeEval = nullptr)
{
typedef UsdBridgeCurveData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(curveGeom);
UsdGeomBasisCurves& attribCreatePrim = curveGeom;
UsdPrim attribRemovePrim = curveGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->positions);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::CURVELENGTHS, CreateCurveVertexCountsAttr, UsdBridgeTokens->curveVertexCounts);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::NORMALS, CreateNormalsAttr, UsdBridgeTokens->normals);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateWidthsAttr, UsdBridgeTokens->widths);
CreateUsdGeomColorPrimvars(primvarApi, curveData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, curveData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, curveData, timeEval);
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeMeshData>* timeEval = nullptr)
{
UsdGeomMesh geomMesh = GetOrDefinePrim<UsdGeomMesh>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomMesh, meshData, settings, timeEval);
if (uniformPrim)
{
geomMesh.CreateDoubleSidedAttr(VtValue(true));
geomMesh.CreateSubdivisionSchemeAttr().Set(UsdGeomTokens->none);
}
return geomMesh.GetPrim();
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
if (instancerData.UseUsdGeomPoints)
{
UsdGeomPoints geomPoints = GetOrDefinePrim<UsdGeomPoints>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomPoints, instancerData, settings, timeEval);
if (uniformPrim)
{
geomPoints.CreateDoubleSidedAttr(VtValue(true));
}
return geomPoints.GetPrim();
}
else
{
UsdGeomPointInstancer geomPoints = GetOrDefinePrim<UsdGeomPointInstancer>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomPoints, instancerData, settings, timeEval);
return geomPoints.GetPrim();
}
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeCurveData>* timeEval = nullptr)
{
UsdGeomBasisCurves geomCurves = GetOrDefinePrim<UsdGeomBasisCurves>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomCurves, curveData, settings, timeEval);
if (uniformPrim)
{
geomCurves.CreateDoubleSidedAttr(VtValue(true));
geomCurves.GetTypeAttr().Set(UsdGeomTokens->linear);
}
return geomCurves.GetPrim();
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomPoints(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::POINTS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::POINTS);
ClearUsdAttributes(UsdGeomGetPointsAttribute(uniformGeom), UsdGeomGetPointsAttribute(timeVarGeom), timeVaryingUpdate);
ClearUsdAttributes(uniformGeom.GetExtentAttr(), timeVarGeom.GetExtentAttr(), timeVaryingUpdate);
if (performsUpdate)
{
if (!geomData.Points)
{
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "GeomData requires points.");
}
else
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::POINTS);
// Points
UsdAttribute pointsAttr = UsdGeomGetPointsAttribute(*outGeom);
const void* arrayData = geomData.Points;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = pointsAttr;
VtVec3fArray& usdVerts = GetStaticTempArray<VtVec3fArray>();
bool setPrimvar = true;
switch (geomData.PointsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_CUSTOM_ARRAY_MACRO(VtVec3fArray, usdVerts); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_CUSTOM_ARRAY_MACRO(VtVec3fArray, GfVec3d, usdVerts); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom PointsAttr should be FLOAT3 or DOUBLE3."); break; }
}
// Usd requires extent.
GfRange3f extent;
for (const auto& pt : usdVerts) {
extent.UnionWith(pt);
}
VtVec3fArray extentArray(2);
extentArray[0] = extent.GetMin();
extentArray[1] = extent.GetMax();
outGeom->GetExtentAttr().Set(extentArray, timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomIndices(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INDICES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INDICES);
ClearUsdAttributes(uniformGeom.GetFaceVertexIndicesAttr(), timeVarGeom.GetFaceVertexIndicesAttr(), timeVaryingUpdate);
ClearUsdAttributes(uniformGeom.GetFaceVertexCountsAttr(), timeVarGeom.GetFaceVertexCountsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INDICES);
uint64_t numIndices = geomData.NumIndices;
VtArray<int>& usdVertexCounts = GetStaticTempArray<VtIntArray>();
usdVertexCounts.resize(numPrims);
int vertexCount = numIndices / numPrims;
for (uint64_t i = 0; i < numPrims; ++i)
usdVertexCounts[i] = vertexCount;//geomData.FaceVertCounts[i];
// Face Vertex counts
UsdAttribute faceVertCountsAttr = outGeom->GetFaceVertexCountsAttr();
faceVertCountsAttr.Set(usdVertexCounts, timeCode);
if (!geomData.Indices)
{
VtIntArray& tempIndices = GetStaticTempArray<VtIntArray>();
tempIndices.resize(numIndices);
for (uint64_t i = 0; i < numIndices; ++i)
tempIndices[i] = (int)i;
UsdAttribute arrayPrimvar = outGeom->GetFaceVertexIndicesAttr();
arrayPrimvar.Set(tempIndices, timeCode);
}
else
{
// Face indices
const void* arrayData = geomData.Indices;
size_t arrayNumElements = numIndices;
UsdAttribute arrayPrimvar = outGeom->GetFaceVertexIndicesAttr();
bool setPrimvar = true;
switch (geomData.IndicesType)
{
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtIntArray, uint64_t); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtIntArray, int64_t); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom FaceVertexIndicesAttr should be (U)LONG or (U)INT."); break; }
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomNormals(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::NORMALS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::NORMALS);
ClearUsdAttributes(uniformGeom.GetNormalsAttr(), timeVarGeom.GetNormalsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::NORMALS);
UsdAttribute normalsAttr = outGeom->GetNormalsAttr();
if (geomData.Normals != nullptr)
{
const void* arrayData = geomData.Normals;
size_t arrayNumElements = geomData.PerPrimNormals ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = normalsAttr;
bool setPrimvar = true;
switch (geomData.NormalsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom NormalsAttr should be FLOAT3 or DOUBLE3."); break; }
}
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken normalInterpolation = geomData.PerPrimNormals ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformGeom.SetNormalsInterpolation(normalInterpolation);
}
else
{
normalsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomTexCoords(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ATTRIBUTE0);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ATTRIBUTE0);
UsdGeomPrimvar uniformPrimvar = uniformPrimvars.GetPrimvar(UsdBridgeTokens->st);
UsdGeomPrimvar timeVarPrimvar = timeVarPrimvars.GetPrimvar(UsdBridgeTokens->st);
ClearUsdAttributes(uniformPrimvar.GetAttr(), timeVarPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::ATTRIBUTE0);
UsdAttribute texcoordPrimvar = timeVaryingUpdate ? timeVarPrimvar : uniformPrimvar;
assert(texcoordPrimvar);
const UsdBridgeAttribute& texCoordAttrib = geomData.Attributes[0];
if (texCoordAttrib.Data != nullptr)
{
const void* arrayData = texCoordAttrib.Data;
size_t arrayNumElements = texCoordAttrib.PerPrimData ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = texcoordPrimvar;
bool setPrimvar = true;
switch (texCoordAttrib.DataType)
{
case UsdBridgeType::FLOAT2: { ASSIGN_PRIMVAR_MACRO(VtVec2fArray); break; }
case UsdBridgeType::DOUBLE2: { ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec2fArray, GfVec2d); break; }
default: { UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::ERR, "UsdGeom st primvar should be FLOAT2 or DOUBLE2."); break; }
}
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken texcoordInterpolation = texCoordAttrib.PerPrimData ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformPrimvar.SetInterpolation(texcoordInterpolation);
}
else
{
texcoordPrimvar.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomAttribute(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval, uint32_t attribIndex)
{
assert(attribIndex < geomData.NumAttributes);
const UsdBridgeAttribute& bridgeAttrib = geomData.Attributes[attribIndex];
TfToken attribToken = bridgeAttrib.Name ? writer->AttributeNameToken(bridgeAttrib.Name) : AttribIndexToToken(attribIndex);
UsdGeomPrimvar uniformPrimvar = uniformPrimvars.GetPrimvar(attribToken);
// The uniform primvar has to exist, otherwise any timevarying data will be ignored as well
if(!uniformPrimvar || uniformPrimvar.GetTypeName() != GetPrimvarArrayType(bridgeAttrib.DataType))
{
CreateUsdGeomAttributePrimvar(writer, uniformPrimvars, geomData, attribIndex); // No timeEval, to force attribute primvar creation on the uniform api
}
UsdGeomPrimvar timeVarPrimvar = timeVarPrimvars.GetPrimvar(attribToken);
if(!timeVarPrimvar || timeVarPrimvar.GetTypeName() != GetPrimvarArrayType(bridgeAttrib.DataType)) // even though new clipstages initialize the correct primvar type/name, it may still be wrong for existing ones (or primstages if so configured)
{
CreateUsdGeomAttributePrimvar(writer, timeVarPrimvars, geomData, attribIndex, &timeEval);
}
using DMI = typename GeomDataType::DataMemberId;
DMI attributeId = DMI::ATTRIBUTE0 + attribIndex;
bool performsUpdate = updateEval.PerformsUpdate(attributeId);
bool timeVaryingUpdate = timeEval.IsTimeVarying(attributeId);
ClearUsdAttributes(uniformPrimvar.GetAttr(), timeVarPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(attributeId);
UsdAttribute attributePrimvar = timeVaryingUpdate ? timeVarPrimvar : uniformPrimvar;
if(!attributePrimvar)
{
UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::ERR, "UsdGeom Attribute<Index> primvar not found, was the attribute at requested index valid during initialization of the prim? Index is " << attribIndex);
}
else
{
if (bridgeAttrib.Data != nullptr)
{
const void* arrayData = bridgeAttrib.Data;
size_t arrayNumElements = bridgeAttrib.PerPrimData ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = attributePrimvar;
AssignAttribArrayToPrimvar(writer->LogObject, arrayData, bridgeAttrib.DataType, arrayNumElements, arrayPrimvar, timeCode);
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken attribInterpolation = bridgeAttrib.PerPrimData ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformPrimvar.SetInterpolation(attribInterpolation);
}
else
{
attributePrimvar.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomAttributes(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
uint32_t startIdx = 0;
for(uint32_t attribIndex = startIdx; attribIndex < geomData.NumAttributes; ++attribIndex)
{
const UsdBridgeAttribute& attrib = geomData.Attributes[attribIndex];
if(attrib.DataType != UsdBridgeType::UNDEFINED)
UpdateUsdGeomAttribute(writer, timeVarPrimvars, uniformPrimvars, geomData, numPrims, updateEval, timeEval, attribIndex);
}
}
template<typename GeomDataType>
void UpdateUsdGeomColors(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::COLORS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::COLORS);
UsdGeomPrimvar uniformDispPrimvar = uniformPrimvars.GetPrimvar(UsdBridgeTokens->color);
UsdGeomPrimvar timeVarDispPrimvar = timeVarPrimvars.GetPrimvar(UsdBridgeTokens->color);
ClearUsdAttributes(uniformDispPrimvar.GetAttr(), timeVarDispPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::COLORS);
UsdGeomPrimvar colorPrimvar = timeVaryingUpdate ? timeVarDispPrimvar : uniformDispPrimvar;
if (geomData.Colors != nullptr)
{
size_t arrayNumElements = geomData.PerPrimColors ? numPrims : geomData.NumPoints;
assert(colorPrimvar);
AssignColorArrayToPrimvar(writer->LogObject, geomData.Colors, arrayNumElements, geomData.ColorsType, timeEval.Eval(DMI::COLORS), colorPrimvar.GetAttr());
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken colorInterpolation = geomData.PerPrimColors ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformDispPrimvar.SetInterpolation(colorInterpolation);
}
else
{
colorPrimvar.GetAttr().Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomInstanceIds(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INSTANCEIDS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INSTANCEIDS);
ClearUsdAttributes(uniformGeom.GetIdsAttr(), timeVarGeom.GetIdsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INSTANCEIDS);
UsdAttribute idsAttr = outGeom->GetIdsAttr();
if (geomData.InstanceIds)
{
const void* arrayData = geomData.InstanceIds;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = idsAttr;
bool setPrimvar = true;
switch (geomData.InstanceIdsType)
{
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, unsigned int); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, int); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom IdsAttribute should be (U)LONG or (U)INT."); break; }
}
}
else
{
idsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomWidths(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SCALES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SCALES);
ClearUsdAttributes(uniformGeom.GetWidthsAttr(), timeVarGeom.GetWidthsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::SCALES);
UsdAttribute widthsAttribute = outGeom.GetWidthsAttr();
assert(widthsAttribute);
if (geomData.Scales)
{
const void* arrayData = geomData.Scales;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = widthsAttribute;
bool setPrimvar = false;
auto doubleFn = [](VtFloatArray& usdArray) { for(auto& x : usdArray) { x *= 2.0f; } };
switch (geomData.ScalesType)
{
case UsdBridgeType::FLOAT: {ASSIGN_PRIMVAR_MACRO(VtFloatArray); doubleFn(usdArray); arrayPrimvar.Set(usdArray, timeCode); break; }
case UsdBridgeType::DOUBLE: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtFloatArray, double); doubleFn(usdArray); arrayPrimvar.Set(usdArray, timeCode); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom WidthsAttribute should be FLOAT or DOUBLE."); break; }
}
}
else
{
// Remember that widths define a diameter, so a default width (1.0) corresponds to a scale of 0.5.
if(geomData.getUniformScale() != 0.5f)
{
VtFloatArray& usdWidths = GetStaticTempArray<VtFloatArray>();
usdWidths.resize(geomData.NumPoints);
for(auto& x : usdWidths) x = geomData.getUniformScale() * 2.0f;
widthsAttribute.Set(usdWidths, timeCode);
}
else
{
widthsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomScales(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SCALES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SCALES);
ClearUsdAttributes(uniformGeom.GetScalesAttr(), timeVarGeom.GetScalesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::SCALES);
UsdAttribute scalesAttribute = outGeom.GetScalesAttr();
assert(scalesAttribute);
if (geomData.Scales)
{
const void* arrayData = geomData.Scales;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = scalesAttribute;
bool setPrimvar = true;
switch (geomData.ScalesType)
{
case UsdBridgeType::FLOAT: {ASSIGN_PRIMVAR_MACRO_1EXPAND3(VtVec3fArray, float); break;}
case UsdBridgeType::DOUBLE: {ASSIGN_PRIMVAR_MACRO_1EXPAND3(VtVec3fArray, double); break;}
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom ScalesAttribute should be FLOAT(3) or DOUBLE(3)."); break; }
}
}
else
{
if(!usdbridgenumerics::isIdentity(geomData.Scale))
{
GfVec3f defaultScale(geomData.Scale.Data);
VtVec3fArray& usdScales = GetStaticTempArray<VtVec3fArray>();
usdScales.resize(geomData.NumPoints);
for(auto& x : usdScales) x = defaultScale;
scalesAttribute.Set(usdScales, timeCode);
}
else
{
scalesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomOrientNormals(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ORIENTATIONS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ORIENTATIONS);
ClearUsdAttributes(uniformGeom.GetNormalsAttr(), timeVarGeom.GetNormalsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ORIENTATIONS);
UsdAttribute normalsAttribute = outGeom.GetNormalsAttr();
assert(normalsAttribute);
if (geomData.Orientations)
{
const void* arrayData = geomData.Orientations;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = normalsAttribute;
bool setPrimvar = true;
switch (geomData.OrientationsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom NormalsAttribute (orientations) should be FLOAT3 or DOUBLE3."); break; }
}
}
else
{
//GfVec3f defaultNormal(1, 0, 0);
//VtVec3fArray& usdNormals = GetStaticTempArray<VtVec3fArray>();
//usdNormals.resize(geomData.NumPoints);
//for(auto& x : usdNormals) x = defaultNormal;
//normalsAttribute.Set(usdNormals, timeCode);
normalsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomOrientations(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ORIENTATIONS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ORIENTATIONS);
ClearUsdAttributes(uniformGeom.GetOrientationsAttr(), timeVarGeom.GetOrientationsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ORIENTATIONS);
// Orientations
UsdAttribute orientationsAttribute = outGeom.GetOrientationsAttr();
assert(orientationsAttribute);
VtQuathArray& usdOrients = GetStaticTempArray<VtQuathArray>();
if (geomData.Orientations)
{
usdOrients.resize(geomData.NumPoints);
switch (geomData.OrientationsType)
{
case UsdBridgeType::FLOAT3: { ConvertNormalsToQuaternions<float>(usdOrients, geomData.Orientations, geomData.NumPoints); break; }
case UsdBridgeType::DOUBLE3: { ConvertNormalsToQuaternions<double>(usdOrients, geomData.Orientations, geomData.NumPoints); break; }
case UsdBridgeType::FLOAT4:
{
for (uint64_t i = 0; i < geomData.NumPoints; ++i)
{
const float* orients = reinterpret_cast<const float*>(geomData.Orientations);
usdOrients[i] = GfQuath(orients[i * 4], orients[i * 4 + 1], orients[i * 4 + 2], orients[i * 4 + 3]);
}
orientationsAttribute.Set(usdOrients, timeCode);
break;
}
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom OrientationsAttribute should be FLOAT3, DOUBLE3 or FLOAT4."); break; }
}
orientationsAttribute.Set(usdOrients, timeCode);
}
else
{
if(!usdbridgenumerics::isIdentity(geomData.Orientation))
{
GfQuath defaultOrient(geomData.Orientation.Data[0], geomData.Orientation.Data[1], geomData.Orientation.Data[2], geomData.Orientation.Data[3]);
usdOrients.resize(geomData.NumPoints);
for(auto& x : usdOrients) x = defaultOrient;
orientationsAttribute.Set(usdOrients, timeCode);
}
else
{
orientationsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomProtoIndices(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SHAPEINDICES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SHAPEINDICES);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::SHAPEINDICES);
UsdGeomType* outGeom = timeCode.IsDefault() ? &uniformGeom : &timeVarGeom;
UsdAttribute protoIndexAttr = outGeom->GetProtoIndicesAttr();
assert(protoIndexAttr);
//Shape indices
if(geomData.ShapeIndices)
{
const void* arrayData = geomData.ShapeIndices;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = protoIndexAttr;
bool setPrimvar = true;
switch (geomData.OrientationsType)
{
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom ProtoIndicesAttr (ShapeIndices) should be INT."); break; }
}
}
else
{
VtIntArray& protoIndices = GetStaticTempArray<VtIntArray>();
protoIndices.resize(geomData.NumPoints);
for(auto& x : protoIndices) x = 0;
protoIndexAttr.Set(protoIndices, timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomLinearVelocities(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::LINEARVELOCITIES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::LINEARVELOCITIES);
ClearUsdAttributes(uniformGeom.GetVelocitiesAttr(), timeVarGeom.GetVelocitiesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::LINEARVELOCITIES);
// Linear velocities
UsdAttribute linearVelocitiesAttribute = outGeom.GetVelocitiesAttr();
assert(linearVelocitiesAttribute);
if (geomData.LinearVelocities)
{
GfVec3f* linVels = (GfVec3f*)geomData.LinearVelocities;
VtVec3fArray& usdVelocities = GetStaticTempArray<VtVec3fArray>();
usdVelocities.assign(linVels, linVels + geomData.NumPoints);
linearVelocitiesAttribute.Set(usdVelocities, timeCode);
}
else
{
linearVelocitiesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomAngularVelocities(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ANGULARVELOCITIES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ANGULARVELOCITIES);
ClearUsdAttributes(uniformGeom.GetAngularVelocitiesAttr(), timeVarGeom.GetAngularVelocitiesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ANGULARVELOCITIES);
// Angular velocities
UsdAttribute angularVelocitiesAttribute = outGeom.GetAngularVelocitiesAttr();
assert(angularVelocitiesAttribute);
if (geomData.AngularVelocities)
{
GfVec3f* angVels = (GfVec3f*)geomData.AngularVelocities;
VtVec3fArray& usdAngularVelocities = GetStaticTempArray<VtVec3fArray>();
usdAngularVelocities.assign(angVels, angVels + geomData.NumPoints);
angularVelocitiesAttribute.Set(usdAngularVelocities, timeCode);
}
else
{
angularVelocitiesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomInvisibleIds(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INVISIBLEIDS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INVISIBLEIDS);
ClearUsdAttributes(uniformGeom.GetInvisibleIdsAttr(), timeVarGeom.GetInvisibleIdsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INVISIBLEIDS);
// Invisible ids
UsdAttribute invisIdsAttr = outGeom.GetInvisibleIdsAttr();
assert(invisIdsAttr);
uint64_t numInvisibleIds = geomData.NumInvisibleIds;
if (numInvisibleIds)
{
const void* arrayData = geomData.InvisibleIds;
size_t arrayNumElements = numInvisibleIds;
UsdAttribute arrayPrimvar = invisIdsAttr;
bool setPrimvar = true;
switch (geomData.InvisibleIdsType)
{
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, unsigned int); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, int); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom GetInvisibleIdsAttr should be (U)LONG or (U)INT."); break; }
}
}
else
{
invisIdsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
static void UpdateUsdGeomCurveLengths(const UsdBridgeLogObject& logObj, UsdGeomBasisCurves& timeVarGeom, UsdGeomBasisCurves& uniformGeom, const UsdBridgeCurveData& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const UsdBridgeCurveData>& updateEval, TimeEvaluator<UsdBridgeCurveData>& timeEval)
{
using DMI = typename UsdBridgeCurveData::DataMemberId;
// Fill geom prim and geometry layer with data.
bool performsUpdate = updateEval.PerformsUpdate(DMI::CURVELENGTHS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::CURVELENGTHS);
ClearUsdAttributes(uniformGeom.GetCurveVertexCountsAttr(), timeVarGeom.GetCurveVertexCountsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomBasisCurves& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::POINTS);
UsdAttribute vertCountAttr = outGeom.GetCurveVertexCountsAttr();
assert(vertCountAttr);
const void* arrayData = geomData.CurveLengths;
size_t arrayNumElements = geomData.NumCurveLengths;
UsdAttribute arrayPrimvar = vertCountAttr;
bool setPrimvar = true;
{ ASSIGN_PRIMVAR_MACRO(VtIntArray); }
}
}
void UpdateUsdGeomPrototypes(const UsdBridgeLogObject& logObj, const UsdStagePtr& sceneStage, UsdGeomPointInstancer& uniformGeom,
const UsdBridgeInstancerRefData& geomRefData, const SdfPrimPathList& protoGeomPaths,
const char* protoShapePathRp)
{
using DMI = typename UsdBridgeInstancerData::DataMemberId;
SdfPath protoBasePath = uniformGeom.GetPath().AppendPath(SdfPath(protoShapePathRp));
sceneStage->RemovePrim(protoBasePath);
UsdRelationship protoRel = uniformGeom.GetPrototypesRel();
for(int shapeIdx = 0; shapeIdx < geomRefData.NumShapes; ++shapeIdx)
{
SdfPath shapePath;
if(geomRefData.Shapes[shapeIdx] != UsdBridgeInstancerRefData::SHAPE_MESH)
{
std::string protoName = constring::protoShapePf + std::to_string(shapeIdx);
shapePath = protoBasePath.AppendPath(SdfPath(protoName.c_str()));
}
else
{
int protoGeomIdx = static_cast<int>(geomRefData.Shapes[shapeIdx]); // The mesh shape value is an index into protoGeomPaths
assert(protoGeomIdx < protoGeomPaths.size());
shapePath = protoGeomPaths[protoGeomIdx];
}
UsdGeomXformable geomXformable;
switch (geomRefData.Shapes[shapeIdx])
{
case UsdBridgeInstancerRefData::SHAPE_SPHERE:
{
geomXformable = UsdGeomSphere::Define(sceneStage, shapePath);
break;
}
case UsdBridgeInstancerRefData::SHAPE_CYLINDER:
{
geomXformable = UsdGeomCylinder::Define(sceneStage, shapePath);
break;
}
case UsdBridgeInstancerRefData::SHAPE_CONE:
{
geomXformable = UsdGeomCone::Define(sceneStage, shapePath);
break;
}
default:
{
geomXformable = UsdGeomXformable::Get(sceneStage, shapePath);
break;
}
}
// Add a transform
geomXformable.ClearXformOpOrder();
if(!usdbridgenumerics::isIdentity(geomRefData.ShapeTransform))
{
const float* transform = geomRefData.ShapeTransform.Data;
GfMatrix4d transMat;
transMat.SetRow(0, GfVec4d(GfVec4f(&transform[0])));
transMat.SetRow(1, GfVec4d(GfVec4f(&transform[4])));
transMat.SetRow(2, GfVec4d(GfVec4f(&transform[8])));
transMat.SetRow(3, GfVec4d(GfVec4f(&transform[12])));
geomXformable.AddTransformOp().Set(transMat);
}
protoRel.AddTarget(shapePath);
}
}
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, meshData, uniformPrim, Settings);
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, instancerData, uniformPrim, Settings);
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, curveData, uniformPrim, Settings);
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMeshData& meshData)
{
TimeEvaluator<UsdBridgeMeshData> timeEval(meshData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, meshData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeInstancerData& instancerData)
{
TimeEvaluator<UsdBridgeInstancerData> timeEval(instancerData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, instancerData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeCurveData& curveData)
{
TimeEvaluator<UsdBridgeCurveData> timeEval(curveData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, curveData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
#define UPDATE_USDGEOM_ARRAYS(FuncDef) \
FuncDef(this->LogObject, timeVarGeom, uniformGeom, geomData, numPrims, updateEval, timeEval)
#define UPDATE_USDGEOM_PRIMVAR_ARRAYS(FuncDef) \
FuncDef(this, timeVarPrimvars, uniformPrimvars, geomData, numPrims, updateEval, timeEval)
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& meshPath, const UsdBridgeMeshData& geomData, double timeStep)
{
// To avoid data duplication when using of clip stages, we need to potentially use the scenestage prim for time-uniform data.
UsdGeomMesh uniformGeom = UsdGeomMesh::Get(this->SceneStage, meshPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomMesh timeVarGeom = UsdGeomMesh::Get(timeVarStage, meshPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
// Update the mesh
UsdBridgeUpdateEvaluator<const UsdBridgeMeshData> updateEval(geomData);
TimeEvaluator<UsdBridgeMeshData> timeEval(geomData, timeStep);
assert((geomData.NumIndices % geomData.FaceVertexCount) == 0);
uint64_t numPrims = int(geomData.NumIndices) / geomData.FaceVertexCount;
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomIndices);
}
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& instancerPath, const UsdBridgeInstancerData& geomData, double timeStep)
{
UsdBridgeUpdateEvaluator<const UsdBridgeInstancerData> updateEval(geomData);
TimeEvaluator<UsdBridgeInstancerData> timeEval(geomData, timeStep);
bool useGeomPoints = geomData.UseUsdGeomPoints;
uint64_t numPrims = geomData.NumPoints;
if (useGeomPoints)
{
UsdGeomPoints uniformGeom = UsdGeomPoints::Get(this->SceneStage, instancerPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomPoints timeVarGeom = UsdGeomPoints::Get(timeVarStage, instancerPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInstanceIds);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomWidths);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomOrientNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
}
else
{
UsdGeomPointInstancer uniformGeom = UsdGeomPointInstancer::Get(this->SceneStage, instancerPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomPointInstancer timeVarGeom = UsdGeomPointInstancer::Get(timeVarStage, instancerPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInstanceIds);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomScales);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomOrientations);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomProtoIndices);
//UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomLinearVelocities);
//UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomAngularVelocities);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInvisibleIds);
}
}
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& curvePath, const UsdBridgeCurveData& geomData, double timeStep)
{
// To avoid data duplication when using of clip stages, we need to potentially use the scenestage prim for time-uniform data.
UsdGeomBasisCurves uniformGeom = UsdGeomBasisCurves::Get(this->SceneStage, curvePath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomBasisCurves timeVarGeom = UsdGeomBasisCurves::Get(timeVarStage, curvePath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
// Update the curve
UsdBridgeUpdateEvaluator<const UsdBridgeCurveData> updateEval(geomData);
TimeEvaluator<UsdBridgeCurveData> timeEval(geomData, timeStep);
uint64_t numPrims = geomData.NumCurveLengths;
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomWidths);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomCurveLengths);
}
void UsdBridgeUsdWriter::UpdateUsdInstancerPrototypes(const SdfPath& instancerPath, const UsdBridgeInstancerRefData& geomRefData,
const SdfPrimPathList& refProtoGeomPrimPaths, const char* protoShapePathRp)
{
UsdGeomPointInstancer uniformGeom = UsdGeomPointInstancer::Get(this->SceneStage, instancerPath);
if(!uniformGeom)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Attempt to perform update of prototypes on a prim that is not a UsdGeomPointInstancer.");
return;
}
// Very basic rel update, without any timevarying aspects
UpdateUsdGeomPrototypes(this->LogObject, this->SceneStage, uniformGeom, geomRefData, refProtoGeomPrimPaths, protoShapePathRp);
} | 54,355 | C++ | 42.835484 | 246 | 0.739582 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridge.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridge.h"
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeCaches.h"
#include "UsdBridgeDiagnosticMgrDelegate.h"
#include <string>
#include <memory>
#define BRIDGE_CACHE Internals->Cache
#define BRIDGE_USDWRITER Internals->UsdWriter
namespace
{
// Parent paths for class definitions (Class path)
const char* const worldPathCp = "worlds";
const char* const instancePathCp = "instances";
const char* const groupPathCp = "groups";
const char* const surfacePathCp = "surfaces";
const char* const volumePathCp = "volumes";
const char* const geometryPathCp = "geometries";
const char* const fieldPathCp = "spatialfields";
const char* const materialPathCp = "materials";
const char* const samplerPathCp = "samplers";
const char* const cameraPathCp = "cameras";
// Parent path extensions for references in parent classes (Reference path)
const char* const instancePathRp = "instances";
const char* const surfacePathRp = "surfaces";
const char* const volumePathRp = "volumes";
const char* const geometryPathRp = "geometry"; // created in surface parent class
const char* const fieldPathRp = "spatialfield"; // created in volume parent class
const char* const materialPathRp = "material"; // created in surface parent class
const char* const samplerPathRp = "samplers"; // created in material parent class (separation from other UsdShader prims in material)
const char* const protoShapePathRp = "protoshapes"; // created in geometry parent class
const char* const protoGeometryPathRp = "protogeometries"; // created in geometry parent class
// Postfixes for prim stage names, also used for manifests
const char* const geomPrimStagePf = "_Geom";
const char* const fieldPrimStagePf = "_Field";
const char* const materialPrimStagePf = "_Material";
const char* const samplerPrimStagePf = "_Sampler";
const char* const cameraPrimStagePf = "_Camera";
// Postfixes for clip stage names
const char* const geomClipPf = "_Geom_";
bool PrimIsNew(const BoolEntryPair& createResult)
{
return !createResult.first.first && !createResult.first.second;
}
}
typedef UsdBridgePrimCacheManager::PrimCacheIterator PrimCacheIterator;
typedef UsdBridgePrimCacheManager::ConstPrimCacheIterator ConstPrimCacheIterator;
struct UsdBridgeInternals
{
UsdBridgeInternals(const UsdBridgeSettings& settings)
: UsdWriter(settings)
{
RefModCallbacks.AtNewRef = [this](UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache){
// Increase the reference count for the child on creation of referencing prim
this->Cache.AddChild(parentCache, childCache);
};
RefModCallbacks.AtRemoveRef = [this](UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache) {
this->Cache.RemoveChild(parentCache, childCache);
};
}
~UsdBridgeInternals()
{
if(DiagRemoveFunc)
DiagRemoveFunc(DiagnosticDelegate.get());
}
BoolEntryPair FindOrCreatePrim(const char* category, const char* name, ResourceCollectFunc collectFunc = nullptr);
void FindAndDeletePrim(const UsdBridgeHandle& handle);
template<class T>
const UsdBridgePrimCacheList& ExtractPrimCaches(const T* handles, uint64_t numHandles);
const UsdBridgePrimCacheList& ToCacheList(UsdBridgePrimCache* primCache);
UsdGeomPrimvarsAPI GetBoundGeomPrimvars(const UsdBridgeHandle& material) const;
// Cache
UsdBridgePrimCacheManager Cache;
// USDWriter
UsdBridgeUsdWriter UsdWriter;
// Material->geometry binding suggestion
std::map<UsdBridgePrimCache*, SdfPath> MaterialToGeometryBinding;
// Callbacks
UsdBridgeUsdWriter::RefModFuncs RefModCallbacks;
// Diagnostic Manager
std::unique_ptr<UsdBridgeDiagnosticMgrDelegate> DiagnosticDelegate;
std::function<void (UsdBridgeDiagnosticMgrDelegate*)> DiagRemoveFunc;
// Temp arrays
UsdBridgePrimCacheList TempPrimCaches;
SdfPrimPathList TempPrimPaths;
SdfPrimPathList ProtoPrimPaths;
};
BoolEntryPair UsdBridgeInternals::FindOrCreatePrim(const char* category, const char* name, ResourceCollectFunc collectFunc)
{
assert(TfIsValidIdentifier(name));
UsdBridgePrimCache* primCache = nullptr;
// Find existing entry
ConstPrimCacheIterator it = Cache.FindPrimCache(name);
bool cacheExists = Cache.ValidIterator(it);
bool stageExists = true;
if (cacheExists)
{
// Get the existing entry
primCache = it->second.get();
}
else
{
primCache = Cache.CreatePrimCache(name, UsdWriter.CreatePrimName(name, category), collectFunc)->second.get();
stageExists = !UsdWriter.CreatePrim(primCache->PrimPath);
}
return BoolEntryPair(std::pair<bool,bool>(stageExists, cacheExists), primCache);
}
void UsdBridgeInternals::FindAndDeletePrim(const UsdBridgeHandle& handle)
{
ConstPrimCacheIterator it = Cache.FindPrimCache(handle);
assert(Cache.ValidIterator(it));
UsdBridgePrimCache* cacheEntry = (*it).second.get();
UsdWriter.DeletePrim(cacheEntry);
Cache.RemovePrimCache(it, UsdWriter.LogObject);
}
template<class T>
const UsdBridgePrimCacheList& UsdBridgeInternals::ExtractPrimCaches(const T* handles, uint64_t numHandles)
{
TempPrimCaches.resize(numHandles);
for (uint64_t i = 0; i < numHandles; ++i)
{
TempPrimCaches[i] = this->Cache.ConvertToPrimCache(handles[i]);
}
return TempPrimCaches;
}
const UsdBridgePrimCacheList& UsdBridgeInternals::ToCacheList(UsdBridgePrimCache* primCache)
{
TempPrimCaches.resize(1);
TempPrimCaches[0] = primCache;
return TempPrimCaches;
}
UsdGeomPrimvarsAPI UsdBridgeInternals::GetBoundGeomPrimvars(const UsdBridgeHandle& material) const
{
auto it = MaterialToGeometryBinding.find(material.value);
if(it != MaterialToGeometryBinding.end())
{
const SdfPath& boundGeomPrimPath = it->second;
UsdPrim boundGeomPrim = UsdWriter.GetSceneStage()->GetPrimAtPath(boundGeomPrimPath);
return UsdGeomPrimvarsAPI(boundGeomPrim);
}
return UsdGeomPrimvarsAPI();
}
template<typename HandleType>
bool HasNullHandles(const HandleType* handles, uint64_t numHandles)
{
for(uint64_t i = 0; i < numHandles; ++i)
if(handles[i].value == nullptr)
return true;
return false;
}
UsdBridge::UsdBridge(const UsdBridgeSettings& settings)
: Internals(new UsdBridgeInternals(settings))
, SessionValid(false)
{
SetEnableSaving(true);
}
void UsdBridge::SetExternalSceneStage(SceneStagePtr sceneStage)
{
BRIDGE_USDWRITER.SetExternalSceneStage(UsdStageRefPtr((UsdStage*)sceneStage));
}
void UsdBridge::SetEnableSaving(bool enableSaving)
{
this->EnableSaving = enableSaving;
BRIDGE_USDWRITER.SetEnableSaving(enableSaving);
}
bool UsdBridge::OpenSession(UsdBridgeLogCallback logCallback, void* logUserData)
{
BRIDGE_USDWRITER.LogObject = {logUserData, logCallback};
Internals->DiagnosticDelegate = std::make_unique<UsdBridgeDiagnosticMgrDelegate>(logUserData, logCallback);
Internals->DiagRemoveFunc = [](UsdBridgeDiagnosticMgrDelegate* delegate)
{ TfDiagnosticMgr::GetInstance().RemoveDelegate(delegate); };
TfDiagnosticMgr::GetInstance().AddDelegate(Internals->DiagnosticDelegate.get());
SessionValid = BRIDGE_USDWRITER.InitializeSession();
SessionValid = SessionValid && BRIDGE_USDWRITER.OpenSceneStage();
return SessionValid;
}
void UsdBridge::CloseSession()
{
BRIDGE_USDWRITER.ResetSession();
}
UsdBridge::~UsdBridge()
{
delete Internals;
}
bool UsdBridge::CreateWorld(const char* name, UsdWorldHandle& handle)
{
if (!SessionValid) return false;
// Find or create a cache entry belonging to a prim located under worldPathCp in the usd.
BoolEntryPair createResult = Internals->FindOrCreatePrim(worldPathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
this->CreateRootPrimAndAttach(cacheEntry, worldPathCp);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateInstance(const char* name, UsdInstanceHandle& handle)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(instancePathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
BRIDGE_USDWRITER.InitializeUsdTransform(cacheEntry);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateGroup(const char* name, UsdGroupHandle& handle)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(groupPathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
BRIDGE_USDWRITER.InitializeUsdTransform(cacheEntry);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateSurface(const char* name, UsdSurfaceHandle& handle)
{
if (!SessionValid) return false;
// Although surface doesn't support transform operations, a transform prim supports timevarying visibility.
BoolEntryPair createResult = Internals->FindOrCreatePrim(surfacePathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
BRIDGE_USDWRITER.InitializeUsdTransform(cacheEntry);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateVolume(const char * name, UsdVolumeHandle& handle)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(volumePathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
BRIDGE_USDWRITER.InitializeUsdTransform(cacheEntry);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
template<typename GeomDataType>
bool UsdBridge::CreateGeometryTemplate(const char* name, UsdGeometryHandle& handle, const GeomDataType& geomData)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(geometryPathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
#ifdef VALUE_CLIP_RETIMING
BRIDGE_USDWRITER.CreateManifestStage(name, geomPrimStagePf, cacheEntry);
#ifndef TIME_CLIP_STAGES
// Default primstage created for clip assetpaths of parents. If this path is not active, individual clip stages are created lazily during data update.
UsdStageRefPtr geomPrimStage = BRIDGE_USDWRITER.FindOrCreatePrimStage(cacheEntry, geomPrimStagePf).second;
BRIDGE_USDWRITER.InitializeUsdGeometry(geomPrimStage, cacheEntry->PrimPath, geomData, false);
#endif
#endif
UsdPrim geomPrim = BRIDGE_USDWRITER.InitializeUsdGeometry(BRIDGE_USDWRITER.GetSceneStage(), cacheEntry->PrimPath, geomData, true);
geomPrim.ApplyAPI<UsdShadeMaterialBindingAPI>();
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeMeshData& meshData)
{
return CreateGeometryTemplate<UsdBridgeMeshData>(name, handle, meshData);
}
bool UsdBridge::CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeInstancerData& instancerData)
{
return CreateGeometryTemplate<UsdBridgeInstancerData>(name, handle, instancerData);
}
bool UsdBridge::CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeCurveData& curveData)
{
return CreateGeometryTemplate<UsdBridgeCurveData>(name, handle, curveData);
}
bool UsdBridge::CreateSpatialField(const char * name, UsdSpatialFieldHandle& handle)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(fieldPathCp, name, &ResourceCollectVolume);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
#ifdef VALUE_CLIP_RETIMING
// Create manifest and primstage
BRIDGE_USDWRITER.CreateManifestStage(name, fieldPrimStagePf, cacheEntry);
UsdStageRefPtr volPrimStage = BRIDGE_USDWRITER.FindOrCreatePrimStage(cacheEntry, fieldPrimStagePf).second;
BRIDGE_USDWRITER.InitializeUsdVolume(volPrimStage, cacheEntry->PrimPath, false);
#endif
UsdPrim volumePrim = BRIDGE_USDWRITER.InitializeUsdVolume(BRIDGE_USDWRITER.GetSceneStage(), cacheEntry->PrimPath, true);
volumePrim.ApplyAPI<UsdShadeMaterialBindingAPI>();
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateMaterial(const char* name, UsdMaterialHandle& handle)
{
if (!SessionValid) return false;
// Create the material
BoolEntryPair createResult = Internals->FindOrCreatePrim(materialPathCp, name);
UsdBridgePrimCache* matCacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
UsdMaterialHandle matHandle; matHandle.value = matCacheEntry;
if (!cacheExists)
{
#ifdef VALUE_CLIP_RETIMING
// Create manifest and primstage
BRIDGE_USDWRITER.CreateManifestStage(name, materialPrimStagePf, matCacheEntry);
UsdStageRefPtr matPrimStage = BRIDGE_USDWRITER.FindOrCreatePrimStage(matCacheEntry, materialPrimStagePf).second;
BRIDGE_USDWRITER.InitializeUsdMaterial(matPrimStage, matCacheEntry->PrimPath, false);
#endif
UsdShadeMaterial matPrim = BRIDGE_USDWRITER.InitializeUsdMaterial(BRIDGE_USDWRITER.GetSceneStage(), matCacheEntry->PrimPath, true);
}
handle = matHandle;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateSampler(const char* name, UsdSamplerHandle& handle, UsdBridgeSamplerData::SamplerType type)
{
if (!SessionValid) return false;
BoolEntryPair createResult = Internals->FindOrCreatePrim(samplerPathCp, name, &ResourceCollectSampler);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
if (!cacheExists)
{
#ifdef VALUE_CLIP_RETIMING
// Create manifest and primstage
BRIDGE_USDWRITER.CreateManifestStage(name, samplerPrimStagePf, cacheEntry);
UsdStageRefPtr samplerPrimStage = BRIDGE_USDWRITER.FindOrCreatePrimStage(cacheEntry, samplerPrimStagePf).second;
BRIDGE_USDWRITER.InitializeUsdSampler(samplerPrimStage, cacheEntry->PrimPath, type, false);
#endif
BRIDGE_USDWRITER.InitializeUsdSampler(BRIDGE_USDWRITER.GetSceneStage(), cacheEntry->PrimPath, type, true);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
bool UsdBridge::CreateCamera(const char* name, UsdCameraHandle& handle)
{
if (!SessionValid) return false;
// Find or create a cache entry belonging to a prim located under worldPathCp in the usd.
BoolEntryPair createResult = Internals->FindOrCreatePrim(cameraPathCp, name);
UsdBridgePrimCache* cacheEntry = createResult.second;
bool cacheExists = createResult.first.second;
// The camera has no manifest, instead the primstage+path is directly referenced by the root camera
// instance prim.
if (!cacheExists)
{
const char* layerId = nullptr;
#ifdef VALUE_CLIP_RETIMING
const UsdStagePair& stagePair = BRIDGE_USDWRITER.FindOrCreatePrimStage(cacheEntry, cameraPrimStagePf);
layerId = stagePair.first.c_str();
UsdStageRefPtr camStage = stagePair.second;
#else
UsdStageRefPtr camStage = BRIDGE_USDWRITER.GetSceneStage();
#endif
BRIDGE_USDWRITER.InitializeUsdCamera(camStage, cacheEntry->PrimPath);
this->CreateRootPrimAndAttach(cacheEntry, cameraPathCp, layerId);
}
handle.value = cacheEntry;
return PrimIsNew(createResult);
}
void UsdBridge::DeleteWorld(UsdWorldHandle handle)
{
if (handle.value == nullptr) return;
UsdBridgePrimCache* worldCache = BRIDGE_CACHE.ConvertToPrimCache(handle);
this->RemoveRootPrimAndDetach(worldCache, worldPathCp);
// Remove the abstract class
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteInstance(UsdInstanceHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteGroup(UsdGroupHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteSurface(UsdSurfaceHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteVolume(UsdVolumeHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteGeometry(UsdGeometryHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteSpatialField(UsdSpatialFieldHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteMaterial(UsdMaterialHandle handle)
{
if (handle.value == nullptr) return;
Internals->MaterialToGeometryBinding.erase(handle.value);
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteSampler(UsdSamplerHandle handle)
{
if (handle.value == nullptr) return;
Internals->FindAndDeletePrim(handle);
}
void UsdBridge::DeleteCamera(UsdCameraHandle handle)
{
if (handle.value == nullptr) return;
UsdBridgePrimCache* cameraCache = BRIDGE_CACHE.ConvertToPrimCache(handle);
this->RemoveRootPrimAndDetach(cameraCache, cameraPathCp);
// Remove the abstract class
Internals->FindAndDeletePrim(handle);
}
template<typename ParentHandleType, typename ChildHandleType>
void UsdBridge::SetNoClipRefs(ParentHandleType parentHandle, const ChildHandleType* childHandles, uint64_t numChildren,
const char* refPathExt, bool timeVarying, double timeStep, bool instanceable)
{
if (parentHandle.value == nullptr) return;
if(HasNullHandles(childHandles, numChildren)) return;
UsdBridgePrimCache* parentCache = BRIDGE_CACHE.ConvertToPrimCache(parentHandle);
const UsdBridgePrimCacheList& childCaches = Internals->ExtractPrimCaches<ChildHandleType>(childHandles, numChildren);
BRIDGE_USDWRITER.ManageUnusedRefs(parentCache, childCaches, refPathExt, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
for (uint64_t i = 0; i < numChildren; ++i)
{
BRIDGE_USDWRITER.AddRef_NoClip(parentCache, childCaches[i], refPathExt, timeVarying, timeStep, instanceable, Internals->RefModCallbacks);
}
}
void UsdBridge::SetInstanceRefs(UsdWorldHandle world, const UsdInstanceHandle* instances, uint64_t numInstances, bool timeVarying, double timeStep)
{
SetNoClipRefs(world, instances, numInstances, instancePathRp, timeVarying, timeStep);
}
void UsdBridge::SetGroupRef(UsdInstanceHandle instance, UsdGroupHandle group, bool timeVarying, double timeStep)
{
if (instance.value == nullptr) return;
if (group.value == nullptr) return;
UsdBridgePrimCache* instanceCache = BRIDGE_CACHE.ConvertToPrimCache(instance);
UsdBridgePrimCache* groupCache = BRIDGE_CACHE.ConvertToPrimCache(group);
constexpr bool instanceable = false;
BRIDGE_USDWRITER.ManageUnusedRefs(instanceCache, Internals->ToCacheList(groupCache), nullptr, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
BRIDGE_USDWRITER.AddRef_NoClip(instanceCache, groupCache, nullptr, timeVarying, timeStep, instanceable, Internals->RefModCallbacks);
}
void UsdBridge::SetSurfaceRefs(UsdWorldHandle world, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep)
{
constexpr bool instanceable = true;
SetNoClipRefs(world, surfaces, numSurfaces, surfacePathRp, timeVarying, timeStep, instanceable);
}
void UsdBridge::SetSurfaceRefs(UsdGroupHandle group, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep)
{
constexpr bool instanceable = true;
SetNoClipRefs(group, surfaces, numSurfaces, surfacePathRp, timeVarying, timeStep, instanceable);
}
void UsdBridge::SetVolumeRefs(UsdWorldHandle world, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep)
{
SetNoClipRefs(world, volumes, numVolumes, volumePathRp, timeVarying, timeStep);
}
void UsdBridge::SetVolumeRefs(UsdGroupHandle group, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep)
{
SetNoClipRefs(group, volumes, numVolumes, volumePathRp, timeVarying, timeStep);
}
void UsdBridge::SetGeometryRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, double timeStep, double geomTimeStep)
{
if (surface.value == nullptr) return;
if (geometry.value == nullptr) return;
UsdBridgePrimCache* surfaceCache = BRIDGE_CACHE.ConvertToPrimCache(surface);
UsdBridgePrimCache* geometryCache = BRIDGE_CACHE.ConvertToPrimCache(geometry);
constexpr bool timeVarying = false; // On a surface, the path to the geometry cannot change over time (ie. is uniformly set), since material is not timevarying either (due to the material binding path rel from the geometry) and the geometry contents itself are already timevarying.
constexpr bool valueClip = true;
constexpr bool clipStages = true;
constexpr bool instanceable = false; // Can only make Xform prims instanceable
BRIDGE_USDWRITER.ManageUnusedRefs(surfaceCache, Internals->ToCacheList(geometryCache), geometryPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
BRIDGE_USDWRITER.ManageUnusedRefs(surfaceCache, UsdBridgePrimCacheList(), materialPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
SdfPath refGeomPath = BRIDGE_USDWRITER.AddRef(surfaceCache, geometryCache, geometryPathRp, timeVarying, valueClip, clipStages, geomClipPf, timeStep, geomTimeStep, instanceable, Internals->RefModCallbacks);
BRIDGE_USDWRITER.UnbindMaterialFromGeom(refGeomPath);
}
void UsdBridge::SetGeometryMaterialRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, UsdMaterialHandle material, double timeStep, double geomTimeStep, double matTimeStep)
{
if (surface.value == nullptr) return;
if (geometry.value == nullptr || material.value == nullptr) return;
UsdBridgePrimCache* surfaceCache = BRIDGE_CACHE.ConvertToPrimCache(surface);
UsdBridgePrimCache* geometryCache = BRIDGE_CACHE.ConvertToPrimCache(geometry);
UsdBridgePrimCache* materialCache = BRIDGE_CACHE.ConvertToPrimCache(material);
constexpr bool timeVarying = false;
constexpr bool valueClip = true;
constexpr bool instanceable = false; // Can only make Xform prims instanceable
// Remove any dangling references
BRIDGE_USDWRITER.ManageUnusedRefs(surfaceCache, Internals->ToCacheList(geometryCache), geometryPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
BRIDGE_USDWRITER.ManageUnusedRefs(surfaceCache, Internals->ToCacheList(materialCache), materialPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
// Update the references
SdfPath refGeomPath = BRIDGE_USDWRITER.AddRef(surfaceCache, geometryCache, geometryPathRp, timeVarying, valueClip, true, geomClipPf, timeStep, geomTimeStep, instanceable, Internals->RefModCallbacks); // Can technically be timeVarying, but would be a bit confusing. Instead, timevary the surface.
SdfPath refMatPath = BRIDGE_USDWRITER.AddRef(surfaceCache, materialCache, materialPathRp, timeVarying, valueClip, false, nullptr, timeStep, matTimeStep, instanceable, Internals->RefModCallbacks);
// For updating material attribute reader output types, update the suggested material->geompath mapping.
// Since multiple geometries can be bound to a material, only one is taken, so it is up to the user to ensure correct attribute connection types.
SdfPath& geomPrimPath = geometryCache->PrimPath;
Internals->MaterialToGeometryBinding[material.value] = geomPrimPath;
// Bind the referencing material to the referencing geom prim (as they are within same scope in this usd prim)
BRIDGE_USDWRITER.BindMaterialToGeom(refGeomPath, refMatPath);
}
void UsdBridge::SetSpatialFieldRef(UsdVolumeHandle volume, UsdSpatialFieldHandle field, double timeStep, double fieldTimeStep)
{
if (volume.value == nullptr) return;
if (field.value == nullptr) return;
UsdBridgePrimCache* volumeCache = BRIDGE_CACHE.ConvertToPrimCache(volume);
UsdBridgePrimCache* fieldCache = BRIDGE_CACHE.ConvertToPrimCache(field);
constexpr bool timeVarying = false;
constexpr bool valueClip = true;
constexpr bool clipStages = false;
constexpr bool instanceable = false;
BRIDGE_USDWRITER.ManageUnusedRefs(volumeCache, Internals->ToCacheList(fieldCache), fieldPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
SdfPath refVolPath = BRIDGE_USDWRITER.AddRef(volumeCache, fieldCache, fieldPathRp, timeVarying, valueClip, clipStages, nullptr, timeStep, fieldTimeStep, instanceable, Internals->RefModCallbacks); // Can technically be timeVarying, but would be a bit confusing. Instead, timevary the volume.
}
void UsdBridge::SetSamplerRefs(UsdMaterialHandle material, const UsdSamplerHandle* samplers, size_t numSamplers, double timeStep, const UsdSamplerRefData* samplerRefData)
{
if (material.value == nullptr) return;
if(HasNullHandles(samplers, numSamplers)) return;
UsdBridgePrimCache* matCache = BRIDGE_CACHE.ConvertToPrimCache(material);
const UsdBridgePrimCacheList& samplerCaches = Internals->ExtractPrimCaches<UsdSamplerHandle>(samplers, numSamplers);
// Sampler references cannot be time-varying (ie. path to sampler cannot change over time - connectToSource doesn't allow for that), and are set on the scenestage prim (so they inherit the type of the sampler prim)
// However, they do allow value clip retiming.
constexpr bool timeVarying = false;
constexpr bool valueClip = true;
constexpr bool clipStages = false;
constexpr bool instanceable = false;
BRIDGE_USDWRITER.ManageUnusedRefs(matCache, samplerCaches, samplerPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
// Bind sampler and material
SdfPath& matPrimPath = matCache->PrimPath;// .AppendPath(SdfPath(materialAttribPf));
UsdStageRefPtr materialStage = BRIDGE_USDWRITER.GetTimeVarStage(matCache);
Internals->TempPrimPaths.resize(numSamplers);
for (uint64_t i = 0; i < numSamplers; ++i)
{
Internals->TempPrimPaths[i] = BRIDGE_USDWRITER.AddRef(matCache, samplerCaches[i], samplerPathRp, timeVarying, valueClip, clipStages, nullptr, timeStep, samplerRefData[i].TimeStep, instanceable, Internals->RefModCallbacks);
}
BRIDGE_USDWRITER.ConnectSamplersToMaterial(materialStage, matPrimPath, Internals->TempPrimPaths, samplerCaches, samplerRefData, numSamplers, timeStep); // requires world timestep, see implementation
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
materialStage->Save();
#endif
}
void UsdBridge::SetPrototypeRefs(UsdGeometryHandle geometry, const UsdGeometryHandle* protoGeometries, size_t numProtoGeometries, double timeStep, double* protoTimeSteps)
{
if (geometry.value == nullptr) return;
if(HasNullHandles(protoGeometries, numProtoGeometries)) return;
UsdBridgePrimCache* geometryCache = BRIDGE_CACHE.ConvertToPrimCache(geometry);
const UsdBridgePrimCacheList& protoGeomCaches = Internals->ExtractPrimCaches<UsdGeometryHandle>(protoGeometries, numProtoGeometries);
// Due to prototype rel paths, the path to the prototype itself cannot change. Also, the contents of the prototype itself can already timevary.
constexpr bool timeVarying = false;
constexpr bool valueClip = true;
constexpr bool clipStages = true;
constexpr bool instanceable = false;
BRIDGE_USDWRITER.ManageUnusedRefs(geometryCache, protoGeomCaches, protoGeometryPathRp, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
Internals->ProtoPrimPaths.resize(numProtoGeometries);
for(uint64_t i = 0; i < numProtoGeometries; ++i)
{
Internals->ProtoPrimPaths[i] = BRIDGE_USDWRITER.AddRef(geometryCache, protoGeomCaches[i], protoGeometryPathRp, timeVarying, valueClip, clipStages, geomClipPf, timeStep, protoTimeSteps[i], instanceable, Internals->RefModCallbacks);
}
}
template<typename ParentHandleType>
void UsdBridge::DeleteAllRefs(ParentHandleType parentHandle, const char* refPathExt, bool timeVarying, double timeStep)
{
if (parentHandle.value == nullptr) return;
UsdBridgePrimCache* parentCache = BRIDGE_CACHE.ConvertToPrimCache(parentHandle);
BRIDGE_USDWRITER.RemoveAllRefs(parentCache, refPathExt, timeVarying, timeStep, Internals->RefModCallbacks.AtRemoveRef);
}
void UsdBridge::DeleteInstanceRefs(UsdWorldHandle world, bool timeVarying, double timeStep)
{
DeleteAllRefs(world, instancePathRp, timeVarying, timeStep);
}
void UsdBridge::DeleteGroupRef(UsdInstanceHandle instance, bool timeVarying, double timeStep)
{
DeleteAllRefs(instance, nullptr, timeVarying, timeStep);
}
void UsdBridge::DeleteSurfaceRefs(UsdWorldHandle world, bool timeVarying, double timeStep)
{
DeleteAllRefs(world, surfacePathRp, timeVarying, timeStep);
}
void UsdBridge::DeleteSurfaceRefs(UsdGroupHandle group, bool timeVarying, double timeStep)
{
DeleteAllRefs(group, surfacePathRp, timeVarying, timeStep);
}
void UsdBridge::DeleteVolumeRefs(UsdWorldHandle world, bool timeVarying, double timeStep)
{
DeleteAllRefs(world, volumePathRp, timeVarying, timeStep);
}
void UsdBridge::DeleteVolumeRefs(UsdGroupHandle group, bool timeVarying, double timeStep)
{
DeleteAllRefs(group, volumePathRp, timeVarying, timeStep);
}
void UsdBridge::DeleteGeometryRef(UsdSurfaceHandle surface, double timeStep)
{
DeleteAllRefs(surface, geometryPathRp, false, timeStep);
}
void UsdBridge::DeleteSpatialFieldRef(UsdVolumeHandle volume, double timeStep)
{
DeleteAllRefs(volume, fieldPathRp, false, timeStep);
}
void UsdBridge::DeleteMaterialRef(UsdSurfaceHandle surface, double timeStep)
{
DeleteAllRefs(surface, materialPathRp, false, timeStep);
}
void UsdBridge::DeleteSamplerRefs(UsdMaterialHandle material, double timeStep)
{
DeleteAllRefs(material, samplerPathRp, false, timeStep);
}
void UsdBridge::DeletePrototypeRefs(UsdGeometryHandle geometry, double timeStep)
{
Internals->ProtoPrimPaths.resize(0);
DeleteAllRefs(geometry, protoGeometryPathRp, false, timeStep);
}
void UsdBridge::UpdateBeginEndTime(double timeStep)
{
if (!SessionValid) return;
BRIDGE_USDWRITER.UpdateBeginEndTime(timeStep);
}
void UsdBridge::SetInstanceTransform(UsdInstanceHandle instance, const float* transform, bool timeVarying, double timeStep)
{
if (instance.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(instance);
SdfPath transformPath = cache->PrimPath;// .AppendPath(SdfPath(transformAttribPf));
BRIDGE_USDWRITER.UpdateUsdTransform(transformPath, transform, timeVarying, timeStep);
}
template<typename GeomDataType>
void UsdBridge::SetGeometryDataTemplate(UsdGeometryHandle geometry, const GeomDataType& geomData, double timeStep)
{
if (geometry.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(geometry);
SdfPath& geomPath = cache->PrimPath;
#ifdef VALUE_CLIP_RETIMING
if(cache->TimeVarBitsUpdate(geomData.TimeVarying))
BRIDGE_USDWRITER.UpdateUsdGeometryManifest(cache, geomData);
#endif
UsdStageRefPtr geomStage = BRIDGE_USDWRITER.GetTimeVarStage(cache
#ifdef TIME_CLIP_STAGES
, true, geomClipPf, timeStep
, [usdWriter=&BRIDGE_USDWRITER, &geomPath, &geomData] (UsdStageRefPtr geomStage)
{ usdWriter->InitializeUsdGeometry(geomStage, geomPath, geomData, false); }
#endif
);
BRIDGE_USDWRITER.UpdateUsdGeometry(geomStage, geomPath, geomData, timeStep);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
geomStage->Save();
#endif
}
void UsdBridge::SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeMeshData& meshData, double timeStep)
{
SetGeometryDataTemplate<UsdBridgeMeshData>(geometry, meshData, timeStep);
}
void UsdBridge::SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeInstancerData& instancerData, double timeStep)
{
SetGeometryDataTemplate<UsdBridgeInstancerData>(geometry, instancerData, timeStep);
}
void UsdBridge::SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeCurveData& curveData, double timeStep)
{
SetGeometryDataTemplate<UsdBridgeCurveData>(geometry, curveData, timeStep);
}
void UsdBridge::SetSpatialFieldData(UsdSpatialFieldHandle field, const UsdBridgeVolumeData& volumeData, double timeStep)
{
if (field.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(field);
#ifdef VALUE_CLIP_RETIMING
if(cache->TimeVarBitsUpdate(volumeData.TimeVarying))
BRIDGE_USDWRITER.UpdateUsdVolumeManifest(cache, volumeData);
#endif
UsdStageRefPtr volumeStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
// To avoid data duplication when using of clip stages, we need to potentially use the scenestage prim for time-uniform data.
BRIDGE_USDWRITER.UpdateUsdVolume(volumeStage, cache, volumeData, timeStep);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
volumeStage->Save();
#endif
}
void UsdBridge::SetMaterialData(UsdMaterialHandle material, const UsdBridgeMaterialData& matData, double timeStep)
{
if (material.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(material);
SdfPath& matPrimPath = cache->PrimPath;
#ifdef VALUE_CLIP_RETIMING
if(cache->TimeVarBitsUpdate(matData.TimeVarying))
BRIDGE_USDWRITER.UpdateUsdMaterialManifest(cache, matData);
#endif
UsdStageRefPtr materialStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
UsdGeomPrimvarsAPI boundGeomPrimvars = Internals->GetBoundGeomPrimvars(material);
BRIDGE_USDWRITER.UpdateUsdMaterial(materialStage, matPrimPath, matData, boundGeomPrimvars, timeStep);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
materialStage->Save();
#endif
}
void UsdBridge::SetSamplerData(UsdSamplerHandle sampler, const UsdBridgeSamplerData& samplerData, double timeStep)
{
if (sampler.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(sampler);
#ifdef VALUE_CLIP_RETIMING
if(cache->TimeVarBitsUpdate(samplerData.TimeVarying))
BRIDGE_USDWRITER.UpdateUsdSamplerManifest(cache, samplerData);
#endif
UsdStageRefPtr samplerStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
BRIDGE_USDWRITER.UpdateUsdSampler(samplerStage, cache, samplerData, timeStep);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
samplerStage->Save();
#endif
}
void UsdBridge::SetCameraData(UsdCameraHandle camera, const UsdBridgeCameraData& cameraData, double timeStep)
{
if (camera.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(camera);
SdfPath& cameraPath = cache->PrimPath;
bool timeVarHasChanged =
#ifdef VALUE_CLIP_RETIMING
cache->TimeVarBitsUpdate(cameraData.TimeVarying);
#else
false;
#endif
UsdStageRefPtr cameraStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
BRIDGE_USDWRITER.UpdateUsdCamera(cameraStage, cameraPath, cameraData, timeStep, timeVarHasChanged);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
cameraStage->Save();
#endif
}
void UsdBridge::SetPrototypeData(UsdGeometryHandle geometry, const UsdBridgeInstancerRefData& instancerRefData)
{
if (geometry.value == nullptr) return;
UsdBridgePrimCache* geomCache = BRIDGE_CACHE.ConvertToPrimCache(geometry);
SdfPath& geomPath = geomCache->PrimPath;
BRIDGE_USDWRITER.UpdateUsdInstancerPrototypes(geomPath, instancerRefData, Internals->ProtoPrimPaths, protoShapePathRp); // The geometry reference path is already merged into ProtoPrimPaths
}
void UsdBridge::ChangeMaterialInputAttributes(UsdMaterialHandle material, const MaterialInputAttribName* inputAttribs, size_t numInputAttribs, double timeStep, MaterialDMI timeVarying)
{
if (material.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(material);
SdfPath& matPrimPath = cache->PrimPath;// .AppendPath(SdfPath(samplerAttribPf));
UsdStageRefPtr materialStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
UsdGeomPrimvarsAPI boundGeomPrimvars = Internals->GetBoundGeomPrimvars(material);
for(int i = 0; i < numInputAttribs; ++i)
BRIDGE_USDWRITER.UpdateAttributeReader(materialStage, matPrimPath, inputAttribs[i].first, inputAttribs[i].second, boundGeomPrimvars, timeStep, timeVarying);
#ifdef VALUE_CLIP_RETIMING
//if(this->EnableSaving)
// materialStage->Save(); // Attrib readers do not have timevarying info at the moment
#endif
}
void UsdBridge::ChangeInAttribute(UsdSamplerHandle sampler, const char* newName, double timeStep, SamplerDMI timeVarying)
{
if (sampler.value == nullptr) return;
UsdBridgePrimCache* cache = BRIDGE_CACHE.ConvertToPrimCache(sampler);
SdfPath& samplerPrimPath = cache->PrimPath;// .AppendPath(SdfPath(samplerAttribPf));
UsdStageRefPtr samplerStage = BRIDGE_USDWRITER.GetTimeVarStage(cache);
BRIDGE_USDWRITER.UpdateInAttribute(samplerStage, samplerPrimPath, newName, timeStep, timeVarying);
#ifdef VALUE_CLIP_RETIMING
if(this->EnableSaving)
samplerStage->Save();
#endif
}
void UsdBridge::SaveScene()
{
if (!SessionValid) return;
if(this->EnableSaving)
BRIDGE_USDWRITER.GetSceneStage()->Save();
}
void UsdBridge::ResetResourceUpdateState()
{
if (!SessionValid) return;
BRIDGE_USDWRITER.ResetSharedResourceModified();
}
void UsdBridge::GarbageCollect()
{
BRIDGE_CACHE.RemoveUnreferencedPrimCaches(
[this](UsdBridgePrimCache* cacheEntry)
{
if(cacheEntry->ResourceCollect)
cacheEntry->ResourceCollect(cacheEntry, BRIDGE_USDWRITER);
BRIDGE_USDWRITER.DeletePrim(cacheEntry);
}
);
if(this->EnableSaving)
BRIDGE_USDWRITER.GetSceneStage()->Save();
}
const char* UsdBridge::GetPrimPath(UsdBridgeHandle* handle)
{
if(handle && handle->value)
{
return handle->value->PrimPath.GetString().c_str();
}
else
return nullptr;
}
void UsdBridge::CreateRootPrimAndAttach(UsdBridgePrimCache* cacheEntry, const char* primPathCp, const char* layerId)
{
BRIDGE_USDWRITER.AddRootPrim(cacheEntry, primPathCp, layerId);
BRIDGE_CACHE.AttachTopLevelPrim(cacheEntry);
}
void UsdBridge::RemoveRootPrimAndDetach(UsdBridgePrimCache* cacheEntry, const char* primPathCp)
{
BRIDGE_CACHE.DetachTopLevelPrim(cacheEntry);
BRIDGE_USDWRITER.RemoveRootPrim(cacheEntry, primPathCp);
}
void UsdBridge::SetConnectionLogVerbosity(int logVerbosity)
{
int logLevel = UsdBridgeRemoteConnection::GetConnectionLogLevelMax() - logVerbosity; // Just invert verbosity to get the level
UsdBridgeRemoteConnection::SetConnectionLogLevel(logLevel);
}
| 38,415 | C++ | 35.071361 | 297 | 0.786958 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Common.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeUsdWriterConvenience_h
#define UsdBridgeUsdWriterConvenience_h
#include "UsdBridgeData.h"
#include "UsdBridgeUtils.h"
#include <string>
#include <sstream>
template<typename T>
using TimeEvaluator = UsdBridgeTimeEvaluator<T>;
#define MISC_TOKEN_SEQ \
(Root) \
(extent)
#define ATTRIB_TOKEN_SEQ \
(faceVertexCounts) \
(faceVertexIndices) \
(points) \
(positions) \
(normals) \
(st) \
(attribute0) \
(attribute1) \
(attribute2) \
(attribute3) \
(attribute4) \
(attribute5) \
(attribute6) \
(attribute7) \
(attribute8) \
(attribute9) \
(attribute10) \
(attribute11) \
(attribute12) \
(attribute13) \
(attribute14) \
(attribute15) \
(color) \
(ids) \
(widths) \
(protoIndices) \
(orientations) \
(scales) \
(velocities) \
(angularVelocities) \
(invisibleIds) \
(curveVertexCounts)
#define USDPREVSURF_TOKEN_SEQ \
(UsdPreviewSurface) \
(useSpecularWorkflow) \
(result) \
(surface) \
((PrimVarReader_Float, "UsdPrimvarReader_float")) \
((PrimVarReader_Float2, "UsdPrimvarReader_float2")) \
((PrimVarReader_Float3, "UsdPrimvarReader_float3")) \
((PrimVarReader_Float4, "UsdPrimvarReader_float4")) \
(UsdUVTexture) \
(fallback) \
(r) \
(rg) \
(rgb) \
(black) \
(clamp) \
(repeat) \
(mirror)
#define USDPREVSURF_INPUT_TOKEN_SEQ \
(roughness) \
(opacity) \
(opacityThreshold) \
(metallic) \
(ior) \
(diffuseColor) \
(specularColor) \
(emissiveColor) \
(file) \
(WrapS) \
(WrapT) \
(WrapR) \
(varname)
#define USDPREVSURF_OUTPUT_TOKEN_SEQ \
(result) \
(r) \
(rg) \
(rgb) \
(a)
#define MDL_OUTPUT_TOKEN_SEQ \
(out)
#define MDL_TOKEN_SEQ \
(mdl) \
(OmniPBR) \
(sourceAsset) \
(out) \
(data_lookup_float) \
(data_lookup_float2) \
(data_lookup_float3) \
(data_lookup_float4) \
(data_lookup_int) \
(data_lookup_int2) \
(data_lookup_int3) \
(data_lookup_int4) \
(data_lookup_color) \
(lookup_color) \
(lookup_float) \
(lookup_float3) \
(lookup_float4) \
((xyz, "xyz(float4)")) \
((x, "x(float4)")) \
((y, "y(float4)")) \
((z, "z(float4)")) \
((w, "w(float4)")) \
((construct_color, "construct_color(float3)")) \
((mul_float, "multiply(float,float)")) \
(coord) \
(colorSpace)
#define MDL_INPUT_TOKEN_SEQ \
(reflection_roughness_constant) \
(opacity_constant) \
(opacity_threshold) \
(enable_opacity) \
(metallic_constant) \
(ior_constant) \
(diffuse_color_constant) \
(emissive_color) \
(emissive_intensity) \
(enable_emission) \
(name) \
(tex) \
(wrap_u) \
(wrap_v) \
(wrap_w) \
(a) \
(b) \
#define VOLUME_TOKEN_SEQ \
(density) \
(filePath)
#define INDEX_TOKEN_SEQ \
(nvindex) \
(volume) \
(colormap) \
(Colormap) \
(colormapValues) \
(colormapSource) \
(domain) \
(domainBoundaryMode) \
(clampToEdge)
TF_DECLARE_PUBLIC_TOKENS(
UsdBridgeTokens,
ATTRIB_TOKEN_SEQ
USDPREVSURF_TOKEN_SEQ
USDPREVSURF_INPUT_TOKEN_SEQ
MDL_TOKEN_SEQ
MDL_INPUT_TOKEN_SEQ
VOLUME_TOKEN_SEQ
INDEX_TOKEN_SEQ
MISC_TOKEN_SEQ
);
TF_DECLARE_PUBLIC_TOKENS(
QualifiedInputTokens,
USDPREVSURF_INPUT_TOKEN_SEQ
MDL_INPUT_TOKEN_SEQ
);
TF_DECLARE_PUBLIC_TOKENS(
QualifiedOutputTokens,
USDPREVSURF_OUTPUT_TOKEN_SEQ
MDL_OUTPUT_TOKEN_SEQ
);
namespace constring
{
// Default names
extern const char* const sessionPf;
extern const char* const rootClassName;
extern const char* const rootPrimName;
// Folder names
extern const char* const manifestFolder;
extern const char* const clipFolder;
extern const char* const primStageFolder;
extern const char* const imgFolder;
extern const char* const volFolder;
// Postfixes for auto generated usd subprims
extern const char* const texCoordReaderPrimPf;
extern const char* const psShaderPrimPf;
extern const char* const mdlShaderPrimPf;
extern const char* const mdlOpacityMulPrimPf;
extern const char* const mdlDiffuseOpacityPrimPf;
extern const char* const mdlGraphXYZPrimPf;
extern const char* const mdlGraphColorPrimPf;
extern const char* const mdlGraphXPrimPf;
extern const char* const mdlGraphYPrimPf;
extern const char* const mdlGraphZPrimPf;
extern const char* const mdlGraphWPrimPf;
extern const char* const psSamplerPrimPf;
extern const char* const mdlSamplerPrimPf;
extern const char* const openVDBPrimPf;
extern const char* const protoShapePf;
// Extensions
extern const char* const imageExtension;
extern const char* const vdbExtension;
// Files
extern const char* const fullSceneNameBin;
extern const char* const fullSceneNameAscii;
extern const char* const mdlShaderAssetName;
extern const char* const mdlSupportAssetName;
extern const char* const mdlAuxAssetName;
#ifdef CUSTOM_PBR_MDL
extern const char* const mdlFolder;
extern const char* const opaqueMaterialFile;
extern const char* const transparentMaterialFile;
#endif
#ifdef USE_INDEX_MATERIALS
extern const char* const indexMaterialPf;
extern const char* const indexShaderPf;
extern const char* const indexColorMapPf;
#endif
}
template<typename ArrayType>
ArrayType& GetStaticTempArray()
{
static ArrayType array;
array.resize(0);
return array;
}
namespace
{
size_t FindLength(std::stringstream& strStream)
{
strStream.seekg(0, std::ios::end);
size_t contentSize = strStream.tellg();
strStream.seekg(0, std::ios::beg);
return contentSize;
}
void FormatDirName(std::string& dirName)
{
if (dirName.length() > 0)
{
if (dirName.back() != '/' && dirName.back() != '\\')
dirName.append("/");
}
}
template<typename NormalsType>
void ConvertNormalsToQuaternions(VtQuathArray& quaternions, const void* normals, uint64_t numVertices)
{
GfVec3f from(0.0f, 0.0f, 1.0f);
NormalsType* norms = (NormalsType*)(normals);
for (int i = 0; i < numVertices; ++i)
{
GfVec3f to((float)(norms[i * 3]), (float)(norms[i * 3 + 1]), (float)(norms[i * 3 + 2]));
GfRotation rot(from, to);
const GfQuaternion& quat = rot.GetQuaternion();
quaternions[i] = GfQuath((float)(quat.GetReal()), GfVec3h(quat.GetImaginary()));
}
}
template<typename GeomDataType>
bool UsdGeomDataHasTexCoords(const GeomDataType& geomData)
{
return geomData.Attributes != nullptr &&
geomData.Attributes[0].Data != nullptr &&
(
geomData.Attributes[0].DataType == UsdBridgeType::FLOAT2 ||
geomData.Attributes[0].DataType == UsdBridgeType::DOUBLE2
);
}
TfToken AttribIndexToToken(uint32_t attribIndex)
{
TfToken attribToken;
switch(attribIndex)
{
case 0: attribToken = UsdBridgeTokens->attribute0; break;
case 1: attribToken = UsdBridgeTokens->attribute1; break;
case 2: attribToken = UsdBridgeTokens->attribute2; break;
case 3: attribToken = UsdBridgeTokens->attribute3; break;
case 4: attribToken = UsdBridgeTokens->attribute4; break;
case 5: attribToken = UsdBridgeTokens->attribute5; break;
case 6: attribToken = UsdBridgeTokens->attribute6; break;
case 7: attribToken = UsdBridgeTokens->attribute7; break;
case 8: attribToken = UsdBridgeTokens->attribute8; break;
case 9: attribToken = UsdBridgeTokens->attribute9; break;
case 10: attribToken = UsdBridgeTokens->attribute10; break;
case 11: attribToken = UsdBridgeTokens->attribute11; break;
case 12: attribToken = UsdBridgeTokens->attribute12; break;
case 13: attribToken = UsdBridgeTokens->attribute13; break;
case 14: attribToken = UsdBridgeTokens->attribute14; break;
case 15: attribToken = UsdBridgeTokens->attribute15; break;
default: attribToken = TfToken((std::string("attribute")+std::to_string(attribIndex)).c_str()); break;
}
return attribToken;
}
TfToken TextureWrapToken(UsdBridgeSamplerData::WrapMode wrapMode)
{
TfToken result = UsdBridgeTokens->black;
switch (wrapMode)
{
case UsdBridgeSamplerData::WrapMode::CLAMP:
result = UsdBridgeTokens->clamp;
break;
case UsdBridgeSamplerData::WrapMode::REPEAT:
result = UsdBridgeTokens->repeat;
break;
case UsdBridgeSamplerData::WrapMode::MIRROR:
result = UsdBridgeTokens->mirror;
break;
default:
break;
}
return result;
}
int TextureWrapInt(UsdBridgeSamplerData::WrapMode wrapMode)
{
int result = 3;
switch (wrapMode)
{
case UsdBridgeSamplerData::WrapMode::CLAMP:
result = 0;
break;
case UsdBridgeSamplerData::WrapMode::REPEAT:
result = 1;
break;
case UsdBridgeSamplerData::WrapMode::MIRROR:
result = 2;
break;
default:
break;
}
return result;
}
SdfValueTypeName GetPrimvarArrayType(UsdBridgeType eltType)
{
assert(eltType != UsdBridgeType::UNDEFINED);
SdfValueTypeName result = SdfValueTypeNames->BoolArray;
switch (eltType)
{
case UsdBridgeType::UCHAR:
case UsdBridgeType::CHAR: { result = SdfValueTypeNames->UCharArray; break;}
case UsdBridgeType::USHORT: { result = SdfValueTypeNames->UIntArray; break; }
case UsdBridgeType::SHORT: { result = SdfValueTypeNames->IntArray; break; }
case UsdBridgeType::UINT: { result = SdfValueTypeNames->UIntArray; break; }
case UsdBridgeType::INT: { result = SdfValueTypeNames->IntArray; break; }
case UsdBridgeType::LONG: { result = SdfValueTypeNames->Int64Array; break; }
case UsdBridgeType::ULONG: { result = SdfValueTypeNames->UInt64Array; break; }
case UsdBridgeType::HALF: { result = SdfValueTypeNames->HalfArray; break; }
case UsdBridgeType::FLOAT: { result = SdfValueTypeNames->FloatArray; break; }
case UsdBridgeType::DOUBLE: { result = SdfValueTypeNames->DoubleArray; break; }
case UsdBridgeType::INT2: { result = SdfValueTypeNames->Int2Array; break; }
case UsdBridgeType::HALF2: { result = SdfValueTypeNames->Half2Array; break; }
case UsdBridgeType::FLOAT2: { result = SdfValueTypeNames->Float2Array; break; }
case UsdBridgeType::DOUBLE2: { result = SdfValueTypeNames->Double2Array; break; }
case UsdBridgeType::INT3: { result = SdfValueTypeNames->Int3Array; break; }
case UsdBridgeType::HALF3: { result = SdfValueTypeNames->Half3Array; break; }
case UsdBridgeType::FLOAT3: { result = SdfValueTypeNames->Float3Array; break; }
case UsdBridgeType::DOUBLE3: { result = SdfValueTypeNames->Double3Array; break; }
case UsdBridgeType::INT4: { result = SdfValueTypeNames->Int4Array; break; }
case UsdBridgeType::HALF4: { result = SdfValueTypeNames->Half4Array; break; }
case UsdBridgeType::FLOAT4: { result = SdfValueTypeNames->Float4Array; break; }
case UsdBridgeType::DOUBLE4: { result = SdfValueTypeNames->Double4Array; break; }
case UsdBridgeType::UCHAR2:
case UsdBridgeType::UCHAR3:
case UsdBridgeType::UCHAR4: { result = SdfValueTypeNames->UCharArray; break; }
case UsdBridgeType::CHAR2:
case UsdBridgeType::CHAR3:
case UsdBridgeType::CHAR4: { result = SdfValueTypeNames->UCharArray; break; }
case UsdBridgeType::USHORT2:
case UsdBridgeType::USHORT3:
case UsdBridgeType::USHORT4: { result = SdfValueTypeNames->UIntArray; break; }
case UsdBridgeType::SHORT2:
case UsdBridgeType::SHORT3:
case UsdBridgeType::SHORT4: { result = SdfValueTypeNames->IntArray; break; }
case UsdBridgeType::UINT2:
case UsdBridgeType::UINT3:
case UsdBridgeType::UINT4: { result = SdfValueTypeNames->UIntArray; break; }
case UsdBridgeType::LONG2:
case UsdBridgeType::LONG3:
case UsdBridgeType::LONG4: { result = SdfValueTypeNames->Int64Array; break; }
case UsdBridgeType::ULONG2:
case UsdBridgeType::ULONG3:
case UsdBridgeType::ULONG4: { result = SdfValueTypeNames->UInt64Array; break; }
default: break; //unsupported defaults to bool
};
return result;
}
template<bool PreviewSurface>
const TfToken& GetMaterialShaderInputToken(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
if(PreviewSurface)
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { return UsdBridgeTokens->diffuseColor; break; }
case DMI::OPACITY: { return UsdBridgeTokens->opacity; break; }
case DMI::EMISSIVECOLOR: { return UsdBridgeTokens->emissiveColor; break; }
case DMI::ROUGHNESS: { return UsdBridgeTokens->roughness; break; }
case DMI::METALLIC: { return UsdBridgeTokens->metallic; break; }
case DMI::IOR: { return UsdBridgeTokens->ior; break; }
default: assert(false); break;
};
}
else
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { return UsdBridgeTokens->diffuse_color_constant; break; }
case DMI::OPACITY: { return UsdBridgeTokens->opacity_constant; break; }
case DMI::EMISSIVECOLOR: { return UsdBridgeTokens->emissive_color; break; }
case DMI::EMISSIVEINTENSITY: { return UsdBridgeTokens->emissive_intensity; break; }
case DMI::ROUGHNESS: { return UsdBridgeTokens->reflection_roughness_constant; break; }
case DMI::METALLIC: { return UsdBridgeTokens->metallic_constant; break; }
case DMI::IOR: { return UsdBridgeTokens->ior_constant; break; }
default: assert(false); break;
};
}
return UsdBridgeTokens->diffuseColor;
}
template<bool PreviewSurface>
const TfToken& GetMaterialShaderInputQualifiedToken(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
if(PreviewSurface)
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { return QualifiedInputTokens->diffuseColor; break; }
case DMI::OPACITY: { return QualifiedInputTokens->opacity; break; }
case DMI::EMISSIVECOLOR: { return QualifiedInputTokens->emissiveColor; break; }
case DMI::ROUGHNESS: { return QualifiedInputTokens->roughness; break; }
case DMI::METALLIC: { return QualifiedInputTokens->metallic; break; }
case DMI::IOR: { return QualifiedInputTokens->ior; break; }
default: assert(false); break;
};
}
else
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { return QualifiedInputTokens->diffuse_color_constant; break; }
case DMI::OPACITY: { return QualifiedInputTokens->opacity_constant; break; }
case DMI::EMISSIVECOLOR: { return QualifiedInputTokens->emissive_color; break; }
case DMI::EMISSIVEINTENSITY: { return QualifiedInputTokens->emissive_intensity; break; }
case DMI::ROUGHNESS: { return QualifiedInputTokens->reflection_roughness_constant; break; }
case DMI::METALLIC: { return QualifiedInputTokens->metallic_constant; break; }
case DMI::IOR: { return QualifiedInputTokens->ior_constant; break; }
default: assert(false); break;
};
}
return QualifiedInputTokens->diffuseColor;
}
template<bool PreviewSurface>
SdfPath GetAttributeReaderPathPf(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
const char* const diffuseAttribReaderPrimPf_ps = "diffuseattribreader_ps";
const char* const opacityAttribReaderPrimPf_ps = "opacityattribreader_ps";
const char* const emissiveColorAttribReaderPrimPf_ps = "emissivecolorattribreader_ps";
const char* const emissiveIntensityAttribReaderPrimPf_ps = "emissiveintensityattribreader_ps";
const char* const roughnessAttribReaderPrimPf_ps = "roughnessattribreader_ps";
const char* const metallicAttribReaderPrimPf_ps = "metallicattribreader_ps";
const char* const iorAttribReaderPrimPf_ps = "iorattribreader_ps";
const char* const diffuseAttribReaderPrimPf_mdl = "diffuseattribreader_mdl";
const char* const opacityAttribReaderPrimPf_mdl = "opacityattribreader_mdl";
const char* const emissiveColorAttribReaderPrimPf_mdl = "emissivecolorattribreader_mdl";
const char* const emissiveIntensityAttribReaderPrimPf_mdl = "emissiveintensityattribreader_mdl";
const char* const roughnessAttribReaderPrimPf_mdl = "roughnessattribreader_mdl";
const char* const metallicAttribReaderPrimPf_mdl = "metallicattribreader_mdl";
const char* const iorAttribReaderPrimPf_mdl = "iorattribreader_mdl";
const char* result = nullptr;
if(PreviewSurface)
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { result = diffuseAttribReaderPrimPf_ps; break; }
case DMI::OPACITY: { result = opacityAttribReaderPrimPf_ps; break; }
case DMI::EMISSIVECOLOR: { result = emissiveColorAttribReaderPrimPf_ps; break; }
case DMI::EMISSIVEINTENSITY: { result = emissiveIntensityAttribReaderPrimPf_ps; break; }
case DMI::ROUGHNESS: { result = roughnessAttribReaderPrimPf_ps; break; }
case DMI::METALLIC: { result = metallicAttribReaderPrimPf_ps; break; }
case DMI::IOR: { result = iorAttribReaderPrimPf_ps; break; }
default: assert(false); break;
};
}
else
{
switch(dataMemberId)
{
case DMI::DIFFUSE: { result = diffuseAttribReaderPrimPf_mdl; break; }
case DMI::OPACITY: { result = opacityAttribReaderPrimPf_mdl; break; }
case DMI::EMISSIVECOLOR: { result = emissiveColorAttribReaderPrimPf_mdl; break; }
case DMI::EMISSIVEINTENSITY: { result = emissiveIntensityAttribReaderPrimPf_mdl; break; }
case DMI::ROUGHNESS: { result = roughnessAttribReaderPrimPf_mdl; break; }
case DMI::METALLIC: { result = metallicAttribReaderPrimPf_mdl; break; }
case DMI::IOR: { result = iorAttribReaderPrimPf_mdl; break; }
default: assert(false); break;
};
}
return SdfPath(result);
}
const TfToken& GetPsAttributeReaderId(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
switch(dataMemberId)
{
case DMI::DIFFUSE: { return UsdBridgeTokens->PrimVarReader_Float4; break; } // float4 instead of float4, to fix implicit conversion issue in storm
case DMI::OPACITY: { return UsdBridgeTokens->PrimVarReader_Float; break; }
case DMI::EMISSIVECOLOR: { return UsdBridgeTokens->PrimVarReader_Float3; break; }
case DMI::EMISSIVEINTENSITY: { return UsdBridgeTokens->PrimVarReader_Float; break; }
case DMI::ROUGHNESS: { return UsdBridgeTokens->PrimVarReader_Float; break; }
case DMI::METALLIC: { return UsdBridgeTokens->PrimVarReader_Float; break; }
case DMI::IOR: { return UsdBridgeTokens->PrimVarReader_Float; break; }
default: { assert(false); break; }
};
return UsdBridgeTokens->PrimVarReader_Float;
}
const TfToken& GetMdlAttributeReaderSubId(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
switch(dataMemberId)
{
case DMI::DIFFUSE: { return UsdBridgeTokens->data_lookup_float4; break; }
case DMI::OPACITY: { return UsdBridgeTokens->data_lookup_float; break; }
case DMI::EMISSIVECOLOR: { return UsdBridgeTokens->data_lookup_color; break; }
case DMI::EMISSIVEINTENSITY: { return UsdBridgeTokens->data_lookup_float; break; }
case DMI::ROUGHNESS: { return UsdBridgeTokens->data_lookup_float; break; }
case DMI::METALLIC: { return UsdBridgeTokens->data_lookup_float; break; }
case DMI::IOR: { return UsdBridgeTokens->data_lookup_float; break; }
default: { assert(false); break; }
};
return UsdBridgeTokens->data_lookup_float4;
}
const TfToken& GetMdlAttributeReaderSubId(const SdfValueTypeName& readerOutputType)
{
if(readerOutputType == SdfValueTypeNames->Float4)
return UsdBridgeTokens->data_lookup_float4;
if(readerOutputType == SdfValueTypeNames->Float3)
return UsdBridgeTokens->data_lookup_float3;
if(readerOutputType == SdfValueTypeNames->Float2)
return UsdBridgeTokens->data_lookup_float2;
if(readerOutputType == SdfValueTypeNames->Float)
return UsdBridgeTokens->data_lookup_float;
if(readerOutputType == SdfValueTypeNames->Int4)
return UsdBridgeTokens->data_lookup_int4;
if(readerOutputType == SdfValueTypeNames->Int3)
return UsdBridgeTokens->data_lookup_int3;
if(readerOutputType == SdfValueTypeNames->Int2)
return UsdBridgeTokens->data_lookup_int2;
if(readerOutputType == SdfValueTypeNames->Int)
return UsdBridgeTokens->data_lookup_int;
if(readerOutputType == SdfValueTypeNames->Color3f)
return UsdBridgeTokens->data_lookup_color;
return UsdBridgeTokens->data_lookup_float4;
}
const SdfValueTypeName& GetAttributeOutputType(UsdBridgeMaterialData::DataMemberId dataMemberId)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
// An educated guess for the type belonging to a particular attribute bound to material inputs
switch(dataMemberId)
{
case DMI::DIFFUSE: { return SdfValueTypeNames->Float4; break; } // Typically bound to the color array, containing rgb and a information.
case DMI::OPACITY: { return SdfValueTypeNames->Float; break; }
case DMI::EMISSIVECOLOR: { return SdfValueTypeNames->Color3f; break; }
case DMI::EMISSIVEINTENSITY: { return SdfValueTypeNames->Float; break; }
case DMI::ROUGHNESS: { return SdfValueTypeNames->Float; break; }
case DMI::METALLIC: { return SdfValueTypeNames->Float; break; }
case DMI::IOR: { return SdfValueTypeNames->Float; break; }
default: assert(false); break;
};
return SdfValueTypeNames->Float;
}
const TfToken& GetSamplerAssetSubId(int numComponents)
{
switch(numComponents)
{
case 1: { return UsdBridgeTokens->lookup_float; break; }
case 4: { return UsdBridgeTokens->lookup_float4; break; }
default: { return UsdBridgeTokens->lookup_float3; break; }
}
return UsdBridgeTokens->lookup_float3;
}
template<bool PreviewSurface>
const TfToken& GetSamplerOutputColorToken(int numComponents)
{
if(PreviewSurface)
{
switch(numComponents)
{
case 1: { return UsdBridgeTokens->r; break; }
case 2: { return UsdBridgeTokens->rg; break; }
default: { return UsdBridgeTokens->rgb; break; } // The alpha component is always separate
}
}
return UsdBridgeTokens->out;
}
template<bool PreviewSurface>
const SdfValueTypeName& GetSamplerOutputColorType(int numComponents)
{
if(PreviewSurface)
{
switch(numComponents)
{
case 1: { return SdfValueTypeNames->Float; break; }
case 2: { return SdfValueTypeNames->Float2; break; }
default: { return SdfValueTypeNames->Float3; break; } // The alpha component is always separate
}
}
else
{
switch(numComponents)
{
case 1: { return SdfValueTypeNames->Float; break; }
case 4: { return SdfValueTypeNames->Float4; break; }
default: { return SdfValueTypeNames->Float3; break; }
}
}
return SdfValueTypeNames->Float3;
}
template<class T>
T GetOrDefinePrim(const UsdStageRefPtr& stage, const SdfPath& path)
{
T prim = T::Get(stage, path);
if (!prim)
prim = T::Define(stage, path);
assert(prim);
return prim;
}
template<typename ValueType>
void ClearAndSetUsdAttribute(const UsdAttribute& attribute, const ValueType& value, const UsdTimeCode& timeCode, bool clearAttrib)
{
if(clearAttrib)
attribute.Clear();
attribute.Set(value, timeCode);
}
void ClearUsdAttributes(const UsdAttribute& uniformAttrib, const UsdAttribute& timeVarAttrib, bool timeVaryingUpdate)
{
#ifdef TIME_BASED_CACHING
#ifdef VALUE_CLIP_RETIMING
// Step could be performed to keep timeVar stage more in sync, but removal of attrib from manifest makes this superfluous
//if (!timeVaryingUpdate && timeVarGeom)
//{
// timeVarAttrib.ClearAtTime(timeEval.TimeCode);
//}
#ifdef OMNIVERSE_CREATE_WORKAROUNDS
if(timeVaryingUpdate && uniformAttrib)
{
// Create considers the referenced uniform prims as a stronger opinion than timeVarying clip values (against the spec, see 'value resolution').
// Just remove the referenced uniform opinion altogether.
uniformAttrib.ClearAtTime(TimeEvaluator<bool>::DefaultTime);
}
#endif
#else // !VALUE_CLIP_RETIMING
// Uniform and timeVar geoms are the same. In case of uniform values, make sure the timesamples are cleared out.
if(!timeVaryingUpdate && timeVarAttrib)
{
timeVarAttrib.Clear();
}
#endif
#endif
}
// Array assignment
template<class ArrayType>
void AssignArrayToPrimvar(const void* data, size_t numElements, const UsdTimeCode& timeCode, ArrayType* usdArray)
{
using ElementType = typename ArrayType::ElementType;
ElementType* typedData = (ElementType*)data;
usdArray->assign(typedData, typedData + numElements);
}
template<class ArrayType>
void AssignArrayToPrimvarFlatten(const void* data, UsdBridgeType dataType, size_t numElements, const UsdTimeCode& timeCode, ArrayType* usdArray)
{
int elementMultiplier = UsdBridgeTypeNumComponents(dataType);
size_t numFlattenedElements = numElements * elementMultiplier;
AssignArrayToPrimvar<ArrayType>(data, numFlattenedElements, timeCode, usdArray);
}
template<class ArrayType, class EltType>
void AssignArrayToPrimvarConvert(const void* data, size_t numElements, const UsdTimeCode& timeCode, ArrayType* usdArray)
{
using ElementType = typename ArrayType::ElementType;
EltType* typedData = (EltType*)data;
usdArray->resize(numElements);
for (int i = 0; i < numElements; ++i)
{
(*usdArray)[i] = ElementType(typedData[i]);
}
}
template<class ArrayType, class EltType>
void AssignArrayToPrimvarConvertFlatten(const void* data, UsdBridgeType dataType, size_t numElements, const UsdTimeCode& timeCode, ArrayType* usdArray)
{
int elementMultiplier = UsdBridgeTypeNumComponents(dataType);
size_t numFlattenedElements = numElements * elementMultiplier;
AssignArrayToPrimvarConvert<ArrayType, EltType>(data, numFlattenedElements, timeCode, usdArray);
}
template<typename ArrayType, typename EltType>
void Expand1ToVec3(const void* data, uint64_t numElements, const UsdTimeCode& timeCode, ArrayType* usdArray)
{
usdArray->resize(numElements);
const EltType* typedInput = reinterpret_cast<const EltType*>(data);
for (int i = 0; i < numElements; ++i)
{
(*usdArray)[i] = typename ArrayType::ElementType(typedInput[i], typedInput[i], typedInput[i]);
}
}
template<typename InputEltType, int numComponents>
void ExpandToColor(const void* data, uint64_t numElements, const UsdTimeCode& timeCode, VtVec4fArray* usdArray)
{
usdArray->resize(numElements);
const InputEltType* typedInput = reinterpret_cast<const InputEltType*>(data);
// No memcopies, as input is not guaranteed to be of float type
if(numComponents == 1)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i], 0.0f, 0.0f, 1.0f);
if(numComponents == 2)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i*2], typedInput[i*2+1], 0.0f, 1.0f);
if(numComponents == 3)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i*3], typedInput[i*3+1], typedInput[i*3+2], 1.0f);
}
template<typename InputEltType, int numComponents>
void ExpandToColorNormalize(const void* data, uint64_t numElements, const UsdTimeCode& timeCode, VtVec4fArray* usdArray)
{
usdArray->resize(numElements);
const InputEltType* typedInput = reinterpret_cast<const InputEltType*>(data);
double normFactor = 1.0 / (double)std::numeric_limits<InputEltType>::max(); // float may not be enough for uint32_t
// No memcopies, as input is not guaranteed to be of float type
if(numComponents == 1)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i]*normFactor, 0.0f, 0.0f, 1.0f);
if(numComponents == 2)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i*2]*normFactor, typedInput[i*2+1]*normFactor, 0.0f, 1.0f);
if(numComponents == 3)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i*3]*normFactor, typedInput[i*3+1]*normFactor, typedInput[i*3+2]*normFactor, 1.0f);
if(numComponents == 4)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(typedInput[i*4]*normFactor, typedInput[i*4+1]*normFactor, typedInput[i*4+2]*normFactor, typedInput[i*4+3]*normFactor);
}
template<int numComponents>
void ExpandSRGBToColor(const void* data, uint64_t numElements, const UsdTimeCode& timeCode, VtVec4fArray* usdArray)
{
usdArray->resize(numElements);
const unsigned char* typedInput = reinterpret_cast<const unsigned char*>(data);
float normFactor = 1.0f / 255.0f;
const float* srgbTable = ubutils::SrgbToLinearTable();
// No memcopies, as input is not guaranteed to be of float type
if(numComponents == 1)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(srgbTable[typedInput[i]], 0.0f, 0.0f, 1.0f);
if(numComponents == 2)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(srgbTable[typedInput[i*2]], 0.0f, 0.0f, typedInput[i*2+1]*normFactor); // Alpha is linear
if(numComponents == 3)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(srgbTable[typedInput[i*3]], srgbTable[typedInput[i*3+1]], srgbTable[typedInput[i*3+2]], 1.0f);
if(numComponents == 4)
for (int i = 0; i < numElements; ++i)
(*usdArray)[i] = GfVec4f(srgbTable[typedInput[i*4]], srgbTable[typedInput[i*4+1]], srgbTable[typedInput[i*4+2]], typedInput[i*4+3]*normFactor);
}
}
#define CREATE_REMOVE_TIMEVARYING_ATTRIB(_prim, _dataMemberId, _token, _type) \
if(!timeEval || timeEval->IsTimeVarying(_dataMemberId)) \
_prim.CreateAttribute(_token, _type); \
else \
_prim.RemoveProperty(_token);
#define CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(_dataMemberId, _CreateFunc, _token) \
if(!timeEval || timeEval->IsTimeVarying(_dataMemberId)) \
attribCreatePrim._CreateFunc(); \
else \
attribRemovePrim.RemoveProperty(_token);
#define SET_TIMEVARYING_ATTRIB(_timeVaryingUpdate, _timeVarAttrib, _uniformAttrib, _value) \
if(_timeVaryingUpdate) \
_timeVarAttrib.Set(_value, timeEval.TimeCode); \
else \
_uniformAttrib.Set(_value, timeEval.Default());
#define ASSIGN_SET_PRIMVAR if(setPrimvar) arrayPrimvar.Set(usdArray, timeCode)
#define ASSIGN_PRIMVAR_MACRO(ArrayType) \
ArrayType& usdArray = GetStaticTempArray<ArrayType>(); AssignArrayToPrimvar<ArrayType>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_FLATTEN_MACRO(ArrayType) \
ArrayType& usdArray = GetStaticTempArray<ArrayType>(); AssignArrayToPrimvarFlatten<ArrayType>(arrayData, arrayDataType, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_CONVERT_MACRO(ArrayType, EltType) \
ArrayType& usdArray = GetStaticTempArray<ArrayType>(); AssignArrayToPrimvarConvert<ArrayType, EltType>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_CONVERT_FLATTEN_MACRO(ArrayType, EltType) \
ArrayType& usdArray = GetStaticTempArray<ArrayType>(); AssignArrayToPrimvarConvertFlatten<ArrayType, EltType>(arrayData, arrayDataType, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_CUSTOM_ARRAY_MACRO(ArrayType, customArray) \
ArrayType& usdArray = customArray; AssignArrayToPrimvar<ArrayType>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_CONVERT_CUSTOM_ARRAY_MACRO(ArrayType, EltType, customArray) \
ArrayType& usdArray = customArray; AssignArrayToPrimvarConvert<ArrayType, EltType>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_1EXPAND3(ArrayType, EltType) \
ArrayType& usdArray = GetStaticTempArray<ArrayType>(); Expand1ToVec3<ArrayType, EltType>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_1EXPAND_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColor<EltType, 1>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_2EXPAND_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColor<EltType, 2>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_3EXPAND_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColor<EltType, 3>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_1EXPAND_NORMALIZE_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColorNormalize<EltType, 1>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_2EXPAND_NORMALIZE_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColorNormalize<EltType, 2>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_3EXPAND_NORMALIZE_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColorNormalize<EltType, 3>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_4EXPAND_NORMALIZE_COL(EltType) \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandToColorNormalize<EltType, 4>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_1EXPAND_SGRB() \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandSRGBToColor<1>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_2EXPAND_SGRB() \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandSRGBToColor<2>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_3EXPAND_SGRB() \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandSRGBToColor<3>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define ASSIGN_PRIMVAR_MACRO_4EXPAND_SGRB() \
VtVec4fArray& usdArray = GetStaticTempArray<VtVec4fArray>(); ExpandSRGBToColor<4>(arrayData, arrayNumElements, timeCode, &usdArray); ASSIGN_SET_PRIMVAR
#define GET_USDARRAY_REF usdArrayRef = &usdArray
namespace
{
// Assigns color data array to VtVec4fArray primvar
VtVec4fArray* AssignColorArrayToPrimvar(const UsdBridgeLogObject& logObj, const void* arrayData, size_t arrayNumElements, UsdBridgeType arrayType, UsdTimeCode timeCode, const UsdAttribute& arrayPrimvar, bool setPrimvar = true)
{
VtVec4fArray* usdArrayRef = nullptr;
switch (arrayType)
{
case UsdBridgeType::UCHAR: {ASSIGN_PRIMVAR_MACRO_1EXPAND_NORMALIZE_COL(uint8_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR2: {ASSIGN_PRIMVAR_MACRO_2EXPAND_NORMALIZE_COL(uint8_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR3: {ASSIGN_PRIMVAR_MACRO_3EXPAND_NORMALIZE_COL(uint8_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR4: {ASSIGN_PRIMVAR_MACRO_4EXPAND_NORMALIZE_COL(uint8_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR_SRGB_R: {ASSIGN_PRIMVAR_MACRO_1EXPAND_SGRB(); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR_SRGB_RA: {ASSIGN_PRIMVAR_MACRO_2EXPAND_SGRB(); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR_SRGB_RGB: {ASSIGN_PRIMVAR_MACRO_3EXPAND_SGRB(); GET_USDARRAY_REF; break; }
case UsdBridgeType::UCHAR_SRGB_RGBA: {ASSIGN_PRIMVAR_MACRO_4EXPAND_SGRB(); GET_USDARRAY_REF; break; }
case UsdBridgeType::USHORT: {ASSIGN_PRIMVAR_MACRO_1EXPAND_NORMALIZE_COL(uint16_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::USHORT2: {ASSIGN_PRIMVAR_MACRO_2EXPAND_NORMALIZE_COL(uint16_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::USHORT3: {ASSIGN_PRIMVAR_MACRO_3EXPAND_NORMALIZE_COL(uint16_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::USHORT4: {ASSIGN_PRIMVAR_MACRO_4EXPAND_NORMALIZE_COL(uint16_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_MACRO_1EXPAND_NORMALIZE_COL(uint32_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UINT2: {ASSIGN_PRIMVAR_MACRO_2EXPAND_NORMALIZE_COL(uint32_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UINT3: {ASSIGN_PRIMVAR_MACRO_3EXPAND_NORMALIZE_COL(uint32_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::UINT4: {ASSIGN_PRIMVAR_MACRO_4EXPAND_NORMALIZE_COL(uint32_t); GET_USDARRAY_REF; break; }
case UsdBridgeType::FLOAT: {ASSIGN_PRIMVAR_MACRO_1EXPAND_COL(float); GET_USDARRAY_REF; break; }
case UsdBridgeType::FLOAT2: {ASSIGN_PRIMVAR_MACRO_2EXPAND_COL(float); GET_USDARRAY_REF; break; }
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO_3EXPAND_COL(float); GET_USDARRAY_REF; break; }
case UsdBridgeType::FLOAT4: {ASSIGN_PRIMVAR_MACRO(VtVec4fArray); GET_USDARRAY_REF; break; }
case UsdBridgeType::DOUBLE: {ASSIGN_PRIMVAR_MACRO_1EXPAND_COL(double); GET_USDARRAY_REF; break; }
case UsdBridgeType::DOUBLE2: {ASSIGN_PRIMVAR_MACRO_2EXPAND_COL(double); GET_USDARRAY_REF; break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_MACRO_3EXPAND_COL(double); GET_USDARRAY_REF; break; }
case UsdBridgeType::DOUBLE4: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec4fArray, GfVec4d); GET_USDARRAY_REF; break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom color primvar is not of type (UCHAR/USHORT/UINT/FLOAT/DOUBLE)(1/2/3/4) or UCHAR_SRGB_<X>."); break; }
}
return usdArrayRef;
}
void AssignAttribArrayToPrimvar(const UsdBridgeLogObject& logObj, const void* arrayData, UsdBridgeType arrayDataType, size_t arrayNumElements, const UsdAttribute& arrayPrimvar, const UsdTimeCode& timeCode)
{
bool setPrimvar = true;
switch (arrayDataType)
{
case UsdBridgeType::UCHAR: { ASSIGN_PRIMVAR_MACRO(VtUCharArray); break; }
case UsdBridgeType::UCHAR_SRGB_R: { ASSIGN_PRIMVAR_MACRO(VtUCharArray); break; }
case UsdBridgeType::CHAR: { ASSIGN_PRIMVAR_MACRO(VtUCharArray); break; }
case UsdBridgeType::USHORT: { ASSIGN_PRIMVAR_CONVERT_MACRO(VtUIntArray, short); break; }
case UsdBridgeType::SHORT: { ASSIGN_PRIMVAR_CONVERT_MACRO(VtIntArray, unsigned short); break; }
case UsdBridgeType::UINT: { ASSIGN_PRIMVAR_MACRO(VtUIntArray); break; }
case UsdBridgeType::INT: { ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
case UsdBridgeType::LONG: { ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG: { ASSIGN_PRIMVAR_MACRO(VtUInt64Array); break; }
case UsdBridgeType::HALF: { ASSIGN_PRIMVAR_MACRO(VtHalfArray); break; }
case UsdBridgeType::FLOAT: { ASSIGN_PRIMVAR_MACRO(VtFloatArray); break; }
case UsdBridgeType::DOUBLE: { ASSIGN_PRIMVAR_MACRO(VtDoubleArray); break; }
case UsdBridgeType::INT2: { ASSIGN_PRIMVAR_MACRO(VtVec2iArray); break; }
case UsdBridgeType::FLOAT2: { ASSIGN_PRIMVAR_MACRO(VtVec2fArray); break; }
case UsdBridgeType::DOUBLE2: { ASSIGN_PRIMVAR_MACRO(VtVec2dArray); break; }
case UsdBridgeType::INT3: { ASSIGN_PRIMVAR_MACRO(VtVec3iArray); break; }
case UsdBridgeType::FLOAT3: { ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: { ASSIGN_PRIMVAR_MACRO(VtVec3dArray); break; }
case UsdBridgeType::INT4: { ASSIGN_PRIMVAR_MACRO(VtVec4iArray); break; }
case UsdBridgeType::FLOAT4: { ASSIGN_PRIMVAR_MACRO(VtVec4fArray); break; }
case UsdBridgeType::DOUBLE4: { ASSIGN_PRIMVAR_MACRO(VtVec4dArray); break; }
case UsdBridgeType::UCHAR2:
case UsdBridgeType::UCHAR3:
case UsdBridgeType::UCHAR4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtUCharArray); break; }
case UsdBridgeType::UCHAR_SRGB_RA:
case UsdBridgeType::UCHAR_SRGB_RGB:
case UsdBridgeType::UCHAR_SRGB_RGBA: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtUCharArray); break; }
case UsdBridgeType::CHAR2:
case UsdBridgeType::CHAR3:
case UsdBridgeType::CHAR4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtUCharArray); break; }
case UsdBridgeType::USHORT2:
case UsdBridgeType::USHORT3:
case UsdBridgeType::USHORT4: { ASSIGN_PRIMVAR_CONVERT_FLATTEN_MACRO(VtUIntArray, short); break; }
case UsdBridgeType::SHORT2:
case UsdBridgeType::SHORT3:
case UsdBridgeType::SHORT4: { ASSIGN_PRIMVAR_CONVERT_FLATTEN_MACRO(VtIntArray, unsigned short); break; }
case UsdBridgeType::UINT2:
case UsdBridgeType::UINT3:
case UsdBridgeType::UINT4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtUIntArray); break; }
case UsdBridgeType::LONG2:
case UsdBridgeType::LONG3:
case UsdBridgeType::LONG4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG2:
case UsdBridgeType::ULONG3:
case UsdBridgeType::ULONG4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtUInt64Array); break; }
case UsdBridgeType::HALF2:
case UsdBridgeType::HALF3:
case UsdBridgeType::HALF4: { ASSIGN_PRIMVAR_FLATTEN_MACRO(VtHalfArray); break; }
default: {UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom Attribute<Index> primvar copy does not support source data type: " << arrayDataType) break; }
};
}
}
#endif | 41,699 | C | 40.205534 | 228 | 0.708746 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeTimeEvaluator.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeTimeEvaluator_h
#define UsdBridgeTimeEvaluator_h
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
template<class T>
class UsdBridgeTimeEvaluator
{
public:
UsdBridgeTimeEvaluator(const T& data, double timeStep)
: Data(data)
, TimeCode(timeStep)
{
}
UsdBridgeTimeEvaluator(const T& data)
: Data(data)
{
}
const UsdTimeCode& Eval(typename T::DataMemberId member) const
{
#ifdef TIME_BASED_CACHING
if ((Data.TimeVarying & member) != T::DataMemberId::NONE)
return TimeCode;
else
#endif
return DefaultTime;
}
bool IsTimeVarying(typename T::DataMemberId member) const
{
#ifdef TIME_BASED_CACHING
return ((Data.TimeVarying & member) != T::DataMemberId::NONE);
#else
return false;
#endif
}
UsdTimeCode Default() const { return DefaultTime; }
const T& Data;
const UsdTimeCode TimeCode;
static const UsdTimeCode DefaultTime;
};
template<class T>
const UsdTimeCode UsdBridgeTimeEvaluator<T>::DefaultTime = UsdTimeCode::Default();
template<>
class UsdBridgeTimeEvaluator<bool>
{
public:
UsdBridgeTimeEvaluator(bool timeVarying, double timeStep)
: TimeVarying(timeVarying)
, TimeCode(timeStep)
{
}
const UsdTimeCode& Eval() const
{
#ifdef TIME_BASED_CACHING
if (TimeVarying)
return TimeCode;
else
#endif
return DefaultTime;
}
UsdTimeCode Default() const { return DefaultTime; }
const bool TimeVarying;
const UsdTimeCode TimeCode;
static const UsdTimeCode DefaultTime;
};
#endif | 1,583 | C | 18.555555 | 82 | 0.720152 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeDiagnosticMgrDelegate.cpp |
// Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeDiagnosticMgrDelegate.h"
bool UsdBridgeDiagnosticMgrDelegate::OutputEnabled = false;
UsdBridgeDiagnosticMgrDelegate::UsdBridgeDiagnosticMgrDelegate(void* logUserData, UsdBridgeLogCallback logCallback)
: LogUserData(logUserData)
, LogCallback(logCallback)
{}
void UsdBridgeDiagnosticMgrDelegate::IssueError(TfError const& err)
{
LogTfMessage(UsdBridgeLogLevel::ERR, err);
}
void UsdBridgeDiagnosticMgrDelegate::IssueFatalError(TfCallContext const& context,
std::string const& msg)
{
std::string message = TfStringPrintf(
"[USD Internal error]: %s in %s at line %zu of %s",
msg.c_str(), context.GetFunction(), context.GetLine(), context.GetFile()
);
LogMessage(UsdBridgeLogLevel::ERR, message);
}
void UsdBridgeDiagnosticMgrDelegate::IssueStatus(TfStatus const& status)
{
LogTfMessage(UsdBridgeLogLevel::STATUS, status);
}
void UsdBridgeDiagnosticMgrDelegate::IssueWarning(TfWarning const& warning)
{
LogTfMessage(UsdBridgeLogLevel::WARNING, warning);
}
void UsdBridgeDiagnosticMgrDelegate::LogTfMessage(UsdBridgeLogLevel level, TfDiagnosticBase const& diagBase)
{
std::string message = TfStringPrintf(
"[USD Internal Message]: %s with error code %s in %s at line %zu of %s",
diagBase.GetCommentary().c_str(),
TfDiagnosticMgr::GetCodeName(diagBase.GetDiagnosticCode()).c_str(),
diagBase.GetContext().GetFunction(),
diagBase.GetContext().GetLine(),
diagBase.GetContext().GetFile()
);
LogMessage(level, message);
}
void UsdBridgeDiagnosticMgrDelegate::LogMessage(UsdBridgeLogLevel level, const std::string& message)
{
if(OutputEnabled)
LogCallback(level, LogUserData, message.c_str());
} | 1,776 | C++ | 30.175438 | 115 | 0.756194 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeCaches.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
#include "UsdBridgeCaches.h"
#include "UsdBridgeUtils.h"
#ifdef VALUE_CLIP_RETIMING
constexpr double UsdBridgePrimCache::PrimStageTimeCode;
#endif
UsdBridgePrimCache::UsdBridgePrimCache(const SdfPath& pp, const SdfPath& nm, ResourceCollectFunc cf)
: PrimPath(pp), Name(nm), ResourceCollect(cf)
#ifndef NDEBUG
, Debug_Name(nm.GetString())
#endif
{
if(cf)
{
ResourceKeys = std::make_unique<ResourceContainer>();
}
}
UsdBridgePrimCache* UsdBridgePrimCache::GetChildCache(const TfToken& nameToken)
{
auto it = std::find_if(this->Children.begin(), this->Children.end(),
[&nameToken](UsdBridgePrimCache* cache) -> bool { return cache->PrimPath.GetNameToken() == nameToken; });
return (it == this->Children.end()) ? nullptr : *it;
}
#ifdef TIME_BASED_CACHING
void UsdBridgePrimCache::SetChildVisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode)
{
auto childIt = std::find(this->Children.begin(), this->Children.end(), childCache);
if(childIt == this->Children.end())
return;
std::vector<double>& visibleTimes = ChildVisibleAtTimes[childIt - this->Children.begin()];
auto timeIt = std::find(visibleTimes.begin(), visibleTimes.end(), timeCode);
if(timeIt == visibleTimes.end())
visibleTimes.push_back(timeCode);
}
bool UsdBridgePrimCache::SetChildInvisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode)
{
auto childIt = std::find(this->Children.begin(), this->Children.end(), childCache);
if(childIt == this->Children.end())
return false;
std::vector<double>& visibleTimes = ChildVisibleAtTimes[childIt - this->Children.begin()];
auto timeIt = std::find(visibleTimes.begin(), visibleTimes.end(), timeCode);
if(timeIt != visibleTimes.end())
{
// Remove the time at visibleTimeIdx
size_t visibleTimeIdx = timeIt - visibleTimes.begin();
visibleTimes[visibleTimeIdx] = visibleTimes.back();
visibleTimes.pop_back();
return visibleTimes.size() == 0; // Return child removed && empty
}
return false;
}
#endif
#ifdef VALUE_CLIP_RETIMING
const UsdStagePair& UsdBridgePrimCache::GetPrimStagePair() const
{
auto it = ClipStages.find(PrimStageTimeCode);
assert(it != ClipStages.end());
return it->second;
}
#endif
void UsdBridgePrimCache::AddChild(UsdBridgePrimCache* child)
{
if(std::find(this->Children.begin(), this->Children.end(), child) != this->Children.end())
return;
this->Children.push_back(child);
child->IncRef();
#ifdef TIME_BASED_CACHING
this->ChildVisibleAtTimes.resize(this->Children.size());
#endif
}
void UsdBridgePrimCache::RemoveChild(UsdBridgePrimCache* child)
{
auto it = std::find(this->Children.begin(), this->Children.end(), child);
// Allow for find to fail; in the case where the bridge is recreated and destroyed,
// a child prim exists which doesn't have a ref in the cache.
if(it != this->Children.end())
{
#ifdef TIME_BASED_CACHING
size_t foundIdx = it - this->Children.begin();
if(foundIdx != this->ChildVisibleAtTimes.size()-1)
this->ChildVisibleAtTimes[foundIdx] = std::move(this->ChildVisibleAtTimes.back());
this->ChildVisibleAtTimes.pop_back();
#endif
child->DecRef();
*it = this->Children.back();
this->Children.pop_back();
}
}
void UsdBridgePrimCache::RemoveUnreferencedChildTree(AtRemoveFunc atRemove)
{
assert(this->RefCount == 0);
atRemove(this);
for (UsdBridgePrimCache* child : this->Children)
{
child->DecRef();
if(child->RefCount == 0)
child->RemoveUnreferencedChildTree(atRemove);
}
this->Children.clear();
}
bool UsdBridgePrimCache::AddResourceKey(UsdBridgeResourceKey key) // copy by value
{
assert(ResourceKeys);
bool newEntry = std::find(ResourceKeys->begin(), ResourceKeys->end(), key) == ResourceKeys->end();
if(newEntry)
ResourceKeys->push_back(key);
return newEntry;
}
UsdBridgePrimCacheManager::ConstPrimCacheIterator UsdBridgePrimCacheManager::FindPrimCache(const UsdBridgeHandle& handle) const
{
ConstPrimCacheIterator it = std::find_if(
UsdPrimCaches.begin(),
UsdPrimCaches.end(),
[handle](const PrimCacheContainer::value_type& cmp) -> bool { return cmp.second.get() == handle.value; }
);
return it;
}
UsdBridgePrimCacheManager::ConstPrimCacheIterator UsdBridgePrimCacheManager::CreatePrimCache(const std::string& name, const std::string& fullPath, ResourceCollectFunc collectFunc)
{
SdfPath nameSuffix(name);
SdfPath primPath(fullPath);
// Create new cache entry
std::unique_ptr<UsdBridgePrimCache> cacheEntry = std::make_unique<UsdBridgePrimCache>(primPath, nameSuffix, collectFunc);
return UsdPrimCaches.emplace(name, std::move(cacheEntry)).first;
}
void UsdBridgePrimCacheManager::AttachTopLevelPrim(UsdBridgePrimCache* primCache)
{
primCache->IncRef();
}
void UsdBridgePrimCacheManager::DetachTopLevelPrim(UsdBridgePrimCache* primCache)
{
primCache->DecRef();
}
void UsdBridgePrimCacheManager::AddChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child)
{
parent->AddChild(child);
}
void UsdBridgePrimCacheManager::RemoveChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child)
{
parent->RemoveChild(child);
}
void UsdBridgePrimCacheManager::RemovePrimCache(ConstPrimCacheIterator it, UsdBridgeLogObject& LogObject)
{
if(it->second->RefCount > 0)
{
UsdBridgeLogMacro(LogObject, UsdBridgeLogLevel::WARNING, "Primcache removed for object named: " << it->first << ", but refs still exist");
}
UsdPrimCaches.erase(it);
}
void UsdBridgePrimCacheManager::RemoveUnreferencedPrimCaches(AtRemoveFunc atRemove)
{
// First recursively remove all the child references for unreferenced prims
// Can only be performed at garbage collect.
// If this is done during RemoveChild, an unreferenced parent cannot subsequently be revived with an AddChild.
PrimCacheContainer::iterator it = UsdPrimCaches.begin();
while (it != UsdPrimCaches.end())
{
if (it->second->RefCount == 0)
{
it->second->RemoveUnreferencedChildTree(atRemove);
}
++it;
}
// Now delete all prims without references from the cache
it = UsdPrimCaches.begin();
while (it != UsdPrimCaches.end())
{
if (it->second->RefCount == 0)
it = UsdPrimCaches.erase(it);
else
++it;
}
} | 6,353 | C++ | 29.84466 | 179 | 0.728947 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Mdl/UsdBridgeMdlStrings.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeMacros.h"
#ifdef CUSTOM_PBR_MDL
static const char Mdl_PBRBase_string[] = R"matstrdelim(
/*****************************************************************************
* Copyright 1986-2017 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 df::*;
import state::*;
import math::*;
import base::*;
import tex::*;
import anno::*;
import ::nvidia::core_definitions::file_texture;
import ::nvidia::core_definitions::normalmap_texture;
// -------------------- HELPER FUNCTIONS ----------------------
base::texture_return multiply_colors(
color color_1 = color(1.0, 1.0, 1.0),
color color_2 = color(.5, .5, .5),
float weight = 1.0
) [[
anno::hidden()
]]
{
return base::blend_color_layers(
layers: base::color_layer[](
base::color_layer(
layer_color: color_2,
weight: weight,
mode: base::color_layer_multiply
)),
base: color_1
);
}
float4 vertex_color_from_coordinate(int VertexColorCoordinateIndex)
[[
anno::description("Vertex Color for float2 PrimVar"),
anno::noinline()
]]
{
// Kit only supports 4 uv sets, 2 uvs are available to vertex color. if vertex color index is invalid, output the constant WHITE color intead
return (VertexColorCoordinateIndex > 2) ? float4(1.0f) : float4(state::texture_coordinate(VertexColorCoordinateIndex).x, state::texture_coordinate(VertexColorCoordinateIndex).y, state::texture_coordinate(VertexColorCoordinateIndex+1).x, state::texture_coordinate(VertexColorCoordinateIndex+1).y);
}
color get_translucent_tint(color base_color, float opacity)
[[
anno::description("base color of Basic translucent"),
anno::noinline()
]]
{
return math::lerp(color(1.0), base_color, opacity);
}
tex::wrap_mode get_wrap_mode(int wrap_constant)
{
tex::wrap_mode result = tex::wrap_clip;
switch(wrap_constant)
{
case 1: result = tex::wrap_clamp; break;
case 2: result = tex::wrap_repeat; break;
case 3: result = tex::wrap_mirrored_repeat; break;
default: break;
}
return result;
}
// -------------------- MATERIAL ----------------------
export material OmniPBR(
color diffuse_color_constant = color(0.2f)
[[
anno::display_name("Base Color"),
anno::description("This is the base color"),
anno::in_group("Albedo")
]],
uniform texture_2d diffuse_texture = texture_2d()
[[
anno::display_name("Albedo Map"),
anno::in_group("Albedo")
]],
float albedo_desaturation = float(0.0)
[[
anno::display_name("Albedo Desaturation"),
anno::soft_range(float(0.0f), float(1.0f)),
anno::description("Desaturates the diffuse color"),
anno::in_group("Albedo")
]],
float albedo_add = float(0.0)
[[
anno::display_name("Albedo Add"),
anno::soft_range(float(-1.0f), float(1.0f)),
anno::description("Adds a constant value to the diffuse color "),
anno::in_group("Albedo")
]],
float albedo_brightness = float(1.0)
[[
anno::display_name("Albedo Brightness"),
anno::soft_range(float(0.0f), float(1.0f)),
anno::description("Multiplier for the diffuse color "),
anno::in_group("Albedo")
]],
color diffuse_tint = color(1.0f)
[[
anno::display_name("Color Tint"),
anno::description("When enabled, this color value is multiplied over the final albedo color"),
anno::in_group("Albedo")
]],
// -------------------- REFLECTIVITY/METALLIC ----------------------
float reflection_roughness_constant = 0.5f
[[
anno::display_name("Roughness Amount"),
anno::hard_range(0.0,1.),
anno::description("Higher roughness values lead to more blurry reflections"),
anno::in_group("Reflectivity")
]],
float reflection_roughness_texture_influence = 0.0f
[[
anno::display_name("Roughness Map Influence"),
anno::hard_range(0.0, 1.),
anno::description("Blends between the constant value and the lookup of the roughness texture"),
anno::in_group("Reflectivity")
]],
uniform texture_2d reflection_roughness_texture = texture_2d()
[[
anno::display_name("Roughness Map"),
anno::in_group("Reflectivity")
]],
float metallic_constant = 0.f
[[
anno::display_name("Metallic Amount"),
anno::hard_range(0.0,1.),
anno::description("Metallic Material"),
anno::in_group("Reflectivity")
]],
float metallic_texture_influence = 0.0f
[[
anno::display_name("Metallic Map Influence"),
anno::hard_range(0.0, 1.),
anno::description("Blends between the constant value and the lookup of the metallic texture"),
anno::in_group("Reflectivity")
]],
uniform texture_2d metallic_texture = texture_2d()
[[
anno::display_name("Metallic Map"),
anno::in_group("Reflectivity")
]],
float specular_level = float(0.5)
[[
anno::display_name("Specular"),
anno::soft_range(float(0.0f), float(1.0f)),
anno::description("The specular level (intensity) of the material"),
anno::in_group("Reflectivity")
]],
// -------------------- EMISSIVE ----------------------
uniform bool enable_emission = false
[[
anno::display_name("Enable Emission"),
anno::description("Enables the emission of light from the material"),
anno::in_group("Emissive")
]],
color emissive_color = color(1.0, 0.1, 0.1)
[[
anno::enable_if("enable_emission == true"),
anno::display_name("Emissive Color"),
anno::description("The emission color"),
anno::in_group("Emissive")
]],
uniform texture_2d emissive_mask_texture = texture_2d()
[[
anno::enable_if("enable_emission == true"),
anno::display_name("Emissive Mask map"),
anno::description("The texture masking the emissive color"),
anno::in_group("Emissive")
]],
uniform float emissive_intensity = 40.f
[[
anno::enable_if("enable_emission == true"),
anno::display_name("Emissive Intensity"),
anno::description("Intensity of the emission"),
anno::in_group("Emissive")
]],
// Opacity Map
uniform bool enable_opacity_texture = false
[[
anno::display_name("Enable Opacity Texture"),
anno::description("Enables or disbales the usage of the opacity texture map"),
anno::in_group("Opacity")
]],
uniform float opacity_constant = 1.0f
[[
anno::enable_if("enable_opacity_texture == true"),
anno::hard_range(0.0, 1.0),
anno::display_name("Opacity Amount"),
anno::description("Amount of Opacity"),
anno::in_group("Opacity")
]],
uniform texture_2d opacity_texture = texture_2d()
[[
anno::enable_if("enable_opacity_texture==true"),
anno::display_name("Opacity Map"),
anno::in_group("Opacity")
]],
uniform float ior_constant = 1.f
[[
anno::enable_if("opacity_constant < 1.0"),
anno::display_name("Index of Refraction"),
anno::description("Index of Refraction for transparent materials"),
anno::in_group("Opacity")
]],
// -------------------- Normal ----------------------
uniform float bump_factor = 1.f
[[
anno::display_name("Normal Map Strength"),
anno::description("Strength of normal map."),
anno::in_group("Normal")
]],
uniform texture_2d normalmap_texture = texture_2d()
[[
anno::display_name("Normal Map"),
anno::description("Enables the usage of the normalmap texture"),
anno::in_group("Normal")
]],
// -------------------- Vertex Colors ----------------------
uniform int vertexcolor_coordinate_index = -1
[[
anno::display_name("Vertex Color Texture Coordinate Index"),
anno::description("Index for texture coordinate with vertex colors"),
anno::in_group("VertexColor")
]],
// -------------------- Wrapping ----------------------
uniform int diffuse_wrapmode_u = 2
[[
anno::display_name("Diffuse Wrapping Mode U"),
anno::description("Wrapping mode along u axis of diffuse_texture, see get_wrap_mode"),
anno::in_group("Texture")
]],
uniform int diffuse_wrapmode_v = 2
[[
anno::display_name("Diffuse Wrapping Mode V"),
anno::description("Wrapping mode along v axis of diffuse_texture, see get_wrap_mode"),
anno::in_group("Texture")
]]
)
[[
anno::display_name("PBR Opacity"),
anno::description("PBR material, supports opacity"),
anno::version( 1, 0, 0),
anno::author("NVIDIA CORPORATION"),
anno::key_words(string[]("PBR", "generic"))
]]
= let{
// -------------------- Texcoord --------------------
int uv_space_index = 0;
base::texture_coordinate_info uvw = base::coordinate_source(
coordinate_system: base::texture_coordinate_uvw,
texture_space: uv_space_index );
base::texture_coordinate_info transformed_uvw = uvw;
// -------------------- Base texture --------------------
base::texture_return base_lookup = base::file_texture(
texture: diffuse_texture,
color_offset: color(albedo_add),
color_scale: color(albedo_brightness),
mono_source: base::mono_luminance,
uvw: transformed_uvw,
wrap_u: get_wrap_mode(diffuse_wrapmode_u),
wrap_v: get_wrap_mode(diffuse_wrapmode_v),
clip: false);
float alpha = tex::texture_isvalid(diffuse_texture) ? base::file_texture(
texture: diffuse_texture,
mono_source: base::mono_alpha,
uvw: transformed_uvw,
wrap_u: get_wrap_mode(diffuse_wrapmode_u),
wrap_v: get_wrap_mode(diffuse_wrapmode_v),
clip: false).mono
: 1.0;
// -------------------- Rougness/Reflection --------------------
base::texture_return roughness_lookup = base::file_texture(
texture: reflection_roughness_texture,
mono_source: base::mono_average,
uvw: transformed_uvw,
clip: false
);
float roughness_selection = roughness_lookup.mono;
float reflection_roughness_1 = math::lerp(reflection_roughness_constant, roughness_selection, reflection_roughness_texture_influence);
color desaturated_base = math::lerp(base_lookup.tint, color(base_lookup.mono), albedo_desaturation);
// -------------------- Metallic --------------------
base::texture_return metallic_lookup = base::file_texture(
texture: metallic_texture,
color_offset: color(0.0, 0.0, 0.0),
color_scale: color(1.0, 1.0, 1.0),
mono_source: base::mono_average,
uvw: transformed_uvw,
clip: false
);
// Choose between ORM or metallic map
float metallic_selection = metallic_lookup.mono;
// blend between the constant metallic value and the map lookup
float metallic = math::lerp(metallic_constant, metallic_selection, metallic_texture_influence);
// -------------------- Emissive --------------------
color emissive_mask = tex::texture_isvalid(emissive_mask_texture) ?
base::file_texture(
texture: emissive_mask_texture,
color_offset: color(0.0, 0.0, 0.0),
color_scale: color(1.0, 1.0, 1.0),
mono_source: base::mono_average,
uvw: transformed_uvw,
clip: false).tint
: color(1.0);
// -------------------- Normal --------------------
float3 the_normal = tex::texture_isvalid(normalmap_texture) ?
base::tangent_space_normal_texture(
texture: normalmap_texture,
factor: bump_factor,
uvw: transformed_uvw
//flip_tangent_u: false,
//flip_tangent_v: true
) : state::normal() ;
float3 final_normal = the_normal;
// -------------------- Opacity --------------------
float final_opacity = enable_opacity_texture ?
base::file_texture(
texture: opacity_texture,
mono_source: base::mono_average,
uvw: transformed_uvw ).mono
: (opacity_constant > 0 ? opacity_constant*alpha : alpha);
// -------------------- Establish base color --------------------
float4 vcData = vertex_color_from_coordinate(vertexcolor_coordinate_index);
color diffuse_color = tex::texture_isvalid(diffuse_texture) ? desaturated_base :
((vertexcolor_coordinate_index >= 0 && vertexcolor_coordinate_index < state::texture_space_max()) ? color(vcData.x, vcData.y, vcData.z) : diffuse_color_constant);
color tinted_diffuse_color = multiply_colors(diffuse_color, diffuse_tint, 1.0).tint;
color final_base_color = tinted_diffuse_color;
// -------------------- Construct bsdf --------------------
float reflection_roughness_sq = reflection_roughness_1*reflection_roughness_1;
)matstrdelim";
static const char Mdl_PBRBase_string_opaque[] = R"matstrdelim(
bsdf diffuse_bsdf = df::diffuse_reflection_bsdf(
tint: final_base_color,
roughness: 0.f );
bsdf ggx_smith_bsdf = df::microfacet_ggx_smith_bsdf(
roughness_u: reflection_roughness_sq,
roughness_v: reflection_roughness_sq,
tint: color(1.0, 1.0, 1.0),
mode: df::scatter_reflect );
bsdf custom_curve_layer_bsdf = df::custom_curve_layer(
normal_reflectivity: 0.08,
grazing_reflectivity: 1.0,
exponent: 5.0,
weight: specular_level,
layer: ggx_smith_bsdf,
base: diffuse_bsdf );
bsdf directional_factor_bsdf = df::directional_factor(
normal_tint: final_base_color,
grazing_tint: final_base_color,
exponent: 3.0f,
base: ggx_smith_bsdf );
bsdf final_bsdf = df::weighted_layer(
weight: metallic,
layer: directional_factor_bsdf,
base: custom_curve_layer_bsdf );
} in material(
surface: material_surface(
scattering: final_bsdf,
emission: material_emission (
df::diffuse_edf(),
intensity: enable_emission? emissive_color * emissive_mask * color(emissive_intensity) : color(0)
)
),
geometry: material_geometry(
normal: final_normal,
cutout_opacity: final_opacity
)
);
)matstrdelim";
static const char Mdl_PBRBase_string_translucent[] = R"matstrdelim(
bsdf ggx_smith_bsdf = df::microfacet_ggx_smith_bsdf(
roughness_u: reflection_roughness_sq,
roughness_v: reflection_roughness_sq,
tint: get_translucent_tint(base_color: final_base_color, opacity: final_opacity),
mode: df::scatter_reflect_transmit
);
bsdf directional_factor_bsdf = df::directional_factor(
normal_tint: final_base_color,
grazing_tint: final_base_color,
exponent: 3.0f,
base: ggx_smith_bsdf );
bsdf final_bsdf = df::weighted_layer(
weight: metallic,
layer: directional_factor_bsdf,
base: ggx_smith_bsdf );
} in material(
thin_walled: true,
ior: color(ior_constant),
surface: material_surface(
scattering: final_bsdf,
emission: material_emission (
df::diffuse_edf(),
intensity: enable_emission? emissive_color * emissive_mask * color(emissive_intensity) : color(0)
)
),
geometry: material_geometry(
normal: final_normal,
cutout_opacity: 1.0
)
);
)matstrdelim";
#endif
| 16,262 | C | 32.462963 | 297 | 0.604846 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Volume/UsdBridgeVolumeWriter.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeVolumeWriter_h
#define UsdBridgeVolumeWriter_h
#include "UsdBridgeData.h"
#ifdef _WIN32
#define USDDevice_DECL __cdecl
#ifdef UsdBridge_Volume_EXPORTS
#define USDDevice_INTERFACE __declspec(dllexport)
#else
#define USDDevice_INTERFACE __declspec(dllimport)
#endif
#else
#define USDDevice_DECL
#define USDDevice_INTERFACE
#endif
class UsdBridgeVolumeWriterI
{
public:
virtual bool Initialize(const UsdBridgeLogObject& logObj) = 0;
virtual void ToVDB(const UsdBridgeVolumeData& volumeData) = 0;
virtual void GetSerializedVolumeData(const char*& data, size_t& size) = 0;
virtual void SetConvertDoubleToFloat(bool convert) = 0;
virtual void Release() = 0; // Accommodate change of CRT
};
extern "C" USDDevice_INTERFACE UsdBridgeVolumeWriterI* USDDevice_DECL Create_VolumeWriter();
#endif | 908 | C | 22.921052 | 92 | 0.770925 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Volume/UsdBridgeVolumeWriter.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeVolumeWriter.h"
#include <memory>
class UsdBridgeVolumeWriterInternals;
class UsdBridgeVolumeWriter : public UsdBridgeVolumeWriterI
{
public:
UsdBridgeVolumeWriter();
~UsdBridgeVolumeWriter();
bool Initialize(const UsdBridgeLogObject& logObj) override;
void ToVDB(const UsdBridgeVolumeData& volumeData) override;
void GetSerializedVolumeData(const char*& data, size_t& size) override;
void SetConvertDoubleToFloat(bool convert) override { ConvertDoubleToFloat = convert; }
void Release() override;
UsdBridgeLogObject LogObject;
protected:
bool ConvertDoubleToFloat = true;
#ifdef USE_OPENVDB
std::unique_ptr<UsdBridgeVolumeWriterInternals> Internals;
#endif
};
extern "C" UsdBridgeVolumeWriterI* USDDevice_DECL Create_VolumeWriter()
{
return new UsdBridgeVolumeWriter();
}
void UsdBridgeVolumeWriter::Release()
{
delete this;
}
#ifdef USE_OPENVDB
#include "openvdb/openvdb.h"
#include "openvdb/io/Stream.h"
#include "openvdb/tools/Dense.h"
#include "openvdb/tools/GridTransformer.h"
#include "openvdb/tree/ValueAccessor.h"
#include <assert.h>
#include <limits>
#include <sstream>
#include "UsdBridgeUtils.h"
#ifdef USDBRIDGE_VOL_FLOAT1_OUTPUT
using ColorGridOutType = openvdb::FloatGrid;
#else
using ColorGridOutType = openvdb::Vec3fGrid;
#endif
using OpacityGridOutType = openvdb::FloatGrid;
class UsdBridgeVolumeWriterInternals
{
public:
UsdBridgeVolumeWriterInternals()
//: GridStream(std::ios::in | std::ios::out)
{}
~UsdBridgeVolumeWriterInternals()
{}
std::ostream& ResetStream()
{
//GridStream.clear(); // Bug in OpenVDB prevents reuse of stream
delete GridStream;
GridStream = new std::stringstream(std::ios::in | std::ios::out);
return *GridStream;
}
const char* GetStreamData()
{
if(!GridStream)
return nullptr;
StreamData = GridStream->str();
return StreamData.c_str();
}
size_t GetStreamDataSize()
{
return StreamData.length();
}
protected:
std::stringstream* GridStream = nullptr;
std::string StreamData;
};
struct TfTransformInput
{
ColorGridOutType::Ptr colorGrid;
OpacityGridOutType::Ptr opacityGrid;
const UsdBridgeVolumeData& volumeData;
const openvdb::CoordBBox& bBox;
};
template<typename DataType, typename OpType, typename TransformerType>
struct TfTransform
{
public:
TfTransform(const UsdBridgeVolumeData& volumeData, const openvdb::CoordBBox& bBox, const TransformerType& transformer)
: Transformer(transformer)
, VolData(static_cast<const DataType*>(volumeData.Data))
, Dims(bBox.max() + openvdb::math::Coord(1, 1, 1)) //Bbox is inclusive, dims are exclusive
, InvValueRangeMag(OpType(1.0) / (OpType)(volumeData.TfData.TfValueRange[1] - volumeData.TfData.TfValueRange[0]))
, ValueRangeMin((OpType)(volumeData.TfData.TfValueRange[0]))
{
}
inline void operator()(const typename TransformerType::Iter& iter) const
{
openvdb::math::Coord coord = iter.getCoord();
assert(coord.x() >= 0 && coord.x() < Dims.x() &&
coord.y() >= 0 && coord.y() < Dims.y() &&
coord.z() >= 0 && coord.z() < Dims.z());
size_t linearIndex = Dims.y() * Dims.x() * coord.z() + Dims.x() * coord.y() + coord.x();
const DataType* curVal = VolData + linearIndex;
OpType ucVal = (((OpType)(*curVal)) - this->ValueRangeMin) * this->InvValueRangeMag;
float normValue = (float)((ucVal < (OpType)0.0) ? (OpType)0.0 : ((ucVal > (OpType)1.0) ? (OpType)1.0 : ucVal));
Transformer.Transform(normValue, iter);
}
/*
inline void operator()(
const openvdb::FloatGrid::ValueOnCIter& iter,
openvdb::tree::ValueAccessor<TreeOutType>& accessor)
{
openvdb::Vec4f transformedColor;
transformColor(*iter, transformedColor);
if (iter.isVoxelValue())
{ // set a single voxel
accessor.setValue(iter.getCoord(), transformedColor);
}
else
{ // fill an entire tile
openvdb::CoordBBox bbox;
iter.getBoundingBox(bbox);
accessor.getTree()->fill(bbox, transformedColor);
}
}
*/
const TransformerType& Transformer;
const DataType* VolData;
openvdb::math::Coord Dims;
OpType InvValueRangeMag;
OpType ValueRangeMin;
};
struct TfColorTransformer
{
public:
typedef ColorGridOutType::ValueOnIter Iter;
TfColorTransformer(const UsdBridgeTfData& tfData)
: TfColors(static_cast<const float*>(tfData.TfColors))
, NumTfColors(tfData.TfNumColors)
{
}
inline void Transform(float normValue, const Iter& iter) const
{
openvdb::Vec3f transformedColor;
float colorIndexF = normValue * (this->NumTfColors - 1);
float floorColor;
float fracColor = std::modf(colorIndexF, &floorColor);
int colIdx0 = int(floorColor);
int colIdx1 = colIdx0 + (colIdx0 != (this->NumTfColors - 1));
const float* color0 = this->TfColors + 3 * colIdx0;
const float* color1 = this->TfColors + 3 * colIdx1;
float OneMinFracColor = 1.0f - fracColor;
transformedColor[0] = fracColor * color1[0] + OneMinFracColor * color0[0];
transformedColor[1] = fracColor * color1[1] + OneMinFracColor * color0[1];
transformedColor[2] = fracColor * color1[2] + OneMinFracColor * color0[2];
#ifdef FLOAT1_OUTPUT
iter.setValue(transformedColor.length());
#else
iter.setValue(transformedColor);
#endif
}
const float* TfColors;
int NumTfColors;
};
struct TfOpacityTransformer
{
public:
typedef OpacityGridOutType::ValueOnIter Iter;
TfOpacityTransformer(const UsdBridgeTfData& tfData)
: TfOpacities(static_cast<const float*>(tfData.TfOpacities))
, NumTfOpacities(tfData.TfNumOpacities)
{
}
inline void Transform(float normValue, const Iter& iter) const
{
float opacityIndexF = normValue * (this->NumTfOpacities - 1);
float floorOpacity;
float fracOpacity = std::modf(opacityIndexF, &floorOpacity);
int opacityIdx0 = int(floorOpacity);
int opacityIdx1 = opacityIdx0 + (opacityIdx0 != (this->NumTfOpacities - 1));
float finalOpacity = fracOpacity * this->TfOpacities[opacityIdx1] +
(1.0f - fracOpacity) * this->TfOpacities[opacityIdx0];
iter.setValue(finalOpacity);
}
const float* TfOpacities;
int NumTfOpacities;
};
template<typename DataType, typename OpType>
void TfTransformCall(TfTransformInput& tfTransformInput)
{
TfColorTransformer colorTransformer(tfTransformInput.volumeData.TfData);
TfTransform<DataType, OpType, TfColorTransformer> tfColorTransform(tfTransformInput.volumeData, tfTransformInput.bBox, colorTransformer);
openvdb::tools::foreach(tfTransformInput.colorGrid->beginValueOn(), tfColorTransform);
TfOpacityTransformer opacityTransformer(tfTransformInput.volumeData.TfData);
TfTransform<DataType, OpType, TfOpacityTransformer> tfOpacityTransform(tfTransformInput.volumeData, tfTransformInput.bBox, opacityTransformer);
openvdb::tools::foreach(tfTransformInput.opacityGrid->beginValueOn(), tfOpacityTransform);
}
static void SelectTfTransform(const UsdBridgeLogObject& logObj, TfTransformInput& tfTransformInput)
{
// Transform the float data to color data
switch (tfTransformInput.volumeData.DataType)
{
case UsdBridgeType::CHAR:
TfTransformCall<char, float>(tfTransformInput);
break;
case UsdBridgeType::UCHAR:
TfTransformCall<unsigned char, float>(tfTransformInput);
break;
case UsdBridgeType::SHORT:
TfTransformCall<short, float>(tfTransformInput);
break;
case UsdBridgeType::USHORT:
TfTransformCall<unsigned short, float>(tfTransformInput);
break;
case UsdBridgeType::INT:
TfTransformCall<int, double>(tfTransformInput);
break;
case UsdBridgeType::UINT:
TfTransformCall<unsigned int, double>(tfTransformInput);
break;
case UsdBridgeType::LONG:
TfTransformCall<long long, double>(tfTransformInput);
break;
case UsdBridgeType::ULONG:
TfTransformCall<unsigned long long, double>(tfTransformInput);
break;
case UsdBridgeType::FLOAT:
TfTransformCall<float, float>(tfTransformInput);
break;
case UsdBridgeType::DOUBLE:
TfTransformCall<double, double>(tfTransformInput);
break;
default:
{
const char* typeStr = ubutils::UsdBridgeTypeToString(tfTransformInput.volumeData.DataType);
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "Volume writer preclassified copy does not support source data type: " << typeStr);
break;
}
}
//openvdb::tools::transformValues(valArray->cbeginValueOn(), *colorGrid, transformOp);
}
struct CopyToGridInput
{
const UsdBridgeVolumeData& volumeData;
const openvdb::CoordBBox& bBox;
};
struct DoublePH // placeholder for double type to implicitly convert to float without warnings
{
public:
DoublePH(double val) : v(val) {}
~DoublePH() {}
operator float() const { return static_cast<float>(v); }
protected:
double v;
};
template<typename InDataType, typename OutGridType>
struct GridConvert
{
GridConvert(const UsdBridgeVolumeData& volumeData, const openvdb::CoordBBox& bBox, bool normalize = true)
: VolData(static_cast<const InDataType*>(volumeData.Data))
, Dims(bBox.max() + openvdb::math::Coord(1, 1, 1)) //Bbox is inclusive, dims are exclusive
, BackgroundIdx(volumeData.BackgroundIdx)
{
}
inline void operator()(const typename OutGridType::ValueOnIter& iter) const
{
openvdb::math::Coord coord = iter.getCoord();
assert(coord.x() >= 0 && coord.x() < Dims.x() &&
coord.y() >= 0 && coord.y() < Dims.y() &&
coord.z() >= 0 && coord.z() < Dims.z());
size_t linearIndex = Dims.y() * Dims.x() * coord.z() + Dims.x() * coord.y() + coord.x();
const InDataType* curVal = VolData + linearIndex;
typename OutGridType::ValueType outVal(*curVal);
iter.setValue(outVal);
}
typename OutGridType::ValueType BackgroundValue()
{
if(BackgroundIdx == -1)
{
return typename OutGridType::ValueType(0);
}
const InDataType* backVal = VolData + BackgroundIdx;
typename OutGridType::ValueType outVal(*backVal);
return outVal;
}
const InDataType* VolData;
openvdb::math::Coord Dims;
long long BackgroundIdx;
};
template<typename DataType>
struct NormalizedToGridConvert
{
NormalizedToGridConvert(const UsdBridgeVolumeData& volumeData, const openvdb::CoordBBox& bBox)
: VolData(static_cast<const DataType*>(volumeData.Data))
, Dims(bBox.max() + openvdb::math::Coord(1, 1, 1)) //Bbox is inclusive, dims are exclusive
, MaxValue(static_cast<float>(std::numeric_limits<DataType>::max()))
, MinValue(static_cast<float>(std::numeric_limits<DataType>::min()))
, BackgroundIdx(volumeData.BackgroundIdx)
{
InvRange = 1.0f / (MaxValue - MinValue);
}
inline void operator()(const openvdb::FloatGrid::ValueOnIter& iter) const
{
openvdb::math::Coord coord = iter.getCoord();
assert(coord.x() >= 0 && coord.x() < Dims.x() &&
coord.y() >= 0 && coord.y() < Dims.y() &&
coord.z() >= 0 && coord.z() < Dims.z());
size_t linearIndex = Dims.y() * Dims.x() * coord.z() + Dims.x() * coord.y() + coord.x();
const DataType* curVal = VolData + linearIndex;
iter.setValue(((static_cast<float>(*curVal)) - MinValue) * InvRange);
}
float BackgroundValue()
{
return (BackgroundIdx == -1) ? 0.0f :
(static_cast<float>(*(VolData + BackgroundIdx)) - MinValue) * InvRange;
}
const DataType* VolData;
openvdb::math::Coord Dims;
float MaxValue;
float MinValue;
float InvRange;
long long BackgroundIdx;
};
template<typename InDataType, typename OutGridType>
openvdb::GridBase::Ptr ConvertAndCopyToGridTemplate(const CopyToGridInput& copyInput)
{
GridConvert<InDataType, OutGridType> gridConverter(copyInput.volumeData, copyInput.bBox);
typename OutGridType::Ptr outGrid = OutGridType::create(gridConverter.BackgroundValue());
typename OutGridType::ValueType defaultValue(0);
outGrid->denseFill(copyInput.bBox, defaultValue, true);
openvdb::tools::foreach(outGrid->beginValueOn(), gridConverter);
return outGrid;
}
template<typename DataType>
openvdb::GridBase::Ptr NormalizedCopyToGridTemplate(const CopyToGridInput& copyInput)
{
NormalizedToGridConvert<DataType> gridConverter(copyInput.volumeData, copyInput.bBox);
openvdb::FloatGrid::Ptr floatGrid = openvdb::FloatGrid::create(gridConverter.BackgroundValue());
floatGrid->denseFill(copyInput.bBox, 0.0f, true);
openvdb::tools::foreach(floatGrid->beginValueOn(), gridConverter);
return floatGrid;
}
template<typename DataType, typename GridType>
openvdb::GridBase::Ptr CopyToGridTemplate(const CopyToGridInput& copyInput)
{
const DataType* typedData = static_cast<const DataType*>(copyInput.volumeData.Data);
long long backgroundIdx = copyInput.volumeData.BackgroundIdx;
typename GridType::ValueType backGroundValue( (backgroundIdx == -1) ?
static_cast<DataType>(0) : *(typedData + backgroundIdx)
);
typename GridType::Ptr scalarGrid = GridType::create(backGroundValue);
openvdb::tools::Dense<const DataType, openvdb::tools::LayoutXYZ> valArray(copyInput.bBox, typedData);
openvdb::tools::copyFromDense(valArray, *scalarGrid, (DataType)0); // No tolerance set to clamp values to background value for sparsity.
return scalarGrid;
}
static openvdb::GridBase::Ptr CopyToGrid(const UsdBridgeLogObject& logObj, const CopyToGridInput& copyInput, bool convertDoubleToFloat)
{
openvdb::GridBase::Ptr scalarGrid;
// Transform the float data to color data
switch (copyInput.volumeData.DataType)
{
case UsdBridgeType::CHAR:
scalarGrid = NormalizedCopyToGridTemplate<char>(copyInput);
break;
case UsdBridgeType::UCHAR:
scalarGrid = NormalizedCopyToGridTemplate<unsigned char>(copyInput);
break;
case UsdBridgeType::SHORT:
scalarGrid = NormalizedCopyToGridTemplate<short>(copyInput);
break;
case UsdBridgeType::USHORT:
scalarGrid = NormalizedCopyToGridTemplate<unsigned short>(copyInput);
break;
case UsdBridgeType::INT:
scalarGrid = CopyToGridTemplate<int, openvdb::Int32Grid>(copyInput);
break;
case UsdBridgeType::UINT:
scalarGrid = CopyToGridTemplate<unsigned int, openvdb::Int32Grid>(copyInput);
break;
case UsdBridgeType::LONG:
scalarGrid = CopyToGridTemplate<long long, openvdb::Int64Grid>(copyInput);
break;
case UsdBridgeType::ULONG:
scalarGrid = CopyToGridTemplate<unsigned long long, openvdb::Int64Grid>(copyInput);
break;
case UsdBridgeType::FLOAT:
scalarGrid = CopyToGridTemplate<float, openvdb::FloatGrid>(copyInput);
break;
case UsdBridgeType::DOUBLE:
if(convertDoubleToFloat)
scalarGrid = ConvertAndCopyToGridTemplate<DoublePH, openvdb::FloatGrid>(copyInput);
else
scalarGrid = CopyToGridTemplate<double, openvdb::DoubleGrid>(copyInput);
break;
case UsdBridgeType::FLOAT3:
scalarGrid = CopyToGridTemplate<openvdb::Vec3f, openvdb::Vec3fGrid>(copyInput);
break;
case UsdBridgeType::DOUBLE3:
if(convertDoubleToFloat)
scalarGrid = ConvertAndCopyToGridTemplate<openvdb::Vec3d, openvdb::Vec3fGrid>(copyInput);
else
scalarGrid = CopyToGridTemplate<openvdb::Vec3d, openvdb::Vec3dGrid>(copyInput);
break;
default:
{
const char* typeStr = ubutils::UsdBridgeTypeToString(copyInput.volumeData.DataType);
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "Volume writer source data copy does not support source data type: " << typeStr);
}
break;
}
return scalarGrid;
}
static void CreateGridAndAdd(const UsdBridgeLogObject& logObj, const UsdBridgeVolumeData& volumeData, const openvdb::CoordBBox& bBox, const char* gridName,
openvdb::math::Transform::Ptr linTrans, bool convertDoubleToFloat, openvdb::GridPtrVecPtr grids)
{
CopyToGridInput copyToGridInput = { volumeData, bBox };
openvdb::GridBase::Ptr outGrid = CopyToGrid(logObj, copyToGridInput, convertDoubleToFloat);
if (outGrid)
{
outGrid->setName(gridName);
outGrid->setTransform(linTrans);
// Push density grid into grid container
grids->push_back(outGrid);
}
}
UsdBridgeVolumeWriter::UsdBridgeVolumeWriter()
: Internals(std::make_unique<UsdBridgeVolumeWriterInternals>())
{
}
UsdBridgeVolumeWriter::~UsdBridgeVolumeWriter()
{
}
bool UsdBridgeVolumeWriter::Initialize(const UsdBridgeLogObject& logObj)
{
openvdb::initialize();
this->LogObject = logObj;
return true;
}
void UsdBridgeVolumeWriter::ToVDB(const UsdBridgeVolumeData& volumeData)
{
const char* densityGridName = "density";
const char* colorGridName = "diffuse";
// Keep the grid/tree transform at identity, and set coord bounding box to element dimensions.
// This will correspond to a worldspace size of element dimensions too, with rest of scaling handled outside of openvdb.
const size_t* coordDims = volumeData.NumElements;
size_t maxInt = std::numeric_limits<int>::max();
assert(coordDims[0] <= maxInt && coordDims[1] <= maxInt && coordDims[2] <= maxInt);
// Wrap data in a Dense and copy to color grid
openvdb::CoordBBox bBox(0, 0, 0, int(coordDims[0] - 1), int(coordDims[1] - 1), int(coordDims[2] - 1)); //Fill is inclusive
// Compose volume transformation
openvdb::math::Transform::Ptr linTrans = openvdb::math::Transform::createLinearTransform();
linTrans->preScale(openvdb::Vec3f(volumeData.CellDimensions));
linTrans->postTranslate(openvdb::Vec3f(volumeData.Origin));
// Prepare output grids
openvdb::GridPtrVecPtr grids(new openvdb::GridPtrVec);
if(volumeData.preClassified)
{
OpacityGridOutType::Ptr opacityGrid = OpacityGridOutType::create();
ColorGridOutType::Ptr colorGrid = ColorGridOutType::create();
opacityGrid->denseFill(bBox, 0.0f, true);
colorGrid->denseFill(bBox,
#ifdef FLOAT1_OUTPUT
0.0f,
#else
openvdb::Vec3f(0, 0, 0),
#endif
true);
// Transform the volumedata and output into color grid
TfTransformInput tfTransformInput = { colorGrid, opacityGrid, volumeData, bBox };
SelectTfTransform(this->LogObject, tfTransformInput);
// Set grid names
opacityGrid->setName(densityGridName);
colorGrid->setName(colorGridName);
// Set grid transformation
opacityGrid->setTransform(linTrans);
colorGrid->setTransform(linTrans);
// Push color and opacity grid into grid container
grids->push_back(opacityGrid);
grids->push_back(colorGrid);
}
else
{
CreateGridAndAdd(this->LogObject, volumeData, bBox, densityGridName, linTrans, ConvertDoubleToFloat, grids);
}
// Must write all grids at once
openvdb::io::Stream(Internals->ResetStream()).write(*grids);
}
void UsdBridgeVolumeWriter::GetSerializedVolumeData(const char*& data, size_t& size)
{
data = Internals->GetStreamData();
size = Internals->GetStreamDataSize();
}
#else //USE_OPENVDB
UsdBridgeVolumeWriter::UsdBridgeVolumeWriter()
{
}
UsdBridgeVolumeWriter::~UsdBridgeVolumeWriter()
{
}
bool UsdBridgeVolumeWriter::Initialize(const UsdBridgeLogObject& logObj)
{
return true;
}
void UsdBridgeVolumeWriter::ToVDB(const UsdBridgeVolumeData & volumeData)
{
}
void UsdBridgeVolumeWriter::GetSerializedVolumeData(const char*& data, size_t& size)
{
data = nullptr;
size = 0;
}
#endif //USE_OPENVDB
| 19,286 | C++ | 29.614286 | 155 | 0.722597 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeNumerics.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeNumerics_h
#define UsdBridgeNumerics_h
#include "UsdBridgeMacros.h"
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#include <math.h>
struct UsdUint2
{
using DataType = unsigned int;
DataType Data[2] = { 0, 0 };
};
struct UsdFloat2
{
using DataType = float;
DataType Data[2] = { 1.0, 1.0 };
};
struct UsdFloat3
{
using DataType = float;
DataType Data[3] = { 1.0, 1.0, 1.0 };
};
struct UsdFloat4
{
using DataType = float;
DataType Data[4] = { 1.0, 1.0, 1.0, 1.0 };
};
struct UsdFloatMat4
{
using DataType = float;
DataType Data[16] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
};
struct UsdQuaternion
{
using DataType = float;
DataType Data[4] = {1.0, 0.0, 0.0, 0.0};
};
struct UsdFloatBox1
{
using DataType = float;
DataType Data[2] = { 0.0f, 1.0f };
};
struct UsdFloatBox2
{
using DataType = float;
DataType Data[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
};
namespace usdbridgenumerics
{
template<typename T>
bool isIdentity(const T& val)
{
static T identity;
return !memcmp(val.Data, identity.Data, sizeof(T));
}
inline void DirectionToQuaternionZ(float* dir, float dirLength, float* quat)
{
// Use Z axis of glyph to orient along.
// (dot(|segDir|, zAxis), cross(|segDir|, zAxis)) gives (cos(th), axis*sin(th)),
// but rotation is represented by cos(th/2), axis*sin(th/2), ie. half the amount of rotation.
// So calculate (dot(|halfVec|, zAxis), cross(|halfVec|, zAxis)) instead.
float invDirLength = 1.0f / dirLength;
float halfVec[3] = {
dir[0] * invDirLength,
dir[1] * invDirLength,
dir[2] * invDirLength + 1.0f
};
float halfNorm = sqrtf(halfVec[0] * halfVec[0] + halfVec[1] * halfVec[1] + halfVec[2] * halfVec[2]);
if (halfNorm != 0.0f)
{
float invHalfNorm = 1.0f / halfNorm;
halfVec[0] *= invHalfNorm;
halfVec[1] *= invHalfNorm;
halfVec[2] *= invHalfNorm;
}
// Cross zAxis (0,0,1) with segment direction (new Z axis) to get rotation axis * sin(angle)
float sinAxis[3] = { -halfVec[1], halfVec[0], 0.0f };
// Dot for cos(angle)
float cosAngle = halfVec[2];
if (halfNorm == 0.0f) // In this case there is a 180 degree rotation
{
sinAxis[1] = 1.0f; //sinAxis*sin(pi/2) = (0,1,0)*sin(pi/2) = (0,1,0)
// cosAngle = cos(pi/2) = 0.0f;
}
quat[0] = cosAngle;
quat[1] = sinAxis[0];
quat[2] = sinAxis[1];
quat[3] = sinAxis[2];
}
}
#endif
| 2,578 | C | 20.855932 | 104 | 0.603957 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeUtils_Internal.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeUtils_Internal_h
#define UsdBridgeUtils_Internal_h
#include "UsdBridgeData.h"
#include <cstring>
namespace
{
inline bool strEquals(const char* arg0, const char* arg1)
{
return strcmp(arg0, arg1) == 0;
}
}
#endif | 318 | C | 15.789473 | 59 | 0.72327 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeMacros.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#define USE_USD_GEOM_POINTS
#define OMNIVERSE_CREATE_WORKAROUNDS
//#define CUSTOM_PBR_MDL
#define USE_INDEX_MATERIALS
//#define REPLACE_SCENE_BY_EXTERNAL_STAGE
// To enable output that usdview can digest (just a single float)
//#define USDBRIDGE_VOL_FLOAT1_OUTPUT
#if defined(TIME_CLIP_STAGES) && !defined(VALUE_CLIP_RETIMING)
#define VALUE_CLIP_RETIMING
#endif
#if defined(VALUE_CLIP_RETIMING) && !defined(TIME_BASED_CACHING)
#define TIME_BASED_CACHING
#endif | 554 | C | 24.227272 | 65 | 0.768953 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeData.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeData_h
#define UsdBridgeData_h
#include "UsdBridgeMacros.h"
#include "UsdBridgeNumerics.h"
#include <cstddef>
#include <functional>
#include <stdint.h>
class UsdBridge;
struct UsdBridgePrimCache;
struct UsdBridgeHandle
{
UsdBridgePrimCache* value = nullptr;
};
struct UsdWorldHandle : public UsdBridgeHandle {};
struct UsdInstanceHandle : public UsdBridgeHandle {};
struct UsdGroupHandle : public UsdBridgeHandle {};
struct UsdSurfaceHandle : public UsdBridgeHandle {};
struct UsdGeometryHandle : public UsdBridgeHandle {};
struct UsdVolumeHandle : public UsdBridgeHandle {};
struct UsdSpatialFieldHandle : public UsdBridgeHandle {};
struct UsdSamplerHandle : public UsdBridgeHandle {};
struct UsdShaderHandle : public UsdBridgeHandle {};
struct UsdMaterialHandle : public UsdBridgeHandle {};
struct UsdLightHandle : public UsdBridgeHandle {};
struct UsdCameraHandle : public UsdBridgeHandle {};
enum class UsdBridgeType
{
BOOL = 0,
UCHAR,
UCHAR_SRGB_R,
CHAR,
USHORT,
SHORT,
UINT,
INT,
ULONG,
LONG,
HALF,
FLOAT,
DOUBLE,
UCHAR2,
UCHAR_SRGB_RA,
CHAR2,
USHORT2,
SHORT2,
UINT2,
INT2,
ULONG2,
LONG2,
HALF2,
FLOAT2,
DOUBLE2,
UCHAR3,
UCHAR_SRGB_RGB,
CHAR3,
USHORT3,
SHORT3,
UINT3,
INT3,
ULONG3,
LONG3,
HALF3,
FLOAT3,
DOUBLE3,
UCHAR4,
UCHAR_SRGB_RGBA,
CHAR4,
USHORT4,
SHORT4,
UINT4,
INT4,
ULONG4,
LONG4,
HALF4,
FLOAT4,
DOUBLE4,
INT_PAIR,
INT_PAIR2,
INT_PAIR3,
INT_PAIR4,
FLOAT_PAIR,
FLOAT_PAIR2,
FLOAT_PAIR3,
FLOAT_PAIR4,
DOUBLE_PAIR,
DOUBLE_PAIR2,
DOUBLE_PAIR3,
DOUBLE_PAIR4,
ULONG_PAIR,
ULONG_PAIR2,
ULONG_PAIR3,
ULONG_PAIR4,
FLOAT_MAT2,
FLOAT_MAT3,
FLOAT_MAT4,
FLOAT_MAT2x3,
FLOAT_MAT3x4,
UNDEFINED
};
constexpr int UsdBridgeNumFundamentalTypes = (int)UsdBridgeType::UCHAR2; // Multi-component groups sizes up until 4 should be equal
inline int UsdBridgeTypeNumComponents(UsdBridgeType dataType)
{
int typeIdent = (int)dataType;
if(typeIdent <= (int)UsdBridgeType::DOUBLE4)
return typeIdent / UsdBridgeNumFundamentalTypes;
switch(dataType)
{
case UsdBridgeType::INT_PAIR: return 2;
case UsdBridgeType::INT_PAIR2: return 4;
case UsdBridgeType::INT_PAIR3: return 6;
case UsdBridgeType::INT_PAIR4: return 8;
case UsdBridgeType::FLOAT_PAIR: return 2;
case UsdBridgeType::FLOAT_PAIR2: return 4;
case UsdBridgeType::FLOAT_PAIR3: return 6;
case UsdBridgeType::FLOAT_PAIR4: return 8;
case UsdBridgeType::DOUBLE_PAIR: return 2;
case UsdBridgeType::DOUBLE_PAIR2: return 4;
case UsdBridgeType::DOUBLE_PAIR3: return 6;
case UsdBridgeType::DOUBLE_PAIR4: return 8;
case UsdBridgeType::ULONG_PAIR: return 2;
case UsdBridgeType::ULONG_PAIR2: return 4;
case UsdBridgeType::ULONG_PAIR3: return 6;
case UsdBridgeType::ULONG_PAIR4: return 8;
case UsdBridgeType::FLOAT_MAT2: return 4;
case UsdBridgeType::FLOAT_MAT3: return 9;
case UsdBridgeType::FLOAT_MAT4: return 16;
case UsdBridgeType::FLOAT_MAT2x3: return 6;
case UsdBridgeType::FLOAT_MAT3x4: return 12;
default: return 1;
}
return 1;
}
enum class UsdBridgeGeomType
{
MESH = 0,
INSTANCER,
CURVE,
VOLUME,
NUM_GEOMTYPES
};
enum class UsdBridgeVolumeFieldType
{
DENSITY,
COLOR
};
enum class UsdBridgeLogLevel
{
STATUS,
WARNING,
ERR
};
typedef void(*UsdBridgeLogCallback)(UsdBridgeLogLevel, void*, const char*);
struct UsdBridgeLogObject
{
void* LogUserData;
UsdBridgeLogCallback LogCallback;
};
struct UsdBridgeSettings
{
const char* HostName; // Name of the remote server
const char* OutputPath; // Directory for output (on server if HostName is not empty)
bool CreateNewSession; // Find a new session directory on creation of the bridge, or re-use the last opened one (leave contents intact).
bool BinaryOutput; // Select usda or usd output.
// Output settings
bool EnablePreviewSurfaceShader;
bool EnableMdlShader;
// About to be deprecated
static constexpr bool EnableStTexCoords = false;
};
// Generic attribute definition
struct UsdBridgeAttribute
{
const void* Data = nullptr;
UsdBridgeType DataType = UsdBridgeType::UNDEFINED;
bool PerPrimData = false;
uint32_t EltSize = 0;
const char* Name = nullptr;
};
struct UsdBridgeMeshData
{
static const UsdBridgeGeomType GeomType = UsdBridgeGeomType::MESH;
//Class definitions
enum class DataMemberId : uint32_t
{
NONE = 0,
POINTS = (1 << 0), // Goes together with extent
NORMALS = (1 << 1),
COLORS = (1 << 2),
INDICES = (1 << 3),
ATTRIBUTE0 = (1 << 4),
ATTRIBUTE1 = (1 << 5),
ATTRIBUTE2 = (1 << 6),
ATTRIBUTE3 = (1 << 7),
ALL = (1 << 8) - 1
};
DataMemberId UpdatesToPerform = DataMemberId::ALL;
DataMemberId TimeVarying = DataMemberId::ALL;
bool isEmpty() { return Points == NULL; }
//Mesh data
uint64_t NumPoints = 0;
const void* Points = nullptr;
UsdBridgeType PointsType = UsdBridgeType::UNDEFINED;
const void* Normals = nullptr;
UsdBridgeType NormalsType = UsdBridgeType::UNDEFINED;
bool PerPrimNormals = false;
const void* Colors = nullptr;
UsdBridgeType ColorsType = UsdBridgeType::UNDEFINED;
bool PerPrimColors = false;
const UsdBridgeAttribute* Attributes = nullptr; // Pointer to externally managed attribute array
uint32_t NumAttributes = 0;
const void* Indices = nullptr;
UsdBridgeType IndicesType = UsdBridgeType::UNDEFINED;
uint64_t NumIndices = 0;
int FaceVertexCount = 0;
};
struct UsdBridgeInstancerData
{
static const UsdBridgeGeomType GeomType = UsdBridgeGeomType::INSTANCER;
//Class definitions
enum class DataMemberId : uint32_t
{
NONE = 0,
POINTS = (1 << 0), // Goes together with extent
SHAPEINDICES = (1 << 1),
SCALES = (1 << 2),
ORIENTATIONS = (1 << 3),
LINEARVELOCITIES = (1 << 4),
ANGULARVELOCITIES = (1 << 5),
INSTANCEIDS = (1 << 6),
COLORS = (1 << 7),
INVISIBLEIDS = (1 << 8),
ATTRIBUTE0 = (1 << 9),
ATTRIBUTE1 = (1 << 10),
ATTRIBUTE2 = (1 << 11),
ATTRIBUTE3 = (1 << 12),
ALL = (1 << 13) - 1
};
DataMemberId UpdatesToPerform = DataMemberId::ALL;
DataMemberId TimeVarying = DataMemberId::ALL;
float getUniformScale() const { return Scale.Data[0]; }
bool UseUsdGeomPoints = true; // Shape is sphere and geomPoints is desired
uint64_t NumPoints = 0;
const void* Points = nullptr;
UsdBridgeType PointsType = UsdBridgeType::UNDEFINED;
const int* ShapeIndices = nullptr; //if set, one for every point
const void* Scales = nullptr;// 3-vector scale
UsdBridgeType ScalesType = UsdBridgeType::UNDEFINED;
UsdFloat3 Scale = {1, 1, 1};// In case no scales are given
const void* Orientations = nullptr;
UsdBridgeType OrientationsType = UsdBridgeType::UNDEFINED;
UsdQuaternion Orientation;// In case no orientations are given
const void* Colors = nullptr;
UsdBridgeType ColorsType = UsdBridgeType::UNDEFINED;
static constexpr bool PerPrimColors = false; // For compatibility
const float* LinearVelocities = nullptr;
const float* AngularVelocities = nullptr;
const UsdBridgeAttribute* Attributes = nullptr; // Pointer to externally managed attribute array
uint32_t NumAttributes = 0;
const void* InstanceIds = nullptr;
UsdBridgeType InstanceIdsType = UsdBridgeType::UNDEFINED;
const void* InvisibleIds = nullptr; //Index into points
uint64_t NumInvisibleIds = 0;
UsdBridgeType InvisibleIdsType = UsdBridgeType::UNDEFINED;
};
struct UsdBridgeInstancerRefData
{
enum InstanceShape
{
SHAPE_SPHERE = -1,
SHAPE_CYLINDER = -2,
SHAPE_CONE = -3,
SHAPE_MESH = 0 // Positive values denote meshes (allows for indices into a list of meshes passed along with a list of shapes)
};
InstanceShape DefaultShape = SHAPE_SPHERE;
InstanceShape* Shapes = &DefaultShape;
int NumShapes = 1;
UsdFloatMat4 ShapeTransform;
};
struct UsdBridgeCurveData
{
static const UsdBridgeGeomType GeomType = UsdBridgeGeomType::CURVE;
//Class definitions
enum class DataMemberId : uint32_t
{
NONE = 0,
POINTS = (1 << 0), // Goes together with extent and curvelengths
NORMALS = (1 << 1),
SCALES = (1 << 2),
COLORS = (1 << 3),
CURVELENGTHS = (1 << 4),
ATTRIBUTE0 = (1 << 5),
ATTRIBUTE1 = (1 << 6),
ATTRIBUTE2 = (1 << 7),
ATTRIBUTE3 = (1 << 8),
ALL = (1 << 9) - 1
};
DataMemberId UpdatesToPerform = DataMemberId::ALL;
DataMemberId TimeVarying = DataMemberId::ALL;
bool isEmpty() { return Points == NULL; }
float getUniformScale() const { return UniformScale; }
uint64_t NumPoints = 0;
const void* Points = nullptr;
UsdBridgeType PointsType = UsdBridgeType::UNDEFINED;
const void* Normals = nullptr;
UsdBridgeType NormalsType = UsdBridgeType::UNDEFINED;
bool PerPrimNormals = false;
const void* Colors = nullptr;
UsdBridgeType ColorsType = UsdBridgeType::UNDEFINED;
bool PerPrimColors = false; // One prim would be a full curve
const void* Scales = nullptr; // Used for line width, typically 1-component
UsdBridgeType ScalesType = UsdBridgeType::UNDEFINED;
float UniformScale = 1;// In case no scales are given
const UsdBridgeAttribute* Attributes = nullptr; // Pointer to externally managed attribute array
uint32_t NumAttributes = 0;
const int* CurveLengths = nullptr;
uint64_t NumCurveLengths = 0;
};
struct UsdBridgeTfData
{
const void* TfColors = nullptr;
UsdBridgeType TfColorsType = UsdBridgeType::UNDEFINED;
int TfNumColors = 0;
const void* TfOpacities = nullptr;
UsdBridgeType TfOpacitiesType = UsdBridgeType::UNDEFINED;
int TfNumOpacities = 0;
double TfValueRange[2] = { 0, 1 };
};
struct UsdBridgeVolumeData
{
static constexpr int TFDataStart = 2;
enum class DataMemberId : uint32_t
{
NONE = 0,
DATA = (1 << 1), // Includes the extent - number of elements per dimension
VOL_ALL = (1 << TFDataStart) - 1,
TFCOLORS = (1 << (TFDataStart + 0)),
TFOPACITIES = (1 << (TFDataStart + 1)),
TFVALUERANGE = (1 << (TFDataStart + 2)),
ALL = (1 << (TFDataStart + 3)) - 1
};
#if __cplusplus >= 201703L
static_assert(DataMemberId::TFCOLORS > DataMemberId::VOL_ALL);
#endif
DataMemberId UpdatesToPerform = DataMemberId::ALL;
DataMemberId TimeVarying = DataMemberId::ALL;
bool preClassified = false;
const void* Data = nullptr;
UsdBridgeType DataType = UsdBridgeType::UNDEFINED; // Same timeVarying rule as 'Data'
size_t NumElements[3] = { 0,0,0 }; // Same timeVarying rule as 'Data'
float Origin[3] = { 0,0,0 };
float CellDimensions[3] = { 1,1,1 };
long long BackgroundIdx = -1; // When not -1, denotes the first element in Data which contains a background value
UsdBridgeTfData TfData;
};
struct UsdBridgeMaterialData
{
template<typename ValueType>
struct MaterialInput
{
ValueType Value;
const char* SrcAttrib;
bool Sampler; // Only denote whether a sampler is attached
};
enum class DataMemberId : uint32_t
{
NONE = 0,
DIFFUSE = (1 << 0),
OPACITY = (1 << 1),
EMISSIVECOLOR = (1 << 2),
EMISSIVEINTENSITY = (1 << 3),
ROUGHNESS = (1 << 4),
METALLIC = (1 << 5),
IOR = (1 << 6),
ALL = (1 << 7) - 1
};
DataMemberId TimeVarying = DataMemberId::NONE;
bool IsPbr = true;
enum class AlphaModes : uint32_t
{
NONE,
BLEND,
MASK
};
AlphaModes AlphaMode = AlphaModes::NONE;
float AlphaCutoff = 0.5f;
MaterialInput<UsdFloat3> Diffuse = {{ 1.0f }, nullptr};
MaterialInput<UsdFloat3> Emissive = {{ 1.0f }, nullptr};
MaterialInput<float> Opacity = {1.0f, nullptr};
MaterialInput<float> EmissiveIntensity = {0.0f, nullptr};
MaterialInput<float> Roughness = {0.5f, nullptr};
MaterialInput<float> Metallic = {0.0, nullptr};
MaterialInput<float> Ior = {1.0f, nullptr};
};
template<typename ValueType>
const typename ValueType::DataType* GetValuePtr(const UsdBridgeMaterialData::MaterialInput<ValueType>& input)
{
return input.Value.Data;
}
struct UsdBridgeSamplerData
{
enum class SamplerType : uint32_t
{
SAMPLER_1D = 0,
SAMPLER_2D,
SAMPLER_3D
};
enum class DataMemberId : uint32_t
{
NONE = 0,
DATA = (1 << 0), // Refers to: data(-type), image name/url
WRAPS = (1 << 1),
WRAPT = (1 << 2),
WRAPR = (1 << 3),
ALL = (1 << 4) - 1
};
DataMemberId TimeVarying = DataMemberId::NONE;
enum class WrapMode
{
BLACK = 0,
CLAMP,
REPEAT,
MIRROR
};
SamplerType Type = SamplerType::SAMPLER_1D;
const char* InAttribute = nullptr;
const char* ImageUrl = nullptr;
const char* ImageName = nullptr;
uint64_t ImageDims[3] = {0, 0, 0};
int64_t ImageStride[3] = {0, 0, 0};
int ImageNumComponents = 4;
const void* Data = nullptr;
UsdBridgeType DataType = UsdBridgeType::UNDEFINED;
WrapMode WrapS = WrapMode::BLACK;
WrapMode WrapT = WrapMode::BLACK;
WrapMode WrapR = WrapMode::BLACK;
};
struct UsdSamplerRefData
{
int ImageNumComponents;
double TimeStep;
UsdBridgeMaterialData::DataMemberId DataMemberId; // Material input parameter to connect to
};
struct UsdBridgeCameraData
{
enum class DataMemberId : uint32_t
{
NONE = 0,
VIEW = (1 << 0),
PROJECTION = (1 << 1),
ALL = (1 << 9) - 1
};
DataMemberId TimeVarying = DataMemberId::NONE;
UsdFloat3 Position = {0.0f, 0.0f, 0.0f};
UsdFloat3 Direction = {0.0f, 0.0f, -1.0f};
UsdFloat3 Up = {0.0f, 1.0f, 0.0f};
UsdFloatBox2 ImageRegion = {0.0f, 0.0f, 1.0f, 1.0f};
float Aspect;
float Near;
float Far;
float Fovy;
float Height;
};
template<class TEnum>
struct DefineBitMaskOps
{
static const bool enable = false;
};
template<class TEnum>
struct DefineAddSubOps
{
static const bool enable = false;
};
#define USDBRIDGE_ENABLE_BITMASK_OP(DataType)\
template<>\
struct DefineBitMaskOps<DataType::DataMemberId>\
{\
static const bool enable = true;\
};
#define USDBRIDGE_ENABLE_ADDSUB_OP(DataType)\
template<>\
struct DefineAddSubOps<DataType::DataMemberId>\
{\
static const bool enable = true;\
};
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeMeshData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeInstancerData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeCurveData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeVolumeData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeMaterialData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeSamplerData);
USDBRIDGE_ENABLE_BITMASK_OP(UsdBridgeCameraData);
USDBRIDGE_ENABLE_ADDSUB_OP(UsdBridgeMeshData);
USDBRIDGE_ENABLE_ADDSUB_OP(UsdBridgeInstancerData);
USDBRIDGE_ENABLE_ADDSUB_OP(UsdBridgeCurveData);
template<class TEnum>
typename std::enable_if<DefineBitMaskOps<TEnum>::enable, TEnum>::type operator |(TEnum lhs, TEnum rhs)
{
using underlying = typename std::underlying_type<TEnum>::type;
return static_cast<TEnum> (
static_cast<underlying>(lhs) |
static_cast<underlying>(rhs)
);
}
template<class TEnum>
typename std::enable_if<DefineBitMaskOps<TEnum>::enable, TEnum>::type operator &(TEnum lhs, TEnum rhs)
{
using underlying = typename std::underlying_type<TEnum>::type;
return static_cast<TEnum> (
static_cast<underlying>(lhs) &
static_cast<underlying>(rhs)
);
}
template<class TEnum>
typename std::enable_if<DefineBitMaskOps<TEnum>::enable, TEnum>::type operator ~(TEnum rhs)
{
using underlying = typename std::underlying_type<TEnum>::type;
return static_cast<TEnum> (~static_cast<underlying>(rhs));
}
template<class TEnum>
typename std::enable_if<DefineAddSubOps<TEnum>::enable, TEnum>::type operator +(TEnum lhs, int rhs)
{
using underlying = typename std::underlying_type<TEnum>::type;
return static_cast<TEnum> ( static_cast<underlying>(lhs) + rhs );
}
template<class T>
class UsdBridgeUpdateEvaluator
{
public:
UsdBridgeUpdateEvaluator(T& data)
: Data(data)
{
}
bool PerformsUpdate(typename T::DataMemberId member) const
{
return ((Data.UpdatesToPerform & member) != T::DataMemberId::NONE);
}
void RemoveUpdate(typename T::DataMemberId member)
{
Data.UpdatesToPerform = (Data.UpdatesToPerform & ~member);
}
void AddUpdate(typename T::DataMemberId member)
{
Data.UpdatesToPerform = (Data.UpdatesToPerform | member);
}
T& Data;
};
#endif
| 16,295 | C | 24.148148 | 150 | 0.694998 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeUtils.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeUtils_h
#define UsdBridgeUtils_h
#include "UsdBridgeData.h"
// USD-independent utils for the UsdBridge
#define UsdBridgeLogMacro(obj, level, message) \
{ std::stringstream logStream; \
logStream << message; \
std::string logString = logStream.str(); \
obj.LogCallback(level, obj.LogUserData, logString.c_str()); }
namespace ubutils
{
const char* UsdBridgeTypeToString(UsdBridgeType type);
UsdBridgeType UsdBridgeTypeFlatten(UsdBridgeType type);
const float* SrgbToLinearTable(); // returns a float[256] array
float SrgbToLinear(float val);
void SrgbToLinear3(float* color); // expects a float[3]
}
#endif | 727 | C | 25.962962 | 65 | 0.742779 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Common/UsdBridgeUtils.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUtils.h"
#include <cmath>
namespace ubutils
{
const char* UsdBridgeTypeToString(UsdBridgeType type)
{
const char* typeStr = nullptr;
switch(type)
{
case UsdBridgeType::BOOL: typeStr = "BOOL"; break;
case UsdBridgeType::UCHAR: typeStr = "UCHAR"; break;
case UsdBridgeType::UCHAR_SRGB_R: typeStr = "UCHAR_SRGB_R"; break;
case UsdBridgeType::CHAR: typeStr = "CHAR"; break;
case UsdBridgeType::USHORT: typeStr = "USHORT"; break;
case UsdBridgeType::SHORT: typeStr = "SHORT"; break;
case UsdBridgeType::UINT: typeStr = "UINT"; break;
case UsdBridgeType::INT: typeStr = "INT"; break;
case UsdBridgeType::ULONG: typeStr = "ULONG"; break;
case UsdBridgeType::LONG: typeStr = "LONG"; break;
case UsdBridgeType::HALF: typeStr = "HALF"; break;
case UsdBridgeType::FLOAT: typeStr = "FLOAT"; break;
case UsdBridgeType::DOUBLE: typeStr = "DOUBLE"; break;
case UsdBridgeType::UCHAR2: typeStr = "UCHAR2"; break;
case UsdBridgeType::UCHAR_SRGB_RA: typeStr = "UCHAR_SRGB_RA"; break;
case UsdBridgeType::CHAR2: typeStr = "CHAR2"; break;
case UsdBridgeType::USHORT2: typeStr = "USHORT2"; break;
case UsdBridgeType::SHORT2: typeStr = "SHORT2"; break;
case UsdBridgeType::UINT2: typeStr = "UINT2"; break;
case UsdBridgeType::INT2: typeStr = "INT2"; break;
case UsdBridgeType::ULONG2: typeStr = "ULONG2"; break;
case UsdBridgeType::LONG2: typeStr = "LONG2"; break;
case UsdBridgeType::HALF2: typeStr = "HALF2"; break;
case UsdBridgeType::FLOAT2: typeStr = "FLOAT2"; break;
case UsdBridgeType::DOUBLE2: typeStr = "DOUBLE2"; break;
case UsdBridgeType::UCHAR3: typeStr = "UCHAR3"; break;
case UsdBridgeType::UCHAR_SRGB_RGB: typeStr = "UCHAR_SRGB_RGB"; break;
case UsdBridgeType::CHAR3: typeStr = "CHAR3"; break;
case UsdBridgeType::USHORT3: typeStr = "USHORT3"; break;
case UsdBridgeType::SHORT3: typeStr = "SHORT3"; break;
case UsdBridgeType::UINT3: typeStr = "UINT3"; break;
case UsdBridgeType::INT3: typeStr = "INT3"; break;
case UsdBridgeType::ULONG3: typeStr = "ULONG3"; break;
case UsdBridgeType::LONG3: typeStr = "LONG3"; break;
case UsdBridgeType::HALF3: typeStr = "HALF3"; break;
case UsdBridgeType::FLOAT3: typeStr = "FLOAT3"; break;
case UsdBridgeType::DOUBLE3: typeStr = "DOUBLE3"; break;
case UsdBridgeType::UCHAR4: typeStr = "UCHAR4"; break;
case UsdBridgeType::UCHAR_SRGB_RGBA: typeStr = "UCHAR_SRGB_RGBA"; break;
case UsdBridgeType::CHAR4: typeStr = "CHAR4"; break;
case UsdBridgeType::USHORT4: typeStr = "USHORT4"; break;
case UsdBridgeType::SHORT4: typeStr = "SHORT4"; break;
case UsdBridgeType::UINT4: typeStr = "UINT4"; break;
case UsdBridgeType::INT4: typeStr = "INT4"; break;
case UsdBridgeType::ULONG4: typeStr = "ULONG4"; break;
case UsdBridgeType::LONG4: typeStr = "LONG4"; break;
case UsdBridgeType::HALF4: typeStr = "HALF4"; break;
case UsdBridgeType::FLOAT4: typeStr = "FLOAT4"; break;
case UsdBridgeType::DOUBLE4: typeStr = "DOUBLE4"; break;
case UsdBridgeType::INT_PAIR: typeStr = "INT_PAIR"; break;
case UsdBridgeType::INT_PAIR2: typeStr = "INT_PAIR2"; break;
case UsdBridgeType::INT_PAIR3: typeStr = "INT_PAIR3"; break;
case UsdBridgeType::INT_PAIR4: typeStr = "INT_PAIR4"; break;
case UsdBridgeType::FLOAT_PAIR: typeStr = "FLOAT_PAIR"; break;
case UsdBridgeType::FLOAT_PAIR2: typeStr = "FLOAT_PAIR2"; break;
case UsdBridgeType::FLOAT_PAIR3: typeStr = "FLOAT_PAIR3"; break;
case UsdBridgeType::FLOAT_PAIR4: typeStr = "FLOAT_PAIR4"; break;
case UsdBridgeType::DOUBLE_PAIR: typeStr = "DOUBLE_PAIR"; break;
case UsdBridgeType::DOUBLE_PAIR2: typeStr = "DOUBLE_PAIR2"; break;
case UsdBridgeType::DOUBLE_PAIR3: typeStr = "DOUBLE_PAIR3"; break;
case UsdBridgeType::DOUBLE_PAIR4: typeStr = "DOUBLE_PAIR4"; break;
case UsdBridgeType::ULONG_PAIR: typeStr = "ULONG_PAIR"; break;
case UsdBridgeType::ULONG_PAIR2: typeStr = "ULONG_PAIR2"; break;
case UsdBridgeType::ULONG_PAIR3: typeStr = "ULONG_PAIR3"; break;
case UsdBridgeType::ULONG_PAIR4: typeStr = "ULONG_PAIR4"; break;
case UsdBridgeType::FLOAT_MAT2: typeStr = "FLOAT_MAT2"; break;
case UsdBridgeType::FLOAT_MAT3: typeStr = "FLOAT_MAT3"; break;
case UsdBridgeType::FLOAT_MAT4: typeStr = "FLOAT_MAT4"; break;
case UsdBridgeType::FLOAT_MAT2x3: typeStr = "FLOAT_MAT2x3"; break;
case UsdBridgeType::FLOAT_MAT3x4: typeStr = "FLOAT_MAT3x4"; break;
case UsdBridgeType::UNDEFINED: default: typeStr = "UNDEFINED"; break;
}
return typeStr;
}
UsdBridgeType UsdBridgeTypeFlatten(UsdBridgeType type)
{
UsdBridgeType flatType = UsdBridgeType::UNDEFINED;
switch(type)
{
case UsdBridgeType::BOOL:
case UsdBridgeType::UCHAR:
case UsdBridgeType::UCHAR_SRGB_R:
case UsdBridgeType::CHAR:
case UsdBridgeType::USHORT:
case UsdBridgeType::SHORT:
case UsdBridgeType::UINT:
case UsdBridgeType::INT:
case UsdBridgeType::ULONG:
case UsdBridgeType::LONG:
case UsdBridgeType::HALF:
case UsdBridgeType::FLOAT:
case UsdBridgeType::DOUBLE: flatType = type; break;
case UsdBridgeType::UCHAR2: flatType = UsdBridgeType::UCHAR; break;
case UsdBridgeType::UCHAR_SRGB_RA: flatType = UsdBridgeType::UCHAR_SRGB_R; break;
case UsdBridgeType::CHAR2: flatType = UsdBridgeType::CHAR; break;
case UsdBridgeType::USHORT2: flatType = UsdBridgeType::USHORT; break;
case UsdBridgeType::SHORT2: flatType = UsdBridgeType::SHORT; break;
case UsdBridgeType::UINT2: flatType = UsdBridgeType::UINT; break;
case UsdBridgeType::INT2: flatType = UsdBridgeType::INT; break;
case UsdBridgeType::ULONG2: flatType = UsdBridgeType::ULONG; break;
case UsdBridgeType::LONG2: flatType = UsdBridgeType::LONG; break;
case UsdBridgeType::HALF2: flatType = UsdBridgeType::HALF; break;
case UsdBridgeType::FLOAT2: flatType = UsdBridgeType::FLOAT; break;
case UsdBridgeType::DOUBLE2: flatType = UsdBridgeType::DOUBLE; break;
case UsdBridgeType::UCHAR3: flatType = UsdBridgeType::UCHAR; break;
case UsdBridgeType::UCHAR_SRGB_RGB: flatType = UsdBridgeType::UCHAR_SRGB_R; break;
case UsdBridgeType::CHAR3: flatType = UsdBridgeType::CHAR; break;
case UsdBridgeType::USHORT3:flatType = UsdBridgeType::USHORT; break;
case UsdBridgeType::SHORT3: flatType = UsdBridgeType::SHORT; break;
case UsdBridgeType::UINT3: flatType = UsdBridgeType::UINT; break;
case UsdBridgeType::INT3: flatType = UsdBridgeType::INT; break;
case UsdBridgeType::ULONG3: flatType = UsdBridgeType::ULONG; break;
case UsdBridgeType::LONG3: flatType = UsdBridgeType::LONG; break;
case UsdBridgeType::HALF3: flatType = UsdBridgeType::HALF; break;
case UsdBridgeType::FLOAT3: flatType = UsdBridgeType::FLOAT; break;
case UsdBridgeType::DOUBLE3: flatType = UsdBridgeType::DOUBLE; break;
case UsdBridgeType::UCHAR4: flatType = UsdBridgeType::UCHAR; break;
case UsdBridgeType::UCHAR_SRGB_RGBA: flatType = UsdBridgeType::UCHAR_SRGB_R; break;
case UsdBridgeType::CHAR4: flatType = UsdBridgeType::CHAR; break;
case UsdBridgeType::USHORT4: flatType = UsdBridgeType::USHORT; break;
case UsdBridgeType::SHORT4: flatType = UsdBridgeType::SHORT; break;
case UsdBridgeType::UINT4: flatType = UsdBridgeType::UINT; break;
case UsdBridgeType::INT4: flatType = UsdBridgeType::INT; break;
case UsdBridgeType::ULONG4: flatType = UsdBridgeType::ULONG; break;
case UsdBridgeType::LONG4: flatType = UsdBridgeType::LONG; break;
case UsdBridgeType::HALF4: flatType = UsdBridgeType::HALF; break;
case UsdBridgeType::FLOAT4: flatType = UsdBridgeType::FLOAT; break;
case UsdBridgeType::DOUBLE4: flatType = UsdBridgeType::DOUBLE; break;
case UsdBridgeType::INT_PAIR:
case UsdBridgeType::INT_PAIR2:
case UsdBridgeType::INT_PAIR3:
case UsdBridgeType::INT_PAIR4: flatType = UsdBridgeType::INT; break;
case UsdBridgeType::FLOAT_PAIR:
case UsdBridgeType::FLOAT_PAIR2:
case UsdBridgeType::FLOAT_PAIR3:
case UsdBridgeType::FLOAT_PAIR4: flatType = UsdBridgeType::FLOAT; break;
case UsdBridgeType::DOUBLE_PAIR:
case UsdBridgeType::DOUBLE_PAIR2:
case UsdBridgeType::DOUBLE_PAIR3:
case UsdBridgeType::DOUBLE_PAIR4: flatType = UsdBridgeType::DOUBLE; break;
case UsdBridgeType::ULONG_PAIR:
case UsdBridgeType::ULONG_PAIR2:
case UsdBridgeType::ULONG_PAIR3:
case UsdBridgeType::ULONG_PAIR4: flatType = UsdBridgeType::ULONG; break;
case UsdBridgeType::FLOAT_MAT2:
case UsdBridgeType::FLOAT_MAT3:
case UsdBridgeType::FLOAT_MAT4:
case UsdBridgeType::FLOAT_MAT2x3:
case UsdBridgeType::FLOAT_MAT3x4: flatType = UsdBridgeType::FLOAT; break;
case UsdBridgeType::UNDEFINED: default: flatType = UsdBridgeType::UNDEFINED; break;
}
return flatType;
}
const unsigned int SRGBTable[] =
{
0x00000000,0x399f22b4,0x3a1f22b4,0x3a6eb40e,0x3a9f22b4,0x3ac6eb61,0x3aeeb40e,0x3b0b3e5d,
0x3b1f22b4,0x3b33070b,0x3b46eb61,0x3b5b518d,0x3b70f18d,0x3b83e1c6,0x3b8fe616,0x3b9c87fd,
0x3ba9c9b7,0x3bb7ad6f,0x3bc63549,0x3bd56361,0x3be539c1,0x3bf5ba70,0x3c0373b5,0x3c0c6152,
0x3c15a703,0x3c1f45be,0x3c293e6b,0x3c3391f7,0x3c3e4149,0x3c494d43,0x3c54b6c7,0x3c607eb1,
0x3c6ca5df,0x3c792d22,0x3c830aa8,0x3c89af9f,0x3c9085db,0x3c978dc5,0x3c9ec7c2,0x3ca63433,
0x3cadd37d,0x3cb5a601,0x3cbdac20,0x3cc5e639,0x3cce54ab,0x3cd6f7d5,0x3cdfd010,0x3ce8ddb9,
0x3cf2212c,0x3cfb9ac1,0x3d02a569,0x3d0798dc,0x3d0ca7e6,0x3d11d2af,0x3d171963,0x3d1c7c2e,
0x3d21fb3c,0x3d2796b2,0x3d2d4ebb,0x3d332380,0x3d39152b,0x3d3f23e3,0x3d454fd1,0x3d4b991c,
0x3d51ffef,0x3d58846a,0x3d5f26b7,0x3d65e6fe,0x3d6cc564,0x3d73c20f,0x3d7add29,0x3d810b67,
0x3d84b795,0x3d887330,0x3d8c3e4a,0x3d9018f6,0x3d940345,0x3d97fd4a,0x3d9c0716,0x3da020bb,
0x3da44a4b,0x3da883d7,0x3daccd70,0x3db12728,0x3db59112,0x3dba0b3b,0x3dbe95b5,0x3dc33092,
0x3dc7dbe2,0x3dcc97b6,0x3dd1641f,0x3dd6412c,0x3ddb2eef,0x3de02d77,0x3de53cd5,0x3dea5d19,
0x3def8e52,0x3df4d091,0x3dfa23e8,0x3dff8861,0x3e027f07,0x3e054280,0x3e080ea3,0x3e0ae378,
0x3e0dc105,0x3e10a754,0x3e13966b,0x3e168e52,0x3e198f10,0x3e1c98ad,0x3e1fab30,0x3e22c6a3,
0x3e25eb09,0x3e29186c,0x3e2c4ed0,0x3e2f8e41,0x3e32d6c4,0x3e362861,0x3e39831e,0x3e3ce703,
0x3e405416,0x3e43ca5f,0x3e4749e4,0x3e4ad2ae,0x3e4e64c2,0x3e520027,0x3e55a4e6,0x3e595303,
0x3e5d0a8b,0x3e60cb7c,0x3e6495e0,0x3e6869bf,0x3e6c4720,0x3e702e0c,0x3e741e84,0x3e781890,
0x3e7c1c38,0x3e8014c2,0x3e82203c,0x3e84308d,0x3e8645ba,0x3e885fc5,0x3e8a7eb2,0x3e8ca283,
0x3e8ecb3d,0x3e90f8e1,0x3e932b74,0x3e9562f8,0x3e979f71,0x3e99e0e2,0x3e9c274e,0x3e9e72b7,
0x3ea0c322,0x3ea31892,0x3ea57308,0x3ea7d289,0x3eaa3718,0x3eaca0b7,0x3eaf0f69,0x3eb18333,
0x3eb3fc18,0x3eb67a18,0x3eb8fd37,0x3ebb8579,0x3ebe12e1,0x3ec0a571,0x3ec33d2d,0x3ec5da17,
0x3ec87c33,0x3ecb2383,0x3ecdd00b,0x3ed081cd,0x3ed338cc,0x3ed5f50b,0x3ed8b68d,0x3edb7d54,
0x3ede4965,0x3ee11ac1,0x3ee3f16b,0x3ee6cd67,0x3ee9aeb6,0x3eec955d,0x3eef815d,0x3ef272ba,
0x3ef56976,0x3ef86594,0x3efb6717,0x3efe6e02,0x3f00bd2d,0x3f02460e,0x3f03d1a7,0x3f055ff9,
0x3f06f106,0x3f0884cf,0x3f0a1b56,0x3f0bb49b,0x3f0d50a0,0x3f0eef67,0x3f1090f1,0x3f12353e,
0x3f13dc51,0x3f15862b,0x3f1732cd,0x3f18e239,0x3f1a946f,0x3f1c4971,0x3f1e0141,0x3f1fbbdf,
0x3f21794e,0x3f23398e,0x3f24fca0,0x3f26c286,0x3f288b41,0x3f2a56d3,0x3f2c253d,0x3f2df680,
0x3f2fca9e,0x3f31a197,0x3f337b6c,0x3f355820,0x3f3737b3,0x3f391a26,0x3f3aff7c,0x3f3ce7b5,
0x3f3ed2d2,0x3f40c0d4,0x3f42b1be,0x3f44a590,0x3f469c4b,0x3f4895f1,0x3f4a9282,0x3f4c9201,
0x3f4e946e,0x3f5099cb,0x3f52a218,0x3f54ad57,0x3f56bb8a,0x3f58ccb0,0x3f5ae0cd,0x3f5cf7e0,
0x3f5f11ec,0x3f612eee,0x3f634eef,0x3f6571e9,0x3f6797e3,0x3f69c0d6,0x3f6beccd,0x3f6e1bbf,
0x3f704db8,0x3f7282af,0x3f74baae,0x3f76f5ae,0x3f7933b9,0x3f7b74c6,0x3f7db8e0,0x3f800000
};
const float* SrgbToLinearTable()
{
return reinterpret_cast<const float*>(SRGBTable);
}
float SrgbToLinear(float val)
{
if( val < 0.04045f )
val /= 12.92f;
else
val = pow((val + 0.055f)/1.055f,2.4f);
return val;
}
void SrgbToLinear3(float* color)
{
color[0] = SrgbToLinear(color[0]);
color[1] = SrgbToLinear(color[1]);
color[2] = SrgbToLinear(color[2]);
}
} | 12,747 | C++ | 54.91228 | 94 | 0.72519 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Connection/UsdBridgeConnection.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeConnection.h"
#include <fstream>
#include <sstream>
#include <atomic>
#include <thread>
#include <condition_variable>
#include <algorithm>
#include <cstring>
#ifdef WIN32
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
#include <filesystem>
namespace fs = std::filesystem;
#else
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
#else
#if (__GNUC__ < 8 || __cplusplus < 201703L)
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
#endif
#define UsdBridgeLogMacro(level, message) \
{ std::stringstream logStream; \
logStream << message; \
std::string logString = logStream.str(); \
try \
{ \
UsdBridgeConnection::LogCallback(level, UsdBridgeConnection::LogUserData, logString.c_str()); \
} \
catch (...) {} \
}
#define CONNECT_CATCH(a) \
catch (const std::bad_alloc &) \
{ \
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR,"USDBRIDGECONNECTION BAD ALLOC\n"); \
return a; \
} \
catch (const std::exception &e) \
{ \
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR,"USDBRIDGECONNECTION ERROR: " << e.what()); \
return a; \
} \
catch (...) \
{ \
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR,"USDBRIDGECONNECTION UNKNOWN EXCEPTION\n"); \
return a; \
}
UsdBridgeLogCallback UsdBridgeConnection::LogCallback = nullptr;
void* UsdBridgeConnection::LogUserData = nullptr;
const char* UsdBridgeConnection::GetBaseUrl() const
{
return Settings.WorkingDirectory.c_str();
}
const char* UsdBridgeConnection::GetUrl(const char* path) const
{
TempUrl = Settings.WorkingDirectory + path;
return TempUrl.c_str();
}
bool UsdBridgeConnection::Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj)
{
Settings = settings;
UsdBridgeConnection::LogCallback = logObj.LogCallback;
UsdBridgeConnection::LogUserData = logObj.LogUserData;
return true;
}
void UsdBridgeConnection::Shutdown()
{
}
int UsdBridgeConnection::MaxSessionNr() const
{
int sessionNr = 0;
try
{
for (;; ++sessionNr)
{
TempUrl = Settings.WorkingDirectory + "Session_" + std::to_string(sessionNr);
if (!fs::exists(TempUrl))
break;
}
}
CONNECT_CATCH(-1)
return sessionNr - 1;
}
bool UsdBridgeConnection::CreateFolder(const char* dirName, bool isRelative, bool mayExist) const
{
try
{
const char* dirUrl = isRelative ? GetUrl(dirName) : dirName;
if (!mayExist || !fs::exists(dirUrl))
return fs::create_directory(dirUrl);
}
CONNECT_CATCH(false)
return true;
}
bool UsdBridgeConnection::RemoveFolder(const char* dirName, bool isRelative) const
{
bool success = false;
try
{
const char* dirUrl = isRelative ? GetUrl(dirName) : dirName;
if(fs::exists(dirUrl))
success = fs::remove_all(dirUrl);
}
CONNECT_CATCH(false)
return success;
}
bool UsdBridgeConnection::WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary) const
{
try
{
const char* fileUrl = isRelative ? GetUrl(filePath) : filePath;
std::ofstream file(fileUrl, std::ios_base::out
| std::ios_base::trunc
| (binary ? std::ios_base::binary : std::ios_base::out));
if (file.is_open())
{
file.write(data, dataSize);
file.close();
return true;
}
}
CONNECT_CATCH(false)
return false;
}
bool UsdBridgeConnection::RemoveFile(const char* filePath, bool isRelative) const
{
bool success = false;
try
{
const char* fileUrl = isRelative ? GetUrl(filePath) : filePath;
if (fs::exists(fileUrl))
success = fs::remove(fileUrl);
}
CONNECT_CATCH(false)
return success;
}
bool UsdBridgeConnection::ProcessUpdates()
{
return true;
}
class UsdBridgeRemoteConnectionInternals
{
public:
UsdBridgeRemoteConnectionInternals()
: RemoteStream(std::ios::in | std::ios::out)
{}
~UsdBridgeRemoteConnectionInternals()
{}
std::ostream* ResetStream(const char * filePath, bool binary)
{
StreamFilePath = filePath;
StreamIsBinary = binary;
RemoteStream.clear();
return &RemoteStream;
}
// To facility the Omniverse path methods
static constexpr size_t MaxBaseUrlSize = 4096;
char BaseUrlBuffer[MaxBaseUrlSize];
char TempUrlBuffer[MaxBaseUrlSize];
// Status callback handle
uint32_t StatusCallbackHandle = 0;
// Stream
const char* StreamFilePath;
bool StreamIsBinary;
std::stringstream RemoteStream;
};
int UsdBridgeRemoteConnection::NumConnInstances = 0;
int UsdBridgeRemoteConnection::NumInitializedConnInstances = 0;
int UsdBridgeRemoteConnection::ConnectionLogLevel = 0;
UsdBridgeRemoteConnection::UsdBridgeRemoteConnection()
: Internals(new UsdBridgeRemoteConnectionInternals())
{
}
UsdBridgeRemoteConnection::~UsdBridgeRemoteConnection()
{
delete Internals;
}
#ifdef OMNIVERSE_CONNECTION_ENABLE
#include <OmniClient.h>
namespace
{
struct DefaultContext
{
OmniClientResult result = eOmniClientResult_Error;
bool done = false;
};
const char* omniResultToString(OmniClientResult result)
{
const char* msg = nullptr;
switch (result)
{
case eOmniClientResult_Ok: msg = "eOmniClientResult_Ok"; break;
case eOmniClientResult_OkLatest: msg = "eOmniClientResult_OkLatest"; break;
case eOmniClientResult_OkNotYetFound: msg = "eOmniClientResult_OkNotYetFound"; break;
case eOmniClientResult_Error: msg = "eOmniClientResult_Error"; break;
case eOmniClientResult_ErrorConnection: msg = "eOmniClientResult_ErrorConnection"; break;
case eOmniClientResult_ErrorNotSupported: msg = "eOmniClientResult_ErrorNotSupported"; break;
case eOmniClientResult_ErrorAccessDenied: msg = "eOmniClientResult_ErrorAccessDenied"; break;
case eOmniClientResult_ErrorNotFound: msg = "eOmniClientResult_ErrorNotFound"; break;
case eOmniClientResult_ErrorBadVersion: msg = "eOmniClientResult_ErrorBadVersion"; break;
case eOmniClientResult_ErrorAlreadyExists: msg = "eOmniClientResult_ErrorAlreadyExists"; break;
case eOmniClientResult_ErrorAccessLost: msg = "eOmniClientResult_ErrorAccessLost"; break;
default: msg = "Unknown OmniClientResult"; break;
};
return msg;
}
void OmniClientStatusCB(const char* threadName, const char* component, OmniClientLogLevel level, const char* message) OMNICLIENT_NOEXCEPT
{
static std::mutex statusMutex;
std::unique_lock<std::mutex> lk(statusMutex);
// This will return "Verbose", "Info", "Warning", "Error"
//const char* levelString = omniClientGetLogLevelString(level);
char levelChar = omniClientGetLogLevelChar(level);
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "OmniClient status message: ");
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "level: " << levelChar << ", thread: " << threadName << ", component: " << component << ", msg: " << message);
}
void OmniClientConnectionStatusCB(void* userData, char const* url, OmniClientConnectionStatus status) OMNICLIENT_NOEXCEPT
{
(void)userData;
static std::mutex statusMutex;
std::unique_lock<std::mutex> lk(statusMutex);
{
std::string urlStr;
if (url) urlStr = url;
switch (status)
{
case eOmniClientConnectionStatus_Connecting: { UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Attempting to connect to " << urlStr); break; }
case eOmniClientConnectionStatus_Connected: { UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Successfully connected to " << urlStr); break; }
case eOmniClientConnectionStatus_ConnectError: { UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Error trying to connect (will attempt reconnection) to " << urlStr); break; }
case eOmniClientConnectionStatus_Disconnected: { UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Disconnected (will attempt reconnection) to " << urlStr); break; }
case Count_eOmniClientConnectionStatus:
default:
break;
}
}
}
OmniClientResult IsValidServerConnection(const char* serverUrl)
{
struct ServerInfoContect : public DefaultContext
{
std::string retVersion;
} context;
omniClientWait(omniClientGetServerInfo(serverUrl, &context,
[](void* userData, OmniClientResult result, OmniClientServerInfo const * info) OMNICLIENT_NOEXCEPT
{
ServerInfoContect& context = *(ServerInfoContect*)(userData);
if (context.result != eOmniClientResult_Ok)
{
context.result = result;
if (result == eOmniClientResult_Ok && info->version)
{
context.retVersion = info->version;
}
context.done = true;
}
})
);
return context.result;
}
void UsdBridgeSetConnectionLogLevel(int logLevel)
{
int clampedLevel = eOmniClientLogLevel_Debug + (logLevel < 0 ? 0 : logLevel);
clampedLevel = (clampedLevel < (int)Count_eOmniClientLogLevel) ? clampedLevel : Count_eOmniClientLogLevel - 1;
omniClientSetLogLevel((OmniClientLogLevel)clampedLevel);
}
}
const char* UsdBridgeRemoteConnection::GetBaseUrl() const
{
return Internals->BaseUrlBuffer;
}
const char* UsdBridgeRemoteConnection::GetUrl(const char* path) const
{
size_t parsedBufSize = Internals->MaxBaseUrlSize;
char* combinedUrl = omniClientCombineUrls(Internals->BaseUrlBuffer, path, Internals->TempUrlBuffer, &parsedBufSize);
return combinedUrl;
}
bool UsdBridgeRemoteConnection::Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj)
{
bool initSuccess = UsdBridgeConnection::Initialize(settings, logObj);
if (NumInitializedConnInstances == 0)
{
omniClientSetLogCallback(OmniClientStatusCB);
}
if (NumConnInstances == 0)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Establishing connection - Omniverse Client Initialization -");
initSuccess = omniClientInitialize(kOmniClientVersion);
UsdBridgeSetConnectionLogLevel(ConnectionLogLevel);
}
++NumConnInstances;
if (initSuccess && NumInitializedConnInstances == 0)
{
Internals->StatusCallbackHandle = omniClientRegisterConnectionStatusCallback(nullptr, OmniClientConnectionStatusCB);
}
if (initSuccess)
{
// Check for Url validity for its various components
std::string serverUrl = "omniverse://" + Settings.HostName + "/";
std::string rawUrl = serverUrl + Settings.WorkingDirectory;
OmniClientUrl* brokenUrl = omniClientBreakUrl(rawUrl.c_str());
if (!brokenUrl->scheme)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Illegal Omniverse scheme.");
initSuccess = false;
}
if (!brokenUrl->host || strlen(brokenUrl->host) == 0)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Illegal Omniverse server.");
initSuccess = false;
}
if (!brokenUrl->path || strlen(brokenUrl->path) == 0)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Illegal Omniverse working directory.");
initSuccess = false;
}
char* urlRes = nullptr;
if (initSuccess)
{
size_t parsedBufSize = Internals->MaxBaseUrlSize;
urlRes = omniClientMakeUrl(brokenUrl, Internals->BaseUrlBuffer, &parsedBufSize);
if (!urlRes)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Connection Url invalid, exceeds 4096 characters.");
initSuccess = false;
}
}
if (initSuccess)
{
OmniClientResult result = IsValidServerConnection(serverUrl.c_str());
if (result != eOmniClientResult_Ok)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Server connection cannot be established, errorcode:" << omniResultToString(result));
initSuccess = false;
}
}
if (initSuccess)
{
bool result = this->CheckWritePermissions();
if (!result)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Omniverse user does not have write permissions to selected output directory.");
initSuccess = false;
}
}
if (initSuccess)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Server for connection:" << brokenUrl->host);
if (brokenUrl->port)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Port for connection:" << brokenUrl->port);
}
if (NumInitializedConnInstances == 0)
{
//omniClientPushBaseUrl(urlRes); // Base urls only apply to *normal* omniClient calls, not usd stage creation
}
++NumInitializedConnInstances;
ConnectionInitialized = true;
}
omniClientFreeUrl(brokenUrl);
}
return initSuccess;
}
void UsdBridgeRemoteConnection::Shutdown()
{
if (ConnectionInitialized && --NumInitializedConnInstances == 0)
{
omniClientSetLogCallback(nullptr);
if (Internals->StatusCallbackHandle)
omniClientUnregisterCallback(Internals->StatusCallbackHandle);
omniClientLiveWaitForPendingUpdates();
//omniClientPopBaseUrl(Internals->BaseUrlBuffer);
//omniClientShutdown();
}
}
int UsdBridgeRemoteConnection::MaxSessionNr() const
{
struct SessionListContext : public DefaultContext
{
int sessionNumber = -1;
} context;
const char* baseUrl = this->GetBaseUrl();
omniClientWait(omniClientList(
baseUrl, &context,
[](void* userData, OmniClientResult result, uint32_t numEntries, struct OmniClientListEntry const* entries) OMNICLIENT_NOEXCEPT
{
auto& context = *(SessionListContext*)(userData);
{
if (result == eOmniClientResult_Ok)
{
for (uint32_t i = 0; i < numEntries; i++)
{
const char* relPath = entries[i].relativePath;
if (strncmp("Session_", relPath, 8) == 0)
{
int pathSessionNr = std::atoi(relPath + 8);
context.sessionNumber = std::max(context.sessionNumber, pathSessionNr);
}
}
}
context.done = true;
}
})
);
return context.sessionNumber;
}
bool UsdBridgeRemoteConnection::CreateFolder(const char* dirName, bool isRelative, bool mayExist) const
{
DefaultContext context;
const char* dirUrl = isRelative ? this->GetUrl(dirName) : dirName;
omniClientWait(omniClientCreateFolder(dirUrl, &context,
[](void* userData, OmniClientResult result) OMNICLIENT_NOEXCEPT
{
auto& context = *(DefaultContext*)(userData);
context.result = result;
context.done = true;
})
);
return context.result == eOmniClientResult_Ok || context.result == eOmniClientResult_OkLatest
|| (mayExist && context.result == eOmniClientResult_ErrorAlreadyExists);
}
bool UsdBridgeRemoteConnection::RemoveFolder(const char* dirName, bool isRelative) const
{
DefaultContext context;
const char* dirUrl = isRelative ? this->GetUrl(dirName) : dirName;
omniClientWait(omniClientDelete(dirUrl, &context,
[](void* userData, OmniClientResult result) OMNICLIENT_NOEXCEPT
{
auto& context = *(DefaultContext*)(userData);
context.result = result;
context.done = true;
})
);
return context.result == eOmniClientResult_Ok || context.result == eOmniClientResult_OkLatest;
}
bool UsdBridgeRemoteConnection::WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary) const
{
(void)binary;
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Copying data to: " << filePath);
DefaultContext context;
const char* fileUrl = isRelative ? this->GetUrl(filePath) : filePath;
OmniClientContent omniContent{ (void*)data, dataSize, nullptr };
omniClientWait(omniClientWriteFile(fileUrl, &omniContent, &context, [](void* userData, OmniClientResult result) OMNICLIENT_NOEXCEPT
{
auto& context = *(DefaultContext*)(userData);
context.result = result;
context.done = true;
})
);
return context.result == eOmniClientResult_Ok || context.result == eOmniClientResult_OkLatest;
}
bool UsdBridgeRemoteConnection::RemoveFile(const char* filePath, bool isRelative) const
{
DefaultContext context;
UsdBridgeLogMacro(UsdBridgeLogLevel::STATUS, "Removing file: " << filePath);
const char* fileUrl = isRelative ? this->GetUrl(filePath) : filePath;
omniClientWait(omniClientDelete(fileUrl, &context, [](void* userData, OmniClientResult result) OMNICLIENT_NOEXCEPT
{
auto& context = *(DefaultContext*)(userData);
context.result = result;
context.done = true;
})
);
return context.result == eOmniClientResult_Ok || context.result == eOmniClientResult_OkLatest;
}
bool UsdBridgeRemoteConnection::ProcessUpdates()
{
omniClientLiveProcess();
return true;
}
bool UsdBridgeRemoteConnection::CheckWritePermissions()
{
bool success = this->CreateFolder("", true, true);
return success;
}
void UsdBridgeRemoteConnection::SetConnectionLogLevel(int logLevel)
{
ConnectionLogLevel = logLevel;
if (NumConnInstances > 0)
{
UsdBridgeSetConnectionLogLevel(logLevel);
}
}
int UsdBridgeRemoteConnection::GetConnectionLogLevelMax()
{
return Count_eOmniClientLogLevel - 1;
}
#else
const char* UsdBridgeRemoteConnection::GetBaseUrl() const
{
return UsdBridgeConnection::GetBaseUrl();
}
const char* UsdBridgeRemoteConnection::GetUrl(const char* path) const
{
return UsdBridgeConnection::GetUrl(path);
}
bool UsdBridgeRemoteConnection::Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj)
{
return UsdBridgeConnection::Initialize(settings, logObj);
}
void UsdBridgeRemoteConnection::Shutdown()
{
UsdBridgeConnection::Shutdown();
}
int UsdBridgeRemoteConnection::MaxSessionNr() const
{
return UsdBridgeConnection::MaxSessionNr();
}
bool UsdBridgeRemoteConnection::CreateFolder(const char* dirName, bool isRelative, bool mayExist) const
{
return UsdBridgeConnection::CreateFolder(dirName, isRelative, mayExist);
}
bool UsdBridgeRemoteConnection::RemoveFolder(const char* dirName, bool isRelative) const
{
return UsdBridgeConnection::RemoveFolder(dirName, isRelative);
}
bool UsdBridgeRemoteConnection::WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary) const
{
return UsdBridgeConnection::WriteFile(data, dataSize, filePath, isRelative, binary);
}
bool UsdBridgeRemoteConnection::RemoveFile(const char* filePath, bool isRelative) const
{
return UsdBridgeConnection::RemoveFile(filePath, isRelative);
}
bool UsdBridgeRemoteConnection::ProcessUpdates()
{
UsdBridgeConnection::ProcessUpdates();
return true;
}
bool UsdBridgeRemoteConnection::CheckWritePermissions()
{
return true;
}
void UsdBridgeRemoteConnection::SetConnectionLogLevel(int logLevel)
{
}
int UsdBridgeRemoteConnection::GetConnectionLogLevelMax()
{
return 0;
}
#endif //OMNIVERSE_CONNECTION_ENABLE
UsdBridgeLocalConnection::UsdBridgeLocalConnection()
{
}
UsdBridgeLocalConnection::~UsdBridgeLocalConnection()
{
}
const char* UsdBridgeLocalConnection::GetBaseUrl() const
{
return UsdBridgeConnection::GetBaseUrl();
}
const char* UsdBridgeLocalConnection::GetUrl(const char* path) const
{
return UsdBridgeConnection::GetUrl(path);
}
bool UsdBridgeLocalConnection::Initialize(const UsdBridgeConnectionSettings& settings, const UsdBridgeLogObject& logObj)
{
bool initSuccess = UsdBridgeConnection::Initialize(settings, logObj);
if (initSuccess)
{
if (settings.WorkingDirectory.length() == 0)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Local Output Directory not set, cannot initialize output.");
return false;
}
bool workingDirExists = fs::exists(settings.WorkingDirectory);
if (!workingDirExists)
workingDirExists = fs::create_directory(settings.WorkingDirectory);
if (!workingDirExists)
{
UsdBridgeLogMacro(UsdBridgeLogLevel::ERR, "Cannot create Local Output Directory, are permissions set correctly?");
return false;
}
else
{
return true;
}
}
return initSuccess;
}
void UsdBridgeLocalConnection::Shutdown()
{
UsdBridgeConnection::Shutdown();
}
int UsdBridgeLocalConnection::MaxSessionNr() const
{
return UsdBridgeConnection::MaxSessionNr();
}
bool UsdBridgeLocalConnection::CreateFolder(const char* dirName, bool isRelative, bool mayExist) const
{
return UsdBridgeConnection::CreateFolder(dirName, isRelative, mayExist);
}
bool UsdBridgeLocalConnection::RemoveFolder(const char* dirName, bool isRelative) const
{
return UsdBridgeConnection::RemoveFolder(dirName, isRelative);
}
bool UsdBridgeLocalConnection::WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary) const
{
return UsdBridgeConnection::WriteFile(data, dataSize, filePath, isRelative, binary);
}
bool UsdBridgeLocalConnection::RemoveFile(const char* filePath, bool isRelative) const
{
return UsdBridgeConnection::RemoveFile(filePath, isRelative);
}
bool UsdBridgeLocalConnection::ProcessUpdates()
{
UsdBridgeConnection::ProcessUpdates();
return true;
}
UsdBridgeVoidConnection::UsdBridgeVoidConnection()
{
}
UsdBridgeVoidConnection::~UsdBridgeVoidConnection()
{
}
const char* UsdBridgeVoidConnection::GetBaseUrl() const
{
return UsdBridgeConnection::GetBaseUrl();
}
const char* UsdBridgeVoidConnection::GetUrl(const char* path) const
{
return UsdBridgeConnection::GetUrl(path);
}
bool UsdBridgeVoidConnection::Initialize(const UsdBridgeConnectionSettings& settings, const UsdBridgeLogObject& logObj)
{
bool initialized = UsdBridgeConnection::Initialize(settings, logObj);
Settings.WorkingDirectory = "./";// Force relative working directory in case of unforeseen usd saves based on GetUrl()
return initialized;
}
void UsdBridgeVoidConnection::Shutdown()
{
UsdBridgeConnection::Shutdown();
}
int UsdBridgeVoidConnection::MaxSessionNr() const
{
return -1;
}
bool UsdBridgeVoidConnection::CreateFolder(const char* dirName, bool isRelative, bool mayExist) const
{
return true;
}
bool UsdBridgeVoidConnection::RemoveFolder(const char* dirName, bool isRelative) const
{
return true;
}
bool UsdBridgeVoidConnection::WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary) const
{
return true;
}
bool UsdBridgeVoidConnection::RemoveFile(const char* filePath, bool isRelative) const
{
return true;
}
bool UsdBridgeVoidConnection::ProcessUpdates()
{
return true;
} | 23,255 | C++ | 28.033708 | 178 | 0.697613 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/Connection/UsdBridgeConnection.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeConnection_h
#define UsdBridgeConnection_h
#include "UsdBridgeData.h"
#include <string>
class UsdBridgeRemoteConnectionInternals;
struct UsdBridgeConnectionSettings
{
std::string HostName;
std::string WorkingDirectory;
};
class UsdBridgeConnection
{
public:
UsdBridgeConnection() {}
virtual ~UsdBridgeConnection() {};
virtual const char* GetBaseUrl() const = 0;
virtual const char* GetUrl(const char* path) const = 0;
virtual bool Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj) = 0;
virtual void Shutdown() = 0;
virtual int MaxSessionNr() const = 0;
virtual bool CreateFolder(const char* dirName, bool isRelative, bool mayExist) const = 0;
virtual bool RemoveFolder(const char* dirName, bool isRelative) const = 0;
virtual bool WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary = true) const = 0;
virtual bool RemoveFile(const char* filePath, bool isRelative) const = 0;
virtual bool ProcessUpdates() = 0;
static UsdBridgeLogCallback LogCallback;
static void* LogUserData;
UsdBridgeConnectionSettings Settings;
protected:
mutable std::string TempUrl;
};
class UsdBridgeLocalConnection : public UsdBridgeConnection
{
public:
UsdBridgeLocalConnection();
~UsdBridgeLocalConnection() override;
const char* GetBaseUrl() const override;
const char* GetUrl(const char* path) const override;
bool Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj) override;
void Shutdown() override;
int MaxSessionNr() const override;
bool CreateFolder(const char* dirName, bool isRelative, bool mayExist) const override;
bool RemoveFolder(const char* dirName, bool isRelative) const override;
bool WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary = true) const override;
bool RemoveFile(const char* filePath, bool isRelative) const override;
bool ProcessUpdates() override;
protected:
};
class UsdBridgeRemoteConnection : public UsdBridgeConnection
{
public:
UsdBridgeRemoteConnection();
~UsdBridgeRemoteConnection() override;
const char* GetBaseUrl() const override;
const char* GetUrl(const char* path) const override;
bool Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj) override;
void Shutdown() override;
int MaxSessionNr() const override;
bool CreateFolder(const char* dirName, bool isRelative, bool mayExist) const override;
bool RemoveFolder(const char* dirName, bool isRelative) const override;
bool WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary = true) const override;
bool RemoveFile(const char* filePath, bool isRelative) const override;
bool ProcessUpdates() override;
static void SetConnectionLogLevel(int logLevel);
static int GetConnectionLogLevelMax();
static int NumConnInstances;
static int NumInitializedConnInstances;
protected:
bool CheckWritePermissions();
UsdBridgeRemoteConnectionInternals* Internals;
bool ConnectionInitialized = false;
static int ConnectionLogLevel;
};
class UsdBridgeVoidConnection : public UsdBridgeConnection
{
public:
UsdBridgeVoidConnection();
~UsdBridgeVoidConnection() override;
const char* GetBaseUrl() const override;
const char* GetUrl(const char* path) const override;
bool Initialize(const UsdBridgeConnectionSettings& settings,
const UsdBridgeLogObject& logObj) override;
void Shutdown() override;
int MaxSessionNr() const override;
bool CreateFolder(const char* dirName, bool isRelative, bool mayExist) const override;
bool RemoveFolder(const char* dirName, bool isRelative) const override;
bool WriteFile(const char* data, size_t dataSize, const char* filePath, bool isRelative, bool binary = true) const override;
bool RemoveFile(const char* filePath, bool isRelative) const override;
bool ProcessUpdates() override;
protected:
};
#endif
| 4,118 | C | 28.007042 | 129 | 0.774648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.