file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/iot-samples/source/omni/live/live_edit_session.py | import os
from .nucleus_client_error import NucleusClientError
from .nucleus_server_config import nucleus_server_config
import omni.client
from pxr import Sdf
class LiveEditSession:
"""
Class used to create a live edit session (unless already exists) on
the Nucleus server, by writing a session toml file and
creating a .live stage
Session name: {org_id}_{simulation_id}_iot_session
Root folder: .live/{usd-file-name}.live/{session-name}/root.live
session_folder_url: {root_folder}/.live/{usd-file-name}.live
live_session_url: {session_folder_url}/{session-name}/root.live
toml_url: {session_folder_url}/{session-name}/__session__.toml
"""
def __init__(self, stage_url):
self.session_name = "iot_session"
self.stage_url = stage_url
self.omni_url = omni.client.break_url(self.stage_url)
root_folder = self._make_root_folder_path()
self.session_folder_url = self._make_url(root_folder)
live_session_folder = f"{root_folder}/{self.session_name}.live"
self.live_session_url = self._make_url(f"{live_session_folder}/root.live")
self.toml_url = self._make_url(f"{live_session_folder}/__session__.toml")
async def ensure_exists(self):
"""Either find an existing live edit session or create a new one"""
# get the folder contains the sessions and list the available sessions
_result, sessions = await omni.client.list_async(self.session_folder_url)
for entry in sessions:
session_name = os.path.splitext(entry.relative_path)[0]
if session_name == self.session_name:
# session exists so exit
return self._ensure_live_layer()
# create new session
# first create the toml file
self._write_session_toml()
return self._ensure_live_layer()
def _ensure_live_layer(self):
# create a new root.live session file
live_layer = Sdf.Layer.FindOrOpen(self.live_session_url)
if not live_layer:
live_layer = Sdf.Layer.CreateNew(self.live_session_url)
if not live_layer:
raise Exception(f"Could load the live layer {self.live_session_url}.")
Sdf.PrimSpec(live_layer, "iot", Sdf.SpecifierDef, "IoT Root")
live_layer.Save()
return live_layer
def _make_url(self, path):
return omni.client.make_url(
self.omni_url.scheme,
self.omni_url.user,
self.omni_url.host,
self.omni_url.port,
path,
)
def _make_root_folder_path(self):
"""
construct the folder that would contain sessions:
{.live}/{usd-file-name.live}/{session_name}/root.live
"""
stage_file_name = os.path.splitext(os.path.basename(self.omni_url.path))[0]
return f"{os.path.dirname(self.omni_url.path)}/.live/{stage_file_name}.live"
def _write_session_toml(self):
"""
writes the session toml to Nucleus
OWNER_KEY = "user_name"
STAGE_URL_KEY = "stage_url"
MODE_KEY = "mode" (possible modes - "default" = "root_authoring",
"auto_authoring", "project_authoring")
SESSION_NAME_KEY = "session_name"
"""
session_config = nucleus_server_config(self)
toml_string = "".join([f'{key} = "{value}"\n' for (key, value) in session_config.items()])
result = omni.client.write_file(self.toml_url, self._toml_bytes(toml_string))
if result != omni.client.Result.OK:
raise NucleusClientError(
f"Error writing live session toml file {self.toml_url}, " f"with configuration {session_config}"
)
@staticmethod
def _toml_bytes(toml_string):
return bytes(toml_string, "utf-8")
| 3,862 | Python | 36.504854 | 112 | 0.613413 |
NVIDIA-Omniverse/iot-samples/source/ingest_app_csv/app.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# pip install pandas
import asyncio
import os
import omni.client
from pxr import Usd, Sdf, Gf
from pathlib import Path
import pandas as pd
import time
from omni.live import LiveEditSession, LiveCube, getUserNameFromToken
OMNI_HOST = os.environ.get("OMNI_HOST", "localhost")
OMNI_USER = os.environ.get("OMNI_USER", "ov")
if OMNI_USER.lower() == "omniverse":
OMNI_USER = "ov"
elif OMNI_USER.lower() == "$omni-api-token":
OMNI_USER = getUserNameFromToken(os.environ.get("OMNI_PASS"))
BASE_FOLDER = "omniverse://" + OMNI_HOST + "/Users/" + OMNI_USER + "/iot-samples"
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
CONTENT_DIR = Path(SCRIPT_DIR).resolve().parents[1].joinpath("content")
messages = []
def log_handler(thread, component, level, message):
# print(message)
messages.append((thread, component, level, message))
def initialize_device_prim(live_layer, iot_topic):
iot_root = live_layer.GetPrimAtPath("/iot")
if not iot_root:
iot_root = Sdf.PrimSpec(live_layer, "iot", Sdf.SpecifierDef, "IoT Root")
iot_spec = live_layer.GetPrimAtPath(f"/iot/{iot_topic}")
if not iot_spec:
iot_spec = Sdf.PrimSpec(iot_root, iot_topic, Sdf.SpecifierDef, "ConveyorBelt Type")
if not iot_spec:
raise Exception("Failed to create the IoT Spec.")
# clear out any attrubutes that may be on the spec
for attrib in iot_spec.attributes:
iot_spec.RemoveProperty(attrib)
IOT_TOPIC_DATA = f"{CONTENT_DIR}/{iot_topic}_iot_data.csv"
data = pd.read_csv(IOT_TOPIC_DATA)
data.head()
# create all the IoT attributes that will be written
attr = Sdf.AttributeSpec(iot_spec, "_ts", Sdf.ValueTypeNames.Double)
if not attr:
raise Exception(f"Could not define the attribute: {attrName}")
# infer the unique data points in the CSV.
# The values may be known in advance and can be hard coded
grouped = data.groupby("Id")
for attrName, group in grouped:
attr = Sdf.AttributeSpec(iot_spec, attrName, Sdf.ValueTypeNames.Double)
if not attr:
raise Exception(f"Could not define the attribute: {attrName}")
async def initialize_async(iot_topic):
# copy a the Conveyor Belt to the target nucleus server
stage_name = f"ConveyorBelt_{iot_topic}"
local_folder = f"file:{CONTENT_DIR}/{stage_name}"
stage_folder = f"{BASE_FOLDER}/{stage_name}"
stage_url = f"{stage_folder}/{stage_name}.usd"
result = await omni.client.copy_async(
local_folder,
stage_folder,
behavior=omni.client.CopyBehavior.ERROR_IF_EXISTS,
message="Copy Conveyor Belt",
)
stage = Usd.Stage.Open(stage_url)
if not stage:
raise Exception(f"Could load the stage {stage_url}.")
live_session = LiveEditSession(stage_url)
live_layer = await live_session.ensure_exists()
session_layer = stage.GetSessionLayer()
session_layer.subLayerPaths.append(live_layer.identifier)
# set the live layer as the edit target
stage.SetEditTarget(live_layer)
initialize_device_prim(live_layer, iot_topic)
# place the cube on the conveyor
live_cube = LiveCube(stage)
live_cube.scale(Gf.Vec3f(0.5))
live_cube.translate(Gf.Vec3f(100.0, -30.0, 195.0))
omni.client.live_process()
return stage, live_layer
def write_to_live(live_layer, iot_topic, group, ts):
# write the iot values to the usd prim attributes
print(group.iloc[0]["TimeStamp"])
ts_attribute = live_layer.GetAttributeAtPath(f"/iot/{iot_topic}._ts")
ts_attribute.default = ts
with Sdf.ChangeBlock():
for index, row in group.iterrows():
id = row["Id"]
value = row["Value"]
attr = live_layer.GetAttributeAtPath(f"/iot/{iot_topic}.{id}")
if not attr:
raise Exception(f"Could not find attribute /iot/{iot_topic}.{id}.")
attr.default = value
omni.client.live_process()
def run(stage, live_layer, iot_topic):
# we assume that the file contains the data for single device
IOT_TOPIC_DATA = f"{CONTENT_DIR}/{iot_topic}_iot_data.csv"
data = pd.read_csv(IOT_TOPIC_DATA)
data.head()
# Converting to DateTime Format and drop ms
data["TimeStamp"] = pd.to_datetime(data["TimeStamp"])
data["TimeStamp"] = data["TimeStamp"].dt.floor("s")
data.set_index("TimeStamp")
start_time = data.min()["TimeStamp"]
last_time = start_time
grouped = data.groupby("TimeStamp")
# play back the data in real-time
for next_time, group in grouped:
diff = (next_time - last_time).total_seconds()
if diff > 0:
time.sleep(diff)
write_to_live(live_layer, iot_topic, group, (next_time - start_time).total_seconds())
last_time = next_time
if __name__ == "__main__":
IOT_TOPIC = "A08_PR_NVD_01"
omni.client.initialize()
omni.client.set_log_level(omni.client.LogLevel.DEBUG)
omni.client.set_log_callback(log_handler)
try:
stage, live_layer = asyncio.run(initialize_async(IOT_TOPIC))
run(stage, live_layer, IOT_TOPIC)
except:
print("---- LOG MESSAGES ---")
print(*messages, sep="\n")
print("----")
finally:
omni.client.shutdown()
| 6,421 | Python | 35.908046 | 98 | 0.678399 |
NVIDIA-Omniverse/iot-samples/source/ingest_app_csv/run_app.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
import argparse
import platform
import subprocess
from pathlib import Path
PLATFORM_SYSTEM = platform.system().lower()
PLATFORM_MACHINE = platform.machine()
if PLATFORM_MACHINE == "i686" or PLATFORM_MACHINE == "AMD64":
PLATFORM_MACHINE = "x86_64"
CURRENT_PLATFORM = f"{PLATFORM_SYSTEM}-{PLATFORM_MACHINE}"
default_username = os.environ.get("OMNI_USER")
default_password = os.environ.get("OMNI_PASS")
default_server = os.environ.get("OMNI_HOST", "localhost")
parser = argparse.ArgumentParser()
parser.add_argument("--server", "-s", default=default_server)
parser.add_argument("--username", "-u", default=default_username)
parser.add_argument("--password", "-p", default=default_password)
parser.add_argument("--config", "-c", choices=["debug", "release"], default="release")
parser.add_argument("--platform", default=CURRENT_PLATFORM)
args = parser.parse_args()
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = Path(SCRIPT_DIR).resolve().parents[1]
BUILD_DIR = ROOT_DIR.joinpath("_build", args.platform, args.config)
DEPS_DIR = ROOT_DIR.joinpath("_build", "target-deps")
USD_BIN_DIR = DEPS_DIR.joinpath("usd", args.config, "bin")
USD_LIB_DIR = DEPS_DIR.joinpath("usd", args.config, "lib")
CLIENT_LIB_DIR = DEPS_DIR.joinpath("omni_client_library", args.config)
RESOLVER_DIR = DEPS_DIR.joinpath("omni_usd_resolver", args.config)
EXTRA_PATHS = [str(CLIENT_LIB_DIR), str(USD_BIN_DIR), str(USD_LIB_DIR), str(BUILD_DIR), str(RESOLVER_DIR)]
EXTRA_PYTHON_PATHS = [
str(Path(SCRIPT_DIR).resolve().parents[0]),
str(USD_LIB_DIR.joinpath("python")),
str(CLIENT_LIB_DIR.joinpath("bindings-python")),
str(BUILD_DIR.joinpath("bindings-python")),
]
if PLATFORM_SYSTEM == "windows":
os.environ["PATH"] += os.pathsep + os.pathsep.join(EXTRA_PATHS)
ot_bin = "carb.omnitrace.plugin.dll"
else:
p = os.environ.get("LD_LIBRARY_PATH", "")
p += os.pathsep + os.pathsep.join(EXTRA_PATHS)
os.environ["LD_LIBRARY_PATH"] = p
ot_bin = "libcarb.omnitrace.plugin.so"
os.environ["OMNI_TRACE_LIB"] = os.path.join(str(DEPS_DIR), "omni-trace", "bin", ot_bin)
os.environ["PYTHONPATH"] = os.pathsep + os.pathsep.join(EXTRA_PYTHON_PATHS)
os.environ["OMNI_USER"] = args.username
os.environ["OMNI_PASS"] = args.password
os.environ["OMNI_HOST"] = args.server
if PLATFORM_SYSTEM == "windows":
PYTHON_EXE = DEPS_DIR.joinpath("python", "python")
else:
PYTHON_EXE = DEPS_DIR.joinpath("python", "bin", "python3")
plugin_paths = DEPS_DIR.joinpath("omni_usd_resolver", args.config, "usd", "omniverse", "resources")
os.environ["PXR_PLUGINPATH_NAME"] = str(plugin_paths)
REQ_FILE = ROOT_DIR.joinpath("requirements.txt")
subprocess.run(f"{PYTHON_EXE} -m pip install -r {REQ_FILE}", shell=True)
result = subprocess.run(
[PYTHON_EXE, os.path.join(SCRIPT_DIR, "app.py")],
stderr=subprocess.STDOUT,
)
| 3,268 | Python | 39.8625 | 106 | 0.717258 |
NVIDIA-Omniverse/ext-openvdb/MAINTAINERS.md | <!-- SPDX-License-Identifier: CC-BY-4.0 -->
<!-- Copyright Contributors to the OpenVDB project. -->
# OpenVDB Committers
The current OpenVDB maintainers are:
| Name | Email |
| -------------- | -----------------
| Jeff Lait | [email protected]
| Dan Bailey | [email protected]
| Nick Avramoussis | [email protected]
| Ken Museth | [email protected]
| Peter Cucka | [email protected]
| 403 | Markdown | 24.249998 | 55 | 0.630273 |
NVIDIA-Omniverse/ext-openvdb/CODE_OF_CONDUCT.md | All participants agree to abide by LF Projects Code of Conduct (as defined in the [charter](tsc/charter.md)) available at https://lfprojects.org/policies/code-of-conduct/
| 171 | Markdown | 84.999958 | 170 | 0.789474 |
NVIDIA-Omniverse/ext-openvdb/CONTRIBUTING.md | # Overview
This project aims to be governed in a transparent, accessible way for the benefit of the community. All participation in this project is open and not bound to corporate affiliation. Participants are all bound to the [Code of Conduct](CODE_OF_CONDUCT.md).
# Project roles
## Contributor
The contributor role is the starting role for anyone participating in the project and wishing to contribute code.
### Process for becoming a contributor
* Review the [coding standards](http://www.openvdb.org/documentation/doxygen/codingStyle.html) to ensure your contribution is in line with the project's coding and styling guidelines.
* Have a signed CLA on file ( see [below](#contributor-license-agreements) )
* Submit your code as a PR with the appropriate [DCO sign-off](#commit-sign-off).
* Have your submission approved by the [committer(s)](#committer) and merged into the codebase.
### Legal Requirements
OpenVDB is a project of the Academy Software Foundation and follows the
open source software best practice policies of the Linux Foundation.
#### License
OpenVDB is licensed under the [Mozilla Public License, version 2.0](LICENSE.md)
license. Contributions to OpenVDB should abide by that standard
license.
#### Contributor License Agreements
Developers who wish to contribute code to be considered for inclusion
in OpenVDB must first complete a **Contributor License Agreement**.
OpenVDB uses [EasyCLA](https://lfcla.com/) for managing CLAs, which automatically
checks to ensure CLAs are signed by a contributor before a commit
can be merged.
* If you are an individual writing the code on your own time and
you're SURE you are the sole owner of any intellectual property you
contribute, you can [sign the CLA as an individual contributor](https://docs.linuxfoundation.org/lfx/easycla/contributors/individual-contributor).
* If you are writing the code as part of your job, or if there is any
possibility that your employers might think they own any
intellectual property you create, then you should use the [Corporate
Contributor Licence
Agreement](https://docs.linuxfoundation.org/lfx/easycla/contributors/corporate-contributor).
The OpenVDB CLAs are the standard forms used by Linux Foundation
projects and [recommended by the ASWF TAC](https://github.com/AcademySoftwareFoundation/tac/blob/master/process/contributing.md#contributor-license-agreement-cla). You can review the text of the CLAs in the [TSC directory](tsc/).
#### Commit Sign-Off
Every commit must be signed off. That is, every commit log message
must include a “`Signed-off-by`” line (generated, for example, with
“`git commit --signoff`”), indicating that the committer wrote the
code and has the right to release it under the
[Mozilla Public License, version 2.0](LICENSE.md)
license. See the [TAC documentation on contribution sign off](https://github.com/AcademySoftwareFoundation/tac/blob/master/process/contributing.md#contribution-sign-off) for more information on this requirement.
## Committer
The committer role enables the participant to commit code directly to the repository, but also comes with the obligation to be a responsible leader in the community.
### Process for becoming a committer
* Show your experience with the codebase through contributions and engagement on the community channels.
* Request to become a committer.
* Have the majority of committers approve you becoming a committer.
* Your name and email is added to the MAINTAINERS.md file for the project.
### Committer responsibilities
* Monitor email aliases.
* Monitor Slack (delayed response is perfectly acceptable).
* Triage GitHub issues and perform pull request reviews for other committers and the community.
* Make sure that ongoing PRs are moving forward at the right pace or close them.
* Remain an active contributor to the project in general and the code base in particular.
### When does a committer lose committer status?
If a committer is no longer interested or cannot perform the committer duties listed above, they
should volunteer to be moved to emeritus status. In extreme cases this can also occur by a vote of
the committers per the voting process below.
## Technical Steering Committee (TSC) member
The Technical Steering Committee (TSC) oversees the overall technical direction of OpenVDB, as defined in the [charter](charter.md).
TSC voting members consist of committers that have been nominated by the committers, with a supermajority of voting members required to have a committer elected to be a TSC voting member. TSC voting members term and succession is defined in the [charter](charter.md).
All meetings of the TSC are open to participation by any member of the OpenVDB community. Meeting times are listed in the [ASWF technical community calendar](https://lists.aswf.io/g/tac/calendar).
## Current TSC members
* Ken Museth, Chair / Weta
* Peter Cucka, DreamWorks
* Jeff Lait, SideFX
* Nick Avramoussis, DNEG
* Dan Bailey, ILM
# Release Process
Project releases will occur on a scheduled basis as agreed to by the TSC.
# Conflict resolution and voting
In general, we prefer that technical issues and committer status/TSC membership are amicably worked out
between the persons involved. If a dispute cannot be decided independently, the TSC can be
called in to decide an issue. If the TSC themselves cannot decide an issue, the issue will
be resolved by voting. The voting process is a simple majority in which each TSC receives one vote.
# Communication
This project, just like all of open source, is a global community. In addition to the [Code of Conduct](CODE_OF_CONDUCT.md), this project will:
* Keep all communication on open channels ( mailing list, forums, chat ).
* Be respectful of time and language differences between community members ( such as scheduling meetings, email/issue responsiveness, etc ).
* Ensure tools are able to be used by community members regardless of their region.
If you have concerns about communication challenges for this project, please contact the [TSC](mailto:[email protected]).
| 6,085 | Markdown | 49.29752 | 267 | 0.790633 |
NVIDIA-Omniverse/ext-openvdb/README.md | 
[](LICENSE.md)
[](https://bestpractices.coreinfrastructure.org/projects/2774)
| Build | Status |
| --------------- | ------ |
| OpenVDB | [](https://github.com/AcademySoftwareFoundation/openvdb/actions?query=workflow%3ABuild) |
| OpenVDB AX | [](https://github.com/AcademySoftwareFoundation/openvdb/actions?query=workflow%3Aax) |
[Website](https://www.openvdb.org) |
[Discussion Forum](https://www.openvdb.org/forum) |
[Documentation](https://www.openvdb.org/documentation/)
OpenVDB is an open source C++ library comprising a novel hierarchical data structure and a large suite of tools for the efficient storage and manipulation of sparse volumetric data discretized on three-dimensional grids. It was developed by DreamWorks Animation for use in volumetric applications typically encountered in feature film production.
### Development Repository
This GitHub repository hosts the trunk of the OpenVDB development. This implies that it is the newest public version with the latest features and bug fixes. However, it also means that it has not undergone a lot of testing and is generally less stable than the [production releases](https://github.com/AcademySoftwareFoundation/openvdb/releases).
### License
OpenVDB is released under the [Mozilla Public License Version 2.0](https://www.mozilla.org/MPL/2.0/), which is a free, open source software license developed and maintained by the Mozilla Foundation.
The trademarks of any contributor to this project may not be used in association with the project without the contributor's express permission.
### Contributing
OpenVDB welcomes contributions to the OpenVDB project. Please refer to the [contribution guidelines](CONTRIBUTING.md) for details on how to make a contribution.
### Developer Quick Start
See the [build documentation](https://www.openvdb.org/documentation/doxygen/build.html) for help with installations.
#### Linux
##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc)
```
apt-get install -y libboost-iostreams-dev
apt-get install -y libboost-system-dev
apt-get install -y libtbb-dev
apt-get install -y libilmbase-dev
apt-get install -y libopenexr-dev
```
```
git clone [email protected]:Blosc/c-blosc.git
cd c-blosc
git checkout tags/v1.5.0 -b v1.5.0
mkdir build
cd build
cmake ..
make -j4
make install
cd ../..
```
##### Building OpenVDB
```
git clone [email protected]:AcademySoftwareFoundation/openvdb.git
cd openvdb
mkdir build
cd build
cmake ..
make -j4
make install
```
#### macOS
##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc)
```
brew install boost
brew install tbb
brew install ilmbase
brew install openexr
```
```
git clone [email protected]:Blosc/c-blosc.git
cd c-blosc
git checkout tags/v1.5.0 -b v1.5.0
mkdir build
cd build
cmake ..
make -j4
make install
cd ../..
```
##### Building OpenVDB
```
git clone [email protected]:AcademySoftwareFoundation/openvdb.git
cd openvdb
mkdir build
cd build
cmake ..
make -j4
make install
```
#### Windows
##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc)
Note that the following commands have only been tested for 64bit systems/libraries.
It is recommended to set the `VCPKG_DEFAULT_TRIPLET` environment variable to
`x64-windows` to use 64-bit libraries by default. You will also require
[Git](https://git-scm.com/downloads), [vcpkg](https://github.com/microsoft/vcpkg)
and [CMake](https://cmake.org/download/) to be installed.
```
vcpkg install zlib:x64-windows
vcpkg install blosc:x64-windows
vcpkg install openexr:x64-windows
vcpkg install tbb:x64-windows
vcpkg install boost-iostreams:x64-windows
vcpkg install boost-system:x64-windows
vcpkg install boost-any:x64-windows
vcpkg install boost-algorithm:x64-windows
vcpkg install boost-uuid:x64-windows
vcpkg install boost-interprocess:x64-windows
```
##### Building OpenVDB
```
git clone [email protected]:AcademySoftwareFoundation/openvdb.git
cd openvdb
mkdir build
cd build
cmake -DCMAKE_TOOLCHAIN_FILE=<PATH_TO_VCPKG>\scripts\buildsystems\vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows -A x64 ..
cmake --build . --parallel 4 --config Release --target install
```
| 4,492 | Markdown | 34.101562 | 346 | 0.766919 |
NVIDIA-Omniverse/ext-openvdb/ci/download_houdini.py | #!/usr/local/bin/python
#
# Copyright Contributors to the OpenVDB Project
# SPDX-License-Identifier: MPL-2.0
#
# Python script to download the latest Houdini builds
# using the SideFX download API:
#
# https://www.sidefx.com/docs/api/download/index.html
#
# Authors: Dan Bailey, SideFX
import time
import sys
import re
import shutil
import json
import base64
import requests
import hashlib
# this argument is for the major.minor version of Houdini to download (such as 15.0, 15.5, 16.0)
version = sys.argv[1]
only_production = True if sys.argv[2] == 'ON' else False
user_client_id = sys.argv[3]
user_client_secret_key = sys.argv[4]
if not re.match('[0-9][0-9]\.[0-9]$', version):
raise IOError('Invalid Houdini Version "%s", expecting in the form "major.minor" such as "16.0"' % version)
# Code that provides convenient Python wrappers to call into the API:
def service(
access_token_url, client_id, client_secret_key, endpoint_url,
access_token=None, access_token_expiry_time=None):
if (access_token is None or
access_token_expiry_time is None or
access_token_expiry_time < time.time()):
access_token, access_token_expiry_time = (
get_access_token_and_expiry_time(
access_token_url, client_id, client_secret_key))
return _Service(
endpoint_url, access_token, access_token_expiry_time)
class _Service(object):
def __init__(
self, endpoint_url, access_token, access_token_expiry_time):
self.endpoint_url = endpoint_url
self.access_token = access_token
self.access_token_expiry_time = access_token_expiry_time
def __getattr__(self, attr_name):
return _APIFunction(attr_name, self)
class _APIFunction(object):
def __init__(self, function_name, service):
self.function_name = function_name
self.service = service
def __getattr__(self, attr_name):
# This isn't actually an API function, but a family of them. Append
# the requested function name to our name.
return _APIFunction(
"{0}.{1}".format(self.function_name, attr_name), self.service)
def __call__(self, *args, **kwargs):
return call_api_with_access_token(
self.service.endpoint_url, self.service.access_token,
self.function_name, args, kwargs)
#---------------------------------------------------------------------------
# Code that implements authentication and raw calls into the API:
def get_access_token_and_expiry_time(
access_token_url, client_id, client_secret_key):
"""Given an API client (id and secret key) that is allowed to make API
calls, return an access token that can be used to make calls.
"""
response = requests.post(
access_token_url,
headers={
"Authorization": u"Basic {0}".format(
base64.b64encode(
"{0}:{1}".format(
client_id, client_secret_key
).encode()
).decode('utf-8')
),
})
if response.status_code != 200:
raise AuthorizationError(response.status_code, reponse.text)
response_json = response.json()
access_token_expiry_time = time.time() - 2 + response_json["expires_in"]
return response_json["access_token"], access_token_expiry_time
class AuthorizationError(Exception):
"""Raised from the client if the server generated an error while generating
an access token.
"""
def __init__(self, http_code, message):
super(AuthorizationError, self).__init__(message)
self.http_code = http_code
def call_api_with_access_token(
endpoint_url, access_token, function_name, args, kwargs):
"""Call into the API using an access token that was returned by
get_access_token.
"""
response = requests.post(
endpoint_url,
headers={
"Authorization": "Bearer " + access_token,
},
data=dict(
json=json.dumps([function_name, args, kwargs]),
))
if response.status_code == 200:
return response.json()
raise APIError(response.status_code, response.text)
class APIError(Exception):
"""Raised from the client if the server generated an error while calling
into the API.
"""
def __init__(self, http_code, message):
super(APIError, self).__init__(message)
self.http_code = http_code
service = service(
access_token_url="https://www.sidefx.com/oauth2/application_token",
client_id=user_client_id,
client_secret_key=user_client_secret_key,
endpoint_url="https://www.sidefx.com/api/",
)
releases_list = service.download.get_daily_builds_list(
product='houdini', version=version, platform='linux', only_production=only_production)
latest_release = service.download.get_daily_build_download(
product='houdini', version=version, platform='linux', build=releases_list[0]['build'])
# Download the file as hou.tar.gz
local_filename = 'hou.tar.gz'
response = requests.get(latest_release['download_url'], stream=True)
if response.status_code == 200:
with open(local_filename, 'wb') as f:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, f)
else:
raise Exception('Error downloading file!')
# Verify the file checksum is matching
file_hash = hashlib.md5()
with open(local_filename, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
file_hash.update(chunk)
if file_hash.hexdigest() != latest_release['hash']:
raise Exception('Checksum does not match!')
| 5,646 | Python | 32.217647 | 111 | 0.639922 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ax.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file ax.h
///
/// @author Nick Avramoussis
///
/// @brief Single header include which provides methods for initializing AX and
/// running a full AX pipeline (pasrsing, compiling and executing) across
/// standard OpenVDB Grid types.
///
/// @details These methods wrap the internal components of OpenVDB AX to
/// provide easier and quick access to running AX code. Users who wish to
/// further optimise and customise the process may interface with these
/// components directly. See the body of the methods provided in this file for
/// example implementations.
#ifndef OPENVDB_AX_AX_HAS_BEEN_INCLUDED
#define OPENVDB_AX_AX_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include <openvdb/version.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @brief Initializes OpenVDB AX and subsequent LLVM components.
/// @details Must be called before any AX compilation or execution is performed.
/// Can be safely called from multiple threads. Cannot be called after
/// uninitialize has been called.
void initialize();
/// @brief Check to see if OpenVDB AX components have been initialized.
/// @note Can be safely called from multiple threads.
bool isInitialized();
/// @brief Uninitialize and deregister OpenVDB AX.
/// @details This has the important function of shutting down LLVM and
/// correctly freeing statically allocated LLVM types. Should be
/// called on application termination. Can be safely called from
/// multiple threads.
void uninitialize();
////////////////////////////////////////
////////////////////////////////////////
/// @brief Run a full AX pipeline (parse, compile and execute) on a single
/// OpenVDB Grid.
/// @details This method wraps the parsing, compilation and execution of AX
/// code for a single OpenVDB grid of any standard grid type
/// (including OpenVDB Points Grids). Provided AX code is expected to
/// only refer to the provided single grid. On success, the grid will
/// have its voxels or point data modified as dictated by the provided
/// AX code.
/// @note Various defaults are applied to this pipeline to provide a simple
/// run signature. For OpenVDB Numerical grids, only active voxels are
/// processed. For OpenVDB Points grids, all points are processed. Any
/// warnings generated by the parser, compiler or executable will be
/// ignored.
/// @note Various runtime errors may be thrown from the different AX pipeline
/// stages. See Exceptions.h for the possible different errors.
/// @param ax The null terminated AX code string to parse and compile
/// @param grid The grid to which to apply the compiled AX function
void run(const char* ax, openvdb::GridBase& grid);
/// @brief Run a full AX pipeline (parse, compile and execute) on a vector of
/// OpenVDB numerical grids OR a vector of OpenVDB Point Data grids.
/// @details This method wraps the parsing, compilation and execution of AX
/// code for a vector of OpenVDB grids. The vector must contain either
/// a set of any numerical grids supported by the default AX types OR
/// a set of OpenVDB Points grids. On success, grids in the provided
/// grid vector will be iterated over and updated if they are written
/// to.
/// @warning The type of grids provided changes the type of AX compilation. If
/// the vector is empty, this function immediately returns with no
/// other effect.
/// @note Various defaults are applied to this pipeline to provide a simple
/// run signature. For numerical grids, only active voxels are processed
/// and missing grid creation is disabled. For OpenVDB Points grids, all
/// points are processed. Any warnings generated by the parser, compiler
/// or executable will be ignored.
/// @note Various runtime errors may be thrown from the different AX pipeline
/// stages. See Exceptions.h for the possible different errors.
/// @param ax The null terminated AX code string to parse and compile
/// @param grids The grids to which to apply the compiled AX function
void run(const char* ax, openvdb::GridPtrVec& grids);
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_AX_HAS_BEEN_INCLUDED
| 4,543 | C | 46.333333 | 81 | 0.692494 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ax.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "ax.h"
#include "ast/AST.h"
#include "compiler/Logger.h"
#include "compiler/Compiler.h"
#include "compiler/PointExecutable.h"
#include "compiler/VolumeExecutable.h"
#include <llvm/InitializePasses.h>
#include <llvm/PassRegistry.h>
#include <llvm/Config/llvm-config.h> // version numbers
#include <llvm/Support/TargetSelect.h> // InitializeNativeTarget
#include <llvm/Support/ManagedStatic.h> // llvm_shutdown
#include <llvm/ExecutionEngine/MCJIT.h> // LLVMLinkInMCJIT
#include <tbb/mutex.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @note Implementation for initialize, isInitialized and unitialized
/// reamins in compiler/Compiler.cc
void run(const char* ax, openvdb::GridBase& grid)
{
// Construct a logger that will output errors to cerr and suppress warnings
openvdb::ax::Logger logger;
// Construct a generic compiler
openvdb::ax::Compiler compiler;
// Parse the provided code and produce an abstract syntax tree
// @note Throws with parser errors if invalid. Parsable code does not
// necessarily equate to compilable code
const openvdb::ax::ast::Tree::ConstPtr
ast = openvdb::ax::ast::parse(ax, logger);
if (grid.isType<points::PointDataGrid>()) {
// Compile for Point support and produce an executable
// @note Throws compiler errors on invalid code. On success, returns
// the executable which can be used multiple times on any inputs
const openvdb::ax::PointExecutable::Ptr exe =
compiler.compile<openvdb::ax::PointExecutable>(*ast, logger);
// Execute on the provided points
// @note Throws on invalid point inputs such as mismatching types
exe->execute(static_cast<points::PointDataGrid&>(grid));
}
else {
// Compile for numerical grid support and produce an executable
// @note Throws compiler errors on invalid code. On success, returns
// the executable which can be used multiple times on any inputs
const openvdb::ax::VolumeExecutable::Ptr exe =
compiler.compile<openvdb::ax::VolumeExecutable>(*ast, logger);
// Execute on the provided numerical grid
// @note Throws on invalid grid inputs such as mismatching types
exe->execute(grid);
}
}
void run(const char* ax, openvdb::GridPtrVec& grids)
{
if (grids.empty()) return;
// Check the type of all grids. If they are all points, run for point data.
// Otherwise, run for numerical volumes. Throw if the container has both.
const bool points = grids.front()->isType<points::PointDataGrid>();
for (auto& grid : grids) {
if (points ^ grid->isType<points::PointDataGrid>()) {
OPENVDB_THROW(AXCompilerError,
"Unable to process both OpenVDB Points and OpenVDB Volumes in "
"a single invocation of ax::run()");
}
}
// Construct a logger that will output errors to cerr and suppress warnings
openvdb::ax::Logger logger;
// Construct a generic compiler
openvdb::ax::Compiler compiler;
// Parse the provided code and produce an abstract syntax tree
// @note Throws with parser errors if invalid. Parsable code does not
// necessarily equate to compilable code
const openvdb::ax::ast::Tree::ConstPtr
ast = openvdb::ax::ast::parse(ax, logger);
if (points) {
// Compile for Point support and produce an executable
// @note Throws compiler errors on invalid code. On success, returns
// the executable which can be used multiple times on any inputs
const openvdb::ax::PointExecutable::Ptr exe =
compiler.compile<openvdb::ax::PointExecutable>(*ast, logger);
// Execute on the provided points individually
// @note Throws on invalid point inputs such as mismatching types
for (auto& grid : grids) {
exe->execute(static_cast<points::PointDataGrid&>(*grid));
}
}
else {
// Compile for Volume support and produce an executable
// @note Throws compiler errors on invalid code. On success, returns
// the executable which can be used multiple times on any inputs
const openvdb::ax::VolumeExecutable::Ptr exe =
compiler.compile<openvdb::ax::VolumeExecutable>(*ast, logger);
// Execute on the provided volumes
// @note Throws on invalid grid inputs such as mismatching types
exe->execute(grids);
}
}
namespace {
// Declare this at file scope to ensure thread-safe initialization.
tbb::mutex sInitMutex;
bool sIsInitialized = false;
bool sShutdown = false;
}
bool isInitialized()
{
tbb::mutex::scoped_lock lock(sInitMutex);
return sIsInitialized;
}
void initialize()
{
tbb::mutex::scoped_lock lock(sInitMutex);
if (sIsInitialized) return;
if (sShutdown) {
OPENVDB_THROW(AXCompilerError,
"Unable to re-initialize LLVM target after uninitialize has been called.");
}
// Init JIT
if (llvm::InitializeNativeTarget() ||
llvm::InitializeNativeTargetAsmPrinter() ||
llvm::InitializeNativeTargetAsmParser())
{
OPENVDB_THROW(AXCompilerError,
"Failed to initialize LLVM target for JIT");
}
// required on some systems
LLVMLinkInMCJIT();
// Initialize passes
llvm::PassRegistry& registry = *llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(registry);
llvm::initializeScalarOpts(registry);
llvm::initializeObjCARCOpts(registry);
llvm::initializeVectorization(registry);
llvm::initializeIPO(registry);
llvm::initializeAnalysis(registry);
llvm::initializeTransformUtils(registry);
llvm::initializeInstCombine(registry);
#if LLVM_VERSION_MAJOR > 6
llvm::initializeAggressiveInstCombine(registry);
#endif
llvm::initializeInstrumentation(registry);
llvm::initializeTarget(registry);
// For codegen passes, only passes that do IR to IR transformation are
// supported.
llvm::initializeExpandMemCmpPassPass(registry);
llvm::initializeScalarizeMaskedMemIntrinPass(registry);
llvm::initializeCodeGenPreparePass(registry);
llvm::initializeAtomicExpandPass(registry);
llvm::initializeRewriteSymbolsLegacyPassPass(registry);
llvm::initializeWinEHPreparePass(registry);
llvm::initializeDwarfEHPreparePass(registry);
llvm::initializeSafeStackLegacyPassPass(registry);
llvm::initializeSjLjEHPreparePass(registry);
llvm::initializePreISelIntrinsicLoweringLegacyPassPass(registry);
llvm::initializeGlobalMergePass(registry);
#if LLVM_VERSION_MAJOR > 6
llvm::initializeIndirectBrExpandPassPass(registry);
#endif
#if LLVM_VERSION_MAJOR > 7
llvm::initializeInterleavedLoadCombinePass(registry);
#endif
llvm::initializeInterleavedAccessPass(registry);
llvm::initializeEntryExitInstrumenterPass(registry);
llvm::initializePostInlineEntryExitInstrumenterPass(registry);
llvm::initializeUnreachableBlockElimLegacyPassPass(registry);
llvm::initializeExpandReductionsPass(registry);
#if LLVM_VERSION_MAJOR > 6
llvm::initializeWasmEHPreparePass(registry);
#endif
llvm::initializeWriteBitcodePassPass(registry);
sIsInitialized = true;
}
void uninitialize()
{
tbb::mutex::scoped_lock lock(sInitMutex);
if (!sIsInitialized) return;
// @todo consider replacing with storage to Support/InitLLVM
llvm::llvm_shutdown();
sIsInitialized = false;
sShutdown = true;
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 7,742 | C++ | 36.587378 | 87 | 0.699303 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/Exceptions.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file openvdb_ax/Exceptions.h
///
/// @authors Nick Avramoussis, Richard Jones
///
/// @brief OpenVDB AX Exceptions
///
#ifndef OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED
#define OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <openvdb/Exceptions.h>
#include <sstream>
#include <string>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
#define OPENVDB_AX_EXCEPTION(_classname) \
class OPENVDB_API _classname: public Exception \
{ \
public: \
_classname() noexcept: Exception( #_classname ) {} \
explicit _classname(const std::string& msg) noexcept: Exception( #_classname , &msg) {} \
}
// @note: Compilation errors due to invalid AX code should be collected using a separate logging system.
// These errors are only thrown upon encountering fatal errors within the compiler/executables themselves
OPENVDB_AX_EXCEPTION(AXTokenError);
OPENVDB_AX_EXCEPTION(AXSyntaxError);
OPENVDB_AX_EXCEPTION(AXCodeGenError);
OPENVDB_AX_EXCEPTION(AXCompilerError);
OPENVDB_AX_EXCEPTION(AXExecutionError);
#undef OPENVDB_AX_EXCEPTION
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED
| 1,297 | C | 26.617021 | 107 | 0.758674 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/math/OpenSimplexNoise.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file math/OpenSimplexNoise.h
///
/// @authors Francisco Gochez
///
/// @brief Methods for generating OpenSimplexNoise (n-dimensional gradient noise)
///
/// @details This code is based on https://gist.github.com/tombsar/716134ec71d1b8c1b530
/// (accessed on 22/05/2019). We have simplified that code in a number of ways,
/// most notably by removing the template on dimension (this only generates 3
/// dimensional noise) and removing the base class as it's unnecessary for our
/// uses. We also assume C++ 2011 or above and have thus removed a number of
/// ifdef blocks.
///
/// The OSN namespace contains the original copyright.
///
#ifndef OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED
#define OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <cstdint>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace math {
template <typename NoiseT>
void curlnoise(double (*out)[3], const double (*in)[3])
{
float delta = 0.0001f;
float a, b;
// noise coordinates for vector potential components.
float p[3][3] = {
{ static_cast<float>((*in)[0]) + 000.0f, static_cast<float>((*in)[1]) + 000.0f, static_cast<float>((*in)[2]) + 000.0f }, // x
{ static_cast<float>((*in)[0]) + 256.0f, static_cast<float>((*in)[1]) - 256.0f, static_cast<float>((*in)[2]) + 256.0f }, // y
{ static_cast<float>((*in)[0]) - 512.0f, static_cast<float>((*in)[1]) + 512.0f, static_cast<float>((*in)[2]) - 512.0f }, // z
};
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
// Compute curl.x
a = (NoiseT::noise(p[2][0], p[2][1] + delta, p[2][2]) - NoiseT::noise(p[2][0], p[2][1] - delta, p[2][2])) / (2.0f * delta);
b = (NoiseT::noise(p[1][0], p[1][1], p[1][2] + delta) - NoiseT::noise(p[1][0], p[1][1], p[1][2] - delta)) / (2.0f * delta);
(*out)[0] = a - b;
// Compute curl.y
a = (NoiseT::noise(p[0][0], p[0][1], p[0][2] + delta) - NoiseT::noise(p[0][0], p[0][1], p[0][2] - delta)) / (2.0f * delta);
b = (NoiseT::noise(p[2][0] + delta, p[2][1], p[2][2]) - NoiseT::noise(p[2][0] - delta, p[2][1], p[2][2])) / (2.0f * delta);
(*out)[1] = a - b;
// Compute curl.z
a = (NoiseT::noise(p[1][0] + delta, p[1][1], p[1][2]) - NoiseT::noise(p[1][0] - delta, p[1][1], p[1][2])) / (2.0f * delta);
b = (NoiseT::noise(p[0][0], p[0][1] + delta, p[0][2]) - NoiseT::noise(p[0][0], p[0][1] - delta, p[0][2])) / (2.0f * delta);
(*out)[2] = a - b;
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
template <typename NoiseT>
void curlnoise(double (*out)[3], double x, double y, double z)
{
const double in[3] = {x, y, z};
curlnoise<NoiseT>(out, &in);
}
}
}
}
}
namespace OSN
{
// The following is the original copyright notice:
/*
*
*
* OpenSimplex (Simplectic) Noise in C++
* by Arthur Tombs
*
* Modified 2015-01-08
*
* This is a derivative work based on OpenSimplex by Kurt Spencer:
* https://gist.github.com/KdotJPG/b1270127455a94ac5d19
*
* Anyone is free to make use of this software in whatever way they want.
* Attribution is appreciated, but not required.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// 3D Implementation of the OpenSimplexNoise generator.
class OSNoise
{
public:
using inttype = int64_t;
// Initializes the class using a permutation array generated from a 64-bit seed.
// Generates a proper permutation (i.e. doesn't merely perform N successive
// pair swaps on a base array).
// Uses a simple 64-bit LCG.
OSNoise(inttype seed = 0LL);
OSNoise(const int * p);
template <typename T>
T eval(const T x, const T y, const T z) const;
private:
template <typename T>
inline T extrapolate(const inttype xsb,
const inttype ysb,
const inttype zsb,
const T dx,
const T dy,
const T dz) const;
template <typename T>
inline T extrapolate(const inttype xsb,
const inttype ysb,
const inttype zsb,
const T dx,
const T dy,
const T dz,
T (&de) [3]) const;
int mPerm [256];
// Array of gradient values for 3D. Values are defined below the class definition.
static const int sGradients [72];
// Because 72 is not a power of two, extrapolate cannot use a bitmask to index
// into the perm array. Pre-calculate and store the indices instead.
int mPermGradIndex [256];
};
}
#endif // OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED
| 5,195 | C | 33.410596 | 133 | 0.613282 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/math/OpenSimplexNoise.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file math/OpenSimplexNoise.cc
#include "OpenSimplexNoise.h"
#include <algorithm>
#include <cmath>
#include <type_traits>
// see OpenSimplexNoise.h for details about the origin on this code
namespace OSN {
namespace {
template <typename T>
inline T pow4 (T x)
{
x *= x;
return x*x;
}
template <typename T>
inline T pow2 (T x)
{
return x*x;
}
template <typename T>
inline OSNoise::inttype fastFloori (T x)
{
OSNoise::inttype ip = (OSNoise::inttype)x;
if (x < 0.0) --ip;
return ip;
}
inline void LCG_STEP (int64_t & x)
{
// Magic constants are attributed to Donald Knuth's MMIX implementation.
static const int64_t MULTIPLIER = 6364136223846793005LL;
static const int64_t INCREMENT = 1442695040888963407LL;
x = ((x * MULTIPLIER) + INCREMENT);
}
} // anonymous namespace
// Array of gradient values for 3D. They approximate the directions to the
// vertices of a rhombicuboctahedron from its center, skewed so that the
// triangular and square facets can be inscribed in circles of the same radius.
// New gradient set 2014-10-06.
const int OSNoise::sGradients [] = {
-11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11,
-11,-4, 4, -4,-11, 4, -4,-4, 11, 11,-4, 4, 4,-11, 4, 4,-4, 11,
-11, 4,-4, -4, 11,-4, -4, 4,-11, 11, 4,-4, 4, 11,-4, 4, 4,-11,
-11,-4,-4, -4,-11,-4, -4,-4,-11, 11,-4,-4, 4,-11,-4, 4,-4,-11
};
template <typename T>
inline T OSNoise::extrapolate(const OSNoise::inttype xsb,
const OSNoise::inttype ysb,
const OSNoise::inttype zsb,
const T dx,
const T dy,
const T dz) const
{
unsigned int index = mPermGradIndex[(mPerm[(mPerm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF];
return sGradients[index] * dx +
sGradients[index + 1] * dy +
sGradients[index + 2] * dz;
}
template <typename T>
inline T OSNoise::extrapolate(const OSNoise::inttype xsb,
const OSNoise::inttype ysb,
const OSNoise::inttype zsb,
const T dx,
const T dy,
const T dz,
T (&de) [3]) const
{
unsigned int index = mPermGradIndex[(mPerm[(mPerm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF];
return (de[0] = sGradients[index]) * dx +
(de[1] = sGradients[index + 1]) * dy +
(de[2] = sGradients[index + 2]) * dz;
}
OSNoise::OSNoise(OSNoise::inttype seed)
{
int source [256];
for (int i = 0; i < 256; ++i) { source[i] = i; }
LCG_STEP(seed);
LCG_STEP(seed);
LCG_STEP(seed);
for (int i = 255; i >= 0; --i) {
LCG_STEP(seed);
int r = (int)((seed + 31) % (i + 1));
if (r < 0) { r += (i + 1); }
mPerm[i] = source[r];
mPermGradIndex[i] = (int)((mPerm[i] % (72 / 3)) * 3);
source[r] = source[i];
}
}
OSNoise::OSNoise(const int * p)
{
// Copy the supplied permutation array into this instance.
for (int i = 0; i < 256; ++i) {
mPerm[i] = p[i];
mPermGradIndex[i] = (int)((mPerm[i] % (72 / 3)) * 3);
}
}
template <typename T>
T OSNoise::eval(const T x, const T y, const T z) const
{
static_assert(std::is_floating_point<T>::value, "OpenSimplexNoise can only be used with floating-point types");
static const T STRETCH_CONSTANT = (T)(-1.0 / 6.0); // (1 / sqrt(3 + 1) - 1) / 3
static const T SQUISH_CONSTANT = (T)(1.0 / 3.0); // (sqrt(3 + 1) - 1) / 3
static const T NORM_CONSTANT = (T)(1.0 / 103.0);
OSNoise::inttype xsb, ysb, zsb;
T dx0, dy0, dz0;
T xins, yins, zins;
// Parameters for the individual contributions
T contr_m [9], contr_ext [9];
{
// Place input coordinates on simplectic lattice.
T stretchOffset = (x + y + z) * STRETCH_CONSTANT;
T xs = x + stretchOffset;
T ys = y + stretchOffset;
T zs = z + stretchOffset;
// Floor to get simplectic lattice coordinates of rhombohedron
// (stretched cube) super-cell.
#ifdef __FAST_MATH__
T xsbd = std::floor(xs);
T ysbd = std::floor(ys);
T zsbd = std::floor(zs);
xsb = (OSNoise::inttype)xsbd;
ysb = (OSNoise::inttype)ysbd;
zsb = (OSNoise::inttype)zsbd;
#else
xsb = fastFloori(xs);
ysb = fastFloori(ys);
zsb = fastFloori(zs);
T xsbd = (T)xsb;
T ysbd = (T)ysb;
T zsbd = (T)zsb;
#endif
// Skew out to get actual coordinates of rhombohedron origin.
T squishOffset = (xsbd + ysbd + zsbd) * SQUISH_CONSTANT;
T xb = xsbd + squishOffset;
T yb = ysbd + squishOffset;
T zb = zsbd + squishOffset;
// Positions relative to origin point.
dx0 = x - xb;
dy0 = y - yb;
dz0 = z - zb;
// Compute simplectic lattice coordinates relative to rhombohedral origin.
xins = xs - xsbd;
yins = ys - ysbd;
zins = zs - zsbd;
}
// These are given values inside the next block, and used afterwards.
OSNoise::inttype xsv_ext0, ysv_ext0, zsv_ext0;
OSNoise::inttype xsv_ext1, ysv_ext1, zsv_ext1;
T dx_ext0, dy_ext0, dz_ext0;
T dx_ext1, dy_ext1, dz_ext1;
// Sum together to get a value that determines which cell we are in.
T inSum = xins + yins + zins;
if (inSum > (T)1.0 && inSum < (T)2.0) {
// The point is inside the octahedron (rectified 3-Simplex) inbetween.
T aScore;
uint_fast8_t aPoint;
bool aIsFurtherSide;
T bScore;
uint_fast8_t bPoint;
bool bIsFurtherSide;
// Decide between point (1,0,0) and (0,1,1) as closest.
T p1 = xins + yins;
if (p1 <= (T)1.0) {
aScore = (T)1.0 - p1;
aPoint = 4;
aIsFurtherSide = false;
} else {
aScore = p1 - (T)1.0;
aPoint = 3;
aIsFurtherSide = true;
}
// Decide between point (0,1,0) and (1,0,1) as closest.
T p2 = xins + zins;
if (p2 <= (T)1.0) {
bScore = (T)1.0 - p2;
bPoint = 2;
bIsFurtherSide = false;
} else {
bScore = p2 - (T)1.0;
bPoint = 5;
bIsFurtherSide = true;
}
// The closest out of the two (0,0,1) and (1,1,0) will replace the
// furthest out of the two decided above if closer.
T p3 = yins + zins;
if (p3 > (T)1.0) {
T score = p3 - (T)1.0;
if (aScore > bScore && bScore < score) {
bScore = score;
bPoint = 6;
bIsFurtherSide = true;
} else if (aScore <= bScore && aScore < score) {
aScore = score;
aPoint = 6;
aIsFurtherSide = true;
}
} else {
T score = (T)1.0 - p3;
if (aScore > bScore && bScore < score) {
bScore = score;
bPoint = 1;
bIsFurtherSide = false;
} else if (aScore <= bScore && aScore < score) {
aScore = score;
aPoint = 1;
aIsFurtherSide = false;
}
}
// Where each of the two closest points are determines how the
// extra two vertices are calculated.
if (aIsFurtherSide == bIsFurtherSide) {
if (aIsFurtherSide) {
// Both closest points on (1,1,1) side.
// One of the two extra points is (1,1,1)
xsv_ext0 = xsb + 1;
ysv_ext0 = ysb + 1;
zsv_ext0 = zsb + 1;
dx_ext0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
dy_ext0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
// Other extra point is based on the shared axis.
uint_fast8_t c = aPoint & bPoint;
if (c & 0x01) {
xsv_ext1 = xsb + 2;
ysv_ext1 = ysb;
zsv_ext1 = zsb;
dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0);
} else if (c & 0x02) {
xsv_ext1 = xsb;
ysv_ext1 = ysb + 2;
zsv_ext1 = zsb;
dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0);
} else {
xsv_ext1 = xsb;
ysv_ext1 = ysb;
zsv_ext1 = zsb + 2;
dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
}
} else {
// Both closest points are on the (0,0,0) side.
// One of the two extra points is (0,0,0).
xsv_ext0 = xsb;
ysv_ext0 = ysb;
zsv_ext0 = zsb;
dx_ext0 = dx0;
dy_ext0 = dy0;
dz_ext0 = dz0;
// The other extra point is based on the omitted axis.
uint_fast8_t c = aPoint | bPoint;
if (!(c & 0x01)) {
xsv_ext1 = xsb - 1;
ysv_ext1 = ysb + 1;
zsv_ext1 = zsb + 1;
dx_ext1 = dx0 + (T)1.0 - SQUISH_CONSTANT;
dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT;
dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT;
} else if (!(c & 0x02)) {
xsv_ext1 = xsb + 1;
ysv_ext1 = ysb - 1;
zsv_ext1 = zsb + 1;
dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT;
dy_ext1 = dy0 + (T)1.0 - SQUISH_CONSTANT;
dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT;
} else {
xsv_ext1 = xsb + 1;
ysv_ext1 = ysb + 1;
zsv_ext1 = zsb - 1;
dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT;
dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT;
dz_ext1 = dz0 + (T)1.0 - SQUISH_CONSTANT;
}
}
} else {
// One point is on the (0,0,0) side, one point is on the (1,1,1) side.
uint_fast8_t c1, c2;
if (aIsFurtherSide) {
c1 = aPoint;
c2 = bPoint;
} else {
c1 = bPoint;
c2 = aPoint;
}
// One contribution is a permutation of (1,1,-1).
if (!(c1 & 0x01)) {
xsv_ext0 = xsb - 1;
ysv_ext0 = ysb + 1;
zsv_ext0 = zsb + 1;
dx_ext0 = dx0 + (T)1.0 - SQUISH_CONSTANT;
dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT;
dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT;
} else if (!(c1 & 0x02)) {
xsv_ext0 = xsb + 1;
ysv_ext0 = ysb - 1;
zsv_ext0 = zsb + 1;
dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT;
dy_ext0 = dy0 + (T)1.0 - SQUISH_CONSTANT;
dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT;
} else {
xsv_ext0 = xsb + 1;
ysv_ext0 = ysb + 1;
zsv_ext0 = zsb - 1;
dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT;
dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT;
dz_ext0 = dz0 + (T)1.0 - SQUISH_CONSTANT;
}
// One contribution is a permutation of (0,0,2).
if (c2 & 0x01) {
xsv_ext1 = xsb + 2;
ysv_ext1 = ysb;
zsv_ext1 = zsb;
dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0);
} else if (c2 & 0x02) {
xsv_ext1 = xsb;
ysv_ext1 = ysb + 2;
zsv_ext1 = zsb;
dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0);
} else {
xsv_ext1 = xsb;
ysv_ext1 = ysb;
zsv_ext1 = zsb + 2;
dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
}
}
contr_m[0] = contr_ext[0] = 0.0;
// Contribution (0,0,1).
T dx1 = dx0 - (T)1.0 - SQUISH_CONSTANT;
T dy1 = dy0 - SQUISH_CONSTANT;
T dz1 = dz0 - SQUISH_CONSTANT;
contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1);
contr_ext[1] = extrapolate(xsb + 1, ysb, zsb, dx1, dy1, dz1);
// Contribution (0,1,0).
T dx2 = dx0 - SQUISH_CONSTANT;
T dy2 = dy0 - (T)1.0 - SQUISH_CONSTANT;
T dz2 = dz1;
contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2);
contr_ext[2] = extrapolate(xsb, ysb + 1, zsb, dx2, dy2, dz2);
// Contribution (1,0,0).
T dx3 = dx2;
T dy3 = dy1;
T dz3 = dz0 - (T)1.0 - SQUISH_CONSTANT;
contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3);
contr_ext[3] = extrapolate(xsb, ysb, zsb + 1, dx3, dy3, dz3);
// Contribution (1,1,0).
T dx4 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
T dy4 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
T dz4 = dz0 - (SQUISH_CONSTANT * (T)2.0);
contr_m[4] = pow2(dx4) + pow2(dy4) + pow2(dz4);
contr_ext[4] = extrapolate(xsb + 1, ysb + 1, zsb, dx4, dy4, dz4);
// Contribution (1,0,1).
T dx5 = dx4;
T dy5 = dy0 - (SQUISH_CONSTANT * (T)2.0);
T dz5 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
contr_m[5] = pow2(dx5) + pow2(dy5) + pow2(dz5);
contr_ext[5] = extrapolate(xsb + 1, ysb, zsb + 1, dx5, dy5, dz5);
// Contribution (0,1,1).
T dx6 = dx0 - (SQUISH_CONSTANT * (T)2.0);
T dy6 = dy4;
T dz6 = dz5;
contr_m[6] = pow2(dx6) + pow2(dy6) + pow2(dz6);
contr_ext[6] = extrapolate(xsb, ysb + 1, zsb + 1, dx6, dy6, dz6);
} else if (inSum <= (T)1.0) {
// The point is inside the tetrahedron (3-Simplex) at (0,0,0)
// Determine which of (0,0,1), (0,1,0), (1,0,0) are closest.
uint_fast8_t aPoint = 1;
T aScore = xins;
uint_fast8_t bPoint = 2;
T bScore = yins;
if (aScore < bScore && zins > aScore) {
aScore = zins;
aPoint = 4;
} else if (aScore >= bScore && zins > bScore) {
bScore = zins;
bPoint = 4;
}
// Determine the two lattice points not part of the tetrahedron that may contribute.
// This depends on the closest two tetrahedral vertices, including (0,0,0).
T wins = (T)1.0 - inSum;
if (wins > aScore || wins > bScore) {
// (0,0,0) is one of the closest two tetrahedral vertices.
// The other closest vertex is the closer of a and b.
uint_fast8_t c = ((bScore > aScore) ? bPoint : aPoint);
if (c != 1) {
xsv_ext0 = xsb - 1;
xsv_ext1 = xsb;
dx_ext0 = dx0 + (T)1.0;
dx_ext1 = dx0;
} else {
xsv_ext0 = xsv_ext1 = xsb + 1;
dx_ext0 = dx_ext1 = dx0 - (T)1.0;
}
if (c != 2) {
ysv_ext0 = ysv_ext1 = ysb;
dy_ext0 = dy_ext1 = dy0;
if (c == 1) {
ysv_ext0 -= 1;
dy_ext0 += (T)1.0;
} else {
ysv_ext1 -= 1;
dy_ext1 += (T)1.0;
}
} else {
ysv_ext0 = ysv_ext1 = ysb + 1;
dy_ext0 = dy_ext1 = dy0 - (T)1.0;
}
if (c != 4) {
zsv_ext0 = zsb;
zsv_ext1 = zsb - 1;
dz_ext0 = dz0;
dz_ext1 = dz0 + (T)1.0;
} else {
zsv_ext0 = zsv_ext1 = zsb + 1;
dz_ext0 = dz_ext1 = dz0 - (T)1.0;
}
} else {
// (0,0,0) is not one of the closest two tetrahedral vertices.
// The two extra vertices are determined by the closest two.
uint_fast8_t c = (aPoint | bPoint);
if (c & 0x01) {
xsv_ext0 = xsv_ext1 = xsb + 1;
dx_ext0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT;
} else {
xsv_ext0 = xsb;
xsv_ext1 = xsb - 1;
dx_ext0 = dx0 - (SQUISH_CONSTANT * (T)2.0);
dx_ext1 = dx0 + (T)1.0 - SQUISH_CONSTANT;
}
if (c & 0x02) {
ysv_ext0 = ysv_ext1 = ysb + 1;
dy_ext0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT;
} else {
ysv_ext0 = ysb;
ysv_ext1 = ysb - 1;
dy_ext0 = dy0 - (SQUISH_CONSTANT * (T)2.0);
dy_ext1 = dy0 + (T)1.0 - SQUISH_CONSTANT;
}
if (c & 0x04) {
zsv_ext0 = zsv_ext1 = zsb + 1;
dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT;
} else {
zsv_ext0 = zsb;
zsv_ext1 = zsb - 1;
dz_ext0 = dz0 - (SQUISH_CONSTANT * (T)2.0);
dz_ext1 = dz0 + (T)1.0 - SQUISH_CONSTANT;
}
}
// Contribution (0,0,0)
{
contr_m[0] = pow2(dx0) + pow2(dy0) + pow2(dz0);
contr_ext[0] = extrapolate(xsb, ysb, zsb, dx0, dy0, dz0);
}
// Contribution (0,0,1)
T dx1 = dx0 - (T)1.0 - SQUISH_CONSTANT;
T dy1 = dy0 - SQUISH_CONSTANT;
T dz1 = dz0 - SQUISH_CONSTANT;
contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1);
contr_ext[1] = extrapolate(xsb + 1, ysb, zsb, dx1, dy1, dz1);
// Contribution (0,1,0)
T dx2 = dx0 - SQUISH_CONSTANT;
T dy2 = dy0 - (T)1.0 - SQUISH_CONSTANT;
T dz2 = dz1;
contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2);
contr_ext[2] = extrapolate(xsb, ysb + 1, zsb, dx2, dy2, dz2);
// Contribution (1,0,0)
T dx3 = dx2;
T dy3 = dy1;
T dz3 = dz0 - (T)1.0 - SQUISH_CONSTANT;
contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3);
contr_ext[3] = extrapolate(xsb, ysb, zsb + 1, dx3, dy3, dz3);
contr_m[4] = contr_m[5] = contr_m[6] = 0.0;
contr_ext[4] = contr_ext[5] = contr_ext[6] = 0.0;
} else {
// The point is inside the tetrahedron (3-Simplex) at (1,1,1)
// Determine which two tetrahedral vertices are the closest
// out of (1,1,0), (1,0,1), and (0,1,1), but not (1,1,1).
uint_fast8_t aPoint = 6;
T aScore = xins;
uint_fast8_t bPoint = 5;
T bScore = yins;
if (aScore <= bScore && zins < bScore) {
bScore = zins;
bPoint = 3;
} else if (aScore > bScore && zins < aScore) {
aScore = zins;
aPoint = 3;
}
// Determine the two lattice points not part of the tetrahedron that may contribute.
// This depends on the closest two tetrahedral vertices, including (1,1,1).
T wins = 3.0 - inSum;
if (wins < aScore || wins < bScore) {
// (1,1,1) is one of the closest two tetrahedral vertices.
// The other closest vertex is the closest of a and b.
uint_fast8_t c = ((bScore < aScore) ? bPoint : aPoint);
if (c & 0x01) {
xsv_ext0 = xsb + 2;
xsv_ext1 = xsb + 1;
dx_ext0 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)3.0);
dx_ext1 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
} else {
xsv_ext0 = xsv_ext1 = xsb;
dx_ext0 = dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)3.0);
}
if (c & 0x02) {
ysv_ext0 = ysv_ext1 = ysb + 1;
dy_ext0 = dy_ext1 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
if (c & 0x01) {
ysv_ext1 += 1;
dy_ext1 -= (T)1.0;
} else {
ysv_ext0 += 1;
dy_ext0 -= (T)1.0;
}
} else {
ysv_ext0 = ysv_ext1 = ysb;
dy_ext0 = dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)3.0);
}
if (c & 0x04) {
zsv_ext0 = zsb + 1;
zsv_ext1 = zsb + 2;
dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)3.0);
} else {
zsv_ext0 = zsv_ext1 = zsb;
dz_ext0 = dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)3.0);
}
} else {
// (1,1,1) is not one of the closest two tetrahedral vertices.
// The two extra vertices are determined by the closest two.
uint_fast8_t c = aPoint & bPoint;
if (c & 0x01) {
xsv_ext0 = xsb + 1;
xsv_ext1 = xsb + 2;
dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT;
dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
} else {
xsv_ext0 = xsv_ext1 = xsb;
dx_ext0 = dx0 - SQUISH_CONSTANT;
dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
}
if (c & 0x02) {
ysv_ext0 = ysb + 1;
ysv_ext1 = ysb + 2;
dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT;
dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
} else {
ysv_ext0 = ysv_ext1 = ysb;
dy_ext0 = dy0 - SQUISH_CONSTANT;
dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0);
}
if (c & 0x04) {
zsv_ext0 = zsb + 1;
zsv_ext1 = zsb + 2;
dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT;
dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0);
} else {
zsv_ext0 = zsv_ext1 = zsb;
dz_ext0 = dz0 - SQUISH_CONSTANT;
dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0);
}
}
// Contribution (1,1,0)
T dx3 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
T dy3 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
T dz3 = dz0 - (SQUISH_CONSTANT * (T)2.0);
contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3);
contr_ext[3] = extrapolate(xsb + 1, ysb + 1, zsb, dx3, dy3, dz3);
// Contribution (1,0,1)
T dx2 = dx3;
T dy2 = dy0 - (SQUISH_CONSTANT * (T)2.0);
T dz2 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0);
contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2);
contr_ext[2] = extrapolate(xsb + 1, ysb, zsb + 1, dx2, dy2, dz2);
// Contribution (0,1,1)
{
T dx1 = dx0 - (SQUISH_CONSTANT * (T)2.0);
T dy1 = dy3;
T dz1 = dz2;
contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1);
contr_ext[1] = extrapolate(xsb, ysb + 1, zsb + 1, dx1, dy1, dz1);
}
// Contribution (1,1,1)
{
dx0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
dy0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
dz0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0);
contr_m[0] = pow2(dx0) + pow2(dy0) + pow2(dz0);
contr_ext[0] = extrapolate(xsb + 1, ysb + 1, zsb + 1, dx0, dy0, dz0);
}
contr_m[4] = contr_m[5] = contr_m[6] = 0.0;
contr_ext[4] = contr_ext[5] = contr_ext[6] = 0.0;
}
// First extra vertex.
contr_m[7] = pow2(dx_ext0) + pow2(dy_ext0) + pow2(dz_ext0);
contr_ext[7] = extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, dx_ext0, dy_ext0, dz_ext0);
// Second extra vertex.
contr_m[8] = pow2(dx_ext1) + pow2(dy_ext1) + pow2(dz_ext1);
contr_ext[8] = extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, dx_ext1, dy_ext1, dz_ext1);
T value = 0.0;
for (int i=0; i<9; ++i) {
value += pow4(std::max((T)2.0 - contr_m[i], (T)0.0)) * contr_ext[i];
}
return (value * NORM_CONSTANT);
}
template double OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb,
const double dx, const double dy, const double dz) const;
template double OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb,
const double dx, const double dy, const double dz,
double (&de) [3]) const;
template double OSNoise::eval(const double x, const double y, const double z) const;
} // namespace OSN
| 22,642 | C++ | 30.624302 | 120 | 0.514796 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/main.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb/openvdb.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/util/CpuTimer.h>
#include <openvdb/util/logging.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestFailure.h>
#include <cppunit/TestListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TextTestProgressListener.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <algorithm> // for std::shuffle()
#include <cmath> // for std::round()
#include <cstdlib> // for EXIT_SUCCESS
#include <cstring> // for strrchr()
#include <exception>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <vector>
/// @note Global unit test flag enabled with -g which symbolises the integration
/// tests to auto-generate their AX tests. Any previous tests will be
/// overwritten.
int sGenerateAX = false;
namespace {
using StringVec = std::vector<std::string>;
void
usage(const char* progName, std::ostream& ostrm)
{
ostrm <<
"Usage: " << progName << " [options]\n" <<
"Which: runs OpenVDB AX library unit tests\n" <<
"Options:\n" <<
" -f file read whitespace-separated names of tests to be run\n" <<
" from the given file (\"#\" comments are supported)\n" <<
" -l list all available tests\n" <<
" -shuffle run tests in random order\n" <<
" -t test specific suite or test to run, e.g., \"-t TestGrid\"\n" <<
" or \"-t TestGrid::testGetGrid\" (default: run all tests)\n" <<
" -v verbose output\n" <<
" -g As well as testing, auto-generate any integration tests\n";
#ifdef OPENVDB_USE_LOG4CPLUS
ostrm <<
"\n" <<
" -error log fatal and non-fatal errors (default: log only fatal errors)\n" <<
" -warn log warnings and errors\n" <<
" -info log info messages, warnings and errors\n" <<
" -debug log debugging messages, info messages, warnings and errors\n";
#endif
}
void
getTestNames(StringVec& nameVec, const CppUnit::Test* test)
{
if (test) {
const int numChildren = test->getChildTestCount();
if (numChildren == 0) {
nameVec.push_back(test->getName());
} else {
for (int i = 0; i < test->getChildTestCount(); ++i) {
getTestNames(nameVec, test->getChildTestAt(i));
}
}
}
}
/// Listener that prints the name, elapsed time, and error status of each test
class TimedTestProgressListener: public CppUnit::TestListener
{
public:
void startTest(CppUnit::Test* test) override
{
mFailed = false;
std::cout << test->getName() << std::flush;
mTimer.start();
}
void addFailure(const CppUnit::TestFailure& failure) override
{
std::cout << " : " << (failure.isError() ? "error" : "assertion");
mFailed = true;
}
void endTest(CppUnit::Test*) override
{
if (!mFailed) {
// Print elapsed time only for successful tests.
const double msec = std::round(mTimer.milliseconds());
if (msec > 1.0) {
openvdb::util::printTime(std::cout, msec, " : OK (", ")",
/*width=*/0, /*precision=*/(msec > 1000.0 ? 1 : 0), /*verbose=*/0);
} else {
std::cout << " : OK (<1ms)";
}
}
std::cout << std::endl;
}
private:
openvdb::util::CpuTimer mTimer;
bool mFailed = false;
};
int
run(int argc, char* argv[])
{
const char* progName = argv[0];
if (const char* ptr = ::strrchr(progName, '/')) progName = ptr + 1;
bool shuffle = false, verbose = false;
StringVec tests;
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
if (arg == "-l") {
StringVec allTests;
getTestNames(allTests,
CppUnit::TestFactoryRegistry::getRegistry().makeTest());
for (const auto& name: allTests) { std::cout << name << "\n"; }
return EXIT_SUCCESS;
} else if (arg == "-shuffle") {
shuffle = true;
} else if (arg == "-v") {
verbose = true;
} else if (arg == "-g") {
sGenerateAX = true;
} else if (arg == "-t") {
if (i + 1 < argc) {
++i;
tests.push_back(argv[i]);
} else {
OPENVDB_LOG_FATAL("missing test name after \"-t\"");
usage(progName, std::cerr);
return EXIT_FAILURE;
}
} else if (arg == "-f") {
if (i + 1 < argc) {
++i;
std::ifstream file{argv[i]};
if (file.fail()) {
OPENVDB_LOG_FATAL("unable to read file " << argv[i]);
return EXIT_FAILURE;
}
while (file) {
// Read a whitespace-separated string from the file.
std::string test;
file >> test;
if (!test.empty()) {
if (test[0] != '#') {
tests.push_back(test);
} else {
// If the string starts with a comment symbol ("#"),
// skip it and jump to the end of the line.
while (file) { if (file.get() == '\n') break; }
}
}
}
} else {
OPENVDB_LOG_FATAL("missing filename after \"-f\"");
usage(progName, std::cerr);
return EXIT_FAILURE;
}
} else if (arg == "-h" || arg == "-help" || arg == "--help") {
usage(progName, std::cout);
return EXIT_SUCCESS;
} else {
OPENVDB_LOG_FATAL("unrecognized option \"" << arg << "\"");
usage(progName, std::cerr);
return EXIT_FAILURE;
}
}
try {
CppUnit::TestFactoryRegistry& registry =
CppUnit::TestFactoryRegistry::getRegistry();
auto* root = registry.makeTest();
if (!root) {
throw std::runtime_error(
"CppUnit test registry was not initialized properly");
}
if (!shuffle) {
if (tests.empty()) tests.push_back("");
} else {
// Get the names of all selected tests and their children.
StringVec allTests;
if (tests.empty()) {
getTestNames(allTests, root);
} else {
for (const auto& name: tests) {
getTestNames(allTests, root->findTest(name));
}
}
// Randomly shuffle the list of names.
std::random_device randDev;
std::mt19937 generator(randDev());
std::shuffle(allTests.begin(), allTests.end(), generator);
tests.swap(allTests);
}
CppUnit::TestRunner runner;
runner.addTest(root);
CppUnit::TestResult controller;
CppUnit::TestResultCollector result;
controller.addListener(&result);
CppUnit::TextTestProgressListener progress;
TimedTestProgressListener vProgress;
if (verbose) {
controller.addListener(&vProgress);
} else {
controller.addListener(&progress);
}
for (size_t i = 0; i < tests.size(); ++i) {
runner.run(controller, tests[i]);
}
CppUnit::CompilerOutputter outputter(&result, std::cerr);
outputter.write();
return result.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (std::exception& e) {
OPENVDB_LOG_FATAL(e.what());
return EXIT_FAILURE;
}
}
} // anonymous namespace
template <typename T>
static inline void registerType()
{
if (!openvdb::points::TypedAttributeArray<T>::isRegistered())
openvdb::points::TypedAttributeArray<T>::registerType();
}
int
main(int argc, char *argv[])
{
openvdb::initialize();
openvdb::ax::initialize();
openvdb::logging::initialize(argc, argv);
// Also intialize Vec2/4 point attributes
registerType<openvdb::math::Vec2<int32_t>>();
registerType<openvdb::math::Vec2<float>>();
registerType<openvdb::math::Vec2<double>>();
registerType<openvdb::math::Vec4<int32_t>>();
registerType<openvdb::math::Vec4<float>>();
registerType<openvdb::math::Vec4<double>>();
auto value = run(argc, argv);
openvdb::ax::uninitialize();
openvdb::uninitialize();
return value;
}
| 8,782 | C++ | 29.926056 | 87 | 0.541904 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/util.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file test/util.h
///
/// @author Nick Avramoussis
///
/// @brief Test utilities
#ifndef OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED
#define OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Parse.h>
#include <openvdb_ax/ast/Tokens.h>
#include <openvdb_ax/compiler/Logger.h>
#include <openvdb/Types.h>
#include <memory>
#include <vector>
#include <utility>
#include <string>
#include <type_traits>
#define ERROR_MSG(Msg, Code) Msg + std::string(": \"") + Code + std::string("\"")
#define TEST_SYNTAX_PASSES(Tests) \
{ \
openvdb::ax::Logger logger;\
for (const auto& test : Tests) { \
logger.clear();\
const std::string& code = test.first; \
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger);\
std::stringstream str; \
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unexpected parsing error(s)\n", str.str()), tree); \
} \
} \
#define TEST_SYNTAX_FAILS(Tests) \
{ \
openvdb::ax::Logger logger([](const std::string&) {});\
for (const auto& test : Tests) { \
logger.clear();\
const std::string& code = test.first; \
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger);\
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected parsing error", code), logger.hasError()); \
} \
} \
namespace unittest_util
{
// Use shared pointers rather than unique pointers so initializer lists can easily
// be used. Could easily introduce some move semantics to work around this if
// necessary.
using CodeTests = std::vector<std::pair<std::string, openvdb::ax::ast::Node::Ptr>>;
//
// Find + Replace all string helper
inline void replace(std::string& str, const std::string& oldStr, const std::string& newStr)
{
std::string::size_type pos = 0u;
while ((pos = str.find(oldStr, pos)) != std::string::npos) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
//
inline bool compareLinearTrees(const std::vector<const openvdb::ax::ast::Node*>& a,
const std::vector<const openvdb::ax::ast::Node*>& b, const bool allowEmpty = false)
{
if (!allowEmpty && (a.empty() || b.empty())) return false;
if (a.size() != b.size()) return false;
const size_t size = a.size();
for (size_t i = 0; i < size; ++i) {
if ((a[i] == nullptr) ^ (b[i] == nullptr)) return false;
if (a[i] == nullptr) continue;
if (a[i]->nodetype() != b[i]->nodetype()) return false;
// Specific handling of various node types to compare child data
// @todo generalize this
// @note Value methods does not compare child text data
if (a[i]->nodetype() == openvdb::ax::ast::Node::AssignExpressionNode) {
if (static_cast<const openvdb::ax::ast::AssignExpression*>(a[i])->operation() !=
static_cast<const openvdb::ax::ast::AssignExpression*>(b[i])->operation()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::BinaryOperatorNode) {
if (static_cast<const openvdb::ax::ast::BinaryOperator*>(a[i])->operation() !=
static_cast<const openvdb::ax::ast::BinaryOperator*>(b[i])->operation()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::CrementNode) {
if (static_cast<const openvdb::ax::ast::Crement*>(a[i])->operation() !=
static_cast<const openvdb::ax::ast::Crement*>(b[i])->operation()) {
return false;
}
if (static_cast<const openvdb::ax::ast::Crement*>(a[i])->post() !=
static_cast<const openvdb::ax::ast::Crement*>(b[i])->post()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::CastNode) {
if (static_cast<const openvdb::ax::ast::Cast*>(a[i])->type() !=
static_cast<const openvdb::ax::ast::Cast*>(b[i])->type()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::FunctionCallNode) {
if (static_cast<const openvdb::ax::ast::FunctionCall*>(a[i])->name() !=
static_cast<const openvdb::ax::ast::FunctionCall*>(b[i])->name()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::LoopNode) {
if (static_cast<const openvdb::ax::ast::Loop*>(a[i])->loopType() !=
static_cast<const openvdb::ax::ast::Loop*>(b[i])->loopType()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::KeywordNode) {
if (static_cast<const openvdb::ax::ast::Keyword*>(a[i])->keyword() !=
static_cast<const openvdb::ax::ast::Keyword*>(b[i])->keyword()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::AttributeNode) {
if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->type() !=
static_cast<const openvdb::ax::ast::Attribute*>(b[i])->type()) {
return false;
}
if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->name() !=
static_cast<const openvdb::ax::ast::Attribute*>(b[i])->name()) {
return false;
}
if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->inferred() !=
static_cast<const openvdb::ax::ast::Attribute*>(b[i])->inferred()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ExternalVariableNode) {
if (static_cast<const openvdb::ax::ast::ExternalVariable*>(a[i])->type() !=
static_cast<const openvdb::ax::ast::ExternalVariable*>(b[i])->type()) {
return false;
}
if (static_cast<const openvdb::ax::ast::ExternalVariable*>(a[i])->name() !=
static_cast<const openvdb::ax::ast::ExternalVariable*>(b[i])->name()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::DeclareLocalNode) {
if (static_cast<const openvdb::ax::ast::DeclareLocal*>(a[i])->type() !=
static_cast<const openvdb::ax::ast::DeclareLocal*>(b[i])->type()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::LocalNode) {
if (static_cast<const openvdb::ax::ast::Local*>(a[i])->name() !=
static_cast<const openvdb::ax::ast::Local*>(b[i])->name()) {
return false;
}
}
// @note Value methods does not compare child text data
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueBoolNode) {
if (static_cast<const openvdb::ax::ast::Value<bool>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<bool>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt16Node) {
if (static_cast<const openvdb::ax::ast::Value<int16_t>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<int16_t>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt32Node) {
if (static_cast<const openvdb::ax::ast::Value<int32_t>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<int32_t>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt64Node) {
if (static_cast<const openvdb::ax::ast::Value<int64_t>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<int64_t>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueFloatNode) {
if (static_cast<const openvdb::ax::ast::Value<float>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<float>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueDoubleNode) {
if (static_cast<const openvdb::ax::ast::Value<double>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<double>*>(b[i])->value()) {
return false;
}
}
else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueStrNode) {
if (static_cast<const openvdb::ax::ast::Value<std::string>*>(a[i])->value() !=
static_cast<const openvdb::ax::ast::Value<std::string>*>(b[i])->value()) {
return false;
}
}
}
return true;
}
inline std::vector<std::string>
nameSequence(const std::string& base, const size_t number)
{
std::vector<std::string> names;
if (number <= 0) return names;
names.reserve(number);
for (size_t i = 1; i <= number; i++) {
names.emplace_back(base + std::to_string(i));
}
return names;
}
}
#endif // OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED
| 9,521 | C | 39.866953 | 95 | 0.537759 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/CompareGrids.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file test/integration/CompareGrids.cc
#include "CompareGrids.h"
#include <openvdb/points/PointDataGrid.h>
namespace unittest_util
{
#if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER == 7 && \
OPENVDB_LIBRARY_MINOR_VERSION_NUMBER == 1)
// Issue with TypeList where Unqiue defines recursively in 7.1
template <typename... Ts> struct TListFix;
template<typename ListT, typename... Ts> struct TSAppendImpl;
template<typename... Ts, typename... OtherTs>
struct TSAppendImpl<TListFix<Ts...>, OtherTs...> { using type = TListFix<Ts..., OtherTs...>; };
template<typename... Ts, typename... OtherTs>
struct TSAppendImpl<TListFix<Ts...>, TListFix<OtherTs...>> { using type = TListFix<Ts..., OtherTs...>; };
template<typename ListT, typename T> struct TSEraseImpl;
template<typename T> struct TSEraseImpl<TListFix<>, T> { using type = TListFix<>; };
template<typename... Ts, typename T>
struct TSEraseImpl<TListFix<T, Ts...>, T> { using type = typename TSEraseImpl<TListFix<Ts...>, T>::type; };
template<typename T2, typename... Ts, typename T>
struct TSEraseImpl<TListFix<T2, Ts...>, T> {
using type = typename TSAppendImpl<TListFix<T2>,
typename TSEraseImpl<TListFix<Ts...>, T>::type>::type;
};
template<typename ListT, typename... Ts> struct TSRemoveImpl;
template<typename ListT> struct TSRemoveImpl<ListT> { using type = ListT; };
template<typename ListT, typename T, typename... Ts>
struct TSRemoveImpl<ListT, T, Ts...> { using type = typename TSRemoveImpl<typename TSEraseImpl<ListT, T>::type, Ts...>::type; };
template<typename ListT, typename... Ts>
struct TSRemoveImpl<ListT, TListFix<Ts...>> { using type = typename TSRemoveImpl<ListT, Ts...>::type; };
template <typename... Ts>
struct TListFix
{
using Self = TListFix;
template<typename... TypesToRemove>
using Remove = typename TSRemoveImpl<Self, TypesToRemove...>::type;
template<typename... TypesToAppend>
using Append = typename TSAppendImpl<Self, TypesToAppend...>::type;
template<typename OpT>
static void foreach(OpT op) { openvdb::internal::TSForEachImpl<OpT, Ts...>(op); }
};
using TypeList = TListFix<
#else
using TypeList = openvdb::TypeList<
#endif
double,
float,
int64_t,
int32_t,
int16_t,
bool,
openvdb::math::Vec2<double>,
openvdb::math::Vec2<float>,
openvdb::math::Vec2<int32_t>,
openvdb::math::Vec3<double>,
openvdb::math::Vec3<float>,
openvdb::math::Vec3<int32_t>,
openvdb::math::Vec4<double>,
openvdb::math::Vec4<float>,
openvdb::math::Vec4<int32_t>,
openvdb::math::Mat3<double>,
openvdb::math::Mat3<float>,
openvdb::math::Mat4<double>,
openvdb::math::Mat4<float>,
std::string>;
struct DiagnosticArrayData
{
DiagnosticArrayData()
: mSizeMatch(true)
, mTypesMatch(true)
, mFlagsMatch(true)
, mArrayValueFlags() {}
inline void
flagArrayValue(const size_t idx) {
if (!mArrayValueFlags) mArrayValueFlags.reset(new std::vector<size_t>());
(*mArrayValueFlags).push_back(idx);
}
bool mSizeMatch;
bool mTypesMatch;
bool mFlagsMatch;
std::unique_ptr<std::vector<size_t>> mArrayValueFlags;
};
struct DiagnosticData
{
using Ptr = std::shared_ptr<DiagnosticData>;
DiagnosticData()
: mValid(true)
, mBufferSizes(true)
, mVoxelTopologyFlags(nullptr)
, mVoxelValueFlags(nullptr)
, mDescriptorsMatch(true)
, mAttributeArrayData() {}
inline bool hasValueFlags() const {
return static_cast<bool>(mVoxelValueFlags);
}
inline bool hasTopologyFlags() const {
return static_cast<bool>(mVoxelTopologyFlags);
}
inline void
flagVoxelTopology(const int16_t idx) {
if (!mVoxelTopologyFlags) {
mVoxelTopologyFlags.reset(new std::array<bool,512>());
mVoxelTopologyFlags->fill(true);
}
(*mVoxelTopologyFlags)[idx] = false;
}
inline void
flagVoxelValue(const int16_t idx) {
if (!mVoxelValueFlags) {
mVoxelValueFlags.reset(new std::array<bool,512>());
mVoxelValueFlags->fill(true);
}
(*mVoxelValueFlags)[idx] = false;
}
inline DiagnosticArrayData&
getDiagnosticArrayData(const std::string& name) {
if (!mAttributeArrayData) {
mAttributeArrayData.reset(new std::map<std::string, DiagnosticArrayData>());
}
return (*mAttributeArrayData)[name];
}
inline bool
hasDiagnosticArrayData() const {
return (static_cast<bool>(mAttributeArrayData));
}
inline bool
hasDiagnosticArrayData(const std::string& name) const {
return (hasDiagnosticArrayData() &&
mAttributeArrayData->find(name) != mAttributeArrayData->end());
}
bool mValid;
bool mBufferSizes;
std::unique_ptr<std::array<bool,512>> mVoxelTopologyFlags;
std::unique_ptr<std::array<bool,512>> mVoxelValueFlags;
bool mDescriptorsMatch;
std::unique_ptr<std::map<std::string, DiagnosticArrayData>> mAttributeArrayData;
};
template <typename LeafNodeType,
typename NodeMaskT>
inline bool compareLeafBuffers(const LeafNodeType& firstLeaf,
const LeafNodeType& secondLeaf,
const NodeMaskT& mask,
DiagnosticData& data,
const ComparisonSettings& settings,
const typename LeafNodeType::ValueType& tolerance)
{
using BufferT = typename LeafNodeType::Buffer;
const BufferT& firstBuffer = firstLeaf.buffer();
const BufferT& secondBuffer = secondLeaf.buffer();
// if the buffers are not the same size the buffer most likely isn't
// loaded or allocated
if (firstBuffer.size() != secondBuffer.size()) {
data.mBufferSizes = false;
return false;
}
const NodeMaskT& firstMask = firstLeaf.getValueMask();
const NodeMaskT& secondMask = secondLeaf.getValueMask();
typename NodeMaskT::OnIterator iter = mask.beginOn();
for (; iter; ++iter) {
const openvdb::Index n = iter.pos();
assert(n < firstBuffer.size() && n < secondBuffer.size());
if (settings.mCheckActiveStates &&
firstMask.isOn(n) ^ secondMask.isOn(n)) {
data.flagVoxelTopology(static_cast<int16_t>(n));
}
if (settings.mCheckBufferValues &&
!openvdb::math::isApproxEqual(firstBuffer[n], secondBuffer[n], tolerance)) {
data.flagVoxelValue(static_cast<int16_t>(n));
}
}
return !data.hasValueFlags() && !data.hasTopologyFlags();
}
void compareStringArrays(const openvdb::points::AttributeArray& a1,
const openvdb::points::AttributeArray& a2,
const openvdb::points::PointDataTree::LeafNodeType& leaf1,
const openvdb::points::PointDataTree::LeafNodeType& leaf2,
const std::string& name,
DiagnosticData& data)
{
using LeafNodeT = openvdb::points::PointDataTree::LeafNodeType;
if (a1.size() != a2.size()) {
auto& arrayData = data.getDiagnosticArrayData(name);
arrayData.mSizeMatch = false;
}
const openvdb::points::AttributeSet::Descriptor& descriptor1 = leaf1.attributeSet().descriptor();
const openvdb::points::AttributeSet::Descriptor& descriptor2 = leaf2.attributeSet().descriptor();
openvdb::points::StringAttributeHandle h1(a1, descriptor1.getMetadata()), h2(a2, descriptor2.getMetadata());
auto iter = leaf1.beginIndexAll();
for (; iter; ++iter) {
if (h1.get(*iter) != h2.get(*iter)) break;
}
if (iter) {
auto& arrayData = data.getDiagnosticArrayData(name);
for (; iter; ++iter) {
const openvdb::Index i = *iter;
if (h1.get(i) != h2.get(i)) {
arrayData.flagArrayValue(i);
data.flagVoxelValue(static_cast<int16_t>(LeafNodeT::coordToOffset(iter.getCoord())));
}
}
}
}
template <typename ValueType>
inline void compareArrays(const openvdb::points::AttributeArray& a1,
const openvdb::points::AttributeArray& a2,
const openvdb::points::PointDataTree::LeafNodeType& leaf,
const std::string& name,
DiagnosticData& data)
{
using LeafNodeT = openvdb::points::PointDataTree::LeafNodeType;
if (a1.size() != a2.size()) {
auto& arrayData = data.getDiagnosticArrayData(name);
arrayData.mSizeMatch = false;
}
openvdb::points::AttributeHandle<ValueType> h1(a1), h2(a2);
auto iter = leaf.beginIndexAll();
for (; iter; ++iter) {
if (h1.get(*iter) != h2.get(*iter)) break;
}
if (iter) {
auto& arrayData = data.getDiagnosticArrayData(name);
for (; iter; ++iter) {
const openvdb::Index i = *iter;
if (h1.get(i) != h2.get(i)) {
arrayData.flagArrayValue(i);
data.flagVoxelValue(static_cast<int16_t>(LeafNodeT::coordToOffset(iter.getCoord())));
}
}
}
}
template <typename LeafNodeType>
inline bool
compareAttributes(const LeafNodeType&,
const LeafNodeType&,
DiagnosticData&,
const ComparisonSettings&) {
return true;
}
template <>
inline bool
compareAttributes<openvdb::points::PointDataTree::LeafNodeType>
(const openvdb::points::PointDataTree::LeafNodeType& firstLeaf,
const openvdb::points::PointDataTree::LeafNodeType& secondLeaf,
DiagnosticData& data,
const ComparisonSettings& settings)
{
using Descriptor = openvdb::points::AttributeSet::Descriptor;
const Descriptor& firstDescriptor = firstLeaf.attributeSet().descriptor();
const Descriptor& secondDescriptor = secondLeaf.attributeSet().descriptor();
if (settings.mCheckDescriptors &&
!firstDescriptor.hasSameAttributes(secondDescriptor)) {
data.mDescriptorsMatch = false;
}
// check common/miss-matching attributes
std::set<std::string> attrs1, attrs2;
for (const auto& nameToPos : firstDescriptor.map()) {
attrs1.insert(nameToPos.first);
}
for (const auto& nameToPos : secondDescriptor.map()) {
attrs2.insert(nameToPos.first);
}
std::vector<std::string> commonAttributes;
std::set_intersection(attrs1.begin(),
attrs1.end(),
attrs2.begin(),
attrs2.end(),
std::back_inserter(commonAttributes));
for (const std::string& name : commonAttributes) {
const size_t pos1 = firstDescriptor.find(name);
const size_t pos2 = secondDescriptor.find(name);
const auto& array1 = firstLeaf.constAttributeArray(pos1);
const auto& array2 = secondLeaf.constAttributeArray(pos2);
const std::string& type = array1.type().first;
if (type != array2.type().first) {
// this mismatch is also loged by differing descriptors
auto& arrayData = data.getDiagnosticArrayData(name);
arrayData.mTypesMatch = false;
continue;
}
if (settings.mCheckArrayFlags &&
array1.flags() != array2.flags()) {
auto& arrayData = data.getDiagnosticArrayData(name);
arrayData.mFlagsMatch = false;
}
if (settings.mCheckArrayValues) {
if (array1.type().second == "str") {
compareStringArrays(array1, array2, firstLeaf, secondLeaf, name, data);
}
else {
bool success = false;
// Remove string types but add uint8_t types (used by group arrays)
TypeList::Remove<std::string>::Append<uint8_t>::foreach([&](auto x) {
if (type == openvdb::typeNameAsString<decltype(x)>()) {
compareArrays<decltype(x)>(array1, array2, firstLeaf, name, data);
success = true;
}
});
if (!success) {
throw std::runtime_error("Unsupported array type for comparison: " + type);
}
}
}
}
return !data.hasDiagnosticArrayData() && data.mDescriptorsMatch;
}
template<typename TreeType>
struct CompareLeafNodes
{
using LeafManagerT = openvdb::tree::LeafManager<const openvdb::MaskTree>;
using LeafNodeType = typename TreeType::LeafNodeType;
using LeafManagerNodeType = typename LeafManagerT::LeafNodeType;
using ConstGridAccessor = openvdb::tree::ValueAccessor<const TreeType>;
CompareLeafNodes(std::vector<DiagnosticData::Ptr>& data,
const TreeType& firstTree,
const TreeType& secondTree,
const typename TreeType::ValueType tolerance,
const ComparisonSettings& settings,
const bool useVoxelMask = true)
: mDiagnosticData(data)
, mFirst(firstTree)
, mSecond(secondTree)
, mTolerance(tolerance)
, mSettings(settings)
, mUseVoxelMask(useVoxelMask) {}
void operator()(LeafManagerNodeType& leaf, size_t index) const
{
const openvdb::Coord& origin = leaf.origin();
// // //
const LeafNodeType* const firstLeafNode = mFirst.probeConstLeaf(origin);
const LeafNodeType* const secondLeafNode = mSecond.probeConstLeaf(origin);
if (firstLeafNode == nullptr &&
secondLeafNode == nullptr) {
return;
}
auto& data = mDiagnosticData[index];
data.reset(new DiagnosticData());
if (static_cast<bool>(firstLeafNode) ^
static_cast<bool>(secondLeafNode)) {
data->mValid = false;
return;
}
assert(firstLeafNode && secondLeafNode);
const openvdb::util::NodeMask<LeafNodeType::LOG2DIM>
mask(mUseVoxelMask ? leaf.valueMask() : true);
if (compareLeafBuffers(*firstLeafNode, *secondLeafNode, mask, *data, mSettings, mTolerance) &&
compareAttributes(*firstLeafNode, *secondLeafNode, *data, mSettings)) {
data.reset();
}
}
private:
std::vector<DiagnosticData::Ptr>& mDiagnosticData;
const ConstGridAccessor mFirst;
const ConstGridAccessor mSecond;
const typename TreeType::ValueType mTolerance;
const ComparisonSettings& mSettings;
const bool mUseVoxelMask;
};
template <typename GridType>
bool compareGrids(ComparisonResult& resultData,
const GridType& firstGrid,
const GridType& secondGrid,
const ComparisonSettings& settings,
const openvdb::MaskGrid::ConstPtr maskGrid,
const typename GridType::ValueType tolerance)
{
using TreeType = typename GridType::TreeType;
using LeafManagerT = openvdb::tree::LeafManager<const openvdb::MaskTree>;
struct Local {
// flag to string
static std::string fts(const bool flag) {
return (flag ? "[SUCCESS]" : "[FAILED]");
}
};
bool result = true;
bool flag = true;
std::ostream& os = resultData.mOs;
os << "[Diagnostic : Compare Leaf Nodes Result]"
<< std::endl
<< " First Grid: \"" << firstGrid.getName() << "\""
<< std::endl
<< " Second Grid: \"" << secondGrid.getName() << "\""
<< std::endl << std::endl;
if (firstGrid.tree().hasActiveTiles() ||
secondGrid.tree().hasActiveTiles()) {
os << "[Diagnostic : WARNING]: Grids contain active tiles which will not be compared."
<< std::endl;
}
if (settings.mCheckTransforms) {
flag = (firstGrid.constTransform() == secondGrid.constTransform());
result &= flag;
os << "[Diagnostic]: Grid transformations: " << Local::fts(flag)
<< std::endl;
}
const openvdb::Index64 leafCount1 = firstGrid.tree().leafCount();
const openvdb::Index64 leafCount2 = secondGrid.tree().leafCount();
flag = (leafCount1 == 0 && leafCount2 == 0);
if (flag) {
os << "[Diagnostic]: Both grids contain 0 leaf nodes."
<< std::endl;
return result;
}
if (settings.mCheckTopologyStructure && !maskGrid) {
flag = firstGrid.tree().hasSameTopology(secondGrid.tree());
result &= flag;
os << "[Diagnostic]: Topology structures: " << Local::fts(flag)
<< std::endl;
}
openvdb::MaskGrid::Ptr mask = openvdb::MaskGrid::create();
if (maskGrid) {
mask->topologyUnion(*maskGrid);
}
else {
mask->topologyUnion(firstGrid);
mask->topologyUnion(secondGrid);
}
openvdb::tools::pruneInactive(mask->tree());
LeafManagerT leafManager(mask->constTree());
std::vector<DiagnosticData::Ptr> data(leafManager.leafCount());
CompareLeafNodes<TreeType>
op(data,
firstGrid.constTree(),
secondGrid.constTree(),
tolerance,
settings);
leafManager.foreach(op);
flag = true;
for (const auto& diagnostic : data) {
if (diagnostic) {
flag = false;
break;
}
}
result &= flag;
os << "[Diagnostic]: Leaf Node Comparison: " << Local::fts(flag)
<< std::endl;
if (flag) return result;
openvdb::MaskGrid& differingTopology = *(resultData.mDifferingTopology);
openvdb::MaskGrid& differingValues = *(resultData.mDifferingValues);
differingTopology.setTransform(firstGrid.transform().copy());
differingValues.setTransform(firstGrid.transform().copy());
differingTopology.setName("different_topology");
differingValues.setName("different_values");
// Print diagnostic info to the stream and intialise the result topologies
openvdb::MaskGrid::Accessor accessorTopology = differingTopology.getAccessor();
openvdb::MaskGrid::Accessor accessorValues = differingValues.getAccessor();
auto range = leafManager.leafRange();
os << "[Diagnostic]: Leaf Node Diagnostics:"
<< std::endl << std::endl;
for (auto leaf = range.begin(); leaf; ++leaf) {
DiagnosticData::Ptr diagnostic = data[leaf.pos()];
if (!diagnostic) continue;
const openvdb::Coord& origin = leaf->origin();
os << " Coord : " << origin << std::endl;
os << " Both Valid : " << Local::fts(diagnostic->mValid) << std::endl;
if (!diagnostic->mValid) {
const bool second = firstGrid.constTree().probeConstLeaf(origin);
os << " Missing in " << (second ? "second" : "first")
<< " grid."
<< std::endl;
continue;
}
const auto& l1 = firstGrid.constTree().probeConstLeaf(origin);
const auto& l2 = secondGrid.constTree().probeConstLeaf(origin);
assert(l1 && l2);
os << " Buffer Sizes : " << Local::fts(diagnostic->mBufferSizes) << std::endl;
const bool topologyMatch = !static_cast<bool>(diagnostic->mVoxelTopologyFlags);
os << " Topology : " << Local::fts(topologyMatch) << std::endl;
if (!topologyMatch) {
os << " The following voxel topologies differ : " << std::endl;
openvdb::Index idx(0);
for (const auto match : *(diagnostic->mVoxelTopologyFlags)) {
if (!match) {
const openvdb::Coord coord = leaf->offsetToGlobalCoord(idx);
os << " [" << idx << "] "<< coord
<< " G1: " << l1->isValueOn(coord)
<< " - G2: " << l2->isValueOn(coord)
<< std::endl;
accessorTopology.setValue(coord, true);
}
++idx;
}
}
const bool valueMatch = !static_cast<bool>(diagnostic->mVoxelValueFlags);
os << " Values : " << Local::fts(valueMatch) << std::endl;
if (!valueMatch) {
os << " The following voxel values differ : " << std::endl;
openvdb::Index idx(0);
for (const auto match : *(diagnostic->mVoxelValueFlags)) {
if (!match) {
const openvdb::Coord coord = leaf->offsetToGlobalCoord(idx);
os << " [" << idx << "] "<< coord
<< " G1: " << l1->getValue(coord)
<< " - G2: " << l2->getValue(coord)
<< std::endl;
accessorValues.setValue(coord, true);
}
++idx;
}
}
if (firstGrid.template isType<openvdb::points::PointDataGrid>()) {
os << " Descriptors : " << Local::fts(diagnostic->mDescriptorsMatch) << std::endl;
const bool attributesMatch = !static_cast<bool>(diagnostic->mAttributeArrayData);
os << " Array Data : " << Local::fts(attributesMatch) << std::endl;
if (!attributesMatch) {
os << " The following attribute values : " << std::endl;
for (const auto& iter : *(diagnostic->mAttributeArrayData)) {
const std::string& name = iter.first;
const DiagnosticArrayData& arrayData = iter.second;
os << " Attribute Array : [" << name << "] " << std::endl
<< " Size Match : " << Local::fts(arrayData.mSizeMatch) << std::endl
<< " Type Match : " << Local::fts(arrayData.mTypesMatch) << std::endl
<< " Flags Match : " << Local::fts(arrayData.mFlagsMatch) << std::endl;
const bool arrayValuesMatch = !static_cast<bool>(arrayData.mArrayValueFlags);
os << " Array Values : " << Local::fts(arrayValuesMatch) << std::endl;
if (!arrayValuesMatch) {
for (size_t idx : *(arrayData.mArrayValueFlags)) {
os << " [" << idx << "] "
<< std::endl;
}
}
}
}
}
}
return result;
}
template <typename ValueT>
using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type;
bool compareUntypedGrids(ComparisonResult &resultData,
const openvdb::GridBase &firstGrid,
const openvdb::GridBase &secondGrid,
const ComparisonSettings &settings,
const openvdb::MaskGrid::ConstPtr maskGrid)
{
bool result = false, valid = false;;
TypeList::foreach([&](auto x) {
using GridT = ConverterT<decltype(x)>;
if (firstGrid.isType<GridT>()) {
valid = true;
const GridT& firstGridTyped = static_cast<const GridT&>(firstGrid);
const GridT& secondGridTyped = static_cast<const GridT&>(secondGrid);
result = compareGrids(resultData, firstGridTyped, secondGridTyped, settings, maskGrid);
}
});
if (!valid) {
if (firstGrid.isType<openvdb::points::PointDataGrid>()) {
valid = true;
const openvdb::points::PointDataGrid& firstGridTyped =
static_cast<const openvdb::points::PointDataGrid&>(firstGrid);
const openvdb::points::PointDataGrid& secondGridTyped =
static_cast<const openvdb::points::PointDataGrid&>(secondGrid);
result = compareGrids(resultData, firstGridTyped, secondGridTyped, settings, maskGrid);
}
}
if (!valid) {
OPENVDB_THROW(openvdb::TypeError, "Unsupported grid type: " + firstGrid.valueType());
}
return result;
}
}
| 24,049 | C++ | 34.842027 | 128 | 0.590669 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestCast.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "../test/util.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestCast : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestCast);
CPPUNIT_TEST(explicitScalar);
CPPUNIT_TEST_SUITE_END();
void explicitScalar();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestCast);
void
TestCast::explicitScalar()
{
auto generate = [this](const auto& types) {
for (const auto& t1 : types) {
std::string code;
size_t idx = 1;
for (const auto& t2 : types) {
if (t1 == t2) continue;
std::string tmp = "_T1_@_A1_ = _T1_(_T2_@_A2_);";
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx));
unittest_util::replace(tmp, "_A2_", "test" + t2);
unittest_util::replace(tmp, "_T1_", t1);
unittest_util::replace(tmp, "_T2_", t2);
code += tmp + "\n";
++idx;
}
this->registerTest(code, "cast_explicit." + t1 + ".ax");
}
};
generate(std::vector<std::string>{ "bool", "int32", "int64", "float", "double" });
const auto names = unittest_util::nameSequence("test", 4);
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){
mHarness.addAttribute<int32_t>("testint32", 1, 1);
mHarness.addAttribute<int64_t>("testint64", 0, 0);
mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f);
mHarness.addAttribute<double>("testdouble", 0.1, 0.1);
mHarness.addAttributes<bool>(names, {true, false, true, true});
}
},
{ "int32", [&](){
mHarness.addAttribute<bool>("testbool", true, true);
mHarness.addAttribute<int64_t>("testint64", 2, 2);
mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f);
mHarness.addAttribute<double>("testdouble", 2.1, 2.1);
mHarness.addAttributes<int32_t>(names, {1, 2, 2, 2});
}
},
{ "int64", [&]() {
mHarness.addAttribute<bool>("testbool", true, true);
mHarness.addAttribute<int32_t>("testint32", 2, 2);
mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f);
mHarness.addAttribute<double>("testdouble", 2.1, 2.1);
mHarness.addAttributes<int64_t>(names, {1, 2, 2, 2});
}
},
{ "float", [&]() {
mHarness.addAttribute<bool>("testbool", true, true);
mHarness.addAttribute<int32_t>("testint32", 1, 1);
mHarness.addAttribute<int64_t>("testint64", 1, 1);
mHarness.addAttribute<double>("testdouble", 1.1, 1.1);
mHarness.addAttributes<float>(names, {1.0f, 1.0f, 1.0f, float(1.1)});
}
},
{ "double", [&]() {
mHarness.addAttribute<bool>("testbool", true, true);
mHarness.addAttribute<int32_t>("testint32", 1, 1);
mHarness.addAttribute<int64_t>("testint64", 1, 1);
mHarness.addAttribute<float>("testfloat", 1.1f, 1.1f);
mHarness.addAttributes<double>(names, {1.0, 1.0, 1.0, double(1.1f)});
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("cast_explicit." + expc.first + ".ax");
}
}
| 3,632 | C++ | 34.271844 | 86 | 0.535242 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestVDBFunctions.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "util.h"
#include <openvdb_ax/ax.h>
#include <openvdb_ax/codegen/Types.h>
#include <openvdb_ax/codegen/Functions.h>
#include <openvdb_ax/codegen/FunctionRegistry.h>
#include <openvdb_ax/codegen/FunctionTypes.h>
#include <openvdb_ax/compiler/PointExecutable.h>
#include <openvdb_ax/compiler/VolumeExecutable.h>
#include <openvdb/points/AttributeArray.h>
#include <openvdb/points/PointConversion.h>
#include <openvdb/points/PointGroup.h>
#include <cppunit/extensions/HelperMacros.h>
class TestVDBFunctions : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestVDBFunctions);
CPPUNIT_TEST(addremovefromgroup);
CPPUNIT_TEST(deletepoint);
CPPUNIT_TEST(getcoord);
CPPUNIT_TEST(getvoxelpws);
CPPUNIT_TEST(ingroupOrder);
CPPUNIT_TEST(ingroup);
CPPUNIT_TEST(testValidContext);
CPPUNIT_TEST_SUITE_END();
void addremovefromgroup();
void deletepoint();
void getcoord();
void getvoxelpws();
void ingroupOrder();
void ingroup();
void testValidContext();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestVDBFunctions);
void
TestVDBFunctions::addremovefromgroup()
{
const std::vector<openvdb::math::Vec3s> positions = {
{1, 1, 1},
{1, 2, 1},
{2, 1, 1},
{2, 2, 1},
};
const float voxelSize = 1.0f;
const openvdb::math::Transform::ConstPtr transform =
openvdb::math::Transform::createLinearTransform(voxelSize);
const openvdb::points::PointAttributeVector<openvdb::math::Vec3s> pointList(positions);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid =
openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>(
pointList, *transform);
openvdb::points::PointDataGrid::Ptr dataGrid =
openvdb::points::createPointDataGrid<openvdb::points::NullCodec, openvdb::points::PointDataGrid>(
*pointIndexGrid, pointList, *transform);
openvdb::points::PointDataTree& dataTree = dataGrid->tree();
// apppend a new attribute for stress testing
openvdb::points::appendAttribute(dataTree, "existingTestAttribute", 2);
openvdb::points::appendGroup(dataTree, "existingTestGroup");
const std::vector<short> membershipTestGroup1{1, 0, 1, 0};
openvdb::points::setGroup(dataTree, pointIndexGrid->tree(), membershipTestGroup1, "existingTestGroup");
// second pre-existing group.
openvdb::points::appendGroup(dataTree, "existingTestGroup2");
openvdb::points::setGroup(dataTree, "existingTestGroup2", false);
const std::string code = unittest_util::loadText("test/snippets/vdb_functions/addremovefromgroup");
openvdb::ax::run(code.c_str(), *dataGrid);
auto leafIter = dataTree.cbeginLeaf();
const openvdb::points::AttributeSet& attributeSet = leafIter->attributeSet();
const openvdb::points::AttributeSet::Descriptor& desc = attributeSet.descriptor();
for (size_t i = 1; i <= 9; i++) {
const std::string groupName = "newTestGroup" + std::to_string(i);
CPPUNIT_ASSERT_MESSAGE(groupName + " doesn't exist", desc.hasGroup(groupName));
}
openvdb::points::GroupHandle newTestGroupHandle = leafIter->groupHandle("newTestGroup9");
CPPUNIT_ASSERT(!newTestGroupHandle.get(0));
CPPUNIT_ASSERT(newTestGroupHandle.get(1));
CPPUNIT_ASSERT(!newTestGroupHandle.get(2));
CPPUNIT_ASSERT(newTestGroupHandle.get(3));
// other new groups should be untouched
for (size_t i = 1; i <= 8; i++) {
openvdb::points::GroupHandle handle = leafIter->groupHandle("newTestGroup" + std::to_string(i));
CPPUNIT_ASSERT(handle.get(0));
CPPUNIT_ASSERT(handle.get(1));
CPPUNIT_ASSERT(handle.get(2));
CPPUNIT_ASSERT(handle.get(3));
}
openvdb::points::GroupHandle existingTestGroupHandle = leafIter->groupHandle("existingTestGroup");
CPPUNIT_ASSERT(existingTestGroupHandle.get(0));
CPPUNIT_ASSERT(!existingTestGroupHandle.get(1));
CPPUNIT_ASSERT(existingTestGroupHandle.get(2));
CPPUNIT_ASSERT(!existingTestGroupHandle.get(3));
// membership of this group should now mirror exisingTestGroup
openvdb::points::GroupHandle existingTestGroup2Handle = leafIter->groupHandle("existingTestGroup2");
CPPUNIT_ASSERT(existingTestGroup2Handle.get(0));
CPPUNIT_ASSERT(!existingTestGroup2Handle.get(1));
CPPUNIT_ASSERT(existingTestGroup2Handle.get(2));
CPPUNIT_ASSERT(!existingTestGroup2Handle.get(3));
// check that "nonExistentGroup" was _not_ added to the tree, as it is removed from but not present
CPPUNIT_ASSERT(!desc.hasGroup("nonExistentGroup"));
// now check 2 new attributes added to tree
openvdb::points::AttributeHandle<int> testResultAttributeHandle1(*attributeSet.get("newTestAttribute1"));
openvdb::points::AttributeHandle<int> testResultAttributeHandle2(*attributeSet.get("newTestAttribute2"));
for (openvdb::Index i = 0;i < 4; i++) {
CPPUNIT_ASSERT(testResultAttributeHandle1.get(i));
}
// should match "existingTestGroup"
CPPUNIT_ASSERT(testResultAttributeHandle2.get(0));
CPPUNIT_ASSERT(!testResultAttributeHandle2.get(1));
CPPUNIT_ASSERT(testResultAttributeHandle2.get(2));
CPPUNIT_ASSERT(!testResultAttributeHandle2.get(3));
// pre-existing attribute should still be present with the correct value
for (; leafIter; ++leafIter) {
openvdb::points::AttributeHandle<int>
handle(leafIter->attributeArray("existingTestAttribute"));
CPPUNIT_ASSERT(handle.isUniform());
CPPUNIT_ASSERT_EQUAL(2, handle.get(0));
}
}
void
TestVDBFunctions::deletepoint()
{
// NOTE: the "deletepoint" function doesn't actually directly delete points - it adds them
// to the "dead" group which marks them for deletion afterwards
mHarness.testVolumes(false);
mHarness.addInputGroups({"dead"}, {false});
mHarness.addExpectedGroups({"dead"}, {true});
mHarness.executeCode("test/snippets/vdb_functions/deletepoint");
AXTESTS_STANDARD_ASSERT();
// test without existing dead group
mHarness.reset();
mHarness.addExpectedGroups({"dead"}, {true});
mHarness.executeCode("test/snippets/vdb_functions/deletepoint");
AXTESTS_STANDARD_ASSERT();
}
void
TestVDBFunctions::getcoord()
{
// create 3 test grids
std::vector<openvdb::Int32Grid::Ptr> testGrids(3);
openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(0.1);
int i = 0;
for (auto& grid : testGrids) {
grid = openvdb::Int32Grid::create();
grid->setTransform(transform);
grid->setName("a" + std::to_string(i));
openvdb::Int32Grid::Accessor accessor = grid->getAccessor();
accessor.setValueOn(openvdb::Coord(1, 2, 3), 0);
accessor.setValueOn(openvdb::Coord(1, 10, 3), 0);
accessor.setValueOn(openvdb::Coord(-1, 1, 10), 0);
++i;
}
// convert to GridBase::Ptr
openvdb::GridPtrVec testGridsBase(3);
std::copy(testGrids.begin(), testGrids.end(), testGridsBase.begin());
const std::string code = unittest_util::loadText("test/snippets/vdb_functions/getcoord");
openvdb::ax::run(code.c_str(), testGridsBase);
// each grid has 3 active voxels. These vectors hold the expected values of those voxels
// for each grid
std::vector<openvdb::Vec3I> expectedVoxelVals(3);
expectedVoxelVals[0] = openvdb::Vec3I(1, 1, -1);
expectedVoxelVals[1] = openvdb::Vec3I(2, 10, 1);
expectedVoxelVals[2] = openvdb::Vec3I(3, 3, 10);
std::vector<openvdb::Int32Grid::Ptr> expectedGrids(3);
for (size_t i = 0; i < 3; i++) {
openvdb::Int32Grid::Ptr grid = openvdb::Int32Grid::create();
grid->setTransform(transform);
grid->setName("a" + std::to_string(i) + "_expected");
openvdb::Int32Grid::Accessor accessor = grid->getAccessor();
const openvdb::Vec3I& expectedVals = expectedVoxelVals[i];
accessor.setValueOn(openvdb::Coord(1, 2 ,3), expectedVals[0]);
accessor.setValueOn(openvdb::Coord(1, 10, 3), expectedVals[1]);
accessor.setValueOn(openvdb::Coord(-1, 1, 10), expectedVals[2]);
expectedGrids[i] = grid;
}
// check grids
bool check = true;
std::stringstream outMessage;
for (size_t i = 0; i < 3; i++){
std::stringstream stream;
unittest_util::ComparisonSettings settings;
unittest_util::ComparisonResult result(stream);
check &= unittest_util::compareGrids(result, *testGrids[i], *expectedGrids[i], settings, nullptr);
if (!check) outMessage << stream.str() << std::endl;
}
CPPUNIT_ASSERT_MESSAGE(outMessage.str(), check);
}
void
TestVDBFunctions::getvoxelpws()
{
mHarness.testPoints(false);
mHarness.addAttribute<openvdb::Vec3f>("a", openvdb::Vec3f(10.0f), openvdb::Vec3f(0.0f));
mHarness.executeCode("test/snippets/vdb_functions/getvoxelpws");
AXTESTS_STANDARD_ASSERT();
}
void
TestVDBFunctions::ingroupOrder()
{
// Test that groups inserted in a different alphabetical order are inferred
// correctly (a regression test for a previous issue)
mHarness.testVolumes(false);
mHarness.addExpectedAttributes<int>({"test", "groupTest", "groupTest2"}, {1,1,1});
mHarness.addInputGroups({"b", "a"}, {false, true});
mHarness.addExpectedGroups({"b", "a"}, {false, true});
mHarness.executeCode("test/snippets/vdb_functions/ingroup", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestVDBFunctions::ingroup()
{
// test a tree with no groups
CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0);
openvdb::points::PointDataGrid::Ptr pointDataGrid1 = mHarness.mInputPointGrids.back();
openvdb::points::PointDataTree& pointTree = pointDataGrid1->tree();
// compile and execute
openvdb::ax::Compiler compiler;
std::string code = unittest_util::loadText("test/snippets/vdb_functions/ingroup");
openvdb::ax::PointExecutable::Ptr executable =
compiler.compile<openvdb::ax::PointExecutable>(code);
CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid1));
// the snippet of code adds "groupTest" and groupTest2 attributes which should both have the values
// "1" everywhere
for (auto leafIter = pointTree.cbeginLeaf(); leafIter; ++leafIter) {
openvdb::points::AttributeHandle<int> handle1(leafIter->attributeArray("groupTest"));
openvdb::points::AttributeHandle<int> handle2(leafIter->attributeArray("groupTest2"));
for (auto iter = leafIter->beginIndexAll(); iter; ++iter) {
CPPUNIT_ASSERT_EQUAL(1, handle1.get(*iter));
CPPUNIT_ASSERT_EQUAL(1, handle2.get(*iter));
}
}
// there should be no groups - ensure none have been added by accident by query code
auto leafIter = pointTree.cbeginLeaf();
const openvdb::points::AttributeSet& attributeSet = leafIter->attributeSet();
const openvdb::points::AttributeSet::Descriptor& descriptor1 = attributeSet.descriptor();
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), descriptor1.groupMap().size());
// now we add a single group and run the test again
openvdb::points::appendGroup(pointTree, "testGroup");
setGroup(pointTree, "testGroup", false);
executable = compiler.compile<openvdb::ax::PointExecutable>(code);
CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid1));
for (auto leafIter = pointTree.cbeginLeaf(); leafIter; ++leafIter) {
openvdb::points::AttributeHandle<int> handle1(leafIter->attributeArray("groupTest"));
openvdb::points::AttributeHandle<int> handle2(leafIter->attributeArray("groupTest2"));
for (auto iter = leafIter->beginIndexAll(); iter; ++iter) {
CPPUNIT_ASSERT_EQUAL(1, handle1.get(*iter));
CPPUNIT_ASSERT_EQUAL(1, handle2.get(*iter));
}
}
// for the next couple of tests we create a small tree with 4 points. We wish to test queries of a single group
// in a tree that has several groups
const std::vector<openvdb::math::Vec3s> positions = {
{1, 1, 1},
{1, 2, 1},
{2, 1, 1},
{2, 2, 1},
};
const float voxelSize = 1.0f;
const openvdb::math::Transform::ConstPtr transform =
openvdb::math::Transform::createLinearTransform(voxelSize);
const openvdb::points::PointAttributeVector<openvdb::math::Vec3s> pointList(positions);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid =
openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>
(pointList, *transform);
openvdb::points::PointDataGrid::Ptr pointDataGrid2 =
openvdb::points::createPointDataGrid<openvdb::points::NullCodec, openvdb::points::PointDataGrid>
(*pointIndexGrid, pointList, *transform);
openvdb::points::PointDataTree::Ptr pointDataTree2 = pointDataGrid2->treePtr();
// add 9 groups. 8 groups can be added by using a single group attribute, but this requires adding another attribute
// and hence exercises the code better
for (size_t i = 0; i < 9; i++) {
openvdb::points::appendGroup(*pointDataTree2, "testGroup" + std::to_string(i));
}
std::vector<short> membershipTestGroup2{0, 0, 1, 0};
openvdb::points::setGroup(*pointDataTree2, pointIndexGrid->tree(), membershipTestGroup2, "testGroup2");
executable = compiler.compile<openvdb::ax::PointExecutable>(code);
CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid2));
auto leafIter2 = pointDataTree2->cbeginLeaf();
const openvdb::points::AttributeSet& attributeSet2 = leafIter2->attributeSet();
openvdb::points::AttributeHandle<int> testResultAttributeHandle(*attributeSet2.get("groupTest2"));
// these should line up with the defined membership
CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(0), 1);
CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(1), 1);
CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(2), 2);
CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(3), 1);
// check that no new groups have been created or deleted
const openvdb::points::AttributeSet::Descriptor& descriptor2 = attributeSet2.descriptor();
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(9), descriptor2.groupMap().size());
for (size_t i = 0; i < 9; i++) {
CPPUNIT_ASSERT(descriptor2.hasGroup("testGroup" + std::to_string(i)));
}
}
void
TestVDBFunctions::testValidContext()
{
std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext);
openvdb::ax::Compiler compiler;
openvdb::ax::FunctionOptions ops;
ops.mLazyFunctions = false;
/// Generate code which calls the given function
auto generate = [&C](const openvdb::ax::codegen::Function::Ptr F,
const std::string& name) -> std::string
{
std::vector<llvm::Type*> types;
F->types(types, *C);
std::string code;
std::string args;
size_t idx = 0;
for (auto T : types) {
const std::string axtype =
openvdb::ax::ast::tokens::typeStringFromToken(
openvdb::ax::codegen::tokenFromLLVMType(T));
code += axtype + " local" + std::to_string(idx) + ";\n";
args += "local" + std::to_string(idx) + ",";
}
// remove last ","
if (!args.empty()) args.pop_back();
code += name + "(" + args + ");";
return code;
};
/// Test Volumes fails when trying to call Point Functions
{
openvdb::ax::codegen::FunctionRegistry::UniquePtr
registry(new openvdb::ax::codegen::FunctionRegistry);
openvdb::ax::codegen::insertVDBPointFunctions(*registry, &ops);
for (auto& func : registry->map()) {
// Don't check internal functions
if (func.second.isInternal()) continue;
const openvdb::ax::codegen::FunctionGroup* const ptr = func.second.function();
CPPUNIT_ASSERT(ptr);
const auto& signatures = ptr->list();
CPPUNIT_ASSERT(!signatures.empty());
const std::string code = generate(signatures.front(), func.first);
CPPUNIT_ASSERT_THROW_MESSAGE(ERROR_MSG("Expected Compiler Error", code),
compiler.compile<openvdb::ax::VolumeExecutable>(code),
openvdb::AXCompilerError);
}
}
/// Test Points fails when trying to call Volume Functions
{
openvdb::ax::codegen::FunctionRegistry::UniquePtr
registry(new openvdb::ax::codegen::FunctionRegistry);
openvdb::ax::codegen::insertVDBVolumeFunctions(*registry, &ops);
for (auto& func : registry->map()) {
// Don't check internal functions
if (func.second.isInternal()) continue;
const openvdb::ax::codegen::FunctionGroup* const ptr = func.second.function();
CPPUNIT_ASSERT(ptr);
const auto& signatures = ptr->list();
CPPUNIT_ASSERT(!signatures.empty());
const std::string code = generate(signatures.front(), func.first);
CPPUNIT_ASSERT_THROW_MESSAGE(ERROR_MSG("Expected Compiler Error", code),
compiler.compile<openvdb::ax::PointExecutable>(code),
openvdb::AXCompilerError);
}
}
}
| 17,370 | C++ | 37.861297 | 121 | 0.672366 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestDeclare.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestDeclare : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestDeclare);
CPPUNIT_TEST(testLocalVariables);
CPPUNIT_TEST(testLocalVectorVariables);
CPPUNIT_TEST(testAttributes);
CPPUNIT_TEST(testVectorAttributes);
CPPUNIT_TEST(testNewAttributes);
CPPUNIT_TEST(testNewVectorAttributes);
CPPUNIT_TEST(testVectorAttributeImplicit);
CPPUNIT_TEST(testAmbiguousScalarAttributes);
CPPUNIT_TEST(testAmbiguousVectorAttributes);
CPPUNIT_TEST(testAmbiguousScalarExternals);
CPPUNIT_TEST(testAmbiguousVectorExternals);
CPPUNIT_TEST(testAttributesVolume);
CPPUNIT_TEST_SUITE_END();
void testLocalVariables();
void testAttributes();
void testNewAttributes();
void testNewVectorAttributes();
void testLocalVectorVariables();
void testVectorAttributes();
void testVectorAttributeImplicit();
void testAmbiguousScalarAttributes();
void testAmbiguousVectorAttributes();
void testAmbiguousScalarExternals();
void testAmbiguousVectorExternals();
void testAttributesVolume();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestDeclare);
void
TestDeclare::testLocalVariables()
{
mHarness.executeCode("test/snippets/declare/declareLocalVariables");
// input data should not have changed
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testLocalVectorVariables()
{
mHarness.executeCode("test/snippets/declare/declareLocalVectorVariables");
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testAttributes()
{
mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 4),
{0.0f, 0.2f, 10.0f, 10.0f});
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("int_test", 3),
{0, 5, 10});
mHarness.addAttribute("short_test", int16_t(1));
mHarness.addAttribute("long_test", int64_t(3));
mHarness.addAttribute("double_test", 0.3);
mHarness.executeCode("test/snippets/declare/declareAttributes");
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testAttributesVolume()
{
mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 4),
{0.0f, 0.2f, 10.0f, 10.0f});
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("int_test", 3),
{0, 5, 10});
mHarness.addAttribute("long_test", int64_t(3));
mHarness.addAttribute("double_test", 0.3);
mHarness.executeCode("test/snippets/declare/declareAttributesVolume");
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testNewAttributes()
{
mHarness.addExpectedAttributes<float>(unittest_util::nameSequence("float_test", 4),
{0.0f, 0.2f, 10.0f, 10.0f});
mHarness.addExpectedAttributes<int32_t>(unittest_util::nameSequence("int_test", 3),
{0, 5, 10});
mHarness.addExpectedAttribute("short_test", int16_t(1));
mHarness.addExpectedAttribute("long_test", int64_t(3));
mHarness.addExpectedAttribute("double_test", 0.3);
// Volume data needs to exist to be tested
mHarness.addInputVolumes<float>(unittest_util::nameSequence("float_test", 4),
{0.0f, 0.2f, 10.0f, 10.0f});
mHarness.addInputVolumes<int32_t>(unittest_util::nameSequence("int_test", 3),
{0, 5, 10});
mHarness.addInputVolumes<int16_t>({"short_test"}, {int16_t(1)});
mHarness.addInputVolumes<int64_t>({"long_test"}, {int64_t(3)});
mHarness.addInputVolumes<double>({"double_test"}, {0.3});
mHarness.executeCode("test/snippets/declare/declareAttributes", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testNewVectorAttributes()
{
mHarness.addExpectedAttributes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"},
{openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)});
mHarness.addExpectedAttributes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"},
{openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)});
mHarness.addExpectedAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(0.3, 0.4, 0.5));
// Volume data needs to exist to be tested
mHarness.addInputVolumes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"},
{openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)});
mHarness.addInputVolumes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"},
{openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)});
mHarness.addInputVolumes<openvdb::Vec3d>({"vec_double_test"}, {openvdb::Vec3d(0.3, 0.4, 0.5)});
mHarness.executeCode("test/snippets/declare/declareNewVectorAttributes", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testVectorAttributes()
{
mHarness.addAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(0.3, 0.4, 0.5));
mHarness.addAttributes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"},
{openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)});
mHarness.addAttributes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"},
{openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)});
mHarness.executeCode("test/snippets/declare/declareVectorAttributes");
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testVectorAttributeImplicit()
{
mHarness.addAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(1.0, 0.3, 0.4));
mHarness.executeCode("test/snippets/declare/declareVectorAttributeImplicit");
AXTESTS_STANDARD_ASSERT();
}
void
TestDeclare::testAmbiguousScalarAttributes()
{
const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousScalarAttributes");
CPPUNIT_ASSERT(!success);
}
void
TestDeclare::testAmbiguousVectorAttributes()
{
const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousVectorAttributes");
CPPUNIT_ASSERT(!success);
}
void
TestDeclare::testAmbiguousScalarExternals()
{
const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousScalarExternals");
CPPUNIT_ASSERT(!success);
}
void
TestDeclare::testAmbiguousVectorExternals()
{
const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousVectorExternals");
CPPUNIT_ASSERT(!success);
}
| 6,335 | C++ | 31.32653 | 104 | 0.714601 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestWorldSpaceAccessors.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <openvdb_ax/ax.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/points/PointGroup.h>
#include <openvdb/points/PointConversion.h>
#include <openvdb/points/AttributeArray.h>
#include <openvdb/math/Transform.h>
#include <openvdb/openvdb.h>
#include <cppunit/extensions/HelperMacros.h>
#include <limits>
using namespace openvdb::points;
class TestWorldSpaceAccessors: public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestWorldSpaceAccessors);
CPPUNIT_TEST(testWorldSpaceAssign);
CPPUNIT_TEST(testWorldSpaceAssignComponent);
CPPUNIT_TEST_SUITE_END();
void testWorldSpaceAssign();
void testWorldSpaceAssignComponent();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestWorldSpaceAccessors);
void
TestWorldSpaceAccessors::testWorldSpaceAssign()
{
std::vector<openvdb::Vec3d> positions =
{openvdb::Vec3d(0.0, 0.0, 0.0),
openvdb::Vec3d(0.0, 0.0, 0.05),
openvdb::Vec3d(0.0, 1.0, 0.0),
openvdb::Vec3d(1.0, 1.0, 0.0)};
CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0);
PointDataGrid::Ptr grid = mHarness.mInputPointGrids.back();
openvdb::points::PointDataTree* tree = &(grid->tree());
// @note snippet moves all points to a single leaf node
CPPUNIT_ASSERT_EQUAL(openvdb::points::pointCount(*tree), openvdb::Index64(4));
const std::string code = unittest_util::loadText("test/snippets/worldspace/worldSpaceAssign");
CPPUNIT_ASSERT_NO_THROW(openvdb::ax::run(code.c_str(), *grid));
// Tree is modified if points are moved
tree = &(grid->tree());
CPPUNIT_ASSERT_EQUAL(openvdb::points::pointCount(*tree), openvdb::Index64(4));
// test that P_original has the world-space value of the P attribute prior to running this snippet.
// test that P_new has the expected world-space P value
PointDataTree::LeafCIter leaf = tree->cbeginLeaf();
const openvdb::math::Transform& transform = grid->transform();
for (; leaf; ++leaf)
{
CPPUNIT_ASSERT(leaf->pointCount() == 4);
AttributeHandle<openvdb::Vec3f>::Ptr pOriginalHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P_original"));
AttributeHandle<openvdb::Vec3f>::Ptr pNewHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P_new"));
AttributeHandle<openvdb::Vec3f>::Ptr pHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P"));
for (auto voxel = leaf->cbeginValueAll(); voxel; ++voxel) {
const openvdb::Coord& coord = voxel.getCoord();
auto iter = leaf->beginIndexVoxel(coord);
for (; iter; ++iter) {
const openvdb::Index idx = *iter;
// test that the value for P_original
const openvdb::Vec3f& oldPosition = positions[idx];
const openvdb::Vec3f& pOriginal = pOriginalHandle->get(idx);
CPPUNIT_ASSERT_EQUAL(oldPosition.x(), pOriginal.x());
CPPUNIT_ASSERT_EQUAL(oldPosition.y(), pOriginal.y());
CPPUNIT_ASSERT_EQUAL(oldPosition.z(), pOriginal.z());
// test that the value for P_new, which should be the world space value of the points
const openvdb::Vec3f newPosition = openvdb::Vec3f(2.22f, 3.33f, 4.44f);
const openvdb::Vec3f& pNew = pNewHandle->get(idx);
CPPUNIT_ASSERT_EQUAL(newPosition.x(), pNew.x());
CPPUNIT_ASSERT_EQUAL(newPosition.y(), pNew.y());
CPPUNIT_ASSERT_EQUAL(newPosition.z(), pNew.z());
// test that the value for P, which should be the updated voxel space value of the points
const openvdb::Vec3f voxelSpacePosition = openvdb::Vec3f(0.2f, 0.3f, 0.4f);
const openvdb::Vec3f& pVoxelSpace = pHandle->get(idx);
// @todo: look at improving precision
CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.x(), pVoxelSpace.x(), 1e-5);
CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.y(), pVoxelSpace.y(), 1e-5);
CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.z(), pVoxelSpace.z(), 1e-5);
// test that the value for P, which should be the updated world space value of the points
const openvdb::Vec3f positionWS = openvdb::Vec3f(2.22f, 3.33f, 4.44f);
const openvdb::Vec3f pWS = transform.indexToWorld(coord.asVec3d() + pHandle->get(idx));
CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.x(), pWS.x(), std::numeric_limits<float>::epsilon());
CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.y(), pWS.y(), std::numeric_limits<float>::epsilon());
CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.z(), pWS.z(), std::numeric_limits<float>::epsilon());
}
}
}
}
void
TestWorldSpaceAccessors::testWorldSpaceAssignComponent()
{
std::vector<openvdb::Vec3d> positions =
{openvdb::Vec3d(0.0, 0.0, 0.0),
openvdb::Vec3d(0.0, 0.0, 0.05),
openvdb::Vec3d(0.0, 1.0, 0.0),
openvdb::Vec3d(1.0, 1.0, 0.0)};
CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0);
PointDataGrid::Ptr grid = mHarness.mInputPointGrids.back();
openvdb::points::PointDataTree& tree = grid->tree();
const openvdb::Index64 originalCount = pointCount(tree);
CPPUNIT_ASSERT(originalCount > 0);
const std::string code = unittest_util::loadText("test/snippets/worldspace/worldSpaceAssignComponent");
CPPUNIT_ASSERT_NO_THROW(openvdb::ax::run(code.c_str(), *grid));
// test that P_original has the world-space value of the P attribute prior to running this snippet.
// test that P_new has the expected world-space P value
PointDataTree::LeafCIter leaf = grid->tree().cbeginLeaf();
const openvdb::math::Transform& transform = grid->transform();
for (; leaf; ++leaf)
{
AttributeHandle<float>::Ptr pXOriginalHandle = AttributeHandle<float>::create(leaf->attributeArray("Px_original"));
AttributeHandle<float>::Ptr pNewHandle = AttributeHandle<float>::create(leaf->attributeArray("Px_new"));
AttributeHandle<openvdb::Vec3f>::Ptr pHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P"));
for (auto voxel = leaf->cbeginValueAll(); voxel; ++voxel) {
const openvdb::Coord& coord = voxel.getCoord();
auto iter = leaf->beginIndexVoxel(coord);
for (; iter; ++iter) {
const openvdb::Index idx = *iter;
//@todo: requiring the point order, we should check the values of the px_original
// test that the value for P_original
// const float oldPosition = positions[idx].x();
// const float pXOriginal = pXOriginalHandle->get(idx);
// CPPUNIT_ASSERT_EQUAL(oldPosition, pOriginal.x());
// test that the value for P_new, which should be the world space value of the points
const float newX = 5.22f;
const float pNewX = pNewHandle->get(idx);
CPPUNIT_ASSERT_EQUAL(newX, pNewX);
// test that the value for P, which should be the updated voxel space value of the points
const float voxelSpacePosition = 0.2f;
const openvdb::Vec3f& pVoxelSpace = pHandle->get(idx);
// @todo: look at improving precision
CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition, pVoxelSpace.x(), 1e-5);
//@todo: requiring point order, check the y and z components are unchanged
// CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.y(), pVoxelSpace.y(), 1e-6);
// CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.z(), pVoxelSpace.z(), 1e-6);
// test that the value for P, which should be the updated world space value of the points
const float positionWSX = 5.22f;
const openvdb::Vec3f pWS = transform.indexToWorld(coord.asVec3d() + pHandle->get(idx));
CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWSX, pWS.x(), std::numeric_limits<float>::epsilon());
//@todo: requiring point order, check the y and z components are unchanged
// CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.y(), pWS.y(), std::numeric_limits<float>::epsilon());
// CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.z(), pWS.z(), std::numeric_limits<float>::epsilon());
}
}
}
}
| 8,610 | C++ | 44.083769 | 139 | 0.637515 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestStandardFunctions.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb_ax/math/OpenSimplexNoise.h>
#include <openvdb_ax/compiler/PointExecutable.h>
#include <openvdb_ax/compiler/VolumeExecutable.h>
#include <openvdb/points/PointConversion.h>
#include <openvdb/util/CpuTimer.h>
#include <cppunit/extensions/HelperMacros.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <functional>
#include <random>
using namespace openvdb::points;
using namespace openvdb::ax;
class TestStandardFunctions : public unittest_util::AXTestCase
{
public:
#ifdef PROFILE
void setUp() override {
// if PROFILE, generate more data for each test
mHarness.reset(/*ppv*/8, openvdb::CoordBBox({0,0,0},{50,50,50}));
}
#endif
CPPUNIT_TEST_SUITE(TestStandardFunctions);
CPPUNIT_TEST(abs);
CPPUNIT_TEST(acos);
CPPUNIT_TEST(asin);
CPPUNIT_TEST(atan);
CPPUNIT_TEST(atan2);
CPPUNIT_TEST(atof);
CPPUNIT_TEST(atoi);
CPPUNIT_TEST(cbrt);
CPPUNIT_TEST(clamp);
CPPUNIT_TEST(cosh);
CPPUNIT_TEST(cross);
CPPUNIT_TEST(curlsimplexnoise);
CPPUNIT_TEST(determinant);
CPPUNIT_TEST(diag);
CPPUNIT_TEST(dot);
CPPUNIT_TEST(euclideanmod);
CPPUNIT_TEST(external);
CPPUNIT_TEST(fit);
CPPUNIT_TEST(floormod);
CPPUNIT_TEST(hash);
CPPUNIT_TEST(identity3);
CPPUNIT_TEST(identity4);
CPPUNIT_TEST(intrinsic);
CPPUNIT_TEST(length);
CPPUNIT_TEST(lengthsq);
CPPUNIT_TEST(lerp);
CPPUNIT_TEST(max);
CPPUNIT_TEST(min);
CPPUNIT_TEST(normalize);
CPPUNIT_TEST(polardecompose);
CPPUNIT_TEST(postscale);
CPPUNIT_TEST(pow);
CPPUNIT_TEST(prescale);
CPPUNIT_TEST(pretransform);
CPPUNIT_TEST(print);
CPPUNIT_TEST(rand);
CPPUNIT_TEST(rand32);
CPPUNIT_TEST(sign);
CPPUNIT_TEST(signbit);
CPPUNIT_TEST(simplexnoise);
CPPUNIT_TEST(sinh);
CPPUNIT_TEST(tan);
CPPUNIT_TEST(tanh);
CPPUNIT_TEST(truncatemod);
CPPUNIT_TEST(trace);
CPPUNIT_TEST(transform);
CPPUNIT_TEST(transpose);
CPPUNIT_TEST_SUITE_END();
void abs();
void acos();
void asin();
void atan();
void atan2();
void atof();
void atoi();
void cbrt();
void clamp();
void cosh();
void cross();
void curlsimplexnoise();
void determinant();
void diag();
void dot();
void euclideanmod();
void external();
void fit();
void floormod();
void hash();
void identity3();
void identity4();
void intrinsic();
void length();
void lengthsq();
void lerp();
void max();
void min();
void normalize();
void polardecompose();
void postscale();
void pow();
void prescale();
void pretransform();
void print();
void rand();
void rand32();
void sign();
void signbit();
void simplexnoise();
void sinh();
void tan();
void tanh();
void truncatemod();
void trace();
void transform();
void transpose();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestStandardFunctions);
inline void testFunctionOptions(unittest_util::AXTestHarness& harness,
const std::string& name,
CustomData::Ptr data = CustomData::create())
{
const std::string file = "test/snippets/function/" + name;
#ifdef PROFILE
struct Timer : public openvdb::util::CpuTimer {} timer;
const std::string code = unittest_util::loadText(file);
timer.start(std::string("\n") + name + std::string(": Parsing"));
const ast::Tree::Ptr syntaxTree = ast::parse(code.c_str());
timer.stop();
// @warning the first execution can take longer due to some llvm startup
// so if you're profiling a single function be aware of this.
// This also profiles execution AND compilation.
auto profile = [&syntaxTree, &timer, &data]
(const openvdb::ax::CompilerOptions& opts,
std::vector<openvdb::points::PointDataGrid::Ptr>& points,
openvdb::GridPtrVec& volumes,
const bool doubleCompile = true)
{
if (!points.empty())
{
openvdb::ax::Compiler compiler(opts);
if (doubleCompile) {
compiler.compile<PointExecutable>(*syntaxTree, data);
}
{
timer.start(" Points/Compilation ");
PointExecutable::Ptr executable =
compiler.compile<PointExecutable>(*syntaxTree, data);
timer.stop();
timer.start(" Points/Execution ");
executable->execute(*points.front());
timer.stop();
}
}
if (!volumes.empty())
{
openvdb::ax::Compiler compiler(opts);
if (doubleCompile) {
compiler.compile<VolumeExecutable>(*syntaxTree, data);
}
{
timer.start(" Volumes/Compilation ");
VolumeExecutable::Ptr executable =
compiler.compile<VolumeExecutable>(*syntaxTree, data);
timer.stop();
timer.start(" Volumes/Execution ");
executable->execute(volumes);
timer.stop();
}
}
};
#endif
openvdb::ax::CompilerOptions opts;
opts.mFunctionOptions.mConstantFoldCBindings = false;
opts.mFunctionOptions.mPrioritiseIR = false;
#ifdef PROFILE
std::cerr << " C Bindings" << std::endl;
profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids);
#else
harness.mOpts = opts;
harness.mCustomData = data;
harness.executeCode(file);
AXTESTS_STANDARD_ASSERT_HARNESS(harness);
#endif
harness.resetInputsToZero();
opts.mFunctionOptions.mConstantFoldCBindings = false;
opts.mFunctionOptions.mPrioritiseIR = true;
#ifdef PROFILE
std::cerr << " IR Functions " << std::endl;
profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids);
#else
harness.mOpts = opts;
harness.mCustomData = data;
harness.executeCode(file);
AXTESTS_STANDARD_ASSERT_HARNESS(harness);
#endif
harness.resetInputsToZero();
opts.mFunctionOptions.mConstantFoldCBindings = true;
opts.mFunctionOptions.mPrioritiseIR = false;
#ifdef PROFILE
std::cerr << " C Folding " << std::endl;
profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids);
#else
harness.mOpts = opts;
harness.mCustomData = data;
harness.executeCode(file);
AXTESTS_STANDARD_ASSERT_HARNESS(harness);
#endif
}
void
TestStandardFunctions::abs()
{
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 3), {
std::abs(-3), std::abs(3), std::abs(0)
});
mHarness.addAttribute<int64_t>("test4", std::abs(-2147483649l));
mHarness.addAttribute<float>("test5", std::abs(0.3f));
mHarness.addAttribute<float>("test6", std::abs(-0.3f));
mHarness.addAttribute<double>("test7", std::abs(1.79769e+308));
mHarness.addAttribute<double>("test8", std::abs(-1.79769e+308));
testFunctionOptions(mHarness, "abs");
}
void
TestStandardFunctions::acos()
{
volatile double arg = 0.5;
volatile float argf = 0.5f;
mHarness.addAttribute<double>("test1", std::acos(arg));
mHarness.addAttribute<float>("test2", std::acos(argf));
testFunctionOptions(mHarness, "acos");
}
void
TestStandardFunctions::asin()
{
mHarness.addAttribute<double>("test1", std::asin(-0.5));
mHarness.addAttribute<float>("test2", std::asin(-0.5f));
testFunctionOptions(mHarness, "asin");
}
void
TestStandardFunctions::atan()
{
mHarness.addAttribute<double>("test1", std::atan(1.0));
mHarness.addAttribute<float>("test2", std::atan(1.0f));
testFunctionOptions(mHarness, "atan");
}
void
TestStandardFunctions::atan2()
{
mHarness.addAttribute<double>("test1", std::atan2(1.0, 1.0));
mHarness.addAttribute<float>("test2", std::atan2(1.0f, 1.0f));
testFunctionOptions(mHarness, "atan2");
}
void
TestStandardFunctions::atoi()
{
const std::vector<int32_t> values {
std::atoi(""),
std::atoi("-0"),
std::atoi("+0"),
std::atoi("-1"),
std::atoi("1"),
std::atoi("1s"),
std::atoi("1s"),
std::atoi(" 1"),
std::atoi("1s1"),
std::atoi("1 1"),
std::atoi("11"),
std::atoi("2147483647"), // int max
std::atoi("-2147483648")
};
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 13), values);
testFunctionOptions(mHarness, "atoi");
}
void
TestStandardFunctions::atof()
{
const std::vector<double> values {
std::atof(""),
std::atof("-0.0"),
std::atof("+0.0"),
std::atof("-1.1"),
std::atof("1.5"),
std::atof("1.s9"),
std::atof("1s.9"),
std::atof(" 1.6"),
std::atof("1.5s1"),
std::atof("1. 1.3"),
std::atof("11.11"),
std::atof("1.79769e+308"),
std::atof("2.22507e-308")
};
mHarness.addAttributes<double>(unittest_util::nameSequence("test", 13), values);
testFunctionOptions(mHarness, "atof");
}
void
TestStandardFunctions::cbrt()
{
volatile double arg = 729.0;
volatile float argf = 729.0f;
mHarness.addAttribute<double>("test1", std::cbrt(arg));
mHarness.addAttribute<float>("test2", std::cbrt(argf));
testFunctionOptions(mHarness, "cbrt");
}
void
TestStandardFunctions::clamp()
{
mHarness.addAttributes<double>(unittest_util::nameSequence("double_test", 3), {-1.5, 0.0, 1.5});
testFunctionOptions(mHarness, "clamp");
}
void
TestStandardFunctions::cosh()
{
volatile float arg = 1.0f;
mHarness.addAttribute<double>("test1", std::cosh(1.0));
mHarness.addAttribute<float>("test2", std::cosh(arg));
testFunctionOptions(mHarness, "cosh");
}
void
TestStandardFunctions::cross()
{
const openvdb::Vec3d ad(1.0,2.2,3.4), bd(4.1,5.3,6.2);
const openvdb::Vec3f af(1.0f,2.2f,3.4f), bf(4.1f,5.3f,6.2f);
const openvdb::Vec3i ai(1,2,3), bi(4,5,6);
mHarness.addAttribute<openvdb::Vec3d>("test1", ad.cross(bd));
mHarness.addAttribute<openvdb::Vec3f>("test2", af.cross(bf));
mHarness.addAttribute<openvdb::Vec3i>("test3", ai.cross(bi));
testFunctionOptions(mHarness, "cross");
}
void
TestStandardFunctions::curlsimplexnoise()
{
struct Local {
static inline double noise(double x, double y, double z) {
const OSN::OSNoise gen;
const double result = gen.eval<double>(x, y, z);
return (result + 1.0) * 0.5;
}
};
double result[3];
openvdb::ax::math::curlnoise<Local>(&result, 4.3, 5.7, -6.2);
const openvdb::Vec3d expected(result[0], result[1], result[2]);
mHarness.addAttributes<openvdb::Vec3d>
(unittest_util::nameSequence("test", 2), {expected,expected});
testFunctionOptions(mHarness, "curlsimplexnoise");
}
void
TestStandardFunctions::determinant()
{
mHarness.addAttribute<float>("det3_float", 600.0f);
mHarness.addAttribute<double>("det3_double", 600.0);
mHarness.addAttribute<float>("det4_float", 24.0f);
mHarness.addAttribute<double>("det4_double", 2400.0);
testFunctionOptions(mHarness, "determinant");
}
void
TestStandardFunctions::diag()
{
mHarness.addAttribute<openvdb::math::Mat3<double>>
("test1", openvdb::math::Mat3<double>(-1,0,0, 0,-2,0, 0,0,-3));
mHarness.addAttribute<openvdb::math::Mat3<float>>
("test2", openvdb::math::Mat3<float>(-1,0,0, 0,-2,0, 0,0,-3));
mHarness.addAttribute<openvdb::math::Mat4<double>>
("test3", openvdb::math::Mat4<double>(-1,0,0,0, 0,-2,0,0, 0,0,-3,0, 0,0,0,-4));
mHarness.addAttribute<openvdb::math::Mat4<float>>
("test4", openvdb::math::Mat4<float>(-1,0,0,0, 0,-2,0,0, 0,0,-3,0, 0,0,0,-4));
mHarness.addAttribute<openvdb::math::Vec3<double>>("test5", openvdb::math::Vec3<float>(-1,-5,-9));
mHarness.addAttribute<openvdb::math::Vec3<float>>("test6", openvdb::math::Vec3<float>(-1,-5,-9));
mHarness.addAttribute<openvdb::math::Vec4<double>>("test7", openvdb::math::Vec4<double>(-1,-6,-11,-16));
mHarness.addAttribute<openvdb::math::Vec4<float>>("test8", openvdb::math::Vec4<float>(-1,-6,-11,-16));
testFunctionOptions(mHarness, "diag");
}
void
TestStandardFunctions::dot()
{
const openvdb::Vec3d ad(1.0,2.2,3.4), bd(4.1,5.3,6.2);
const openvdb::Vec3f af(1.0f,2.2f,3.4f), bf(4.1f,5.3f,6.2f);
const openvdb::Vec3i ai(1,2,3), bi(4,5,6);
mHarness.addAttribute<double>("test1", ad.dot(bd));
mHarness.addAttribute<float>("test2", af.dot(bf));
mHarness.addAttribute<int32_t>("test3", ai.dot(bi));
testFunctionOptions(mHarness, "dot");
}
void
TestStandardFunctions::euclideanmod()
{
static auto emod = [](auto D, auto d) -> auto {
using ValueType = decltype(D);
return ValueType(D - d * (d < 0 ? std::ceil(D/double(d)) : std::floor(D/double(d))));
};
// @note these also test that these match % op
const std::vector<int32_t> ivalues{ emod(7, 5), emod(-7, 5), emod(7,-5), emod(-7,-5) };
const std::vector<float> fvalues{ emod(7.2f, 5.7f), emod(-7.2f, 5.7f), emod(7.2f, -5.7f), emod(-7.2f, -5.7f) };
const std::vector<double> dvalues{ emod(7.2, 5.7), emod(-7.2, 5.7), emod(7.2, -5.7), emod(-7.2, -5.7) };
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 4), ivalues);
mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 4), fvalues);
mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 4), dvalues);
testFunctionOptions(mHarness, "euclideanmod");
}
void
TestStandardFunctions::external()
{
mHarness.addAttribute<float>("foo", 2.0f);
mHarness.addAttribute<openvdb::Vec3f>("v", openvdb::Vec3f(1.0f, 2.0f, 3.0f));
using FloatMeta = openvdb::TypedMetadata<float>;
using VectorFloatMeta = openvdb::TypedMetadata<openvdb::math::Vec3<float>>;
FloatMeta customFloatData(2.0f);
VectorFloatMeta customVecData(openvdb::math::Vec3<float>(1.0f, 2.0f, 3.0f));
// test initialising the data before compile
CustomData::Ptr data = CustomData::create();
data->insertData("float1", customFloatData.copy());
data->insertData("vector1", customVecData.copy());
testFunctionOptions(mHarness, "external", data);
mHarness.reset();
mHarness.addAttribute<float>("foo", 2.0f);
mHarness.addAttribute<openvdb::Vec3f>("v", openvdb::Vec3f(1.0f, 2.0f, 3.0f));
// test post compilation
data->reset();
const std::string code = unittest_util::loadText("test/snippets/function/external");
Compiler compiler;
PointExecutable::Ptr pointExecutable = compiler.compile<PointExecutable>(code, data);
VolumeExecutable::Ptr volumeExecutable = compiler.compile<VolumeExecutable>(code, data);
data->insertData("float1", customFloatData.copy());
VectorFloatMeta::Ptr customTypedVecData =
openvdb::StaticPtrCast<VectorFloatMeta>(customVecData.copy());
data->insertData<VectorFloatMeta>("vector1", customTypedVecData);
for (auto& grid : mHarness.mInputPointGrids) {
pointExecutable->execute(*grid);
}
volumeExecutable->execute(mHarness.mInputVolumeGrids);
AXTESTS_STANDARD_ASSERT()
}
void
TestStandardFunctions::fit()
{
std::vector<double> values{23.0, -23.0, -25.0, -15.0, -15.0, -18.0, -24.0, 0.0, 10.0,
-5.0, 0.0, -1.0, 4.5, 4.5, 4.5, 4.5, 4.5};
mHarness.addAttributes<double>(unittest_util::nameSequence("double_test", 17), values);
testFunctionOptions(mHarness, "fit");
}
void
TestStandardFunctions::floormod()
{
auto axmod = [](auto D, auto d) -> auto {
auto r = std::fmod(D, d);
if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d;
return r;
};
// @note these also test that these match % op
const std::vector<int32_t> ivalues{ 2,2, 3,3, -3,-3, -2,-2 };
const std::vector<float> fvalues{ axmod(7.2f,5.7f),axmod(7.2f,5.7f),
axmod(-7.2f,5.7f),axmod(-7.2f,5.7f),
axmod(7.2f,-5.7f),axmod(7.2f,-5.7f),
axmod(-7.2f,-5.7f),axmod(-7.2f,-5.7f)
};
const std::vector<double> dvalues{ axmod(7.2,5.7),axmod(7.2,5.7),
axmod(-7.2,5.7),axmod(-7.2,5.7),
axmod(7.2,-5.7),axmod(7.2,-5.7),
axmod(-7.2,-5.7),axmod(-7.2,-5.7)
};
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 8), ivalues);
mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 8), fvalues);
mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 8), dvalues);
testFunctionOptions(mHarness, "floormod");
}
void
TestStandardFunctions::hash()
{
const std::vector<int64_t> values{
static_cast<int64_t>(std::hash<std::string>{}("")),
static_cast<int64_t>(std::hash<std::string>{}("0")),
static_cast<int64_t>(std::hash<std::string>{}("abc")),
static_cast<int64_t>(std::hash<std::string>{}("123")),
};
mHarness.addAttributes<int64_t>(unittest_util::nameSequence("test", 4), values);
testFunctionOptions(mHarness, "hash");
}
void
TestStandardFunctions::identity3()
{
mHarness.addAttribute<openvdb::Mat3d>("test", openvdb::Mat3d::identity());
testFunctionOptions(mHarness, "identity3");
}
void
TestStandardFunctions::identity4()
{
mHarness.addAttribute<openvdb::Mat4d>("test", openvdb::Mat4d::identity());
testFunctionOptions(mHarness, "identity4");
}
void
TestStandardFunctions::intrinsic()
{
mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 12), {
std::sqrt(9.0),
std::cos(0.0),
std::sin(0.0),
std::log(1.0),
std::log10(1.0),
std::log2(2.0),
std::exp(0.0),
std::exp2(4.0),
std::fabs(-10.321),
std::floor(2194.213),
std::ceil(2194.213),
std::round(0.5)
});
mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 12), {
std::sqrt(9.0f),
std::cos(0.0f),
std::sin(0.0f),
std::log(1.0f),
std::log10(1.0f),
std::log2(2.0f),
std::exp(0.0f),
std::exp2(4.0f),
std::fabs(-10.321f),
std::floor(2194.213f),
std::ceil(2194.213f),
std::round(0.5f)
});
testFunctionOptions(mHarness, "intrinsic");
}
void
TestStandardFunctions::length()
{
mHarness.addAttribute("test1", openvdb::Vec2d(2.2, 3.3).length());
mHarness.addAttribute("test2", openvdb::Vec2f(2.2f, 3.3f).length());
mHarness.addAttribute("test3", std::sqrt(double(openvdb::Vec2i(2, 3).lengthSqr())));
mHarness.addAttribute("test4", openvdb::Vec3d(2.2, 3.3, 6.6).length());
mHarness.addAttribute("test5", openvdb::Vec3f(2.2f, 3.3f, 6.6f).length());
mHarness.addAttribute("test6", std::sqrt(double(openvdb::Vec3i(2, 3, 6).lengthSqr())));
mHarness.addAttribute("test7", openvdb::Vec4d(2.2, 3.3, 6.6, 7.7).length());
mHarness.addAttribute("test8", openvdb::Vec4f(2.2f, 3.3f, 6.6f, 7.7f).length());
mHarness.addAttribute("test9", std::sqrt(double(openvdb::Vec4i(2, 3, 6, 7).lengthSqr())));
testFunctionOptions(mHarness, "length");
}
void
TestStandardFunctions::lengthsq()
{
mHarness.addAttribute("test1", openvdb::Vec2d(2.2, 3.3).lengthSqr());
mHarness.addAttribute("test2", openvdb::Vec2f(2.2f, 3.3f).lengthSqr());
mHarness.addAttribute("test3", openvdb::Vec2i(2, 3).lengthSqr());
mHarness.addAttribute("test4", openvdb::Vec3d(2.2, 3.3, 6.6).lengthSqr());
mHarness.addAttribute("test5", openvdb::Vec3f(2.2f, 3.3f, 6.6f).lengthSqr());
mHarness.addAttribute("test6", openvdb::Vec3i(2, 3, 6).lengthSqr());
mHarness.addAttribute("test7", openvdb::Vec4d(2.2, 3.3, 6.6, 7.7).lengthSqr());
mHarness.addAttribute("test8", openvdb::Vec4f(2.2f, 3.3f, 6.6f, 7.7f).lengthSqr());
mHarness.addAttribute("test9", openvdb::Vec4i(2, 3, 6, 7).lengthSqr());
testFunctionOptions(mHarness, "lengthsq");
}
void
TestStandardFunctions::lerp()
{
mHarness.addAttributes<double>(unittest_util::nameSequence("test", 9),
{-1.1, 1.0000001, 1.0000001, -1.0000001, 1.1, -1.1, 6.0, 21.0, -19.0});
mHarness.addAttribute<float>("test10", 6.0f);
testFunctionOptions(mHarness, "lerp");
}
void
TestStandardFunctions::max()
{
mHarness.addAttribute("test1", std::max(-1.5, 1.5));
mHarness.addAttribute("test2", std::max(-1.5f, 1.5f));
mHarness.addAttribute("test3", std::max(-1, 1));
testFunctionOptions(mHarness, "max");
}
void
TestStandardFunctions::min()
{
mHarness.addAttribute("test1", std::min(-1.5, 1.5));
mHarness.addAttribute("test2", std::min(-1.5f, 1.5f));
mHarness.addAttribute("test3", std::min(-1, 1));
testFunctionOptions(mHarness, "min");
}
void
TestStandardFunctions::normalize()
{
openvdb::Vec3f expectedf(1.f, 2.f, 3.f);
openvdb::Vec3d expectedd(1., 2., 3.);
openvdb::Vec3d expectedi(1, 2, 3);
expectedf.normalize();
expectedd.normalize();
expectedi.normalize();
mHarness.addAttribute("test1", expectedf);
mHarness.addAttribute("test2", expectedd);
mHarness.addAttribute("test3", expectedi);
testFunctionOptions(mHarness, "normalize");
}
void
TestStandardFunctions::polardecompose()
{
// See snippet/polardecompose for details
const openvdb::Mat3d composite(
1.41421456236949, 0.0, -5.09116882455613,
0.0, 3.3, 0.0,
-1.41421356237670, 0.0, -5.09116882453015);
openvdb::Mat3d rot, symm;
openvdb::math::polarDecomposition(composite, rot, symm);
mHarness.addAttribute<openvdb::Mat3d>("rotation", rot);
mHarness.addAttribute<openvdb::Mat3d>("symm", symm);
testFunctionOptions(mHarness, "polardecompose");
}
void
TestStandardFunctions::postscale()
{
mHarness.addAttributes<openvdb::math::Mat4<float>>
({"mat1", "mat3", "mat5"}, {
openvdb::math::Mat4<float>(
10.0f, 22.0f, 36.0f, 4.0f,
50.0f, 66.0f, 84.0f, 8.0f,
90.0f, 110.0f,132.0f,12.0f,
130.0f,154.0f,180.0f,16.0f),
openvdb::math::Mat4<float>(
-1.0f, -4.0f, -9.0f, 4.0f,
-5.0f, -12.0f,-21.0f, 8.0f,
-9.0f, -20.0f,-33.0f,12.0f,
-13.0f,-28.0f,-45.0f,16.0f),
openvdb::math::Mat4<float>(
0.0f, 100.0f, 200.0f, 100.0f,
0.0f, 200.0f, 400.0f, 200.0f,
0.0f, 300.0f, 600.0f, 300.0f,
0.0f, 400.0f, 800.0f, 400.0f)
});
mHarness.addAttributes<openvdb::math::Mat4<double>>
({"mat2", "mat4", "mat6"}, {
openvdb::math::Mat4<double>(
10.0, 22.0, 36.0, 4.0,
50.0, 66.0, 84.0, 8.0,
90.0, 110.0,132.0,12.0,
130.0,154.0,180.0,16.0),
openvdb::math::Mat4<double>(
-1.0, -4.0, -9.0, 4.0,
-5.0, -12.0,-21.0, 8.0,
-9.0, -20.0,-33.0,12.0,
-13.0,-28.0,-45.0,16.0),
openvdb::math::Mat4<double>(
0.0, 100.0, 200.0, 100.0,
0.0, 200.0, 400.0, 200.0,
0.0, 300.0, 600.0, 300.0,
0.0, 400.0, 800.0, 400.0)
});
testFunctionOptions(mHarness, "postscale");
}
void
TestStandardFunctions::pow()
{
mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 5),{
1.0f,
static_cast<float>(std::pow(3.0, -2.1)),
std::pow(4.7f, -4.3f),
static_cast<float>(std::pow(4.7f, 3)),
0.00032f
});
mHarness.addAttribute<int>("int_test1", static_cast<int>(std::pow(3, 5)));
testFunctionOptions(mHarness, "pow");
}
void
TestStandardFunctions::prescale()
{
mHarness.addAttributes<openvdb::math::Mat4<float>>
({"mat1", "mat3", "mat5"}, {
openvdb::math::Mat4<float>(
10.0f, 20.0f, 30.0f, 40.0f,
55.0f, 66.0f, 77.0f, 88.0f,
108.0f, 120.0f,132.0f,144.0f,
13.0f,14.0f,15.0f,16.0f),
openvdb::math::Mat4<float>(
-1.0f,-2.0f,-3.0f,-4.0f,
-10.0f,-12.0f,-14.0f,-16.0f,
-27.0f,-30.0f,-33.0f,-36.0f,
13.0f,14.0f,15.0f,16.0f),
openvdb::math::Mat4<float>(
0.0f, 0.0f, 0.0f, 0.0f,
200.0f, 200.0f, 200.0f, 200.0f,
600.0f, 600.0f, 600.0f, 600.0f,
400.0f, 400.0f, 400.0f, 400.0f)
});
mHarness.addAttributes<openvdb::math::Mat4<double>>
({"mat2", "mat4", "mat6"}, {
openvdb::math::Mat4<double>(
10.0, 20.0, 30.0, 40.0,
55.0, 66.0, 77.0, 88.0,
108.0, 120.0,132.0,144.0,
13.0,14.0,15.0,16.0),
openvdb::math::Mat4<double>(
-1.0,-2.0,-3.0,-4.0,
-10.0,-12.0,-14.0,-16.0,
-27.0,-30.0,-33.0,-36.0,
13.0,14.0,15.0,16.0),
openvdb::math::Mat4<double>(
0.0, 0.0, 0.0, 0.0,
200.0, 200.0, 200.0, 200.0,
600.0, 600.0, 600.0, 600.0,
400.0, 400.0, 400.0, 400.0)
});
testFunctionOptions(mHarness, "prescale");
}
void
TestStandardFunctions::pretransform()
{
mHarness.addAttributes<openvdb::math::Vec3<double>>
({"test1", "test3", "test7"}, {
openvdb::math::Vec3<double>(14.0, 32.0, 50.0),
openvdb::math::Vec3<double>(18.0, 46.0, 74.0),
openvdb::math::Vec3<double>(18.0, 46.0, 74.0),
});
mHarness.addAttribute<openvdb::math::Vec4<double>>("test5",
openvdb::math::Vec4<double>(30.0, 70.0, 110.0, 150.0));
mHarness.addAttributes<openvdb::math::Vec3<float>>
({"test2", "test4", "test8"}, {
openvdb::math::Vec3<float>(14.0f, 32.0f, 50.0f),
openvdb::math::Vec3<float>(18.0f, 46.0f, 74.0f),
openvdb::math::Vec3<float>(18.0f, 46.0f, 74.0f),
});
mHarness.addAttribute<openvdb::math::Vec4<float>>("test6",
openvdb::math::Vec4<float>(30.0f, 70.0f, 110.0f, 150.0f));
testFunctionOptions(mHarness, "pretransform");
}
void
TestStandardFunctions::print()
{
openvdb::math::Transform::Ptr transform =
openvdb::math::Transform::createLinearTransform();
const std::vector<openvdb::Vec3d> single = {
openvdb::Vec3d::zero()
};
openvdb::points::PointDataGrid::Ptr grid =
openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>
(single, *transform);
const std::string code = unittest_util::loadText("test/snippets/function/print");
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(code);
std::streambuf* sbuf = std::cout.rdbuf();
try {
// Redirect cout
std::stringstream buffer;
std::cout.rdbuf(buffer.rdbuf());
executable->execute(*grid);
const std::string& result = buffer.str();
std::string expected = "a\n1\n2e-10\n";
expected += openvdb::Vec4i(3,4,5,6).str() + "\n";
expected += "bcd\n";
CPPUNIT_ASSERT_EQUAL(expected, result);
}
catch (...) {
std::cout.rdbuf(sbuf);
throw;
}
std::cout.rdbuf(sbuf);
}
void
TestStandardFunctions::rand()
{
std::mt19937_64 engine;
std::uniform_real_distribution<double> uniform(0.0,1.0);
size_t hash = std::hash<double>()(2.0);
engine.seed(hash);
const double expected1 = uniform(engine);
hash = std::hash<double>()(3.0);
engine.seed(hash);
const double expected2 = uniform(engine);
const double expected3 = uniform(engine);
mHarness.addAttributes<double>({"test0", "test1", "test2", "test3"},
{expected1, expected1, expected2, expected3});
testFunctionOptions(mHarness, "rand");
}
void
TestStandardFunctions::rand32()
{
auto hashToSeed = [](size_t hash) ->
std::mt19937::result_type
{
unsigned int seed = 0;
do {
seed ^= (uint32_t) hash;
} while (hash >>= sizeof(uint32_t) * 8);
return std::mt19937::result_type(seed);
};
std::mt19937 engine;
std::uniform_real_distribution<double> uniform(0.0,1.0);
size_t hash = std::hash<double>()(2.0);
engine.seed(hashToSeed(hash));
const double expected1 = uniform(engine);
hash = std::hash<double>()(3.0);
engine.seed(hashToSeed(hash));
const double expected2 = uniform(engine);
const double expected3 = uniform(engine);
mHarness.addAttributes<double>({"test0", "test1", "test2", "test3"},
{expected1, expected1, expected2, expected3});
testFunctionOptions(mHarness, "rand32");
}
void
TestStandardFunctions::sign()
{
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 13),
{ 0,0,0,0,0,0,0, -1,-1,-1, 1,1,1 });
testFunctionOptions(mHarness, "sign");
}
void
TestStandardFunctions::signbit()
{
mHarness.addAttributes<bool>(unittest_util::nameSequence("test", 5), {true,false,true,false,false});
testFunctionOptions(mHarness, "signbit");
}
void
TestStandardFunctions::simplexnoise()
{
const OSN::OSNoise noiseGenerator;
const double noise1 = noiseGenerator.eval<double>(1.0, 2.0, 3.0);
const double noise2 = noiseGenerator.eval<double>(1.0, 2.0, 0.0);
const double noise3 = noiseGenerator.eval<double>(1.0, 0.0, 0.0);
const double noise4 = noiseGenerator.eval<double>(4.0, 14.0, 114.0);
mHarness.addAttribute<double>("noise1", (noise1 + 1.0) * 0.5);
mHarness.addAttribute<double>("noise2", (noise2 + 1.0) * 0.5);
mHarness.addAttribute<double>("noise3", (noise3 + 1.0) * 0.5);
mHarness.addAttribute<double>("noise4", (noise4 + 1.0) * 0.5);
testFunctionOptions(mHarness, "simplexnoise");
}
void
TestStandardFunctions::sinh()
{
mHarness.addAttribute<double>("test1", std::sinh(1.0));
mHarness.addAttribute<float>("test2", std::sinh(1.0f));
testFunctionOptions(mHarness, "sinh");
}
void
TestStandardFunctions::tan()
{
mHarness.addAttribute<double>("test1", std::tan(1.0));
mHarness.addAttribute<float>("test2", std::tan(1.0f));
testFunctionOptions(mHarness, "tan");
}
void
TestStandardFunctions::tanh()
{
mHarness.addAttribute<double>("test1", std::tanh(1.0));
mHarness.addAttribute<float>("test2", std::tanh(1.0f));
testFunctionOptions(mHarness, "tanh");
}
void
TestStandardFunctions::trace()
{
mHarness.addAttribute<double>("test1", 6.0);
mHarness.addAttribute<float>("test2", 6.0f);
testFunctionOptions(mHarness, "trace");
}
void
TestStandardFunctions::truncatemod()
{
// @note these also test that these match % op
const std::vector<int32_t> ivalues{ 2,-2,2,-2, };
const std::vector<float> fvalues{ std::fmod(7.2f, 5.7f), std::fmod(-7.2f, 5.7f), std::fmod(7.2f, -5.7f), std::fmod(-7.2f, -5.7f) };
const std::vector<double> dvalues{ std::fmod(7.2, 5.7), std::fmod(-7.2, 5.7), std::fmod(7.2, -5.7), std::fmod(-7.2, -5.7) };
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 4), ivalues);
mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 4), fvalues);
mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 4), dvalues);
testFunctionOptions(mHarness, "truncatemod");
}
void
TestStandardFunctions::transform()
{
mHarness.addAttributes<openvdb::math::Vec3<double>>
({"test1", "test3", "test7"}, {
openvdb::math::Vec3<double>(30.0, 36.0, 42.0),
openvdb::math::Vec3<double>(51.0, 58, 65.0),
openvdb::math::Vec3<double>(51.0, 58, 65.0),
});
mHarness.addAttribute<openvdb::math::Vec4<double>>("test5",
openvdb::math::Vec4<double>(90.0, 100.0, 110.0, 120.0));
mHarness.addAttributes<openvdb::math::Vec3<float>>
({"test2", "test4", "test8"}, {
openvdb::math::Vec3<float>(30.0f, 36.0f, 42.0f),
openvdb::math::Vec3<float>(51.0f, 58.0f, 65.0f),
openvdb::math::Vec3<float>(51.0f, 58.0f, 65.0f),
});
mHarness.addAttribute<openvdb::math::Vec4<float>>("test6",
openvdb::math::Vec4<float>(90.0f, 100.0f, 110.0f, 120.0f));
testFunctionOptions(mHarness, "transform");
}
void
TestStandardFunctions::transpose()
{
mHarness.addAttribute("test1",
openvdb::math::Mat3<double>(
1.0, 4.0, 7.0,
2.0, 5.0, 8.0,
3.0, 6.0, 9.0));
mHarness.addAttribute("test2",
openvdb::math::Mat3<float>(
1.0f, 4.0f, 7.0f,
2.0f, 5.0f, 8.0f,
3.0f, 6.0f, 9.0f));
mHarness.addAttribute("test3",
openvdb::math::Mat4<double>(
1.0, 5.0, 9.0,13.0,
2.0, 6.0,10.0,14.0,
3.0, 7.0,11.0,15.0,
4.0, 8.0,12.0,16.0));
mHarness.addAttribute("test4",
openvdb::math::Mat4<float>(
1.0f, 5.0f, 9.0f,13.0f,
2.0f, 6.0f,10.0f,14.0f,
3.0f, 7.0f,11.0f,15.0f,
4.0f, 8.0f,12.0f,16.0f));
testFunctionOptions(mHarness, "transpose");
}
| 33,322 | C++ | 30.615749 | 135 | 0.605576 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestHarness.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "util.h"
#include <openvdb_ax/compiler/PointExecutable.h>
#include <openvdb_ax/compiler/VolumeExecutable.h>
#include <openvdb/points/PointConversion.h>
namespace unittest_util
{
std::string loadText(const std::string& codeFileName)
{
std::ostringstream sstream;
std::ifstream fs(codeFileName);
if (fs.fail()) {
throw std::runtime_error(std::string("Failed to open ") + std::string(codeFileName));
}
sstream << fs.rdbuf();
return sstream.str();
}
bool wrapExecution(openvdb::points::PointDataGrid& grid,
const std::string& codeFileName,
const std::string * const group,
openvdb::ax::Logger& logger,
const openvdb::ax::CustomData::Ptr& data,
const openvdb::ax::CompilerOptions& opts,
const bool createMissing)
{
using namespace openvdb::ax;
Compiler compiler(opts);
const std::string code = loadText(codeFileName);
ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger);
PointExecutable::Ptr executable = compiler.compile<PointExecutable>(*syntaxTree, logger, data);
if (!executable) return false;
executable->setCreateMissing(createMissing);
if (group) executable->setGroupExecution(*group);
executable->execute(grid);
return true;
}
bool wrapExecution(openvdb::GridPtrVec& grids,
const std::string& codeFileName,
openvdb::ax::Logger& logger,
const openvdb::ax::CustomData::Ptr& data,
const openvdb::ax::CompilerOptions& opts,
const bool createMissing)
{
using namespace openvdb::ax;
Compiler compiler(opts);
const std::string code = loadText(codeFileName);
ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger);
VolumeExecutable::Ptr executable = compiler.compile<VolumeExecutable>(*syntaxTree, logger, data);
if (!executable) return false;
executable->setCreateMissing(createMissing);
executable->setValueIterator(VolumeExecutable::IterType::ON);
executable->execute(grids);
return true;
}
void AXTestHarness::addInputGroups(const std::vector<std::string> &names,
const std::vector<bool> &defaults)
{
for (size_t i = 0; i < names.size(); i++) {
for (auto& grid : mInputPointGrids) {
openvdb::points::appendGroup(grid->tree(), names[i]);
openvdb::points::setGroup(grid->tree(), names[i], defaults[i]);
}
}
}
void AXTestHarness::addExpectedGroups(const std::vector<std::string> &names,
const std::vector<bool> &defaults)
{
for (size_t i = 0; i < names.size(); i++) {
for (auto& grid : mOutputPointGrids) {
openvdb::points::appendGroup(grid->tree(), names[i]);
openvdb::points::setGroup(grid->tree(), names[i], defaults[i]);
}
}
}
bool AXTestHarness::executeCode(const std::string& codeFile,
const std::string* const group,
const bool createMissing)
{
bool success = false;
if (mUsePoints) {
for (auto& grid : mInputPointGrids) {
mLogger.clear();
success = wrapExecution(*grid, codeFile, group, mLogger, mCustomData, mOpts, createMissing);
if (!success) break;
}
}
if (mUseVolumes) {
mLogger.clear();
success = wrapExecution(mInputVolumeGrids, codeFile, mLogger, mCustomData, mOpts, createMissing);
}
return success;
}
template <typename T>
void AXTestHarness::addInputPtAttributes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
for (size_t i = 0; i < names.size(); i++) {
for (auto& grid : mInputPointGrids) {
openvdb::points::appendAttribute<T>(grid->tree(), names[i], values[i]);
}
}
}
template <typename T>
void AXTestHarness::addInputVolumes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
using GridType = typename openvdb::BoolGrid::ValueConverter<T>::Type;
for (size_t i = 0; i < names.size(); i++) {
typename GridType::Ptr grid = GridType::create();
grid->denseFill(mVolumeBounds, values[i], true/*active*/);
grid->setName(names[i]);
mInputVolumeGrids.emplace_back(grid);
}
}
template <typename T>
void AXTestHarness::addExpectedPtAttributes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
for (size_t i = 0; i < names.size(); i++) {
for (auto& grid : mOutputPointGrids) {
openvdb::points::appendAttribute<T>(grid->tree(), names[i], values[i]);
}
}
}
template <typename T>
void AXTestHarness::addExpectedVolumes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
using GridType = typename openvdb::BoolGrid::ValueConverter<T>::Type;
for (size_t i = 0; i < names.size(); i++) {
typename GridType::Ptr grid = GridType::create();
grid->denseFill(mVolumeBounds, values[i], true/*active*/);
grid->setName(names[i] + "_expected");
mOutputVolumeGrids.emplace_back(grid);
}
}
bool AXTestHarness::checkAgainstExpected(std::ostream& sstream)
{
unittest_util::ComparisonSettings settings;
bool success = true;
if (mUsePoints) {
std::stringstream resultStream;
unittest_util::ComparisonResult result(resultStream);
const size_t count = mInputPointGrids.size();
for (size_t i = 0; i < count; ++i) {
const auto& input = mInputPointGrids[i];
const auto& expected = mOutputPointGrids[i];
const bool pass =
unittest_util::compareGrids(result, *expected, *input, settings, nullptr);
if (!pass) sstream << resultStream.str() << std::endl;
success &= pass;
}
}
if (mUseVolumes) {
for (size_t i = 0; i < mInputVolumeGrids.size(); i++) {
std::stringstream resultStream;
unittest_util::ComparisonResult result(resultStream);
const bool volumeSuccess =
unittest_util::compareUntypedGrids(result, *mOutputVolumeGrids[i],
*mInputVolumeGrids[i], settings, nullptr);
success &= volumeSuccess;
if (!volumeSuccess) sstream << resultStream.str() << std::endl;
}
}
return success;
}
void AXTestHarness::testVolumes(const bool enable)
{
mUseVolumes = enable;
}
void AXTestHarness::testPoints(const bool enable)
{
mUsePoints = enable;
}
void AXTestHarness::reset(const openvdb::Index64 ppv, const openvdb::CoordBBox& bounds)
{
using openvdb::points::PointDataGrid;
using openvdb::points::NullCodec;
mInputPointGrids.clear();
mOutputPointGrids.clear();
mInputVolumeGrids.clear();
mOutputVolumeGrids.clear();
openvdb::math::Transform::Ptr transform =
openvdb::math::Transform::createLinearTransform(1.0);
openvdb::MaskGrid::Ptr mask = openvdb::MaskGrid::create();
mask->setTransform(transform);
mask->sparseFill(bounds, true, true);
openvdb::points::PointDataGrid::Ptr points =
openvdb::points::denseUniformPointScatter(*mask, static_cast<float>(ppv));
mask.reset();
mInputPointGrids.emplace_back(points);
mOutputPointGrids.emplace_back(points->deepCopy());
mOutputPointGrids.back()->setName("custom_expected");
mVolumeBounds = bounds;
mLogger.clear();
}
void AXTestHarness::reset()
{
using openvdb::points::PointDataGrid;
using openvdb::points::NullCodec;
mInputPointGrids.clear();
mOutputPointGrids.clear();
mInputVolumeGrids.clear();
mOutputVolumeGrids.clear();
std::vector<openvdb::Vec3d> coordinates =
{openvdb::Vec3d(0.0, 0.0, 0.0),
openvdb::Vec3d(0.0, 0.0, 0.05),
openvdb::Vec3d(0.0, 1.0, 0.0),
openvdb::Vec3d(1.0, 1.0, 0.0)};
openvdb::math::Transform::Ptr transform1 =
openvdb::math::Transform::createLinearTransform(1.0);
openvdb::points::PointDataGrid::Ptr onePointGrid =
openvdb::points::createPointDataGrid<NullCodec, PointDataGrid>
(std::vector<openvdb::Vec3d>{coordinates[0]}, *transform1);
onePointGrid->setName("1_point");
mInputPointGrids.emplace_back(onePointGrid);
mOutputPointGrids.emplace_back(onePointGrid->deepCopy());
mOutputPointGrids.back()->setName("1_point_expected");
openvdb::math::Transform::Ptr transform2 =
openvdb::math::Transform::createLinearTransform(0.1);
openvdb::points::PointDataGrid::Ptr fourPointGrid =
openvdb::points::createPointDataGrid<NullCodec, PointDataGrid>
(coordinates, *transform2);
fourPointGrid->setName("4_points");
mInputPointGrids.emplace_back(fourPointGrid);
mOutputPointGrids.emplace_back(fourPointGrid->deepCopy());
mOutputPointGrids.back()->setName("4_points_expected");
mVolumeBounds = openvdb::CoordBBox({0,0,0}, {0,0,0});
mLogger.clear();
}
template <typename ValueT>
using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type;
void AXTestHarness::resetInputsToZero()
{
for (auto& grid : mInputPointGrids) {
openvdb::tree::LeafManager<openvdb::points::PointDataTree> manager(grid->tree());
manager.foreach([](openvdb::points::PointDataTree::LeafNodeType& leaf, size_t) {
const size_t attrs = leaf.attributeSet().size();
const size_t pidx = leaf.attributeSet().descriptor().find("P");
for (size_t idx = 0; idx < attrs; ++idx) {
if (idx == pidx) continue;
leaf.attributeArray(idx).collapse();
}
});
}
/// @todo: share with volume executable when the move to header files is made
/// for customization of grid types.
using SupportedTypeList = openvdb::TypeList<
ConverterT<double>,
ConverterT<float>,
ConverterT<int64_t>,
ConverterT<int32_t>,
ConverterT<int16_t>,
ConverterT<bool>,
ConverterT<openvdb::math::Vec2<double>>,
ConverterT<openvdb::math::Vec2<float>>,
ConverterT<openvdb::math::Vec2<int32_t>>,
ConverterT<openvdb::math::Vec3<double>>,
ConverterT<openvdb::math::Vec3<float>>,
ConverterT<openvdb::math::Vec3<int32_t>>,
ConverterT<openvdb::math::Vec4<double>>,
ConverterT<openvdb::math::Vec4<float>>,
ConverterT<openvdb::math::Vec4<int32_t>>,
ConverterT<openvdb::math::Mat3<double>>,
ConverterT<openvdb::math::Mat3<float>>,
ConverterT<openvdb::math::Mat4<double>>,
ConverterT<openvdb::math::Mat4<float>>,
ConverterT<std::string>>;
for (auto& grid : mInputVolumeGrids) {
const bool success = grid->apply<SupportedTypeList>([](auto& typed) {
using GridType = typename std::decay<decltype(typed)>::type;
openvdb::tree::LeafManager<typename GridType::TreeType> manager(typed.tree());
manager.foreach([](typename GridType::TreeType::LeafNodeType& leaf, size_t) {
leaf.fill(openvdb::zeroVal<typename GridType::ValueType>());
});
});
if (!success) {
throw std::runtime_error("Unable to reset input grid of an unsupported type");
}
}
}
#define REGISTER_HARNESS_METHODS(T) \
template void AXTestHarness::addInputPtAttributes<T>(const std::vector<std::string>&, const std::vector<T>&); \
template void AXTestHarness::addInputVolumes<T>(const std::vector<std::string>&, const std::vector<T>&); \
template void AXTestHarness::addExpectedPtAttributes<T>(const std::vector<std::string>&, const std::vector<T>&); \
template void AXTestHarness::addExpectedVolumes<T>(const std::vector<std::string>&, const std::vector<T>&);
REGISTER_HARNESS_METHODS(double)
REGISTER_HARNESS_METHODS(float)
REGISTER_HARNESS_METHODS(int64_t)
REGISTER_HARNESS_METHODS(int32_t)
REGISTER_HARNESS_METHODS(int16_t)
REGISTER_HARNESS_METHODS(bool)
REGISTER_HARNESS_METHODS(openvdb::math::Vec2<double>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec2<float>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec2<int32_t>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec3<double>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec3<float>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec3<int32_t>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec4<double>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec4<float>)
REGISTER_HARNESS_METHODS(openvdb::math::Vec4<int32_t>)
REGISTER_HARNESS_METHODS(openvdb::math::Mat3<double>)
REGISTER_HARNESS_METHODS(openvdb::math::Mat3<float>)
REGISTER_HARNESS_METHODS(openvdb::math::Mat4<double>)
REGISTER_HARNESS_METHODS(openvdb::math::Mat4<float>)
REGISTER_HARNESS_METHODS(std::string)
}
| 13,028 | C++ | 34.598361 | 114 | 0.643 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestTernary.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestTernary : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestTernary);
CPPUNIT_TEST(testTernary);
CPPUNIT_TEST(testTernaryVoid);
CPPUNIT_TEST(testTernaryErrors);
CPPUNIT_TEST_SUITE_END();
void testTernary();
void testTernaryVoid();
void testTernaryErrors();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestTernary);
void
TestTernary::testTernary()
{
mHarness.addAttribute<bool>("ternary_test1", true);
mHarness.addAttribute<bool>("ternary_test2", true);
mHarness.addAttribute<int>("ternary_test3", 3);
mHarness.addAttribute<int>("ternary_test4", 1);
mHarness.addAttribute<int>("ternary_test5", 2);
mHarness.addAttribute<float>("ternary_test6", 10.f);
mHarness.addAttribute<double>("ternary_test7", 0.75);
mHarness.addAttribute<openvdb::Vec3i>("ternary_test8", openvdb::Vec3i(1,2,3));
mHarness.addAttribute<openvdb::Vec3d>("ternary_test9", openvdb::Vec3f(4.5,5.5,6.5));
mHarness.addAttribute<int>("ternary_test10", 1);
mHarness.addAttribute<int>("ternary_test11", 123);
mHarness.addAttribute<int>("ternary_test12", 2);
mHarness.addAttribute<int>("ternary_test13", 2);
mHarness.addAttribute<int>("ternary_test14", 123);
mHarness.addAttribute<float>("ternary_test15", 2.f);
mHarness.addAttribute<float>("ternary_test16", 1.5f);
mHarness.addAttribute<openvdb::Vec3i>("ternary_test17", openvdb::Vec3i(1,2,3));
mHarness.addAttribute<openvdb::Vec3i>("ternary_test18", openvdb::Vec3i(4,5,6));
mHarness.addAttribute<std::string>("ternary_test19", "foo");
mHarness.addAttribute<std::string>("ternary_test20", "foo");
mHarness.addAttribute<std::string>("ternary_test21", "bar");
mHarness.addAttribute<openvdb::Vec3f>("ternary_test22", openvdb::Vec3f(1.5f,1.5f,1.5f));
mHarness.addAttribute<openvdb::Vec3f>("ternary_test23", openvdb::Vec3f(1.6f,1.6f,1.6f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("ternary_test24",
openvdb::math::Mat3<double>(1.8,0.0,0.0,
0.0,1.8,0.0,
0.0,0.0,1.8));
mHarness.addAttribute<openvdb::math::Mat3<double>>("ternary_test25",
openvdb::math::Mat3<double>(1.9,0.0,0.0,
0.0,1.9,0.0,
0.0,0.0,1.9));
mHarness.addAttribute<openvdb::math::Mat4<double>>("ternary_test26",
openvdb::math::Mat4<double>(1.8,0.0,0.0,0.0,
0.0,1.8,0.0,0.0,
0.0,0.0,1.8,0.0,
0.0,0.0,0.0,1.8));
mHarness.addAttribute<openvdb::math::Mat4<double>>("ternary_test27",
openvdb::math::Mat4<double>(1.9,0.0,0.0,0.0,
0.0,1.9,0.0,0.0,
0.0,0.0,1.9,0.0,
0.0,0.0,0.0,1.9));
mHarness.addAttribute<openvdb::Vec3f>("ternary_test28", openvdb::Vec3f(1.76f,1.76f,1.76f));
mHarness.addAttribute<openvdb::Vec3f>("ternary_test29", openvdb::Vec3f(1.76f,1.76f,1.76f));
mHarness.addAttribute<float>("ternary_test30", openvdb::Vec3f(1.3f,1.3f,1.3f).length());
mHarness.addAttribute<float>("ternary_test31", openvdb::Vec3f(1.3f,1.3f,1.3f).length());
mHarness.addAttribute<float>("ternary_test32", openvdb::Vec3f(1.5f,2.5f,3.5f).length());
mHarness.addAttribute<float>("ternary_test33", openvdb::Vec3f(1.5f,2.5f,3.5f).length());
mHarness.executeCode("test/snippets/ternary/ternary");
AXTESTS_STANDARD_ASSERT();
}
void
TestTernary::testTernaryVoid()
{
mHarness.testVolumes(false);
mHarness.addExpectedGroups({"notdead"}, {true});
mHarness.executeCode("test/snippets/ternary/ternaryVoid");
AXTESTS_STANDARD_ASSERT();
}
void
TestTernary::testTernaryErrors()
{
const bool success = mHarness.executeCode("test/snippets/ternary/ternaryErrors");
CPPUNIT_ASSERT(!success);
}
| 4,783 | C++ | 47.323232 | 100 | 0.550073 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestExternals.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "CompareGrids.h"
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb_ax/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestExternals : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestExternals);
CPPUNIT_TEST(assignFrom);
CPPUNIT_TEST_SUITE_END();
void assignFrom();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestExternals);
void
TestExternals::assignFrom()
{
const std::string code = R"(
_T1_@test1 = _T1_$ext1;)";
auto generate = [&](const auto& types) {
for (const auto& type : types) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", type);
this->registerTest(repl, "external_assign_from." + type + ".ax");
}
};
generate(std::vector<std::string>{
"bool", "int32", "int64", "float", "double",
"vec2i", "vec2f", "vec2d",
"vec3i", "vec3f", "vec3d",
"vec4i", "vec4f", "vec4d",
"mat3f", "mat3d",
"mat4f", "mat4d",
"string"
});
const std::map<std::string, std::function<void()>> expected = {
{ "bool",
[&](){
mHarness.addAttribute<bool>("test1", true);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<bool>(true).copy());
},
},
{ "int32",
[&](){
mHarness.addAttribute<int32_t>("test1", -2);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<int32_t>(-2).copy());
},
},
{ "int64",
[&](){
mHarness.addAttribute<int64_t>("test1", 3);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<int64_t>(3).copy());
},
},
{ "float",
[&](){
mHarness.addAttribute<float>("test1", 4.5f);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<float>(4.5f).copy());
},
},
{ "double",
[&](){
mHarness.addAttribute<double>("test1", -3);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<double>(-3).copy());
},
},
{ "vec2i",
[&](){
const openvdb::math::Vec2<int32_t> value(5,-6);
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<int32_t>>(value).copy());
},
},
{ "vec2f",
[&](){
const openvdb::math::Vec2<float> value(2.3f,-7.8f);
mHarness.addAttribute<openvdb::math::Vec2<float>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<float>>(value).copy());
},
},
{ "vec2d",
[&](){
const openvdb::math::Vec2<double> value(-1.3,9.8);
mHarness.addAttribute<openvdb::math::Vec2<double>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<double>>(value).copy());
},
},
{ "vec3i",
[&](){
const openvdb::math::Vec3<int32_t> value(-1,3,8);
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<int32_t>>(value).copy());
},
},
{ "vec3f",
[&](){
const openvdb::math::Vec3<float> value(4.3f,-9.0f, 1.1f);
mHarness.addAttribute<openvdb::math::Vec3<float>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<float>>(value).copy());
},
},
{ "vec3d",
[&](){
const openvdb::math::Vec3<double> value(8.2, 5.9, 1.6);
mHarness.addAttribute<openvdb::math::Vec3<double>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<double>>(value).copy());
},
},
{ "vec4i",
[&](){
const openvdb::math::Vec4<int32_t> value(10,1,3,-8);
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<int32_t>>(value).copy());
},
},
{ "vec4f",
[&](){
const openvdb::math::Vec4<float> value(4.4f, 3.3f, -0.1f, 0.3f);
mHarness.addAttribute<openvdb::math::Vec4<float>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<float>>(value).copy());
},
},
{ "vec4d",
[&](){
const openvdb::math::Vec4<double> value(4.5, 5.3, 1.1, 3.3);
mHarness.addAttribute<openvdb::math::Vec4<double>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<double>>(value).copy());
},
},
{ "mat3f",
[&](){
const openvdb::math::Mat3<float> value(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f);
mHarness.addAttribute<openvdb::math::Mat3<float>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat3<float>>(value).copy());
},
},
{ "mat3d",
[&](){
const openvdb::math::Mat3<double> value(6.7f, 2.9f,-1.1f, 3.2f, 2.2f, 0.8f, -5.1f, 9.3f, 2.5f);
mHarness.addAttribute<openvdb::math::Mat3<double>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat3<double>>(value).copy());
},
},
{ "mat4f",
[&](){
const openvdb::math::Mat4<float> value(1.1f,-2.3f,-0.3f, 7.8f, -9.1f,-4.5f, 1.1f, 8.2f, -4.3f, 5.4f, 6.7f,-0.2f, 8.8f, 5.5f, -6.6f, 7.7f);
mHarness.addAttribute<openvdb::math::Mat4<float>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat4<float>>(value).copy());
},
},
{ "mat4d",
[&](){
const openvdb::math::Mat4<double> value(-2.3,0.0,-0.3,9.8, 0.0, 6.5, 3.7, 1.2, -7.8,-0.3,-5.5,3.3, -0.2, 9.1, 0.1,-9.1);
mHarness.addAttribute<openvdb::math::Mat4<double>>("test1", value);
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat4<double>>(value).copy());
},
},
{ "string",
[&](){
mHarness.addAttribute<std::string>("test1", "foo");
mHarness.mCustomData.reset(new openvdb::ax::CustomData());
mHarness.mCustomData->insertData("ext1", openvdb::ax::AXStringMetadata("foo").copy());
},
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("external_assign_from." + expc.first + ".ax");
}
}
| 9,052 | C++ | 41.70283 | 157 | 0.53038 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestHarness.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file test/integration/TestHarness.h
///
/// @authors Francisco Gochez, Nick Avramoussis
///
/// @brief Test harness and base methods
#ifndef OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED
#define OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED
#include "CompareGrids.h"
#include <openvdb_ax/ast/Tokens.h>
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb/points/PointAttribute.h>
#include <openvdb/points/PointScatter.h>
#include <cppunit/TestCase.h>
#include <unordered_map>
extern int sGenerateAX;
namespace unittest_util
{
std::string loadText(const std::string& codeFileName);
bool wrapExecution(openvdb::points::PointDataGrid& grid,
const std::string& codeFileName,
const std::string * const group,
openvdb::ax::Logger& logger,
const openvdb::ax::CustomData::Ptr& data,
const openvdb::ax::CompilerOptions& opts,
const bool createMissing);
bool wrapExecution(openvdb::GridPtrVec& grids,
const std::string& codeFileName,
openvdb::ax::Logger& logger,
const openvdb::ax::CustomData::Ptr& data,
const openvdb::ax::CompilerOptions& opts,
const bool createMissing);
/// @brief Structure for wrapping up most of the existing integration
/// tests with a simple interface
struct AXTestHarness
{
AXTestHarness() :
mInputPointGrids()
, mOutputPointGrids()
, mInputVolumeGrids()
, mOutputVolumeGrids()
, mUseVolumes(true)
, mUsePoints(true)
, mVolumeBounds({0,0,0},{0,0,0})
, mOpts(openvdb::ax::CompilerOptions())
, mCustomData(openvdb::ax::CustomData::create())
, mLogger([](const std::string&) {})
{
reset();
}
void addInputGroups(const std::vector<std::string>& names, const std::vector<bool>& defaults);
void addExpectedGroups(const std::vector<std::string>& names, const std::vector<bool>& defaults);
/// @brief adds attributes to input data set
template <typename T>
void addInputAttributes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
if (mUsePoints) addInputPtAttributes<T>(names, values);
if (mUseVolumes) addInputVolumes(names, values);
}
template <typename T>
void addInputAttribute(const std::string& name, const T& inputVal)
{
addInputAttributes<T>({name}, {inputVal});
}
/// @brief adds attributes to expected output data sets
template <typename T>
void addExpectedAttributes(const std::vector<std::string>& names,
const std::vector<T>& values)
{
if (mUsePoints) addExpectedPtAttributes<T>(names, values);
if (mUseVolumes) addExpectedVolumes<T>(names, values);
}
/// @brief adds attributes to both input and expected data
template <typename T>
void addAttributes(const std::vector<std::string>& names,
const std::vector<T>& inputValues,
const std::vector<T>& expectedValues)
{
if (inputValues.size() != expectedValues.size() ||
inputValues.size() != names.size()) {
throw std::runtime_error("bad unittest setup - input/expected value counts don't match");
}
addInputAttributes(names, inputValues);
addExpectedAttributes(names, expectedValues);
}
/// @brief adds attributes to both input and expected data, with input data set to 0 values
template <typename T>
void addAttributes(const std::vector<std::string>& names,
const std::vector<T>& expectedValues)
{
std::vector<T> zeroVals(expectedValues.size(), openvdb::zeroVal<T>());
addAttributes(names, zeroVals, expectedValues);
}
template <typename T>
void addAttribute(const std::string& name, const T& inVal, const T& expVal)
{
addAttributes<T>({name}, {inVal}, {expVal});
}
template <typename T>
void addAttribute(const std::string& name, const T& expVal)
{
addAttribute<T>(name, openvdb::zeroVal<T>(), expVal);
}
template <typename T>
void addExpectedAttribute(const std::string& name, const T& expVal)
{
addExpectedAttributes<T>({name}, {expVal});
}
/// @brief excecutes a snippet of code contained in a file to the input data sets
bool executeCode(const std::string& codeFile,
const std::string* const group = nullptr,
const bool createMissing = false);
/// @brief rebuilds the input and output data sets to their default harness states. This
/// sets the bounds of volumes to a single voxel, with a single and four point grid
void reset();
/// @brief reset the input data to a set amount of points per voxel within a given bounds
/// @note The bounds is also used to fill the volume data of numerical vdb volumes when
/// calls to addAttribute functions are made, where as points have their positions
/// generated here
void reset(const openvdb::Index64, const openvdb::CoordBBox&);
/// @brief reset all grids without changing the harness data. This has the effect of zeroing
/// out all volume voxel data and point data attributes (except for position) without
/// changing the number of points or voxels
void resetInputsToZero();
/// @brief compares the input and expected point grids and outputs a report of differences to
/// the provided stream
bool checkAgainstExpected(std::ostream& sstream);
/// @brief Toggle whether to execute tests for points or volumes
void testVolumes(const bool);
void testPoints(const bool);
template <typename T>
void addInputPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values);
template <typename T>
void addInputVolumes(const std::vector<std::string>& names, const std::vector<T>& values);
template <typename T>
void addExpectedPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values);
template <typename T>
void addExpectedVolumes(const std::vector<std::string>& names, const std::vector<T>& values);
std::vector<openvdb::points::PointDataGrid::Ptr> mInputPointGrids;
std::vector<openvdb::points::PointDataGrid::Ptr> mOutputPointGrids;
openvdb::GridPtrVec mInputVolumeGrids;
openvdb::GridPtrVec mOutputVolumeGrids;
bool mUseVolumes;
bool mUsePoints;
openvdb::CoordBBox mVolumeBounds;
openvdb::ax::CompilerOptions mOpts;
openvdb::ax::CustomData::Ptr mCustomData;
openvdb::ax::Logger mLogger;
};
class AXTestCase : public CppUnit::TestCase
{
public:
void tearDown() override
{
std::string out;
for (auto& test : mTestFiles) {
if (!test.second) out += test.first + "\n";
}
CPPUNIT_ASSERT_MESSAGE("unused tests left in test case:\n" + out,
out.empty());
}
// @todo make pure
virtual std::string dir() const { return ""; }
/// @brief Register an AX code snippet with this test. If the tests
/// have been launched with -g, the code is also serialized
/// into the test directory
void registerTest(const std::string& code,
const std::string& filename,
const std::ios_base::openmode flags = std::ios_base::out)
{
if (flags & std::ios_base::out) {
CPPUNIT_ASSERT_MESSAGE(
"duplicate test file found during test setup:\n" + filename,
mTestFiles.find(filename) == mTestFiles.end());
mTestFiles[filename] = false;
}
if (flags & std::ios_base::app) {
CPPUNIT_ASSERT_MESSAGE(
"test not found during ofstream append:\n" + filename,
mTestFiles.find(filename) != mTestFiles.end());
}
if (sGenerateAX) {
std::ofstream outfile;
outfile.open(this->dir() + "/" + filename, flags);
outfile << code << std::endl;
outfile.close();
}
}
template <typename ...Args>
void execute(const std::string& filename, Args&&... args)
{
CPPUNIT_ASSERT_MESSAGE(
"test not found during execution:\n" + this->dir() + "/" + filename,
mTestFiles.find(filename) != mTestFiles.end());
mTestFiles[filename] = true; // has been used
// execute
const bool success = mHarness.executeCode(this->dir() + "/" + filename, args...);
CPPUNIT_ASSERT_MESSAGE("error thrown during test: " + filename, success);
//@todo: print error message here
// check
std::stringstream out;
const bool correct = mHarness.checkAgainstExpected(out);
CPPUNIT_ASSERT_MESSAGE(out.str(), correct);
}
protected:
AXTestHarness mHarness;
std::unordered_map<std::string, bool> mTestFiles;
};
} // namespace unittest_util
#define GET_TEST_DIRECTORY() \
std::string(__FILE__).substr(0, std::string(__FILE__).find_last_of('.')); \
#define AXTESTS_STANDARD_ASSERT_HARNESS(harness) \
{ std::stringstream out; \
const bool correct = harness.checkAgainstExpected(out); \
CPPUNIT_ASSERT_MESSAGE(out.str(), correct); }
#define AXTESTS_STANDARD_ASSERT() \
AXTESTS_STANDARD_ASSERT_HARNESS(mHarness);
#endif // OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED
| 9,685 | C | 34.350365 | 102 | 0.633557 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestEmpty.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <openvdb_ax/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestEmpty : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestEmpty);
CPPUNIT_TEST(testEmpty);
CPPUNIT_TEST_SUITE_END();
void testEmpty();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestEmpty);
void
TestEmpty::testEmpty()
{
unittest_util::AXTestHarness harness;
harness.executeCode("test/snippets/empty/empty");
AXTESTS_STANDARD_ASSERT_HARNESS(harness);
}
| 630 | C++ | 18.718749 | 53 | 0.74127 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestString.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "../test/util.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestString : public unittest_util::AXTestCase
{
public:
void setUp() override {
unittest_util::AXTestCase::setUp();
}
CPPUNIT_TEST_SUITE(TestString);
CPPUNIT_TEST(testAssignCompound);
CPPUNIT_TEST(testAssignFromAttributes);
CPPUNIT_TEST(testAssignFromLocals);
CPPUNIT_TEST(testAssignNewOverwrite);
CPPUNIT_TEST(testBinaryConcat);
CPPUNIT_TEST(testDeclare);
CPPUNIT_TEST_SUITE_END();
void testAssignCompound();
void testAssignFromAttributes();
void testAssignFromLocals();
void testAssignNewOverwrite();
void testBinaryConcat();
void testDeclare();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestString);
void
TestString::testAssignCompound()
{
mHarness.addAttributes<std::string>(unittest_util::nameSequence("test", 3),
{"foo", "foobar", "aaaaaaaaaa"});
mHarness.executeCode("test/snippets/string/assignCompound");
AXTESTS_STANDARD_ASSERT();
}
void
TestString::testAssignFromAttributes()
{
mHarness.addInputPtAttributes<std::string>({"string_test1"}, {"test"});
mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6),
{"new value", "test", "new value", "new value", "", ""});
// Volume data needs to exist
mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6),
{"test", "test", "new value", "new value", "", ""});
mHarness.executeCode("test/snippets/string/assignFromAttributes", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestString::testAssignFromLocals()
{
mHarness.addAttributes<std::string>(unittest_util::nameSequence("string_test", 4),
{"test", "test", "new string size", ""});
mHarness.executeCode("test/snippets/string/assignFromLocals");
AXTESTS_STANDARD_ASSERT();
}
void
TestString::testAssignNewOverwrite()
{
mHarness.addExpectedAttributes<std::string>({"string_test1", "string_test2"},
{"next_value", "new_value"});
// Volume data needs to exist
mHarness.addInputVolumes<std::string>({"string_test1", "string_test2"},
{"next_value", "new_value"});
mHarness.executeCode("test/snippets/string/assignNewOverwrite", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestString::testBinaryConcat()
{
mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6),
{"test new value", "test new value", "test new value", "test new value", "", "test new value"});
// Volume data needs to exist
mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6),
{"test new value", "test new value", "test new value", "test new value", "", "test new value"});
mHarness.executeCode("test/snippets/string/binaryConcat", nullptr, true);
AXTESTS_STANDARD_ASSERT();
}
void
TestString::testDeclare()
{
mHarness.addAttribute<std::string>("string_test", "test");
mHarness.executeCode("test/snippets/string/declare");
AXTESTS_STANDARD_ASSERT();
}
| 3,224 | C++ | 30.009615 | 104 | 0.695099 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestArrayUnpack.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "CompareGrids.h"
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb_ax/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestArrayUnpack : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestArrayUnpack);
CPPUNIT_TEST(componentVectorAssignment);
CPPUNIT_TEST(componentMatrixAssignment);
CPPUNIT_TEST_SUITE_END();
void componentVectorAssignment();
void componentMatrixAssignment();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpack);
void
TestArrayUnpack::componentVectorAssignment()
{
const std::string code = R"(
vec2@test1[0] = vec2@test2[1];
vec2@test2[1] = vec2@test1[0];
vec3@test3[1] = vec3@test3[2];
vec3@test4[2] = vec3@test4[0];
vec3@test3[0] = vec3@test4[1];
vec4@test5[0] = vec4@test6[2];
vec4@test5[3] = vec4@test5[1];
vec4@test5[2] = vec4@test6[3];
vec4@test6[1] = vec4@test6[0];
)";
auto generate = [&](const auto& suffixes) {
for (const auto& s : suffixes) {
std::string repl = code;
const std::string type = (s == 'i' ? "int" : (s == 'f' ? "float" : (s == 'd' ? "double" : "")));
CPPUNIT_ASSERT(!type.empty());
unittest_util::replace(repl, "vec2", std::string("vec2").append(1, s));
unittest_util::replace(repl, "vec3", std::string("vec3").append(1, s));
unittest_util::replace(repl, "vec4", std::string("vec4").append(1, s));
this->registerTest(repl, "array_unpack.vec." + type + ".ax");
unittest_util::replace(repl, "[0]", ".x");
unittest_util::replace(repl, "[1]", ".y");
unittest_util::replace(repl, "[2]", ".z");
this->registerTest(repl, "array_unpack.vec." + type + ".xyz" + ".ax");
unittest_util::replace(repl, ".x", ".r");
unittest_util::replace(repl, ".y", ".g");
unittest_util::replace(repl, ".z", ".b");
this->registerTest(repl, "array_unpack.vec." + type + ".rgb" + ".ax");
}
};
generate(std::vector<char>{'i', 'f', 'd'});
const std::map<std::string, std::function<void()>> expected = {
{ "int", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test1", openvdb::math::Vec2<int32_t>( 1, 2), openvdb::math::Vec2<int32_t>( 4,2));
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test2", openvdb::math::Vec2<int32_t>( 3, 4), openvdb::math::Vec2<int32_t>( 3, 4));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test3", openvdb::math::Vec3<int32_t>( 5 ,6, 7), openvdb::math::Vec3<int32_t>( 8 ,7, 7));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test4", openvdb::math::Vec3<int32_t>( 9, 8,-1), openvdb::math::Vec3<int32_t>( 9, 8, 9));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test5", openvdb::math::Vec4<int32_t>(-1,-2,-3,-4), openvdb::math::Vec4<int32_t>(-7,-2,-8,-2));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test6", openvdb::math::Vec4<int32_t>(-5,-6,-7,-8), openvdb::math::Vec4<int32_t>(-5,-5,-7,-8));
}
},
{ "float", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<float>>("test1", openvdb::math::Vec2<float>( 1.2f, 2.7f), openvdb::math::Vec2<float>(4.7f, 2.7f));
mHarness.addAttribute<openvdb::math::Vec2<float>>("test2", openvdb::math::Vec2<float>( 3.2f, 4.7f), openvdb::math::Vec2<float>(3.2f ,4.7f));
mHarness.addAttribute<openvdb::math::Vec3<float>>("test3", openvdb::math::Vec3<float>( 5.2f ,6.7f, 7.4f), openvdb::math::Vec3<float>( 8.7f ,7.4f, 7.4f));
mHarness.addAttribute<openvdb::math::Vec3<float>>("test4", openvdb::math::Vec3<float>( 9.2f, 8.7f,-1.4f), openvdb::math::Vec3<float>( 9.2f, 8.7f, 9.2f));
mHarness.addAttribute<openvdb::math::Vec4<float>>("test5", openvdb::math::Vec4<float>(-1.2f,-2.7f,-3.4f,-4.1f), openvdb::math::Vec4<float>(-7.4f,-2.7f,-8.1f,-2.7f));
mHarness.addAttribute<openvdb::math::Vec4<float>>("test6", openvdb::math::Vec4<float>(-5.2f,-6.7f,-7.4f,-8.1f), openvdb::math::Vec4<float>(-5.2f,-5.2f,-7.4f,-8.1f));
}
},
{ "double", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<double>>("test1", openvdb::math::Vec2<double>( 1.2, 2.7), openvdb::math::Vec2<double>(4.7, 2.7));
mHarness.addAttribute<openvdb::math::Vec2<double>>("test2", openvdb::math::Vec2<double>( 3.2, 4.7), openvdb::math::Vec2<double>(3.2, 4.7));
mHarness.addAttribute<openvdb::math::Vec3<double>>("test3", openvdb::math::Vec3<double>( 5.2 ,6.7, 7.4), openvdb::math::Vec3<double>( 8.7 ,7.4, 7.4));
mHarness.addAttribute<openvdb::math::Vec3<double>>("test4", openvdb::math::Vec3<double>( 9.2, 8.7,-1.4), openvdb::math::Vec3<double>( 9.2, 8.7, 9.2));
mHarness.addAttribute<openvdb::math::Vec4<double>>("test5", openvdb::math::Vec4<double>(-1.2,-2.7,-3.4,-4.1), openvdb::math::Vec4<double>(-7.4,-2.7,-8.1,-2.7));
mHarness.addAttribute<openvdb::math::Vec4<double>>("test6", openvdb::math::Vec4<double>(-5.2,-6.7,-7.4,-8.1), openvdb::math::Vec4<double>(-5.2,-5.2,-7.4,-8.1));
}
},
};
const std::array<std::string, 3> suffixes {{ "", ".xyz", ".rgb" }};
for (const auto& expc : expected) {
for (const auto& suffix : suffixes) {
mHarness.reset();
expc.second.operator()();
this->execute("array_unpack.vec." + expc.first + suffix + ".ax");
}
}
}
void
TestArrayUnpack::componentMatrixAssignment()
{
const std::string code = R"(
mat3@test1[0] = mat3@test2[4];
mat3@test2[1] = mat3@test1[0];
mat3@test1[2] = mat3@test2[5];
mat3@test2[3] = mat3@test1[6];
mat3@test1[4] = mat3@test2[3];
mat3@test2[5] = mat3@test1[1];
mat3@test1[6] = mat3@test2[7];
mat3@test2[7] = mat3@test1[8];
mat3@test1[8] = mat3@test2[2];
mat3@test3[0,0] = mat3@test4[1,1];
mat3@test4[0,1] = mat3@test3[0,0];
mat3@test3[0,2] = mat3@test4[1,2];
mat3@test4[1,0] = mat3@test3[2,0];
mat3@test3[1,1] = mat3@test4[1,0];
mat3@test4[1,2] = mat3@test3[0,1];
mat3@test3[2,0] = mat3@test4[2,1];
mat3@test4[2,1] = mat3@test3[2,2];
mat3@test3[2,2] = mat3@test4[0,2];
mat4@test5[0] = mat4@test6[15];
mat4@test6[1] = mat4@test5[0];
mat4@test5[2] = mat4@test6[11];
mat4@test6[3] = mat4@test5[6];
mat4@test5[4] = mat4@test6[13];
mat4@test6[5] = mat4@test5[1];
mat4@test5[6] = mat4@test6[10];
mat4@test6[7] = mat4@test5[8];
mat4@test5[8] = mat4@test6[2];
mat4@test6[9] = mat4@test5[7];
mat4@test5[10] = mat4@test6[14];
mat4@test6[11] = mat4@test5[3];
mat4@test5[12] = mat4@test6[4];
mat4@test6[13] = mat4@test5[12];
mat4@test5[14] = mat4@test6[5];
mat4@test6[15] = mat4@test5[9];
mat4@test7[0,0] = mat4@test8[3,3];
mat4@test8[0,1] = mat4@test7[0,0];
mat4@test7[0,2] = mat4@test8[2,3];
mat4@test8[0,3] = mat4@test7[1,2];
mat4@test7[1,0] = mat4@test8[3,1];
mat4@test8[1,1] = mat4@test7[0,1];
mat4@test7[1,2] = mat4@test8[2,2];
mat4@test8[1,3] = mat4@test7[2,0];
mat4@test7[2,0] = mat4@test8[0,2];
mat4@test8[2,1] = mat4@test7[1,3];
mat4@test7[2,2] = mat4@test8[3,2];
mat4@test8[2,3] = mat4@test7[0,3];
mat4@test7[3,0] = mat4@test8[1,0];
mat4@test8[3,1] = mat4@test7[3,0];
mat4@test7[3,2] = mat4@test8[1,1];
mat4@test8[3,3] = mat4@test7[2,1];
)";
auto generate = [&](const auto& suffixes) {
for (const auto& s : suffixes) {
std::string repl = code;
unittest_util::replace(repl, "mat3", std::string("mat3").append(1,s));
unittest_util::replace(repl, "mat4", std::string("mat4").append(1,s));
const std::string type = s == 'f' ? "float" : s == 'd' ? "double" : "";
CPPUNIT_ASSERT(!type.empty());
this->registerTest(repl, "array_unpack.mat." + type + ".ax");
}
};
generate(std::vector<char>{'f', 'd'});
const std::map<std::string, std::function<void()>> expected = {
{ "float", [&]() {
mHarness.addAttribute<openvdb::math::Mat3<float>>("test1",
openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in
openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected
mHarness.addAttribute<openvdb::math::Mat3<float>>("test2",
openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f),
openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("test3",
openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in
openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected
mHarness.addAttribute<openvdb::math::Mat3<float>>("test4",
openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f),
openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f));
mHarness.addAttribute<openvdb::math::Mat4<float>>("test5",
openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in
openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected
mHarness.addAttribute<openvdb::math::Mat4<float>>("test6",
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f),
openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f));
mHarness.addAttribute<openvdb::math::Mat4<float>>("test7",
openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in
openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected
mHarness.addAttribute<openvdb::math::Mat4<float>>("test8",
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f),
openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f));
}
},
{ "double", [&]() {
mHarness.addAttribute<openvdb::math::Mat3<double>>("test1",
openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in
openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected
mHarness.addAttribute<openvdb::math::Mat3<double>>("test2",
openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2),
openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2));
mHarness.addAttribute<openvdb::math::Mat3<double>>("test3",
openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in
openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected
mHarness.addAttribute<openvdb::math::Mat3<double>>("test4",
openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2),
openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2));
mHarness.addAttribute<openvdb::math::Mat4<double>>("test5",
openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in
openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected
mHarness.addAttribute<openvdb::math::Mat4<double>>("test6",
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7),
openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3));
mHarness.addAttribute<openvdb::math::Mat4<double>>("test7",
openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in
openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected
mHarness.addAttribute<openvdb::math::Mat4<double>>("test8",
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7),
openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3));
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("array_unpack.mat." + expc.first + ".ax");
}
}
| 13,765 | C++ | 52.773437 | 181 | 0.537523 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestUnary.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "util.h"
#include <cppunit/extensions/HelperMacros.h>
class TestUnary : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestUnary);
CPPUNIT_TEST(testBitwiseNot);
CPPUNIT_TEST(testNegate);
CPPUNIT_TEST(testNot);
CPPUNIT_TEST(testUnaryVector);
CPPUNIT_TEST_SUITE_END();
void testBitwiseNot();
void testNegate();
void testNot();
void testUnaryVector();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestUnary);
void
TestUnary::testBitwiseNot()
{
mHarness.addAttributes<int>({"int_test", "int_test2"}, {-9, -8});
mHarness.executeCode("test/snippets/unary/unaryBitwiseNot");
AXTESTS_STANDARD_ASSERT();
}
void
TestUnary::testNegate()
{
mHarness.addAttribute<int>("int_test", -3);
mHarness.addAttribute<float>("float_test", -5.5f);
mHarness.executeCode("test/snippets/unary/unaryNegate");
AXTESTS_STANDARD_ASSERT();
}
void
TestUnary::testNot()
{
mHarness.addAttributes<bool>({"bool_test", "bool_test2"}, {false, true});
mHarness.executeCode("test/snippets/unary/unaryNot");
AXTESTS_STANDARD_ASSERT();
}
void
TestUnary::testUnaryVector()
{
// vec3
mHarness.addAttributes<openvdb::math::Vec3<int32_t>>
(unittest_util::nameSequence("v3i", 4), {
openvdb::math::Vec3<int32_t>(0, 1,-1),
openvdb::math::Vec3<int32_t>(0,-1, 1),
openvdb::math::Vec3<int32_t>(-1,-2,0),
openvdb::math::Vec3<int32_t>(1, 0, 0)
});
mHarness.addAttributes<openvdb::math::Vec3<float>>
(unittest_util::nameSequence("v3f", 2), {
openvdb::math::Vec3<float>(0.0f, 1.1f,-1.1f),
openvdb::math::Vec3<float>(0.0f,-1.1f, 1.1f),
});
mHarness.addAttributes<openvdb::math::Vec3<double>>
(unittest_util::nameSequence("v3d", 2), {
openvdb::math::Vec3<double>(0.0, 1.1,-1.1),
openvdb::math::Vec3<double>(0.0,-1.1, 1.1),
});
// vec4
mHarness.addAttributes<openvdb::math::Vec4<int32_t>>
(unittest_util::nameSequence("v4i", 4), {
openvdb::math::Vec4<int32_t>(0, 1,-1, 2),
openvdb::math::Vec4<int32_t>(0,-1, 1, -2),
openvdb::math::Vec4<int32_t>(-1,-2,0,-3),
openvdb::math::Vec4<int32_t>(1, 0, 0, 0)
});
mHarness.addAttributes<openvdb::math::Vec4<float>>
(unittest_util::nameSequence("v4f", 2), {
openvdb::math::Vec4<float>(0.0f, 1.1f,-1.1f, 2.1f),
openvdb::math::Vec4<float>(0.0f,-1.1f, 1.1f, -2.1f)
});
mHarness.addAttributes<openvdb::math::Vec4<double>>
(unittest_util::nameSequence("v4d", 2), {
openvdb::math::Vec4<double>(0.0, 1.1,-1.1, 2.1),
openvdb::math::Vec4<double>(0.0,-1.1, 1.1, -2.1)
});
mHarness.executeCode("test/snippets/unary/unaryVector");
AXTESTS_STANDARD_ASSERT();
}
| 2,983 | C++ | 25.882883 | 77 | 0.60409 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestLoop.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestLoop : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestLoop);
CPPUNIT_TEST(testLoopForLoop);
CPPUNIT_TEST(testLoopWhileLoop);
CPPUNIT_TEST(testLoopDoWhileLoop);
CPPUNIT_TEST(testLoopOverflow);
CPPUNIT_TEST(testLoopErrors);
CPPUNIT_TEST_SUITE_END();
void testLoopForLoop();
void testLoopWhileLoop();
void testLoopDoWhileLoop();
void testLoopOverflow();
void testLoopErrors();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestLoop);
void
TestLoop::testLoopForLoop()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test1", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test2", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test3", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test15", openvdb::Vec3f(0.0,0.0,0.0));
mHarness.addAttribute<openvdb::math::Mat3s>("loop_test18",
openvdb::math::Mat3s(1.0,2.0,3.0, 4.0,5.0,6.0, 7.0,8.0,9.0));
mHarness.addAttribute<int32_t>("loop_test22", 3);
mHarness.addAttribute<int32_t>("loop_test23", 4);
mHarness.addAttribute<int32_t>("loop_test25", 1);
mHarness.addAttribute<int32_t>("loop_test27", 14);
mHarness.addAttribute<int32_t>("loop_test30", 19);
mHarness.executeCode("test/snippets/loop/forLoop");
AXTESTS_STANDARD_ASSERT();
}
void
TestLoop::testLoopWhileLoop()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test9", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test16", openvdb::Vec3f(0.0,0.0,0.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test28", openvdb::Vec3f(0.0,0.0,0.0));
mHarness.addAttribute<int32_t>("loop_test31", 2);
mHarness.executeCode("test/snippets/loop/whileLoop");
AXTESTS_STANDARD_ASSERT();
}
void
TestLoop::testLoopDoWhileLoop()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test12", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test17", openvdb::Vec3f(1.0,0.0,0.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test29", openvdb::Vec3f(1.0,0.0,0.0));
mHarness.addAttribute<int32_t>("loop_test32", 2);
mHarness.executeCode("test/snippets/loop/doWhileLoop");
AXTESTS_STANDARD_ASSERT();
}
void
TestLoop::testLoopOverflow()
{
// Disable all optimizations to force the loop to not remove the interior
// allocation. The loop should generate its allocas in the function prologue
// to avoid stack overflow
openvdb::ax::CompilerOptions opts;
opts.mOptLevel = openvdb::ax::CompilerOptions::OptLevel::NONE;
mHarness.mOpts = opts;
mHarness.executeCode("test/snippets/loop/loopOverflow");
}
void
TestLoop::testLoopErrors()
{
const bool success = mHarness.executeCode("test/snippets/loop/loopErrors");
CPPUNIT_ASSERT(!success);
}
| 3,035 | C++ | 32 | 86 | 0.707743 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestConditional.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestConditional : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestConditional);
CPPUNIT_TEST(testConditionalIfWithinElse);
CPPUNIT_TEST(testConditionalScopingStatement);
CPPUNIT_TEST(testConditionalSimpleStatement);
CPPUNIT_TEST(testConditionalSimpleElseIf);
CPPUNIT_TEST(testConditionalErrors);
CPPUNIT_TEST_SUITE_END();
void testConditionalIfWithinElse();
void testConditionalSimpleStatement();
void testConditionalScopingStatement();
void testConditionalSimpleElseIf();
void testConditionalErrors();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestConditional);
void
TestConditional::testConditionalIfWithinElse()
{
mHarness.addAttribute<bool>("bool_test", true);
mHarness.executeCode("test/snippets/conditional/conditionalIfWithinElse");
AXTESTS_STANDARD_ASSERT();
}
void
TestConditional::testConditionalSimpleStatement()
{
mHarness.addAttribute<bool>("bool_test", true);
mHarness.addAttribute<float>("float_test", 1.0f);
mHarness.executeCode("test/snippets/conditional/conditionalSimpleStatement");
AXTESTS_STANDARD_ASSERT();
}
void
TestConditional::testConditionalScopingStatement()
{
mHarness.addAttribute<int32_t>("int_test", 1);
mHarness.executeCode("test/snippets/conditional/conditionalScopingStatement");
AXTESTS_STANDARD_ASSERT();
}
void
TestConditional::testConditionalSimpleElseIf()
{
mHarness.addAttribute("bool_test", true);
mHarness.addAttribute("int_test", 2);
mHarness.executeCode("test/snippets/conditional/conditionalSimpleElseIf");
AXTESTS_STANDARD_ASSERT();
}
void
TestConditional::testConditionalErrors()
{
const bool success = mHarness.executeCode("test/snippets/conditional/conditionalErrors");
CPPUNIT_ASSERT(!success);
}
| 1,984 | C++ | 24.448718 | 93 | 0.767641 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/CompareGrids.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file test/integration/CompareGrids.h
///
/// @authors Francisco Gochez, Nick Avramoussis
///
/// @brief Functions for comparing entire VDB grids and generating
/// reports on their differences
///
#ifndef OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED
#define OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED
#include <openvdb/openvdb.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/tree/LeafManager.h>
#include <openvdb/tools/Prune.h>
namespace unittest_util
{
struct ComparisonSettings
{
bool mCheckTransforms = true; // Check grid transforms
bool mCheckTopologyStructure = true; // Checks node (voxel/leaf/tile) layout
bool mCheckActiveStates = true; // Checks voxel active states match
bool mCheckBufferValues = true; // Checks voxel buffer values match
bool mCheckDescriptors = true; // Check points leaf descriptors
bool mCheckArrayValues = true; // Checks attribute array sizes and values
bool mCheckArrayFlags = true; // Checks attribute array flags
};
/// @brief The results collected from compareGrids()
///
struct ComparisonResult
{
ComparisonResult(std::ostream& os = std::cout)
: mOs(os)
, mDifferingTopology(openvdb::MaskGrid::create())
, mDifferingValues(openvdb::MaskGrid::create()) {}
std::ostream& mOs;
openvdb::MaskGrid::Ptr mDifferingTopology; // Always empty if mCheckActiveStates is false
openvdb::MaskGrid::Ptr mDifferingValues; // Always empty if mCheckBufferValues is false
// or if mCheckBufferValues and mCheckArrayValues
// is false for point data grids
};
template <typename GridType>
bool compareGrids(ComparisonResult& resultData,
const GridType& firstGrid,
const GridType& secondGrid,
const ComparisonSettings& settings,
const openvdb::MaskGrid::ConstPtr maskGrid,
const typename GridType::ValueType tolerance =
openvdb::zeroVal<typename GridType::ValueType>());
bool compareUntypedGrids(ComparisonResult& resultData,
const openvdb::GridBase& firstGrid,
const openvdb::GridBase& secondGrid,
const ComparisonSettings& settings,
const openvdb::MaskGrid::ConstPtr maskGrid);
} // namespace unittest_util
#endif // OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED
| 2,627 | C | 36.014084 | 96 | 0.660069 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestAssign.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "CompareGrids.h"
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb_ax/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
// Configuration values for assignment code
using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>;
static const ConfigMap integral = {
{ "bool", { { "_l1_", "true" }, { "_l2_", "false" } } },
{ "int32", { { "_l1_", "2" }, { "_l2_", "3" } } },
{ "int64", { { "_l1_", "2l" }, { "_l2_", "3l" } } }
};
static const ConfigMap floating = {
{ "float", { { "_l1_", "1.1f" }, { "_l2_", "2.3f" } } },
{ "double", { { "_l1_", "1.1" }, { "_l2_", "2.3" } } }
};
static const ConfigMap vec2 = {
{ "vec2i", { { "_l1_", "{1, 2}" }, { "_l2_", "{3, 4}" } } },
{ "vec2f", { { "_l1_", "{1.1f, 2.3f}" }, { "_l2_", "{4.1f, 5.3f}" } } },
{ "vec2d", { { "_l1_", "{1.1, 2.3}" }, { "_l2_", "{4.1, 5.3}" } } }
};
static const ConfigMap vec3 = {
{ "vec3i", { { "_l1_", "{1, 2, 3}" }, { "_l2_", "{4, 5, 6}" } } },
{ "vec3f", { { "_l1_", "{1.1f, 2.3f, 4.3f}" }, { "_l2_", "{4.1f, 5.3f, 6.3f}" } } },
{ "vec3d", { { "_l1_", "{1.1, 2.3 , 4.3}" }, { "_l2_", "{4.1, 5.3, 6.3}" } } }
};
static const ConfigMap vec4 = {
{ "vec4i", { { "_l1_", "{1, 2, 3, 4}" }, { "_l2_", "{5, 6, 7, 8}" } } },
{ "vec4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_l2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } },
{ "vec4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_l2_", "{5.1, 6.3, 7.3, 8.4}" } } }
};
static const ConfigMap mat3 = {
{ "mat3f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" },
{ "_l2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } }
},
{ "mat3d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" },
{ "_l2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } }
}
};
static const ConfigMap mat4 = {
{ "mat4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" },
{ "_l2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } }
},
{ "mat4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" },
{ "_l2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } }
}
};
static const ConfigMap string = {
{ "string", { { "_l1_", "\"foo\"" }, { "_l2_", "\"bar\"" } } }
};
//
class TestAssign : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestAssign);
CPPUNIT_TEST(directAssignment);
CPPUNIT_TEST(compoundIntegralAssignment);
CPPUNIT_TEST(compoundFloatingAssignment);
CPPUNIT_TEST(compoundVectorAssignment);
CPPUNIT_TEST(compoundMatrixAssignment);
CPPUNIT_TEST(compoundStringAssignment);
CPPUNIT_TEST(implicitScalarAssignment);
CPPUNIT_TEST(implicitContainerAssignment);
CPPUNIT_TEST(implicitContainerScalarAssignment);
CPPUNIT_TEST(scopedAssign);
CPPUNIT_TEST_SUITE_END();
void directAssignment();
void compoundIntegralAssignment();
void compoundFloatingAssignment();
void compoundVectorAssignment();
void compoundMatrixAssignment();
void compoundStringAssignment();
void implicitScalarAssignment();
void implicitContainerAssignment();
void implicitContainerScalarAssignment();
void scopedAssign();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAssign);
void
TestAssign::directAssignment()
{
const std::string code = R"(
_T1_@test1 = _l1_;
_T1_ local1 = _l1_;
_T1_@test2 = local1;
_T1_@test3 =
_T1_@test4 =
_T1_@test2;
_T1_ local3,
local2 = _l2_;
_T1_@test5 =
local3 =
local2;
_T1_@test6 = _l2_,
_T1_@test7 = _l1_;
_T1_@test8 = _l2_;
_T1_@test8 = _l1_;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign." + config.first + ".ax");
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
generate(string);
const auto names = unittest_util::nameSequence("test", 8);
const std::map<std::string, std::function<void()>> expected = {
{ "bool",
[&](){ mHarness.addAttributes<bool>(names,
{ true, true, true, true, false, false, true, true });
},
},
{ "int32",
[&](){ mHarness.addAttributes<int32_t>(names,
{ 2, 2, 2, 2, 3, 3, 2, 2 });
},
},
{ "int64",
[&](){ mHarness.addAttributes<int64_t>(names,
{ 2, 2, 2, 2, 3, 3, 2, 2 });
},
},
{ "float",
[&](){ mHarness.addAttributes<float>(names,
{ 1.1f, 1.1f, 1.1f, 1.1f, 2.3f, 2.3f, 1.1f, 1.1f });
},
},
{ "double",
[&](){ mHarness.addAttributes<double>(names,
{ 1.1, 1.1, 1.1, 1.1, 2.3, 2.3, 1.1, 1.1 });
},
},
{ "vec2i",
[&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names,
{ openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(3,4),
openvdb::math::Vec2<int32_t>(3,4),
openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(1,2)
});
},
},
{ "vec2f",
[&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names,
{ openvdb::math::Vec2<float>(1.1f, 2.3f),
openvdb::math::Vec2<float>(1.1f, 2.3f),
openvdb::math::Vec2<float>(1.1f, 2.3f),
openvdb::math::Vec2<float>(1.1f, 2.3f),
openvdb::math::Vec2<float>(4.1f, 5.3f),
openvdb::math::Vec2<float>(4.1f, 5.3f),
openvdb::math::Vec2<float>(1.1f, 2.3f),
openvdb::math::Vec2<float>(1.1f, 2.3f)
});
},
},
{ "vec2d",
[&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names,
{ openvdb::math::Vec2<double>(1.1, 2.3),
openvdb::math::Vec2<double>(1.1, 2.3),
openvdb::math::Vec2<double>(1.1, 2.3),
openvdb::math::Vec2<double>(1.1, 2.3),
openvdb::math::Vec2<double>(4.1, 5.3),
openvdb::math::Vec2<double>(4.1, 5.3),
openvdb::math::Vec2<double>(1.1, 2.3),
openvdb::math::Vec2<double>(1.1, 2.3)
});
},
},
{ "vec3i",
[&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names,
{ openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(4,5,6),
openvdb::math::Vec3<int32_t>(4,5,6),
openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(1,2,3)
});
},
},
{ "vec3f",
[&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names,
{ openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f),
openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f),
openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f)
});
},
},
{ "vec3d",
[&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names,
{ openvdb::math::Vec3<double>(1.1, 2.3, 4.3),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3),
openvdb::math::Vec3<double>(4.1, 5.3, 6.3),
openvdb::math::Vec3<double>(4.1, 5.3, 6.3),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3)
});
},
},
{ "vec4i",
[&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names,
{ openvdb::math::Vec4<int32_t>(1, 2, 3, 4),
openvdb::math::Vec4<int32_t>(1, 2, 3, 4),
openvdb::math::Vec4<int32_t>(1, 2, 3, 4),
openvdb::math::Vec4<int32_t>(1, 2, 3, 4),
openvdb::math::Vec4<int32_t>(5, 6, 7, 8),
openvdb::math::Vec4<int32_t>(5, 6, 7, 8),
openvdb::math::Vec4<int32_t>(1, 2, 3, 4),
openvdb::math::Vec4<int32_t>(1, 2, 3, 4)
});
},
},
{ "vec4f",
[&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names,
{ openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f),
openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f)
});
},
},
{ "vec4d",
[&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names,
{ openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4),
openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4),
openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4)
});
},
},
{ "mat3f",
[&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names,
{ openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f),
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f),
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f),
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f),
openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f),
openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f),
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f),
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f)
});
},
},
{ "mat3d",
[&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names,
{ openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2),
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2),
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2),
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2),
openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2),
openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2),
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2),
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2)
});
},
},
{ "mat4f",
[&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names,
{ openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f),
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f),
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f),
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f),
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f),
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f),
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f),
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f)
});
},
},
{ "mat4d",
[&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names,
{ openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9),
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9),
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9),
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9),
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7),
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7),
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9),
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9)
});
},
},
{ "string",
[&](){ mHarness.addAttributes<std::string>(names,
{ "foo", "foo", "foo", "foo", "bar", "bar", "foo", "foo" });
},
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("assign." + expc.first + ".ax");
}
}
void
TestAssign::compoundIntegralAssignment()
{
const std::string code = R"(
_T1_@test1 += _l1_;
_T1_@test2 -= _l1_;
_T1_@test3 *= _l1_;
_T1_@test4 /= _l1_;
_T1_@test5 %= _l1_;
_T1_@test6 <<= _l1_;
_T1_@test7 >>= _l1_;
_T1_@test8 &= _l1_;
_T1_@test9 ^= _l1_;
_T1_@test10 |= _l1_;
_T1_ local1 = _l1_,
local2 = _l2_;
local1 += local2;
_T1_@test11 = local1;
_T1_@test12 += _T1_@test13;
_T1_@test14 += local2;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign_compound." + config.first + ".ax");
}
};
generate(integral);
const auto names = unittest_util::nameSequence("test", 14);
const std::map<std::string, std::vector<std::function<void()>>> expected = {
{ "bool", {
[&](){ mHarness.addAttributes<bool>(names,
{ true, true, false, false, false, false, false, false, true, true, true, false, false, false });
},
[&](){ mHarness.addAttributes<bool>(names,
{ true, true, true, true, true, true, true, true, true, true, false, true, true, true }, // in
{ true, false, true, true, false, true, false, true, false, true, true, true, true, true }); // expected
},
}
},
{ "int32", {
[&](){ mHarness.addAttributes<int32_t>(names,
{ 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 });
},
[&](){ mHarness.addAttributes<int32_t>(names,
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in
{ 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected
},
}
},
{ "int64", {
[&](){ mHarness.addAttributes<int64_t>(names,
{ 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 });
},
[&](){ mHarness.addAttributes<int64_t>(names,
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in
{ 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected
},
}
}
};
for (const auto& expc : expected) {
for (const auto& test : expc.second) {
mHarness.reset();
test.operator()();
this->execute("assign_compound." + expc.first + ".ax");
}
}
}
void
TestAssign::compoundFloatingAssignment()
{
const std::string code = R"(
_T1_@test1 += _l1_;
_T1_@test2 -= _l1_;
_T1_@test3 *= _l1_;
_T1_@test4 /= _l1_;
_T1_@test5 %= _l1_;
_T1_ local1 = _l1_,
local2 = _l2_;
local1 += local2;
_T1_@test6 = local1;
_T1_@test7 += _T1_@test8;
_T1_@test9 += local2;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign_compound." + config.first + ".ax");
}
};
generate(floating);
const auto names = unittest_util::nameSequence("test", 9);
const std::map<std::string, std::vector<std::function<void()>>> expected = {
{ "float", {
[&](){ mHarness.addAttributes<float>(names,
{ 1.1f, -1.1f, 0.0f, 0.0f, 0.0f, (1.1f+2.3f), 0.0f, 0.0f, 2.3f });
},
[&](){ mHarness.addAttributes<float>(names,
{ 1.1f, 2.3f, 4.5f, 6.7f, 8.9f, -1.1f, -2.3f, -4.5f, 6.1f }, // in
{ (1.1f+1.1f), (2.3f-1.1f), (4.5f*1.1f), (6.7f/1.1f),
std::fmod(8.9f,1.1f),
(1.1f+2.3f), (-2.3f+-4.5f), (-4.5f), (6.1f+2.3f) }); // expected
}
}
},
{ "double", {
[&](){ mHarness.addAttributes<double>(names,
{ 1.1, -1.1, 0.0, 0.0, 0.0, (1.1+2.3), 0.0, 0.0, 2.3 });
},
[&](){ mHarness.addAttributes<double>(names,
{ 1.1, 2.3, 4.5, 6.7, 8.9, -1.1, -2.3, -4.5, 6.1 }, // in
{ (1.1+1.1), (2.3-1.1), (4.5*1.1), (6.7/1.1),
std::fmod(8.9,1.1),
(1.1+2.3), (-2.3+-4.5), (-4.5), (6.1+2.3) }); // expected
}
}
},
};
for (const auto& expc : expected) {
for (const auto& test : expc.second) {
mHarness.reset();
test.operator()();
this->execute("assign_compound." + expc.first + ".ax");
}
}
}
void
TestAssign::compoundVectorAssignment()
{
const std::string code = R"(
_T1_@test1 += _l1_;
_T1_@test2 -= _l1_;
_T1_@test3 *= _l1_;
_T1_@test4 /= _l1_;
_T1_@test5 %= _l1_;
_T1_ local1 = _l1_,
local2 = _l2_;
local1 += local2;
_T1_@test6 = local1;
_T1_@test7 += _T1_@test8;
_T1_@test9 += local2;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign_compound." + config.first + ".ax");
}
};
generate(vec2);
generate(vec3);
generate(vec4);
const auto names = unittest_util::nameSequence("test", 9);
const std::map<std::string, std::vector<std::function<void()>>> expected = {
{ "vec2i", {
[&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names,
{ openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(-1,-2),
openvdb::math::Vec2<int32_t>(0,0),
openvdb::math::Vec2<int32_t>(0,0),
openvdb::math::Vec2<int32_t>(0,0),
openvdb::math::Vec2<int32_t>(4,6),
openvdb::math::Vec2<int32_t>(0,0),
openvdb::math::Vec2<int32_t>(0,0),
openvdb::math::Vec2<int32_t>(3,4) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names,
{ openvdb::math::Vec2<int32_t>(1,2),
openvdb::math::Vec2<int32_t>(3,4),
openvdb::math::Vec2<int32_t>(5,6),
openvdb::math::Vec2<int32_t>(7,8),
openvdb::math::Vec2<int32_t>(3,9),
openvdb::math::Vec2<int32_t>(9,-1),
openvdb::math::Vec2<int32_t>(-2,-3),
openvdb::math::Vec2<int32_t>(-4,-5),
openvdb::math::Vec2<int32_t>(-6,-7) }, // in
{ openvdb::math::Vec2<int32_t>(2,4),
openvdb::math::Vec2<int32_t>(2,2),
openvdb::math::Vec2<int32_t>(5,12),
openvdb::math::Vec2<int32_t>(7,4),
openvdb::math::Vec2<int32_t>(0,1),
openvdb::math::Vec2<int32_t>(4,6),
openvdb::math::Vec2<int32_t>(-6,-8),
openvdb::math::Vec2<int32_t>(-4,-5),
openvdb::math::Vec2<int32_t>(-3,-3) }); // expected
}
}
},
{ "vec2f", {
[&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names,
{ openvdb::math::Vec2<float>(1.1f,2.3f),
openvdb::math::Vec2<float>(-1.1f,-2.3f),
openvdb::math::Vec2<float>(0.0f,0.0f),
openvdb::math::Vec2<float>(0.0f,0.0f),
openvdb::math::Vec2<float>(0.0f,0.0f),
openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f),
openvdb::math::Vec2<float>(0.0f,0.0f),
openvdb::math::Vec2<float>(0.0f,0.0f),
openvdb::math::Vec2<float>(4.1f,5.3f) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names,
{ openvdb::math::Vec2<float>(1.1f,2.2f),
openvdb::math::Vec2<float>(3.3f,4.4f),
openvdb::math::Vec2<float>(5.5f,6.6f),
openvdb::math::Vec2<float>(7.7f,8.8f),
openvdb::math::Vec2<float>(2.3f,5.5f),
openvdb::math::Vec2<float>(9.9f,-1.1f),
openvdb::math::Vec2<float>(-2.2f,-3.3f),
openvdb::math::Vec2<float>(-4.3f,-5.5f),
openvdb::math::Vec2<float>(-6.1f,-8.2f) }, // in
{ openvdb::math::Vec2<float>(1.1f,2.2f) + openvdb::math::Vec2<float>(1.1f,2.3f),
openvdb::math::Vec2<float>(3.3f,4.4f) - openvdb::math::Vec2<float>(1.1f,2.3f),
openvdb::math::Vec2<float>(5.5f,6.6f) * openvdb::math::Vec2<float>(1.1f,2.3f),
openvdb::math::Vec2<float>(7.7f,8.8f) / openvdb::math::Vec2<float>(1.1f,2.3f),
openvdb::math::Vec2<float>(std::fmod(2.3f, 1.1f), std::fmod(5.5f, 2.3f)),
openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f),
openvdb::math::Vec2<float>(-2.2f,-3.3f) + openvdb::math::Vec2<float>(-4.3f,-5.5f),
openvdb::math::Vec2<float>(-4.3f,-5.5f),
openvdb::math::Vec2<float>(-6.1f,-8.2f) + openvdb::math::Vec2<float>(4.1f,5.3f)
}); // expected
}
}
},
{ "vec2d", {
[&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names,
{ openvdb::math::Vec2<double>(1.1,2.3),
openvdb::math::Vec2<double>(-1.1,-2.3),
openvdb::math::Vec2<double>(0.0,0.0),
openvdb::math::Vec2<double>(0.0,0.0),
openvdb::math::Vec2<double>(0.0,0.0),
openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3),
openvdb::math::Vec2<double>(0.0,0.0),
openvdb::math::Vec2<double>(0.0,0.0),
openvdb::math::Vec2<double>(4.1,5.3) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names,
{ openvdb::math::Vec2<double>(1.1,2.2),
openvdb::math::Vec2<double>(3.3,4.4),
openvdb::math::Vec2<double>(5.5,6.6),
openvdb::math::Vec2<double>(7.7,8.8),
openvdb::math::Vec2<double>(2.3,5.5),
openvdb::math::Vec2<double>(9.9,-1.1),
openvdb::math::Vec2<double>(-2.2,-3.3),
openvdb::math::Vec2<double>(-4.3,-5.5),
openvdb::math::Vec2<double>(-6.1,-8.2) }, // in
{ openvdb::math::Vec2<double>(1.1,2.2) + openvdb::math::Vec2<double>(1.1,2.3),
openvdb::math::Vec2<double>(3.3,4.4) - openvdb::math::Vec2<double>(1.1,2.3),
openvdb::math::Vec2<double>(5.5,6.6) * openvdb::math::Vec2<double>(1.1,2.3),
openvdb::math::Vec2<double>(7.7,8.8) / openvdb::math::Vec2<double>(1.1,2.3),
openvdb::math::Vec2<double>(std::fmod(2.3, 1.1), std::fmod(5.5, 2.3)),
openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3),
openvdb::math::Vec2<double>(-2.2,-3.3) + openvdb::math::Vec2<double>(-4.3,-5.5),
openvdb::math::Vec2<double>(-4.3,-5.5),
openvdb::math::Vec2<double>(-6.1,-8.2) + openvdb::math::Vec2<double>(4.1,5.3)
}); // expected
}
}
},
{ "vec3i", {
[&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names,
{ openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(-1,-2,-3),
openvdb::math::Vec3<int32_t>(0,0,0),
openvdb::math::Vec3<int32_t>(0,0,0),
openvdb::math::Vec3<int32_t>(0,0,0),
openvdb::math::Vec3<int32_t>(5,7,9),
openvdb::math::Vec3<int32_t>(0,0,0),
openvdb::math::Vec3<int32_t>(0,0,0),
openvdb::math::Vec3<int32_t>(4,5,6) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names,
{ openvdb::math::Vec3<int32_t>(1,2,3),
openvdb::math::Vec3<int32_t>(4,5,6),
openvdb::math::Vec3<int32_t>(7,8,9),
openvdb::math::Vec3<int32_t>(-1,-2,-3),
openvdb::math::Vec3<int32_t>(4,-5,6),
openvdb::math::Vec3<int32_t>(5,7,9),
openvdb::math::Vec3<int32_t>(-7,-8,-9),
openvdb::math::Vec3<int32_t>(-1,2,-3),
openvdb::math::Vec3<int32_t>(-4,5,-6) }, // in
{ openvdb::math::Vec3<int32_t>(2,4,6),
openvdb::math::Vec3<int32_t>(3,3,3),
openvdb::math::Vec3<int32_t>(7,16,27),
openvdb::math::Vec3<int32_t>(-1,-1,-1),
openvdb::math::Vec3<int32_t>(0,1,0),
openvdb::math::Vec3<int32_t>(5,7,9),
openvdb::math::Vec3<int32_t>(-8,-6,-12),
openvdb::math::Vec3<int32_t>(-1,2,-3),
openvdb::math::Vec3<int32_t>(0,10,0) }); // expected
}
}
},
{ "vec3f", {
[&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names,
{ openvdb::math::Vec3<float>(1.1f,2.3f,4.3f),
openvdb::math::Vec3<float>(-1.1f,-2.3f,-4.3f),
openvdb::math::Vec3<float>(0.0f,0.0f,0.0f),
openvdb::math::Vec3<float>(0.0f,0.0f,0.0f),
openvdb::math::Vec3<float>(0.0f,0.0f,0.0f),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f),
openvdb::math::Vec3<float>(0.0f,0.0f,0.0f),
openvdb::math::Vec3<float>(0.0f,0.0f,0.0f),
openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names,
{ openvdb::math::Vec3<float>(1.1f,2.2f,3.3f),
openvdb::math::Vec3<float>(3.3f,4.4f,5.5f),
openvdb::math::Vec3<float>(5.5f,6.6f,7.7f),
openvdb::math::Vec3<float>(7.7f,8.8f,9.9f),
openvdb::math::Vec3<float>(7.7f,8.8f,9.9f),
openvdb::math::Vec3<float>(9.9f,-1.1f,-2.2f),
openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f),
openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f),
openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f), }, // in
{ openvdb::math::Vec3<float>(1.1f,2.2f,3.3f) + openvdb::math::Vec3<float>(1.1f,2.3f,4.3f),
openvdb::math::Vec3<float>(3.3f,4.4f,5.5f) - openvdb::math::Vec3<float>(1.1f,2.3f,4.3f),
openvdb::math::Vec3<float>(5.5f,6.6f,7.7f) * openvdb::math::Vec3<float>(1.1f,2.3f,4.3f),
openvdb::math::Vec3<float>(7.7f,8.8f,9.9f) / openvdb::math::Vec3<float>(1.1f,2.3f,4.3f),
openvdb::math::Vec3<float>(std::fmod(7.7f,1.1f), std::fmod(8.8f,2.3f), std::fmod(9.9f,4.3f)),
openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f),
openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f) + openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f),
openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f),
openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f)
}); // expected
}
}
},
{ "vec3d", {
[&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names,
{ openvdb::math::Vec3<double>(1.1,2.3,4.3),
openvdb::math::Vec3<double>(-1.1,-2.3,-4.3),
openvdb::math::Vec3<double>(0.0,0.0,0.0),
openvdb::math::Vec3<double>(0.0,0.0,0.0),
openvdb::math::Vec3<double>(0.0,0.0,0.0),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3),
openvdb::math::Vec3<double>(0.0,0.0,0.0),
openvdb::math::Vec3<double>(0.0,0.0,0.0),
openvdb::math::Vec3<double>(4.1, 5.3, 6.3) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names,
{ openvdb::math::Vec3<double>(1.1,2.2,3.3),
openvdb::math::Vec3<double>(3.3,4.4,5.5),
openvdb::math::Vec3<double>(5.5,6.6,7.7),
openvdb::math::Vec3<double>(7.7,8.8,9.9),
openvdb::math::Vec3<double>(7.7,8.8,9.9),
openvdb::math::Vec3<double>(9.9,-1.1,-2.2),
openvdb::math::Vec3<double>(-2.2,-3.3,-4.4),
openvdb::math::Vec3<double>(-4.3,-5.5,-6.6),
openvdb::math::Vec3<double>(-7.1,8.5,-9.9), }, // in
{ openvdb::math::Vec3<double>(1.1,2.2,3.3) + openvdb::math::Vec3<double>(1.1,2.3,4.3),
openvdb::math::Vec3<double>(3.3,4.4,5.5) - openvdb::math::Vec3<double>(1.1,2.3,4.3),
openvdb::math::Vec3<double>(5.5,6.6,7.7) * openvdb::math::Vec3<double>(1.1,2.3,4.3),
openvdb::math::Vec3<double>(7.7,8.8,9.9) / openvdb::math::Vec3<double>(1.1,2.3,4.3),
openvdb::math::Vec3<double>(std::fmod(7.7,1.1), std::fmod(8.8,2.3), std::fmod(9.9,4.3)),
openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3),
openvdb::math::Vec3<double>(-2.2,-3.3,-4.4) + openvdb::math::Vec3<double>(-4.3,-5.5,-6.6),
openvdb::math::Vec3<double>(-4.3,-5.5,-6.6),
openvdb::math::Vec3<double>(-7.1,8.5,-9.9) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3)
}); // expected
}
}
},
{ "vec4i", {
[&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names,
{ openvdb::math::Vec4<int32_t>(1,2,3,4),
openvdb::math::Vec4<int32_t>(-1,-2,-3,-4),
openvdb::math::Vec4<int32_t>(0,0,0,0),
openvdb::math::Vec4<int32_t>(0,0,0,0),
openvdb::math::Vec4<int32_t>(0,0,0,0),
openvdb::math::Vec4<int32_t>(6,8,10,12),
openvdb::math::Vec4<int32_t>(0,0,0,0),
openvdb::math::Vec4<int32_t>(0,0,0,0),
openvdb::math::Vec4<int32_t>(5,6,7,8) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names,
{ openvdb::math::Vec4<int32_t>(1,2,3,4),
openvdb::math::Vec4<int32_t>(4,5,6,7),
openvdb::math::Vec4<int32_t>(7,8,9,-1),
openvdb::math::Vec4<int32_t>(-1,-2,-3,1),
openvdb::math::Vec4<int32_t>(-4,-5,-6,2),
openvdb::math::Vec4<int32_t>(4,5,-6,2),
openvdb::math::Vec4<int32_t>(-7,-8,-9,3),
openvdb::math::Vec4<int32_t>(-1,2,-3,4),
openvdb::math::Vec4<int32_t>(-5,6,-7,8) }, // in
{ openvdb::math::Vec4<int32_t>(2,4,6,8),
openvdb::math::Vec4<int32_t>(3,3,3,3),
openvdb::math::Vec4<int32_t>(7,16,27,-4),
openvdb::math::Vec4<int32_t>(-1,-1,-1,0),
openvdb::math::Vec4<int32_t>(0,1,0,2),
openvdb::math::Vec4<int32_t>(6,8,10,12),
openvdb::math::Vec4<int32_t>(-8,-6,-12,7),
openvdb::math::Vec4<int32_t>(-1,2,-3,4),
openvdb::math::Vec4<int32_t>(0,12,0,16) }); // expected
}
}
},
{ "vec4f", {
[&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names,
{ openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f),
openvdb::math::Vec4<float>(-1.1f,-2.3f,-4.3f,-5.4f),
openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f),
openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f),
openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f),
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f),
openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f),
openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f),
openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names,
{ openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f),
openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f),
openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f),
openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f),
openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f),
openvdb::math::Vec4<float>(9.9f,-1.1f,-2.2f,-3.3f),
openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f),
openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f),
openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) }, // in
{ openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f) + openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f),
openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f) - openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f),
openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f) * openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f),
openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f) / openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f),
openvdb::math::Vec4<float>(std::fmod(7.7f,1.1f),std::fmod(8.8f,2.3f),std::fmod(9.9f,4.3f),std::fmod(-1.1f,5.4f)+5.4f), // floored mod
openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f),
openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f) + openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f),
openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f),
openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f)
}); // expected
}
}
},
{ "vec4d", {
[&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names,
{ openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4),
openvdb::math::Vec4<double>(-1.1,-2.3,-4.3,-5.4),
openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0),
openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0),
openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0),
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4),
openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0),
openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0),
openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4) });
},
[&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names,
{ openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4),
openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6),
openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8),
openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1),
openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1),
openvdb::math::Vec4<double>(9.9,-1.1,-2.2,-3.3),
openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5),
openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7),
openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) }, // in
{ openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4) + openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4),
openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6) - openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4),
openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8) * openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4),
openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1) / openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4),
openvdb::math::Vec4<double>(std::fmod(7.7,1.1),std::fmod(8.8,2.3),std::fmod(9.9,4.3),std::fmod(-1.1,5.4)+5.4), // floored mod
openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4),
openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5) + openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7),
openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7),
openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4)
}); // expected
}
}
}
};
for (const auto& expc : expected) {
for (const auto& test : expc.second) {
mHarness.reset();
test.operator()();
this->execute("assign_compound." + expc.first + ".ax");
}
}
}
void
TestAssign::compoundMatrixAssignment()
{
const std::string code = R"(
_T1_@test1 += _l1_;
_T1_@test2 -= _l1_;
_T1_@test3 *= _l1_;
_T1_ local1 = _l1_,
local2 = _l2_;
local1 += local2;
_T1_@test4 = local1;
_T1_@test5 += _T1_@test6;
_T1_@test7 += local2;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign_compound." + config.first + ".ax");
}
};
generate(mat3);
generate(mat4);
const openvdb::math::Mat3<float> m3fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f);
const openvdb::math::Mat3<float> m3fl2(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f);
const openvdb::math::Mat3<double> m3dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2);
const openvdb::math::Mat3<double> m3dl2(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2);
const openvdb::math::Mat4<float> m4fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f);
const openvdb::math::Mat4<float> m4fl2(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f);
const openvdb::math::Mat4<double> m4dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9);
const openvdb::math::Mat4<double> m4dl2(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7);
const auto names = unittest_util::nameSequence("test", 7);
const std::map<std::string, std::vector<std::function<void()>>> expected = {
{ "mat3f", {
[&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names,
{ m3fl1,
-m3fl1,
openvdb::math::Mat3<float>::zero(),
m3fl1 + m3fl2,
openvdb::math::Mat3<float>::zero(),
openvdb::math::Mat3<float>::zero(),
m3fl2 });
},
[&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names,
{ openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f),
openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f),
openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f),
openvdb::math::Mat3<float>(8.3f, 2.3f, 6.1f, 4.5f, 0.1f, 0.1f, 5.3f, 4.5f, 8.9f),
openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f),
openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f),
openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f)
}, // in
{ openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f) + m3fl1,
openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f) - m3fl1,
openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f) * m3fl1,
m3fl1 + m3fl2,
openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f) +
openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f),
openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f),
openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f) + m3fl2
}); // expected
}
}
},
{ "mat3d", {
[&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names,
{ m3dl1,
-m3dl1,
openvdb::math::Mat3<double>::zero(),
m3dl1 + m3dl2,
openvdb::math::Mat3<double>::zero(),
openvdb::math::Mat3<double>::zero(),
m3dl2 });
},
[&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names,
{ openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1),
openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3),
openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3),
openvdb::math::Mat3<double>(8.3, 2.3, 6.1, 4.5, 0.1, 0.1, 5.3, 4.5, 8.9),
openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4),
openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7),
openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7)
}, // in
{ openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1) + m3dl1,
openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3) - m3dl1,
openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3) * m3dl1,
m3dl1 + m3dl2,
openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4) +
openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7),
openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7),
openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7) + m3dl2
}); // expected
}
}
},
{ "mat4f", {
[&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names,
{ m4fl1,
-m4fl1,
openvdb::math::Mat4<float>::zero(),
m4fl1 + m4fl2,
openvdb::math::Mat4<float>::zero(),
openvdb::math::Mat4<float>::zero(),
m4fl2 });
},
[&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names,
{ openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f),
openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f),
openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f),
openvdb::math::Mat4<float>(1.2f, 5.1f, 8.2f, 3.1f, -3.3f, -7.3f, 0.2f,-0.1f, 1.4f, 0.8f, 8.8f,-1.1f, -7.8f, 4.1f, 4.4f, -4.7f),
openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f),
openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f),
openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f),
}, // in
{ openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f) + m4fl1,
openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f) - m4fl1,
openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f) * m4fl1,
m4fl1 + m4fl2,
openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f) +
openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f),
openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f),
openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f) + m4fl2
}); // expected
}
}
},
{ "mat4d", {
[&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names,
{ m4dl1,
-m4dl1,
openvdb::math::Mat4<double>::zero(),
m4dl1 + m4dl2,
openvdb::math::Mat4<double>::zero(),
openvdb::math::Mat4<double>::zero(),
m4dl2 });
},
[&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names,
{ openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4),
openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9),
openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1),
openvdb::math::Mat4<double>(1.2, 5.1, 8.2, 3.1, -3.3, -7.3, 0.2,-0.1, 1.4, 0.8, 8.8,-1.1, -7.8, 4.1, 4.4, -4.7),
openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7),
openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8),
openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8),
}, // in
{ openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4) + m4dl1,
openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9) - m4dl1,
openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1) * m4dl1,
m4dl1 + m4dl2,
openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7) +
openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8),
openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8),
openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8) + m4dl2
}); // expected
}
}
}
};
for (const auto& expc : expected) {
for (const auto& test : expc.second) {
mHarness.reset();
test.operator()();
this->execute("assign_compound." + expc.first + ".ax");
}
}
}
void
TestAssign::compoundStringAssignment()
{
const std::string code = R"(
_T1_@test1 += _l1_;
_T1_ local1 = _l1_,
local2 = _l2_;
// test default init and empty string
string empty = "";
string defaultstr;
local1 += local2;
defaultstr += local1;
defaultstr += empty;
_T1_@test2 = defaultstr;
_T1_@test3 += _T1_@test4;
_T1_@test5 += local2;
)";
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", config.first); // replace type
// replace literal values
for (const auto& settings : config.second) {
unittest_util::replace(repl, settings.first, settings.second);
}
this->registerTest(repl, "assign_compound." + config.first + ".ax");
}
};
generate(string);
const auto names = unittest_util::nameSequence("test", 5);
const std::map<std::string, std::vector<std::function<void()>>> expected = {
{ "string", {
[&](){ mHarness.addAttributes<std::string>(names,
{ "foo", "foobar", "", "", "bar" });
},
[&](){ mHarness.addAttributes<std::string>(names,
{ "abc ", "xyz", " 123", "4560", " " }, // in
{ "abc foo", "foobar", " 1234560", "4560", " bar" }); // expected
},
}
}
};
for (const auto& expc : expected) {
for (const auto& test : expc.second) {
mHarness.reset();
test.operator()();
this->execute("assign_compound." + expc.first + ".ax");
}
}
}
void
TestAssign::implicitScalarAssignment()
{
auto generate = [this](const auto& source, const auto& targets) {
for (const auto& t1 : source) {
std::string code = "_T1_ local = _l1_;\n";
unittest_util::replace(code, "_T1_", t1.first);
unittest_util::replace(code, "_l1_", t1.second.at("_l1_"));
for (const auto& target : targets) {
for (const auto& t2 : *target) {
if (t1.first == t2.first) continue;
std::string tmp = "_T2_@_A1_ = local;";
unittest_util::replace(tmp, "_A1_", "test" + t2.first);
unittest_util::replace(tmp, "_T2_", t2.first);
code += tmp + "\n";
}
}
this->registerTest(code, "assign_implicit_scalar." + t1.first + ".ax");
}
};
// source -> dest
generate(integral, std::vector<decltype(integral)*>{ &integral, &floating });
generate(floating, std::vector<decltype(integral)*>{ &integral, &floating });
// source -> dest
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){
mHarness.addAttribute<int32_t>("testint32", 1);
mHarness.addAttribute<int64_t>("testint64", 1);
mHarness.addAttribute<float>("testfloat", 1.0f);
mHarness.addAttribute<double>("testdouble", 1.0);
}
},
{ "int32", [&](){
mHarness.addAttribute<bool>("testbool", true);
mHarness.addAttribute<int64_t>("testint64", 2);
mHarness.addAttribute<float>("testfloat", 2.0f);
mHarness.addAttribute<double>("testdouble", 2.0);
}
},
{ "int64", [&](){
mHarness.addAttribute<bool>("testbool", true);
mHarness.addAttribute<int32_t>("testint32", 2);
mHarness.addAttribute<float>("testfloat", 2.0f);
mHarness.addAttribute<double>("testdouble", 2.0);
}
},
{ "float", [&](){
mHarness.addAttribute<bool>("testbool", true);
mHarness.addAttribute<int32_t>("testint32", 1);
mHarness.addAttribute<int64_t>("testint64", 1);
mHarness.addAttribute<double>("testdouble", double(1.1f));
}
},
{ "double", [&](){
mHarness.addAttribute<bool>("testbool", true);
mHarness.addAttribute<int32_t>("testint32", 1);
mHarness.addAttribute<int64_t>("testint64", 1);
mHarness.addAttribute<float>("testfloat", float(1.1));
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("assign_implicit_scalar." + expc.first + ".ax");
}
}
void
TestAssign::implicitContainerAssignment()
{
auto generate = [this](const auto& source, const auto& target) {
for (const auto& t1 : source) {
std::string code = "_T1_ local = _l1_;\n";
unittest_util::replace(code, "_T1_", t1.first);
unittest_util::replace(code, "_l1_", t1.second.at("_l1_"));
for (const auto& t2 : target) {
if (t1.first == t2.first) continue;
std::string tmp = "_T2_@_A1_ = local;";
unittest_util::replace(tmp, "_A1_", "test" + t2.first);
unittest_util::replace(tmp, "_T2_", t2.first);
code += tmp + "\n";
}
this->registerTest(code, "assign_implicit_container." + t1.first + ".ax");
}
};
// source -> dest
generate(vec2, vec2);
generate(vec3, vec3);
generate(vec4, vec4);
generate(mat3, mat3);
generate(mat4, mat4);
// test name is the source type in use. source -> dest
const std::map<std::string, std::function<void()>> expected = {
{ "vec2i", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,2.0f));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,2.0));
}
},
{ "vec2f", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(2.3f)));
}
},
{ "vec2d", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(2.3)));
}
},
{ "vec3i", [&]() {
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,2.0f,3.0f));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,2.0,3.0));
}
},
{ "vec3f", [&]() {
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(2.3f),double(4.3f)));
}
},
{ "vec3d", [&]() {
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(2.3),float(4.3)));
}
},
{ "vec4i", [&]() {
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,2.0f,3.0f,4.0f));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,2.0,3.0,4.0));
}
},
{ "vec4f", [&]() {
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(2.3f),double(4.3f),double(5.4f)));
}
},
{ "vec4d", [&]() {
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(2.3),float(4.3),float(5.4)));
}
},
{ "mat3f",
[&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d",
openvdb::math::Mat3<double>(
double(1.1f),double(2.3f),double(4.3f),
double(5.4f),double(6.7f),double(7.8f),
double(9.1f),double(4.5f),double(8.2f)));
}
},
{ "mat3d",
[&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f",
openvdb::math::Mat3<float>(
float(1.1),float(2.3),float(4.3),
float(5.4),float(6.7),float(7.8),
float(9.1),float(4.5),float(8.2)));
}
},
{ "mat4f",
[&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d",
openvdb::math::Mat4<double>(
double(1.1f),double(2.3f),double(4.3f),double(5.4f),
double(6.7f),double(7.8f),double(9.1f),double(4.5f),
double(8.2f),double(3.3f),double(2.9f),double(5.9f),
double(0.1f),double(0.3f),double(5.1f),double(1.9f)));
}
},
{ "mat4d",
[&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f",
openvdb::math::Mat4<float>(
float(1.1),float(2.3),float(4.3),float(5.4),
float(6.7),float(7.8),float(9.1),float(4.5),
float(8.2),float(3.3),float(2.9),float(5.9),
float(0.1),float(0.3),float(5.1),float(1.9)));
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("assign_implicit_container." + expc.first + ".ax");
}
}
void
TestAssign::implicitContainerScalarAssignment()
{
auto generate = [this](const auto& source, const auto& targets) {
for (const auto& t1 : source) {
std::string code = "_T1_ local = _l1_;\n";
unittest_util::replace(code, "_T1_", t1.first);
unittest_util::replace(code, "_l1_", t1.second.at("_l1_"));
for (const auto& target : targets) {
for (const auto& t2 : *target) {
if (t1.first == t2.first) continue;
std::string tmp = "_T2_@_A1_ = local;";
unittest_util::replace(tmp, "_A1_", "test" + t2.first);
unittest_util::replace(tmp, "_T2_", t2.first);
code += tmp + "\n";
}
}
this->registerTest(code, "assign_implicit_container_scalar." + t1.first + ".ax");
}
};
generate(integral, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 });
generate(floating, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 });
auto symmetric3 = [](auto val) -> openvdb::math::Mat3<decltype(val)> {
openvdb::math::Mat3<decltype(val)> mat;
mat.setZero();
mat(0,0) = val;
mat(1,1) = val;
mat(2,2) = val;
return mat;
};
auto symmetric4 = [](auto val) -> openvdb::math::Mat4<decltype(val)> {
openvdb::math::Mat4<decltype(val)> mat;
mat.setZero();
mat(0,0) = val;
mat(1,1) = val;
mat(2,2) = val;
mat(3,3) = val;
return mat;
};
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&]() {
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,1.0f));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,1.0));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,1.0f,1.0f));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,1.0,1.0));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,1.0f,1.0f,1.0f));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,1.0,1.0,1.0));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.0f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.0));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.0f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.0));
}
},
{ "int32", [&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0));
}
},
{ "int64", [&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0));
}
},
{ "float", [&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(1.1f)));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f,1.1f));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(1.1f),double(1.1f)));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f,1.1f,1.1f));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(1.1f),double(1.1f),double(1.1f)));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f,1.1f,1.1f,1.1f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.1f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(double(1.1f)));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.1f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(double(1.1f)));
}
},
{ "double", [&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1,1.1));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(1.1)));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1,1.1,1.1));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(1.1),float(1.1)));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1,1.1,1.1,1.1));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(1.1),float(1.1),float(1.1)));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(float(1.1)));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.1));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(float(1.1)));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.1));
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("assign_implicit_container_scalar." + expc.first + ".ax");
}
}
void
TestAssign::scopedAssign()
{
const std::string code = R"(
float var = 30.0f;
{
float var = 3.0f;
}
{
float var = 1.0f;
float@test2 = var;
{
float var = -10.0f;
float@test3 = var;
}
{
float@test7 = var;
}
}
{
float var = -100.0f;
}
{
float var = 50.0f;
{
float var = -15.0f;
float@test4 = var;
}
{
float var = -10.0f;
}
{
float@test5 = var;
}
float@test6 = var;
}
float@test1 = var;
)";
this->registerTest(code, "assign_scoped.float.ax");
const auto names = unittest_util::nameSequence("test", 7);
mHarness.addAttributes<float>(names, {30.0f, 1.0f, -10.0f, -15.0f, 50.0f, 50.0f, 1.0f});
this->execute("assign_scoped.float.ax");
CPPUNIT_ASSERT(mHarness.mLogger.hasWarning());
}
| 77,820 | C++ | 51.019385 | 162 | 0.455744 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestKeyword.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestKeyword : public unittest_util::AXTestCase
{
public:
CPPUNIT_TEST_SUITE(TestKeyword);
CPPUNIT_TEST(testKeywordSimpleReturn);
CPPUNIT_TEST(testKeywordReturnBranchIf);
CPPUNIT_TEST(testKeywordReturnBranchLoop);
CPPUNIT_TEST(testKeywordConditionalReturn);
CPPUNIT_TEST(testKeywordForLoopKeywords);
CPPUNIT_TEST(testKeywordWhileLoopKeywords);
CPPUNIT_TEST(testKeywordDoWhileLoopKeywords);
CPPUNIT_TEST_SUITE_END();
void testKeywordSimpleReturn();
void testKeywordReturnBranchIf();
void testKeywordReturnBranchLoop();
void testKeywordConditionalReturn();
void testKeywordForLoopKeywords();
void testKeywordWhileLoopKeywords();
void testKeywordDoWhileLoopKeywords();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestKeyword);
void
TestKeyword::testKeywordSimpleReturn()
{
mHarness.addAttribute<int>("return_test0", 0);
mHarness.executeCode("test/snippets/keyword/simpleReturn");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordReturnBranchIf()
{
mHarness.addAttribute<int>("return_test1", 1);
mHarness.executeCode("test/snippets/keyword/returnBranchIf");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordReturnBranchLoop()
{
mHarness.addAttribute<int>("return_test2", 1);
mHarness.executeCode("test/snippets/keyword/returnBranchLoop");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordConditionalReturn()
{
mHarness.addAttribute<int>("return_test3", 3);
mHarness.executeCode("test/snippets/keyword/conditionalReturn");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordForLoopKeywords()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test4", openvdb::Vec3f(1.0,0.0,0.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test5", openvdb::Vec3f(1.0,0.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test6", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test7", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test8", openvdb::Vec3f(1.0,2.0,3.0));
mHarness.addAttribute<openvdb::math::Mat3s>("loop_test19",
openvdb::math::Mat3s(1.0,2.0,3.0, 0.0,0.0,0.0, 7.0,8.0,9.0));
mHarness.addAttribute<openvdb::math::Mat3s>("loop_test20",
openvdb::math::Mat3s(1.0,0.0,0.0, 0.0,0.0,0.0, 7.0,0.0,0.0));
mHarness.addAttribute<openvdb::math::Mat3s>("loop_test21",
openvdb::math::Mat3s(1.0,0.0,3.0, 0.0,0.0,0.0, 7.0,0.0,9.0));
mHarness.addAttribute<openvdb::Vec3f>("return_test4", openvdb::Vec3f(10,10,10));
mHarness.executeCode("test/snippets/keyword/forLoopKeywords");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordWhileLoopKeywords()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test10", openvdb::Vec3f(1.0,0.0,0.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test11", openvdb::Vec3f(0.0,0.0,2.0));
mHarness.addAttribute<openvdb::Vec3f>("return_test6", openvdb::Vec3f(100,100,100));
mHarness.executeCode("test/snippets/keyword/whileLoopKeywords");
AXTESTS_STANDARD_ASSERT();
}
void
TestKeyword::testKeywordDoWhileLoopKeywords()
{
mHarness.addAttribute<openvdb::Vec3f>("loop_test13", openvdb::Vec3f(1.0,0.0,0.0));
mHarness.addAttribute<openvdb::Vec3f>("loop_test14", openvdb::Vec3f(0.0,0.0,2.0));
mHarness.addAttribute<openvdb::Vec3f>("return_test7", openvdb::Vec3f(100,100,100));
mHarness.executeCode("test/snippets/keyword/doWhileLoopKeywords");
AXTESTS_STANDARD_ASSERT();
}
| 3,690 | C++ | 31.377193 | 87 | 0.726829 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestBinary.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "TestHarness.h"
#include "../test/util.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
// Configuration values for binary code
using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>;
static const ConfigMap integral = {
{ "bool", { { "_L1_", "true" }, { "_L2_", "false" } } },
{ "int16", { { "_L1_", "2" }, { "_L2_", "3" } } },
{ "int32", { { "_L1_", "2" }, { "_L2_", "3" } } },
{ "int64", { { "_L1_", "2l" }, { "_L2_", "3l" } } }
};
static const ConfigMap floating = {
{ "float", { { "_L1_", "1.1f" }, { "_L2_", "2.3f" } } },
{ "double", { { "_L1_", "1.1" }, { "_L2_", "2.3" } } }
};
static const ConfigMap vec2 = {
{ "vec2i", { { "_L1_", "{1, 2}" }, { "_L2_", "{3, 4}" } } },
{ "vec2f", { { "_L1_", "{1.1f, 2.3f}" }, { "_L2_", "{4.1f, 5.3f}" } } },
{ "vec2d", { { "_L1_", "{1.1, 2.3}" }, { "_L2_", "{4.1, 5.3}" } } }
};
static const ConfigMap vec3 = {
{ "vec3i", { { "_L1_", "{1, 2, 3}" }, { "_L2_", "{4, 5, 6}" } } },
{ "vec3f", { { "_L1_", "{1.1f, 2.3f, 4.3f}" }, { "_L2_", "{4.1f, 5.3f, 6.3f}" } } },
{ "vec3d", { { "_L1_", "{1.1, 2.3 , 4.3}" }, { "_L2_", "{4.1, 5.3, 6.3}" } } }
};
static const ConfigMap vec4 = {
{ "vec4i", { { "_L1_", "{1, 2, 3, 4}" }, { "_L2_", "{5, 6, 7, 8}" } } },
{ "vec4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_L2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } },
{ "vec4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_L2_", "{5.1, 6.3, 7.3, 8.4}" } } }
};
static const ConfigMap mat3 = {
{ "mat3f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" },
{ "_L2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } }
},
{ "mat3d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" },
{ "_L2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } }
}
};
static const ConfigMap mat4 = {
{ "mat4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" },
{ "_L2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } }
},
{ "mat4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" },
{ "_L2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } }
}
};
static const ConfigMap string = {
{ "string", { { "_L1_", "\"foo\"" }, { "_L2_", "\"bar\"" } } }
};
class TestBinary : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestBinary);
CPPUNIT_TEST(plus);
CPPUNIT_TEST(minus);
CPPUNIT_TEST(mult);
CPPUNIT_TEST(div);
CPPUNIT_TEST(mod);
CPPUNIT_TEST(btand);
CPPUNIT_TEST(btor);
CPPUNIT_TEST(btxor);
CPPUNIT_TEST(logicaland);
CPPUNIT_TEST(logicalor);
CPPUNIT_TEST(equalsequals);
CPPUNIT_TEST(notequals);
CPPUNIT_TEST(greaterthan);
CPPUNIT_TEST(lessthan);
CPPUNIT_TEST(greaterthanequals);
CPPUNIT_TEST(lessthanequals);
CPPUNIT_TEST(shiftleft);
CPPUNIT_TEST(shiftright);
CPPUNIT_TEST_SUITE_END();
void plus();
void minus();
void mult();
void div();
void mod();
void btand();
void btor();
void btxor();
void logicaland();
void logicalor();
void equalsequals();
void notequals();
void greaterthan();
void lessthan();
void greaterthanequals();
void lessthanequals();
void shiftleft();
void shiftright();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestBinary);
void
TestBinary::plus()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ + _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
generate(string);
this->registerTest(repl, "binary_plus.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 5); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 5); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 5); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f + 2.3f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 + 2.3); } },
{ "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(4,6)); } },
{ "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f+4.1f, 2.3f+5.3f)); } },
{ "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1+4.1, 2.3+5.3)); } },
{ "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(5,7,9)); } },
{ "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f+4.1f, 2.3f+5.3f, 4.3f+6.3f)); } },
{ "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1+4.1, 2.3+5.3, 4.3+6.3)); } },
{ "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(6,8,10,12)); } },
{ "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f+5.1f, 2.3f+6.3f, 4.3f+7.3f, 5.4f+8.4f)); } },
{ "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1+5.1, 2.3+6.3, 4.3+7.3, 5.4+8.4)); } },
{ "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f",
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) +
openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); }
},
{ "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d",
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) +
openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); }
},
{ "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f",
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) +
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); }
},
{ "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d",
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) +
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); }
},
{ "string", [&](){ mHarness.addAttribute<std::string>("teststring", "foobar"); } }
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_plus.ax");
}
void
TestBinary::minus()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ - _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
this->registerTest(repl, "binary_minus.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", -1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", -1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", -1); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f - 2.3f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 - 2.3); } },
{ "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(-2,-2)); } },
{ "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f-4.1f, 2.3f-5.3f)); } },
{ "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1-4.1, 2.3-5.3)); } },
{ "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(-3,-3,-3)); } },
{ "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f-4.1f, 2.3f-5.3f, 4.3f-6.3f)); } },
{ "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1-4.1, 2.3-5.3, 4.3-6.3)); } },
{ "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(-4,-4,-4,-4)); } },
{ "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f-5.1f, 2.3f-6.3f, 4.3f-7.3f, 5.4f-8.4f)); } },
{ "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1-5.1, 2.3-6.3, 4.3-7.3, 5.4-8.4)); } },
{ "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f",
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) -
openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); }
},
{ "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d",
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) -
openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); }
},
{ "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f",
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) -
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); }
},
{ "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d",
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) -
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); }
},
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_minus.ax");
}
void
TestBinary::mult()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ * _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
this->registerTest(repl, "binary_mult.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 6); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 6); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 6); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f * 2.3f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 * 2.3); } },
{ "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,8)); } },
{ "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f*4.1f, 2.3f*5.3f)); } },
{ "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1*4.1, 2.3*5.3)); } },
{ "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,10,18)); } },
{ "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f*4.1f, 2.3f*5.3f, 4.3f*6.3f)); } },
{ "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1*4.1, 2.3*5.3, 4.3*6.3)); } },
{ "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,12,21,32)); } },
{ "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f*5.1f, 2.3f*6.3f, 4.3f*7.3f, 5.4f*8.4f)); } },
{ "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1*5.1, 2.3*6.3, 4.3*7.3, 5.4*8.4)); } },
{ "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f",
openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) *
openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); }
},
{ "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d",
openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) *
openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); }
},
{ "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f",
openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) *
openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); }
},
{ "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d",
openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) *
openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); }
}
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_mult.ax");
}
void
TestBinary::div()
{
// @note reverses L1 and L2 as L2 is usually larger
const std::string code = R"(
_T1_@_A1_ = _L2_ / _L1_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
this->registerTest(repl, "binary_div.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 2.3f/1.1f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 2.3/1.1); } },
{ "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,2)); } },
{ "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(4.1f/1.1f, 5.3f/2.3f)); } },
{ "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(4.1/1.1, 5.3/2.3)); } },
{ "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,2,2)); } },
{ "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(4.1f/1.1f, 5.3f/2.3f, 6.3f/4.3f)); } },
{ "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(4.1/1.1, 5.3/2.3, 6.3/4.3)); } },
{ "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,3,2,2)); } },
{ "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(5.1f/1.1f, 6.3f/2.3f, 7.3f/4.3f, 8.4f/5.4f)); } },
{ "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(5.1/1.1, 6.3/2.3, 7.3/4.3, 8.4/5.4)); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_div.ax");
}
void
TestBinary::mod()
{
// @note reverses L1 and L2 as L2 is usually larger
const std::string code = R"(
_T1_@_A1_ = _L2_ % _L1_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
this->registerTest(repl, "binary_mod.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", std::fmod(2.3f,1.1f)); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", std::fmod(2.3,1.1)); } },
{ "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(0,0)); } },
{ "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f))); } },
{ "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3))); } },
{ "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(0,1,0)); } },
{ "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f), std::fmod(6.3f,4.3f))); } },
{ "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3), std::fmod(6.3,4.3))); } },
{ "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(0,0,1,0)); } },
{ "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(std::fmod(5.1f,1.1f), std::fmod(6.3f,2.3f), std::fmod(7.3f,4.3f), std::fmod(8.4f,5.4f))); } },
{ "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(std::fmod(5.1,1.1), std::fmod(6.3,2.3), std::fmod(7.3,4.3), std::fmod(8.4,5.4))); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_mod.ax");
}
void
TestBinary::btand()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ & _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
this->registerTest(repl, "binary_bitand.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 2); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 2); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 2); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_bitand.ax");
}
void
TestBinary::btor()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ | _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
this->registerTest(repl, "binary_bitor.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 3); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 3); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 3); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_bitor.ax");
}
void
TestBinary::btxor()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ ^ _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
this->registerTest(repl, "binary_bitxor.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_bitxor.ax");
}
void
TestBinary::logicaland()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ && _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_logicaland.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_logicaland.ax");
// Also test short circuiting logical op for &&
mHarness.reset();
this->registerTest(R"(
int@scircuit1 = 0;
int@scircuit2 = 1;
int@scircuit3 = 2;
int@scircuit1++ && ++int@scircuit2;
++int@scircuit1 && ++int@scircuit3;
int@scircuit4 = 1;
int@scircuit5 = 1;
true && int@scircuit4 = 2;
false && int@scircuit5 = 2;)",
"binary_logicaland_scircuit.ax");
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 1, 3, 2, 1 });
this->execute("binary_logicaland_scircuit.ax");
}
void
TestBinary::logicalor()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ || _L2_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first);
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_logicalor.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } },
{ "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } },
{ "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } },
{ "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } },
{ "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } },
{ "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } },
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_logicalor.ax");
// Also test short circuiting logical op for ||
mHarness.reset();
this->registerTest(R"(
int@scircuit1 = 0;
int@scircuit2 = 1;
int@scircuit3 = 2;
int@scircuit1++ || ++int@scircuit2;
++int@scircuit1 || ++int@scircuit3;
int@scircuit4 = 1;
int@scircuit5 = 1;
true || int@scircuit4 = 2;
false || int@scircuit5 = 2;)",
"binary_logicalor_scircuit.ax");
mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 2, 2, 1, 2 });
this->execute("binary_logicalor_scircuit.ax");
}
void
TestBinary::equalsequals()
{
const std::string code = R"(
bool@_A1_ = _L1_ == _L2_;
bool@_A2_ = _L2_ == _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
this->registerTest(repl, "binary_relational_equalsequals.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (size_t i = 0; i < idx-1; ++i) {
results.emplace_back((i % 2 == 0) ? false : true);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_equalsequals.ax");
}
void
TestBinary::notequals()
{
const std::string code = R"(
bool@_A1_ = _L1_ != _L2_;
bool@_A2_ = _L2_ != _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
generate(vec2);
generate(vec3);
generate(vec4);
generate(mat3);
generate(mat4);
this->registerTest(repl, "binary_relational_notequals.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (size_t i = 0; i < idx-1; ++i) {
results.emplace_back((i % 2 == 1) ? false : true);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_notequals.ax");
}
void
TestBinary::greaterthan()
{
const std::string code = R"(
bool@_A1_ = _L1_ > _L2_;
bool@_A2_ = _L2_ > _L1_;
bool@_A3_ = _L2_ > _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_relational_greaterthan.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (const auto& config : integral) {
if (config.first == "bool") {
// L1 and L2 for bools are swapped
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(false);
}
else {
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(false);
}
}
const size_t typecount = floating.size();
for (size_t i = 0; i < typecount; ++i) {
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(false);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_greaterthan.ax");
}
void
TestBinary::lessthan()
{
const std::string code = R"(
bool@_A1_ = _L1_ < _L2_;
bool@_A2_ = _L2_ < _L1_;
bool@_A3_ = _L2_ < _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_relational_lessthan.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (const auto& config : integral) {
if (config.first == "bool") {
// L1 and L2 for bools are swapped
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(false);
}
else {
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(false);
}
}
const size_t typecount = floating.size();
for (size_t i = 0; i < typecount; ++i) {
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(false);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_lessthan.ax");
}
void
TestBinary::greaterthanequals()
{
const std::string code = R"(
bool@_A1_ = _L1_ >= _L2_;
bool@_A2_ = _L2_ >= _L1_;
bool@_A3_ = _L2_ >= _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_relational_greaterthanequals.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (const auto& config : integral) {
if (config.first == "bool") {
// L1 and L2 for bools are swapped
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(true);
}
else {
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(true);
}
}
const size_t typecount = floating.size();
for (size_t i = 0; i < typecount; ++i) {
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(true);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_greaterthanequals.ax");
}
void
TestBinary::lessthanequals()
{
const std::string code = R"(
bool@_A1_ = _L1_ <= _L2_;
bool@_A2_ = _L2_ <= _L1_;
bool@_A3_ = _L2_ <= _L2_;)";
size_t idx = 1;
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++));
unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++));
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
generate(floating);
this->registerTest(repl, "binary_relational_lessthanequals.ax");
CPPUNIT_ASSERT(idx != 0);
const auto names = unittest_util::nameSequence("test", idx-1);
std::vector<bool> results;
for (const auto& config : integral) {
if (config.first == "bool") {
// L1 and L2 for bools are swapped
results.emplace_back(false);
results.emplace_back(true);
results.emplace_back(true);
}
else {
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(true);
}
}
const size_t typecount = floating.size();
for (size_t i = 0; i < typecount; ++i) {
results.emplace_back(true);
results.emplace_back(false);
results.emplace_back(true);
}
mHarness.addAttributes<bool>(names, results);
this->execute("binary_relational_lessthanequals.ax");
}
void
TestBinary::shiftleft()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ << _L2_;
_T1_@_A2_ = _L2_ << _L1_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first + "1");
unittest_util::replace(tmp, "_A2_", "test" + config.first + "2");
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
this->registerTest(repl, "binary_shiftleft.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){
mHarness.addAttribute<bool>("testbool1", true);
mHarness.addAttribute<bool>("testbool2", false);
}
},
{ "int16", [&](){
mHarness.addAttribute<int16_t>("testint161", 16);
mHarness.addAttribute<int16_t>("testint162", 12);
}
},
{ "int32", [&](){
mHarness.addAttribute<int32_t>("testint321", 16);
mHarness.addAttribute<int32_t>("testint322", 12);
}
},
{ "int64", [&](){
mHarness.addAttribute<int64_t>("testint641", 16);
mHarness.addAttribute<int64_t>("testint642", 12);
}
},
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_shiftleft.ax");
}
void
TestBinary::shiftright()
{
const std::string code = R"(
_T1_@_A1_ = _L1_ >> _L2_;
_T1_@_A2_ = _L2_ >> _L1_;)";
std::string repl;
auto generate = [&](const auto& map) {
for (const auto& config : map) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", config.first);
unittest_util::replace(tmp, "_A1_", "test" + config.first + "1");
unittest_util::replace(tmp, "_A2_", "test" + config.first + "2");
for (const auto& settings : config.second) {
unittest_util::replace(tmp, settings.first, settings.second);
}
repl += tmp;
}
};
generate(integral);
this->registerTest(repl, "binary_shiftright.ax");
const std::map<std::string, std::function<void()>> expected = {
{ "bool", [&](){
mHarness.addAttribute<bool>("testbool1", true);
mHarness.addAttribute<bool>("testbool2", false);
}
},
{ "int16", [&](){
mHarness.addAttribute<int16_t>("testint161", 0);
mHarness.addAttribute<int16_t>("testint162", 0);
}
},
{ "int", [&](){
mHarness.addAttribute<int32_t>("testint321", 0);
mHarness.addAttribute<int32_t>("testint322", 0);
}
},
{ "int64", [&](){
mHarness.addAttribute<int64_t>("testint641", 0);
mHarness.addAttribute<int64_t>("testint642", 0);
}
},
};
for (const auto& expc : expected) {
expc.second.operator()();
}
this->execute("binary_shiftright.ax");
}
| 42,437 | C++ | 38.330862 | 211 | 0.525579 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestCrement.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "CompareGrids.h"
#include "TestHarness.h"
#include "../test/util.h"
#include <openvdb_ax/compiler/CustomData.h>
#include <openvdb_ax/Exceptions.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace openvdb::points;
class TestCrement : public unittest_util::AXTestCase
{
public:
std::string dir() const override { return GET_TEST_DIRECTORY(); }
CPPUNIT_TEST_SUITE(TestCrement);
CPPUNIT_TEST(crementScalar);
CPPUNIT_TEST(crementComponent);
CPPUNIT_TEST_SUITE_END();
void crementScalar();
void crementComponent();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestCrement);
void
TestCrement::crementScalar()
{
const std::string code = R"(
_T1_@test1 = ++_T1_@test2;
_T1_@test3 = _T1_@test4++;
_T1_@test5 = (_T1_@test6++, _T1_@test7++, ++_T1_@test6);
_T1_@test8 = (++_T1_@test6, ++_T1_@test7, _T1_@test6++);
++_T1_@test9 = _T1_@test9;
)";
auto generate = [&](const auto& types) {
for (const auto& type : types) {
std::string repl = code;
unittest_util::replace(repl, "_T1_", type);
this->registerTest(repl, "crement_inc." + type + ".ax");
unittest_util::replace(repl, "++", "--");
this->registerTest(repl, "crement_dec." + type + ".ax");
}
};
generate(std::vector<std::string>{
"int16", "int32", "int64", "float", "double",
});
const auto names = unittest_util::nameSequence("test", 9);
const std::map<std::string, std::function<void(bool)>> expected = {
{ "int16",
[&](bool inc){
if (inc)
mHarness.addAttributes<int16_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 2, 2, 2, 3, 6, 8, -1, 7, -3 });
else
mHarness.addAttributes<int16_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 0, 0, 2, 1, 2, 0, -5, 1, -5 });
},
},
{ "int32",
[&](bool inc){
if (inc)
mHarness.addAttributes<int32_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 2, 2, 2, 3, 6, 8, -1, 7, -3 });
else
mHarness.addAttributes<int32_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 0, 0, 2, 1, 2, 0, -5, 1, -5 });
},
},
{ "int64",
[&](bool inc){
if (inc)
mHarness.addAttributes<int64_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 2, 2, 2, 3, 6, 8, -1, 7, -3 });
else
mHarness.addAttributes<int64_t>(names,
{ 0, 1, -1, 2, -3, 4, -3, 4, -4 },
{ 0, 0, 2, 1, 2, 0, -5, 1, -5 });
},
},
{ "float",
[&](bool inc){
if (inc)
mHarness.addAttributes<float>(names,
{ 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f },
{ (1.4f+1.0f),
(1.4f+1.0f), 2.5f,
(2.5f+1.0f),
(4.5f+1.0f+1.0f),
(4.5f+1.0f+1.0f+1.0f+1.0f),
(-3.3f+1.0f+1.0f),
(4.5f+1.0f+1.0f+1.0f),
(-4.8f+1.0f) });
else
mHarness.addAttributes<float>(names,
{ 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f },
{ (1.4f-1.0f),
(1.4f-1.0f), 2.5f,
(2.5f-1.0f),
(4.5f-1.0f-1.0f),
(4.5f-1.0f-1.0f-1.0f-1.0f),
(-3.3f-1.0f-1.0f),
(4.5f-1.0f-1.0f-1.0f),
(-4.8f-1.0f) });
},
},
{ "double",
[&](bool inc){
if (inc)
mHarness.addAttributes<double>(names,
{ 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 },
{ (1.4+1.0),
(1.4+1.0), 2.5,
(2.5+1.0),
(4.5+1.0+1.0),
(4.5+1.0+1.0+1.0+1.0),
(-3.3+1.0+1.0),
(4.5+1.0+1.0+1.0),
(-4.8+1.0) });
else
mHarness.addAttributes<double>(names,
{ 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 },
{ (1.4-1.0),
(1.4-1.0), 2.5,
(2.5-1.0),
(4.5-1.0-1.0),
(4.5-1.0-1.0-1.0-1.0),
(-3.3-1.0-1.0),
(4.5-1.0-1.0-1.0),
(-4.8-1.0) });
},
},
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()(true); // increment
this->execute("crement_inc." + expc.first + ".ax");
mHarness.reset();
expc.second.operator()(false); // decrement
this->execute("crement_dec." + expc.first + ".ax");
}
}
void
TestCrement::crementComponent()
{
// Just tests the first two components of every container
const std::string code = R"(
_T1_@_A1_[0] = ++_T1_@_A2_[0];
_T1_@_A1_[1] = _T1_@_A2_[1]++;
)";
auto generate = [&](const auto& types) {
std::string repl;
for (const auto& type : types) {
std::string tmp = code;
unittest_util::replace(tmp, "_T1_", type);
unittest_util::replace(tmp, "_A1_", "test" + type + "1");
unittest_util::replace(tmp, "_A2_", "test" + type + "2");
repl += tmp;
}
this->registerTest(repl, "crement_inc.component.ax");
unittest_util::replace(repl, "++", "--");
this->registerTest(repl, "crement_dec.component.ax");
};
generate(std::vector<std::string>{
"vec2i", "vec2f", "vec2d",
"vec3i", "vec3f", "vec3d",
"vec4i", "vec4f", "vec4d",
"mat3f", "mat3d",
"mat4f", "mat4d"
});
const std::map<std::string, std::function<void()>> expected = {
{ "inc",
[&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(0,1));
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2",
openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(0,2));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2",
openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f+1.0f));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1+1.0, 1.1));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2",
openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1+1.0, 1.1+1.0));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(0,1,0));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2",
openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(0,2,0));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2",
openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1+1.0, 1.1, 0.0));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2",
openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1+1.0, 1.1+1.0 ,0.0));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(0,1,0,0));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2",
openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(0,2,0,0));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f, 0.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2",
openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1+1.0, 1.1, 0.0, 0.0));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2",
openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1+1.0, 1.1+1.0, 0.0, 0.0));
auto getmat = [](auto x, auto a, auto b) -> decltype(x) {
x = decltype(x)::zero();
x(0,0) = a;
x(0,1) = b;
return x;
};
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f+1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2",
getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f),
getmat(openvdb::math::Mat3<float>(),-1.1f+1.0f,1.1f+1.0f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1+1.0, 1.1));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2",
getmat(openvdb::math::Mat3<double>(),-1.1,1.1),
getmat(openvdb::math::Mat3<double>(),-1.1+1.0, 1.1+1.0));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f+1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2",
getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f),
getmat(openvdb::math::Mat4<float>(),-1.1f+1.0f,1.1f+1.0f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1+1.0, 1.1));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2",
getmat(openvdb::math::Mat4<double>(),-1.1,1.1),
getmat(openvdb::math::Mat4<double>(),-1.1+1.0, 1.1+1.0));
}
},
{ "dec",
[&](){
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(-2,1));
mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2",
openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(-2,0));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2",
openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f-1.0f));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1-1.0, 1.1));
mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2",
openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1-1.0, 1.1-1.0));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(-2,1,0));
mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2",
openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(-2,0,0));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2",
openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1-1.0, 1.1, 0.0));
mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2",
openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1-1.0, 1.1-1.0 ,0.0));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(-2,1,0,0));
mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2",
openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(-2,0,0,0));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f, 0.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2",
openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f, 0.0f));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1-1.0, 1.1, 0.0, 0.0));
mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2",
openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1-1.0, 1.1-1.0, 0.0, 0.0));
auto getmat = [](auto x, auto a, auto b) -> decltype(x) {
x = decltype(x)::zero();
x(0,0) = a;
x(0,1) = b;
return x;
};
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f-1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2",
getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f),
getmat(openvdb::math::Mat3<float>(),-1.1f-1.0f,1.1f-1.0f));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1-1.0, 1.1));
mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2",
getmat(openvdb::math::Mat3<double>(),-1.1,1.1),
getmat(openvdb::math::Mat3<double>(),-1.1-1.0, 1.1-1.0));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f-1.0f, 1.1f));
mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2",
getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f),
getmat(openvdb::math::Mat4<float>(),-1.1f-1.0f,1.1f-1.0f));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1-1.0, 1.1));
mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2",
getmat(openvdb::math::Mat4<double>(),-1.1,1.1),
getmat(openvdb::math::Mat4<double>(),-1.1-1.0, 1.1-1.0));
}
}
};
for (const auto& expc : expected) {
mHarness.reset();
expc.second.operator()();
this->execute("crement_" + expc.first + ".component.ax");
}
}
| 16,068 | C++ | 45.712209 | 138 | 0.483321 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestLogger.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include <openvdb_ax/ast/Parse.h>
#include <openvdb_ax/compiler/Logger.h>
#include <cppunit/extensions/HelperMacros.h>
class TestLogger : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestLogger);
//CPPUNIT_TEST(testParseNewNode);
CPPUNIT_TEST(testParseSetsTree);
CPPUNIT_TEST(testAddError);
CPPUNIT_TEST(testAddWarning);
CPPUNIT_TEST(testWarningsAsErrors);
CPPUNIT_TEST(testMaxErrors);
CPPUNIT_TEST_SUITE_END();
//void testParseNewNode();
void testParseSetsTree();
void testAddError();
void testAddWarning();
void testWarningsAsErrors();
void testMaxErrors();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestLogger);
/*
extern openvdb::ax::Logger* axlog;
/// @note We don't deploy the grammar c files as part of the AX install.
/// Because the unit tests are structured to be able to build against
/// an existing version of AX we can't include the parser.cc here for
/// access to newNode. It's tested through other methods, but we
/// should restructure how this code is shared by perhaps moving it to
/// a shared header (including the definition of AXLTYPE)
void
TestLogger::testParseNewNode()
{
openvdb::ax::Logger logger;
axlog = &logger;// setting global Logger* used in parser
AXLTYPE location;
location.first_line = 100;
location.first_column = 65;
const auto& nodeToLineColMap = logger.mNodeToLineColMap;
CPPUNIT_ASSERT(nodeToLineColMap.empty());
const openvdb::ax::ast::Local* testLocal =
newNode<openvdb::ax::ast::Local>(&location, "test");
CPPUNIT_ASSERT_EQUAL(nodeToLineColMap.size(),static_cast<size_t>(1));
openvdb::ax::Logger::CodeLocation lineCol = nodeToLineColMap.at(testLocal);
CPPUNIT_ASSERT_EQUAL(lineCol.first, static_cast<size_t>(100));
CPPUNIT_ASSERT_EQUAL(lineCol.second, static_cast<size_t>(65));
}
*/
void
TestLogger::testParseSetsTree()
{
openvdb::ax::Logger logger;
CPPUNIT_ASSERT(!logger.mTreePtr);
std::string code("");
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger);
CPPUNIT_ASSERT(tree);
CPPUNIT_ASSERT_EQUAL(tree, logger.mTreePtr);
}
void
TestLogger::testAddError()
{
std::vector<std::string> messages;
openvdb::ax::Logger logger([&messages](const std::string& message) {
messages.emplace_back(message);
});
CPPUNIT_ASSERT(!logger.hasError());
CPPUNIT_ASSERT_EQUAL(logger.errors(), messages.size());
openvdb::ax::Logger::CodeLocation codeLocation(1,1);
std::string message("test");
logger.error(message, codeLocation);
CPPUNIT_ASSERT(logger.hasError());
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0);
logger.error(message, codeLocation);
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2));
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(2));
logger.clear();
CPPUNIT_ASSERT(!logger.hasError());
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(0));
openvdb::ax::ast::Local testLocal("name");
logger.error(message, &testLocal);
CPPUNIT_ASSERT(logger.hasError());
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3));
CPPUNIT_ASSERT(!logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test"), 0);
logger.clear();
CPPUNIT_ASSERT(!logger.hasError());
// test that add error finds code location
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger);
const openvdb::ax::ast::Node* local = tree->child(0)->child(0);
CPPUNIT_ASSERT(local);
logger.error(message, local);
CPPUNIT_ASSERT(logger.hasError());
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1));
CPPUNIT_ASSERT(logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:2"), 0);
}
logger.clear();
CPPUNIT_ASSERT(!logger.hasError());
// test add error finds code location even when node is deep copy
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger);
openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy());
const openvdb::ax::ast::Node* local = tree->child(0)->child(0);
CPPUNIT_ASSERT(local);
const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0);
CPPUNIT_ASSERT(localCopy);
// add referring to copy
logger.error(message, localCopy);
CPPUNIT_ASSERT(logger.hasError());
CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5));
CPPUNIT_ASSERT(logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0);
}
}
void
TestLogger::testAddWarning()
{
std::vector<std::string> messages;
openvdb::ax::Logger logger([](const std::string&) {},
[&messages](const std::string& message) {
messages.emplace_back(message);
});
CPPUNIT_ASSERT(!logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(logger.warnings(), messages.size());
openvdb::ax::Logger::CodeLocation codeLocation(1,1);
std::string message("test");
logger.warning(message, codeLocation);
CPPUNIT_ASSERT(logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0);
logger.warning(message, codeLocation);
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2));
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(2));
logger.clear();
CPPUNIT_ASSERT(!logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(0));
openvdb::ax::ast::Local testLocal("name");
logger.warning(message, &testLocal);
CPPUNIT_ASSERT(logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3));
CPPUNIT_ASSERT(!logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test"), 0);
logger.clear();
CPPUNIT_ASSERT(!logger.hasWarning());
// test that add warning finds code location
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger);
const openvdb::ax::ast::Node* local = tree->child(0)->child(0);
CPPUNIT_ASSERT(local);
logger.warning(message, local);
CPPUNIT_ASSERT(logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1));
CPPUNIT_ASSERT(logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:2"), 0);
}
logger.clear();
CPPUNIT_ASSERT(!logger.hasWarning());
// test add warning finds code location even when node is deep copy
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger);
openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy());
const openvdb::ax::ast::Node* local = tree->child(0)->child(0);
CPPUNIT_ASSERT(local);
const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0);
CPPUNIT_ASSERT(localCopy);
// add referring to copy
logger.warning(message, localCopy);
CPPUNIT_ASSERT(logger.hasWarning());
CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1));
CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5));
CPPUNIT_ASSERT(logger.mTreePtr);
CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0);
}
}
void
TestLogger::testWarningsAsErrors()
{
openvdb::ax::Logger logger([](const std::string&) {});
const std::string message("test");
const openvdb::ax::Logger::CodeLocation location(10,20);
logger.setWarningsAsErrors(true);
CPPUNIT_ASSERT(!logger.hasError());
CPPUNIT_ASSERT(!logger.hasWarning());
logger.warning(message, location);
CPPUNIT_ASSERT(logger.hasError());
CPPUNIT_ASSERT(!logger.hasWarning());
}
void
TestLogger::testMaxErrors()
{
openvdb::ax::Logger logger([](const std::string&) {});
const std::string message("test");
const openvdb::ax::Logger::CodeLocation location(10,20);
CPPUNIT_ASSERT(logger.error(message, location));
CPPUNIT_ASSERT(logger.error(message, location));
CPPUNIT_ASSERT(logger.error(message, location));
logger.clear();
logger.setMaxErrors(2);
CPPUNIT_ASSERT(logger.error(message, location));
CPPUNIT_ASSERT(!logger.error(message, location));
CPPUNIT_ASSERT(!logger.error(message, location));
}
| 9,112 | C++ | 34.877953 | 90 | 0.664618 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionGroup.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include <openvdb_ax/codegen/FunctionTypes.h>
#include <cppunit/extensions/HelperMacros.h>
#include <memory>
#include <string>
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Framework methods for the subsequent unit tests
/// @brief Dummy derived function which implemented types
struct TestFunction : public openvdb::ax::codegen::Function
{
static_assert(std::has_virtual_destructor
<openvdb::ax::codegen::Function>::value,
"Base class destructor is not virtual");
TestFunction(const std::vector<llvm::Type*>& types,
llvm::Type* ret,
const std::string& symbol)
: openvdb::ax::codegen::Function(types.size(), symbol)
, mTypes(types), mRet(ret) {}
~TestFunction() override {}
llvm::Type* types(std::vector<llvm::Type*>& types,
llvm::LLVMContext&) const override {
types = mTypes;
return mRet;
}
const std::vector<llvm::Type*> mTypes;
llvm::Type* mRet;
};
inline openvdb::ax::codegen::FunctionGroup::Ptr
axtestscalar(llvm::LLVMContext& C)
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
llvm::Type* voidty = llvm::Type::getVoidTy(C);
FunctionGroup::Ptr group(new FunctionGroup("test",
"The documentation", {
Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.testd")),
Function::Ptr(new TestFunction({llvm::Type::getFloatTy(C)}, voidty, "ax.testf")),
Function::Ptr(new TestFunction({llvm::Type::getInt64Ty(C)}, voidty, "ax.testi64")),
Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.testi32")),
Function::Ptr(new TestFunction({llvm::Type::getInt16Ty(C)}, voidty, "ax.testi16")),
Function::Ptr(new TestFunction({llvm::Type::getInt1Ty(C)}, voidty, "ax.testi1"))
}));
return group;
}
inline openvdb::ax::codegen::FunctionGroup::Ptr
axtestsize(llvm::LLVMContext& C)
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
llvm::Type* voidty = llvm::Type::getVoidTy(C);
FunctionGroup::Ptr group(new FunctionGroup("test",
"The documentation", {
Function::Ptr(new TestFunction({}, voidty, "ax.empty")),
Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.d")),
Function::Ptr(new TestFunction({
llvm::Type::getDoubleTy(C),
llvm::Type::getDoubleTy(C)
}, voidty, "ax.dd")),
}));
return group;
}
inline openvdb::ax::codegen::FunctionGroup::Ptr
axtestmulti(llvm::LLVMContext& C)
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
llvm::Type* voidty = llvm::Type::getVoidTy(C);
FunctionGroup::Ptr group(new FunctionGroup("test",
"The documentation", {
Function::Ptr(new TestFunction({}, voidty, "ax.empty")),
Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.i32")),
Function::Ptr(new TestFunction({
llvm::Type::getDoubleTy(C),
llvm::Type::getDoubleTy(C)
}, voidty, "ax.dd")),
Function::Ptr(new TestFunction({
llvm::Type::getInt32Ty(C),
llvm::Type::getDoubleTy(C)
}, voidty, "ax.i32d")),
Function::Ptr(new TestFunction({
llvm::Type::getDoubleTy(C)->getPointerTo(),
llvm::Type::getInt32Ty(C),
llvm::Type::getDoubleTy(C)
}, voidty, "ax.d*i32d")),
Function::Ptr(new TestFunction({
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo(),
}, voidty, "ax.i32x1")),
Function::Ptr(new TestFunction({
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(),
}, voidty, "ax.i32x2")),
}));
return group;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class TestFunctionGroup : public CppUnit::TestCase
{
public:
// Test FunctionGroup signature matching and execution errors
CPPUNIT_TEST_SUITE(TestFunctionGroup);
CPPUNIT_TEST(testFunctionGroup);
CPPUNIT_TEST(testMatch);
CPPUNIT_TEST(testExecute);
CPPUNIT_TEST_SUITE_END();
void testFunctionGroup();
void testMatch();
void testExecute();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionGroup);
void
TestFunctionGroup::testFunctionGroup()
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Type* voidty = llvm::Type::getVoidTy(C);
Function::Ptr decl1(new TestFunction({}, voidty, "ax.test1"));
Function::Ptr decl2(new TestFunction({}, voidty, "ax.test2"));
Function::Ptr decl3(new TestFunction({}, voidty, "ax.test3"));
FunctionGroup::Ptr group(new FunctionGroup("test",
"The documentation", {
decl1, decl2, decl3
}));
CPPUNIT_ASSERT_EQUAL(std::string("test"), std::string(group->name()));
CPPUNIT_ASSERT_EQUAL(std::string("The documentation"), std::string(group->doc()));
CPPUNIT_ASSERT_EQUAL(size_t(3), group->list().size());
CPPUNIT_ASSERT_EQUAL(decl1, group->list()[0]);
CPPUNIT_ASSERT_EQUAL(decl2, group->list()[1]);
CPPUNIT_ASSERT_EQUAL(decl3, group->list()[2]);
}
void
TestFunctionGroup::testMatch()
{
using openvdb::ax::codegen::LLVMType;
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
std::vector<llvm::Type*> types;
Function::SignatureMatch match;
Function::Ptr result;
//
FunctionGroup::Ptr group = axtestscalar(C);
const std::vector<Function::Ptr>* list = &group->list();
// test explicit matching
types.resize(1);
types[0] = llvm::Type::getInt1Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[5], result);
//
types[0] = llvm::Type::getInt16Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[4], result);
//
types[0] = llvm::Type::getInt32Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[3], result);
//
types[0] = llvm::Type::getInt64Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
//
types[0] = llvm::Type::getFloatTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[1], result);
//
types[0] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[0], result);
// test unsigned integers automatic type creation - these are not supported in the
// language however can be constructed from the API. The function framework does
// not differentiate between signed and unsigned integers
types[0] = LLVMType<uint64_t>::get(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
// test implicit matching - types should match to the first available castable signature
// which is always the void(double) "tsfd" function for all provided scalars
types[0] = llvm::Type::getInt8Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[0], result);
types.clear();
// test invalid matching - Size matching returns the first function which matched
// the size
result = group->match(types, C, &match);
CPPUNIT_ASSERT_EQUAL(Function::SignatureMatch::None, match);
CPPUNIT_ASSERT(!result);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::None == match);
CPPUNIT_ASSERT(!result);
//
types.emplace_back(llvm::Type::getInt1Ty(C)->getPointerTo());
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Size == match);
CPPUNIT_ASSERT(!result);
//
types[0] = llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Size == match);
CPPUNIT_ASSERT(!result);
//
types[0] = llvm::Type::getInt1Ty(C);
types.emplace_back(llvm::Type::getInt1Ty(C));
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::None == match);
CPPUNIT_ASSERT(!result);
//
// Test varying argument size function
// test explicit matching
group = axtestsize(C);
list = &group->list();
types.resize(2);
types[0] = llvm::Type::getDoubleTy(C);
types[1] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
//
types.resize(1);
types[0] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[1], result);
//
types.clear();
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[0], result);
// Test implicit matching
types.resize(2);
types[0] = llvm::Type::getFloatTy(C);
types[1] = llvm::Type::getInt32Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
// Test non matching
types.resize(3);
types[0] = llvm::Type::getDoubleTy(C);
types[1] = llvm::Type::getDoubleTy(C);
types[2] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::None == match);
CPPUNIT_ASSERT(!result);
//
// Test multi function
group = axtestmulti(C);
list = &group->list();
// test explicit/implicit matching
types.clear();
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[0], result);
//
types.resize(2);
types[0] = llvm::Type::getDoubleTy(C);
types[1] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
//
types[0] = llvm::Type::getInt32Ty(C);
types[1] = llvm::Type::getDoubleTy(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[3], result);
//
types[0] = llvm::Type::getInt32Ty(C);
types[1] = llvm::Type::getInt32Ty(C);
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[2], result);
//
types.resize(1);
types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo();
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[5], result);
//
types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo();
result = group->match(types, C, &match);
CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_EQUAL((*list)[6], result);
}
void
TestFunctionGroup::testExecute()
{
using openvdb::ax::codegen::LLVMType;
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::FunctionGroup;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::IRBuilder<> B(state.scratchBlock());
llvm::Value* result = nullptr;
llvm::CallInst* call = nullptr;
llvm::Function* target = nullptr;
std::vector<llvm::Value*> args;
// test execution
// test invalid arguments throws
FunctionGroup::Ptr group(new FunctionGroup("empty", "", {}));
CPPUNIT_ASSERT(!group->execute(/*args*/{}, B));
group = axtestscalar(C);
const std::vector<Function::Ptr>* list = &group->list();
CPPUNIT_ASSERT(!group->execute({}, B));
CPPUNIT_ASSERT(!group->execute({
B.getTrue(),
B.getTrue()
}, B));
args.resize(1);
// test llvm function calls - execute and get the called function.
// check this is already inserted into the module and is expected
// llvm::Function using create on the expected function signature
args[0] = B.getTrue();
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target);
//
args[0] = B.getInt16(1);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[4]->create(state.module()), target);
//
args[0] = B.getInt32(1);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[3]->create(state.module()), target);
//
args[0] = B.getInt64(1);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target);
//
args[0] = llvm::ConstantFP::get(llvm::Type::getFloatTy(C), 1.0f);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[1]->create(state.module()), target);
//
args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target);
//
// Test multi function
group = axtestmulti(C);
list = &group->list();
args.clear();
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target);
//
args.resize(1);
args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1));
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target);
//
args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2));
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[6]->create(state.module()), target);
//
args.resize(2);
args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0);
args[1] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0);
result = group->execute(args, B);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result));
call = llvm::cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
target = call->getCalledFunction();
CPPUNIT_ASSERT(target);
CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target);
}
| 18,078 | C++ | 30.829225 | 95 | 0.623797 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionRegistry.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <iostream>
#include "util.h"
#include <openvdb_ax/compiler/CompilerOptions.h>
#include <openvdb_ax/codegen/Functions.h>
#include <openvdb_ax/codegen/FunctionRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
class TestFunctionRegistry : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestFunctionRegistry);
CPPUNIT_TEST(testCreateAllVerify);
CPPUNIT_TEST_SUITE_END();
void testCreateAllVerify();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionRegistry);
void
TestFunctionRegistry::testCreateAllVerify()
{
openvdb::ax::codegen::FunctionRegistry::UniquePtr reg =
openvdb::ax::codegen::createDefaultRegistry();
openvdb::ax::FunctionOptions opts;
// check that no warnings are printed during registration
// @todo Replace this with a better logger once AX has one!
std::streambuf* sbuf = std::cerr.rdbuf();
try {
// Redirect cerr
std::stringstream buffer;
std::cerr.rdbuf(buffer.rdbuf());
reg->createAll(opts, true);
const std::string& result = buffer.str();
CPPUNIT_ASSERT_MESSAGE(result, result.empty());
}
catch (...) {
std::cerr.rdbuf(sbuf);
throw;
}
std::cerr.rdbuf(sbuf);
}
| 1,325 | C++ | 23.555555 | 64 | 0.686038 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestSymbolTable.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include <openvdb_ax/codegen/SymbolTable.h>
#include <cppunit/extensions/HelperMacros.h>
template <typename T>
using LLVMType = openvdb::ax::codegen::LLVMType<T>;
class TestSymbolTable : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestSymbolTable);
CPPUNIT_TEST(testSingleTable);
CPPUNIT_TEST(testTableBlocks);
CPPUNIT_TEST_SUITE_END();
void testSingleTable();
void testTableBlocks();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestSymbolTable);
void
TestSymbolTable::testSingleTable()
{
unittest_util::LLVMState state;
llvm::IRBuilder<> builder(state.scratchBlock());
llvm::Type* type = LLVMType<float>::get(state.context());
llvm::Value* value1 = builder.CreateAlloca(type);
llvm::Value* value2 = builder.CreateAlloca(type);
CPPUNIT_ASSERT(value1);
CPPUNIT_ASSERT(value2);
openvdb::ax::codegen::SymbolTable table;
CPPUNIT_ASSERT(table.map().empty());
CPPUNIT_ASSERT(table.insert("test", value1));
CPPUNIT_ASSERT(!table.insert("test", nullptr));
CPPUNIT_ASSERT(table.exists("test"));
CPPUNIT_ASSERT_EQUAL(value1, table.get("test"));
table.clear();
CPPUNIT_ASSERT(table.map().empty());
CPPUNIT_ASSERT(!table.exists("test"));
CPPUNIT_ASSERT(table.insert("test", value1));
CPPUNIT_ASSERT(table.replace("test", value2));
CPPUNIT_ASSERT(!table.replace("other", value2));
CPPUNIT_ASSERT(table.exists("test"));
CPPUNIT_ASSERT(table.exists("other"));
CPPUNIT_ASSERT_EQUAL(value2, table.get("test"));
CPPUNIT_ASSERT_EQUAL(value2, table.get("other"));
}
void
TestSymbolTable::testTableBlocks()
{
unittest_util::LLVMState state;
llvm::IRBuilder<> builder(state.scratchBlock());
llvm::Type* type = LLVMType<float>::get(state.context());
llvm::Value* value1 = builder.CreateAlloca(type);
llvm::Value* value2 = builder.CreateAlloca(type);
llvm::Value* value3 = builder.CreateAlloca(type);
llvm::Value* value4 = builder.CreateAlloca(type);
CPPUNIT_ASSERT(value1);
CPPUNIT_ASSERT(value2);
CPPUNIT_ASSERT(value3);
CPPUNIT_ASSERT(value4);
// test table insertion and erase
openvdb::ax::codegen::SymbolTableBlocks tables;
openvdb::ax::codegen::SymbolTable* table1 = &(tables.globals());
openvdb::ax::codegen::SymbolTable* table2 = tables.getOrInsert(0);
CPPUNIT_ASSERT_EQUAL(table1, table2);
table2 = &(tables.get(0));
CPPUNIT_ASSERT_EQUAL(table1, table2);
CPPUNIT_ASSERT_THROW(tables.erase(0), std::runtime_error);
tables.getOrInsert(1);
tables.getOrInsert(2);
tables.getOrInsert(4);
CPPUNIT_ASSERT_THROW(tables.get(3), std::runtime_error);
CPPUNIT_ASSERT(tables.erase(4));
CPPUNIT_ASSERT(tables.erase(2));
CPPUNIT_ASSERT(tables.erase(1));
tables.globals().insert("global1", value1);
tables.globals().insert("global2", value2);
// test find methods
llvm::Value* result = tables.find("global1");
CPPUNIT_ASSERT_EQUAL(value1, result);
result = tables.find("global2");
CPPUNIT_ASSERT_EQUAL(value2, result);
table1 = tables.getOrInsert(2);
table2 = tables.getOrInsert(4);
tables.getOrInsert(5);
// test multi table find methods
table1->insert("table_level_2", value3);
table2->insert("table_level_4", value4);
// test find second nested value
result = tables.find("table_level_2", 0);
CPPUNIT_ASSERT(!result);
result = tables.find("table_level_2", 1);
CPPUNIT_ASSERT(!result);
result = tables.find("table_level_2", 2);
CPPUNIT_ASSERT_EQUAL(value3, result);
// test find fourth nested value
result = tables.find("table_level_4", 0);
CPPUNIT_ASSERT(!result);
result = tables.find("table_level_4", 3);
CPPUNIT_ASSERT(!result);
result = tables.find("table_level_4", 4);
CPPUNIT_ASSERT_EQUAL(value4, result);
result = tables.find("table_level_4", 10000);
CPPUNIT_ASSERT_EQUAL(value4, result);
// test find fourth nested value with matching global name
tables.globals().insert("table_level_4", value1);
result = tables.find("table_level_4");
CPPUNIT_ASSERT_EQUAL(value4, result);
result = tables.find("table_level_4", 4);
CPPUNIT_ASSERT_EQUAL(value4, result);
result = tables.find("table_level_4", 3);
CPPUNIT_ASSERT_EQUAL(value1, result);
// test replace
CPPUNIT_ASSERT(tables.replace("table_level_4", value2));
result = tables.find("table_level_4");
CPPUNIT_ASSERT_EQUAL(value2, result);
// test global was not replaced
result = tables.find("table_level_4", 0);
CPPUNIT_ASSERT_EQUAL(value1, result);
CPPUNIT_ASSERT(!tables.replace("empty", nullptr));
}
| 4,781 | C++ | 27.295858 | 70 | 0.678101 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestComputeGeneratorFailures.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include "../util.h"
#include <openvdb_ax/compiler/CompilerOptions.h>
#include <openvdb_ax/compiler/Logger.h>
#include <openvdb_ax/codegen/FunctionRegistry.h>
#include <openvdb_ax/codegen/ComputeGenerator.h>
#include <openvdb_ax/ast/AST.h>
#include <cppunit/extensions/HelperMacros.h>
static const std::vector<std::string> tests {
// codegen errors
/// implicit narrow
"int a; vec2i b; a=b;",
"int a; vec3i b; a=b;",
"int a; vec4i b; a=b;",
"float a; vec2f b; a=b;",
"float a; vec3f b; a=b;",
"float a; vec4f b; a=b;",
"float a; mat3f b; a=b;",
"float a; mat4f b; a=b;",
"double a; vec2d b; a=b;",
"double a; vec3d b; a=b;",
"double a; vec4d b; a=b;",
"double a; mat3f b; a=b;",
"double a; mat4f b; a=b;",
/// unsupported bin ops
"float a; a << 1;",
"float a; a >> 1;",
"float a; a | 1;",
"float a; a ^ 1;",
"float a; a & 1;",
"double a; a << 1;",
"double a; a >> 1;",
"double a; a | 1;",
"double a; a ^ 1;",
"double a; a & 1;",
"mat3d a,b; a % b;",
"mat3d a,b; a & b;",
"mat3d a,b; a && b;",
"mat3d a,b; a << b;",
"mat3d a,b; a >> b;",
"mat3d a,b; a ^ b;",
"mat3d a,b; a || b;",
"mat3f a,b; a % b;",
"mat3f a,b; a & b;",
"mat3f a,b; a && b;",
"mat3f a,b; a << b;",
"mat3f a,b; a >> b;",
"mat3f a,b; a ^ b;",
"mat3f a,b; a || b;",
"mat4d a,b; a % b;",
"mat4d a,b; a & b;",
"mat4d a,b; a && b;",
"mat4d a,b; a << b;",
"mat4d a,b; a >> b;",
"mat4d a,b; a ^ b;",
"mat4d a,b; a || b;",
"string a,b; a & b;",
"string a,b; a && b;",
"string a,b; a - b;",
"string a,b; a << b;",
"string a,b; a >> b;",
"string a,b; a ^ b;",
"string a,b; a | b;",
"string a,b; a || b;",
"vec2d a,b; a & b;",
"vec2d a,b; a && b;",
"vec2d a,b; a << b;",
"vec2d a,b; a >> b;",
"vec2d a,b; a ^ b;",
"vec2d a,b; a | b;",
"vec2d a,b; a || b;",
"vec2f a,b; a & b;",
"vec2f a,b; a && b;",
"vec2f a,b; a << b;",
"vec2f a,b; a >> b;",
"vec2f a,b; a ^ b;",
"vec2f a,b; a | b;",
"vec2f a,b; a || b;",
"vec2i a,b; a & b;",
"vec2i a,b; a && b;",
"vec2i a,b; a << b;",
"vec2i a,b; a >> b;",
"vec2i a,b; a ^ b;",
"vec2i a,b; a | b;",
"vec2i a,b; a || b;",
"vec3d a,b; a & b;",
"vec3d a,b; a && b;",
"vec3d a,b; a << b;",
"vec3d a,b; a >> b;",
"vec3d a,b; a ^ b;",
"vec3d a,b; a | b;",
"vec3d a,b; a || b;",
"vec3f a,b; a & b;",
"vec3f a,b; a && b;",
"vec3f a,b; a << b;",
"vec3f a,b; a >> b;",
"vec3f a,b; a ^ b;",
"vec3f a,b; a | b;",
"vec3f a,b; a || b;",
"vec3i a,b; a & b;",
"vec3i a,b; a && b;",
"vec3i a,b; a << b;",
"vec3i a,b; a >> b;",
"vec3i a,b; a ^ b;",
"vec3i a,b; a | b;",
"vec3i a,b; a || b;",
"vec4d a,b; a & b;",
"vec4d a,b; a && b;",
"vec4d a,b; a << b;",
"vec4d a,b; a >> b;",
"vec4d a,b; a ^ b;",
"vec4d a,b; a ^ b;",
"vec4d a,b; a || b;",
"vec4f a,b; a & b;",
"vec4f a,b; a && b;",
"vec4f a,b; a << b;",
"vec4f a,b; a >> b;",
"vec4f a,b; a ^ b;",
"vec4f a,b; a | b;",
"vec4f a,b; a || b;",
"vec4i a,b; a & b;",
"vec4i a,b; a && b;",
"vec4i a,b; a << b;",
"vec4i a,b; a >> b;",
"vec4i a,b; a ^ b;",
"vec4i a,b; a | b;",
"vec4i a,b; a || b;",
/// invalid unary ops
"vec2f a; !a;",
"vec2d a; !a;",
"vec3d a; !a;",
"vec3f a; !a;",
"vec4f a; !a;",
"vec4d a; !a;",
"mat3f a; !a;",
"mat3d a; !a;",
"mat3f a; !a;",
"mat4d a; !a;",
"vec2f a; ~a;",
"vec2d a; ~a;",
"vec3d a; ~a;",
"vec3f a; ~a;",
"vec4f a; ~a;",
"vec4d a; ~a;",
"mat3f a; ~a;",
"mat3d a; ~a;",
"mat3f a; ~a;",
"mat4d a; ~a;",
/// missing function
"nonexistent();",
/// non/re declared
"a;",
"int a; int a;",
"{ int a; int a; }",
"int a, a;",
"a ? b : c;",
"a ? true : false;",
"true ? a : c;",
"true ? a : false;",
"true ? true : c;",
"a && b;",
"a && true;",
"true && b;",
/// invalid crement
"string a; ++a;",
"vec2f a; ++a;",
"vec3f a; ++a;",
"vec4f a; ++a;",
"mat3f a; ++a;",
"mat4f a; ++a;",
/// array size assignments
"vec2f a; vec3f b; a=b;",
"vec3f a; vec2f b; a=b;",
"vec4f a; vec3f b; a=b;",
"vec2d a; vec3d b; a=b;",
"vec3d a; vec2d b; a=b;",
"vec4d a; vec3d b; a=b;",
"vec2i a; vec3i b; a=b;",
"vec3i a; vec2i b; a=b;",
"vec4i a; vec3i b; a=b;",
"mat4f a; mat3f b; a=b;",
"mat4d a; mat3d b; a=b;",
/// string assignments
"string a = 1;",
"int a; string b; b=a;",
"float a; string b; b=a;",
"double a; string b; b=a;",
"vec3f a; string b; b=a;",
"mat3f a; string b; b=a;",
/// array index
"int a; a[0];",
"vec3f a; string b; a[b];",
"vec3f a; vec3f b; a[b];",
"vec3f a; mat3f b; a[b];",
"vec3f a; a[1,1];",
"mat3f a; vec3f b; a[b,1];",
"mat3f a; vec3f b; a[1,b];",
/// unsupported implicit casts/ops
"vec2f a; vec3f b; a*b;",
"vec3f a; vec4f b; a*b;",
"vec3f a; vec2f b; a*b;",
"vec2i a; vec3f b; a*b;",
"mat3f a; mat4f b; a*b;",
"string a; mat4f b; a*b;",
"int a; string b; a*b;",
"string a; string b; a*b;",
"string a; string b; a-b;",
"string a; string b; a/b;",
"~0.0f;",
"vec3f a; ~a;"
/// loops
"break;",
"continue;",
// ternary
"int a = true ? print(1) : print(2);",
"true ? print(1) : 1;",
"mat4d a; a ? 0 : 1;",
"mat4f a; a ? 0 : 1;",
"string a; a ? 0 : 1;",
"vec2d a; a ? 0 : 1;",
"vec2f a; a ? 0 : 1;",
"vec2i a; a ? 0 : 1;",
"vec3d a; a ? 0 : 1;",
"vec3f a; a ? 0 : 1;",
"vec3i a; a ? 0 : 1;",
"vec4d a; a ? 0 : 1;",
"vec4f a; a ? 0 : 1;",
"vec4i a; a ? 0 : 1;",
// "int a, b; (a ? b : 2) = 1;",
"true ? {1,2} : {1,2,3};",
"true ? \"foo\" : 1;",
"true ? 1.0f : \"foo\";",
"{1,1} && 1 ? true : false;",
"{1,1} ? true : false;",
"{1,1} && 1 ? \"foo\" : false;",
"\"foo\" ? true : false;",
"true ? {1,1} && 1: {1,1};",
"true ? {1,1} : {1,1} && 1;",
"string a; true ? a : 1;",
"string a; true ? 1.0f : a;",
// conditional
"mat4d a; if (a) 1;",
"mat4f a; if (a) 1;",
"string a; if (a) 1;",
"vec2d a; if (a) 1;",
"vec2f a; if (a) 1;",
"vec2i a; if (a) 1;",
"vec3d a; if (a) 1;",
"vec3f a; if (a) 1;",
"vec3i a; if (a) 1;",
"vec4d a; if (a) 1;",
"vec4f a; if (a) 1;",
"vec4i a; if (a) 1;",
"if ({1,1} && 1) 1;",
"if (true) {1,1} && 1;",
// loops
"mat4d a; for (;a;) 1;",
"mat4f a; for (;a;) 1;",
"string a; for (;a;) 1;",
"vec2d a; for (;a;) 1;",
"vec2f a; for (;a;) 1;",
"vec2i a; for (;a;) 1;",
"vec3d a; for (;a;) 1;",
"vec3f a; for (;a;) 1;",
"vec3i a; for (;a;) 1;",
"vec4d a; for (;a;) 1;",
"vec4f a; for (;a;) 1;",
"vec4i a; for (;a;) 1;",
"mat4d a; while (a) 1;",
"mat4f a; while (a) 1;",
"string a; while (a) 1;",
"vec2d a; while (a) 1;",
"vec2f a; while (a) 1;",
"vec2i a; while (a) 1;",
"vec3d a; while (a) 1;",
"vec3f a; while (a) 1;",
"vec3i a; while (a) 1;",
"vec4d a; while (a) 1;",
"vec4f a; while (a) 1;",
"vec4i a; while (a) 1;",
"mat4d a; do { 1; } while(a);",
"mat4f a; do { 1; } while(a);",
"string a; do { 1; } while(a);",
"vec2d a; do { 1; } while(a);",
"vec2f a; do { 1; } while(a);",
"vec2i a; do { 1; } while(a);",
"vec3d a; do { 1; } while(a);",
"vec3f a; do { 1; } while(a);",
"vec3i a; do { 1; } while(a);",
"vec4d a; do { 1; } while(a);",
"vec4f a; do { 1; } while(a);",
"vec4i a; do { 1; } while(a);",
// comma
"vec2i v; v++, 1;",
"vec2i v; 1, v++;"
};
class TestComputeGeneratorFailures : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestComputeGeneratorFailures);
CPPUNIT_TEST(testFailures);
CPPUNIT_TEST_SUITE_END();
void testFailures();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestComputeGeneratorFailures);
void
TestComputeGeneratorFailures::testFailures()
{
openvdb::ax::FunctionOptions opts;
openvdb::ax::codegen::FunctionRegistry reg;
// create logger that suppresses all messages, but still logs number of errors/warnings
openvdb::ax::Logger logger([](const std::string&) {});
logger.setMaxErrors(1);
for (const auto& code : tests) {
const openvdb::ax::ast::Tree::ConstPtr ast =
openvdb::ax::ast::parse(code.c_str(), logger);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to parse", code), ast.get());
unittest_util::LLVMState state;
openvdb::ax::codegen::codegen_internal::ComputeGenerator gen(state.module(), opts, reg, logger);
gen.generate(*ast);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected Compiler Error", code), logger.hasError());
logger.clear();
}
}
| 9,126 | C++ | 25.609329 | 104 | 0.446198 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionTypes.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include <openvdb_ax/codegen/FunctionTypes.h>
#include <cppunit/extensions/HelperMacros.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#include <sstream>
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// @brief Dummy derived function which implemented types
struct TestFunction : public openvdb::ax::codegen::Function
{
static_assert(std::has_virtual_destructor
<openvdb::ax::codegen::Function>::value,
"Base class destructor is not virtual");
TestFunction(const std::vector<llvm::Type*>& types,
llvm::Type* ret,
const std::string& symbol)
: openvdb::ax::codegen::Function(types.size(), symbol)
, mTypes(types), mRet(ret) {}
~TestFunction() override {}
llvm::Type* types(std::vector<llvm::Type*>& types,
llvm::LLVMContext&) const override {
types = mTypes;
return mRet;
}
const std::vector<llvm::Type*> mTypes;
llvm::Type* mRet;
};
/// @brief Dummy derived IR function which implemented types and
/// forwards on the generator
struct TestIRFunction : public openvdb::ax::codegen::IRFunctionBase
{
static_assert(std::has_virtual_destructor
<openvdb::ax::codegen::IRFunctionBase>::value,
"Base class destructor is not virtual");
TestIRFunction(const std::vector<llvm::Type*>& types,
llvm::Type* ret,
const std::string& symbol,
const openvdb::ax::codegen::IRFunctionBase::GeneratorCb& gen)
: openvdb::ax::codegen::IRFunctionBase(symbol, gen, types.size())
, mTypes(types), mRet(ret) {}
~TestIRFunction() override {}
llvm::Type* types(std::vector<llvm::Type*>& types,
llvm::LLVMContext&) const override {
types = mTypes;
return mRet;
}
const std::vector<llvm::Type*> mTypes;
llvm::Type* mRet;
};
/// @brief static function to test c binding addresses
struct CBindings
{
static void voidfunc() {}
static int16_t scalarfunc(bool,int16_t,int32_t,int64_t,float,double) { return int16_t(); }
static int32_t scalatptsfunc(bool*,int16_t*,int32_t*,int64_t*,float*,double*) { return int32_t(); }
static int64_t arrayfunc(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6]) { return int64_t(); }
static void multiptrfunc(void*, void**, void***, float*, float**, float***) { }
template <typename Type> static inline Type tmplfunc() { return Type(); }
};
/// @brief Helper method to finalize a function (with a terminator)
/// If F is nullptr, finalizes the current function
inline llvm::Instruction*
finalizeFunction(llvm::IRBuilder<>& B, llvm::Function* F = nullptr)
{
auto IP = B.saveIP();
if (F) {
if (F->empty()) {
B.SetInsertPoint(llvm::BasicBlock::Create(B.getContext(), "", F));
}
else {
B.SetInsertPoint(&(F->getEntryBlock()));
}
}
llvm::Instruction* ret = B.CreateRetVoid();
B.restoreIP(IP);
return ret;
}
/// @brief Defines to wrap the verification of IR
#define VERIFY_FUNCTION_IR(Function) { \
std::string error; llvm::raw_string_ostream os(error); \
const bool valid = !llvm::verifyFunction(*Function, &os); \
CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \
}
#define VERIFY_MODULE_IR(Module) { \
std::string error; llvm::raw_string_ostream os(error); \
const bool valid = !llvm::verifyModule(*Module, &os); \
CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \
}
#define VERIFY_MODULE_IR_INVALID(Module) { \
const bool valid = llvm::verifyModule(*Module); \
CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \
}
#define VERIFY_FUNCTION_IR_INVALID(Function) { \
const bool valid = llvm::verifyFunction(*Function); \
CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class TestFunctionTypes : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestFunctionTypes);
CPPUNIT_TEST(testLLVMTypesFromSignature);
CPPUNIT_TEST(testLLVMFunctionTypeFromSignature);
CPPUNIT_TEST(testPrintSignature);
// Test Function::create, Function::types and other base methods
CPPUNIT_TEST(testFunctionCreate);
// Test Function::call
CPPUNIT_TEST(testFunctionCall);
// Test Function::match
CPPUNIT_TEST(testFunctionMatch);
// Test derived CFunctions, mainly CFunction::create and CFunction::types
CPPUNIT_TEST(testCFunctions);
// Test C constant folding
CPPUNIT_TEST(testCFunctionCF);
// Test derived IR Function, IRFunctionBase::create and IRFunctionBase::call
CPPUNIT_TEST(testIRFunctions);
// Test SRET methods for both C and IR functions
CPPUNIT_TEST(testSRETFunctions);
CPPUNIT_TEST_SUITE_END();
void testLLVMTypesFromSignature();
void testLLVMFunctionTypeFromSignature();
void testPrintSignature();
void testFunctionCreate();
void testFunctionCall();
void testFunctionMatch();
void testCFunctions();
void testCFunctionCF();
void testIRFunctions();
void testSRETFunctions();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionTypes);
void
TestFunctionTypes::testLLVMTypesFromSignature()
{
using openvdb::ax::codegen::llvmTypesFromSignature;
unittest_util::LLVMState state;
llvm::Type* type = nullptr;
std::vector<llvm::Type*> types;
type = llvmTypesFromSignature<void()>(state.context());
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
type = llvmTypesFromSignature<void()>(state.context(), &types);
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
CPPUNIT_ASSERT(types.empty());
type = llvmTypesFromSignature<float()>(state.context(), &types);
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isFloatTy());
CPPUNIT_ASSERT(types.empty());
type = llvmTypesFromSignature<float(double, int64_t, float(*)[3])>(state.context(), &types);
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isFloatTy());
CPPUNIT_ASSERT_EQUAL(size_t(3), types.size());
CPPUNIT_ASSERT(types[0]->isDoubleTy());
CPPUNIT_ASSERT(types[1]->isIntegerTy(64));
CPPUNIT_ASSERT(types[2]->isPointerTy());
type = types[2]->getPointerElementType();
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isArrayTy());
type = type->getArrayElementType();
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isFloatTy());
}
void
TestFunctionTypes::testLLVMFunctionTypeFromSignature()
{
using openvdb::ax::codegen::llvmFunctionTypeFromSignature;
unittest_util::LLVMState state;
llvm::FunctionType* ftype = nullptr;
std::vector<llvm::Type*> types;
ftype = llvmFunctionTypeFromSignature<void()>(state.context());
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams());
ftype = llvmFunctionTypeFromSignature<float(double, int64_t, float(*)[3])>(state.context());
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy());
CPPUNIT_ASSERT_EQUAL(3u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0)->isDoubleTy());
CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(64));
CPPUNIT_ASSERT(ftype->getParamType(2)->isPointerTy());
llvm::Type* type = ftype->getParamType(2)->getPointerElementType();
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isArrayTy());
type = type->getArrayElementType();
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isFloatTy());
}
void
TestFunctionTypes::testPrintSignature()
{
using openvdb::ax::codegen::printSignature;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
std::vector<llvm::Type*> types;
const llvm::Type* vt = llvm::Type::getVoidTy(C);
std::ostringstream os;
printSignature(os, types, vt);
CPPUNIT_ASSERT(os.str() == "void()");
os.str("");
types.emplace_back(llvm::Type::getInt32Ty(C));
types.emplace_back(llvm::Type::getInt64Ty(C));
printSignature(os, types, vt);
CPPUNIT_ASSERT_EQUAL(std::string("void(i32; i64)"), os.str());
os.str("");
printSignature(os, types, vt, "test");
CPPUNIT_ASSERT_EQUAL(std::string("void test(i32; i64)"), os.str());
os.str("");
printSignature(os, types, vt, "", {"one"}, true);
CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64)"), os.str());
os.str("");
printSignature(os, types, vt, "", {"one", "two"}, true);
CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64 two)"), os.str());
os.str("");
printSignature(os, types, vt, "1", {"one", "two", "three"}, true);
CPPUNIT_ASSERT_EQUAL(std::string("void 1(int32 one; int64 two)"), os.str());
os.str("");
printSignature(os, types, vt, "1", {"", "two"}, false);
CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str());
os.str("");
printSignature(os, types, vt, "1", {"", "two"}, false);
CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str());
os.str("");
types.emplace_back(llvm::Type::getInt8PtrTy(C));
types.emplace_back(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3));
printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"}, true);
CPPUNIT_ASSERT_EQUAL(std::string("int64 test(int32; int64 two; i8*; vec3i)"), os.str());
os.str("");
types.clear();
printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"});
CPPUNIT_ASSERT_EQUAL(std::string("i64 test()"), os.str());
os.str("");
}
void
TestFunctionTypes::testFunctionCreate()
{
using openvdb::ax::codegen::Function;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Module& M = state.module();
std::vector<llvm::Type*> types;
llvm::Type* type = nullptr;
std::ostringstream os;
Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)},
llvm::Type::getVoidTy(C), "ax.test"));
// test types
type = test->types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(1), types.size());
CPPUNIT_ASSERT(types[0]->isIntegerTy(32));
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
// test various getters
CPPUNIT_ASSERT_EQUAL(std::string("ax.test"), std::string(test->symbol()));
CPPUNIT_ASSERT_EQUAL(size_t(1), test->size());
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0)));
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1)));
// test create
llvm::Function* function = test->create(C);
// additional create call should create a new function
CPPUNIT_ASSERT(function != test->create(C));
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size());
llvm::FunctionType* ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32));
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.test"));
function = test->create(M);
// additional call should match
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.test"));
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32));
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test print
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("void name(int32)"), os.str());
//
// Test empty signature
test.reset(new TestFunction({}, llvm::Type::getInt32Ty(C), "ax.empty.test"));
types.clear();
// test types
type = test->types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(0), types.size());
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isIntegerTy(32));
// test various getters
CPPUNIT_ASSERT_EQUAL(std::string("ax.empty.test"), std::string(test->symbol()));
CPPUNIT_ASSERT_EQUAL(size_t(0), test->size());
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0)));
// test create
function = test->create(C);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(0), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32));
CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.empty.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.empty.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.empty.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
// test print
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("int32 name()"), os.str());
//
// Test scalar types
test.reset(new TestFunction({
llvm::Type::getInt1Ty(C),
llvm::Type::getInt16Ty(C),
llvm::Type::getInt32Ty(C),
llvm::Type::getInt64Ty(C),
llvm::Type::getFloatTy(C),
llvm::Type::getDoubleTy(C),
},
llvm::Type::getInt16Ty(C), "ax.scalars.test"));
types.clear();
CPPUNIT_ASSERT_EQUAL(std::string("ax.scalars.test"), std::string(test->symbol()));
type = test->types(types, state.context());
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isIntegerTy(16));
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0]->isIntegerTy(1));
CPPUNIT_ASSERT(types[1]->isIntegerTy(16));
CPPUNIT_ASSERT(types[2]->isIntegerTy(32));
CPPUNIT_ASSERT(types[3]->isIntegerTy(64));
CPPUNIT_ASSERT(types[4]->isFloatTy());
CPPUNIT_ASSERT(types[5]->isDoubleTy());
// test create
function = test->create(C);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(16));
CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(1));
CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(16));
CPPUNIT_ASSERT(ftype->getParamType(2)->isIntegerTy(32));
CPPUNIT_ASSERT(ftype->getParamType(3)->isIntegerTy(64));
CPPUNIT_ASSERT(ftype->getParamType(4)->isFloatTy());
CPPUNIT_ASSERT(ftype->getParamType(5)->isDoubleTy());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.scalars.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.scalars.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalars.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
// test print
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("int16 name(bool; int16; int32; int64; float; double)"), os.str());
//
// Test scalar ptrs types
test.reset(new TestFunction({
llvm::Type::getInt1Ty(C)->getPointerTo(),
llvm::Type::getInt16Ty(C)->getPointerTo(),
llvm::Type::getInt32Ty(C)->getPointerTo(),
llvm::Type::getInt64Ty(C)->getPointerTo(),
llvm::Type::getFloatTy(C)->getPointerTo(),
llvm::Type::getDoubleTy(C)->getPointerTo()
},
llvm::Type::getInt32Ty(C), "ax.scalarptrs.test"));
types.clear();
CPPUNIT_ASSERT_EQUAL(std::string("ax.scalarptrs.test"), std::string(test->symbol()));
type = test->types(types, C);
CPPUNIT_ASSERT(type->isIntegerTy(32));
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo());
// test create
function = test->create(C);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32));
CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getInt1Ty(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getInt16Ty(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getInt32Ty(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getInt64Ty(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getDoubleTy(C)->getPointerTo());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.scalarptrs.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.scalarptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalarptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
//
// Test array ptrs types
test.reset(new TestFunction({
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d
},
llvm::Type::getInt64Ty(C), "ax.arrayptrs.test"));
types.clear();
type = test->types(types, C);
CPPUNIT_ASSERT(type->isIntegerTy(64));
CPPUNIT_ASSERT_EQUAL(size_t(15), types.size());
CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo());
CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo());
CPPUNIT_ASSERT(types[6] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo());
CPPUNIT_ASSERT(types[7] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo());
CPPUNIT_ASSERT(types[8] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo());
CPPUNIT_ASSERT(types[9] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo());
CPPUNIT_ASSERT(types[10] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo());
CPPUNIT_ASSERT(types[11] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo());
CPPUNIT_ASSERT(types[12] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo());
CPPUNIT_ASSERT(types[13] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo());
CPPUNIT_ASSERT(types[14] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo());
// test create
function = test->create(C);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(15), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(64));
CPPUNIT_ASSERT_EQUAL(15u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(6) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(7) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(8) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(9) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(10) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(11) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(12) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(13) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(14) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.arrayptrs.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.arrayptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.arrayptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
// test print - note mat/i types are not ax types
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("int64 name(vec2i; vec2f; vec2d; vec3i; vec3f; vec3d;"
" vec4i; vec4f; vec4d; [9 x i32]*; mat3f; mat3d; [16 x i32]*; mat4f; mat4d)"),
os.str());
//
// Test void ptr arguments
test.reset(new TestFunction({
llvm::Type::getVoidTy(C)->getPointerTo(),
llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo(),
llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo(),
llvm::Type::getFloatTy(C)->getPointerTo(),
llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(),
llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()
},
llvm::Type::getVoidTy(C), "ax.vptrs.test"));
types.clear();
// Note that C++ bindings will convert void* to i8* but they should be
// unmodified in this example where we use the derived TestFunction
type = test->types(types, C);
CPPUNIT_ASSERT(type->isVoidTy());
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::Type::getVoidTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[1] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo());
// test create
function = test->create(C);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getVoidTy(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// test create with a module (same as above, but check inserted into M)
CPPUNIT_ASSERT(!M.getFunction("ax.vptrs.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.vptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.vptrs.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
//
// Test creation with builder methods
// @note These methods may be moved to the constructor in the future
CPPUNIT_ASSERT(test->dependencies().empty());
CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::ReadOnly));
CPPUNIT_ASSERT(!test->hasParamAttribute(-1, llvm::Attribute::ReadOnly));
test->setDependencies({"dep"});
CPPUNIT_ASSERT_EQUAL(size_t(1), test->dependencies().size());
CPPUNIT_ASSERT_EQUAL(std::string("dep"), std::string(test->dependencies().front()));
test->setDependencies({});
CPPUNIT_ASSERT(test->dependencies().empty());
test->setFnAttributes({llvm::Attribute::ReadOnly});
test->setRetAttributes({llvm::Attribute::NoAlias});
test->setParamAttributes(1, {llvm::Attribute::WriteOnly});
test->setParamAttributes(-1, {llvm::Attribute::WriteOnly});
CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::WriteOnly));
CPPUNIT_ASSERT(!test->hasParamAttribute(2, llvm::Attribute::WriteOnly));
CPPUNIT_ASSERT(test->hasParamAttribute(1, llvm::Attribute::WriteOnly));
CPPUNIT_ASSERT(test->hasParamAttribute(-1, llvm::Attribute::WriteOnly));
function = test->create(C);
CPPUNIT_ASSERT(function);
llvm::AttributeList list = function->getAttributes();
CPPUNIT_ASSERT(!list.isEmpty());
CPPUNIT_ASSERT(!list.hasParamAttrs(0));
CPPUNIT_ASSERT(!list.hasParamAttrs(2));
CPPUNIT_ASSERT(list.hasParamAttr(1, llvm::Attribute::WriteOnly));
CPPUNIT_ASSERT(list.hasFnAttribute(llvm::Attribute::ReadOnly));
CPPUNIT_ASSERT(list.hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias));
}
void
TestFunctionTypes::testFunctionCall()
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::LLVMType;
using openvdb::ax::AXString;
//
{
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Module& M = state.module();
llvm::IRBuilder<> B(state.scratchBlock());
llvm::Function* BaseFunction = B.GetInsertBlock()->getParent();
Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)},
llvm::Type::getVoidTy(C), "ax.test"));
llvm::Function* function = test->create(M);
llvm::Value* arg = B.getInt32(1);
llvm::Value* result = test->call({arg}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0));
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
// add a ret void to the current function and to the created function,
// then check the IR is valid (this will check the function arguments
// and creation are all correct)
finalizeFunction(B);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
VERIFY_MODULE_IR(&M);
}
{
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Module& M = state.module();
llvm::IRBuilder<> B(state.scratchBlock());
llvm::Function* BaseFunction = B.GetInsertBlock()->getParent();
Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)},
llvm::Type::getVoidTy(C), "ax.test"));
// call first, then create
llvm::Value* arg = B.getInt32(1);
llvm::Value* result = test->call({arg}, B, /*cast*/false);
llvm::Function* function = test->create(M);
CPPUNIT_ASSERT(result);
llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0));
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
// add a ret void to the current function and to the created function,
// then check the IR is valid (this will check the function arguments
// and creation are all correct)
finalizeFunction(B);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
VERIFY_MODULE_IR(&M);
}
// Now test casting/argument mismatching for most argument types
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Module& M = state.module();
llvm::IRBuilder<> B(state.scratchBlock());
Function::Ptr test(new TestFunction({
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d
llvm::Type::getInt32Ty(C), // int
llvm::Type::getInt64Ty(C), // int64
llvm::Type::getFloatTy(C) // float
},
llvm::Type::getVoidTy(C),
"ax.test"));
std::vector<llvm::Type*> expected;
test->types(expected, C);
// default args
llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float
llvm::Value* d64c0 = LLVMType<double>::get(C, 0.0); // double
llvm::Value* i32c1 = B.getInt32(1); // int
llvm::Value* i64c1 = B.getInt64(1); // int64
llvm::Value* vec3i = openvdb::ax::codegen::arrayPack({i32c1,i32c1,i32c1}, B); // vec3i
llvm::Value* vec2d = openvdb::ax::codegen::arrayPack({d64c0,d64c0},B); // vec2d
llvm::Value* mat3d = openvdb::ax::codegen::arrayPack({ d64c0,d64c0,d64c0,
d64c0,d64c0,d64c0,
d64c0,d64c0,d64c0
}, B); // mat3d
std::vector<llvm::Value*> args{vec3i, vec2d, mat3d, i32c1, i64c1, f32c0};
llvm::Function* function = test->create(M);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
// also finalize the current module function, but set the inset point
// just above it so we can continue to verify IR during this test
llvm::Value* inst = B.CreateRetVoid();
// This specifies that created instructions should be inserted before
// the specified instruction.
B.SetInsertPoint(llvm::cast<llvm::Instruction>(inst));
// test no casting needed for valid IR
llvm::Value* result = test->call(args, B, /*cast*/false);
CPPUNIT_ASSERT(result);
llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1));
CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2));
CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3));
CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4));
CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5));
VERIFY_MODULE_IR(&M);
// test no casting needed for valid IR, even with cast=true
result = test->call(args, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1));
CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2));
CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3));
CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4));
CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5));
VERIFY_MODULE_IR(&M);
//
// Test different types of valid casting
llvm::Value* i1c0 = LLVMType<bool>::get(C, true); // bool
llvm::Value* vec3f = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f
llvm::Value* vec3d = openvdb::ax::codegen::arrayPack({d64c0,d64c0,d64c0}, B); // vec3d
llvm::Value* vec2f = openvdb::ax::codegen::arrayPack({f32c0,f32c0},B); // vec2f
llvm::Value* vec2i = openvdb::ax::codegen::arrayPack({i32c1,i32c1},B); // vecid
llvm::Value* mat3f = openvdb::ax::codegen::arrayPack({ f32c0,f32c0,f32c0,
f32c0,f32c0,f32c0,
f32c0,f32c0,f32c0
}, B); // mat3f
//
std::vector<llvm::Value*> argsToCast;
argsToCast.emplace_back(vec3f); // vec3f
argsToCast.emplace_back(vec2f); // vec2f
argsToCast.emplace_back(mat3f); // mat3f
argsToCast.emplace_back(i1c0); // bool
argsToCast.emplace_back(i1c0); // bool
argsToCast.emplace_back(i1c0); // bool
result = test->call(argsToCast, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0));
CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1));
CPPUNIT_ASSERT(argsToCast[2] != call->getArgOperand(2));
CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3));
CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4));
CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5));
CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType());
CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType());
CPPUNIT_ASSERT(expected[2] == call->getArgOperand(2)->getType());
CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType());
CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType());
CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType());
VERIFY_MODULE_IR(&M);
//
argsToCast.clear();
argsToCast.emplace_back(vec3d); // vec3d
argsToCast.emplace_back(vec2i); // vec2i
argsToCast.emplace_back(mat3d); // mat3d - no cast required
argsToCast.emplace_back(f32c0); // float
argsToCast.emplace_back(f32c0); // float
argsToCast.emplace_back(f32c0); // float - no cast required
result = test->call(argsToCast, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0));
CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1));
CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2));
CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3));
CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4));
CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5));
CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType());
CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType());
CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType());
CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType());
VERIFY_MODULE_IR(&M);
//
argsToCast.clear();
argsToCast.emplace_back(vec3i); // vec3i - no cast required
argsToCast.emplace_back(vec2d); // vec2d - no cast required
argsToCast.emplace_back(mat3d); // mat3d - no cast required
argsToCast.emplace_back(i64c1); // int64
argsToCast.emplace_back(i64c1); // int64 - no cast required
argsToCast.emplace_back(i64c1); // int64
result = test->call(argsToCast, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1));
CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2));
CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3));
CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4));
CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5));
CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType());
CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType());
VERIFY_MODULE_IR(&M);
//
// Test that invalid IR is generated if casting cannot be performed.
// This is just to test that call doesn't error or behave unexpectedly
// Test called with castable arg but cast is false. Test arg is left
// unchanged and IR is invalid due to signature size
result = test->call({vec3f}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
// should be the same as cast is false
CPPUNIT_ASSERT(vec3f == call->getArgOperand(0));
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
// Test called with castable arg with cast true. Test IR is invalid
// due to signature size
result = test->call({vec3f}, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
// shouldn't be the same as it should have been cast
CPPUNIT_ASSERT(vec3f != call->getArgOperand(0));
CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType());
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
// Test called with non castable args, but matchign signature size.
// Test IR is invalid due to cast being off
result = test->call(argsToCast, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands());
// no casting, args should match operands
CPPUNIT_ASSERT(argsToCast[0] == call->getArgOperand(0));
CPPUNIT_ASSERT(argsToCast[1] == call->getArgOperand(1));
CPPUNIT_ASSERT(argsToCast[2] == call->getArgOperand(2));
CPPUNIT_ASSERT(argsToCast[3] == call->getArgOperand(3));
CPPUNIT_ASSERT(argsToCast[4] == call->getArgOperand(4));
CPPUNIT_ASSERT(argsToCast[5] == call->getArgOperand(5));
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
//
// Test strings
llvm::Type* axstr = LLVMType<AXString*>::get(C); // str*
llvm::Type* chars = LLVMType<char*>::get(C); // char*
// build values
llvm::Value* chararray = B.CreateGlobalStringPtr("tmp"); // char*
llvm::Constant* constLoc = llvm::cast<llvm::Constant>(chararray);
llvm::Constant* size = LLVMType<AXString::SizeType>::get(C, static_cast<AXString::SizeType>(3));
llvm::Value* constStr = LLVMType<AXString>::get(C, constLoc, size);
llvm::Value* strptr = B.CreateAlloca(LLVMType<AXString>::get(C));
B.CreateStore(constStr, strptr);
// void ax.str.test(AXString*, char*)
test.reset(new TestFunction({axstr, chars},
llvm::Type::getVoidTy(C),
"ax.str.test"));
std::vector<llvm::Value*> stringArgs{strptr, chararray};
function = test->create(M);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
result = test->call(stringArgs, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0));
CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1));
//
result = test->call(stringArgs, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0));
CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1));
// Test AXString -> char*
stringArgs[0] = strptr;
stringArgs[1] = strptr;
result = test->call(stringArgs, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0));
CPPUNIT_ASSERT(stringArgs[1] != call->getArgOperand(1));
CPPUNIT_ASSERT(chars == call->getArgOperand(1)->getType());
VERIFY_MODULE_IR(&M);
// Test char* does not catch to AXString
stringArgs[0] = chararray;
stringArgs[1] = chararray;
result = test->call(stringArgs, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
// no valid casting
CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0));
CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1));
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
//
// Test ** pointers
test.reset(new TestFunction({
llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(),
llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo()
},
llvm::Type::getVoidTy(C),
"ax.ptrs.test"));
function = test->create(M);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
llvm::Value* fptr = B.CreateAlloca(llvm::Type::getFloatTy(C)->getPointerTo());
llvm::Value* dptr = B.CreateAlloca(llvm::Type::getDoubleTy(C)->getPointerTo());
result = test->call({fptr, dptr}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT(fptr == call->getArgOperand(0));
CPPUNIT_ASSERT(dptr == call->getArgOperand(1));
VERIFY_MODULE_IR(&M);
//
result = test->call({fptr, dptr}, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT(fptr == call->getArgOperand(0));
CPPUNIT_ASSERT(dptr == call->getArgOperand(1));
VERIFY_MODULE_IR(&M);
// switch the points, check no valid casting
result = test->call({dptr, fptr}, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
// args unaltered as casting is invalid
CPPUNIT_ASSERT(dptr == call->getArgOperand(0));
CPPUNIT_ASSERT(fptr == call->getArgOperand(1));
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
//
// Test void pointers
test.reset(new TestFunction({
LLVMType<void*>::get(C),
},
llvm::Type::getVoidTy(C),
"ax.void.test"));
function = test->create(M);
finalizeFunction(B, function);
VERIFY_FUNCTION_IR(function);
llvm::Value* vptrptr = B.CreateAlloca(LLVMType<void*>::get(C));
llvm::Value* vptr = B.CreateLoad(vptrptr);
result = test->call({vptr}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
CPPUNIT_ASSERT(vptr == call->getArgOperand(0));
VERIFY_MODULE_IR(&M);
//
result = test->call({vptr}, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
CPPUNIT_ASSERT(vptr == call->getArgOperand(0));
VERIFY_MODULE_IR(&M);
// verify no cast from other pointers to void*
result = test->call({fptr}, B, /*cast*/true);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands());
CPPUNIT_ASSERT(fptr == call->getArgOperand(0));
VERIFY_MODULE_IR_INVALID(&M);
// Remove the bad instruction (and re-verify to double check)
call->eraseFromParent();
VERIFY_MODULE_IR(&M);
}
void
TestFunctionTypes::testFunctionMatch()
{
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::LLVMType;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
Function::SignatureMatch match;
const std::vector<llvm::Type*> scalars {
llvm::Type::getInt1Ty(C), // bool
llvm::Type::getInt16Ty(C), // int16
llvm::Type::getInt32Ty(C), // int
llvm::Type::getInt64Ty(C), // int64
llvm::Type::getFloatTy(C), // float
llvm::Type::getDoubleTy(C) // double
};
const std::vector<llvm::Type*> array2 {
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo() // vec2d
};
const std::vector<llvm::Type*> array3 {
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo() // vec3d
};
const std::vector<llvm::Type*> array4 {
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec3i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo() // vec3d
};
const std::vector<llvm::Type*> array9 {
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo() // mat3d
};
const std::vector<llvm::Type*> array16 {
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d
};
const std::vector<std::vector<llvm::Type*>> arrays {
array2,
array3,
array4,
array9,
array16,
};
// test empty explicit match
Function::Ptr test(new TestFunction({},
llvm::Type::getVoidTy(C), "ax.test"));
match = test->match({}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
//
std::vector<llvm::Type*> types;
types.insert(types.end(), scalars.begin(), scalars.end());
types.insert(types.end(), array2.begin(), array2.end());
types.insert(types.end(), array3.begin(), array3.end());
types.insert(types.end(), array4.begin(), array4.end());
types.insert(types.end(), array9.begin(), array9.end());
types.insert(types.end(), array16.begin(), array16.end());
types.insert(types.end(), LLVMType<openvdb::ax::AXString*>::get(C));
// check types are unique
CPPUNIT_ASSERT_EQUAL(std::set<llvm::Type*>(types.begin(), types.end()).size(), types.size());
//
test.reset(new TestFunction({
llvm::Type::getInt1Ty(C), // bool
llvm::Type::getInt16Ty(C), // int16
llvm::Type::getInt32Ty(C), // int32
llvm::Type::getInt64Ty(C), // int64
llvm::Type::getFloatTy(C), // float
llvm::Type::getDoubleTy(C), // double
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d
llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax)
llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat4f
llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo(), // mat4d
LLVMType<openvdb::ax::AXString*>::get(C) // string
},
llvm::Type::getVoidTy(C),
"ax.test"));
match = test->match(types, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
// test size match
llvm::Type* i32t = llvm::Type::getInt32Ty(C);
test.reset(new TestFunction({i32t},
llvm::Type::getVoidTy(C), "ax.test"));
match = test->match({llvm::ArrayType::get(i32t, 1)->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Size);
match = test->match({i32t->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Size);
// test no match
match = test->match({}, C);
CPPUNIT_ASSERT_EQUAL(Function::None, match);
match = test->match({i32t, i32t}, C);
CPPUNIT_ASSERT_EQUAL(Function::None, match);
// test scalar matches
for (size_t i = 0; i < scalars.size(); ++i) {
test.reset(new TestFunction({scalars[i]}, llvm::Type::getVoidTy(C), "ax.test"));
std::vector<llvm::Type*> copy(scalars);
std::swap(copy[i], copy.back());
copy.pop_back();
CPPUNIT_ASSERT_EQUAL(size_t(5), copy.size());
CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({scalars[i]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[2]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[3]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[4]}, C));
}
//
// Test array matches - no implicit cast as operands are not marked as readonly
for (const std::vector<llvm::Type*>& types : arrays) {
// test these array types
for (size_t i = 0; i < types.size(); ++i) {
test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test"));
std::vector<llvm::Type*> copy(types);
std::swap(copy[i], copy.back());
copy.pop_back();
CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size());
CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[0]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[1]}, C));
// test non matching size arrays
for (const std::vector<llvm::Type*>& inputs : arrays) {
if (&types == &inputs) continue;
for (size_t i = 0; i < inputs.size(); ++i) {
CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C));
}
}
}
}
//
// Test array matches with readonly marking
for (const std::vector<llvm::Type*>& types : arrays) {
// test these array types
for (size_t i = 0; i < types.size(); ++i) {
test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test"));
test->setParamAttributes(0, {llvm::Attribute::ReadOnly});
std::vector<llvm::Type*> copy(types);
std::swap(copy[i], copy.back());
copy.pop_back();
CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size());
CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C));
CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C));
// test non matching size arrays
for (const std::vector<llvm::Type*>& inputs : arrays) {
if (&types == &inputs) continue;
for (size_t i = 0; i < inputs.size(); ++i) {
CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C));
}
}
}
}
// test strings
test.reset(new TestFunction({LLVMType<char*>::get(C)},
llvm::Type::getVoidTy(C), "ax.test"));
CPPUNIT_ASSERT_EQUAL(Function::Size,
test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C));
CPPUNIT_ASSERT_EQUAL(Function::Explicit,
test->match({LLVMType<char*>::get(C)}, C));
test->setParamAttributes(0, {llvm::Attribute::ReadOnly});
CPPUNIT_ASSERT_EQUAL(Function::Implicit,
test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C));
test.reset(new TestFunction({LLVMType<openvdb::ax::AXString*>::get(C)},
llvm::Type::getVoidTy(C), "ax.test"));
CPPUNIT_ASSERT_EQUAL(Function::Size,
test->match({LLVMType<char*>::get(C)}, C));
// test pointers
llvm::Type* fss = llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo();
llvm::Type* dss = llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo();
test.reset(new TestFunction({fss, dss},
llvm::Type::getVoidTy(C),
"ax.ptrs.test"));
CPPUNIT_ASSERT_EQUAL(Function::Explicit,
test->match({fss, dss}, C));
CPPUNIT_ASSERT_EQUAL(Function::Size,
test->match({fss, fss}, C));
// Even if pointers are marked as readonly, casting is not supported
test->setParamAttributes(0, {llvm::Attribute::ReadOnly});
test->setParamAttributes(1, {llvm::Attribute::ReadOnly});
CPPUNIT_ASSERT_EQUAL(Function::Size,
test->match({fss, fss}, C));
}
void
TestFunctionTypes::testCFunctions()
{
using openvdb::ax::codegen::CFunction;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Type* returnType = nullptr;
std::vector<llvm::Type*> types;
// test basic creation
CFunction<void()> voidfunc("voidfunc", &CBindings::voidfunc);
CFunction<int16_t(bool,int16_t,int32_t,int64_t,float,double)>
scalars("scalarfunc", &CBindings::scalarfunc);
CFunction<int32_t(bool*,int16_t*,int32_t*,int64_t*,float*,double*)>
scalarptrs("scalatptsfunc", &CBindings::scalatptsfunc);
CFunction<int64_t(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6])>
arrayptrs("arrayfunc", &CBindings::arrayfunc);
CFunction<float()> select("tmplfunc", (float(*)())(CBindings::tmplfunc));
CFunction<void(void*, void**, void***, float*, float**, float***)>
mindirect("multiptrfunc", &CBindings::multiptrfunc);
// test static void function
CPPUNIT_ASSERT_EQUAL(size_t(0), voidfunc.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::voidfunc),
voidfunc.address());
CPPUNIT_ASSERT_EQUAL(std::string("voidfunc"),
std::string(voidfunc.symbol()));
// test scalar arguments
CPPUNIT_ASSERT_EQUAL(size_t(6), scalars.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalarfunc),
scalars.address());
CPPUNIT_ASSERT_EQUAL(std::string("scalarfunc"),
std::string(scalars.symbol()));
// test scalar ptr arguments
CPPUNIT_ASSERT_EQUAL(size_t(6), scalarptrs.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalatptsfunc),
scalarptrs.address());
CPPUNIT_ASSERT_EQUAL(std::string("scalatptsfunc"),
std::string(scalarptrs.symbol()));
// test array ptr arguments
CPPUNIT_ASSERT_EQUAL(size_t(6), arrayptrs.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::arrayfunc),
arrayptrs.address());
CPPUNIT_ASSERT_EQUAL(std::string("arrayfunc"),
std::string(arrayptrs.symbol()));
// test selected template functions
CPPUNIT_ASSERT_EQUAL(size_t(0), select.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::tmplfunc<float>),
select.address());
CPPUNIT_ASSERT_EQUAL(std::string("tmplfunc"),
std::string(select.symbol()));
// test multiple indirection layers
CPPUNIT_ASSERT_EQUAL(size_t(6), mindirect.size());
CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::multiptrfunc),
mindirect.address());
CPPUNIT_ASSERT_EQUAL(std::string("multiptrfunc"),
std::string(mindirect.symbol()));
//
// Test types
// test scalar arguments
returnType = scalars.types(types, C);
CPPUNIT_ASSERT(returnType->isIntegerTy(16));
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0]->isIntegerTy(1));
CPPUNIT_ASSERT(types[1]->isIntegerTy(16));
CPPUNIT_ASSERT(types[2]->isIntegerTy(32));
CPPUNIT_ASSERT(types[3]->isIntegerTy(64));
CPPUNIT_ASSERT(types[4]->isFloatTy());
CPPUNIT_ASSERT(types[5]->isDoubleTy());
types.clear();
// test scalar ptr arguments
returnType = scalarptrs.types(types, C);
CPPUNIT_ASSERT(returnType->isIntegerTy(32));
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo());
types.clear();
// test array ptr arguments
returnType = arrayptrs.types(types, C);
CPPUNIT_ASSERT(returnType->isIntegerTy(64));
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)->getPointerTo());
CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 2)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 4)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 5)->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 6)->getPointerTo());
types.clear();
// test void ptr arguments
// void* are inferred as int8_t* types
returnType = mindirect.types(types, C);
CPPUNIT_ASSERT(returnType->isVoidTy());
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::Type::getInt8PtrTy(C));
CPPUNIT_ASSERT(types[1] == llvm::Type::getInt8PtrTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::Type::getInt8PtrTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo());
}
void
TestFunctionTypes::testCFunctionCF()
{
using openvdb::ax::codegen::CFunction;
using openvdb::ax::codegen::LLVMType;
static auto cftest1 = []() -> int32_t { return 10; };
static auto cftest2 = [](float a) -> float { return a; };
// currently unsupported for arrays
static auto cftest3 = [](float(*a)[3]) -> float { return (*a)[0]; };
// currently unsupported for return voids
static auto cftest4 = [](float* a) -> void { (*a)*=5.0f; };
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::IRBuilder<> B(state.scratchBlock());
// test with no args
CFunction<int32_t()> test1("ax.test1", cftest1);
// off by default
CPPUNIT_ASSERT(!test1.hasConstantFold());
CPPUNIT_ASSERT(test1.fold({B.getInt32(1)}, C) == nullptr);
test1.setConstantFold(true);
llvm::Value* result = test1.fold({B.getInt32(1)}, C);
CPPUNIT_ASSERT(result);
llvm::ConstantInt* constant = llvm::dyn_cast<llvm::ConstantInt>(result);
CPPUNIT_ASSERT(constant);
CPPUNIT_ASSERT_EQUAL(uint64_t(10), constant->getLimitedValue());
// test with scalar arg
CFunction<float(float)> test2("ax.test2", cftest2);
test2.setConstantFold(true);
result = test2.fold({LLVMType<float>::get(C, -3.2f)}, C);
CPPUNIT_ASSERT(result);
llvm::ConstantFP* constantfp = llvm::dyn_cast<llvm::ConstantFP>(result);
CPPUNIT_ASSERT(constantfp);
const llvm::APFloat& apf = constantfp->getValueAPF();
CPPUNIT_ASSERT_EQUAL(-3.2f, apf.convertToFloat());
// test unsupported
CFunction<float(float(*)[3])> test3("ax.test3", cftest3);
test3.setConstantFold(true);
// constant arg (verify it would 100% match)
// note that this arg is fundamentally the wrong type for this function
// and the way in which we support vector types anyway (by ptr) - but because
// its impossible to have a constant ptr, use this for now as this will most
// likely be the way we support folding for arrays in the future
llvm::Value* arg = LLVMType<float[3]>::get(C, {1,2,3});
CPPUNIT_ASSERT(llvm::isa<llvm::Constant>(arg));
// check fold fails
CPPUNIT_ASSERT(test3.fold({arg}, C) == nullptr);
//
CFunction<void(float*)> test4("ax.test4", cftest4);
test4.setConstantFold(true);
// constant arg (verify it would 100% match)
llvm::Value* nullfloat = llvm::ConstantPointerNull::get(LLVMType<float*>::get(C));
std::vector<llvm::Type*> types;
test4.types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(1), types.size());
CPPUNIT_ASSERT(nullfloat->getType() == types.front());
CPPUNIT_ASSERT(test4.fold({nullfloat}, C) == nullptr);
}
void
TestFunctionTypes::testIRFunctions()
{
using openvdb::ax::codegen::LLVMType;
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::IRFunctionBase;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
// Small test to check the templated version of IRFunction::types.
// All other checks work with the IRFunctionBase class
{
using openvdb::ax::codegen::IRFunction;
static auto generate =
[](const std::vector<llvm::Value*>&,
llvm::IRBuilder<>&) -> llvm::Value*
{ return nullptr; };
IRFunction<double(bool,
int16_t*,
int32_t(*)[1],
int64_t,
float*,
double(*)[2])>
mix("mix", generate);
CPPUNIT_ASSERT_EQUAL(std::string("mix"),
std::string(mix.symbol()));
std::vector<llvm::Type*> types;
llvm::Type* returnType = mix.types(types, C);
CPPUNIT_ASSERT(returnType->isDoubleTy());
CPPUNIT_ASSERT_EQUAL(size_t(6), types.size());
CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C));
CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo());
CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo());
CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C));
CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo());
CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo());
}
llvm::Module& M = state.module();
llvm::IRBuilder<> B(state.scratchBlock("TestFunction"));
llvm::Function* BaseFunction = B.GetInsertBlock()->getParent();
B.SetInsertPoint(finalizeFunction(B));
// Build the following function:
// float test(float a, float b) {
// float c = a + b;
// return c;
// }
// how to handle the terminating instruction
int termMode = 0;
std::string expectedName;
auto generate =
[&B, &M, &termMode, &expectedName]
(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& _B) -> llvm::Value*
{
// test the builder is pointing to the correct location
CPPUNIT_ASSERT(&B != &_B);
llvm::BasicBlock* Block = _B.GetInsertBlock();
CPPUNIT_ASSERT(Block);
CPPUNIT_ASSERT(Block->empty());
llvm::Function* F = Block->getParent();
CPPUNIT_ASSERT(F);
CPPUNIT_ASSERT_EQUAL(expectedName, std::string(F->getName()));
llvm::Module* _M = F->getParent();
CPPUNIT_ASSERT_EQUAL(&M, _M);
CPPUNIT_ASSERT_EQUAL(size_t(2), args.size());
CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin()));
CPPUNIT_ASSERT(args[1] == llvm::cast<llvm::Value>(F->arg_begin()+1));
CPPUNIT_ASSERT(args[0]->getType()->isFloatTy());
CPPUNIT_ASSERT(args[1]->getType()->isFloatTy());
llvm::Value* result = _B.CreateFAdd(args[0], args[1]);
if (termMode == 0) return _B.CreateRet(result);
if (termMode == 1) return result;
if (termMode == 2) return nullptr;
CPPUNIT_ASSERT(false);
return nullptr;
};
llvm::Function* function = nullptr;
expectedName = "ax.ir.test";
Function::Ptr test(new TestIRFunction({
llvm::Type::getFloatTy(C),
llvm::Type::getFloatTy(C)
},
llvm::Type::getFloatTy(C),
expectedName, generate));
// Test function prototype creation
CPPUNIT_ASSERT(!M.getFunction("ax.ir.test"));
function = test->create(C);
CPPUNIT_ASSERT(!M.getFunction("ax.ir.test"));
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT(function != test->create(C));
CPPUNIT_ASSERT(!function->isVarArg());
CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size());
llvm::FunctionType* ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy());
CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0)->isFloatTy());
CPPUNIT_ASSERT(ftype->getParamType(1)->isFloatTy());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// Test function creation with module and IR generation
CPPUNIT_ASSERT(!M.getFunction("ax.ir.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test"));
CPPUNIT_ASSERT(!function->empty());
llvm::BasicBlock* BB = &(function->getEntryBlock());
// two instructions - the add and return
CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size());
auto iter = BB->begin();
llvm::BinaryOperator* binary = llvm::dyn_cast<llvm::BinaryOperator>(iter);
CPPUNIT_ASSERT(binary);
CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()),
binary->getOperand(0));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1),
binary->getOperand(1));
++iter;
llvm::ReturnInst* ret = llvm::dyn_cast<llvm::ReturnInst>(iter);
CPPUNIT_ASSERT(ret);
llvm::Value* rvalue = ret->getReturnValue();
CPPUNIT_ASSERT(rvalue);
CPPUNIT_ASSERT(rvalue->getType()->isFloatTy());
// the return is the result of the bin op
CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary));
++iter;
CPPUNIT_ASSERT(BB->end() == iter);
// additional call should match
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
// verify IR
VERIFY_FUNCTION_IR(function);
// Test call
llvm::Value* fp1 = LLVMType<float>::get(C, 1.0f);
llvm::Value* fp2 = LLVMType<float>::get(C, 2.0f);
llvm::Value* result = test->call({fp1, fp2}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1));
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call),
llvm::cast<llvm::Value>(--B.GetInsertPoint()));
// verify IR
VERIFY_FUNCTION_IR(function);
VERIFY_FUNCTION_IR(BaseFunction);
VERIFY_MODULE_IR(&M);
//
// Test auto return - the IRFunctionBase should handle the return
// also test that calling Function::call correctly creates the
// function in the module
expectedName = "ax.ir.autoret.test";
termMode = 1;
test.reset(new TestIRFunction({
llvm::Type::getFloatTy(C),
llvm::Type::getFloatTy(C)
},
llvm::Type::getFloatTy(C),
expectedName, generate));
CPPUNIT_ASSERT(!M.getFunction("ax.ir.autoret.test"));
result = test->call({fp1, fp2}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
function = M.getFunction("ax.ir.autoret.test");
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1));
CPPUNIT_ASSERT(!function->empty());
BB = &(function->getEntryBlock());
// two instructions - the add and return
CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size());
iter = BB->begin();
binary = llvm::dyn_cast<llvm::BinaryOperator>(iter);
CPPUNIT_ASSERT(binary);
CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()),
binary->getOperand(0));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1),
binary->getOperand(1));
++iter;
ret = llvm::dyn_cast<llvm::ReturnInst>(iter);
CPPUNIT_ASSERT(ret);
rvalue = ret->getReturnValue();
CPPUNIT_ASSERT(rvalue);
CPPUNIT_ASSERT(rvalue->getType()->isFloatTy());
// the return is the result of the bin op
CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary));
++iter;
CPPUNIT_ASSERT(BB->end() == iter);
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call),
llvm::cast<llvm::Value>(--B.GetInsertPoint()));
// verify
VERIFY_FUNCTION_IR(function);
VERIFY_FUNCTION_IR(BaseFunction);
VERIFY_MODULE_IR(&M);
// Test invalid return
expectedName = "ax.ir.retnull.test";
termMode = 2;
test.reset(new TestIRFunction({
llvm::Type::getFloatTy(C),
llvm::Type::getFloatTy(C)
},
llvm::Type::getFloatTy(C),
expectedName, generate));
CPPUNIT_ASSERT(!M.getFunction("ax.ir.retnull.test"));
// will throw as the function expects a float ret, not void or null
// NOTE: The function will still be created, but be in an invaid state
CPPUNIT_ASSERT_THROW(test->create(M), openvdb::AXCodeGenError);
function = M.getFunction("ax.ir.retnull.test");
CPPUNIT_ASSERT(function);
result = test->call({fp1, fp2}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
call = llvm::dyn_cast<llvm::CallInst>(result);
CPPUNIT_ASSERT(call);
CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction());
CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands());
CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0));
CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1));
BB = &(function->getEntryBlock());
// two instructions - the add and return
CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size());
iter = BB->begin();
binary = llvm::dyn_cast<llvm::BinaryOperator>(iter);
CPPUNIT_ASSERT(binary);
CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()),
binary->getOperand(0));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1),
binary->getOperand(1));
++iter;
ret = llvm::dyn_cast<llvm::ReturnInst>(iter);
CPPUNIT_ASSERT(ret);
CPPUNIT_ASSERT(!ret->getReturnValue());
++iter;
CPPUNIT_ASSERT(BB->end() == iter);
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call),
llvm::cast<llvm::Value>(--B.GetInsertPoint()));
// verify - function is invalid as it returns void but the
// prototype wants a float
VERIFY_FUNCTION_IR_INVALID(function);
VERIFY_FUNCTION_IR(BaseFunction);
VERIFY_MODULE_IR_INVALID(&M);
//
// Test embedded IR
auto embdedGen = [&B, &M]
(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& _B) -> llvm::Value*
{
// test the builder is pointing to the correct location
// note, for embedded IR, the same builder will be used
CPPUNIT_ASSERT_EQUAL(&B, &_B);
llvm::BasicBlock* Block = _B.GetInsertBlock();
CPPUNIT_ASSERT(Block);
CPPUNIT_ASSERT(!Block->empty());
llvm::Function* F = Block->getParent();
CPPUNIT_ASSERT(F);
CPPUNIT_ASSERT_EQUAL(std::string("TestFunction"), std::string(F->getName()));
CPPUNIT_ASSERT_EQUAL(&M, F->getParent());
CPPUNIT_ASSERT_EQUAL(size_t(2), args.size());
CPPUNIT_ASSERT(args[0]->getType()->isFloatTy());
CPPUNIT_ASSERT(args[1]->getType()->isFloatTy());
// Can't just do a CreateFAdd as the IR builder won't actually even
// write the instruction as its const and unused - so store in a new
// alloc
llvm::Value* alloc = _B.CreateAlloca(args[0]->getType());
_B.CreateStore(args[0], alloc);
return _B.CreateLoad(alloc);
};
test.reset(new TestIRFunction({
llvm::Type::getFloatTy(C),
llvm::Type::getFloatTy(C)
},
llvm::Type::getFloatTy(C),
"ax.ir.embed.test", embdedGen));
static_cast<IRFunctionBase&>(*test).setEmbedIR(true);
// test create does nothing
CPPUNIT_ASSERT(test->create(C) == nullptr);
CPPUNIT_ASSERT(test->create(M) == nullptr);
// test call
CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test"));
result = test->call({fp1, fp2}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test"));
auto IP = B.GetInsertPoint();
// check the prev instructions are as expected
CPPUNIT_ASSERT(llvm::isa<llvm::LoadInst>(--IP));
CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(--IP));
CPPUNIT_ASSERT(llvm::isa<llvm::AllocaInst>(--IP));
// Test the builder is pointing to the correct location
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
}
void
TestFunctionTypes::testSRETFunctions()
{
using openvdb::ax::codegen::LLVMType;
using openvdb::ax::codegen::Function;
using openvdb::ax::codegen::CFunctionSRet;
using openvdb::ax::codegen::IRFunctionSRet;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
llvm::Module& M = state.module();
llvm::IRBuilder<> B(state.scratchBlock());
std::vector<llvm::Type*> types;
llvm::Type* type = nullptr;
llvm::Value* result = nullptr;
llvm::Function* function = nullptr;
llvm::FunctionType* ftype = nullptr;
Function::SignatureMatch match;
std::ostringstream os;
B.SetInsertPoint(finalizeFunction(B));
llvm::Function* BaseFunction = B.GetInsertBlock()->getParent();
// test C SRET
static auto csret = [](float(*output)[3]) { (*output)[0] = 1.0f; };
Function::Ptr test(new CFunctionSRet<void(float(*)[3])>
("ax.c.test", (void(*)(float(*)[3]))(csret)));
// test types
llvm::Type* vec3f = llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3);
type = test->types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(1), types.size());
CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0));
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
// test various getters
CPPUNIT_ASSERT_EQUAL(std::string("ax.c.test"), std::string(test->symbol()));
CPPUNIT_ASSERT_EQUAL(size_t(1), test->size());
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0)));
// test printing
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str());
// test match
match = test->match({vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::None);
match = test->match({}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
match = test->Function::match({vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
// test create
CPPUNIT_ASSERT(!M.getFunction("ax.c.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.c.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo());
// test call - sret function do not return the CallInst as the value
result = test->call({}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result));
CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo());
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
VERIFY_FUNCTION_IR(function);
VERIFY_MODULE_IR(&M);
//
// test sret with two arguments
static auto csret2 = [](float(*output)[3], float(*input)[3]) { (*output)[0] = (*input)[0]; };
test.reset(new CFunctionSRet<void(float(*)[3],float(*)[3])>
("ax.c2.test", (void(*)(float(*)[3],float(*)[3]))(csret2)));
types.clear();
// test types
type = test->types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(2), types.size());
CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0));
CPPUNIT_ASSERT(types[1] == vec3f->getPointerTo(0));
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
// test various getters
CPPUNIT_ASSERT_EQUAL(std::string("ax.c2.test"), std::string(test->symbol()));
CPPUNIT_ASSERT_EQUAL(size_t(2), test->size());
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0)));
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1)));
// test printing
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("vec3f name(vec3f)"), os.str());
// test match
match = test->match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::None);
match = test->match({vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
match = test->match({}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::None);
match = test->Function::match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
// test create
CPPUNIT_ASSERT(!M.getFunction("ax.c2.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT(M.getFunction("ax.c2.test"));
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
CPPUNIT_ASSERT(function->empty());
CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo());
CPPUNIT_ASSERT(ftype->getParamType(1) == vec3f->getPointerTo());
// test call - sret function do not return the CallInst as the value
llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float
llvm::Value* vec3fv = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f
result = test->call({vec3fv}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result));
CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo());
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
VERIFY_FUNCTION_IR(function);
VERIFY_MODULE_IR(&M);
//
// test IR SRET
// Build the following function:
// void test(vec3f* a) {
// a[0] = 1.0f;
// }
// which has a front interface of:
// vec3f test() { vec3f a; a[0] = 1; return a;};
//
auto generate = [&B, &M]
(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& _B) -> llvm::Value*
{
// test the builder is pointing to the correct location
CPPUNIT_ASSERT(&B != &_B);
llvm::BasicBlock* Block = _B.GetInsertBlock();
CPPUNIT_ASSERT(Block);
CPPUNIT_ASSERT(Block->empty());
llvm::Function* F = Block->getParent();
CPPUNIT_ASSERT(F);
CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(F->getName()));
llvm::Module* _M = F->getParent();
CPPUNIT_ASSERT_EQUAL(&M, _M);
CPPUNIT_ASSERT_EQUAL(size_t(1), args.size());
CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin()));
CPPUNIT_ASSERT(args[0]->getType() ==
llvm::ArrayType::get(llvm::Type::getFloatTy(_B.getContext()), 3)->getPointerTo());
llvm::Value* e0 = _B.CreateConstGEP2_64(args[0], 0, 0);
_B.CreateStore(LLVMType<float>::get(_B.getContext(), 1.0f), e0);
return nullptr;
};
test.reset(new IRFunctionSRet<void(float(*)[3])>("ax.ir.test", generate));
types.clear();
// test types
type = test->types(types, C);
CPPUNIT_ASSERT_EQUAL(size_t(1), types.size());
CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0));
CPPUNIT_ASSERT(type);
CPPUNIT_ASSERT(type->isVoidTy());
// test various getters
CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(test->symbol()));
CPPUNIT_ASSERT_EQUAL(size_t(1), test->size());
CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0)));
// test printing
os.str("");
test->print(C, os, "name", /*axtypes=*/true);
CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str());
// test match
match = test->match({vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::None);
match = test->match({}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
match = test->Function::match({vec3f->getPointerTo()}, C);
CPPUNIT_ASSERT_EQUAL(match, Function::Explicit);
// test create
CPPUNIT_ASSERT(!M.getFunction("ax.ir.test"));
function = test->create(M);
CPPUNIT_ASSERT(function);
CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test"));
CPPUNIT_ASSERT(!function->empty());
// test instructions
llvm::BasicBlock* BB = &(function->getEntryBlock());
CPPUNIT_ASSERT_EQUAL(size_t(3), BB->size());
auto iter = BB->begin();
CPPUNIT_ASSERT(llvm::isa<llvm::GetElementPtrInst>(iter++));
CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(iter++));
CPPUNIT_ASSERT(llvm::isa<llvm::ReturnInst>(iter++));
CPPUNIT_ASSERT(BB->end() == iter);
// additional call should match
CPPUNIT_ASSERT_EQUAL(function, test->create(M));
CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size());
CPPUNIT_ASSERT(function->getAttributes().isEmpty());
// check function type
ftype = function->getFunctionType();
CPPUNIT_ASSERT(ftype);
CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy());
CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams());
CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo());
// test call - sret function do not return the CallInst as the value
result = test->call({}, B, /*cast*/false);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result));
CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo());
CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock());
VERIFY_FUNCTION_IR(function);
VERIFY_MODULE_IR(&M);
}
| 90,722 | C++ | 40.014014 | 129 | 0.637784 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestTypes.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "util.h"
#include <openvdb_ax/codegen/Types.h>
#include <openvdb/math/Vec2.h>
#include <openvdb/math/Vec3.h>
#include <openvdb/math/Vec4.h>
#include <openvdb/math/Mat3.h>
#include <openvdb/math/Mat4.h>
#include <cppunit/extensions/HelperMacros.h>
class TestTypes : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestTypes);
CPPUNIT_TEST(testTypes);
CPPUNIT_TEST(testVDBTypes);
CPPUNIT_TEST_SUITE_END();
void testTypes();
void testVDBTypes();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestTypes);
void
TestTypes::testTypes()
{
using openvdb::ax::codegen::LLVMType;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
// scalar types
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt1Ty(C)), LLVMType<bool>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<int8_t>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt16Ty(C)), LLVMType<int16_t>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt32Ty(C)), LLVMType<int32_t>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt64Ty(C)), LLVMType<int64_t>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getFloatTy(C)), LLVMType<float>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getDoubleTy(C)), LLVMType<double>::get(C));
// scalar values
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt1Ty(C), true)),
LLVMType<bool>::get(C, true));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt8Ty(C), int8_t(1))),
LLVMType<int8_t>::get(C, int8_t(1)));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt16Ty(C), int16_t(2))),
LLVMType<int16_t>::get(C, int16_t(2)));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), int32_t(3))),
LLVMType<int32_t>::get(C, int32_t(3)));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt64Ty(C), int64_t(4))),
LLVMType<int64_t>::get(C, int64_t(4)));
// array types
#if LLVM_VERSION_MAJOR > 6
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)),
LLVMType<bool[1]>::get(C));
#endif
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt8Ty(C), 2)),
LLVMType<int8_t[2]>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 3)),
LLVMType<int16_t[3]>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)),
LLVMType<int32_t[4]>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 5)),
LLVMType<int64_t[5]>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 6)),
LLVMType<float[6]>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 7)),
LLVMType<double[7]>::get(C));
// array values
#if LLVM_VERSION_MAJOR > 6
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get<bool>(C, {true})),
LLVMType<bool[1]>::get(C, {true}));
#endif
const std::vector<uint8_t> veci8{1,2};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci8)),
LLVMType<uint8_t[2]>::get(C, {1,2}));
const std::vector<uint16_t> veci16{1,2,3};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci16)),
LLVMType<uint16_t[3]>::get(C, {1,2,3}));
const std::vector<uint32_t> veci32{1,2,3,4};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci32)),
LLVMType<uint32_t[4]>::get(C, {1,2,3,4}));
const std::vector<uint64_t> veci64{1,2,3,4,5};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci64)),
LLVMType<uint64_t[5]>::get(C, {1,2,3,4,5}));
const std::vector<float> vecf{.0f,.1f,.2f,.3f,.4f,.5f};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecf)),
LLVMType<float[6]>::get(C, {.0f,.1f,.2f,.3f,.4f,.5f}));
const std::vector<double> vecd{.0,.1,.2,.3,.4,.5,.6};
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecd)),
LLVMType<double[7]>::get(C, {.0,.1,.2,.3,.4,.5,.6}));
// void
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getVoidTy(C)), LLVMType<void>::get(C));
// some special cases we alias
CPPUNIT_ASSERT_EQUAL(llvm::Type::getInt8PtrTy(C), LLVMType<void*>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<char>::get(C));
}
void
TestTypes::testVDBTypes()
{
using openvdb::ax::codegen::LLVMType;
unittest_util::LLVMState state;
llvm::LLVMContext& C = state.context();
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)),
LLVMType<openvdb::math::Vec2<int32_t>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)),
LLVMType<openvdb::math::Vec2<float>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)),
LLVMType<openvdb::math::Vec2<double>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)),
LLVMType<openvdb::math::Vec3<int32_t>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)),
LLVMType<openvdb::math::Vec3<float>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)),
LLVMType<openvdb::math::Vec3<double>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)),
LLVMType<openvdb::math::Vec4<int32_t>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)),
LLVMType<openvdb::math::Vec4<float>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)),
LLVMType<openvdb::math::Vec4<double>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)),
LLVMType<openvdb::math::Mat3<float>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)),
LLVMType<openvdb::math::Mat3<double>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)),
LLVMType<openvdb::math::Mat4<float>>::get(C));
CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)),
LLVMType<openvdb::math::Mat4<double>>::get(C));
}
| 7,308 | C++ | 44.68125 | 115 | 0.654762 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/util.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#ifndef OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED
#define OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED
#include <openvdb_ax/codegen/Types.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <memory>
#include <string>
namespace unittest_util
{
struct LLVMState
{
LLVMState(const std::string& name = "__test_module")
: mCtx(new llvm::LLVMContext), mModule(new llvm::Module(name, *mCtx)) {}
llvm::LLVMContext& context() { return *mCtx; }
llvm::Module& module() { return *mModule; }
inline llvm::BasicBlock*
scratchBlock(const std::string& functionName = "TestFunction",
const std::string& blockName = "TestEntry")
{
llvm::FunctionType* type =
llvm::FunctionType::get(openvdb::ax::codegen::LLVMType<void>::get(this->context()),
/**var-args*/false);
llvm::Function* dummyFunction =
llvm::Function::Create(type, llvm::Function::ExternalLinkage, functionName, &this->module());
return llvm::BasicBlock::Create(this->context(), blockName, dummyFunction);
}
private:
std::unique_ptr<llvm::LLVMContext> mCtx;
std::unique_ptr<llvm::Module> mModule;
};
}
#endif // OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED
| 1,393 | C | 28.041666 | 105 | 0.671931 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestUnaryOperatorNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "-a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::MINUS)) },
{ "+a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::PLUS)) },
{ "!a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::NOT)) },
{ "~a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::BITNOT)) },
{ "~~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::BITNOT)) },
{ "!~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::NOT)) },
{ "+-a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::MINUS), OperatorToken::PLUS)) },
{ "-+a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::PLUS), OperatorToken::MINUS)) },
{ "!!!a;", Node::Ptr(new UnaryOperator(
new UnaryOperator(
new UnaryOperator(new Local("a"), OperatorToken::NOT),
OperatorToken::NOT
),
OperatorToken::NOT
))
},
{ "~~~a;", Node::Ptr(new UnaryOperator(
new UnaryOperator(
new UnaryOperator(new Local("a"), OperatorToken::BITNOT),
OperatorToken::BITNOT
),
OperatorToken::BITNOT
))
},
{ "-(a+b);", Node::Ptr(new UnaryOperator(
new BinaryOperator(
new Local("a"), new Local("b"), OperatorToken::PLUS
),
OperatorToken::MINUS
))
},
{ "!func();", Node::Ptr(new UnaryOperator(new FunctionCall("func"), OperatorToken::NOT)) },
{ "-@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::FLOAT, true), OperatorToken::MINUS)) },
{ "!v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::NOT)) },
{ "~v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::BITNOT)) },
{ "+int(a);", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::INT32), OperatorToken::PLUS)) },
{ "-(float(a));", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::FLOAT), OperatorToken::MINUS)) },
{ "!a.x;", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::NOT)) },
{ "-a[0];", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::MINUS)) },
{ "-++a;", Node::Ptr(new UnaryOperator(new Crement(new Local("a"), Crement::Operation::Increment, false), OperatorToken::MINUS)) },
{ "!{a,b,c};", Node::Ptr(new UnaryOperator(
new ArrayPack({
new Local("a"),
new Local("b"),
new Local("c")
}),
OperatorToken::NOT
))
},
{ "!(a,b,c);", Node::Ptr(new UnaryOperator(
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
}),
OperatorToken::NOT
))
},
// This is a bit of a weird one - should perhaps look to making this a syntax error
// (it will fail at compilation with an lvalue error)
{ "-a=a;", Node::Ptr(new UnaryOperator(
new AssignExpression(new Local("a"), new Local("a")),
OperatorToken::MINUS
))
}
};
}
class TestUnaryOperatorNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestUnaryOperatorNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestUnaryOperatorNode);
void TestUnaryOperatorNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::UnaryOperatorNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Unary Operator code", code) + os.str());
}
}
}
| 6,046 | C++ | 44.126865 | 144 | 0.523652 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCastNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "bool(a);", Node::Ptr(new Cast(new Local("a"), CoreType::BOOL)) },
{ "int(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) },
{ "int32(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) },
{ "int64(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT64)) },
{ "float(a);", Node::Ptr(new Cast(new Local("a"), CoreType::FLOAT)) },
{ "double(a);", Node::Ptr(new Cast(new Local("a"), CoreType::DOUBLE)) },
{ "int32((a));", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) },
{ "int32(1l);", Node::Ptr(new Cast(new Value<int64_t>(1), CoreType::INT32)) },
{ "int32(1);", Node::Ptr(new Cast(new Value<int32_t>(1), CoreType::INT32)) },
{ "int32(0);", Node::Ptr(new Cast(new Value<int32_t>(0), CoreType::INT32)) },
{ "int32(@a);", Node::Ptr(new Cast(new Attribute("a", CoreType::FLOAT, true), CoreType::INT32)) },
{ "double(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::DOUBLE)) },
{ "double(false);", Node::Ptr(new Cast(new Value<bool>(false), CoreType::DOUBLE)) },
{ "int32(1.0f);", Node::Ptr(new Cast(new Value<float>(1.0f), CoreType::INT32)) },
{ "int64(1.0);", Node::Ptr(new Cast(new Value<double>(1.0), CoreType::INT64)) },
{ "float(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::FLOAT)) },
{ "int32(func());", Node::Ptr(new Cast(new FunctionCall("func"), CoreType::INT32)) },
{ "bool(a+b);", Node::Ptr(new Cast(new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::PLUS), CoreType::BOOL)) },
{ "int32(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT32)) },
{ "int64(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT64)) },
{ "float(a = b);", Node::Ptr(new Cast(new AssignExpression(new Local("a"), new Local("b")), CoreType::FLOAT)) },
{ "double(a.x);", Node::Ptr(new Cast(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), CoreType::DOUBLE)) },
{ "int32(a++);", Node::Ptr(new Cast(new Crement(new Local("a"), Crement::Operation::Increment, true), CoreType::INT32)) },
{ "int32({a,b,c});", Node::Ptr(new Cast(new ArrayPack({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) },
{ "int32((a,b,c));", Node::Ptr(new Cast(new CommaOperator({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) },
{ "float(double(0));", Node::Ptr(new Cast(new Cast(new Value<int32_t>(0), CoreType::DOUBLE), CoreType::FLOAT)) },
};
}
class TestCastNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestCastNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestCastNode);
void TestCastNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::CastNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Cast code", code) + os.str());
}
}
}
| 4,581 | C++ | 47.231578 | 139 | 0.596158 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCommaOperator.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "(1, 2, (1,2,3));", Node::Ptr(
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
})
}))
},
{ "(1.f,2.0,3l);" , Node::Ptr(
new CommaOperator({
new Value<float>(1.0f),
new Value<double>(2.0),
new Value<int64_t>(3)
}))
},
{ "((a,b,c), (d,e,f), (g,h,i));", Node::Ptr(
new CommaOperator({
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
}),
new CommaOperator({
new Local("d"),
new Local("e"),
new Local("f")
}),
new CommaOperator({
new Local("g"),
new Local("h"),
new Local("i")
})
}))
},
{ "((a),b+1,-c);", Node::Ptr(
new CommaOperator({
new Local("a"),
new BinaryOperator(new Local("b"), new Value<int32_t>(1), OperatorToken::PLUS),
new UnaryOperator(new Local("c"), OperatorToken::MINUS)
}))
},
{ "(@x,++z,true);", Node::Ptr(
new CommaOperator({
new Attribute("x", CoreType::FLOAT, true),
new Crement(new Local("z"), Crement::Operation::Increment, false),
new Value<bool>(true)
}))
},
{ "(@x,z++,\"bar\");", Node::Ptr(
new CommaOperator({
new Attribute("x", CoreType::FLOAT, true),
new Crement(new Local("z"), Crement::Operation::Increment, true),
new Value<std::string>("bar")
}))
},
{ "(float(x),b=c,c.z);", Node::Ptr(
new CommaOperator({
new Cast(new Local("x"), CoreType::FLOAT),
new AssignExpression(new Local("b"), new Local("c")),
new ArrayUnpack(new Local("c"), new Value<int32_t>(2))
}))
},
{ "(test(),a[0],b[1,2]);", Node::Ptr(
new CommaOperator({
new FunctionCall("test"),
new ArrayUnpack(new Local("a"), new Value<int32_t>(0)),
new ArrayUnpack(new Local("b"), new Value<int32_t>(1), new Value<int32_t>(2))
}))
},
{ "(1,2,3,4,5,6,7,8,9);", Node::Ptr(
new CommaOperator({
new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3),
new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6),
new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9)
}))
},
{ "( 1, 2, 3, 4, \
5, 6, 7, 8, \
9,10,11,12, \
13,14,15,16 );", Node::Ptr(
new CommaOperator({
new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4),
new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8),
new Value<int32_t>(9), new Value<int32_t>(10), new Value<int32_t>(11), new Value<int32_t>(12),
new Value<int32_t>(13), new Value<int32_t>(14), new Value<int32_t>(15), new Value<int32_t>(16)
}))
},
};
}
class TestCommaOperator : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestCommaOperator);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestCommaOperator);
void TestCommaOperator::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::CommaOperatorNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Comma Operator code", code) + os.str());
}
}
}
| 7,752 | C++ | 47.761006 | 143 | 0.353715 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestStatementListNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "int32 a = (1,2,3), b=1, c=(b=1);", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a"),
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3),
})),
new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)),
new DeclareLocal(CoreType::INT32, new Local("c"),
new AssignExpression(
new Local("b"),
new Value<int32_t>(1))),
}))
},
{ "int32 a, b;", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a")),
new DeclareLocal(CoreType::INT32, new Local("b"))
}))
},
{ "int32 a, b = 1;", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a")),
new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1))
}))
},
{ "int32 a, b = 1, c = 1;", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a")),
new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)),
new DeclareLocal(CoreType::INT32, new Local("c"), new Value<int32_t>(1))
}))
},
{ "int32 a, b = 1, c;", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a")),
new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)),
new DeclareLocal(CoreType::INT32, new Local("c"))
}))
},
{ "int32 a, b = 1, c, d = 1;", Node::Ptr(new StatementList({
new DeclareLocal(CoreType::INT32, new Local("a")),
new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)),
new DeclareLocal(CoreType::INT32, new Local("c")),
new DeclareLocal(CoreType::INT32, new Local("d"), new Value<int32_t>(1))
}))
}
};
}
class TestStatementList : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestStatementList);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestStatementList);
void TestStatementList::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::StatementListNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Statement List code", code) + os.str());
}
}
}
| 4,873 | C++ | 42.517857 | 117 | 0.470962 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCrementNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "a++;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/true)) },
{ "++a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/false)) },
{ "a--;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/true)) },
{ "--a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/false)) },
{ "s@a--;", Node::Ptr(new Crement(new Attribute("a", CoreType::STRING), Crement::Operation::Decrement, /*post*/true)) },
{ "f@a++;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/true)) },
{ "++f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/false)) },
{ "++mat3f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::MAT3F), Crement::Operation::Increment, /*post*/false)) }
};
}
class TestCrementNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestCrementNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests) };
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestCrementNode);
void TestCrementNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::CrementNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Crement code", code) + os.str());
}
}
}
| 2,855 | C++ | 36.090909 | 128 | 0.630823 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestArrayUnpackNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "a.x;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) },
{ "a.y;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) },
{ "a.z;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) },
{ "a.r;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) },
{ "a.g;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) },
{ "a.b;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) },
{ "x.x;", Node::Ptr(new ArrayUnpack(new Local("x"), new Value<int32_t>(0))) },
{ "@x.x;", Node::Ptr(new ArrayUnpack(new Attribute("x", CoreType::FLOAT, true), new Value<int32_t>(0))) },
{ "@a.x;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) },
{ "@b.y;", Node::Ptr(new ArrayUnpack(new Attribute("b", CoreType::FLOAT, true), new Value<int32_t>(1))) },
{ "@c.z;", Node::Ptr(new ArrayUnpack(new Attribute("c", CoreType::FLOAT, true), new Value<int32_t>(2))) },
{ "@a.r;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) },
{ "@a.g;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) },
{ "@a.b;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) },
{ "@a[0l];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int64_t>(0))) },
{ "@a[0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) },
{ "@a[1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) },
{ "@a[2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) },
{ "@a[0.0f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<float>(0.0f))) },
{ "@a[0.0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<double>(0.0))) },
{ "@a[\"str\"];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("str"))) },
{ "@a[true];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) },
{ "@a[false];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(false))) },
{ "@a[a];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"))) },
{ "@a[0,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0), new Value<int32_t>(0))) },
{ "@a[1,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0))) },
{ "@a[2,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2), new Value<int32_t>(0))) },
{ "a[0,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0))) },
{ "a[1,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1), new Value<int32_t>(0))) },
{ "a[2,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2), new Value<int32_t>(0))) },
{ "@a[a,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Value<int32_t>(0))) },
{ "@a[b,1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Value<int32_t>(1))) },
{ "@a[c,2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Value<int32_t>(2))) },
{ "@a[a,d];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Local("d"))) },
{ "@a[b,e];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Local("e"))) },
{ "@a[c,f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Local("f"))) },
//
{ "a[(a),1+1];", Node::Ptr(new ArrayUnpack(new Local("a"),
new Local("a"),
new BinaryOperator(new Value<int32_t>(1), new Value<int32_t>(1), OperatorToken::PLUS)))
},
{ "a[!0,a=b];", Node::Ptr(new ArrayUnpack(new Local("a"),
new UnaryOperator(new Value<int32_t>(0), OperatorToken::NOT),
new AssignExpression(new Local("a"), new Local("b"))))
},
{ "a[test(),$A];", Node::Ptr(new ArrayUnpack(new Local("a"),
new FunctionCall("test"),
new ExternalVariable("A", CoreType::FLOAT)))
},
{ "a[a++,++a];", Node::Ptr(new ArrayUnpack(new Local("a"),
new Crement(new Local("a"), Crement::Operation::Increment, true),
new Crement(new Local("a"), Crement::Operation::Increment, false)))
},
{ "a[a[0,0],0];", Node::Ptr(new ArrayUnpack(new Local("a"),
new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)),
new Value<int32_t>(0)))
},
{ "a[(1,2,3)];", Node::Ptr(new ArrayUnpack(new Local("a"),
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
})
))
},
{ "a[(1,2,3),(4,5,6)];", Node::Ptr(new ArrayUnpack(new Local("a"),
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3),
}),
new CommaOperator({
new Value<int32_t>(4),
new Value<int32_t>(5),
new Value<int32_t>(6),
})
))
},
{ "a[a[0,0],a[0]];", Node::Ptr(new ArrayUnpack(new Local("a"),
new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)),
new ArrayUnpack(new Local("a"), new Value<int32_t>(0))))
}
// @todo should this be a syntax error
// { "@a[{1,2,3},{1,2,3,4}];", }
};
}
class TestArrayUnpackNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestArrayUnpackNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpackNode);
void TestArrayUnpackNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::ArrayUnpackNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Array Unpack code", code) + os.str());
}
}
}
| 8,853 | C++ | 56.869281 | 144 | 0.521857 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAssignExpressionNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
unittest_util::CodeTests tests =
{
// test an attribute type passes for all expression types
{ "@a = (true);", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) },
{ "@a = (1,2,3);", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3),
})
))
},
{ "@a = test();", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new FunctionCall("test"))) },
{ "@a = 1 + i@b;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new BinaryOperator(new Value<int32_t>(1), new Attribute("b", CoreType::INT32), OperatorToken::PLUS)
))
},
{ "@a = -int@b;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new UnaryOperator(new Attribute("b", CoreType::INT32), OperatorToken::MINUS)
))
},
{ "@a = ++float@b;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Crement(new Attribute("b", CoreType::FLOAT), Crement::Operation::Increment, false)
))
},
{ "@a = bool(2);", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Cast(new Value<int32_t>(2), CoreType::BOOL)
))
},
{ "@a = {1, 2, 3};", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
})
))
},
{ "@a = [email protected];", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0))
))
},
{ "@a = \"b\";", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("b"))) },
{ "@a = b;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Local("b"))) },
// test all attribute
{ "bool@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::BOOL), new Value<bool>(true))) },
{ "int16@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT16), new Value<bool>(true))) },
{ "i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) },
{ "int@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) },
{ "int32@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) },
{ "int64@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT64), new Value<bool>(true))) },
{ "f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) },
{ "float@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) },
{ "double@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::DOUBLE), new Value<bool>(true))) },
{ "vec3i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3I), new Value<bool>(true))) },
{ "v@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) },
{ "vec3f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) },
{ "vec3d@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3D), new Value<bool>(true))) },
{ "s@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) },
{ "string@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) },
// compound assignments (operation is stored implicitly)
{ "@a += true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::PLUS
))
},
{ "@a -= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::MINUS
))
},
{ "@a *= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::MULTIPLY
))
},
{ "@a /= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::DIVIDE
))
},
{ "@a &= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::BITAND
))
},
{ "@a |= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::BITOR
))
},
{ "@a ^= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::BITXOR
))
},
{ "@a %= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::MODULO
))
},
{ "@a <<= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::SHIFTLEFT
))
},
{ "@a >>= true;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new Value<bool>(true),
OperatorToken::SHIFTRIGHT
))
},
// test component assignment
{ "[email protected] = true;", Node::Ptr(new AssignExpression(
new ArrayUnpack(
new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0)
),
new Value<bool>(true)
))
},
{ "vec3i@a[1] = true;", Node::Ptr(new AssignExpression(
new ArrayUnpack(
new Attribute("a", CoreType::VEC3I), new Value<int32_t>(1)
),
new Value<bool>(true)
))
},
{ "[email protected] = true;", Node::Ptr(new AssignExpression(
new ArrayUnpack(
new Attribute("a", CoreType::VEC3I), new Value<int32_t>(2)
),
new Value<bool>(true)
))
},
{ "[email protected] += true;", Node::Ptr(new AssignExpression(
new ArrayUnpack(
new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0)
),
new Value<bool>(true),
OperatorToken::PLUS
))
},
// test other lhs
{ "a = true;", Node::Ptr(new AssignExpression(new Local("a"), new Value<bool>(true))) },
{ "++a = true;", Node::Ptr(new AssignExpression(
new Crement(new Local("a"), Crement::Operation::Increment, false),
new Value<bool>(true)
))
},
{ "++@a = true;", Node::Ptr(new AssignExpression(
new Crement(new Attribute("a", CoreType::FLOAT, true), Crement::Operation::Increment, false),
new Value<bool>(true)
))
},
// chains
{ "@a = @b += 1;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new AssignExpression(
new Attribute("b", CoreType::FLOAT, true),
new Value<int32_t>(1),
OperatorToken::PLUS)
))
},
{ "@a = [email protected] = 1;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new AssignExpression(
new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)),
new Value<int32_t>(1)
)
))
},
{ "@a += [email protected] = x %= 1;", Node::Ptr(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new AssignExpression(
new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)),
new AssignExpression(
new Local("x"),
new Value<int32_t>(1),
OperatorToken::MODULO
)
),
OperatorToken::PLUS
))
}
};
}
class TestAssignExpressionNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestAssignExpressionNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAssignExpressionNode);
void TestAssignExpressionNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::AssignExpressionNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Assign Expression code", code) + os.str());
}
}
}
| 13,318 | C++ | 47.966912 | 134 | 0.443685 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestFunctionCallNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "func();", Node::Ptr(new FunctionCall("func")) },
{ "_();", Node::Ptr(new FunctionCall("_")) },
{ "_1();", Node::Ptr(new FunctionCall("_1")) },
{ "a_();", Node::Ptr(new FunctionCall("a_")) },
{ "_a();", Node::Ptr(new FunctionCall("_a")) },
{ "A();", Node::Ptr(new FunctionCall("A")) },
{ "D1f();", Node::Ptr(new FunctionCall("D1f")) },
{ "f(a);", Node::Ptr(new FunctionCall("f", new Local("a"))) },
{ "a(a,1);", Node::Ptr(new FunctionCall("a", {
new Local("a"),
new Value<int32_t>(1)
}))
},
{ "func(1);", Node::Ptr(new FunctionCall("func",
new Value<int32_t>(1)
))
},
{ "func(\"string\");", Node::Ptr(new FunctionCall("func",
new Value<std::string>("string")
))
},
{ "func(true);", Node::Ptr(new FunctionCall("func",
new Value<bool>(true)
))
},
{ "func({a,b,c});", Node::Ptr(new FunctionCall("func",
new ArrayPack({
new Local("a"),
new Local("b"),
new Local("c")
})
))
},
{ "func((a,b,c));", Node::Ptr(new FunctionCall("func",
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
})
))
},
{ "func(@a);", Node::Ptr(new FunctionCall("func",
new Attribute("a", CoreType::FLOAT, true)
))
},
{ "func(++a);", Node::Ptr(new FunctionCall("func",
new Crement(new Local("a"), Crement::Operation::Increment, false)
))
},
{ "func(~a);", Node::Ptr(new FunctionCall("func",
new UnaryOperator(new Local("a"), OperatorToken::BITNOT)
))
},
{ "func((a));", Node::Ptr(new FunctionCall("func",
new Local("a")
))
},
{ "func1(func2());", Node::Ptr(new FunctionCall("func1",
new FunctionCall("func2")
))
},
{ "func(a=b);", Node::Ptr(new FunctionCall("func",
new AssignExpression(new Local("a"), new Local("b"))
))
},
{ "func(a==b);", Node::Ptr(new FunctionCall("func",
new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS)
))
},
{ "func(a.x);", Node::Ptr(new FunctionCall("func",
new ArrayUnpack(new Local("a"), new Value<int32_t>(0))
))
},
{ "func(bool(a));", Node::Ptr(new FunctionCall("func",
new Cast(new Local("a"), CoreType::BOOL)
))
},
{ "func(a,b,c,d,e,f);", Node::Ptr(new FunctionCall("func", {
new Local("a"), new Local("b"), new Local("c"),
new Local("d"), new Local("e"), new Local("f")
}
))
},
{ "func((a, b), c);", Node::Ptr(new FunctionCall("func", {
new CommaOperator({ new Local("a"), new Local("b") }),
new Local("c")
}))
}
};
}
class TestFunctionCallNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestFunctionCallNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionCallNode);
void TestFunctionCallNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::FunctionCallNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Function Call code", code) + os.str());
}
}
}
| 6,011 | C++ | 37.292993 | 111 | 0.433539 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestSyntaxFailures.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "test/util.h"
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb_ax/Exceptions.h>
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
#include <cppunit/extensions/HelperMacros.h>
namespace {
// mimics std::pair<std::string, null>
struct StrWrapper {
StrWrapper(const char* str) : first(str) {}
const std::string first;
};
static const std::vector<StrWrapper> tests {
// invalid r-value syntax
"@a = @;",
"@a = =;",
"@a = +;",
"@a = -;",
"@a = *;",
"@a = /;",
"@a = %;",
"@a = |;",
"@a = &;",
"@a = ^;",
"@a = ~;",
"@a = ==;",
"@a = !=;",
"@a = >;",
"@a = <;",
"@a = >=;",
"@a = <=;",
"@a = +=;",
"@a = -=;",
"@a = *=;",
"@a = /=;",
"@a = ++;",
"@a = --;",
"@a = &&;",
"@a = ||;",
"@a = !;",
"@a = ,;",
"@a = (;",
"@a = );",
"@a = {;",
"@a =};",
"@a = .x;",
"@a = .y;",
"@a = .z;",
"@a = .r;",
"@a = .g;",
"@a = .b;",
"@a = f@;",
"@a = i@;",
"@a = v@;",
"@a = s@;",
"@a = if;",
"@a = else;",
"@a = return;",
"@a = ;",
"@a = {};",
"@a = \"a;",
"[email protected] = 0;",
"$a = $;",
"$a = =;",
"$a = +;",
"$a = -;",
"$a = *;",
"$a = /;",
"$a = %;",
"$a = |;",
"$a = &;",
"$a = ^;",
"$a = ~;",
"$a = ==;",
"$a = !=;",
"$a = >;",
"$a = <;",
"$a = >=;",
"$a = <=;",
"$a = +=;",
"$a = -=;",
"$a = *=;",
"$a = /=;",
"$a = ++;",
"$a = --;",
"$a = &&;",
"$a = ||;",
"$a = !;",
"$a = ,;",
"$a = (;",
"$a = );",
"$a = {;",
"$a =};",
"$a = .x;",
"$a = .y;",
"$a = .z;",
"$a = .r;",
"$a = .g;",
"$a = .b;",
"$a = f$;",
"$a = i$;",
"$a = v$;",
"$a = s$;",
"$a = if;",
"$a = else;",
"$a = return;",
"$a = ;",
"$a = {};",
"$a = {1};",
"$a = \"a;",
"v$a[0] = 0;",
"v$a.a = 0;",
// @todo these should probably be valid syntax and the code
// generators should handle assignments based on the current
// r/lvalues
"5 = 5;",
"$a = 5;",
// invalid l-value
// TODO: these should fail syntax tests
// {"+@a = 0;", },
// {"-@a = 0;", },
// {"~@a = 0;", },
// {"!@a = 0;", },
// "++@a = 0;",
// "--@a = 0;",
"=@a;",
"*@a;",
"/@a;",
"%@a;",
"|@a;",
"&@a;",
"^@a;",
"==@a;",
"!=@a;",
">@a;",
"<@a;",
">=@a;",
"<=@a;",
"+=@a;",
"-=@a;",
"*=@a;",
"/=@a;",
"&&@a;",
"||@a;",
",@a;",
"(@a;",
")@a;",
"{@a;",
"}@a;",
".x@a;",
".y@a;",
".z@a;",
".r@a;",
".g@a;",
".b@a;",
"@@a;",
"f@@a;",
"i@@a;",
"v@@a;",
"s@@a;",
"if@a;",
"else@a;",
"return@a;",
"{1}@a;",
"\"a\"@a;",
"b@a;",
"sht@a;",
"it@a;",
"l@a;",
"flt@a;",
"dbl@a;",
"vecint@a;",
"vint@a;",
"vfloat@a;",
"vecflt@a;",
"vflt@a;",
"vdouble@a;",
"vecdbl@a;",
"vdbl@a;",
"str@a;",
"++$a = 0;",
"--$a = 0;",
"=$a;",
"*$a;",
"/$a;",
"%$a;",
"|$a;",
"&$a;",
"^$a;",
"==$a;",
"!=$a;",
">$a;",
"<$a;",
">=$a;",
"<=$a;",
"+=$a;",
"-=$a;",
"*=$a;",
"/=$a;",
"&&$a;",
"||$a;",
",$a;",
"($a;",
")$a;",
"{$a;",
"}$a;",
".x$a;",
".y$a;",
".z$a;",
".r$a;",
".g$a;",
".b$a;",
"$$a;",
"f$$a;",
"i$$a;",
"v$$a;",
"s$$a;",
"if$a;",
"else$a;",
"return$a;",
"{1}$a;",
"\"a\"$a;",
"b$a;",
"sht$a;",
"it$a;",
"l$a;",
"flt$a;",
"dbl$a;",
"vecint$a;",
"vint$a;",
"vfloat$a;",
"vecflt$a;",
"vflt$a;",
"vdouble$a;",
"vecdbl$a;",
"vdbl$a;",
"str$a;",
"a ! a;",
"a ~ a;",
"a \\ a;",
"a ? a;",
"bool + a;",
"bool a + a;",
"return + a;",
"if + a;",
"a + if(true) {};",
"{} + {};",
"~ + !;",
"+ + -;",
"; + ;",
"int();",
"int(return);",
"int(if(true) {});",
"int(;);",
"int(bool a;);",
"int(bool a);",
"int{a};",
"int[a];",
"string(a);",
"vector(a);",
"vec3i(a);",
"vec3f(a);",
"vec3d(a);",
// invalid if block
"if (a) {b}",
"if (a) else ();",
"if (); else (a);",
"if (a) if(b) {if (c)} else {}",
"if (if(a));",
"if ();",
"if (); else ;",
"if (); else ();",
"if (); else () {}",
"if (); elf {}",
"if (a) {} elif (b) {}",
"else {}",
"else ;",
"if a;",
"if a {} elif b {}",
"if (a); else ; else ;",
"else (a); ",
"if (a) {}; else {};",
"if (a) {b = 1} else {};",
"if (a) {} ; else {}",
"if () {}; else (a);",
// invalid ternary
"?;",
":;",
"? :;",
"? : false;",
"true ? :;",
"true ? false;",
"true ? false :;",
"true : 1 ? 2;",
"true ? 1 ? 2;",
"true : 1 : 2;",
"true ?? 1 : 2;",
"true (? 1 :) 2;",
"true (?:) 2;",
"true (? false ? 1 : 2): 3;",
"true ? (false ? 1 : 2:) 3;",
"(true ? false ? 1 : 2): 3;",
// invalid crement
"++5;",
"5++;",
"--5;",
"5--;",
"++5--;",
"++5++;",
"--5++;",
"--5--;",
"{ 1, 1, 1}++;",
"++{ 1, 1, 1};",
"--{ 1, 1, 1};",
"{ 1, 1, 1}--;",
"++{ 1, 1, 1}++;",
"++{ 1, 1, 1}--;",
"--{ 1, 1, 1}--;",
"++a-;",
//"++a--;",
//"++a++;",
//"--a++;",
//"--a--;",
//"----a;",
//"++++a;",
//"a.x--;",
//"-a.y--;",
//"++a.z;",
//"++@a--;",
//"@a.x--;",
//"[email protected];",
//"[email protected];",
"++$a--;",
"$a.x--;",
"-$a.y--;",
"++$a.z;",
"--f();",
"f()++;",
"return++;",
"--return;",
"true++;",
"--false;",
"--if;",
"if++;",
"else++;",
"--else;",
"--bool;",
"short++;",
"--int;",
"long++;",
"--float;",
"++double;",
"--vector;",
"matrix--;",
"--();",
"()++;",
"{}++;",
"--{};",
"--,;",
",--;",
// invalid declare
"int;",
"int 1;",
"string int;",
"int bool a;",
"int a",
"vector a",
"vector float a",
// invalid function
"function(;",
"function);",
"return();",
"function(bool);",
"function(bool a);",
"function(+);",
"function(!);",
"function(~);",
"function(-);",
"function(&&);",
"function{};" ,
"function(,);" ,
"function(, a);",
"function(a, );",
"function({,});",
"function({});",
"function({)};",
"function{()};",
"function{(});",
"function{,};",
"function(if(true) {});",
"function(return);",
"function(return;);",
"function(while(true) a);",
"function(while(true) {});",
"\"function\"();" ,
"();",
"+();",
"10();",
// invalid keyword return
"return",
"int return;",
"return return;",
"return max(1, 2);",
"return 1 + a;",
"return !a;",
"return a = 1;",
"return a.x = 1;",
"return ++a;",
"return int(a);",
"return {1, 2, 3};",
"return a[1];",
"return true;",
"return 0;",
"return (1);",
"return \"a\";",
"return int a;",
"return a;",
"return @a;",
// invalid unary
"+bool;" ,
"+bool a;" ,
"bool -a;" ,
"-return;" ,
"!return;" ,
"+return;" ,
"~return;" ,
"~if(a) {};" ,
"if(a) -{};" ,
"if(a) {} !else {};",
// @todo unary crementation expressions should be parsable but perhaps
// not compilable
"---a;" ,
"+++a;" ,
// invalid value
".0.0;",
".0.0f;",
".f;",
"0..0;",
"0.0l;",
"0.0ls;",
"0.0s;",
"0.0sf;",
"0.a",
"0.af",
"00ls;",
"0ef;",
"0f0;",
"1.0f.0;",
"1.\"1\";",
"1.e6f;",
"10000000.00000001s;",
"1e.6f;",
"1Ee6;",
"1ee6;",
"1eE6f;",
"1ee6f;",
"1l.0;",
"1s.0;",
"\"1.\"2;",
"a.0",
"a.0f",
"false.0;",
"true.;",
// invalid vector
"{1,2,3];",
"[1,2,3};",
"{,,};",
"{,2,3};",
"{()};",
"{(1,)};",
"{(,1)};",
"{(1});",
"({1)};",
"{1,};",
"{,1};",
// invalid vector unpack
"5.x;",
"foo.2;",
"a.w;",
"a.X;",
"a.Y;",
"a.Z;",
"@a.X;",
"@a.Y;",
"@a.Z;",
"$a.X;",
"$a.Y;",
"$a.Z;",
"a.xx;",
"a++.x",
"++a.x",
"func().x",
"int(y).x",
"vector .",
"vector .x",
"vector foo.x",
"(a + b).x",
"(a).x;",
"(@a).x;",
"@.x;",
"($a).x;",
"$.x;",
"true.x;",
"a.rx;",
"a.rgb;",
// other failures (which may be used in the future)
"function<>();",
"function<true>();",
"a[1:1];",
"a.a;",
"a->a;",
"&a;",
"a . a;",
"a .* a;",
"@a();",
"$a();",
"@a.function();",
"@a.member;",
"/**/;",
"(a,a,a) = (b,b,b);",
"(a,a,a) = 1;",
"(a) = 1;",
"a = (a=a) = a;",
// invalid lone characters
"£;",
"`;",
"¬;",
"@;",
"~;",
"+;",
"-;",
"*;",
"/;",
"<<;",
">>;",
">;",
"<;",
"[];",
"|;",
",;",
"!;",
"\\;"
};
}
class TestSyntaxFailures : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestSyntaxFailures);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST_SUITE_END();
void testSyntax();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestSyntaxFailures);
void TestSyntaxFailures::testSyntax()
{
// Quickly check the above doesn't have multiple occurance
// store multiple in a hash map
const auto hash = [](const StrWrapper* s) {
return std::hash<std::string>()(s->first);
};
const auto equal = [](const StrWrapper* s1, const StrWrapper* s2) {
return s1->first.compare(s2->first) == 0;
};
std::unordered_map<const StrWrapper*,
size_t, decltype(hash), decltype(equal)> map(tests.size(), hash, equal);
for (const auto& test : tests) {
++map[&test];
}
// Print strings that occur more than once
for (auto iter : map) {
if (iter.second > 1) {
std::cout << iter.first->first << " printed x" << iter.second << std::endl;
}
}
TEST_SYNTAX_FAILS(tests);
}
| 10,391 | C++ | 15.87013 | 87 | 0.307381 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestTernaryOperatorNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "true ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))},
{ "true ? a : 1.5f;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Local("a"), new Value<float>(1.5f)))},
{ "false ? true : false;", Node::Ptr(new TernaryOperator(new Value<bool>(false), new Value<bool>(true), new Value<bool>(false)))},
{ "a == b ? 1 : 0;", Node::Ptr(new TernaryOperator(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::EQUALSEQUALS),
new Value<int32_t>(1),
new Value<int32_t>(0)))},
{ "a++ ? 1 : 0;", Node::Ptr(new TernaryOperator(
new Crement(new Local("a"), Crement::Operation::Increment, true),
new Value<int32_t>(1),
new Value<int32_t>(0)))},
{ "@a ? 1 : 0;", Node::Ptr(new TernaryOperator(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0)))},
{ "func() ? 1 : 0;", Node::Ptr(new TernaryOperator(new FunctionCall("func"), new Value<int32_t>(1), new Value<int32_t>(0)))},
{ "(true) ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))},
{ "true ? 3 : 2 ? 1 : 0;", Node::Ptr(new TernaryOperator(
new Value<bool>(true),
new Value<int32_t>(3),
new TernaryOperator(new Value<int32_t>(2), new Value<int32_t>(1), new Value<int32_t>(0))))},
{ "(true ? 3 : 2) ? 1 : 0;", Node::Ptr(new TernaryOperator(
new TernaryOperator(new Value<bool>(true), new Value<int32_t>(3), new Value<int32_t>(2)),
new Value<int32_t>(1),
new Value<int32_t>(0)))},
{ "true ? \"foo\" : \"bar\";", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<std::string>("foo"), new Value<std::string>("bar")))},
{ "true ? voidfunc1() : voidfunc2();", Node::Ptr(new TernaryOperator(new Value<bool>(true), new FunctionCall("voidfunc1"), new FunctionCall("voidfunc2")))},
{ "true ? {1,1,1} : {0,0,0};", Node::Ptr(new TernaryOperator(
new Value<bool>(true),
new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(1),
new Value<int32_t>(1)
})
,
new ArrayPack({
new Value<int32_t>(0),
new Value<int32_t>(0),
new Value<int32_t>(0)
})
))},
{ "true ? false ? 3 : 2 : 1;" , Node::Ptr(new TernaryOperator(
new Value<bool>(true),
new TernaryOperator(
new Value<bool>(false),
new Value<int32_t>(3),
new Value<int32_t>(2)),
new Value<int32_t>(1)))},
{ "true ? false ? 3 : 2 : (true ? 4 : 5);" , Node::Ptr(new TernaryOperator(
new Value<bool>(true),
new TernaryOperator(
new Value<bool>(false),
new Value<int32_t>(3),
new Value<int32_t>(2)),
new TernaryOperator(
new Value<bool>(true),
new Value<int32_t>(4),
new Value<int32_t>(5))))},
{ "true ? : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), nullptr, new Value<int32_t>(0)))},
};
}
class TestTernaryOperatorNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestTernaryOperatorNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestTernaryOperatorNode);
void TestTernaryOperatorNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::TernaryOperatorNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Ternary Operator code", code) + os.str());
}
}
}
| 7,769 | C++ | 59.703125 | 177 | 0.387051 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLoopNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "for (int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for(int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (int32 i = 0;i < 10;++i) ;", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new Local("i"),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (@i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new Attribute("i", CoreType::FLOAT, true),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (!i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new UnaryOperator(new Local("i"), OperatorToken::NOT),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new AssignExpression(new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (i+j; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new BinaryOperator(new Local("i"), new Local("j"), OperatorToken::PLUS),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (func(i); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new FunctionCall("func", new Local("i")),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (1; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new Value<int32_t>(1),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (float$ext; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new ExternalVariable("ext", CoreType::FLOAT),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (i++; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new Crement(new Local("i"), Crement::Operation::Increment, true),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for ({1,2.0,3.0f}; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new ArrayPack({new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f)}),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (1,2.0,3.0f; (i < 10, i > 10); (++i, --i)) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new CommaOperator({
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::MORETHAN)
}),
new Block(),
new CommaOperator({
new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f)
}),
new CommaOperator({
new Crement(new Local("i"), Crement::Operation::Increment, false),
new Crement(new Local("i"), Crement::Operation::Decrement, false),
})
))
},
{ "for (++i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new Crement(new Local("i"), Crement::Operation::Increment, false),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (x[2]; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new ArrayUnpack(new Local("x"), new Value<int32_t>(2)),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for ((x[2]); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new ArrayUnpack(new Local("x"), new Value<int32_t>(2)),
new Crement(new Local("i"), Crement::Operation::Increment, false)))
},
{ "for (; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
nullptr,
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (int32 i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new CommaOperator({
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false),
new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false)
})))
},
{ "for (i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new AssignExpression(new Local("i"), new Value<int32_t>(0)),
new CommaOperator({
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false),
new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false)
})))
},
{ "for (int32 i = 0; i; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new Local("i"),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (int32 i = 0; func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new FunctionCall("func", new Local("i")),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (int32 i = 0; int32 j = func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new DeclareLocal(CoreType::INT32, new Local("j"),new FunctionCall("func", new Local("i"))),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (; i < 10;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block()))
},
{ "for (;;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new Value<bool>(true),
new Block()))
},
{ "for (;;) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new Value<bool>(true),
new Block(new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
},
{ "for (;;) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new Value<bool>(true),
new Block(new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
},
{ "for (int32 i = 0, j = 0, k; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new StatementList({new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new DeclareLocal(CoreType::INT32, new Local("j"), new Value<int32_t>(0)),
new DeclareLocal( CoreType::INT32, new Local("k"))}),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (i = 0, j = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new Block(),
new CommaOperator({
new AssignExpression(new Local("i"), new Value<int32_t>(0)),
new AssignExpression(new Local("j"), new Value<int32_t>(0))
}),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "for (int32 i = 0; i < 10, j < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR,
new CommaOperator({
new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN),
new BinaryOperator(new Local("j"), new Value<int32_t>(10), OperatorToken::LESSTHAN)
}),
new Block(),
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false)))
},
{ "while (int32 i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Block()))
},
{ "while (i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new AssignExpression(new Local("i"), new Value<int32_t>(0)),
new Block()))
},
{ "while ((a,b,c)) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
}),
new Block()))
},
{ "while (i < 0, j = 10) ;", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new CommaOperator({
new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN),
new AssignExpression(new Local("j"), new Value<int32_t>(10))
}),
new Block()))
},
{ "while (i) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new Local("i"),
new Block(new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
},
{ "while (i) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::WHILE,
new Local("i"),
new Block(new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
},
{ "do {} while (i < 0, j = 10)", Node::Ptr(new Loop(tokens::LoopToken::DO,
new CommaOperator({
new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN),
new AssignExpression(new Local("j"), new Value<int32_t>(10))
}),
new Block()))
},
{ "do ; while (int32 i = 0)", Node::Ptr(new Loop(tokens::LoopToken::DO,
new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)),
new Block()))
},
{ "do ; while ((a,b,c))", Node::Ptr(new Loop(tokens::LoopToken::DO,
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
}),
new Block()))
},
{ "do ; while (a,b,c)", Node::Ptr(new Loop(tokens::LoopToken::DO,
new CommaOperator({
new Local("a"),
new Local("b"),
new Local("c")
}),
new Block()))
},
{ "do { 1,2,3 }; while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO,
new Local("i"),
new Block(new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
},
{ "do { 1,2,3; } while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO,
new Local("i"),
new Block(new CommaOperator({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
}))))
}
};
}
class TestLoopNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestLoopNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestLoopNode);
void TestLoopNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::LoopNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Loop code", code) + os.str());
}
}
}
| 21,950 | C++ | 61.008474 | 144 | 0.405011 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAttributeNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "bool@_a;", Node::Ptr(new Attribute("_a", CoreType::BOOL)) },
{ "int16@a_;", Node::Ptr(new Attribute("a_", CoreType::INT16)) },
{ "i@a1;", Node::Ptr(new Attribute("a1", CoreType::INT32)) },
{ "int@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) },
{ "int32@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) },
{ "int64@a;", Node::Ptr(new Attribute("a", CoreType::INT64)) },
{ "@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT, true)) },
{ "f@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) },
{ "float@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) },
{ "double@a;", Node::Ptr(new Attribute("a", CoreType::DOUBLE)) },
{ "vec2i@a;", Node::Ptr(new Attribute("a", CoreType::VEC2I)) },
{ "vec2f@a;", Node::Ptr(new Attribute("a", CoreType::VEC2F)) },
{ "vec2d@a;", Node::Ptr(new Attribute("a", CoreType::VEC2D)) },
{ "vec3i@a;", Node::Ptr(new Attribute("a", CoreType::VEC3I)) },
{ "v@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) },
{ "vec3f@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) },
{ "vec3d@a;", Node::Ptr(new Attribute("a", CoreType::VEC3D)) },
{ "vec4i@a;", Node::Ptr(new Attribute("a", CoreType::VEC4I)) },
{ "vec4f@a;", Node::Ptr(new Attribute("a", CoreType::VEC4F)) },
{ "vec4d@a;", Node::Ptr(new Attribute("a", CoreType::VEC4D)) },
{ "mat3f@a;", Node::Ptr(new Attribute("a", CoreType::MAT3F)) },
{ "mat3d@a;", Node::Ptr(new Attribute("a", CoreType::MAT3D)) },
{ "mat4f@a;", Node::Ptr(new Attribute("a", CoreType::MAT4F)) },
{ "mat4d@a;", Node::Ptr(new Attribute("a", CoreType::MAT4D)) },
{ "string@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) },
{ "s@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) },
};
}
class TestAttributeNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestAttributeNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAttributeNode);
void TestAttributeNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::AttributeNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Attribute code", code) + os.str());
}
}
}
| 3,758 | C++ | 38.568421 | 93 | 0.601384 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestValueNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
#include <cstdlib>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
using CodeTestMap = std::map<Node::NodeType, unittest_util::CodeTests>;
auto converti(const char* c) -> uint64_t { return std::strtoull(c, /*end*/nullptr, /*base*/10); }
auto convertf(const char* c) -> float { return std::strtof(c, /*end*/nullptr); }
auto convertd(const char* c) -> double { return std::strtod(c, /*end*/nullptr); }
template <typename T>
std::string fullDecimalValue(const T t) {
// 767 is max number of digits necessary to accurately represent base 2 doubles
std::ostringstream os;
os << std::setprecision(767) << t;
return os.str();
}
static const CodeTestMap value_tests =
{
// No limits::lowest, negative values are a unary operator
{
Node::NodeType::ValueBoolNode,
{
{ "false;", Node::Ptr(new Value<bool>(false)) },
{ "true;", Node::Ptr(new Value<bool>(true)) },
}
},
{
Node::NodeType::ValueInt32Node,
{
{ "00;", Node::Ptr(new Value<int32_t>(converti("0"))) },
{ "1000000000000000;", Node::Ptr(new Value<int32_t>(converti("1000000000000000"))) }, // signed int wrap
{ "0;", Node::Ptr(new Value<int32_t>(converti("0"))) },
{ "1234567890;", Node::Ptr(new Value<int32_t>(converti("1234567890"))) },
{ "1;", Node::Ptr(new Value<int32_t>(converti("1"))) },
// signed int wrap
{ std::to_string(std::numeric_limits<int64_t>::max()) + ";",
Node::Ptr(new Value<int32_t>(std::numeric_limits<int64_t>::max()))
},
// signed int wrap
{ std::to_string(std::numeric_limits<uint64_t>::max()) + ";",
Node::Ptr(new Value<int32_t>(std::numeric_limits<uint64_t>::max()))
},
// signed int wrap
{ std::to_string(std::numeric_limits<int32_t>::max()) + "0;",
Node::Ptr(new Value<int32_t>(uint64_t(std::numeric_limits<int32_t>::max()) * 10ul))
}
}
},
{
Node::NodeType::ValueInt64Node,
{
{ "01l;", Node::Ptr(new Value<int64_t>(converti("1"))) },
{ "0l;", Node::Ptr(new Value<int64_t>(converti("0"))) },
{ "1234567890l;", Node::Ptr(new Value<int64_t>(converti("1234567890l"))) },
// signed int wrap
{ std::to_string(uint64_t(std::numeric_limits<int64_t>::max()) + 1) + "l;",
Node::Ptr(new Value<int64_t>(uint64_t(std::numeric_limits<int64_t>::max()) + 1ul))
}
}
},
{
Node::NodeType::ValueFloatNode,
{
{ ".123456789f;", Node::Ptr(new Value<float>(convertf(".123456789f"))) },
{ "0.0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) },
{ "00.f;", Node::Ptr(new Value<float>(convertf("0.0f"))) },
{ "0e+0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) },
{ "0e-0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) },
{ "0e0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) },
{ "1234567890.0987654321f;", Node::Ptr(new Value<float>(convertf("1234567890.0987654321f"))) },
{ "1e+6f;", Node::Ptr(new Value<float>(convertf("1e+6f"))) },
{ "1E+6f;", Node::Ptr(new Value<float>(convertf("1E+6f"))) },
{ "1e-6f;", Node::Ptr(new Value<float>(convertf("1e-6f"))) },
{ "1E-6f;", Node::Ptr(new Value<float>(convertf("1E-6f"))) },
{ "1e6f;", Node::Ptr(new Value<float>(convertf("1e6f"))) },
{ "1E6f;", Node::Ptr(new Value<float>(convertf("1E6f"))) }
}
},
{
Node::NodeType::ValueDoubleNode,
{
{ ".123456789;", Node::Ptr(new Value<double>(convertd(".123456789"))) },
{ "0.0;", Node::Ptr(new Value<double>(convertd("0.0"))) },
{ "0e0;", Node::Ptr(new Value<double>(convertd("0.0f"))) },
{ "1.0;", Node::Ptr(new Value<double>(convertd("1.0"))) },
{ "1234567890.00000000;", Node::Ptr(new Value<double>(convertd("1234567890.0"))) },
{ "1234567890.0987654321;", Node::Ptr(new Value<double>(convertd("1234567890.0987654321"))) },
{ "1234567890.10000000;", Node::Ptr(new Value<double>(convertd("1234567890.1"))) },
{ "1234567890e-0;", Node::Ptr(new Value<double>(convertd("1234567890e-0"))) },
{ "1e+6;", Node::Ptr(new Value<double>(convertd("1e+6"))) },
{ "1e-6;", Node::Ptr(new Value<double>(convertd("1e-6"))) },
{ "1e01;", Node::Ptr(new Value<double>(convertd("1e01"))) },
{ "1e6;", Node::Ptr(new Value<double>(convertd("1e6"))) },
{ "1E6;", Node::Ptr(new Value<double>(convertd("1E6"))) },
{ std::to_string(std::numeric_limits<double>::max()) + ";",
Node::Ptr(new Value<double>(std::numeric_limits<double>::max()))
},
{ fullDecimalValue(std::numeric_limits<double>::max()) + ".0;",
Node::Ptr(new Value<double>(std::numeric_limits<double>::max()))
},
{ fullDecimalValue(std::numeric_limits<double>::min()) + ";",
Node::Ptr(new Value<double>(std::numeric_limits<double>::min()))
}
}
},
{
Node::NodeType::ValueStrNode,
{
{ "\"0.0\";", Node::Ptr(new Value<std::string>("0.0")) },
{ "\"0.0f\";", Node::Ptr(new Value<std::string>("0.0f")) },
{ "\"0\";", Node::Ptr(new Value<std::string>("0")) },
{ "\"1234567890.0987654321\";", Node::Ptr(new Value<std::string>("1234567890.0987654321")) },
{ "\"1234567890\";", Node::Ptr(new Value<std::string>("1234567890")) },
{ "\"a1b2c3d4.e5f6g7.0\";", Node::Ptr(new Value<std::string>("a1b2c3d4.e5f6g7.0")) },
{ "\"literal\";", Node::Ptr(new Value<std::string>("literal")) },
{ "\"\";", Node::Ptr(new Value<std::string>("")) },
{ "\"" + std::to_string(std::numeric_limits<double>::lowest()) + "\";",
Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::lowest())))
},
{ "\"" + std::to_string(std::numeric_limits<double>::max()) + "\";",
Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::max())))
},
{ "\"" + std::to_string(std::numeric_limits<int64_t>::lowest()) + "\";",
Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::lowest())))
},
{ "\"" + std::to_string(std::numeric_limits<int64_t>::max()) + "\";",
Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::max())))
}
}
}
};
}
class TestValueNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestValueNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() {
for (const auto& tests : value_tests) {
TEST_SYNTAX_PASSES(tests.second);
}
}
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestValueNode);
void TestValueNode::testASTNode()
{
for (const auto& tests : value_tests) {
const Node::NodeType nodeType = tests.first;
for (const auto& test : tests.second) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
nodeType == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Value (literal) code", code) + os.str());
}
}
}
}
| 9,562 | C++ | 44.538095 | 117 | 0.497804 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLocalNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "a_;", Node::Ptr(new Local("a_")) },
{ "_a;", Node::Ptr(new Local("_a")) },
{ "_;", Node::Ptr(new Local("_")) },
{ "aa;", Node::Ptr(new Local("aa")) },
{ "A;", Node::Ptr(new Local("A")) },
{ "_A;", Node::Ptr(new Local("_A")) },
{ "a1;", Node::Ptr(new Local("a1")) },
{ "_1;", Node::Ptr(new Local("_1")) },
{ "abc;", Node::Ptr(new Local("abc")) },
{ "D1f;", Node::Ptr(new Local("D1f")) },
{ "var;", Node::Ptr(new Local("var")) }
};
}
class TestLocalNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestLocalNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestLocalNode);
void TestLocalNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::LocalNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Local code", code) + os.str());
}
}
}
| 2,395 | C++ | 28.580247 | 92 | 0.59666 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestKeywordNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "return;", Node::Ptr(new Keyword(KeywordToken::RETURN)) },
{ "break;", Node::Ptr(new Keyword(KeywordToken::BREAK)) },
{ "continue;", Node::Ptr(new Keyword(KeywordToken::CONTINUE)) }
};
}
class TestKeywordNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestKeywordNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestKeywordNode);
void TestKeywordNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
const Keyword* resultAsKeyword = static_cast<const Keyword*>(result);
CPPUNIT_ASSERT(resultAsKeyword);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::KeywordNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Return code", code) + os.str());
}
}
}
| 2,225 | C++ | 29.081081 | 92 | 0.650337 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestExternalVariableNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) },
{ "bool$_a;", Node::Ptr(new ExternalVariable("_a", CoreType::BOOL)) },
{ "i$a1;", Node::Ptr(new ExternalVariable("a1", CoreType::INT32)) },
{ "int$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) },
{ "int32$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) },
{ "int64$a;", Node::Ptr(new ExternalVariable("a", CoreType::INT64)) },
{ "f$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) },
{ "float$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) },
{ "double$a;", Node::Ptr(new ExternalVariable("a", CoreType::DOUBLE)) },
{ "vec3i$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3I)) },
{ "v$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) },
{ "vec3f$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) },
{ "vec3d$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3D)) },
{ "string$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) },
{ "s$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) },
};
}
class TestExternalVariableNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestExternalVariableNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestExternalVariableNode);
void TestExternalVariableNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::ExternalVariableNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for External Variable code", code) + os.str());
}
}
}
| 3,130 | C++ | 36.273809 | 101 | 0.630671 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestBinaryOperatorNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "a + b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::PLUS
)
)
},
{ "a - b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::MINUS
)
)
},
{ "a * b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::MULTIPLY
)
)
},
{ "a / b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::DIVIDE
)
)
},
{ "a % b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::MODULO
)
)
},
{ "a << b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::SHIFTLEFT
)
)
},
{ "a >> b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::SHIFTRIGHT
)
)
},
{ "a & b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::BITAND
)
)
},
{ "a | b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::BITOR
)
)
},
{ "a ^ b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::BITXOR
)
)
},
{ "a && b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::AND
)
)
},
{ "a || b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::OR
)
)
},
{ "a == b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::EQUALSEQUALS
)
)
},
{ "a != b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::NOTEQUALS
)
)
},
{ "a > b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::MORETHAN
)
)
},
{ "a < b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::LESSTHAN
)
)
},
{ "a >= b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::MORETHANOREQUAL
)
)
},
{ "a <= b;", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::LESSTHANOREQUAL
)
)
},
{ "(a) + (a);", Node::Ptr(
new BinaryOperator(
new Local("a"),
new Local("a"),
OperatorToken::PLUS
)
)
},
{ "(a,b,c) + (d,e,f);", Node::Ptr(
new BinaryOperator(
new CommaOperator({
new Local("a"), new Local("b"), new Local("c")
}),
new CommaOperator({
new Local("d"), new Local("e"), new Local("f")
}),
OperatorToken::PLUS
)
)
},
{ "func1() + func2();", Node::Ptr(
new BinaryOperator(
new FunctionCall("func1"),
new FunctionCall("func2"),
OperatorToken::PLUS
)
)
},
{ "a + b - c;", Node::Ptr(
new BinaryOperator(
new BinaryOperator(
new Local("a"),
new Local("b"),
OperatorToken::PLUS
),
new Local("c"),
OperatorToken::MINUS
)
)
},
{ "~a + !b;", Node::Ptr(
new BinaryOperator(
new UnaryOperator(new Local("a"), OperatorToken::BITNOT),
new UnaryOperator(new Local("b"), OperatorToken::NOT),
OperatorToken::PLUS
)
)
},
{ "++a - --b;", Node::Ptr(
new BinaryOperator(
new Crement(new Local("a"), Crement::Operation::Increment, false),
new Crement(new Local("b"), Crement::Operation::Decrement, false),
OperatorToken::MINUS
)
)
},
{ "a-- + b++;", Node::Ptr(
new BinaryOperator(
new Crement(new Local("a"), Crement::Operation::Decrement, true),
new Crement(new Local("b"), Crement::Operation::Increment, true),
OperatorToken::PLUS
)
)
},
{ "int(a) + float(b);", Node::Ptr(
new BinaryOperator(
new Cast(new Local("a"), CoreType::INT32),
new Cast(new Local("b"), CoreType::FLOAT),
OperatorToken::PLUS
)
)
},
{ "{a,b,c} + {d,e,f};", Node::Ptr(
new BinaryOperator(
new ArrayPack({
new Local("a"),
new Local("b"),
new Local("c")
}),
new ArrayPack({
new Local("d"),
new Local("e"),
new Local("f")
}),
OperatorToken::PLUS
)
)
},
{ "a.x + b.y;", Node::Ptr(
new BinaryOperator(
new ArrayUnpack(new Local("a"), new Value<int32_t>(0)),
new ArrayUnpack(new Local("b"), new Value<int32_t>(1)),
OperatorToken::PLUS
)
)
},
{ "0 + 1;", Node::Ptr(
new BinaryOperator(
new Value<int32_t>(0),
new Value<int32_t>(1),
OperatorToken::PLUS
)
)
},
{ "0.0f + 1.0;", Node::Ptr(
new BinaryOperator(
new Value<float>(0.0),
new Value<double>(1.0),
OperatorToken::PLUS
)
)
},
{ "@a + @b;", Node::Ptr(
new BinaryOperator(
new Attribute("a", CoreType::FLOAT, true),
new Attribute("b", CoreType::FLOAT, true),
OperatorToken::PLUS
)
)
},
{ "\"a\" + \"b\";", Node::Ptr(
new BinaryOperator(
new Value<std::string>("a"),
new Value<std::string>("b"),
OperatorToken::PLUS
)
)
},
};
}
class TestBinaryOperatorNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestBinaryOperatorNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestBinaryOperatorNode);
void TestBinaryOperatorNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::BinaryOperatorNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Binary Operator code", code) + os.str());
}
}
}
| 14,725 | C++ | 42.184751 | 106 | 0.267029 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestDeclareLocalNode.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "bool a_;", Node::Ptr(new DeclareLocal(CoreType::BOOL, new Local("a_"))) },
{ "int32 _;", Node::Ptr(new DeclareLocal(CoreType::INT32, new Local("_"))) },
{ "int64 aa;", Node::Ptr(new DeclareLocal(CoreType::INT64, new Local("aa"))) },
{ "float A;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("A"))) },
{ "double _A;", Node::Ptr(new DeclareLocal(CoreType::DOUBLE, new Local("_A"))) },
{ "vec2i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC2I, new Local("a1"))) },
{ "vec2f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC2F, new Local("_1"))) },
{ "vec2d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC2D, new Local("abc"))) },
{ "vec3i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC3I, new Local("a1"))) },
{ "vec3f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("_1"))) },
{ "vec3d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC3D, new Local("abc"))) },
{ "vec4i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC4I, new Local("a1"))) },
{ "vec4f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC4F, new Local("_1"))) },
{ "vec4d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC4D, new Local("abc"))) },
{ "mat3f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F, new Local("_1"))) },
{ "mat3d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT3D, new Local("abc"))) },
{ "mat4f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT4F, new Local("_1"))) },
{ "mat4d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT4D, new Local("abc"))) },
{ "string D1f;", Node::Ptr(new DeclareLocal(CoreType::STRING, new Local("D1f"))) },
{ "float a = 1.0f;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<float>(1.0f))) },
{ "float a = 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<int32_t>(1))) },
{ "float a = a + 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"),
new BinaryOperator(new Local("a"), new Value<int32_t>(1), OperatorToken::PLUS)))
},
{ "float a = v.x;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"),
new ArrayUnpack(new Local("v"), new Value<int32_t>(0))))
},
{ "vec3f v = {1, 2, 3};", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("v"),
new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3),
})))
},
{ "mat3f m = 1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F,
new Local("m"),
new Value<int32_t>(1)))
},
{ "string s = \"foo\";", Node::Ptr(new DeclareLocal(CoreType::STRING,
new Local("s"),
new Value<std::string>("foo")))
},
{ "float a = b = c;", Node::Ptr(new DeclareLocal(CoreType::FLOAT,
new Local("a"),
new AssignExpression(new Local("b"), new Local("c"))))
},
};
}
class TestDeclareLocalNode : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestDeclareLocalNode);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestDeclareLocalNode);
void TestDeclareLocalNode::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::DeclareLocalNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Declaration code", code) + os.str());
}
}
}
| 5,116 | C++ | 43.112069 | 113 | 0.571931 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestArrayPack.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
static const unittest_util::CodeTests tests =
{
{ "{1, 2, {1,2,3}};", Node::Ptr(new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new ArrayPack({
new Value<int32_t>(1),
new Value<int32_t>(2),
new Value<int32_t>(3)
})
}))
},
{ "{1.f,2.0,3l};" , Node::Ptr(new ArrayPack({
new Value<float>(1.0f),
new Value<double>(2.0),
new Value<int64_t>(3)
}))
},
{ "({1.f,2.0,3l});" , Node::Ptr(new ArrayPack({
new Value<float>(1.0f),
new Value<double>(2.0),
new Value<int64_t>(3)
}))
},
{ "{{a,b,c}, {d,e,f}, {g,h,i}};", Node::Ptr(new ArrayPack({
new ArrayPack({
new Local("a"),
new Local("b"),
new Local("c")
}),
new ArrayPack({
new Local("d"),
new Local("e"),
new Local("f")
}),
new ArrayPack({
new Local("g"),
new Local("h"),
new Local("i")
})
}))
},
{ "{(a),b+1,-c};", Node::Ptr(new ArrayPack({
new Local("a"),
new BinaryOperator(new Local("b"), new Value<int32_t>(1), OperatorToken::PLUS),
new UnaryOperator(new Local("c"), OperatorToken::MINUS)
}))
},
{ "{@x,++z,true};", Node::Ptr(new ArrayPack({
new Attribute("x", CoreType::FLOAT, true),
new Crement(new Local("z"), Crement::Operation::Increment, false),
new Value<bool>(true)
}))
},
{ "{@x,z++,\"bar\"};", Node::Ptr(new ArrayPack({
new Attribute("x", CoreType::FLOAT, true),
new Crement(new Local("z"), Crement::Operation::Increment, true),
new Value<std::string>("bar")
}))
},
{ "{float(x),b=c,c.z};", Node::Ptr(new ArrayPack({
new Cast(new Local("x"), CoreType::FLOAT),
new AssignExpression(new Local("b"), new Local("c")),
new ArrayUnpack(new Local("c"), new Value<int32_t>(2))
}))
},
{ "{test(),a[0],b[1,2]};", Node::Ptr(new ArrayPack({
new FunctionCall("test"),
new ArrayUnpack(new Local("a"), new Value<int32_t>(0)),
new ArrayUnpack(new Local("b"), new Value<int32_t>(1), new Value<int32_t>(2))
}))
},
{ "{(1), (1,2), (1,2,(3))};", Node::Ptr(new ArrayPack({
new Value<int32_t>(1),
new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2) }),
new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3)
})
}))
},
{ "{1,2,3,4,5,6,7,8,9};", Node::Ptr(new ArrayPack({
new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3),
new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6),
new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9)
}))
},
{ "{ 1, 2, 3, 4, \
5, 6, 7, 8, \
9,10,11,12, \
13,14,15,16 };", Node::Ptr(new ArrayPack({
new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4),
new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8),
new Value<int32_t>(9), new Value<int32_t>(10), new Value<int32_t>(11), new Value<int32_t>(12),
new Value<int32_t>(13), new Value<int32_t>(14), new Value<int32_t>(15), new Value<int32_t>(16)
}))
},
};
}
class TestArrayPack : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestArrayPack);
CPPUNIT_TEST(testSyntax);
CPPUNIT_TEST(testASTNode);
CPPUNIT_TEST_SUITE_END();
void testSyntax() { TEST_SYNTAX_PASSES(tests); }
void testASTNode();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayPack);
void TestArrayPack::testASTNode()
{
for (const auto& test : tests) {
const std::string& code = test.first;
const Node* expected = test.second.get();
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree));
// get the first statement
const Node* result = tree->child(0)->child(0);
CPPUNIT_ASSERT(result);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code),
Node::ArrayPackNode == result->nodetype());
std::vector<const Node*> resultList, expectedList;
linearize(*result, resultList);
linearize(*expected, expectedList);
if (!unittest_util::compareLinearTrees(expectedList, resultList)) {
std::ostringstream os;
os << "\nExpected:\n";
openvdb::ax::ast::print(*expected, true, os);
os << "Result:\n";
openvdb::ax::ast::print(*result, true, os);
CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Array Pack code", code) + os.str());
}
}
}
| 7,785 | C++ | 47.061728 | 139 | 0.370071 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestAXRun.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ax.h>
#include <openvdb_ax/Exceptions.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/points/PointConversion.h>
#include <cppunit/extensions/HelperMacros.h>
class TestAXRun : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestAXRun);
CPPUNIT_TEST(singleRun);
CPPUNIT_TEST(multiRun);
CPPUNIT_TEST_SUITE_END();
void singleRun();
void multiRun();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAXRun);
void
TestAXRun::singleRun()
{
openvdb::FloatGrid f;
f.setName("a");
f.tree().setValueOn({0,0,0}, 0.0f);
openvdb::ax::run("@a = 1.0f;", f);
CPPUNIT_ASSERT_EQUAL(1.0f, f.tree().getValue({0,0,0}));
openvdb::math::Transform::Ptr defaultTransform =
openvdb::math::Transform::createLinearTransform();
const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()};
openvdb::points::PointDataGrid::Ptr
points = openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform);
openvdb::ax::run("@a = 1.0f;", *points);
const auto leafIter = points->tree().cbeginLeaf();
const auto& descriptor = leafIter->attributeSet().descriptor();
CPPUNIT_ASSERT_EQUAL(size_t(2), descriptor.size());
const size_t idx = descriptor.find("a");
CPPUNIT_ASSERT(idx != openvdb::points::AttributeSet::INVALID_POS);
CPPUNIT_ASSERT(descriptor.valueType(idx) == openvdb::typeNameAsString<float>());
openvdb::points::AttributeHandle<float> handle(leafIter->constAttributeArray(idx));
CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0));
}
void
TestAXRun::multiRun()
{
{
// test error on points and volumes
openvdb::FloatGrid::Ptr f(new openvdb::FloatGrid);
openvdb::points::PointDataGrid::Ptr p(new openvdb::points::PointDataGrid);
std::vector<openvdb::GridBase::Ptr> v1 { f, p };
CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v1), openvdb::AXCompilerError);
std::vector<openvdb::GridBase::Ptr> v2 { p, f };
CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v2), openvdb::AXCompilerError);
}
{
// multi volumes
openvdb::FloatGrid::Ptr f1(new openvdb::FloatGrid);
openvdb::FloatGrid::Ptr f2(new openvdb::FloatGrid);
f1->setName("a");
f2->setName("b");
f1->tree().setValueOn({0,0,0}, 0.0f);
f2->tree().setValueOn({0,0,0}, 0.0f);
std::vector<openvdb::GridBase::Ptr> v { f1, f2 };
openvdb::ax::run("@a = @b = 1;", v);
CPPUNIT_ASSERT_EQUAL(1.0f, f1->tree().getValue({0,0,0}));
CPPUNIT_ASSERT_EQUAL(1.0f, f2->tree().getValue({0,0,0}));
}
{
// multi points
openvdb::math::Transform::Ptr defaultTransform =
openvdb::math::Transform::createLinearTransform();
const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()};
openvdb::points::PointDataGrid::Ptr
p1 = openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform);
openvdb::points::PointDataGrid::Ptr
p2 = openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform);
std::vector<openvdb::GridBase::Ptr> v { p1, p2 };
openvdb::ax::run("@a = @b = 1;", v);
const auto leafIter1 = p1->tree().cbeginLeaf();
const auto leafIter2 = p2->tree().cbeginLeaf();
const auto& descriptor1 = leafIter1->attributeSet().descriptor();
const auto& descriptor2 = leafIter1->attributeSet().descriptor();
CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor1.size());
CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor2.size());
const size_t idx1 = descriptor1.find("a");
CPPUNIT_ASSERT_EQUAL(idx1, descriptor2.find("a"));
const size_t idx2 = descriptor1.find("b");
CPPUNIT_ASSERT_EQUAL(idx2, descriptor2.find("b"));
CPPUNIT_ASSERT(idx1 != openvdb::points::AttributeSet::INVALID_POS);
CPPUNIT_ASSERT(idx2 != openvdb::points::AttributeSet::INVALID_POS);
CPPUNIT_ASSERT(descriptor1.valueType(idx1) == openvdb::typeNameAsString<float>());
CPPUNIT_ASSERT(descriptor1.valueType(idx2) == openvdb::typeNameAsString<float>());
CPPUNIT_ASSERT(descriptor2.valueType(idx1) == openvdb::typeNameAsString<float>());
CPPUNIT_ASSERT(descriptor2.valueType(idx2) == openvdb::typeNameAsString<float>());
openvdb::points::AttributeHandle<float> handle(leafIter1->constAttributeArray(idx1));
CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0));
handle = openvdb::points::AttributeHandle<float>(leafIter1->constAttributeArray(idx2));
CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0));
handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx1));
CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0));
handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx2));
CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0));
}
}
| 5,276 | C++ | 39.906976 | 113 | 0.65182 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestVolumeExecutable.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb_ax/compiler/VolumeExecutable.h>
#include <cppunit/extensions/HelperMacros.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
class TestVolumeExecutable : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestVolumeExecutable);
CPPUNIT_TEST(testConstructionDestruction);
CPPUNIT_TEST(testCreateMissingGrids);
CPPUNIT_TEST(testTreeExecutionLevel);
CPPUNIT_TEST(testCompilerCases);
CPPUNIT_TEST_SUITE_END();
void testConstructionDestruction();
void testCreateMissingGrids();
void testTreeExecutionLevel();
void testCompilerCases();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestVolumeExecutable);
void
TestVolumeExecutable::testConstructionDestruction()
{
// Test the building and teardown of executable objects. This is primarily to test
// the destruction of Context and ExecutionEngine LLVM objects. These must be destructed
// in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash
// must be initialized, otherwise construction/destruction of llvm objects won't
// exhibit correct behaviour
CPPUNIT_ASSERT(openvdb::ax::isInitialized());
std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext);
std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C));
std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M))
.setEngineKind(llvm::EngineKind::JIT)
.create());
CPPUNIT_ASSERT(!M);
CPPUNIT_ASSERT(E);
std::weak_ptr<llvm::LLVMContext> wC = C;
std::weak_ptr<const llvm::ExecutionEngine> wE = E;
// Basic construction
openvdb::ax::ast::Tree tree;
openvdb::ax::AttributeRegistry::ConstPtr emptyReg =
openvdb::ax::AttributeRegistry::create(tree);
openvdb::ax::VolumeExecutable::Ptr volumeExecutable
(new openvdb::ax::VolumeExecutable(C, E, emptyReg, nullptr, {}));
CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count()));
C.reset();
E.reset();
CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count()));
// test destruction
volumeExecutable.reset();
CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count()));
}
void
TestVolumeExecutable::testCreateMissingGrids()
{
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>("@[email protected];");
CPPUNIT_ASSERT(executable);
executable->setCreateMissing(false);
executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON);
openvdb::GridPtrVec grids;
CPPUNIT_ASSERT_THROW(executable->execute(grids), openvdb::AXExecutionError);
CPPUNIT_ASSERT(grids.empty());
executable->setCreateMissing(true);
executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON);
executable->execute(grids);
openvdb::math::Transform::Ptr defaultTransform =
openvdb::math::Transform::createLinearTransform();
CPPUNIT_ASSERT_EQUAL(size_t(2), grids.size());
CPPUNIT_ASSERT(grids[0]->getName() == "b");
CPPUNIT_ASSERT(grids[0]->isType<openvdb::Vec3fGrid>());
CPPUNIT_ASSERT(grids[0]->empty());
CPPUNIT_ASSERT(grids[0]->transform() == *defaultTransform);
CPPUNIT_ASSERT(grids[1]->getName() == "a");
CPPUNIT_ASSERT(grids[1]->isType<openvdb::FloatGrid>());
CPPUNIT_ASSERT(grids[1]->empty());
CPPUNIT_ASSERT(grids[1]->transform() == *defaultTransform);
}
void
TestVolumeExecutable::testTreeExecutionLevel()
{
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>("f@test = 1.0f;");
CPPUNIT_ASSERT(executable);
using NodeT0 = openvdb::FloatGrid::Accessor::NodeT0;
using NodeT1 = openvdb::FloatGrid::Accessor::NodeT1;
using NodeT2 = openvdb::FloatGrid::Accessor::NodeT2;
openvdb::FloatGrid test;
test.setName("test");
// NodeT0 tile
test.tree().addTile(1, openvdb::Coord(0), -2.0f, /*active*/true);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0)));
// default is leaf nodes, expect no change
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0)));
executable->setTreeExecutionLevel(1);
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0)));
// NodeT1 tile
test.tree().addTile(2, openvdb::Coord(0), -2.0f, /*active*/true);
// level is set to 1, expect no change
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0)));
executable->setTreeExecutionLevel(2);
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0)));
// NodeT2 tile
test.tree().addTile(3, openvdb::Coord(0), -2.0f, /*active*/true);
// level is set to 2, expect no change
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0)));
executable->setTreeExecutionLevel(3);
executable->execute(test);
CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount());
CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount());
CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0)));
// test higher values throw
CPPUNIT_ASSERT_THROW(executable->setTreeExecutionLevel(4), openvdb::RuntimeError);
}
void
TestVolumeExecutable::testCompilerCases()
{
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
CPPUNIT_ASSERT(compiler);
{
// with string only
CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::VolumeExecutable>("int i;")));
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i;"), openvdb::AXCompilerError);
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i"), openvdb::AXCompilerError);
// with AST only
auto ast = openvdb::ax::ast::parse("i;");
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>(*ast), openvdb::AXCompilerError);
}
openvdb::ax::Logger logger([](const std::string&) {});
// using string and logger
{
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>("", logger); // empty
CPPUNIT_ASSERT(executable);
}
logger.clear();
{
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>("i;", logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
CPPUNIT_ASSERT(logger.hasError());
logger.clear();
openvdb::ax::VolumeExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::VolumeExecutable>("i", logger); // expected ; error (parser)
CPPUNIT_ASSERT(!executable2);
CPPUNIT_ASSERT(logger.hasError());
}
logger.clear();
{
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>("int i = 18446744073709551615;", logger); // warning
CPPUNIT_ASSERT(executable);
CPPUNIT_ASSERT(logger.hasWarning());
}
// using syntax tree and logger
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty
CPPUNIT_ASSERT(executable);
logger.clear(); // no tree for line col numbers
openvdb::ax::VolumeExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty
CPPUNIT_ASSERT(executable2);
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
CPPUNIT_ASSERT(logger.hasError());
logger.clear(); // no tree for line col numbers
openvdb::ax::VolumeExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error
CPPUNIT_ASSERT(!executable2);
CPPUNIT_ASSERT(logger.hasError());
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning
CPPUNIT_ASSERT(executable);
CPPUNIT_ASSERT(logger.hasWarning());
logger.clear(); // no tree for line col numbers
openvdb::ax::VolumeExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning
CPPUNIT_ASSERT(executable2);
CPPUNIT_ASSERT(logger.hasWarning());
}
logger.clear();
// with copied tree
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // empty
CPPUNIT_ASSERT(executable);
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
CPPUNIT_ASSERT(logger.hasError());
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger);
openvdb::ax::VolumeExecutable::Ptr executable =
compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // warning
CPPUNIT_ASSERT(executable);
CPPUNIT_ASSERT(logger.hasWarning());
}
logger.clear();
}
| 12,216 | C++ | 39.996644 | 115 | 0.672561 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestPointExecutable.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb_ax/compiler/PointExecutable.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/points/PointConversion.h>
#include <openvdb/points/PointAttribute.h>
#include <openvdb/points/PointGroup.h>
#include <cppunit/extensions/HelperMacros.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
class TestPointExecutable : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestPointExecutable);
CPPUNIT_TEST(testConstructionDestruction);
CPPUNIT_TEST(testCreateMissingAttributes);
CPPUNIT_TEST(testGroupExecution);
CPPUNIT_TEST(testCompilerCases);
CPPUNIT_TEST_SUITE_END();
void testConstructionDestruction();
void testCreateMissingAttributes();
void testGroupExecution();
void testCompilerCases();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestPointExecutable);
void
TestPointExecutable::testConstructionDestruction()
{
// Test the building and teardown of executable objects. This is primarily to test
// the destruction of Context and ExecutionEngine LLVM objects. These must be destructed
// in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash
// must be initialized, otherwise construction/destruction of llvm objects won't
// exhibit correct behaviour
CPPUNIT_ASSERT(openvdb::ax::isInitialized());
std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext);
std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C));
std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M))
.setEngineKind(llvm::EngineKind::JIT)
.create());
CPPUNIT_ASSERT(!M);
CPPUNIT_ASSERT(E);
std::weak_ptr<llvm::LLVMContext> wC = C;
std::weak_ptr<const llvm::ExecutionEngine> wE = E;
// Basic construction
openvdb::ax::ast::Tree tree;
openvdb::ax::AttributeRegistry::ConstPtr emptyReg =
openvdb::ax::AttributeRegistry::create(tree);
openvdb::ax::PointExecutable::Ptr pointExecutable
(new openvdb::ax::PointExecutable(C, E, emptyReg, nullptr, {}));
CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count()));
C.reset();
E.reset();
CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count()));
// test destruction
pointExecutable.reset();
CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count()));
CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count()));
}
void
TestPointExecutable::testCreateMissingAttributes()
{
openvdb::math::Transform::Ptr defaultTransform =
openvdb::math::Transform::createLinearTransform();
const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()};
openvdb::points::PointDataGrid::Ptr
grid = openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform);
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>("@[email protected];");
CPPUNIT_ASSERT(executable);
executable->setCreateMissing(false);
CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::AXExecutionError);
executable->setCreateMissing(true);
executable->execute(*grid);
const auto leafIter = grid->tree().cbeginLeaf();
const auto& descriptor = leafIter->attributeSet().descriptor();
CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor.size());
const size_t bIdx = descriptor.find("b");
CPPUNIT_ASSERT(bIdx != openvdb::points::AttributeSet::INVALID_POS);
CPPUNIT_ASSERT(descriptor.valueType(bIdx) == openvdb::typeNameAsString<openvdb::Vec3f>());
openvdb::points::AttributeHandle<openvdb::Vec3f>::Ptr
bHandle = openvdb::points::AttributeHandle<openvdb::Vec3f>::create(leafIter->constAttributeArray(bIdx));
CPPUNIT_ASSERT(bHandle->get(0) == openvdb::Vec3f::zero());
const size_t aIdx = descriptor.find("a");
CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS);
CPPUNIT_ASSERT(descriptor.valueType(aIdx) == openvdb::typeNameAsString<float>());
openvdb::points::AttributeHandle<float>::Ptr
aHandle = openvdb::points::AttributeHandle<float>::create(leafIter->constAttributeArray(aIdx));
CPPUNIT_ASSERT(aHandle->get(0) == 0.0f);
}
void
TestPointExecutable::testGroupExecution()
{
openvdb::math::Transform::Ptr defaultTransform =
openvdb::math::Transform::createLinearTransform(0.1);
// 4 points in 4 leaf nodes
const std::vector<openvdb::Vec3d> positions = {
{0,0,0},
{1,1,1},
{2,2,2},
{3,3,3},
};
openvdb::points::PointDataGrid::Ptr grid =
openvdb::points::createPointDataGrid
<openvdb::points::NullCodec, openvdb::points::PointDataGrid>
(positions, *defaultTransform);
// check the values of "a"
auto checkValues = [&](const int expected)
{
auto leafIter = grid->tree().cbeginLeaf();
CPPUNIT_ASSERT(leafIter);
const auto& descriptor = leafIter->attributeSet().descriptor();
const size_t aIdx = descriptor.find("a");
CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS);
for (; leafIter; ++leafIter) {
openvdb::points::AttributeHandle<int> handle(leafIter->constAttributeArray(aIdx));
CPPUNIT_ASSERT(handle.size() == 1);
CPPUNIT_ASSERT_EQUAL(expected, handle.get(0));
}
};
openvdb::points::appendAttribute<int>(grid->tree(), "a", 0);
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>("i@a=1;");
CPPUNIT_ASSERT(executable);
const std::string group = "test";
// non existent group
executable->setGroupExecution(group);
CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::LookupError);
checkValues(0);
openvdb::points::appendGroup(grid->tree(), group);
// false group
executable->execute(*grid);
checkValues(0);
openvdb::points::setGroup(grid->tree(), group, true);
// true group
executable->execute(*grid);
checkValues(1);
}
void
TestPointExecutable::testCompilerCases()
{
openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create();
CPPUNIT_ASSERT(compiler);
{
// with string only
CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::PointExecutable>("int i;")));
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i;"), openvdb::AXCompilerError);
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i"), openvdb::AXCompilerError);
// with AST only
auto ast = openvdb::ax::ast::parse("i;");
CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>(*ast), openvdb::AXCompilerError);
}
openvdb::ax::Logger logger([](const std::string&) {});
// using string and logger
{
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>("", logger); // empty
CPPUNIT_ASSERT(executable);
}
logger.clear();
{
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>("i;", logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
CPPUNIT_ASSERT(logger.hasError());
logger.clear();
openvdb::ax::PointExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::PointExecutable>("i", logger); // expected ; error (parser)
CPPUNIT_ASSERT(!executable2);
CPPUNIT_ASSERT(logger.hasError());
}
logger.clear();
{
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>("int i = 18446744073709551615;", logger); // warning
CPPUNIT_ASSERT(executable);
CPPUNIT_ASSERT(logger.hasWarning());
}
// using syntax tree and logger
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty
CPPUNIT_ASSERT(executable);
logger.clear(); // no tree for line col numbers
openvdb::ax::PointExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty
CPPUNIT_ASSERT(executable2);
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
CPPUNIT_ASSERT(logger.hasError());
logger.clear(); // no tree for line col numbers
openvdb::ax::PointExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error
CPPUNIT_ASSERT(!executable2);
CPPUNIT_ASSERT(logger.hasError());
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger);
CPPUNIT_ASSERT(tree);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning
CPPUNIT_ASSERT(executable);
CPPUNIT_ASSERT(logger.hasWarning());
logger.clear(); // no tree for line col numbers
openvdb::ax::PointExecutable::Ptr executable2 =
compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning
CPPUNIT_ASSERT(executable2);
CPPUNIT_ASSERT(logger.hasWarning());
}
logger.clear();
// with copied tree
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // empty
CPPUNIT_ASSERT(executable);
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // undeclared variable error
CPPUNIT_ASSERT(!executable);
}
logger.clear();
{
openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger);
openvdb::ax::PointExecutable::Ptr executable =
compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // warning
CPPUNIT_ASSERT(executable);
}
logger.clear();
}
| 11,201 | C++ | 36.590604 | 114 | 0.660923 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestScanners.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/test/util.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
namespace {
// No dependencies
// - use @a once (read), no other variables
const std::vector<std::string> none = {
"@a;",
"@a+1;",
"@a=1;",
"@a=func(5);",
"-@a;",
"@a[0]=1;",
"if(true) @a = 1;",
"if(@a) a=1;",
"if (@e) if (@b) if (@c) @a;",
"@b = c ? : @a;",
"@a ? : c = 1;",
"for (@a; @b; @c) ;",
"while (@a) ;",
"for(;true;) @a = 1;"
};
// Self dependencies
// - use @a potentially multiple times (read/write), no other variables
const std::vector<std::string> self = {
"@a=@a;",
"@a+=1;",
"++@a;",
"@a--;",
"func(@a);",
"--@a + 1;",
"if(@a) @a = 1;",
"if(@a) ; else @a = 1;",
"@a ? : @a = 2;",
"for (@b;@a;@c) @a = 0;",
"while(@a) @a = 1;"
};
// Code where @a should have a direct dependency on @b only
// - use @a once (read/write), use @b once
const std::vector<std::string> direct = {
"@a=@b;",
"@a=-@b;",
"@a=@b;",
"@a=1+@b;",
"@a=func(@b);",
"@a=++@b;",
"if(@b) @a=1;",
"if(@b) {} else { @a=1; }",
"@b ? @a = 1 : 0;",
"@b ? : @a = 1;",
"for (;@b;) @a = 1;",
"while (@b) @a = 1;"
};
// Code where @a should have a direct dependency on @b only
// - use @a once (read/write), use @b once, b a vector
const std::vector<std::string> directvec = {
"@[email protected];",
"@a=v@b[0];",
"@[email protected] + 1;",
"@a=v@b[0] * 3;",
"if (v@b[0]) @a = 3;",
};
// Code where @a should have dependencies on @b and c (c always first)
const std::vector<std::string> indirect = {
"c=@b; @a=c;",
"c=@b; @a=c[0];",
"c = {@b,1,2}; @a=c;",
"int c=@b; @a=c;",
"int c; c=@b; @a=c;",
"if (c = @b) @a = c;",
"(c = @b) ? @a=c : 0;",
"(c = @b) ? : @a=c;",
"for(int c = @b; true; e) @a = c;",
"for(int c = @b;; @a = c) ;",
"for(int c = @b; c; e) @a = c;",
"for(c = @b; c; e) @a = c;",
"int c; for(c = @b; c; e) @a = c;",
"for(; c = @b;) @a = c;",
"while(int c = @b) @a = c;",
};
}
class TestScanners : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestScanners);
CPPUNIT_TEST(testVisitNodeType);
CPPUNIT_TEST(testFirstLastLocation);
CPPUNIT_TEST(testAttributeDependencyTokens);
// CPPUNIT_TEST(testVariableDependencies);
CPPUNIT_TEST_SUITE_END();
void testVisitNodeType();
void testFirstLastLocation();
void testAttributeDependencyTokens();
// void testVariableDependencies();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestScanners);
void TestScanners::testVisitNodeType()
{
size_t count = 0;
auto counter = [&](const Node&) -> bool {
++count; return true;
};
// "int64@a;"
Node::Ptr node(new Attribute("a", CoreType::INT64));
visitNodeType<Node>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
count = 0;
visitNodeType<Local>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(0), count);
count = 0;
visitNodeType<Variable>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
count = 0;
visitNodeType<Attribute>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
// "{1.0f, 2.0, 3};"
node.reset(new ArrayPack( {
new Value<float>(1.0f),
new Value<double>(2.0),
new Value<int64_t>(3)
}));
count = 0;
visitNodeType<Node>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(4), count);
count = 0;
visitNodeType<Local>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(0), count);
count = 0;
visitNodeType<ValueBase>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(3), count);
count = 0;
visitNodeType<ArrayPack>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
count = 0;
visitNodeType<Expression>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(4), count);
count = 0;
visitNodeType<Statement>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(4), count);
// "@a += [email protected] = x %= 1;"
// @note 9 explicit nodes
node.reset(new AssignExpression(
new Attribute("a", CoreType::FLOAT, true),
new AssignExpression(
new ArrayUnpack(
new Attribute("b", CoreType::VEC3F),
new Value<int32_t>(0)
),
new AssignExpression(
new Local("x"),
new Value<int32_t>(1),
OperatorToken::MODULO
)
),
OperatorToken::PLUS
));
count = 0;
visitNodeType<Node>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(9), count);
count = 0;
visitNodeType<Local>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
count = 0;
visitNodeType<Attribute>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(2), count);
count = 0;
visitNodeType<Value<int>>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(2), count);
count = 0;
visitNodeType<ArrayUnpack>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(1), count);
count = 0;
visitNodeType<AssignExpression>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(3), count);
count = 0;
visitNodeType<Expression>(*node, counter);
CPPUNIT_ASSERT_EQUAL(size_t(9), count);
}
void TestScanners::testFirstLastLocation()
{
// The list of above code sets which are expected to have the same
// first and last use of @a.
const std::vector<const std::vector<std::string>*> snippets {
&none,
&direct,
&indirect
};
for (const auto& samples : snippets) {
for (const std::string& code : *samples) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
const Variable* first = firstUse(*tree, "@a");
const Variable* last = lastUse(*tree, "@a");
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate first @a AST node", code), first);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate last @a AST node", code), last);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid first/last AST node comparison", code),
first == last);
}
}
// Test some common edge cases
// @a = @a;
Node::Ptr node(new AssignExpression(
new Attribute("a", CoreType::FLOAT),
new Attribute("a", CoreType::FLOAT)));
const Node* expectedFirst =
static_cast<AssignExpression*>(node.get())->lhs();
const Node* expectedLast =
static_cast<AssignExpression*>(node.get())->rhs();
CPPUNIT_ASSERT(expectedFirst != expectedLast);
const Node* first = firstUse(*node, "@a");
const Node* last = lastUse(*node, "@a");
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"),
first, expectedFirst);
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"),
last, expectedLast);
// for(@a;@a;@a) { @a; }
node.reset(new Loop(
tokens::FOR,
new Attribute("a", CoreType::FLOAT),
new Block(new Attribute("a", CoreType::FLOAT)),
new Attribute("a", CoreType::FLOAT),
new Attribute("a", CoreType::FLOAT)
));
expectedFirst = static_cast<Loop*>(node.get())->initial();
expectedLast = static_cast<Loop*>(node.get())->body()->child(0);
CPPUNIT_ASSERT(expectedFirst != expectedLast);
first = firstUse(*node, "@a");
last = lastUse(*node, "@a");
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"for(@a;@a;@a) { @a; }"), first, expectedFirst);
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"for(@a;@a;@a) { @a; }"), last, expectedLast);
// do { @a; } while(@a);
node.reset(new Loop(
tokens::DO,
new Attribute("a", CoreType::FLOAT),
new Block(new Attribute("a", CoreType::FLOAT)),
nullptr,
nullptr
));
expectedFirst = static_cast<Loop*>(node.get())->body()->child(0);
expectedLast = static_cast<Loop*>(node.get())->condition();
CPPUNIT_ASSERT(expectedFirst != expectedLast);
first = firstUse(*node, "@a");
last = lastUse(*node, "@a");
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"do { @a; } while(@a);"), first, expectedFirst);
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"do { @a; } while(@a);"), last, expectedLast);
// if (@a) {} else if (@a) {} else { @a; }
node.reset(new ConditionalStatement(
new Attribute("a", CoreType::FLOAT),
new Block(),
new Block(
new ConditionalStatement(
new Attribute("a", CoreType::FLOAT),
new Block(),
new Block(new Attribute("a", CoreType::FLOAT))
)
)
));
expectedFirst = static_cast<ConditionalStatement*>(node.get())->condition();
expectedLast =
static_cast<const ConditionalStatement*>(
static_cast<ConditionalStatement*>(node.get())
->falseBranch()->child(0))
->falseBranch()->child(0);
CPPUNIT_ASSERT(expectedFirst != expectedLast);
first = firstUse(*node, "@a");
last = lastUse(*node, "@a");
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"if (@a) {} else if (1) {} else { @a; }"), first, expectedFirst);
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node",
"if (@a) {} else if (1) {} else { @a; }"), last, expectedLast);
}
void TestScanners::testAttributeDependencyTokens()
{
for (const std::string& code : none) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code),
dependencies.empty());
}
for (const std::string& code : self) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT(!dependencies.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
dependencies.front(), std::string("float@a"));
}
for (const std::string& code : direct) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT(!dependencies.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
dependencies.front(), std::string("float@b"));
}
for (const std::string& code : directvec) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT(!dependencies.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
dependencies.front(), std::string("vec3f@b"));
}
for (const std::string& code : indirect) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT(!dependencies.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
dependencies.front(), std::string("float@b"));
}
// Test a more complicated code snippet. Note that this also checks the
// order which isn't strictly necessary
const std::string complex =
"int a = func(1,@e);"
"pow(@d, a);"
"mat3f m = 0;"
"scale(m, v@v);"
""
"float f1 = 0;"
"float f2 = 0;"
"float f3 = 0;"
""
"f3 = @f;"
"f2 = f3;"
"f1 = f2;"
"if (@a - @e > f1) {"
" @b = func(m);"
" if (true) {"
" ++@c[0] = a;"
" }"
"}";
const Tree::ConstPtr tree = parse(complex.c_str());
CPPUNIT_ASSERT(tree);
std::vector<std::string> dependencies;
attributeDependencyTokens(*tree, "b", tokens::CoreType::FLOAT, dependencies);
// @b should depend on: @a, @e, @f, v@v
CPPUNIT_ASSERT_EQUAL(4ul, dependencies.size());
CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a"));
CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e"));
CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@f"));
CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("vec3f@v"));
// @c should depend on: @a, @c, @d, @e, @f
dependencies.clear();
attributeDependencyTokens(*tree, "c", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT_EQUAL(5ul, dependencies.size());
CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a"));
CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@c"));
CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@d"));
CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("float@e"));
CPPUNIT_ASSERT_EQUAL(dependencies[4], std::string("float@f"));
// @d should depend on: @d, @e
dependencies.clear();
attributeDependencyTokens(*tree, "d", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT_EQUAL(2ul, dependencies.size());
CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@d"));
CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e"));
// @e should depend on itself
dependencies.clear();
attributeDependencyTokens(*tree, "e", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size());
CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@e"));
// @f should depend on nothing
dependencies.clear();
attributeDependencyTokens(*tree, "f", tokens::CoreType::FLOAT, dependencies);
CPPUNIT_ASSERT(dependencies.empty());
// @v should depend on: v@v
dependencies.clear();
attributeDependencyTokens(*tree, "v", tokens::CoreType::VEC3F, dependencies);
CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size());
CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("vec3f@v"));
}
/*
void TestScanners::testVariableDependencies()
{
for (const std::string& code : none) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
const Variable* last = lastUse(*tree, "@a");
CPPUNIT_ASSERT(last);
std::vector<const Variable*> vars;
variableDependencies(*last, vars);
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code),
vars.empty());
}
for (const std::string& code : self) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
const Variable* last = lastUse(*tree, "@a");
CPPUNIT_ASSERT(last);
std::vector<const Variable*> vars;
variableDependencies(*last, vars);
const Variable* var = vars.front();
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
var->isType<Attribute>());
const Attribute* attrib = static_cast<const Attribute*>(var);
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
std::string("float@a"), attrib->tokenname());
}
for (const std::string& code : direct) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
const Variable* last = lastUse(*tree, "@a");
CPPUNIT_ASSERT(last);
std::vector<const Variable*> vars;
variableDependencies(*last, vars);
const Variable* var = vars.front();
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
var->isType<Attribute>());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
std::string("b"), var->name());
}
for (const std::string& code : indirect) {
const Tree::ConstPtr tree = parse(code.c_str());
CPPUNIT_ASSERT(tree);
const Variable* last = lastUse(*tree, "@a");
CPPUNIT_ASSERT(last);
std::vector<const Variable*> vars;
variableDependencies(*last, vars);
// check c
const Variable* var = vars[0];
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
var->isType<Local>());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
std::string("c"), var->name());
// check @b
var = vars[1];
CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
var->isType<Attribute>());
CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code),
std::string("b"), var->name());
}
// Test a more complicated code snippet. Note that this also checks the
// order which isn't strictly necessary
const std::string complex =
"int a = func(1,@e);"
"pow(@d, a);"
"mat3f m = 0;"
"scale(m, v@v);"
""
"float f1 = 0;"
"float f2 = 0;"
"float f3 = 0;"
""
"f3 = @f;"
"f2 = f3;"
"f1 = f2;"
"if (@a - @e > f1) {"
" @b = func(m);"
" if (true) {"
" ++@c[0] = a;"
" }"
"}";
const Tree::ConstPtr tree = parse(complex.c_str());
CPPUNIT_ASSERT(tree);
const Variable* lasta = lastUse(*tree, "@a");
const Variable* lastb = lastUse(*tree, "@b");
const Variable* lastc = lastUse(*tree, "@c");
const Variable* lastd = lastUse(*tree, "@d");
const Variable* laste = lastUse(*tree, "@e");
const Variable* lastf = lastUse(*tree, "@f");
const Variable* lastv = lastUse(*tree, "vec3f@v");
CPPUNIT_ASSERT(lasta);
CPPUNIT_ASSERT(lastb);
CPPUNIT_ASSERT(lastc);
CPPUNIT_ASSERT(lastd);
CPPUNIT_ASSERT(laste);
CPPUNIT_ASSERT(lastf);
CPPUNIT_ASSERT(lastv);
std::vector<const Variable*> vars;
variableDependencies(*lasta, vars);
CPPUNIT_ASSERT(vars.empty());
// @b should depend on: m, m, v@v, @a, @e, @e, f1, f2, f3, @f
variableDependencies(*lastb, vars);
CPPUNIT_ASSERT_EQUAL(10ul, vars.size());
CPPUNIT_ASSERT(vars[0]->isType<Local>());
CPPUNIT_ASSERT(vars[0]->name() == "m");
CPPUNIT_ASSERT(vars[1]->isType<Local>());
CPPUNIT_ASSERT(vars[1]->name() == "m");
CPPUNIT_ASSERT(vars[2]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "vec3f@v");
CPPUNIT_ASSERT(vars[3]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@a");
CPPUNIT_ASSERT(vars[4]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[4])->tokenname() == "float@e");
CPPUNIT_ASSERT(vars[5]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@e");
CPPUNIT_ASSERT(vars[6]->isType<Local>());
CPPUNIT_ASSERT(vars[6]->name() == "f1");
CPPUNIT_ASSERT(vars[7]->isType<Local>());
CPPUNIT_ASSERT(vars[7]->name() == "f2");
CPPUNIT_ASSERT(vars[8]->isType<Local>());
CPPUNIT_ASSERT(vars[8]->name() == "f3");
CPPUNIT_ASSERT(vars[9]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[9])->tokenname() == "float@f");
// @c should depend on: @c, a, @e, @d, a, @e, @a, @e, f1, f2, f3, @f
vars.clear();
variableDependencies(*lastc, vars);
CPPUNIT_ASSERT_EQUAL(11ul, vars.size());
CPPUNIT_ASSERT(vars[0]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@c");
CPPUNIT_ASSERT(vars[1]->isType<Local>());
CPPUNIT_ASSERT(vars[1]->name() == "a");
CPPUNIT_ASSERT(vars[2]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e");
CPPUNIT_ASSERT(vars[3]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@d");
CPPUNIT_ASSERT(vars[4]->isType<Local>());
CPPUNIT_ASSERT(vars[4]->name() == "a");
CPPUNIT_ASSERT(vars[5]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@a");
CPPUNIT_ASSERT(vars[6]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[6])->tokenname() == "float@e");
CPPUNIT_ASSERT(vars[7]->isType<Local>());
CPPUNIT_ASSERT(vars[7]->name() == "f1");
CPPUNIT_ASSERT(vars[8]->isType<Local>());
CPPUNIT_ASSERT(vars[8]->name() == "f2");
CPPUNIT_ASSERT(vars[9]->isType<Local>());
CPPUNIT_ASSERT(vars[9]->name() == "f3");
CPPUNIT_ASSERT(vars[10]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[10])->tokenname() == "float@f");
// @d should depend on: @d, a, @e
vars.clear();
variableDependencies(*lastd, vars);
CPPUNIT_ASSERT_EQUAL(3ul, vars.size());
CPPUNIT_ASSERT(vars[0]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@d");
CPPUNIT_ASSERT(vars[1]->isType<Local>());
CPPUNIT_ASSERT(vars[1]->name() == "a");
CPPUNIT_ASSERT(vars[2]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e");
// @e should depend on itself
vars.clear();
variableDependencies(*laste, vars);
CPPUNIT_ASSERT_EQUAL(1ul, vars.size());
CPPUNIT_ASSERT(vars[0]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@e");
// @f should depend on nothing
vars.clear();
variableDependencies(*lastf, vars);
CPPUNIT_ASSERT(vars.empty());
// @v should depend on: m, v@v
vars.clear();
variableDependencies(*lastv, vars);
CPPUNIT_ASSERT_EQUAL(2ul, vars.size());
CPPUNIT_ASSERT(vars[0]->isType<Local>());
CPPUNIT_ASSERT(vars[0]->name() == "m");
CPPUNIT_ASSERT(vars[1]->isType<Attribute>());
CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[1])->tokenname() == "vec3f@v");
}
*/
| 22,773 | C++ | 33.453858 | 97 | 0.585957 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestPrinters.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Parse.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <cppunit/extensions/HelperMacros.h>
#include <string>
#include <ostream>
using namespace openvdb::ax::ast;
using namespace openvdb::ax::ast::tokens;
class TestPrinters : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(TestPrinters);
CPPUNIT_TEST(testReprint);
CPPUNIT_TEST_SUITE_END();
void testReprint();
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestPrinters);
void TestPrinters::testReprint()
{
// Small function providing more verbose output on failures
auto check = [](const std::string& in, const std::string& expected) {
const size_t min = std::min(in.size(), expected.size());
for (size_t i = 0; i < min; ++i) {
if (in[i] != expected[i]) {
std::ostringstream msg;
msg << "TestReprint failed at character " << i << '.'
<< '[' << in[i] << "] vs [" << expected[i] << "]\n"
<< "Got:\n" << in
<< "Expected:\n" << expected;
CPPUNIT_FAIL(msg.str());
}
}
if (in.size() != expected.size()) {
std::ostringstream msg;
msg << "TestReprint failed at end character.\n"
<< "Got:\n" << in
<< "Expected:\n" << expected ;
CPPUNIT_FAIL(msg.str());
}
};
std::ostringstream os;
// Test binary ops
std::string in = "a + b * c / d % e << f >> g = h & i | j ^ k && l || m;";
std::string expected = "(((a + (((b * c) / d) % e)) << f) >> g = ((((h & i) | (j ^ k)) && l) || m));\n";
Tree::ConstPtr tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test binary ops paren
os.str("");
in = "(a + b) * (c / d) % e << (f) >> g = (((h & i) | j) ^ k) && l || m;";
expected = "(((((a + b) * (c / d)) % e) << f) >> g = (((((h & i) | j) ^ k) && l) || m));\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test relational
os.str("");
in = "a <= b; c >= d; e == f; g != h; i < j; k > l;";
expected = "(a <= b);\n(c >= d);\n(e == f);\n(g != h);\n(i < j);\n(k > l);\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test assignments
os.str("");
in = "a = b; b += c; c -= d; d /= e; e *= f; f %= 1; g &= 2; h |= 3; i ^= 4; j <<= 5; k >>= 6;";
expected = "a = b;\nb += c;\nc -= d;\nd /= e;\ne *= f;\nf %= 1;\ng &= 2;\nh |= 3;\ni ^= 4;\nj <<= 5;\nk >>= 6;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test crement
os.str("");
in = "++++a; ----b; a++; b--;";
expected = "++++a;\n----b;\na++;\nb--;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test comma
os.str("");
in = "a,b,(c,d),(e,(f,(g,h,i)));";
expected = "(a, b, (c, d), (e, (f, (g, h, i))));\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test array unpack
os.str("");
in = "a.x; b.y; c.z; d[0]; d[1,2]; e[(a.r, c.b), b.g];";
expected = "a[0];\nb[1];\nc[2];\nd[0];\nd[1, 2];\ne[(a[0], c[2]), b[1]];\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test array pack
os.str("");
in = "a = {0,1}; b = {2,3,4}; c = {a,(b,c), d};";
expected = "a = {0, 1};\nb = {2, 3, 4};\nc = {a, (b, c), d};\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test declarations
os.str("");
in = "bool a; int b,c; int32 d=0, e; int64 f; float g; double h, i=0;";
expected = "bool a;\nint32 b, c;\nint32 d = 0, e;\nint64 f;\nfloat g;\ndouble h, i = 0;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test conditionals
os.str("");
in = "if (a) b; else if (c) d; else e; if (a) if (b) { c,d; } else { e,f; }";
expected = "if (a)\n{\nb;\n}\nelse\n{\nif (c)\n{\nd;\n}\nelse\n{\ne;\n}\n}\nif (a)\n{\nif (b)\n{\n(c, d);\n}\nelse\n{\n(e, f);\n}\n}\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test keywords
os.str("");
in = "return; break; continue; true; false;";
expected = "return;\nbreak;\ncontinue;\ntrue;\nfalse;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test attributes/externals
os.str("");
in = "@a; $a; v@b; v$b; f@a; f$a; i@c; i$c; s@d; s$d;";
expected = "float@a;\nfloat$a;\nvec3f@b;\nvec3f$b;\nfloat@a;\nfloat$a;\nint32@c;\nint32$c;\nstring@d;\nstring$d;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test ternary
os.str("");
in = "a ? b : c; a ? b ? c ? : d : e : f;";
expected = "a ? b : c;\na ? b ? c ?: d : e : f;\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test loops
os.str("");
in = "while (a) for (int32 b, c;;) do { d; } while (e)";
expected = "while (a)\n{\nfor (int32 b, c; true; )\n{\ndo\n{\nd;\n}\nwhile (e)\n}\n}\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, "");
check(os.str(), ("{\n" + expected + "}\n"));
// Test loops with indents
os.str("");
in = "while (a) for (int32 b, c;;) do { d; } while (e)";
expected = " while (a)\n {\n for (int32 b, c; true; )\n {\n do\n {\n d;\n }\n while (e)\n }\n }\n";
tree = parse(in.c_str());
CPPUNIT_ASSERT(tree.get());
reprint(*tree, os, " ");
check(os.str(), ("{\n" + expected + "}\n"));
}
| 6,566 | C++ | 33.382199 | 142 | 0.465885 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/cmd/openvdb_ax.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file cmd/openvdb_ax.cc
///
/// @authors Nick Avramoussis, Richard Jones
///
/// @brief The command line vdb_ax binary which provides tools to
/// run and analyze AX code.
///
#include <openvdb_ax/ast/AST.h>
#include <openvdb_ax/ast/Scanners.h>
#include <openvdb_ax/ast/PrintTree.h>
#include <openvdb_ax/codegen/Functions.h>
#include <openvdb_ax/compiler/Compiler.h>
#include <openvdb_ax/compiler/AttributeRegistry.h>
#include <openvdb_ax/compiler/CompilerOptions.h>
#include <openvdb_ax/compiler/PointExecutable.h>
#include <openvdb_ax/compiler/VolumeExecutable.h>
#include <openvdb_ax/compiler/Logger.h>
#include <openvdb/openvdb.h>
#include <openvdb/version.h>
#include <openvdb/util/logging.h>
#include <openvdb/util/CpuTimer.h>
#include <openvdb/points/PointDelete.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* gProgName = "";
void usage [[noreturn]] (int exitStatus = EXIT_FAILURE)
{
std::cerr <<
"Usage: " << gProgName << " [input.vdb [output.vdb] | analyze] [-s \"string\" | -f file.txt] [OPTIONS]\n" <<
"Which: executes a string or file containing a code snippet on an input.vdb file\n\n" <<
"Options:\n" <<
" -s snippet execute code snippet on the input.vdb file\n" <<
" -f file.txt execute text file containing a code snippet on the input.vdb file\n" <<
" -v verbose (print timing and diagnostics)\n" <<
" --opt level set an optimization level on the generated IR [NONE, O0, O1, O2, Os, Oz, O3]\n" <<
" --werror set warnings as errors\n" <<
" --max-errors n sets the maximum number of error messages to n, a value of 0 (default) allows all error messages\n" <<
" analyze parse the provided code and enter analysis mode\n" <<
" --ast-print descriptive print the abstract syntax tree generated\n" <<
" --re-print re-interpret print of the provided code after ast traversal\n" <<
" --reg-print print the attribute registry (name, types, access, dependencies)\n" <<
" --try-compile [points|volumes] \n" <<
" attempt to compile the provided code for points or volumes, or both if no\n" <<
" additional option is provided, reporting any failures or success.\n" <<
" functions enter function mode to query available function information\n" <<
" --list [name] list all available functions, their documentation and their signatures.\n" <<
" optionally only list functions which whose name includes a provided string.\n" <<
" --list-names list all available functions names only\n" <<
"Warning:\n" <<
" Providing the same file-path to both input.vdb and output.vdb arguments will overwrite\n" <<
" the file. If no output file is provided, the input.vdb will be processed but will remain\n" <<
" unchanged on disk (this is useful for testing the success status of code).\n";
exit(exitStatus);
}
struct ProgOptions
{
enum Mode { Execute, Analyze, Functions };
enum Compilation { All, Points, Volumes };
Mode mMode = Execute;
// Compilation options
size_t mMaxErrors = 0;
bool mWarningsAsErrors = false;
// Execute options
std::unique_ptr<std::string> mInputCode = nullptr;
std::string mInputVDBFile = "";
std::string mOutputVDBFile = "";
bool mVerbose = false;
openvdb::ax::CompilerOptions::OptLevel mOptLevel =
openvdb::ax::CompilerOptions::OptLevel::O3;
// Analyze options
bool mPrintAST = false;
bool mReprint = false;
bool mAttribRegPrint = false;
bool mInitCompile = false;
Compilation mCompileFor = All;
// Function Options
bool mFunctionList = false;
bool mFunctionNamesOnly = false;
std::string mFunctionSearch = "";
};
inline std::string modeString(const ProgOptions::Mode mode)
{
switch (mode) {
case ProgOptions::Execute : return "execute";
case ProgOptions::Analyze : return "analyze";
case ProgOptions::Functions : return "functions";
default : return "";
}
}
ProgOptions::Compilation
tryCompileStringToCompilation(const std::string& str)
{
if (str == "points") return ProgOptions::Points;
if (str == "volumes") return ProgOptions::Volumes;
OPENVDB_LOG_FATAL("invalid option given for --try-compile level");
usage();
}
openvdb::ax::CompilerOptions::OptLevel
optStringToLevel(const std::string& str)
{
if (str == "NONE") return openvdb::ax::CompilerOptions::OptLevel::NONE;
if (str == "O0") return openvdb::ax::CompilerOptions::OptLevel::O0;
if (str == "O1") return openvdb::ax::CompilerOptions::OptLevel::O1;
if (str == "O2") return openvdb::ax::CompilerOptions::OptLevel::O2;
if (str == "Os") return openvdb::ax::CompilerOptions::OptLevel::Os;
if (str == "Oz") return openvdb::ax::CompilerOptions::OptLevel::Oz;
if (str == "O3") return openvdb::ax::CompilerOptions::OptLevel::O3;
OPENVDB_LOG_FATAL("invalid option given for --opt level");
usage();
}
inline std::string
optLevelToString(const openvdb::ax::CompilerOptions::OptLevel level)
{
switch (level) {
case openvdb::ax::CompilerOptions::OptLevel::NONE : return "NONE";
case openvdb::ax::CompilerOptions::OptLevel::O1 : return "O1";
case openvdb::ax::CompilerOptions::OptLevel::O2 : return "O2";
case openvdb::ax::CompilerOptions::OptLevel::Os : return "Os";
case openvdb::ax::CompilerOptions::OptLevel::Oz : return "Oz";
case openvdb::ax::CompilerOptions::OptLevel::O3 : return "O3";
default : return "";
}
}
void loadSnippetFile(const std::string& fileName, std::string& textString)
{
std::ifstream in(fileName.c_str(), std::ios::in | std::ios::binary);
if (!in) {
OPENVDB_LOG_FATAL("File Load Error: " << fileName);
usage();
}
textString =
std::string(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
}
struct OptParse
{
int argc;
char** argv;
OptParse(int argc_, char* argv_[]): argc(argc_), argv(argv_) {}
bool check(int idx, const std::string& name, int numArgs = 1) const
{
if (argv[idx] == name) {
if (idx + numArgs >= argc) {
OPENVDB_LOG_FATAL("option " << name << " requires "
<< numArgs << " argument" << (numArgs == 1 ? "" : "s"));
usage();
}
return true;
}
return false;
}
};
struct ScopedInitialize
{
ScopedInitialize(int argc, char *argv[]) {
openvdb::logging::initialize(argc, argv);
openvdb::initialize();
}
~ScopedInitialize() {
if (openvdb::ax::isInitialized()) {
openvdb::ax::uninitialize();
}
openvdb::uninitialize();
}
inline void initializeCompiler() const { openvdb::ax::initialize(); }
inline bool isInitialized() const { return openvdb::ax::isInitialized(); }
};
void printFunctions(const bool namesOnly,
const std::string& search,
std::ostream& os)
{
static const size_t maxHelpTextWidth = 100;
openvdb::ax::FunctionOptions opts;
opts.mLazyFunctions = false;
const openvdb::ax::codegen::FunctionRegistry::UniquePtr registry =
openvdb::ax::codegen::createDefaultRegistry(&opts);
// convert to ordered map for alphabetical sorting
// only include non internal functions and apply any search
// criteria
std::map<std::string, const openvdb::ax::codegen::FunctionGroup*> functionMap;
for (const auto& iter : registry->map()) {
if (iter.second.isInternal()) continue;
if (!search.empty() && iter.first.find(search) == std::string::npos) {
continue;
}
functionMap[iter.first] = iter.second.function();
}
if (functionMap.empty()) return;
if (namesOnly) {
const size_t size = functionMap.size();
size_t pos = 0, count = 0;
auto iter = functionMap.cbegin();
for (; iter != functionMap.cend(); ++iter) {
if (count == size - 1) break;
const std::string& name = iter->first;
if (count != 0 && pos > maxHelpTextWidth) {
os << '\n';
pos = 0;
}
pos += name.size() + 2; // 2=", "
os << name << ',' << ' ';
++count;
}
os << iter->first << '\n';
}
else {
llvm::LLVMContext C;
for (const auto& iter : functionMap) {
const openvdb::ax::codegen::FunctionGroup* const function = iter.second;
const char* cdocs = function->doc();
if (!cdocs || cdocs[0] == '\0') {
cdocs = "<No documentation exists for this function>";
}
// do some basic formatting on the help text
std::string docs(cdocs);
size_t pos = maxHelpTextWidth;
while (pos < docs.size()) {
while (docs[pos] != ' ' && pos != 0) --pos;
if (pos == 0) break;
docs.insert(pos, "\n| ");
pos += maxHelpTextWidth;
}
os << iter.first << '\n' << '|' << '\n';
os << "| - " << docs << '\n' << '|' << '\n';
const auto& list = function->list();
for (const openvdb::ax::codegen::Function::Ptr& decl : list) {
os << "| - ";
decl->print(C, os);
os << '\n';
}
os << '\n';
}
}
}
int
main(int argc, char *argv[])
{
OPENVDB_START_THREADSAFE_STATIC_WRITE
gProgName = argv[0];
const char* ptr = ::strrchr(gProgName, '/');
if (ptr != nullptr) gProgName = ptr + 1;
OPENVDB_FINISH_THREADSAFE_STATIC_WRITE
if (argc == 1) usage();
OptParse parser(argc, argv);
ProgOptions opts;
openvdb::util::CpuTimer timer;
auto getTime = [&timer]() -> std::string {
const double msec = timer.milliseconds();
std::ostringstream os;
openvdb::util::printTime(os, msec, "", "", 1, 1, 0);
return os.str();
};
auto& os = std::cout;
#define axlog(message) \
{ if (opts.mVerbose) os << message; }
#define axtimer() timer.restart()
#define axtime() getTime()
bool multiSnippet = false;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg[0] == '-') {
if (parser.check(i, "-s")) {
++i;
multiSnippet |= static_cast<bool>(opts.mInputCode);
opts.mInputCode.reset(new std::string(argv[i]));
} else if (parser.check(i, "-f")) {
++i;
multiSnippet |= static_cast<bool>(opts.mInputCode);
opts.mInputCode.reset(new std::string());
loadSnippetFile(argv[i], *opts.mInputCode);
} else if (parser.check(i, "-v", 0)) {
opts.mVerbose = true;
} else if (parser.check(i, "--max-errors")) {
opts.mMaxErrors = atoi(argv[++i]);
} else if (parser.check(i, "--werror", 0)) {
opts.mWarningsAsErrors = true;
} else if (parser.check(i, "--list", 0)) {
opts.mFunctionList = true;
opts.mInitCompile = true; // need to intialize llvm
opts.mFunctionNamesOnly = false;
if (i + 1 >= argc) continue;
if (argv[i+1][0] == '-') continue;
++i;
opts.mFunctionSearch = std::string(argv[i]);
} else if (parser.check(i, "--list-names", 0)) {
opts.mFunctionList = true;
opts.mFunctionNamesOnly = true;
} else if (parser.check(i, "--ast-print", 0)) {
opts.mPrintAST = true;
} else if (parser.check(i, "--re-print", 0)) {
opts.mReprint = true;
} else if (parser.check(i, "--reg-print", 0)) {
opts.mAttribRegPrint = true;
} else if (parser.check(i, "--try-compile", 0)) {
opts.mInitCompile = true;
if (i + 1 >= argc) continue;
if (argv[i+1][0] == '-') continue;
++i;
opts.mCompileFor = tryCompileStringToCompilation(argv[i]);
} else if (parser.check(i, "--opt")) {
++i;
opts.mOptLevel = optStringToLevel(argv[i]);
} else if (arg == "-h" || arg == "-help" || arg == "--help") {
usage(EXIT_SUCCESS);
} else {
OPENVDB_LOG_FATAL("\"" + arg + "\" is not a valid option");
usage();
}
} else if (!arg.empty()) {
// if mode has already been set, no more positional arguments are expected
// (except for execute which takes in and out)
if (opts.mMode != ProgOptions::Mode::Execute) {
OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\"");
usage();
}
if (arg == "analyze") opts.mMode = ProgOptions::Analyze;
else if (arg == "functions") opts.mMode = ProgOptions::Functions;
if (opts.mMode == ProgOptions::Mode::Execute) {
opts.mInitCompile = true;
// execute positional argument setup
if (opts.mInputVDBFile.empty()) {
opts.mInputVDBFile = arg;
}
else if (opts.mOutputVDBFile.empty()) {
opts.mOutputVDBFile = arg;
}
else {
OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\"");
usage();
}
}
else if (!opts.mInputVDBFile.empty() ||
!opts.mOutputVDBFile.empty())
{
OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\"");
usage();
}
} else {
usage();
}
}
if (opts.mVerbose) {
axlog("OpenVDB AX " << openvdb::getLibraryVersionString() << '\n');
axlog("----------------\n");
axlog("Inputs\n");
axlog(" mode : " << modeString(opts.mMode));
if (opts.mMode == ProgOptions::Analyze) {
axlog(" (");
if (opts.mPrintAST) axlog("|ast out");
if (opts.mReprint) axlog("|reprint out");
if (opts.mAttribRegPrint) axlog("|registry out");
if (opts.mInitCompile) axlog("|compilation");
axlog("|)");
}
axlog('\n');
if (opts.mMode == ProgOptions::Execute) {
axlog(" vdb in : \"" << opts.mInputVDBFile << "\"\n");
axlog(" vdb out : \"" << opts.mOutputVDBFile << "\"\n");
}
if (opts.mMode == ProgOptions::Execute ||
opts.mMode == ProgOptions::Analyze) {
axlog(" ax code : ");
if (opts.mInputCode && !opts.mInputCode->empty()) {
const bool containsnl =
opts.mInputCode->find('\n') != std::string::npos;
if (containsnl) axlog("\n ");
// indent output
const char* c = opts.mInputCode->c_str();
while (*c != '\0') {
axlog(*c);
if (*c == '\n') axlog(" ");
++c;
}
}
else {
axlog("\"\"");
}
axlog('\n');
axlog('\n');
}
axlog(std::flush);
}
if (opts.mMode != ProgOptions::Functions) {
if (!opts.mInputCode) {
OPENVDB_LOG_FATAL("expected at least one AX file or a code snippet");
usage();
}
if (multiSnippet) {
OPENVDB_LOG_WARN("multiple code snippets provided, only using last input.");
}
}
if (opts.mMode == ProgOptions::Execute) {
if (opts.mInputVDBFile.empty()) {
OPENVDB_LOG_FATAL("expected at least one VDB file or analysis mode");
usage();
}
if (opts.mOutputVDBFile.empty()) {
OPENVDB_LOG_WARN("no output VDB File specified - nothing will be written to disk");
}
}
axtimer();
axlog("[INFO] Initializing OpenVDB" << std::flush);
ScopedInitialize initializer(argc, argv);
axlog(": " << axtime() << '\n');
// read vdb file data for
openvdb::GridPtrVecPtr grids;
openvdb::MetaMap::Ptr meta;
if (opts.mMode == ProgOptions::Execute) {
openvdb::io::File file(opts.mInputVDBFile);
try {
axtimer();
axlog("[INFO] Reading VDB data"
<< (openvdb::io::Archive::isDelayedLoadingEnabled() ?
" (delay-load)" : "") << std::flush);
file.open();
grids = file.getGrids();
meta = file.getMetadata();
file.close();
axlog(": " << axtime() << '\n');
} catch (openvdb::Exception& e) {
OPENVDB_LOG_ERROR(e.what() << " (" << opts.mInputVDBFile << ")");
return EXIT_FAILURE;
}
}
if (opts.mInitCompile) {
axtimer();
axlog("[INFO] Initializing AX/LLVM" << std::flush);
initializer.initializeCompiler();
axlog(": " << axtime() << '\n');
}
if (opts.mMode == ProgOptions::Functions) {
if (opts.mFunctionList) {
axlog("Querying available functions\n" << std::flush);
assert(opts.mFunctionNamesOnly || initializer.isInitialized());
printFunctions(opts.mFunctionNamesOnly,
opts.mFunctionSearch,
std::cout);
}
return EXIT_SUCCESS;
}
// set up logger
openvdb::ax::Logger
logs([](const std::string& msg) { std::cerr << msg << std::endl; },
[](const std::string& msg) { std::cerr << msg << std::endl; });
logs.setMaxErrors(opts.mMaxErrors);
logs.setWarningsAsErrors(opts.mWarningsAsErrors);
logs.setPrintLines(true);
logs.setNumberedOutput(true);
// parse
axtimer();
axlog("[INFO] Parsing input code" << std::flush);
const openvdb::ax::ast::Tree::ConstPtr syntaxTree =
openvdb::ax::ast::parse(opts.mInputCode->c_str(), logs);
axlog(": " << axtime() << '\n');
if (!syntaxTree) {
return EXIT_FAILURE;
}
if (opts.mMode == ProgOptions::Analyze) {
axlog("[INFO] Running analysis options\n" << std::flush);
if (opts.mPrintAST) {
axlog("[INFO] | Printing AST\n" << std::flush);
openvdb::ax::ast::print(*syntaxTree, true, std::cout);
}
if (opts.mReprint) {
axlog("[INFO] | Reprinting code\n" << std::flush);
openvdb::ax::ast::reprint(*syntaxTree, std::cout);
}
if (opts.mAttribRegPrint) {
axlog("[INFO] | Printing Attribute Registry\n" << std::flush);
const openvdb::ax::AttributeRegistry::ConstPtr reg =
openvdb::ax::AttributeRegistry::create(*syntaxTree);
reg->print(std::cout);
std::cout << std::flush;
}
if (!opts.mInitCompile) {
return EXIT_SUCCESS;
}
}
assert(opts.mInitCompile);
axtimer();
axlog("[INFO] Creating Compiler\n");
axlog("[INFO] | Optimization Level [" << optLevelToString(opts.mOptLevel) << "]\n" << std::flush);
openvdb::ax::CompilerOptions compOpts;
compOpts.mOptLevel = opts.mOptLevel;
openvdb::ax::Compiler::Ptr compiler =
openvdb::ax::Compiler::create(compOpts);
openvdb::ax::CustomData::Ptr customData =
openvdb::ax::CustomData::create();
axlog("[INFO] | " << axtime() << '\n' << std::flush);
// Check what we need to compile for if performing execution
if (opts.mMode == ProgOptions::Execute) {
assert(meta);
assert(grids);
bool points = false;
bool volumes = false;
for (auto grid : *grids) {
points |= grid->isType<openvdb::points::PointDataGrid>();
volumes |= !points;
if (points && volumes) break;
}
if (points && volumes) opts.mCompileFor = ProgOptions::Compilation::All;
else if (points) opts.mCompileFor = ProgOptions::Compilation::Points;
else if (volumes) opts.mCompileFor = ProgOptions::Compilation::Volumes;
}
if (opts.mMode == ProgOptions::Analyze) {
bool psuccess = true;
if (opts.mCompileFor == ProgOptions::Compilation::All ||
opts.mCompileFor == ProgOptions::Compilation::Points) {
axtimer();
axlog("[INFO] Compiling for VDB Points\n" << std::flush);
try {
compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData);
if (logs.hasError()) {
axlog("[INFO] Compilation error(s)!\n");
psuccess = false;
}
}
catch (std::exception& e) {
psuccess = false;
axlog("[INFO] Fatal error!\n");
OPENVDB_LOG_ERROR(e.what());
}
const bool hasWarning = logs.hasWarning();
if (psuccess) {
axlog("[INFO] | Compilation successful");
if (hasWarning) axlog(" with warning(s)\n");
}
axlog("[INFO] | " << axtime() << '\n' << std::flush);
}
bool vsuccess = true;
if (opts.mCompileFor == ProgOptions::Compilation::All ||
opts.mCompileFor == ProgOptions::Compilation::Volumes) {
axtimer();
axlog("[INFO] Compiling for VDB Volumes\n" << std::flush);
try {
compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData);
if (logs.hasError()) {
axlog("[INFO] Compilation error(s)!\n");
vsuccess = false;
}
}
catch (std::exception& e) {
vsuccess = false;
axlog("[INFO] Fatal error!\n");
OPENVDB_LOG_ERROR(e.what());
}
const bool hasWarning = logs.hasWarning();
if (vsuccess) {
axlog("[INFO] | Compilation successful");
if (hasWarning) axlog(" with warning(s)\n");
}
axlog("[INFO] | " << axtime() << '\n' << std::flush);
}
return ((vsuccess && psuccess) ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Execute points
if (opts.mCompileFor == ProgOptions::Compilation::All ||
opts.mCompileFor == ProgOptions::Compilation::Points) {
axlog("[INFO] VDB PointDataGrids Found\n" << std::flush);
openvdb::ax::PointExecutable::Ptr pointExe;
axtimer();
try {
axlog("[INFO] Compiling for VDB Points\n" << std::flush);
pointExe = compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData);
} catch (std::exception& e) {
OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what());
return EXIT_FAILURE;
}
if (pointExe) {
axlog("[INFO] | Compilation successful");
if (logs.hasWarning()) {
axlog(" with warning(s)\n");
}
}
else {
if (logs.hasError()) {
axlog("[INFO] Compilation error(s)!\n");
}
return EXIT_FAILURE;
}
axlog("[INFO] | " << axtime() << '\n' << std::flush);
size_t total = 0, count = 1;
if (opts.mVerbose) {
for (auto grid : *grids) {
if (!grid->isType<openvdb::points::PointDataGrid>()) continue;
++total;
}
}
for (auto grid : *grids) {
if (!grid->isType<openvdb::points::PointDataGrid>()) continue;
openvdb::points::PointDataGrid::Ptr points =
openvdb::gridPtrCast<openvdb::points::PointDataGrid>(grid);
axtimer();
axlog("[INFO] Executing on \"" << points->getName() << "\" "
<< count << " of " << total << '\n' << std::flush);
++count;
try {
pointExe->execute(*points);
if (openvdb::ax::ast::callsFunction(*syntaxTree, "deletepoint")) {
openvdb::points::deleteFromGroup(points->tree(), "dead", false, false);
}
}
catch (std::exception& e) {
OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what());
return EXIT_FAILURE;
}
axlog("[INFO] | Execution success.\n");
axlog("[INFO] | " << axtime() << '\n' << std::flush);
}
}
// Execute volumes
if (opts.mCompileFor == ProgOptions::Compilation::All ||
opts.mCompileFor == ProgOptions::Compilation::Volumes) {
axlog("[INFO] VDB Volumes Found\n" << std::flush);
openvdb::ax::VolumeExecutable::Ptr volumeExe;
try {
axlog("[INFO] Compiling for VDB Points\n" << std::flush);
volumeExe = compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData);
} catch (std::exception& e) {
OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what());
return EXIT_FAILURE;
}
if (volumeExe) {
axlog("[INFO] | Compilation successful");
if (logs.hasWarning()) {
axlog(" with warning(s)\n"); }
}
else {
if (logs.hasError()) {
axlog("[INFO] Compilation error(s)!\n");
}
return EXIT_FAILURE;
}
axlog("[INFO] | " << axtime() << '\n' << std::flush);
if (opts.mVerbose) {
std::vector<const std::string*> names;
axlog("[INFO] Executing using:\n");
for (auto grid : *grids) {
if (grid->isType<openvdb::points::PointDataGrid>()) continue;
axlog(" " << grid->getName() << '\n');
axlog(" " << grid->valueType() << '\n');
axlog(" " << grid->gridClassToString(grid->getGridClass()) << '\n');
}
axlog(std::flush);
}
try { volumeExe->execute(*grids); }
catch (std::exception& e) {
OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what());
return EXIT_FAILURE;
}
axlog("[INFO] | Execution success.\n");
axlog("[INFO] | " << axtime() << '\n' << std::flush);
}
if (!opts.mOutputVDBFile.empty()) {
axtimer();
axlog("[INFO] Writing results" << std::flush);
openvdb::io::File out(opts.mOutputVDBFile);
try {
out.write(*grids, *meta);
} catch (openvdb::Exception& e) {
OPENVDB_LOG_ERROR(e.what() << " (" << out.filename() << ")");
return EXIT_FAILURE;
}
axlog("[INFO] | " << axtime() << '\n' << std::flush);
}
return EXIT_SUCCESS;
}
| 27,537 | C++ | 34.71725 | 128 | 0.525584 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionTypes.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/FunctionTypes.h
///
/// @authors Nick Avramoussis
///
/// @brief Contains frameworks for creating custom AX functions which can
/// be registered within the FunctionRegistry and used during code
/// generation. The intended and safest way to build a function is to
/// use the FunctionBuilder struct with its addSignature methods. Note
/// that the derived Function classes provided can also be subclassed
/// for more granular control, however may be subject to more substantial
/// API changes.
///
/// @details There are a variety of different ways to build a function
/// which are tailored towards different function types. The two currently
/// supported function implementations are C Bindings and IR generation.
/// Additionally, depending on the return type of the function, you may
/// need to declare your function an SRET (structural return) function.
///
/// C Bindings:
/// As the name suggests, the CFunction class infrastructure provides
/// the quickest and easiest way to bind to methods in your host
/// application. The most important thing to consider when choosing
/// this approach is performance. LLVM will have no knowledge of the
/// function body during optimization passes. Depending on the
/// implementation of your method and the user's usage from AX, C
/// bindings may be subject to limited optimizations in comparison to
/// IR functions. For example, a static function which is called from
/// within a loop cannot be unrolled. See the CFunction templated
/// class.
///
/// IR Functions:
/// IR Functions expect implementations to generate the body of the
/// function directly into IR during code generation. This ensures
/// optimal performance during optimization passes however can be
/// trickier to design. Note that, in the future, AX functions will
/// be internally supported to provide a better solution for
/// IR generated functions. See the IRFunction templated class.
///
/// SRET Functions:
/// Both C Bindings and IR Functions can be marked as SRET methods.
/// SRET methods, in AX, are any function which returns a value which
/// is not a scalar (e.g. vectors, matrices). This follows the same
/// optimization logic as clang which will rebuild function signatures
/// with their return type as the first argument if the return type is
/// greater than a given size. You should never attempt to return
/// alloca's directly from functions (unless malloced).
///
/// Some other things to consider:
/// - Ensure C Binding dependencies have been correctly mapped.
/// - Avoid calling B.CreateAlloca inside of IR functions - instead
/// rely on the utility method insertStaticAlloca() where possible.
/// - Ensure both floating point and integer argument signatures are
/// provided if you wish to avoid floats truncating.
/// - Array arguments (vectors/matrices) are always passed by pointer.
/// Scalar arguments are always passed by copy.
/// - Ensure array arguments which will not be modified are marked as
/// readonly. Currently, only array arguments can be passed by
/// "reference".
/// - Ensure function bodies, return types and parameters and marked
/// with desirable llvm attributes.
///
#ifndef OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED
#include "Types.h"
#include "Utils.h" // isValidCast
#include "ConstantFolding.h"
#include <openvdb/version.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <stack>
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief Object to array conversion methods to allow functions to return
/// vector types. These containers provided an interface for automatic
/// conversion of C++ objects to LLVM types as array types.
template <typename T, size_t _SIZE = 1>
struct ArgType {
using Type = T;
static const size_t SIZE = _SIZE;
using ArrayType = Type[SIZE];
ArrayType mData;
};
template <typename T, size_t S>
struct LLVMType<ArgType<T,S>> : public AliasTypeMap<ArgType<T,S>, T[S]> {};
using V2D = ArgType<double, 2>;
using V2F = ArgType<float, 2>;
using V2I = ArgType<int32_t, 2>;
using V3D = ArgType<double, 3>;
using V3F = ArgType<float, 3>;
using V3I = ArgType<int32_t, 3>;
using V4D = ArgType<double, 4>;
using V4F = ArgType<float, 4>;
using V4I = ArgType<int32_t, 4>;
using M3D = ArgType<double, 9>;
using M3F = ArgType<float, 9>;
using M4D = ArgType<double, 16>;
using M4F = ArgType<float, 16>;
////////////////////////////////////////////////////////////////////////////////
/// @brief Type to symbol conversions - these characters are used to build each
/// functions unique signature. They differ from standard AX or LLVM
/// syntax to be as short as possible i.e. vec4d, [4 x double] = d4
template <typename T> struct TypeToSymbol { static inline std::string s() { return "?"; } };
template <> struct TypeToSymbol<void> { static inline std::string s() { return "v"; } };
template <> struct TypeToSymbol<char> { static inline std::string s() { return "c"; } };
template <> struct TypeToSymbol<int16_t> { static inline std::string s() { return "s"; } };
template <> struct TypeToSymbol<int32_t> { static inline std::string s() { return "i"; } };
template <> struct TypeToSymbol<int64_t> { static inline std::string s() { return "l"; } };
template <> struct TypeToSymbol<float> { static inline std::string s() { return "f"; } };
template <> struct TypeToSymbol<double> { static inline std::string s() { return "d"; } };
template <> struct TypeToSymbol<AXString> { static inline std::string s() { return "a"; } };
template <typename T>
struct TypeToSymbol<T*> {
static inline std::string s() { return TypeToSymbol<T>::s() + "*"; }
};
template <typename T, size_t S>
struct TypeToSymbol<T[S]> {
static inline std::string s() { return TypeToSymbol<T>::s() + std::to_string(S); }
};
template <typename T, size_t S> struct TypeToSymbol<ArgType<T,S>> : public TypeToSymbol<T[S]> {};
template <typename T> struct TypeToSymbol<math::Vec2<T>> : public TypeToSymbol<T[2]> {};
template <typename T> struct TypeToSymbol<math::Vec3<T>> : public TypeToSymbol<T[3]> {};
template <typename T> struct TypeToSymbol<math::Vec4<T>> : public TypeToSymbol<T[4]> {};
template <typename T> struct TypeToSymbol<math::Mat3<T>> : public TypeToSymbol<T[9]> {};
template <typename T> struct TypeToSymbol<math::Mat4<T>> : public TypeToSymbol<T[16]> {};
template <typename T> struct TypeToSymbol<const T> : public TypeToSymbol<T> {};
template <typename T> struct TypeToSymbol<const T*> : public TypeToSymbol<T*> {};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief Templated argument iterator which implements various small functions
/// per argument type, resolved at compile time.
///
template <typename SignatureT, size_t I = FunctionTraits<SignatureT>::N_ARGS>
struct ArgumentIterator
{
using ArgT = typename FunctionTraits<SignatureT>::template Arg<I-1>;
using ArgumentValueType = typename ArgT::Type;
template <typename OpT>
static void apply(const OpT& op, const bool forwards) {
if (forwards) {
ArgumentIterator<SignatureT, I-1>::apply(op, forwards);
op(ArgumentValueType());
}
else {
op(ArgumentValueType());
ArgumentIterator<SignatureT, I-1>::apply(op, forwards);
}
}
};
template <typename SignatureT>
struct ArgumentIterator<SignatureT, 0>
{
template <typename OpT>
static void apply(const OpT&, const bool) {}
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief Populate a vector of llvm types from a function signature declaration.
///
/// @param C The llvm context
/// @param types A vector of types to populate
///
template <typename SignatureT>
inline llvm::Type*
llvmTypesFromSignature(llvm::LLVMContext& C,
std::vector<llvm::Type*>* types = nullptr)
{
using Traits = FunctionTraits<SignatureT>;
using ArgumentIteratorT =
ArgumentIterator<SignatureT, Traits::N_ARGS>;
if (types) {
types->reserve(Traits::N_ARGS);
auto callback = [&types, &C](auto type) {
using Type = decltype(type);
types->emplace_back(LLVMType<Type>::get(C));
};
ArgumentIteratorT::apply(callback, /*forwards*/true);
}
return LLVMType<typename Traits::ReturnType>::get(C);
}
/// @brief Generate an LLVM FunctionType from a function signature
///
/// @param C The llvm context
///
template <typename SignatureT>
inline llvm::FunctionType*
llvmFunctionTypeFromSignature(llvm::LLVMContext& C)
{
std::vector<llvm::Type*> types;
llvm::Type* returnType =
llvmTypesFromSignature<SignatureT>(C, &types);
return llvm::FunctionType::get(/*Result=*/returnType,
/*Params=*/llvm::ArrayRef<llvm::Type*>(types),
/*isVarArg=*/false);
}
/// @brief Print a function signature to the provided ostream.
///
/// @param os The stream to print to
/// @param types The function argument types
/// @param returnType The return type of the function. Must not be a nullptr
/// @param name The name of the function. If not provided, the return type
/// neighbours the first parenthesis
/// @param names Names of the function parameters. If a name is nullptr, it
/// skipped
/// @param axTypes Whether to try and convert the llvm::Types provided to
/// AX types. If false, the llvm types are used.
void
printSignature(std::ostream& os,
const std::vector<llvm::Type*>& types,
const llvm::Type* returnType,
const char* name = nullptr,
const std::vector<const char*>& names = {},
const bool axTypes = false);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief The base/abstract representation of an AX function. Derived classes
/// must implement the Function::types call to describe their signature.
struct Function
{
using Ptr = std::shared_ptr<Function>;
Function(const size_t size, const std::string& symbol)
: mSize(size)
, mSymbol(symbol)
, mAttributes(nullptr)
, mNames()
, mDeps() {
// symbol must be a valid string
assert(!symbol.empty());
}
virtual ~Function() = default;
/// @brief Populate a vector of llvm::Types which describe this function
/// signature. This method is used by Function::create,
/// Function::print and Function::match.
virtual llvm::Type* types(std::vector<llvm::Type*>&, llvm::LLVMContext&) const = 0;
/// @brief Converts and creates this AX function into a llvm Function.
/// @details This method uses the result from Function::types() to construct
/// a llvm::FunctionType and a subsequent a llvm::Function. Any
/// parameter, return or function attributes are also added to the
/// function. If a module is provided, the module if first checked
/// to see if the function already exists. If it does, it is
/// immediately returned. If the function doesn't exist in the
/// module, its prototype is created and also inserted into the end
/// of the modules function list. If no module is provided, the
/// function is left detached and must be added to a valid Module
/// to be callable.
/// @note The body of the function is left to derived classes to
/// implement. As you need a Module to generate the prototype/body,
/// this function serves two purposes. The first is to return the
/// detached function signature if only a context is provided.
/// The second is to ensure the function prototype and body (if
/// required) is inserted into the module prior to returning.
/// @note It is possible to end up with function symbol collisions if you
/// do not have unique function symbols in your module
///
/// @param C The LLVM Context
/// @param M The Module to write the function to
virtual llvm::Function*
create(llvm::LLVMContext& C, llvm::Module* M = nullptr) const;
/// @brief Convenience method which always uses the provided module to find
/// the function or insert it if necessary.
/// @param M The llvm::Module to use
llvm::Function* create(llvm::Module& M) const {
return this->create(M.getContext(), &M);
}
/// @brief Uses the IRBuilder to create a call to this function with the
/// given arguments, creating the function and inserting it into the
/// IRBuilder's Module if necessary (through Function::create).
/// @note The IRBuilder must have a valid llvm Module/Function/Block
/// attached
/// @note If the number of provided arguments do not match the size of the
/// current function, invalid IR will be generated.
/// @note If the provided argument types do not match the current function
/// and cast is false, invalid IR will be generated. Additionally,
/// invalid IR will be generated if cast is true but no valid cast
/// exists for a given argument.
/// @note When casting arguments, the readonly flags of the function are
/// not checked (unlike Function::match). Casting an argument will
/// cause a new copy of the argument to be created and passed to the
/// function. These new values do not propagate back any changes to
/// the original argument. Separate functions for all writable
/// argument types must be created.
///
/// @param args The llvm Value arguments to call this function with
/// @param B The llvm IRBuilder
/// @param cast Whether to allow implicit casting of arguments
virtual llvm::Value*
call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast = false) const;
/// @brief The result type from calls to Function::match
enum SignatureMatch { None = 0, Size, Implicit, Explicit };
/// @brief The base implementation for determining how a vector of llvm
/// arguments translates to this functions signature. Returns an
/// enum which represents the available mapping.
/// @details This method calls types() to figure out the function signature,
/// then compares each argument type to the type in the input
/// vector. If the types match exactly, an Explicit match is found.
/// If the sizes of the inputs and signature differ, no match is
/// found and None is returned. If however, the sizes match and
/// there exists a valid implicit cast from the input type to the
/// signature type for every input, an Implicit match is returned.
/// Finally, if the sizes match but there is no implicit cast
/// mapping, Size is returned.
/// i8 -> i32 : Implicit
/// i32 -> i32 : Explicit
/// str -> i32 : Size
/// (i32,i32) -> i32 : None
/// @note Due to the way CFunctionSRet is implemented, the LLVM Context
/// must be provided in case we have a zero arg function signature
/// with a SRET.
/// @param inputs The input types
/// @param C The LLVM Context
virtual SignatureMatch match(const std::vector<llvm::Type*>& inputs, llvm::LLVMContext& C) const;
/// @brief The number of arguments that this function has
inline size_t size() const { return mSize; }
/// @brief The function symbol name.
/// @details This will be used as its identifier in IR and must be unique.
inline const char* symbol() const { return mSymbol.c_str(); }
/// @brief Returns the descriptive name of the given argument index
/// @details If the index is greater than the number of arguments, an empty
/// string is returned.
///
/// @param idx The index of the argument
inline const char* argName(const size_t idx) const {
return idx < mNames.size() ? mNames[idx] : "";
}
/// @brief Print this function's signature to the provided ostream.
/// @details This is intended to return a descriptive front end user string
/// rather than the function's IR representation. This function is
/// virtual so that derived classes can customize how they present
/// frontend information.
/// @sa printSignature
///
/// @param C The llvm context
/// @param os The ostream to print to
/// @param name The name to insert into the description.
/// @param axTypes Whether to print llvm IR or AX Types.
virtual void print(llvm::LLVMContext& C,
std::ostream& os,
const char* name = nullptr,
const bool axTypes = true) const;
/// Builder methods
inline bool hasParamAttribute(const size_t i,
const llvm::Attribute::AttrKind& kind) const
{
if (!mAttributes) return false;
const auto iter = mAttributes->mParamAttrs.find(i);
if (iter == mAttributes->mParamAttrs.end()) return false;
const auto& vec = iter->second;
return std::find(vec.begin(), vec.end(), kind) != vec.end();
}
inline void setArgumentNames(std::vector<const char*> names) { mNames = names; }
const std::vector<const char*>& dependencies() const { return mDeps; }
inline void setDependencies(std::vector<const char*> deps) { mDeps = deps; }
inline void setFnAttributes(const std::vector<llvm::Attribute::AttrKind>& in)
{
this->attrs().mFnAttrs = in;
}
inline void setRetAttributes(const std::vector<llvm::Attribute::AttrKind>& in)
{
this->attrs().mRetAttrs = in;
}
inline void setParamAttributes(const size_t i,
const std::vector<llvm::Attribute::AttrKind>& in)
{
this->attrs().mParamAttrs[i] = in;
}
protected:
/// @brief Cast the provided arguments to the given type as supported by
/// implicit casting of function types. If the types already match
/// OR if a cast cannot be performed, nothing is done to the argument.
/// @todo This should really be generalized out for Function::call and
/// Function::match to both use. However, due to SRET functions,
/// this logic must be performed somewhere in the Function class
/// hierarchy and not in FunctionGroup
static void cast(std::vector<llvm::Value*>& args,
const std::vector<llvm::Type*>& types,
llvm::IRBuilder<>& B);
private:
struct Attributes {
std::vector<llvm::Attribute::AttrKind> mFnAttrs, mRetAttrs;
std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs;
};
inline Attributes& attrs() {
if (!mAttributes) mAttributes.reset(new Attributes());
return *mAttributes;
}
llvm::AttributeList flattenAttrs(llvm::LLVMContext& C) const;
const size_t mSize;
const std::string mSymbol;
std::unique_ptr<Attributes> mAttributes;
std::vector<const char*> mNames;
std::vector<const char*> mDeps;
};
/// @brief Templated interface class for SRET functions. This struct provides
/// the interface for functions that wish to return arrays (vectors or
/// matrices) by internally remapping the first argument for the user.
/// As far as LLVM and any bindings are concerned, the function
/// signature remains unchanged - however the first argument becomes
/// "invisible" to the user and is instead allocated by LLVM before the
/// function is executed. Importantly, the argument has no impact on
/// the user facing AX signature and doesn't affect declaration selection.
/// @note This class is not intended to be instantiated directly, but instead
/// used by derived implementation which hold a valid implementations
/// of member functions required to create a llvm::Function (such as
/// Function::types and Function::call). This exists as an interface to
/// avoid virtual inheritance.
///
template <typename SignatureT, typename DerivedFunction>
struct SRetFunction : public DerivedFunction
{
using Ptr = std::shared_ptr<SRetFunction<SignatureT, DerivedFunction>>;
using Traits = FunctionTraits<SignatureT>;
// check there actually are arguments
static_assert(Traits::N_ARGS > 0,
"SRET Function object has been setup with the first argument as the return "
"value, however the provided signature is empty.");
// check no return value exists
static_assert(std::is_same<typename Traits::ReturnType, void>::value,
"SRET Function object has been setup with the first argument as the return "
"value and a non void return type.");
private:
using FirstArgument = typename Traits::template Arg<0>::Type;
static_assert(std::is_pointer<FirstArgument>::value,
"SRET Function object has been setup with the first argument as the return "
"value, but this argument it is not a pointer type.");
using SRetType = typename std::remove_pointer<FirstArgument>::type;
public:
/// @brief Override of match which inserts the SRET type such that the base
/// class methods ignore it.
Function::SignatureMatch match(const std::vector<llvm::Type*>& args,
llvm::LLVMContext& C) const override
{
// append return type and right rotate
std::vector<llvm::Type*> inputs(args);
inputs.emplace_back(LLVMType<SRetType*>::get(C));
std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend());
return DerivedFunction::match(inputs, C);
}
/// @brief Override of call which allocates the required SRET llvm::Value
/// for this function.
/// @note Unlike other function where the returned llvm::Value* is a
/// llvm::CallInst (which also represents the return value),
/// SRET functions return the allocated 1st argument i.e. not a
/// llvm::CallInst
llvm::Value*
call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast) const override
{
// append return value and right rotate
std::vector<llvm::Value*> inputs(args);
llvm::Type* sret = LLVMType<SRetType>::get(B.getContext());
inputs.emplace_back(insertStaticAlloca(B, sret));
std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend());
DerivedFunction::call(inputs, B, cast);
return inputs.front();
}
/// @brief Override of print to avoid printing out the SRET type
void print(llvm::LLVMContext& C,
std::ostream& os,
const char* name = nullptr,
const bool axTypes = true) const override
{
std::vector<llvm::Type*> current;
llvm::Type* ret = this->types(current, C);
// left rotate
std::rotate(current.begin(), current.begin() + 1, current.end());
ret = current.back();
current.pop_back();
std::vector<const char*> names;
names.reserve(this->size());
for (size_t i = 0; i < this->size()-1; ++i) {
names.emplace_back(this->argName(i));
}
printSignature(os, current, ret, name, names, axTypes);
}
protected:
/// @brief Forward all arguments to the derived class
template <typename ...Args>
SRetFunction(Args&&... ts) : DerivedFunction(ts...) {}
};
/// @brief The base class for all C bindings.
struct CFunctionBase : public Function
{
using Ptr = std::shared_ptr<CFunctionBase>;
~CFunctionBase() override = default;
/// @brief Returns the global address of this function.
/// @note This is only required for C bindings.
virtual uint64_t address() const = 0;
inline void setConstantFold(bool on) { mConstantFold = on; }
inline bool hasConstantFold() const { return mConstantFold; }
inline virtual llvm::Value* fold(const std::vector<llvm::Value*>&,
llvm::LLVMContext&) const {
return nullptr;
}
protected:
CFunctionBase(const size_t size,
const std::string& symbol)
: Function(size, symbol)
, mConstantFold(false) {}
private:
bool mConstantFold;
};
/// @brief Represents a concrete C function binding.
///
/// @note This struct is templated on the signature to allow for evaluation of
/// the arguments to llvm types from any llvm context.
///
template <typename SignatureT>
struct CFunction : public CFunctionBase
{
using CFunctionT = CFunction<SignatureT>;
using Ptr = std::shared_ptr<CFunctionT>;
using Traits = FunctionTraits<SignatureT>;
// Assert that the return argument is not a pointer. Note that this is
// relaxed for IR functions where it's allowed if the function is embedded.
static_assert(!std::is_pointer<typename Traits::ReturnType>::value,
"CFunction object has been setup with a pointer return argument. C bindings "
"cannot return memory locations to LLVM - Consider using a CFunctionSRet.");
CFunction(const std::string& symbol, const SignatureT function)
: CFunctionBase(Traits::N_ARGS, symbol)
, mFunction(function) {}
~CFunction() override = default;
inline llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override
{
return llvmTypesFromSignature<SignatureT>(C, &types);
}
inline uint64_t address() const override final {
return reinterpret_cast<uint64_t>(mFunction);
}
llvm::Value*
call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast) const override
{
llvm::Value* result = this->fold(args, B.getContext());
if (result) return result;
return Function::call(args, B, cast);
}
llvm::Value* fold(const std::vector<llvm::Value*>& args, llvm::LLVMContext& C) const override final
{
auto allconst =
[](const std::vector<llvm::Value*>& vals) -> bool {
for (auto& value : vals) {
if (!llvm::isa<llvm::Constant>(value)) return false;
}
return true;
};
if (!this->hasConstantFold()) return nullptr;
if (!allconst(args)) return nullptr;
std::vector<llvm::Constant*> constants;
constants.reserve(args.size());
for (auto& value : args) {
constants.emplace_back(llvm::cast<llvm::Constant>(value));
}
// no guarantee that fold() will be able to cast all arguments
return ConstantFolder<SignatureT>::fold(constants, *mFunction, C);
}
private:
const SignatureT* mFunction;
};
/// @brief The base/abstract definition for an IR function.
struct IRFunctionBase : public Function
{
using Ptr = std::shared_ptr<IRFunctionBase>;
/// @brief The IR callback function which will write the LLVM IR for this
/// function's body.
/// @details The first argument is the vector of functional arguments. i.e.
/// a representation of the value that the callback has been invoked
/// with.
/// The last argument is the IR builder which should be used to
/// generate the function body IR.
/// @note You can return a nullptr from this method which will represent
/// a ret void, a ret void instruction, or an actual value
using GeneratorCb = std::function<llvm::Value*
(const std::vector<llvm::Value*>&, llvm::IRBuilder<>&)>;
llvm::Type* types(std::vector<llvm::Type*>& types,
llvm::LLVMContext& C) const override = 0;
/// @brief Enable or disable the embedding of IR. Embedded IR is currently
/// required for function which use parent function parameters.
inline void setEmbedIR(bool on) { mEmbedIR = on; }
inline bool hasEmbedIR() const { return mEmbedIR; }
/// @brief Override for the creation of an IR function. This ensures that
/// the body and prototype of the function are generated if a Module
/// is provided.
/// @note A nullptr is returned if mEmbedIR is true and no action is
/// performed.
/// @note Throws if this function has been initialized with a nullptr
/// generator callback. In this case, the function prototype will
/// be created, but not the function body.
/// @note Throws if the return type of the generator callback does not
/// match the function prototype. In this case, both the prototype
/// and the function body will be created and inserted, but the IR
/// will be invalid.
llvm::Function*
create(llvm::LLVMContext& C, llvm::Module* M) const override;
/// @brief Override for call, which is only necessary if mEmbedIR is true,
/// as the IR generation for embedded functions is delayed until
/// the function is called. If mEmbedIR is false, this simply calls
/// Function::call
llvm::Value*
call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast) const override;
protected:
// @todo This should ideally live in FunctionGroup::execute, but the return
// type is allowed to differ for sret C bindings.
inline void
verifyResultType(const llvm::Type* result, const llvm::Type* expected) const
{
if (result == expected) return;
std::string source, target;
if (result) llvmTypeToString(result, source);
llvmTypeToString(expected, target);
OPENVDB_THROW(AXCodeGenError, "Function \"" + std::string(this->symbol()) +
"\" has been invoked with a mismatching return type. Expected: \"" +
target + "\", got \"" + source + "\".");
}
IRFunctionBase(const std::string& symbol,
const GeneratorCb& gen,
const size_t size)
: Function(size, symbol)
, mGen(gen)
, mEmbedIR(false) {}
~IRFunctionBase() override = default;
const GeneratorCb mGen;
bool mEmbedIR;
};
/// @brief Represents a concrete IR function.
template <typename SignatureT>
struct IRFunction : public IRFunctionBase
{
using Traits = FunctionTraits<SignatureT>;
using Ptr = std::shared_ptr<IRFunction>;
IRFunction(const std::string& symbol, const GeneratorCb& gen)
: IRFunctionBase(symbol, gen, Traits::N_ARGS) {}
inline llvm::Type*
types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override
{
return llvmTypesFromSignature<SignatureT>(C, &types);
}
};
/// @brief Represents a concrete C function binding with the first argument as
/// its return type.
template <typename SignatureT>
struct CFunctionSRet : public SRetFunction<SignatureT, CFunction<SignatureT>>
{
using BaseT = SRetFunction<SignatureT, CFunction<SignatureT>>;
CFunctionSRet(const std::string& symbol, const SignatureT function)
: BaseT(symbol, function) {}
~CFunctionSRet() override = default;
};
/// @brief Represents a concrete IR function with the first argument as
/// its return type.
template <typename SignatureT>
struct IRFunctionSRet : public SRetFunction<SignatureT, IRFunction<SignatureT>>
{
using BaseT = SRetFunction<SignatureT, IRFunction<SignatureT>>;
IRFunctionSRet(const std::string& symbol,
const IRFunctionBase::GeneratorCb& gen)
: BaseT(symbol, gen) {}
~IRFunctionSRet() override = default;
};
/// @brief todo
struct FunctionGroup
{
using Ptr = std::shared_ptr<FunctionGroup>;
using UniquePtr = std::unique_ptr<FunctionGroup>;
using FunctionList = std::vector<Function::Ptr>;
FunctionGroup(const char* name,
const char* doc,
const FunctionList& list)
: mName(name)
, mDoc(doc)
, mFunctionList(list) {}
~FunctionGroup() = default;
/// @brief Given a vector of llvm types, automatically returns the best
/// possible function declaration from the stored function list. The
/// 'best' declaration is determined by the provided types
/// compatibility to each functions signature.
/// @note If multiple implicit matches are found, the first match is
/// returned.
/// @note Returns a nullptr if no compatible match was found or if the
/// function list is empty. A compatible match is defined as an
/// Explicit or Implicit match.
///
/// @param types A vector of types representing the function argument types
/// @param C The llvm context
/// @param type If provided, type is set to the type of match that occurred
///
Function::Ptr
match(const std::vector<llvm::Type*>& types,
llvm::LLVMContext& C,
Function::SignatureMatch* type = nullptr) const;
/// @brief Given a vector of llvm values provided by the user, find the
/// best possible function signature, generate and execute the
/// function body. Returns the return value of the function (can be
/// void).
/// @note This function will throw if not compatible match is found or if
/// no valid return is provided by the matched declarations
/// implementation.
///
/// @param args A vector of values representing the function arguments
/// @param B The current llvm IRBuilder
///
llvm::Value*
execute(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) const;
/// @brief Accessor to the underlying function signature list
///
inline const FunctionList& list() const { return mFunctionList; }
const char* name() const { return mName; }
const char* doc() const { return mDoc; }
private:
const char* mName;
const char* mDoc;
const FunctionList mFunctionList;
};
/// @brief The FunctionBuilder class provides a builder pattern framework to
/// allow easy and valid construction of AX functions. There are a
/// number of complex tasks which may need to be performed during
/// construction of C or IR function which are delegated to this
/// builder, whilst ensuring that the constructed functions are
/// guaranteed to be valid.
/// @details Use the FunctionBuilder::addSignature methods to append function
/// signatures. Finalize the group of functions with
/// FunctionBuilder::get.
struct FunctionBuilder
{
enum DeclPreferrence {
C, IR, Any
};
struct Settings
{
using Ptr = std::shared_ptr<Settings>;
inline bool isDefault() const {
if (mNames) return false;
if (!mDeps.empty()) return false;
if (mConstantFold || mEmbedIR) return false;
if (!mFnAttrs.empty()) return false;
if (!mRetAttrs.empty()) return false;
if (!mParamAttrs.empty()) return false;
return true;
}
std::shared_ptr<std::vector<const char*>> mNames = nullptr;
std::vector<const char*> mDeps = {};
bool mConstantFold = false;
bool mEmbedIR = false;
std::vector<llvm::Attribute::AttrKind> mFnAttrs = {};
std::vector<llvm::Attribute::AttrKind> mRetAttrs = {};
std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs = {};
};
FunctionBuilder(const char* name)
: mName(name)
, mCurrentSettings(new Settings()) {}
template <typename Signature, bool SRet = false>
inline FunctionBuilder&
addSignature(const IRFunctionBase::GeneratorCb& cb,
const char* symbol = nullptr)
{
using IRFType = typename std::conditional
<!SRet, IRFunction<Signature>, IRFunctionSRet<Signature>>::type;
using IRPtr = typename IRFType::Ptr;
Settings::Ptr settings = mCurrentSettings;
if (!mCurrentSettings->isDefault()) {
settings.reset(new Settings());
}
std::string s;
if (symbol) s = std::string(symbol);
else s = this->genSymbol<Signature>();
auto ir = IRPtr(new IRFType(s, cb));
mIRFunctions.emplace_back(ir);
mSettings[ir.get()] = settings;
mCurrentSettings = settings;
return *this;
}
template <typename Signature, bool SRet = false>
inline FunctionBuilder&
addSignature(const Signature* ptr,
const char* symbol = nullptr)
{
using CFType = typename std::conditional
<!SRet, CFunction<Signature>, CFunctionSRet<Signature>>::type;
using CPtr = typename CFType::Ptr;
Settings::Ptr settings = mCurrentSettings;
if (!mCurrentSettings->isDefault()) {
settings.reset(new Settings());
}
std::string s;
if (symbol) s = std::string(symbol);
else s = this->genSymbol<Signature>();
auto c = CPtr(new CFType(s, ptr));
mCFunctions.emplace_back(c);
mSettings[c.get()] = settings;
mCurrentSettings = settings;
return *this;
}
template <typename Signature, bool SRet = false>
inline FunctionBuilder&
addSignature(const IRFunctionBase::GeneratorCb& cb, const Signature* ptr, const char* symbol = nullptr)
{
this->addSignature<Signature, SRet>(cb, symbol);
this->addSignature<Signature, SRet>(ptr, symbol);
return *this;
}
inline FunctionBuilder& addDependency(const char* name) {
mCurrentSettings->mDeps.emplace_back(name); return *this;
}
inline FunctionBuilder& setEmbedIR(bool on) { mCurrentSettings->mEmbedIR = on; return *this; }
inline FunctionBuilder& setConstantFold(bool on) { mCurrentSettings->mConstantFold = on; return *this; }
inline FunctionBuilder& setArgumentNames(const std::vector<const char*>& names) {
mCurrentSettings->mNames.reset(new std::vector<const char*>(names));
return *this;
}
/// @details Parameter and Function Attributes. When designing a C binding,
/// llvm will be unable to assign parameter markings to the return
/// type, function body or parameter attributes due to there not
/// being any visibility on the function itself during codegen.
/// The best way to ensure performant C bindings is to ensure
/// that the function is marked with the required llvm parameters.
/// Some of the heavy hitters (which can have the most impact)
/// are below:
///
/// Functions:
/// - norecurse
/// This function attribute indicates that the function does
/// not call itself either directly or indirectly down any
/// possible call path.
///
/// - willreturn
/// This function attribute indicates that a call of this
/// function will either exhibit undefined behavior or comes
/// back and continues execution at a point in the existing
/// call stack that includes the current invocation.
///
/// - nounwind
/// This function attribute indicates that the function never
/// raises an exception.
///
/// - readnone
/// On a function, this attribute indicates that the function
/// computes its result (or decides to unwind an exception) based
/// strictly on its arguments, without dereferencing any pointer
/// arguments or otherwise accessing any mutable state (e.g. memory,
/// control registers, etc) visible to caller functions.
///
/// - readonly
/// On a function, this attribute indicates that the function
/// does not write through any pointer arguments (including byval
/// arguments) or otherwise modify any state (e.g. memory, control
/// registers, etc) visible to caller functions.
/// control registers, etc) visible to caller functions.
///
/// - writeonly
/// On a function, this attribute indicates that the function may
/// write to but does not read from memory.
///
/// Parameters:
/// - noalias
/// This indicates that objects accessed via pointer values based
/// on the argument or return value are not also accessed, during
/// the execution of the function, via pointer values not based on
/// the argument or return value.
///
/// - nonnull
/// This indicates that the parameter or return pointer is not null.
///
/// - readonly
/// Indicates that the function does not write through this pointer
/// argument, even though it may write to the memory that the pointer
/// points to.
///
/// - writeonly
/// Indicates that the function may write to but does not read through
/// this pointer argument (even though it may read from the memory
/// that the pointer points to).
///
inline FunctionBuilder&
addParameterAttribute(const size_t idx, const llvm::Attribute::AttrKind attr) {
mCurrentSettings->mParamAttrs[idx].emplace_back(attr);
return *this;
}
inline FunctionBuilder&
addReturnAttribute(const llvm::Attribute::AttrKind attr) {
mCurrentSettings->mRetAttrs.emplace_back(attr);
return *this;
}
inline FunctionBuilder&
addFunctionAttribute(const llvm::Attribute::AttrKind attr) {
mCurrentSettings->mFnAttrs.emplace_back(attr);
return *this;
}
inline FunctionBuilder& setDocumentation(const char* doc) { mDoc = doc; return *this; }
inline FunctionBuilder& setPreferredImpl(DeclPreferrence pref) { mDeclPref = pref; return *this; }
inline FunctionGroup::UniquePtr get() const
{
for (auto& decl : mCFunctions) {
const auto& s = mSettings.at(decl.get());
decl->setDependencies(s->mDeps);
decl->setConstantFold(s->mConstantFold);
if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs);
if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs);
if (!s->mParamAttrs.empty()) {
for (auto& idxAttrs : s->mParamAttrs) {
if (idxAttrs.first > decl->size()) continue;
decl->setParamAttributes(idxAttrs.first, idxAttrs.second);
}
}
if (s->mNames) decl->setArgumentNames(*s->mNames);
}
for (auto& decl : mIRFunctions) {
const auto& s = mSettings.at(decl.get());
decl->setDependencies(s->mDeps);
decl->setEmbedIR(s->mEmbedIR);
if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs);
if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs);
if (!s->mParamAttrs.empty()) {
for (auto& idxAttrs : s->mParamAttrs) {
if (idxAttrs.first > decl->size()) continue;
decl->setParamAttributes(idxAttrs.first, idxAttrs.second);
}
}
if (s->mNames) decl->setArgumentNames(*s->mNames);
}
std::vector<Function::Ptr> functions;
if (mDeclPref == DeclPreferrence::IR) {
functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end());
}
if (mDeclPref == DeclPreferrence::C) {
functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end());
}
if (functions.empty()) {
functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end());
functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end());
}
FunctionGroup::UniquePtr group(new FunctionGroup(mName, mDoc, functions));
return group;
}
private:
template <typename Signature>
std::string genSymbol() const
{
using Traits = FunctionTraits<Signature>;
std::string args;
auto callback = [&args](auto type) {
using Type = decltype(type);
args += TypeToSymbol<Type>::s();
};
ArgumentIterator<Signature>::apply(callback, /*forwards*/true);
/// @note important to prefix all symbols with "ax." so that
/// they will never conflict with internal llvm symbol
/// names (such as standard library methods e.g, cos, cosh
// assemble the symbol
return "ax." + std::string(this->mName) + "." +
TypeToSymbol<typename Traits::ReturnType>::s() + args;
}
const char* mName = "";
const char* mDoc = "";
DeclPreferrence mDeclPref = IR;
std::vector<CFunctionBase::Ptr> mCFunctions = {};
std::vector<IRFunctionBase::Ptr> mIRFunctions = {};
std::map<const Function*, Settings::Ptr> mSettings = {};
Settings::Ptr mCurrentSettings = nullptr;
};
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED
| 46,940 | C | 40.799644 | 108 | 0.623647 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/PointComputeGenerator.h
///
/// @authors Nick Avramoussis, Matt Warner, Francisco Gochez, Richard Jones
///
/// @brief The visitor framework and function definition for point data
/// grid code generation
///
#ifndef OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#define OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#include "ComputeGenerator.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../compiler/AttributeRegistry.h"
#include <openvdb/version.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief The function definition and signature which is built by the
/// PointComputeGenerator.
///
/// The argument structure is as follows:
///
/// 1) - A void pointer to the CustomData
/// 2) - A void pointer to the leaf AttributeSet
/// 3) - An unsigned integer, representing the leaf relative point
/// id being executed
/// 4) - A void pointer to a vector of void pointers, representing an
/// array of attribute handles
/// 5) - A void pointer to a vector of void pointers, representing an
/// array of group handles
/// 6) - A void pointer to a LeafLocalData object, used to track newly
/// initialized attributes and arrays
///
struct PointKernel
{
/// The signature of the generated function
using Signature =
void(const void* const,
const void* const,
uint64_t,
void**,
void**,
void*);
using FunctionTraitsT = codegen::FunctionTraits<Signature>;
static const size_t N_ARGS = FunctionTraitsT::N_ARGS;
/// The argument key names available during code generation
static const std::array<std::string, N_ARGS>& argumentKeys();
static std::string getDefaultName();
};
/// @brief An additonal function built by the PointComputeGenerator.
/// Currently both compute and compute range functions have the same
/// signature
struct PointRangeKernel : public PointKernel
{
static std::string getDefaultName();
};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
/// @brief Visitor object which will generate llvm IR for a syntax tree which has been generated from
/// AX that targets point grids. The IR will represent 2 functions : one that executes over
/// single points and one that executes over a collection of points. This is primarily used by the
/// Compiler class.
struct PointComputeGenerator : public ComputeGenerator
{
/// @brief Constructor
/// @param module llvm Module for generating IR
/// @param options Options for the function registry behaviour
/// @param functionRegistry Function registry object which will be used when generating IR
/// for function calls
/// @param logger Logger for collecting logical errors and warnings
PointComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger);
~PointComputeGenerator() override = default;
using ComputeGenerator::traverse;
using ComputeGenerator::visit;
AttributeRegistry::Ptr generate(const ast::Tree& node);
bool visit(const ast::Attribute*) override;
private:
llvm::Value* attributeHandleFromToken(const std::string&);
void getAttributeValue(const std::string& globalName, llvm::Value* location);
};
} // namespace namespace codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
| 4,032 | C | 32.890756 | 106 | 0.653522 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Utils.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/Utils.h
///
/// @authors Nick Avramoussis
///
/// @brief Utility code generation methods for performing various llvm
/// operations
///
#ifndef OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED
#include "Types.h"
#include "../ast/Tokens.h"
#include "../Exceptions.h"
#include <openvdb/version.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
// Note: As of LLVM 5.0, the llvm::Type::dump() method isn't being
// picked up correctly by the linker. dump() is internally implemented
// using Type::print(llvm::errs()) which is being used in place. See:
//
// https://stackoverflow.com/questions/43723127/llvm-5-0-makefile-undefined-reference-fail
//
#include <llvm/Support/raw_ostream.h> // llvm::errs()
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @note Function definitions for some types returned from automatic token to
/// llvm IR operations. See llvmArithmeticConversion and llvmBianryConversion
using CastFunction = std::function<llvm::Value*
(llvm::IRBuilder<>&, llvm::Value*, llvm::Type*)>;
using BinaryFunction = std::function<llvm::Value*
(llvm::IRBuilder<>&, llvm::Value*, llvm::Value*)>;
/// @brief Populate a vector of llvm Types from a vector of llvm values
///
/// @param values A vector of llvm values to retrieve types from
/// @param types A vector of llvm types to populate
///
inline void
valuesToTypes(const std::vector<llvm::Value*>& values,
std::vector<llvm::Type*>& types)
{
types.reserve(values.size());
for (const auto& v : values) {
types.emplace_back(v->getType());
}
}
/// @brief Prints an llvm type to a std string
///
/// @param type The llvm type to convert
/// @param str The string to store the type info to
///
inline void
llvmTypeToString(const llvm::Type* const type, std::string& str)
{
llvm::raw_string_ostream os(str);
type->print(os);
os.flush();
}
/// @brief Return the base llvm value which is being pointed to through
/// any number of layered pointers.
/// @note This function does not check for cyclical pointer dependencies
///
/// @param type A llvm pointer type to traverse
///
inline llvm::Type*
getBaseContainedType(llvm::Type* const type)
{
llvm::Type* elementType = type;
while (elementType->isPointerTy()) {
elementType = elementType->getContainedType(0);
}
return elementType;
}
/// @brief Return an llvm value representing a pointer to the provided ptr builtin
/// ValueT.
/// @note This is probably not a suitable solution for anything other than POD
/// types and should be used with caution.
///
/// @param ptr A pointer to a type of ValueT whose address will be computed and
/// returned
/// @param builder The current llvm IRBuilder
///
template <typename ValueT>
inline llvm::Value*
llvmPointerFromAddress(const ValueT* const& ptr,
llvm::IRBuilder<>& builder)
{
llvm::Value* address =
llvm::ConstantInt::get(llvm::Type::getIntNTy(builder.getContext(), sizeof(uintptr_t)*8),
reinterpret_cast<uintptr_t>(ptr));
return builder.CreateIntToPtr(address, LLVMType<ValueT*>::get(builder.getContext()));
}
/// @brief Insert a stack allocation at the beginning of the current function
/// of the provided type and size. The IRBuilder's insertion point must
/// be set to a BasicBlock with a valid Function parent.
/// @note If a size is provided, the size must not depend on any other
/// instructions. If it does, invalid LLVM IR will bb generated.
///
/// @param B The IRBuilder
/// @param type The type to allocate
/// @param size Optional count of allocations. If nullptr, runs a single allocation
inline llvm::Value*
insertStaticAlloca(llvm::IRBuilder<>& B,
llvm::Type* type,
llvm::Value* size = nullptr)
{
// Create the allocation at the start of the function block
llvm::Function* parent = B.GetInsertBlock()->getParent();
assert(parent && !parent->empty());
auto IP = B.saveIP();
llvm::BasicBlock& block = parent->front();
if (block.empty()) B.SetInsertPoint(&block);
else B.SetInsertPoint(&(block.front()));
llvm::Value* result = B.CreateAlloca(type, size);
B.restoreIP(IP);
return result;
}
inline llvm::Argument*
extractArgument(llvm::Function* F, const size_t idx)
{
if (!F) return nullptr;
if (idx >= F->arg_size()) return nullptr;
return llvm::cast<llvm::Argument>(F->arg_begin() + idx);
}
inline llvm::Argument*
extractArgument(llvm::Function* F, const std::string& name)
{
if (!F) return nullptr;
for (auto iter = F->arg_begin(); iter != F->arg_end(); ++iter) {
llvm::Argument* arg = llvm::cast<llvm::Argument>(iter);
if (arg->getName() == name) return arg;
}
return nullptr;
}
/// @brief Returns the highest order type from two LLVM Scalar types
///
/// @param typeA The first scalar llvm type
/// @param typeB The second scalar llvm type
///
inline llvm::Type*
typePrecedence(llvm::Type* const typeA,
llvm::Type* const typeB)
{
assert(typeA && (typeA->isIntegerTy() || typeA->isFloatingPointTy()) &&
"First Type in typePrecedence is not a scalar type");
assert(typeB && (typeB->isIntegerTy() || typeB->isFloatingPointTy()) &&
"Second Type in typePrecedence is not a scalar type");
// handle implicit arithmetic conversion
// (http://osr507doc.sco.com/en/tools/clang_conv_implicit.html)
if (typeA->isDoubleTy()) return typeA;
if (typeB->isDoubleTy()) return typeB;
if (typeA->isFloatTy()) return typeA;
if (typeB->isFloatTy()) return typeB;
if (typeA->isIntegerTy(64)) return typeA;
if (typeB->isIntegerTy(64)) return typeB;
if (typeA->isIntegerTy(32)) return typeA;
if (typeB->isIntegerTy(32)) return typeB;
if (typeA->isIntegerTy(16)) return typeA;
if (typeB->isIntegerTy(16)) return typeB;
if (typeA->isIntegerTy(8)) return typeA;
if (typeB->isIntegerTy(8)) return typeB;
if (typeA->isIntegerTy(1)) return typeA;
if (typeB->isIntegerTy(1)) return typeB;
assert(false && "invalid LLVM type precedence");
return nullptr;
}
/// @brief Returns a CastFunction which represents the corresponding instruction
/// to convert a source llvm Type to a target llvm Type. If the conversion
/// is unsupported, throws an error.
///
/// @param sourceType The source type to cast
/// @param targetType The target type to cast to
/// @param twine An optional string description of the cast function. This can
/// be used for for more verbose llvm information on IR compilation
/// failure
inline CastFunction
llvmArithmeticConversion(const llvm::Type* const sourceType,
const llvm::Type* const targetType,
const std::string& twine = "")
{
#define BIND_ARITHMETIC_CAST_OP(Function, Twine) \
std::bind(&Function, \
std::placeholders::_1, \
std::placeholders::_2, \
std::placeholders::_3, \
Twine)
if (targetType->isDoubleTy()) {
if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPExt, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateUIToFP, twine);
}
else if (targetType->isFloatTy()) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPTrunc, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateUIToFP, twine);
}
else if (targetType->isIntegerTy(64)) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine);
}
else if (targetType->isIntegerTy(32)) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine);
}
else if (targetType->isIntegerTy(16)) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine);
}
else if (targetType->isIntegerTy(8)) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine);
}
else if (targetType->isIntegerTy(1)) {
if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToUI, twine);
else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToUI, twine);
else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine);
}
#undef BIND_ARITHMETIC_CAST_OP
assert(false && "invalid LLVM type conversion");
return CastFunction();
}
/// @brief Returns a BinaryFunction representing the corresponding instruction to
/// peform on two scalar values, relative to a provided operator token. Note that
/// not all operations are supported on floating point types! If the token is not
/// supported, or the llvm type is not a scalar type, throws an error.
/// @note Various default arguments are bound to provide a simple function call
/// signature. For floating point operations, this includes a null pointer to
/// the optional metadata node. For integer operations, this includes disabling
/// all overflow/rounding optimisations
///
/// @param type The type defining the precision of the binary operation
/// @param token The token used to create the relative binary operation
/// @param twine An optional string description of the binary function. This can
/// be used for for more verbose llvm information on IR compilation
/// failure
inline BinaryFunction
llvmBinaryConversion(const llvm::Type* const type,
const ast::tokens::OperatorToken& token,
const std::string& twine = "")
{
#define BIND_BINARY_OP(Function) \
[twine](llvm::IRBuilder<>& B, llvm::Value* L, llvm::Value* R) \
-> llvm::Value* { return B.Function(L, R, twine); }
// NOTE: Binary % and / ops always take sign into account (CreateSDiv vs CreateUDiv, CreateSRem vs CreateURem).
// See http://stackoverflow.com/questions/5346160/llvm-irbuildercreateudiv-createsdiv-createexactudiv
// a%b in AX is implemented as a floored modulo op and is handled explicitly in binaryExpression
if (type->isFloatingPointTy()) {
assert(!(ast::tokens::operatorType(token) == ast::tokens::LOGICAL ||
ast::tokens::operatorType(token) == ast::tokens::BITWISE)
&& "unable to perform logical or bitwise operation on floating point values");
if (token == ast::tokens::PLUS) return BIND_BINARY_OP(CreateFAdd);
else if (token == ast::tokens::MINUS) return BIND_BINARY_OP(CreateFSub);
else if (token == ast::tokens::MULTIPLY) return BIND_BINARY_OP(CreateFMul);
else if (token == ast::tokens::DIVIDE) return BIND_BINARY_OP(CreateFDiv);
else if (token == ast::tokens::MODULO) return BIND_BINARY_OP(CreateFRem); // Note this is NOT a%b in AX.
else if (token == ast::tokens::EQUALSEQUALS) return BIND_BINARY_OP(CreateFCmpOEQ);
else if (token == ast::tokens::NOTEQUALS) return BIND_BINARY_OP(CreateFCmpONE);
else if (token == ast::tokens::MORETHAN) return BIND_BINARY_OP(CreateFCmpOGT);
else if (token == ast::tokens::LESSTHAN) return BIND_BINARY_OP(CreateFCmpOLT);
else if (token == ast::tokens::MORETHANOREQUAL) return BIND_BINARY_OP(CreateFCmpOGE);
else if (token == ast::tokens::LESSTHANOREQUAL) return BIND_BINARY_OP(CreateFCmpOLE);
assert(false && "unrecognised binary operator");
}
else if (type->isIntegerTy()) {
if (token == ast::tokens::PLUS) return BIND_BINARY_OP(CreateAdd); // No Unsigned/Signed Wrap
else if (token == ast::tokens::MINUS) return BIND_BINARY_OP(CreateSub); // No Unsigned/Signed Wrap
else if (token == ast::tokens::MULTIPLY) return BIND_BINARY_OP(CreateMul); // No Unsigned/Signed Wrap
else if (token == ast::tokens::DIVIDE) return BIND_BINARY_OP(CreateSDiv); // IsExact = false - when true, poison value if the reuslt is rounded
else if (token == ast::tokens::MODULO) return BIND_BINARY_OP(CreateSRem); // Note this is NOT a%b in AX.
else if (token == ast::tokens::EQUALSEQUALS) return BIND_BINARY_OP(CreateICmpEQ);
else if (token == ast::tokens::NOTEQUALS) return BIND_BINARY_OP(CreateICmpNE);
else if (token == ast::tokens::MORETHAN) return BIND_BINARY_OP(CreateICmpSGT);
else if (token == ast::tokens::LESSTHAN) return BIND_BINARY_OP(CreateICmpSLT);
else if (token == ast::tokens::MORETHANOREQUAL) return BIND_BINARY_OP(CreateICmpSGE);
else if (token == ast::tokens::LESSTHANOREQUAL) return BIND_BINARY_OP(CreateICmpSLE);
else if (token == ast::tokens::AND) return BIND_BINARY_OP(CreateAnd);
else if (token == ast::tokens::OR) return BIND_BINARY_OP(CreateOr);
else if (token == ast::tokens::SHIFTLEFT) return BIND_BINARY_OP(CreateShl); // No Unsigned/Signed Wrap
else if (token == ast::tokens::SHIFTRIGHT) return BIND_BINARY_OP(CreateAShr); // IsExact = false - poison value if any of the bits shifted out are non-zero.
else if (token == ast::tokens::BITAND) return BIND_BINARY_OP(CreateAnd);
else if (token == ast::tokens::BITOR) return BIND_BINARY_OP(CreateOr);
else if (token == ast::tokens::BITXOR) return BIND_BINARY_OP(CreateXor);
assert(false && "unrecognised binary operator");
}
#undef BIND_BINARY_OP
assert(false && "invalid LLVM type for binary operation");
return BinaryFunction();
}
/// @brief Returns true if the llvm Type 'from' can be safely cast to the llvm
/// Type 'to'.
inline bool isValidCast(llvm::Type* from, llvm::Type* to)
{
assert(from && "llvm Type 'from' is null in isValidCast");
assert(to && "llvm Type 'to' is null in isValidCast");
if ((from->isIntegerTy() || from->isFloatingPointTy()) &&
(to->isIntegerTy() || to->isFloatingPointTy())) {
return true;
}
if (from->isArrayTy() && to->isArrayTy()) {
llvm::ArrayType* af = llvm::cast<llvm::ArrayType>(from);
llvm::ArrayType* at = llvm::cast<llvm::ArrayType>(to);
if (af->getArrayNumElements() == at->getArrayNumElements()) {
return isValidCast(af->getArrayElementType(),
at->getArrayElementType());
}
}
return false;
}
/// @brief Casts a scalar llvm Value to a target scalar llvm Type. Returns
/// the cast scalar value of type targetType.
///
/// @param value A llvm scalar value to convert
/// @param targetType The target llvm scalar type to convert to
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
arithmeticConversion(llvm::Value* value,
llvm::Type* targetType,
llvm::IRBuilder<>& builder)
{
assert(value && (value->getType()->isIntegerTy() || value->getType()->isFloatingPointTy()) &&
"First Value in arithmeticConversion is not a scalar type");
assert(targetType && (targetType->isIntegerTy() || targetType->isFloatingPointTy()) &&
"Target Type in arithmeticConversion is not a scalar type");
const llvm::Type* const valueType = value->getType();
if (valueType == targetType) return value;
CastFunction llvmCastFunction = llvmArithmeticConversion(valueType, targetType);
return llvmCastFunction(builder, value, targetType);
}
/// @brief Casts an array to another array of equal size but of a different element
/// type. Both source and target array element types must be scalar types.
/// The source array llvm Value should be a pointer to the array to cast.
///
/// @param ptrToArray A llvm value which is a pointer to a llvm array
/// @param targetElementType The target llvm scalar type to convert each element
/// of the input array
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
arrayCast(llvm::Value* ptrToArray,
llvm::Type* targetElementType,
llvm::IRBuilder<>& builder)
{
assert(targetElementType && (targetElementType->isIntegerTy() ||
targetElementType->isFloatingPointTy()) &&
"Target element type is not a scalar type");
assert(ptrToArray && ptrToArray->getType()->isPointerTy() &&
"Input to arrayCast is not a pointer type.");
llvm::Type* arrayType = ptrToArray->getType()->getContainedType(0);
assert(arrayType && llvm::isa<llvm::ArrayType>(arrayType));
// getArrayElementType() calls getContainedType(0)
llvm::Type* sourceElementType = arrayType->getArrayElementType();
assert(sourceElementType && (sourceElementType->isIntegerTy() ||
sourceElementType->isFloatingPointTy()) &&
"Source element type is not a scalar type");
if (sourceElementType == targetElementType) return ptrToArray;
CastFunction llvmCastFunction = llvmArithmeticConversion(sourceElementType, targetElementType);
const size_t elementSize = arrayType->getArrayNumElements();
llvm::Value* targetArray =
insertStaticAlloca(builder,
llvm::ArrayType::get(targetElementType, elementSize));
for (size_t i = 0; i < elementSize; ++i) {
llvm::Value* target = builder.CreateConstGEP2_64(targetArray, 0, i);
llvm::Value* source = builder.CreateConstGEP2_64(ptrToArray, 0, i);
source = builder.CreateLoad(source);
source = llvmCastFunction(builder, source, targetElementType);
builder.CreateStore(source, target);
}
return targetArray;
}
/// @brief Converts a vector of loaded llvm scalar values of the same type to a
/// target scalar type. Each value is converted individually and the loaded result
/// stored in the same location within values.
///
/// @param values A vector of llvm scalar values to convert
/// @param targetElementType The target llvm scalar type to convert each value
/// of the input vector
/// @param builder The current llvm IRBuilder
///
inline void
arithmeticConversion(std::vector<llvm::Value*>& values,
llvm::Type* targetElementType,
llvm::IRBuilder<>& builder)
{
assert(targetElementType && (targetElementType->isIntegerTy() ||
targetElementType->isFloatingPointTy()) &&
"Target element type is not a scalar type");
llvm::Type* sourceElementType = values.front()->getType();
assert(sourceElementType && (sourceElementType->isIntegerTy() ||
sourceElementType->isFloatingPointTy()) &&
"Source element type is not a scalar type");
if (sourceElementType == targetElementType) return;
CastFunction llvmCastFunction = llvmArithmeticConversion(sourceElementType, targetElementType);
for (llvm::Value*& value : values) {
value = llvmCastFunction(builder, value, targetElementType);
}
}
/// @brief Converts a vector of loaded llvm scalar values to the highest precision
/// type stored amongst them. Any values which are not scalar types are ignored
///
/// @param values A vector of llvm scalar values to convert
/// @param builder The current llvm IRBuilder
///
inline void
arithmeticConversion(std::vector<llvm::Value*>& values,
llvm::IRBuilder<>& builder)
{
llvm::Type* typeCast = LLVMType<bool>::get(builder.getContext());
for (llvm::Value*& value : values) {
llvm::Type* type = value->getType();
if (type->isIntegerTy() || type->isFloatingPointTy()) {
typeCast = typePrecedence(typeCast, type);
}
}
arithmeticConversion(values, typeCast, builder);
}
/// @brief Chooses the highest order llvm Type as defined by typePrecedence
/// from either of the two incoming values and casts the other value to
/// the choosen type if it is not already. The types of valueA and valueB
/// are guaranteed to match. Both values must be scalar LLVM types
///
/// @param valueA The first llvm value
/// @param valueB The second llvm value
/// @param builder The current llvm IRBuilder
///
inline void
arithmeticConversion(llvm::Value*& valueA,
llvm::Value*& valueB,
llvm::IRBuilder<>& builder)
{
llvm::Type* type = typePrecedence(valueA->getType(), valueB->getType());
valueA = arithmeticConversion(valueA, type, builder);
valueB = arithmeticConversion(valueB, type, builder);
}
/// @brief Performs a C style boolean comparison from a given scalar LLVM value
///
/// @param value The scalar llvm value to convert to a boolean
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
boolComparison(llvm::Value* value,
llvm::IRBuilder<>& builder)
{
llvm::Type* type = value->getType();
if (type->isFloatingPointTy()) return builder.CreateFCmpONE(value, llvm::ConstantFP::get(type, 0.0));
else if (type->isIntegerTy(1)) return builder.CreateICmpNE(value, llvm::ConstantInt::get(type, 0));
else if (type->isIntegerTy()) return builder.CreateICmpNE(value, llvm::ConstantInt::getSigned(type, 0));
assert(false && "Invalid type for bool conversion");
return nullptr;
}
/// @ brief Performs a binary operation on two loaded llvm scalar values of the same type.
/// The type of operation performed is defined by the token (see the list of supported
/// tokens in ast/Tokens.h. Returns a loaded llvm scalar result
///
/// @param lhs The left hand side value of the binary operation
/// @param rhs The right hand side value of the binary operation
/// @param token The token representing the binary operation to perform
/// @param builder The current llvm IRBuilder
inline llvm::Value*
binaryOperator(llvm::Value* lhs, llvm::Value* rhs,
const ast::tokens::OperatorToken& token,
llvm::IRBuilder<>& builder)
{
llvm::Type* lhsType = lhs->getType();
assert(lhsType == rhs->getType());
const ast::tokens::OperatorType opType = ast::tokens::operatorType(token);
if (opType == ast::tokens::LOGICAL) {
lhs = boolComparison(lhs, builder);
rhs = boolComparison(rhs, builder);
lhsType = lhs->getType(); // now bool type
}
const BinaryFunction llvmBinaryFunction = llvmBinaryConversion(lhsType, token);
return llvmBinaryFunction(builder, lhs, rhs);
}
/// @brief Unpack a particular element of an array and return a pointer to that element
/// The provided llvm Value is expected to be a pointer to an array
///
/// @param ptrToArray A llvm value which is a pointer to a llvm array
/// @param index The index at which to access the array
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
arrayIndexUnpack(llvm::Value* ptrToArray,
const int16_t index,
llvm::IRBuilder<>& builder)
{
return builder.CreateConstGEP2_64(ptrToArray, 0, index);
}
/// @brief Unpack an array type into llvm Values which represent all its elements
/// The provided llvm Value is expected to be a pointer to an array
/// If loadElements is true, values will store loaded llvm values instead
/// of pointers to the array elements
///
/// @param ptrToArray A llvm value which is a pointer to a llvm array
/// @param values A vector of llvm values where to store the array elements
/// @param builder The current llvm IRBuilder
/// @param loadElements Whether or not to load each array element into a register
///
inline void
arrayUnpack(llvm::Value* ptrToArray,
std::vector<llvm::Value*>& values,
llvm::IRBuilder<>& builder,
const bool loadElements = false)
{
const size_t elements =
ptrToArray->getType()->getContainedType(0)->getArrayNumElements();
values.reserve(elements);
for (size_t i = 0; i < elements; ++i) {
llvm::Value* value = builder.CreateConstGEP2_64(ptrToArray, 0, i);
if (loadElements) value = builder.CreateLoad(value);
values.push_back(value);
}
}
/// @brief Unpack the first three elements of an array.
/// The provided llvm Value is expected to be a pointer to an array
/// @note The elements are note loaded
///
/// @param ptrToArray A llvm value which is a pointer to a llvm array
/// @param value1 The first array value
/// @param value2 The second array value
/// @param value3 The third array value
/// @param builder The current llvm IRBuilder
///
inline void
array3Unpack(llvm::Value* ptrToArray,
llvm::Value*& value1,
llvm::Value*& value2,
llvm::Value*& value3,
llvm::IRBuilder<>& builder)
{
assert(ptrToArray && ptrToArray->getType()->isPointerTy() &&
"Input to array3Unpack is not a pointer type.");
value1 = builder.CreateConstGEP2_64(ptrToArray, 0, 0);
value2 = builder.CreateConstGEP2_64(ptrToArray, 0, 1);
value3 = builder.CreateConstGEP2_64(ptrToArray, 0, 2);
}
/// @brief Pack three values into a new array and return a pointer to the
/// newly allocated array. If the values are of a mismatching type,
/// the highets order type is uses, as defined by typePrecedence. All
/// llvm values are expected to a be a loaded scalar type
///
/// @param value1 The first array value
/// @param value2 The second array value
/// @param value3 The third array value
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
array3Pack(llvm::Value* value1,
llvm::Value* value2,
llvm::Value* value3,
llvm::IRBuilder<>& builder)
{
llvm::Type* type = typePrecedence(value1->getType(), value2->getType());
type = typePrecedence(type, value3->getType());
value1 = arithmeticConversion(value1, type, builder);
value2 = arithmeticConversion(value2, type, builder);
value3 = arithmeticConversion(value3, type, builder);
llvm::Type* vectorType = llvm::ArrayType::get(type, 3);
llvm::Value* vector = insertStaticAlloca(builder, vectorType);
llvm::Value* e1 = builder.CreateConstGEP2_64(vector, 0, 0);
llvm::Value* e2 = builder.CreateConstGEP2_64(vector, 0, 1);
llvm::Value* e3 = builder.CreateConstGEP2_64(vector, 0, 2);
builder.CreateStore(value1, e1);
builder.CreateStore(value2, e2);
builder.CreateStore(value3, e3);
return vector;
}
/// @brief Pack a loaded llvm scalar value into a new array of a specified
/// size and return a pointer to the newly allocated array. Each element
/// of the new array will have the value of the given scalar
///
/// @param value The uniform scalar llvm value to pack into the array
/// @param builder The current llvm IRBuilder
/// @param size The size of the newly allocated array
///
inline llvm::Value*
arrayPack(llvm::Value* value,
llvm::IRBuilder<>& builder,
const size_t size = 3)
{
assert(value && (value->getType()->isIntegerTy() ||
value->getType()->isFloatingPointTy()) &&
"value type is not a scalar type");
llvm::Type* type = value->getType();
llvm::Value* array =
insertStaticAlloca(builder,
llvm::ArrayType::get(type, size));
for (size_t i = 0; i < size; ++i) {
llvm::Value* element = builder.CreateConstGEP2_64(array, 0, i);
builder.CreateStore(value, element);
}
return array;
}
/// @brief Pack a vector of loaded llvm scalar values into a new array of
/// equal size and return a pointer to the newly allocated array.
///
/// @param values A vector of loaded llvm scalar values to pack
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
arrayPack(const std::vector<llvm::Value*>& values,
llvm::IRBuilder<>& builder)
{
llvm::Type* type = values.front()->getType();
llvm::Value* array = insertStaticAlloca(builder,
llvm::ArrayType::get(type, values.size()));
size_t idx = 0;
for (llvm::Value* const& value : values) {
llvm::Value* element = builder.CreateConstGEP2_64(array, 0, idx++);
builder.CreateStore(value, element);
}
return array;
}
/// @brief Pack a vector of loaded llvm scalar values into a new array of
/// equal size and return a pointer to the newly allocated array.
/// arrayPackCast first checks all the contained types in values
/// and casts all types to the highest order type present. All llvm
/// values in values are expected to be loaded scalar types
///
/// @param values A vector of loaded llvm scalar values to pack
/// @param builder The current llvm IRBuilder
///
inline llvm::Value*
arrayPackCast(std::vector<llvm::Value*>& values,
llvm::IRBuilder<>& builder)
{
// get the highest order type present
llvm::Type* type = LLVMType<bool>::get(builder.getContext());
for (llvm::Value* const& value : values) {
type = typePrecedence(type, value->getType());
}
// convert all to this type
for (llvm::Value*& value : values) {
value = arithmeticConversion(value, type, builder);
}
return arrayPack(values, builder);
}
inline llvm::Value*
scalarToMatrix(llvm::Value* scalar,
llvm::IRBuilder<>& builder,
const size_t dim = 3)
{
assert(scalar && (scalar->getType()->isIntegerTy() ||
scalar->getType()->isFloatingPointTy()) &&
"value type is not a scalar type");
llvm::Type* type = scalar->getType();
llvm::Value* array =
insertStaticAlloca(builder,
llvm::ArrayType::get(type, dim*dim));
llvm::Value* zero = llvm::ConstantFP::get(type, 0.0);
for (size_t i = 0; i < dim*dim; ++i) {
llvm::Value* m = ((i % (dim+1) == 0) ? scalar : zero);
llvm::Value* element = builder.CreateConstGEP2_64(array, 0, i);
builder.CreateStore(m, element);
}
return array;
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED
| 34,561 | C | 42.860406 | 170 | 0.660716 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeComputeGenerator.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/VolumeComputeGenerator.h
///
/// @authors Nick Avramoussis
///
/// @brief The visitor framework and function definition for volume grid
/// code generation
///
#ifndef OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#define OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#include "ComputeGenerator.h"
#include "FunctionTypes.h"
#include "../compiler/AttributeRegistry.h"
#include <openvdb/version.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief The function definition and signature which is built by the
/// VolumeComputeGenerator.
///
/// The argument structure is as follows:
///
/// 1) - A void pointer to the CustomData
/// 2) - A pointer to an array of three ints representing the
/// current voxel coord being accessed
/// 3) - An pointer to an array of three floats representing the
/// current voxel world space coord being accessed
/// 4) - A void pointer to a vector of void pointers, representing
/// an array of grid accessors
/// 5) - A void pointer to a vector of void pointers, representing
/// an array of grid transforms
///
struct VolumeKernel
{
// The signature of the generated function
using Signature =
void(const void* const,
const int32_t (*)[3],
const float (*)[3],
void**,
void**,
int64_t,
void*);
using FunctionTraitsT = codegen::FunctionTraits<Signature>;
static const size_t N_ARGS = FunctionTraitsT::N_ARGS;
static const std::array<std::string, N_ARGS>& argumentKeys();
static std::string getDefaultName();
};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
/// @brief Visitor object which will generate llvm IR for a syntax tree which has been generated
/// from AX that targets volumes. The IR will represent a single function. It is mainly
/// used by the Compiler class.
struct VolumeComputeGenerator : public ComputeGenerator
{
/// @brief Constructor
/// @param module llvm Module for generating IR
/// @param options Options for the function registry behaviour
/// @param functionRegistry Function registry object which will be used when generating IR
/// for function calls
/// @param logger Logger for collecting logical errors and warnings
VolumeComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger);
~VolumeComputeGenerator() override = default;
using ComputeGenerator::traverse;
using ComputeGenerator::visit;
AttributeRegistry::Ptr generate(const ast::Tree& node);
bool visit(const ast::Attribute*) override;
private:
llvm::Value* accessorHandleFromToken(const std::string&);
void getAccessorValue(const std::string&, llvm::Value*);
};
} // namespace codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
| 3,505 | C | 31.766355 | 96 | 0.635378 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Types.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/Types.h
///
/// @authors Nick Avramoussis
///
/// @brief Consolidated llvm types for most supported types
///
#ifndef OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED
#include "../ast/Tokens.h"
#include "../Exceptions.h"
#include "../compiler/CustomData.h" // for AXString
#include <openvdb/version.h>
#include <openvdb/Types.h>
#include <openvdb/math/Mat3.h>
#include <openvdb/math/Mat4.h>
#include <openvdb/math/Vec3.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <type_traits>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
template <size_t Bits> struct int_t;
template <> struct int_t<8> { using type = int8_t; };
template <> struct int_t<16> { using type = int16_t; };
template <> struct int_t<32> { using type = int32_t; };
template <> struct int_t<64> { using type = int64_t; };
/// @brief LLVM type mapping from pod types
/// @note LLVM Types do not store information about the value sign, only meta
/// information about the primitive type (i.e. float, int, pointer) and
/// the precision width. LLVMType<uint64_t>::get(C) will provide the same
/// type as LLVMType<int64_t>::get(C), however sign is taken into account
/// during construction of LLVM constants.
/// @note LLVMType classes are importantly used to provided automatic external
/// function mapping. Note that references are not supported, pointers
/// should be used instead.
/// @note Provide your own custom class mapping by specializing the below.
template <typename T>
struct LLVMType
{
static_assert(!std::is_reference<T>::value,
"Reference types/arguments are not supported for automatic "
"LLVM Type conversion. Use pointers instead.");
static_assert(!std::is_class<T>::value,
"Object types/arguments are not supported for automatic "
"LLVM Type conversion.");
/// @brief Return an LLVM type which represents T
/// @param C The LLVMContext to request the Type from.
static inline llvm::Type*
get(llvm::LLVMContext& C)
{
// @note bools always treated as i1 values as the constants
// true and false from the IRBuilder are i1
if (std::is_same<T, bool>::value) {
return llvm::Type::getInt1Ty(C);
}
#if LLVM_VERSION_MAJOR > 6
return llvm::Type::getScalarTy<T>(C);
#else
int bits = sizeof(T) * CHAR_BIT;
if (std::is_integral<T>::value) {
return llvm::Type::getIntNTy(C, bits);
}
else if (std::is_floating_point<T>::value) {
switch (bits) {
case 32: return llvm::Type::getFloatTy(C);
case 64: return llvm::Type::getDoubleTy(C);
}
}
OPENVDB_THROW(AXCodeGenError, "LLVMType called with an unsupported type \"" +
std::string(typeNameAsString<T>()) + "\".");
#endif
}
/// @brief Return an LLVM constant Value which represents T value
/// @param C The LLVMContext
/// @param V The value to convert to an LLVM constant
/// @return If successful, returns a pointer to an LLVM constant which
/// holds the value T.
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T V)
{
llvm::Type* type = LLVMType<T>::get(C);
llvm::Constant* constant = nullptr;
if (std::is_floating_point<T>::value) {
assert(llvm::ConstantFP::isValueValidForType(type,
llvm::APFloat(static_cast<typename std::conditional
<std::is_floating_point<T>::value, T, double>::type>(V))));
constant = llvm::ConstantFP::get(type, static_cast<double>(V));
}
else if (std::is_integral<T>::value) {
const constexpr bool isSigned = std::is_signed<T>::value;
assert((isSigned && llvm::ConstantInt::isValueValidForType(type, static_cast<int64_t>(V))) ||
(!isSigned && llvm::ConstantInt::isValueValidForType(type, static_cast<uint64_t>(V))));
constant = llvm::ConstantInt::get(type, static_cast<uint64_t>(V), isSigned);
}
assert(constant);
return constant;
}
/// @brief Return an LLVM constant which holds an uintptr_t, representing
/// the current address of the given value.
/// @param C The LLVMContext
/// @param V The address of a given type to convert to an LLVM constant
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T* const V)
{
return LLVMType<uintptr_t>::get(C,
reinterpret_cast<uintptr_t>(V));
}
};
template <typename T, size_t S>
struct LLVMType<T[S]>
{
static_assert(S != 0,
"Zero size array types are not supported for automatic LLVM "
"Type conversion");
static inline llvm::Type*
get(llvm::LLVMContext& C) {
return llvm::ArrayType::get(LLVMType<T>::get(C), S);
}
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T(&array)[S]) {
return llvm::ConstantDataArray::get(C, array);
}
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T(*array)[S])
{
return LLVMType<uintptr_t>::get(C,
reinterpret_cast<uintptr_t>(array));
}
};
template <typename T>
struct LLVMType<T*>
{
static inline llvm::PointerType*
get(llvm::LLVMContext& C) {
return LLVMType<T>::get(C)->getPointerTo(0);
}
};
template <>
struct LLVMType<char> : public LLVMType<uint8_t>
{
static_assert(std::is_same<uint8_t, unsigned char>::value,
"This library requires std::uint8_t to be implemented as unsigned char.");
};
template <>
struct LLVMType<AXString>
{
static inline llvm::StructType*
get(llvm::LLVMContext& C) {
const std::vector<llvm::Type*> types {
LLVMType<char*>::get(C), // array
LLVMType<AXString::SizeType>::get(C) // size
};
return llvm::StructType::get(C, types);
}
static inline llvm::Value*
get(llvm::LLVMContext& C, llvm::Constant* string, llvm::Constant* size) {
return llvm::ConstantStruct::get(LLVMType<AXString>::get(C), {string, size});
}
/// @note Creating strings from a literal requires a GEP instruction to
/// store the string ptr on the struct.
/// @note Usually you should be using s = builder.CreateGlobalStringPtr()
/// followed by LLVMType<AXString>::get(C, s) rather than allocating
/// a non global string
static inline llvm::Value*
get(llvm::LLVMContext& C, const std::string& string, llvm::IRBuilder<>& builder) {
llvm::Constant* constant =
llvm::ConstantDataArray::getString(C, string, /*terminator*/true);
llvm::Constant* size = llvm::cast<llvm::Constant>
(LLVMType<AXString::SizeType>::get(C, static_cast<AXString::SizeType>(string.size())));
llvm::Value* zero = LLVMType<int32_t>::get(C, 0);
llvm::Value* args[] = { zero, zero };
constant = llvm::cast<llvm::Constant>
(builder.CreateInBoundsGEP(constant->getType(), constant, args));
return LLVMType<AXString>::get(C, constant, size);
}
static inline llvm::Constant*
get(llvm::LLVMContext& C, const AXString* const string)
{
return LLVMType<uintptr_t>::get(C,
reinterpret_cast<uintptr_t>(string));
}
};
template <>
struct LLVMType<void>
{
static inline llvm::Type*
get(llvm::LLVMContext& C) {
return llvm::Type::getVoidTy(C);
}
};
/// @note void* implemented as signed int_t* to match clang IR generation
template <> struct LLVMType<void*> : public LLVMType<int_t<sizeof(void*)>::type*> {};
template <typename T> struct LLVMType<const T> : public LLVMType<T> {};
template <typename T> struct LLVMType<const T*> : public LLVMType<T*> {};
/// @brief Alias mapping between two types, a frontend type T1 and a backend
/// type T2. This class is the intended interface for binding objects
/// which implement supported backend AX/IR types to this given backend
/// type. More specifically, it's current and expected usage is limited
/// to objects which hold a single member of a supported backend type
/// and implements a StandardLayoutType as defined by the standard.
/// Fundamentally, T1->T2 mapping should be supported by
/// reinterpret_cast<> as defined by the type aliasing rules.
/// @note The static asserts provide preliminary checks but are by no means
/// a guarantee that a provided mapping is correct. Ensure the above
/// requirements are met when instantiating an alias.
template <typename T1, typename T2>
struct AliasTypeMap
{
using LLVMTypeT = LLVMType<T2>;
static_assert(sizeof(T1) == sizeof(T2),
"T1 differs in size to T2 during alias mapping. Types should have "
"the same memory layout.");
static_assert(std::is_standard_layout<T1>::value,
"T1 in instantiation of an AliasTypeMap does not have a standard layout. "
"This will most likely cause undefined behaviour when attempting to map "
"T1->T2.");
static inline llvm::Type*
get(llvm::LLVMContext& C) {
return LLVMTypeT::get(C);
}
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T1& value) {
return LLVMTypeT::get(C, reinterpret_cast<const T2&>(value));
}
static inline llvm::Constant*
get(llvm::LLVMContext& C, const T1* const value) {
return LLVMTypeT::get(C, reinterpret_cast<const T2* const>(value));
}
};
/// @brief Supported aliasing for VDB math types, allowing use in external
/// function signatures.
template <typename T> struct LLVMType<math::Vec2<T>> : public AliasTypeMap<math::Vec2<T>, T[2]> {};
template <typename T> struct LLVMType<math::Vec3<T>> : public AliasTypeMap<math::Vec3<T>, T[3]> {};
template <typename T> struct LLVMType<math::Vec4<T>> : public AliasTypeMap<math::Vec4<T>, T[4]> {};
template <typename T> struct LLVMType<math::Mat3<T>> : public AliasTypeMap<math::Mat3<T>, T[9]> {};
template <typename T> struct LLVMType<math::Mat4<T>> : public AliasTypeMap<math::Mat4<T>, T[16]> {};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// @brief Templated function traits which provides compile-time index access to
/// the types of the function signature
///
template<typename SignatureT>
struct FunctionTraits;
template<typename R, typename... Args>
struct FunctionTraits<R(&)(Args...)> : public FunctionTraits<R(Args...)> {};
template<typename R, typename... Args>
struct FunctionTraits<R(*)(Args...)> : public FunctionTraits<R(Args...)> {};
template<typename ReturnT, typename ...Args>
struct FunctionTraits<ReturnT(Args...)>
{
using ReturnType = ReturnT;
using SignatureType = ReturnType(Args...);
static const size_t N_ARGS = sizeof...(Args);
template <size_t I>
struct Arg
{
public:
static_assert(I < N_ARGS,
"Invalid index specified for function argument access");
using Type = typename std::tuple_element<I, std::tuple<Args...>>::type;
static_assert(!std::is_reference<Type>::value,
"Reference types/arguments are not supported for automatic "
"LLVM Type conversion. Use pointers instead.");
};
};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// @brief Returns an llvm Constant holding a scalar value
/// @param t The scalar constant
/// @param type The LLVM type. Can differ from the type of t, in which
/// case the value will be cast to the llvm type
///
template <typename T>
inline llvm::Constant*
llvmConstant(const T t, llvm::Type* type)
{
static_assert(std::is_floating_point<T>::value || std::is_integral<T>::value,
"T type for llvmConstant must be a floating point or integral type.");
if (type->isIntegerTy()) {
return llvm::ConstantInt::get(type, static_cast<uint64_t>(t), /*signed*/true);
}
else {
assert(type->isFloatingPointTy());
return llvm::ConstantFP::get(type, static_cast<double>(t));
}
}
/// @brief Returns an llvm IntegerType given a requested size and context
/// @param size The number of bits of the integer type
/// @param C The LLVMContext to request the Type from.
///
llvm::IntegerType* llvmIntType(const uint32_t size, llvm::LLVMContext& C);
/// @brief Returns an llvm floating point Type given a requested size and context
/// @param size The size of the float to request, i.e. float - 32, double - 64 etc.
/// @param C The LLVMContext to request the Type from.
///
llvm::Type* llvmFloatType(const uint32_t size, llvm::LLVMContext& C);
/// @brief Returns an llvm type representing a type defined by a string.
/// @note For string types, this function returns the element type, not the
/// object type! The llvm type representing a char block of memory
/// is LLVMType<char*>::get(C);
/// @param type The AX token type
/// @param C The LLVMContext to request the Type from.
///
llvm::Type* llvmTypeFromToken(const ast::tokens::CoreType& type, llvm::LLVMContext& C);
/// @brief Return a corresponding AX token which represents the given LLVM Type.
/// @note If the type does not exist in AX, ast::tokens::UNKNOWN is returned.
/// Must not be a nullptr.
/// @param type a valid LLVM Type
///
ast::tokens::CoreType tokenFromLLVMType(const llvm::Type* type);
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED
| 14,001 | C | 37.25683 | 106 | 0.63674 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ComputeGenerator.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/ComputeGenerator.h
///
/// @authors Nick Avramoussis, Matt Warner, Francisco Gochez, Richard Jones
///
/// @brief The core visitor framework for code generation
///
#ifndef OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
#include "FunctionRegistry.h"
#include "FunctionTypes.h"
#include "SymbolTable.h"
#include "../ast/AST.h"
#include "../ast/Visitor.h"
#include "../compiler/CompilerOptions.h"
#include "../compiler/Logger.h"
#include <openvdb/version.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <stack>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief The function definition and signature which is built by the
/// ComputeGenerator.
///
/// The argument structure is as follows:
///
/// 1) - A void pointer to the CustomData
///
struct ComputeKernel
{
/// The name of the generated function
static const std::string Name;
/// The signature of the generated function
using Signature = void(const void* const);
using FunctionTraitsT = codegen::FunctionTraits<Signature>;
static const size_t N_ARGS = FunctionTraitsT::N_ARGS;
/// The argument key names available during code generation
static const std::array<std::string, N_ARGS>& getArgumentKeys();
static std::string getDefaultName();
};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
/// @brief Visitor object which will generate llvm IR for a syntax tree.
/// This provides the majority of the code generation functionality but is incomplete
/// and should be inherited from and extended with ast::Attribute handling (see
/// PointComputeGenerator.h/VolumeComputeGenerator.h for examples).
/// @note: The visit/traverse methods work slightly differently to the normal Visitor
/// to allow proper handling of errors and visitation history. Nodes that inherit from
/// ast::Expression can return false from visit() (and so traverse()), but this will not
/// necessarily stop traversal altogether. Instead, any ast::Statements that are not also
/// ast::Expressions i.e. Block, ConditionalStatement, Loop, DeclareLocal override their
/// visit/traverse methods to handle custom traversal order, and the catching of failed child
/// Expression visit/traverse calls. This allows errors in independent Statements to not halt
/// traversal for future Statements and so allow capturing of multiple errors in an ast::Tree
/// in a single call to generate().
///
struct ComputeGenerator : public ast::Visitor<ComputeGenerator>
{
ComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger);
virtual ~ComputeGenerator() = default;
bool generate(const ast::Tree&);
inline SymbolTable& globals() { return mSymbolTables.globals(); }
inline const SymbolTable& globals() const { return mSymbolTables.globals(); }
// Visitor pattern
using ast::Visitor<ComputeGenerator>::traverse;
using ast::Visitor<ComputeGenerator>::visit;
/// @brief Code generation always runs post order
inline bool postOrderNodes() const { return true; }
/// @brief Custom traversal of scoped blocks
/// @note This overrides the default traversal to incorporate
/// the scoping of variables declared in this block
bool traverse(const ast::Block* block)
{
if (!block) return true;
if (!this->visit(block)) return false;
return true;
}
/// @brief Custom traversal of comma expression
/// @note This overrides the default traversal to handle errors
/// without stopping generation of entire list
/// @todo Replace with a binary operator that simply returns the second value
bool traverse(const ast::CommaOperator* comma)
{
if (!comma) return true;
if (!this->visit(comma)) return false;
return true;
}
/// @brief Custom traversal of conditional statements
/// @note This overrides the default traversal to handle
/// branching between different code paths
bool traverse(const ast::ConditionalStatement* cond)
{
if (!cond) return true;
if (!this->visit(cond)) return false;
return true;
}
/// @brief Custom traversal of binary operators
/// @note This overrides the default traversal to handle
/// short-circuiting in logical AND and OR
bool traverse(const ast::BinaryOperator* bin)
{
if (!bin) return true;
if (!this->visit(bin)) return false;
return true;
}
/// @brief Custom traversal of ternary operators
/// @note This overrides the default traversal to handle
/// branching between different code paths
bool traverse(const ast::TernaryOperator* tern)
{
if (!tern) return true;
if (!this->visit(tern)) return false;
return true;
}
/// @brief Custom traversal of loops
/// @note This overrides the default traversal to handle
/// branching between different code paths and the
/// scoping of variables in for-loop initialisation
bool traverse(const ast::Loop* loop)
{
if (!loop) return true;
if (!this->visit(loop)) return false;
return true;
}
/// @brief Custom traversal of declarations
/// @note This overrides the default traversal to
/// handle traversal of the local and
/// assignment of initialiser, if it exists
bool traverse(const ast::DeclareLocal* decl)
{
if (!decl) return true;
if (!this->visit(decl)) return false;
return true;
}
virtual bool visit(const ast::CommaOperator*);
virtual bool visit(const ast::AssignExpression*);
virtual bool visit(const ast::Crement*);
virtual bool visit(const ast::FunctionCall*);
virtual bool visit(const ast::Attribute*);
virtual bool visit(const ast::Tree*);
virtual bool visit(const ast::Block*);
virtual bool visit(const ast::ConditionalStatement*);
virtual bool visit(const ast::Loop*);
virtual bool visit(const ast::Keyword*);
virtual bool visit(const ast::UnaryOperator*);
virtual bool visit(const ast::BinaryOperator*);
virtual bool visit(const ast::TernaryOperator*);
virtual bool visit(const ast::Cast*);
virtual bool visit(const ast::DeclareLocal*);
virtual bool visit(const ast::Local*);
virtual bool visit(const ast::ExternalVariable*);
virtual bool visit(const ast::ArrayUnpack*);
virtual bool visit(const ast::ArrayPack*);
virtual bool visit(const ast::Value<bool>*);
virtual bool visit(const ast::Value<int16_t>*);
virtual bool visit(const ast::Value<int32_t>*);
virtual bool visit(const ast::Value<int64_t>*);
virtual bool visit(const ast::Value<float>*);
virtual bool visit(const ast::Value<double>*);
virtual bool visit(const ast::Value<std::string>*);
template <typename ValueType>
typename std::enable_if<std::is_integral<ValueType>::value, bool>::type
visit(const ast::Value<ValueType>* node);
template <typename ValueType>
typename std::enable_if<std::is_floating_point<ValueType>::value, bool>::type
visit(const ast::Value<ValueType>* node);
protected:
const FunctionGroup* getFunction(const std::string& identifier,
const bool allowInternal = false);
bool binaryExpression(llvm::Value*& result, llvm::Value* lhs, llvm::Value* rhs,
const ast::tokens::OperatorToken op, const ast::Node* node);
bool assignExpression(llvm::Value* lhs, llvm::Value*& rhs, const ast::Node* node);
llvm::Module& mModule;
llvm::LLVMContext& mContext;
llvm::IRBuilder<> mBuilder;
// The stack of accessed values
std::stack<llvm::Value*> mValues;
// The stack of blocks for keyword branching
std::stack<std::pair<llvm::BasicBlock*, llvm::BasicBlock*>> mBreakContinueStack;
// The current scope number used to track scoped declarations
size_t mScopeIndex;
// The map of scope number to local variable names to values
SymbolTableBlocks mSymbolTables;
// The function used as the base code block
llvm::Function* mFunction;
const FunctionOptions mOptions;
Logger& mLog;
private:
FunctionRegistry& mFunctionRegistry;
};
} // codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
| 9,038 | C | 33.899614 | 93 | 0.674264 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointLeafLocalData.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/PointLeafLocalData.h
///
/// @authors Nick Avramoussis
///
/// @brief Thread/Leaf local data used during execution over OpenVDB Points
///
#ifndef OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include <openvdb/version.h>
#include <openvdb/points/AttributeArray.h>
#include <openvdb/points/PointAttribute.h>
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/points/PointGroup.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace codegen_internal {
/// @brief Various functions can request the use and initialization of point data from within
/// the kernel that does not use the standard attribute handle methods. This data can
/// then be accessed after execution to perform post-processes such as adding new groups,
/// adding new string attributes or updating positions.
///
/// @note Due to the way string handles work, string write attribute handles cannot
/// be constructed in parallel, nor can read handles retrieve values in parallel
/// if there is a chance the shared metadata is being written to (with set()).
/// As the compiler allows for any arbitrary string setting/getting, leaf local
/// maps are used for temporary storage per point. The maps use the string array
/// pointers as a key for later synchronization.
///
struct PointLeafLocalData
{
using UniquePtr = std::unique_ptr<PointLeafLocalData>;
using GroupArrayT = openvdb::points::GroupAttributeArray;
using GroupHandleT = openvdb::points::GroupWriteHandle;
using PointStringMap = std::map<uint64_t, std::string>;
using StringArrayMap = std::map<points::AttributeArray*, PointStringMap>;
using LeafNode = openvdb::points::PointDataTree::LeafNodeType;
/// @brief Construct a new data object to keep track of various data objects
/// created per leaf by the point compute generator.
///
/// @param count The number of points within the current leaf, used to initialize
/// the size of new arrays
///
PointLeafLocalData(const size_t count)
: mPointCount(count)
, mArrays()
, mOffset(0)
, mHandles()
, mStringMap() {}
////////////////////////////////////////////////////////////////////////
/// Group methods
/// @brief Return a group write handle to a specific group name, creating the
/// group array if it doesn't exist. This includes either registering a
/// new offset or allocating an entire array. The returned handle is
/// guaranteed to be valid.
///
/// @param name The group name
///
inline GroupHandleT* getOrInsert(const std::string& name)
{
GroupHandleT* ptr = get(name);
if (ptr) return ptr;
static const size_t maxGroupsInArray =
#if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER > 7 || \
(OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER >= 7 && \
OPENVDB_LIBRARY_MINOR_VERSION_NUMBER >= 1))
points::AttributeSet::Descriptor::groupBits();
#else
// old removed method
points::point_group_internal::GroupInfo::groupBits();
#endif
if (mArrays.empty() || mOffset == maxGroupsInArray) {
assert(mPointCount < static_cast<size_t>(std::numeric_limits<openvdb::Index>::max()));
mArrays.emplace_back(new GroupArrayT(static_cast<openvdb::Index>(mPointCount)));
mOffset = 0;
}
GroupArrayT* array = mArrays.back().get();
assert(array);
std::unique_ptr<GroupHandleT>& handle = mHandles[name];
handle.reset(new GroupHandleT(*array, mOffset++));
return handle.get();
}
/// @brief Return a group write handle to a specific group name if it exists.
/// Returns a nullptr if no group exists of the given name
///
/// @param name The group name
///
inline GroupHandleT* get(const std::string& name) const
{
const auto iter = mHandles.find(name);
if (iter == mHandles.end()) return nullptr;
return iter->second.get();
}
/// @brief Return true if a valid group handle exists
///
/// @param name The group name
///
inline bool hasGroup(const std::string& name) const {
return mHandles.find(name) != mHandles.end();
}
/// @brief Populate a set with all the groups which have been inserted into
/// this object. Used to compute a final set of all new groups which
/// have been created across all leaf nodes
///
/// @param groups The set to populate
///
inline void getGroups(std::set<std::string>& groups) const {
for (const auto& iter : mHandles) {
groups.insert(iter.first);
}
}
/// @brief Compact all arrays stored on this object. This does not invalidate
/// any active write handles.
///
inline void compact() {
for (auto& array : mArrays) array->compact();
}
////////////////////////////////////////////////////////////////////////
/// String methods
/// @brief Get any new string data associated with a particular point on a
/// particular string attribute array. Returns true if data was set,
/// false if no data was found.
///
/// @param array The array pointer to use as a key lookup
/// @param idx The point index
/// @param data The string to set if data is stored
///
inline bool
getNewStringData(const points::AttributeArray* array, const uint64_t idx, std::string& data) const {
const auto arrayMapIter = mStringMap.find(const_cast<points::AttributeArray*>(array));
if (arrayMapIter == mStringMap.end()) return false;
const auto iter = arrayMapIter->second.find(idx);
if (iter == arrayMapIter->second.end()) return false;
data = iter->second;
return true;
}
/// @brief Set new string data associated with a particular point on a
/// particular string attribute array.
///
/// @param array The array pointer to use as a key lookup
/// @param idx The point index
/// @param data The string to set
///
inline void
setNewStringData(points::AttributeArray* array, const uint64_t idx, const std::string& data) {
mStringMap[array][idx] = data;
}
/// @brief Remove any new string data associated with a particular point on a
/// particular string attribute array. Does nothing if no data exists
///
/// @param array The array pointer to use as a key lookup
/// @param idx The point index
///
inline void
removeNewStringData(points::AttributeArray* array, const uint64_t idx) {
const auto arrayMapIter = mStringMap.find(array);
if (arrayMapIter == mStringMap.end()) return;
arrayMapIter->second.erase(idx);
if (arrayMapIter->second.empty()) mStringMap.erase(arrayMapIter);
}
/// @brief Insert all new point strings stored across all collected string
/// attribute arrays into a StringMetaInserter. Returns false if the
/// inserter was not accessed and true if it was potentially modified.
///
/// @param inserter The string meta inserter to update
///
inline bool
insertNewStrings(points::StringMetaInserter& inserter) const {
for (const auto& arrayIter : mStringMap) {
for (const auto& iter : arrayIter.second) {
inserter.insert(iter.second);
}
}
return !mStringMap.empty();
}
/// @brief Returns a const reference to the string array map
///
inline const StringArrayMap& getStringArrayMap() const {
return mStringMap;
}
private:
const size_t mPointCount;
std::vector<std::unique_ptr<GroupArrayT>> mArrays;
points::GroupType mOffset;
std::map<std::string, std::unique_ptr<GroupHandleT>> mHandles;
StringArrayMap mStringMap;
};
} // codegen_internal
} // namespace compiler
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED
| 8,466 | C | 35.029787 | 104 | 0.634774 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointFunctions.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/PointFunctions.cc
///
/// @authors Nick Avramoussis, Richard Jones
///
/// @brief Contains the function objects that define the functions used in
/// point compute function generation, to be inserted into the
/// FunctionRegistry. These define the functions available when operating
/// on points. Also includes the definitions for the point attribute
/// retrieval and setting.
///
#include "Functions.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "PointLeafLocalData.h"
#include "../ast/Tokens.h"
#include "../compiler/CompilerOptions.h"
#include "../Exceptions.h"
#include <openvdb/openvdb.h>
#include <openvdb/points/PointDataGrid.h>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace
{
/// @todo Provide more framework for functions such that they can only
/// be registered against compatible code generators.
inline void verifyContext(const llvm::Function* const F, const std::string& name)
{
if (!F || F->getName() != "ax.compute.point") {
OPENVDB_THROW(AXCompilerError, "Function \"" << name << "\" cannot be called for "
"the current target. This function only runs on OpenVDB Point Grids.");
}
}
/// @brief Retrieve a group handle from an expected vector of handles using the offset
/// pointed to by the engine data. Note that HandleT should only ever be a GroupHandle
/// or GroupWriteHandle object
template <typename HandleT>
inline HandleT*
groupHandle(const std::string& name, void** groupHandles, const void* const data)
{
const openvdb::points::AttributeSet* const attributeSet =
static_cast<const openvdb::points::AttributeSet*>(data);
const size_t groupIdx = attributeSet->groupOffset(name);
if (groupIdx == openvdb::points::AttributeSet::INVALID_POS) return nullptr;
return static_cast<HandleT*>(groupHandles[groupIdx]);
}
}
inline FunctionGroup::UniquePtr ax_ingroup(const FunctionOptions& op)
{
static auto ingroup =
[](const AXString* const name,
const uint64_t index,
void** groupHandles,
const void* const leafDataPtr,
const void* const data) -> bool
{
assert(name);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
if (name->size == 0) return false;
if (!groupHandles) return false;
const std::string nameStr(name->ptr, name->size);
const openvdb::points::GroupHandle* handle =
groupHandle<openvdb::points::GroupHandle>(nameStr, groupHandles, data);
if (handle) return handle->get(static_cast<openvdb::Index>(index));
// If the handle doesn't exist, check to see if any new groups have
// been added
const codegen_internal::PointLeafLocalData* const leafData =
static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr);
handle = leafData->get(nameStr);
return handle ? handle->get(static_cast<openvdb::Index>(index)) : false;
};
using InGroup = bool(const AXString* const,
const uint64_t,
void**,
const void* const,
const void* const);
return FunctionBuilder("_ingroup")
.addSignature<InGroup>(ingroup)
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::NoAlias)
.addParameterAttribute(3, llvm::Attribute::ReadOnly)
.addParameterAttribute(3, llvm::Attribute::NoAlias)
.addParameterAttribute(4, llvm::Attribute::ReadOnly)
.addParameterAttribute(4, llvm::Attribute::NoAlias)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
// @note handle->get can throw, so no unwind. Maybe use getUnsafe?
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for querying point group data")
.get();
}
inline FunctionGroup::UniquePtr axingroup(const FunctionOptions& op)
{
static auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out parent function arguments
llvm::Function* compute = B.GetInsertBlock()->getParent();
verifyContext(compute, "ingroup");
llvm::Value* point_index = extractArgument(compute, "point_index");
llvm::Value* group_handles = extractArgument(compute, "group_handles");
llvm::Value* leaf_data = extractArgument(compute, "leaf_data");
llvm::Value* attribute_set = extractArgument(compute, "attribute_set");
assert(point_index);
assert(group_handles);
assert(leaf_data);
assert(attribute_set);
std::vector<llvm::Value*> input(args);
input.emplace_back(point_index);
input.emplace_back(group_handles);
input.emplace_back(leaf_data);
input.emplace_back(attribute_set);
return ax_ingroup(op)->execute(input, B);
};
return FunctionBuilder("ingroup")
.addSignature<bool(const AXString* const)>(generate)
.addDependency("_ingroup")
.setEmbedIR(true)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation( "Return whether or not the current point is "
"a member of the given group name. This returns false if the group does "
"not exist.")
.get();
}
inline FunctionGroup::UniquePtr axeditgroup(const FunctionOptions& op)
{
static auto editgroup =
[](const AXString* const name,
const uint64_t index,
void** groupHandles,
void* const leafDataPtr,
const void* const data,
const bool flag)
{
assert(name);
if (name->size == 0) return;
// Get the group handle out of the pre-existing container of handles if they
// exist
const std::string nameStr(name->ptr, name->size);
openvdb::points::GroupWriteHandle* handle = nullptr;
if (groupHandles) {
handle = groupHandle<openvdb::points::GroupWriteHandle>(nameStr, groupHandles, data);
}
if (!handle) {
codegen_internal::PointLeafLocalData* const leafData =
static_cast<codegen_internal::PointLeafLocalData*>(leafDataPtr);
// If we are setting membership and the handle doesnt exist, create in in
// the set of new data thats being added
if (!flag && !leafData->hasGroup(nameStr)) return;
handle = leafData->getOrInsert(nameStr);
assert(handle);
}
// set the group membership
handle->set(static_cast<openvdb::Index>(index), flag);
};
using EditGroup = void(const AXString* const,
const uint64_t,
void**,
void* const,
const void* const,
const bool);
return FunctionBuilder("editgroup")
.addSignature<EditGroup>(editgroup)
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addParameterAttribute(3, llvm::Attribute::ReadOnly)
.addParameterAttribute(4, llvm::Attribute::ReadOnly)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for setting point group data")
.get();
}
inline FunctionGroup::UniquePtr axaddtogroup(const FunctionOptions& op)
{
static auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out parent function arguments
llvm::Function* compute = B.GetInsertBlock()->getParent();
verifyContext(compute, "addtogroup");
llvm::Value* point_index = extractArgument(compute, "point_index");
llvm::Value* group_handles = extractArgument(compute, "group_handles");
llvm::Value* leaf_data = extractArgument(compute, "leaf_data");
llvm::Value* attribute_set = extractArgument(compute, "attribute_set");
assert(point_index);
assert(group_handles);
assert(leaf_data);
assert(attribute_set);
std::vector<llvm::Value*> input(args);
input.emplace_back(point_index);
input.emplace_back(group_handles);
input.emplace_back(leaf_data);
input.emplace_back(attribute_set);
input.emplace_back(llvm::ConstantInt::get(LLVMType<bool>::get(B.getContext()), true));
return axeditgroup(op)->execute(input, B);
};
return FunctionBuilder("addtogroup")
.addSignature<void(const AXString* const)>(generate)
.addDependency("editgroup")
.setEmbedIR(true)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Add the current point to the given group "
"name, effectively setting its membership to true. If the group does not "
"exist, it is implicitly created. This function has no effect if the point "
"already belongs to the given group.")
.get();
}
inline FunctionGroup::UniquePtr axremovefromgroup(const FunctionOptions& op)
{
static auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out parent function arguments
llvm::Function* compute = B.GetInsertBlock()->getParent();
verifyContext(compute, "removefromgroup");
llvm::Value* point_index = extractArgument(compute, "point_index");
llvm::Value* group_handles = extractArgument(compute, "group_handles");
llvm::Value* leaf_data = extractArgument(compute, "leaf_data");
llvm::Value* attribute_set = extractArgument(compute, "attribute_set");
assert(point_index);
assert(group_handles);
assert(leaf_data);
assert(attribute_set);
std::vector<llvm::Value*> input(args);
input.emplace_back(point_index);
input.emplace_back(group_handles);
input.emplace_back(leaf_data);
input.emplace_back(attribute_set);
input.emplace_back(llvm::ConstantInt::get(LLVMType<bool>::get(B.getContext()), false));
return axeditgroup(op)->execute(input, B);
};
return FunctionBuilder("removefromgroup")
.addSignature<void(const AXString* const)>(generate)
.addDependency("editgroup")
.setEmbedIR(true)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Remove the current point from the "
"given group name, effectively setting its membership to false. This "
"function has no effect if the group does not exist.")
.get();
}
inline FunctionGroup::UniquePtr axdeletepoint(const FunctionOptions& op)
{
static auto generate =
[op](const std::vector<llvm::Value*>&,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// args guaranteed to be empty
llvm::Constant* loc = llvm::cast<llvm::Constant>(B.CreateGlobalStringPtr("dead")); // char*
llvm::Constant* size = LLVMType<AXString::SizeType>::get(B.getContext(), 4);
llvm::Value* str = LLVMType<AXString>::get(B.getContext(), loc, size);
// Always allocate an AXString here for easier passing to functions
// @todo shouldn't need an AXString for char* literals
llvm::Value* alloc =
B.CreateAlloca(LLVMType<AXString>::get(B.getContext()));
B.CreateStore(str, alloc);
return axaddtogroup(op)->execute({alloc}, B);
};
return FunctionBuilder("deletepoint")
.addSignature<void()>(generate)
.addDependency("addtogroup")
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setEmbedIR(true) // axaddtogroup needs access to parent function arguments
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Delete the current point from the point set. Note that this does not "
"stop AX execution - any additional AX commands will be executed on the "
"point and it will remain accessible until the end of execution.")
.get();
}
inline FunctionGroup::UniquePtr axsetattribute(const FunctionOptions& op)
{
static auto setattribptr =
[](void* attributeHandle, uint64_t index, const auto value)
{
using ValueType = typename std::remove_const
<typename std::remove_pointer
<decltype(value)>::type>::type;
using AttributeHandleType = openvdb::points::AttributeWriteHandle<ValueType>;
assert(attributeHandle);
assert(value);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
AttributeHandleType* handle = static_cast<AttributeHandleType*>(attributeHandle);
handle->set(static_cast<openvdb::Index>(index), *value);
};
static auto setattribstr =
[](void* attributeHandle,
const uint64_t index,
const AXString* value,
void* const leafDataPtr)
{
using AttributeHandleType = openvdb::points::StringAttributeWriteHandle;
assert(attributeHandle);
assert(value);
assert(leafDataPtr);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
const std::string s(value->ptr, value->size);
AttributeHandleType* const handle =
static_cast<AttributeHandleType*>(attributeHandle);
codegen_internal::PointLeafLocalData* const leafData =
static_cast<codegen_internal::PointLeafLocalData*>(leafDataPtr);
// Check to see if the string exists in the metadata cache. If so, set the string and
// remove any new data associated with it, otherwise set the new data
if (handle->contains(s)) {
handle->set(static_cast<openvdb::Index>(index), s);
leafData->removeNewStringData(&(handle->array()), index);
}
else {
leafData->setNewStringData(&(handle->array()), index, s);
}
};
static auto setattrib =
[](void* attributeHandle,
uint64_t index,
const auto value) {
setattribptr(attributeHandle, index, &value);
};
using SetAttribD = void(void*, uint64_t, const double);
using SetAttribF = void(void*, uint64_t, const float);
using SetAttribI64 = void(void*, uint64_t, const int64_t);
using SetAttribI32 = void(void*, uint64_t, const int32_t);
using SetAttribI16 = void(void*, uint64_t, const int16_t);
using SetAttribB = void(void*, uint64_t, const bool);
using SetAttribV2D = void(void*, uint64_t, const openvdb::math::Vec2<double>*);
using SetAttribV2F = void(void*, uint64_t, const openvdb::math::Vec2<float>*);
using SetAttribV2I = void(void*, uint64_t, const openvdb::math::Vec2<int32_t>*);
using SetAttribV3D = void(void*, uint64_t, const openvdb::math::Vec3<double>*);
using SetAttribV3F = void(void*, uint64_t, const openvdb::math::Vec3<float>*);
using SetAttribV3I = void(void*, uint64_t, const openvdb::math::Vec3<int32_t>*);
using SetAttribV4D = void(void*, uint64_t, const openvdb::math::Vec4<double>*);
using SetAttribV4F = void(void*, uint64_t, const openvdb::math::Vec4<float>*);
using SetAttribV4I = void(void*, uint64_t, const openvdb::math::Vec4<int32_t>*);
using SetAttribM3D = void(void*, uint64_t, const openvdb::math::Mat3<double>*);
using SetAttribM3F = void(void*, uint64_t, const openvdb::math::Mat3<float>*);
using SetAttribM4D = void(void*, uint64_t, const openvdb::math::Mat4<double>*);
using SetAttribM4F = void(void*, uint64_t, const openvdb::math::Mat4<float>*);
using SetAttribStr = void(void*, uint64_t, const AXString*, void* const);
return FunctionBuilder("setattribute")
.addSignature<SetAttribD>((SetAttribD*)(setattrib))
.addSignature<SetAttribF>((SetAttribF*)(setattrib))
.addSignature<SetAttribI64>((SetAttribI64*)(setattrib))
.addSignature<SetAttribI32>((SetAttribI32*)(setattrib))
.addSignature<SetAttribI16>((SetAttribI16*)(setattrib))
.addSignature<SetAttribB>((SetAttribB*)(setattrib))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.addSignature<SetAttribV2D>((SetAttribV2D*)(setattribptr))
.addSignature<SetAttribV2F>((SetAttribV2F*)(setattribptr))
.addSignature<SetAttribV2I>((SetAttribV2I*)(setattribptr))
.addSignature<SetAttribV3D>((SetAttribV3D*)(setattribptr))
.addSignature<SetAttribV3F>((SetAttribV3F*)(setattribptr))
.addSignature<SetAttribV3I>((SetAttribV3I*)(setattribptr))
.addSignature<SetAttribV4D>((SetAttribV4D*)(setattribptr))
.addSignature<SetAttribV4F>((SetAttribV4F*)(setattribptr))
.addSignature<SetAttribV4I>((SetAttribV4I*)(setattribptr))
.addSignature<SetAttribM3D>((SetAttribM3D*)(setattribptr))
.addSignature<SetAttribM3F>((SetAttribM3F*)(setattribptr))
.addSignature<SetAttribM4D>((SetAttribM4D*)(setattribptr))
.addSignature<SetAttribM4F>((SetAttribM4F*)(setattribptr))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.addSignature<SetAttribStr>((SetAttribStr*)(setattribstr))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addParameterAttribute(3, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for setting the value of a point attribute.")
.get();
}
inline FunctionGroup::UniquePtr axgetattribute(const FunctionOptions& op)
{
static auto getattrib =
[](void* attributeHandle, uint64_t index, auto value)
{
using ValueType = typename std::remove_const
<typename std::remove_pointer
<decltype(value)>::type>::type;
// typedef is a read handle. As write handles are derived types this
// is okay and lets us define the handle types outside IR for attributes that are
// only being read!
using AttributeHandleType = openvdb::points::AttributeHandle<ValueType>;
assert(value);
assert(attributeHandle);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
AttributeHandleType* handle = static_cast<AttributeHandleType*>(attributeHandle);
(*value) = handle->get(static_cast<openvdb::Index>(index));
};
static auto getattribstr =
[](void* attributeHandle,
uint64_t index,
AXString* value,
const void* const leafDataPtr)
{
using AttributeHandleType = openvdb::points::StringAttributeHandle;
assert(value);
assert(attributeHandle);
assert(leafDataPtr);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
AttributeHandleType* const handle =
static_cast<AttributeHandleType*>(attributeHandle);
const codegen_internal::PointLeafLocalData* const leafData =
static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr);
std::string data;
if (!leafData->getNewStringData(&(handle->array()), index, data)) {
handle->get(data, static_cast<openvdb::Index>(index));
}
assert(value->size == static_cast<AXString::SizeType>(data.size()));
strcpy(const_cast<char*>(value->ptr), data.c_str());
};
using GetAttribD = void(void*, uint64_t, double*);
using GetAttribF = void(void*, uint64_t, float*);
using GetAttribI64 = void(void*, uint64_t, int64_t*);
using GetAttribI32 = void(void*, uint64_t, int32_t*);
using GetAttribI16 = void(void*, uint64_t, int16_t*);
using GetAttribB = void(void*, uint64_t, bool*);
using GetAttribV2D = void(void*, uint64_t, openvdb::math::Vec2<double>*);
using GetAttribV2F = void(void*, uint64_t, openvdb::math::Vec2<float>*);
using GetAttribV2I = void(void*, uint64_t, openvdb::math::Vec2<int32_t>*);
using GetAttribV3D = void(void*, uint64_t, openvdb::math::Vec3<double>*);
using GetAttribV3F = void(void*, uint64_t, openvdb::math::Vec3<float>*);
using GetAttribV3I = void(void*, uint64_t, openvdb::math::Vec3<int32_t>*);
using GetAttribV4D = void(void*, uint64_t, openvdb::math::Vec4<double>*);
using GetAttribV4F = void(void*, uint64_t, openvdb::math::Vec4<float>*);
using GetAttribV4I = void(void*, uint64_t, openvdb::math::Vec4<int32_t>*);
using GetAttribM3D = void(void*, uint64_t, openvdb::math::Mat3<double>*);
using GetAttribM3F = void(void*, uint64_t, openvdb::math::Mat3<float>*);
using GetAttribM4D = void(void*, uint64_t, openvdb::math::Mat4<double>*);
using GetAttribM4F = void(void*, uint64_t, openvdb::math::Mat4<float>*);
using GetAttribStr = void(void*, uint64_t, AXString*, const void* const);
return FunctionBuilder("getattribute")
.addSignature<GetAttribD>((GetAttribD*)(getattrib))
.addSignature<GetAttribF>((GetAttribF*)(getattrib))
.addSignature<GetAttribI64>((GetAttribI64*)(getattrib))
.addSignature<GetAttribI32>((GetAttribI32*)(getattrib))
.addSignature<GetAttribI16>((GetAttribI16*)(getattrib))
.addSignature<GetAttribB>((GetAttribB*)(getattrib))
.addSignature<GetAttribV2D>((GetAttribV2D*)(getattrib))
.addSignature<GetAttribV2F>((GetAttribV2F*)(getattrib))
.addSignature<GetAttribV2I>((GetAttribV2I*)(getattrib))
.addSignature<GetAttribV3D>((GetAttribV3D*)(getattrib))
.addSignature<GetAttribV3F>((GetAttribV3F*)(getattrib))
.addSignature<GetAttribV3I>((GetAttribV3I*)(getattrib))
.addSignature<GetAttribV4D>((GetAttribV4D*)(getattrib))
.addSignature<GetAttribV4F>((GetAttribV4F*)(getattrib))
.addSignature<GetAttribV4I>((GetAttribV4I*)(getattrib))
.addSignature<GetAttribM3D>((GetAttribM3D*)(getattrib))
.addSignature<GetAttribM3F>((GetAttribM3F*)(getattrib))
.addSignature<GetAttribM4D>((GetAttribM4D*)(getattrib))
.addSignature<GetAttribM4F>((GetAttribM4F*)(getattrib))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.addSignature<GetAttribStr>((GetAttribStr*)(getattribstr))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(3, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for getting the value of a point attribute.")
.get();
}
inline FunctionGroup::UniquePtr axstrattribsize(const FunctionOptions& op)
{
static auto strattribsize =
[](void* attributeHandle,
uint64_t index,
const void* const leafDataPtr) -> AXString::SizeType
{
using AttributeHandleType = openvdb::points::StringAttributeHandle;
assert(attributeHandle);
assert(leafDataPtr);
assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max()));
const AttributeHandleType* const handle =
static_cast<AttributeHandleType*>(attributeHandle);
const codegen_internal::PointLeafLocalData* const leafData =
static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr);
std::string data;
if (!leafData->getNewStringData(&(handle->array()), index, data)) {
handle->get(data, static_cast<openvdb::Index>(index));
}
return static_cast<AXString::SizeType>(data.size());
};
using StrAttribSize = AXString::SizeType(void*, uint64_t, const void* const);
return FunctionBuilder("strattribsize")
.addSignature<StrAttribSize>((StrAttribSize*)(strattribsize))
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for querying the size of a points string attribute")
.get();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
void insertVDBPointFunctions(FunctionRegistry& registry,
const FunctionOptions* options)
{
const bool create = options && !options->mLazyFunctions;
auto add = [&](const std::string& name,
const FunctionRegistry::ConstructorT creator,
const bool internal = false)
{
if (create) registry.insertAndCreate(name, creator, *options, internal);
else registry.insert(name, creator, internal);
};
// point functions
add("addtogroup", axaddtogroup);
add("ingroup", axingroup);
add("removefromgroup",axremovefromgroup);
add("deletepoint", axdeletepoint);
add("_ingroup", ax_ingroup, true);
add("editgroup", axeditgroup, true);
add("getattribute", axgetattribute, true);
add("setattribute", axsetattribute, true);
add("strattribsize", axstrattribsize, true);
}
} // namespace codegen
} // namespace ax
} // namespace openvdb_version
} // namespace openvdb
| 26,426 | C++ | 42.181372 | 99 | 0.654961 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeComputeGenerator.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/VolumeComputeGenerator.cc
#include "VolumeComputeGenerator.h"
#include "FunctionRegistry.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../Exceptions.h"
#include "../ast/Scanners.h"
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
const std::array<std::string, VolumeKernel::N_ARGS>&
VolumeKernel::argumentKeys()
{
static const std::array<std::string, VolumeKernel::N_ARGS> arguments = {{
"custom_data",
"coord_is",
"coord_ws",
"accessors",
"transforms",
"write_index",
"write_acccessor"
}};
return arguments;
}
std::string VolumeKernel::getDefaultName() { return "ax.compute.voxel"; }
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
VolumeComputeGenerator::VolumeComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger)
: ComputeGenerator(module, options, functionRegistry, logger) {}
AttributeRegistry::Ptr VolumeComputeGenerator::generate(const ast::Tree& tree)
{
llvm::FunctionType* type =
llvmFunctionTypeFromSignature<VolumeKernel::Signature>(mContext);
mFunction = llvm::Function::Create(type,
llvm::Function::ExternalLinkage,
VolumeKernel::getDefaultName(),
&mModule);
// Set up arguments for initial entry
llvm::Function::arg_iterator argIter = mFunction->arg_begin();
const auto arguments = VolumeKernel::argumentKeys();
auto keyIter = arguments.cbegin();
for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) {
argIter->setName(*keyIter);
}
llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext,
"entry_" + VolumeKernel::getDefaultName(), mFunction);
mBuilder.SetInsertPoint(entry);
// build the attribute registry
AttributeRegistry::Ptr registry = AttributeRegistry::create(tree);
// Visit all attributes and allocate them in local IR memory - assumes attributes
// have been verified by the ax compiler
// @note Call all attribute allocs at the start of this block so that llvm folds
// them into the function prologue (as a static allocation)
SymbolTable* localTable = this->mSymbolTables.getOrInsert(1);
// run allocations and update the symbol table
for (const AttributeRegistry::AccessData& data : registry->data()) {
llvm::Value* value = mBuilder.CreateAlloca(llvmTypeFromToken(data.type(), mContext));
assert(llvm::cast<llvm::AllocaInst>(value)->isStaticAlloca());
localTable->insert(data.tokenname(), value);
}
// insert getters for read variables
for (const AttributeRegistry::AccessData& data : registry->data()) {
if (!data.reads()) continue;
const std::string token = data.tokenname();
this->getAccessorValue(token, localTable->get(token));
}
// full code generation
// errors can stop traversal, but dont always, so check the log
if (!this->traverse(&tree) || mLog.hasError()) return nullptr;
// insert set code
std::vector<const AttributeRegistry::AccessData*> write;
for (const AttributeRegistry::AccessData& access : registry->data()) {
if (access.writes()) write.emplace_back(&access);
}
if (write.empty()) return registry;
// Cache the basic blocks which have been created as we will create
// new branches below
std::vector<llvm::BasicBlock*> blocks;
for (auto block = mFunction->begin(); block != mFunction->end(); ++block) {
blocks.emplace_back(&*block);
}
// insert set voxel calls
for (auto& block : blocks) {
// Only inset set calls if theres a valid return instruction in this block
llvm::Instruction* inst = block->getTerminator();
if (!inst || !llvm::isa<llvm::ReturnInst>(inst)) continue;
// remove the old return statement (we'll point to the final return jump)
inst->eraseFromParent();
// Set builder to the end of this block
mBuilder.SetInsertPoint(&(*block));
for (const AttributeRegistry::AccessData* access : write) {
const std::string token = access->tokenname();
llvm::Value* value = localTable->get(token);
// Expected to be used more than one (i.e. should never be zero)
assert(value->hasNUsesOrMore(1));
// Check to see if this value is still being used - it may have
// been cleaned up due to returns. If there's only one use, it's
// the original get of this attribute.
if (value->hasOneUse()) {
// @todo The original get can also be optimized out in this case
// this->globals().remove(variable.first);
// mModule.getGlobalVariable(variable.first)->eraseFromParent();
continue;
}
llvm::Value* coordis = extractArgument(mFunction, "coord_is");
llvm::Value* accessIndex = extractArgument(mFunction, "write_index");
llvm::Value* accessor = extractArgument(mFunction, "write_acccessor");
assert(coordis);
assert(accessor);
assert(accessIndex);
llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable>
(mModule.getOrInsertGlobal(token, LLVMType<int64_t>::get(mContext)));
registeredIndex = mBuilder.CreateLoad(registeredIndex);
llvm::Value* result = mBuilder.CreateICmpEQ(accessIndex, registeredIndex);
result = boolComparison(result, mBuilder);
llvm::BasicBlock* thenBlock =
llvm::BasicBlock::Create(mContext, "post_assign " + token, mFunction);
llvm::BasicBlock* continueBlock =
llvm::BasicBlock::Create(mContext, "post_continue", mFunction);
mBuilder.CreateCondBr(result, thenBlock, continueBlock);
mBuilder.SetInsertPoint(thenBlock);
llvm::Type* type = value->getType()->getPointerElementType();
// load the result (if its a scalar)
if (type->isIntegerTy() || type->isFloatingPointTy()) {
value = mBuilder.CreateLoad(value);
}
const FunctionGroup* const function = this->getFunction("setvoxel", true);
function->execute({accessor, coordis, value}, mBuilder);
mBuilder.CreateBr(continueBlock);
mBuilder.SetInsertPoint(continueBlock);
}
mBuilder.CreateRetVoid();
}
return registry;
}
bool VolumeComputeGenerator::visit(const ast::Attribute* node)
{
const std::string globalName = node->tokenname();
SymbolTable* localTable = this->mSymbolTables.getOrInsert(1);
llvm::Value* value = localTable->get(globalName);
assert(value);
mValues.push(value);
return true;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void VolumeComputeGenerator::getAccessorValue(const std::string& globalName, llvm::Value* location)
{
std::string name, type;
ast::Attribute::nametypeFromToken(globalName, &name, &type);
llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable>
(mModule.getOrInsertGlobal(globalName, LLVMType<int64_t>::get(mContext)));
this->globals().insert(globalName, registeredIndex);
registeredIndex = mBuilder.CreateLoad(registeredIndex);
// index into the void* array of handles and load the value.
// The result is a loaded void* value
llvm::Value* accessorPtr = extractArgument(mFunction, "accessors");
llvm::Value* transformPtr = extractArgument(mFunction, "transforms");
llvm::Value* coordws = extractArgument(mFunction, "coord_ws");
assert(accessorPtr);
assert(transformPtr);
assert(coordws);
accessorPtr = mBuilder.CreateGEP(accessorPtr, registeredIndex);
transformPtr = mBuilder.CreateGEP(transformPtr, registeredIndex);
llvm::Value* accessor = mBuilder.CreateLoad(accessorPtr);
llvm::Value* transform = mBuilder.CreateLoad(transformPtr);
const FunctionGroup* const function = this->getFunction("getvoxel", true);
function->execute({accessor, transform, coordws, location}, mBuilder);
}
llvm::Value* VolumeComputeGenerator::accessorHandleFromToken(const std::string& globalName)
{
// Visiting an "attribute" - get the volume accessor out of a vector of void pointers
// mAttributeHandles is a void pointer to a vector of void pointers (void**)
llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable>
(mModule.getOrInsertGlobal(globalName, LLVMType<int64_t>::get(mContext)));
this->globals().insert(globalName, registeredIndex);
registeredIndex = mBuilder.CreateLoad(registeredIndex);
// index into the void* array of handles and load the value.
// The result is a loaded void* value
llvm::Value* accessorPtr = extractArgument(mFunction, "accessors");
assert(accessorPtr);
accessorPtr = mBuilder.CreateGEP(accessorPtr, registeredIndex);
// return loaded void** = void*
return mBuilder.CreateLoad(accessorPtr);
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
} // namespace codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 9,898 | C++ | 35.127737 | 99 | 0.627905 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/SymbolTable.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/SymbolTable.h
///
/// @authors Nick Avramoussis
///
/// @brief Contains the symbol table which holds mappings of variables names
/// to llvm::Values.
///
#ifndef OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <llvm/IR/Value.h>
#include <string>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief A symbol table which can be used to represent a single scoped set of
/// a programs variables. This is simply an unordered map of strings to
/// llvm::Values
/// @note Consider using llvm's ValueSymbolTable
///
struct SymbolTable
{
using MapType = std::unordered_map<std::string, llvm::Value*>;
SymbolTable() : mMap() {}
~SymbolTable() = default;
/// @brief Get a llvm::Value from this symbol table with the given name
/// mapping. It it does not exist, a nullptr is returned.
/// @param name The name of the variable
///
inline llvm::Value* get(const std::string& name) const
{
const auto iter = mMap.find(name);
if (iter == mMap.end()) return nullptr;
return iter->second;
}
/// @brief Returns true if a variable exists in this symbol table with the
/// given name.
/// @param name The name of the variable
///
inline bool exists(const std::string& name) const
{
const auto iter = mMap.find(name);
return (iter != mMap.end());
}
/// @brief Insert a variable to this symbol table if it does not exist. Returns
/// true if successfully, false if a variable already exists with the
/// given name.
/// @param name The name of the variable
/// @param value The llvm::Value corresponding to this variable
///
inline bool insert(const std::string& name, llvm::Value* value)
{
if (exists(name)) return false;
mMap[name] = value;
return true;
}
/// @brief Replace a variable in this symbol table. Returns true if the variable
/// previously existed and false if not. In both cases, the variable is
/// inserted.
/// @param name The name of the variable
/// @param value The llvm::Value corresponding to this variable
///
inline bool replace(const std::string& name, llvm::Value* value)
{
const bool existed = exists(name);
mMap[name] = value;
return existed;
}
/// @brief Clear all symbols in this table
///
inline void clear() { mMap.clear(); }
/// @brief Access to the underlying map
///
inline const MapType& map() const { return mMap; }
private:
MapType mMap;
};
/// @brief A map of unique ids to symbol tables which can be used to represent local
/// variables within a program. New scopes can be added and erased where necessary
/// and iterated through using find(). Find assumes that tables are added through
/// parented ascending ids.
///
/// @note The zero id is used to represent global variables
/// @note The block symbol table is fairly simple and currently only supports insertion
/// by integer ids. Scopes that exist at the same level are expected to be built
/// in isolation and erase and re-create the desired ids where necessary.
///
struct SymbolTableBlocks
{
using MapType = std::map<size_t, SymbolTable>;
SymbolTableBlocks() : mTables({{0, SymbolTable()}}) {}
~SymbolTableBlocks() = default;
/// @brief Access to the list of global variables which are always accessible
///
inline SymbolTable& globals() { return mTables.at(0); }
inline const SymbolTable& globals() const { return mTables.at(0); }
/// @brief Erase a given scoped indexed SymbolTable from the list of held
/// SymbolTables. Returns true if the table previously existed.
/// @note If the zero index is supplied, this function throws a runtime error
///
/// @param index The SymbolTable index to erase
///
inline bool erase(const size_t index)
{
if (index == 0) {
throw std::runtime_error("Attempted to erase global variables which is disallowed.");
}
const bool existed = (mTables.find(index) != mTables.end());
mTables.erase(index);
return existed;
}
/// @brief Get or insert and get a SymbolTable with a unique index
///
/// @param index The SymbolTable index
///
inline SymbolTable* getOrInsert(const size_t index)
{
return &(mTables[index]);
}
/// @brief Get a SymbolTable with a unique index. If the symbol table does not exist,
/// this function throws a runtime error
///
/// @param index The SymbolTable index
///
inline SymbolTable& get(const size_t index)
{
auto iter = mTables.find(index);
if (iter != mTables.end()) return iter->second;
throw std::runtime_error("Attempted to access invalid symbol table with index "
+ std::to_string(index));
}
/// @brief Find a variable within the program starting at a given table index. If
/// the given index does not exist, the next descending index is used.
/// @note This function assumes that tables have been added in ascending order
/// dictating their nested structure.
///
/// @param name The variable name to find
/// @param startIndex The start SymbolTable index
///
inline llvm::Value* find(const std::string& name, const size_t startIndex) const
{
// Find the lower bound start index and if necessary, decrement into
// the first block where the search will be started. Note that this
// is safe as the global block 0 will always exist
auto it = mTables.lower_bound(startIndex);
if (it == mTables.end() || it->first != startIndex) --it;
// reverse the iterator (which also make it point to the preceding
// value, hence the crement)
assert(it != mTables.end());
MapType::const_reverse_iterator iter(++it);
for (; iter != mTables.crend(); ++iter) {
llvm::Value* value = iter->second.get(name);
if (value) return value;
}
return nullptr;
}
/// @brief Find a variable within the program starting at the lowest level
/// SymbolTable
///
/// @param name The variable name to find
///
inline llvm::Value* find(const std::string& name) const
{
return this->find(name, mTables.crbegin()->first);
}
/// @brief Replace the first occurance of a variable with a given name with a
/// replacement value. Returns true if a replacement occured.
///
/// @param name The variable name to find and replace
/// @param value The llvm::Value to replace
///
inline bool replace(const std::string& name, llvm::Value* value)
{
for (auto it = mTables.rbegin(); it != mTables.rend(); ++it) {
if (it->second.get(name)) {
it->second.replace(name, value);
return true;
}
}
return false;
}
private:
MapType mTables;
};
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED
| 7,650 | C | 31.978448 | 97 | 0.624183 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeFunctions.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/VolumeFunctions.cc
///
/// @authors Nick Avramoussis, Richard Jones
///
/// @brief Contains the function objects that define the functions used in
/// volume compute function generation, to be inserted into the FunctionRegistry.
/// These define the functions available when operating on volumes.
/// Also includes the definitions for the volume value retrieval and setting.
///
#include "Functions.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../compiler/CompilerOptions.h"
#include "../Exceptions.h"
#include <openvdb/version.h>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace {
/// @todo Provide more framework for functions such that they can only
/// be registered against compatible code generators.
inline void verifyContext(const llvm::Function* const F, const std::string& name)
{
if (!F || F->getName() != "ax.compute.voxel") {
OPENVDB_THROW(AXCompilerError, "Function \"" << name << "\" cannot be called for "
"the current target. This function only runs on OpenVDB Grids (not OpenVDB Point Grids).");
}
}
}
inline FunctionGroup::UniquePtr axgetvoxelpws(const FunctionOptions& op)
{
static auto generate = [](const std::vector<llvm::Value*>&,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out parent function arguments
llvm::Function* compute = B.GetInsertBlock()->getParent();
verifyContext(compute, "getvoxelpws");
llvm::Value* coordws = extractArgument(compute, "coord_ws");
assert(coordws);
return coordws;
};
return FunctionBuilder("getvoxelpws")
.addSignature<openvdb::math::Vec3<float>*()>(generate)
.setEmbedIR(true)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the current voxel's position in world space as a vector float.")
.get();
}
template <size_t Index>
inline FunctionGroup::UniquePtr axgetcoord(const FunctionOptions& op)
{
static_assert(Index <= 2, "Invalid index for axgetcoord");
static auto generate = [](const std::vector<llvm::Value*>&,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out parent function arguments
llvm::Function* compute = B.GetInsertBlock()->getParent();
verifyContext(compute, (Index == 0 ? "getcoordx" : Index == 1 ? "getcoordy" : "getcoordz"));
llvm::Value* coordis = extractArgument(compute, "coord_is");
assert(coordis);
return B.CreateLoad(B.CreateConstGEP2_64(coordis, 0, Index));
};
return FunctionBuilder((Index == 0 ? "getcoordx" : Index == 1 ? "getcoordy" : "getcoordz"))
.addSignature<int()>(generate)
.setEmbedIR(true)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation((
Index == 0 ? "Returns the current voxel's X index value in index space as an integer." :
Index == 1 ? "Returns the current voxel's Y index value in index space as an integer." :
"Returns the current voxel's Z index value in index space as an integer."))
.get();
}
inline FunctionGroup::UniquePtr axsetvoxel(const FunctionOptions& op)
{
static auto setvoxelptr =
[](void* accessor,
const openvdb::math::Vec3<int32_t>* coord,
const auto value)
{
using ValueType = typename std::remove_const
<typename std::remove_pointer
<decltype(value)>::type>::type;
using GridType = typename openvdb::BoolGrid::ValueConverter<ValueType>::Type;
using RootNodeType = typename GridType::TreeType::RootNodeType;
using AccessorType = typename GridType::Accessor;
assert(accessor);
assert(coord);
// set value only to avoid changing topology
const openvdb::Coord* ijk = reinterpret_cast<const openvdb::Coord*>(coord);
AccessorType* const accessorPtr = static_cast<AccessorType*>(accessor);
// Check the depth to avoid creating voxel topology for higher levels
// @todo As this option is not configurable outside of the executable, we
// should be able to avoid this branching by setting the depth as a global
const int depth = accessorPtr->getValueDepth(*ijk);
if (depth == static_cast<int>(RootNodeType::LEVEL)) {
accessorPtr->setValueOnly(*ijk, *value);
}
else {
// If the current depth is not the maximum (i.e voxel/leaf level) then
// we're iterating over tiles of an internal node (NodeT0 is the leaf level).
// We can't call setValueOnly or other variants as this will forcer voxel
// topology to be created. Whilst the VolumeExecutables runs in such a
// way that this is safe, it's not desriable; we just want to change the
// tile value. There is no easy way to do this; we have to set a new tile
// with the same active state.
// @warning This code assume that getValueDepth() is always called to force
// a node cache.
using NodeT1 = typename AccessorType::NodeT1;
using NodeT2 = typename AccessorType::NodeT2;
if (NodeT1* node = accessorPtr->template getNode<NodeT1>()) {
const openvdb::Index index = node->coordToOffset(*ijk);
assert(node->isChildMaskOff(index));
node->addTile(index, *value, node->isValueOn(index));
}
else if (NodeT2* node = accessorPtr->template getNode<NodeT2>()) {
const openvdb::Index index = node->coordToOffset(*ijk);
assert(node->isChildMaskOff(index));
node->addTile(index, *value, node->isValueOn(index));
}
else {
const int level = RootNodeType::LEVEL - depth;
accessorPtr->addTile(level, *ijk, *value, accessorPtr->isValueOn(*ijk));
}
}
};
static auto setvoxelstr =
[](void* accessor,
const openvdb::math::Vec3<int32_t>* coord,
const AXString* value)
{
const std::string copy(value->ptr, value->size);
setvoxelptr(accessor, coord, ©);
};
static auto setvoxel =
[](void* accessor,
const openvdb::math::Vec3<int32_t>* coord,
const auto value) {
setvoxelptr(accessor, coord, &value);
};
using SetVoxelD = void(void*, const openvdb::math::Vec3<int32_t>*, const double);
using SetVoxelF = void(void*, const openvdb::math::Vec3<int32_t>*, const float);
using SetVoxelI64 = void(void*, const openvdb::math::Vec3<int32_t>*, const int64_t);
using SetVoxelI32 = void(void*, const openvdb::math::Vec3<int32_t>*, const int32_t);
using SetVoxelI16 = void(void*, const openvdb::math::Vec3<int32_t>*, const int16_t);
using SetVoxelB = void(void*, const openvdb::math::Vec3<int32_t>*, const bool);
using SetVoxelV2D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<double>*);
using SetVoxelV2F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<float>*);
using SetVoxelV2I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<int32_t>*);
using SetVoxelV3D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<double>*);
using SetVoxelV3F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<float>*);
using SetVoxelV3I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<int32_t>*);
using SetVoxelV4D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<double>*);
using SetVoxelV4F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<float>*);
using SetVoxelV4I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<int32_t>*);
using SetVoxelM3D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat3<double>*);
using SetVoxelM3F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat3<float>*);
using SetVoxelM4D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat4<double>*);
using SetVoxelM4F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat4<float>*);
using SetVoxelStr = void(void*, const openvdb::math::Vec3<int32_t>*, const AXString*);
return FunctionBuilder("setvoxel")
.addSignature<SetVoxelD>((SetVoxelD*)(setvoxel))
.addSignature<SetVoxelF>((SetVoxelF*)(setvoxel))
.addSignature<SetVoxelI64>((SetVoxelI64*)(setvoxel))
.addSignature<SetVoxelI32>((SetVoxelI32*)(setvoxel))
.addSignature<SetVoxelI16>((SetVoxelI16*)(setvoxel))
.addSignature<SetVoxelB>((SetVoxelB*)(setvoxel))
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.addSignature<SetVoxelV2D>((SetVoxelV2D*)(setvoxelptr))
.addSignature<SetVoxelV2F>((SetVoxelV2F*)(setvoxelptr))
.addSignature<SetVoxelV2I>((SetVoxelV2I*)(setvoxelptr))
.addSignature<SetVoxelV3D>((SetVoxelV3D*)(setvoxelptr))
.addSignature<SetVoxelV3F>((SetVoxelV3F*)(setvoxelptr))
.addSignature<SetVoxelV3I>((SetVoxelV3I*)(setvoxelptr))
.addSignature<SetVoxelV4D>((SetVoxelV4D*)(setvoxelptr))
.addSignature<SetVoxelV4F>((SetVoxelV4F*)(setvoxelptr))
.addSignature<SetVoxelV4I>((SetVoxelV4I*)(setvoxelptr))
.addSignature<SetVoxelM3D>((SetVoxelM3D*)(setvoxelptr))
.addSignature<SetVoxelM3F>((SetVoxelM3F*)(setvoxelptr))
.addSignature<SetVoxelM4D>((SetVoxelM4D*)(setvoxelptr))
.addSignature<SetVoxelM4F>((SetVoxelM4F*)(setvoxelptr))
.addSignature<SetVoxelStr>((SetVoxelStr*)(setvoxelstr))
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for setting the value of a voxel.")
.get();
}
inline FunctionGroup::UniquePtr axgetvoxel(const FunctionOptions& op)
{
static auto getvoxel =
[](void* accessor,
void* transform,
const openvdb::math::Vec3<float>* wspos,
auto value)
{
using ValueType = typename std::remove_pointer<decltype(value)>::type;
using GridType = typename openvdb::BoolGrid::ValueConverter<ValueType>::Type;
using AccessorType = typename GridType::Accessor;
assert(accessor);
assert(wspos);
assert(transform);
const AccessorType* const accessorPtr = static_cast<const AccessorType*>(accessor);
const openvdb::math::Transform* const transformPtr =
static_cast<const openvdb::math::Transform*>(transform);
const openvdb::Coord coordIS = transformPtr->worldToIndexCellCentered(*wspos);
(*value) = accessorPtr->getValue(coordIS);
};
// @todo This is inherently flawed as we're not allocating the data in IR when passing
// this back. When, in the future, grids can be written to and read from at the
// same time we might need to revisit string accesses.
static auto getvoxelstr =
[](void* accessor,
void* transform,
const openvdb::math::Vec3<float>* wspos,
AXString* value)
{
using GridType = typename openvdb::BoolGrid::ValueConverter<std::string>::Type;
using AccessorType = typename GridType::Accessor;
assert(accessor);
assert(wspos);
assert(transform);
const AccessorType* const accessorPtr = static_cast<const AccessorType*>(accessor);
const openvdb::math::Transform* const transformPtr =
static_cast<const openvdb::math::Transform*>(transform);
openvdb::Coord coordIS = transformPtr->worldToIndexCellCentered(*wspos);
const std::string& str = accessorPtr->getValue(coordIS);
value->ptr = str.c_str();
value->size = static_cast<AXString::SizeType>(str.size());
};
using GetVoxelD = void(void*, void*, const openvdb::math::Vec3<float>*, double*);
using GetVoxelF = void(void*, void*, const openvdb::math::Vec3<float>*, float*);
using GetVoxelI64 = void(void*, void*, const openvdb::math::Vec3<float>*, int64_t*);
using GetVoxelI32 = void(void*, void*, const openvdb::math::Vec3<float>*, int32_t*);
using GetVoxelI16 = void(void*, void*, const openvdb::math::Vec3<float>*, int16_t*);
using GetVoxelB = void(void*, void*, const openvdb::math::Vec3<float>*, bool*);
using GetVoxelV2D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<double>*);
using GetVoxelV2F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<float>*);
using GetVoxelV2I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<int32_t>*);
using GetVoxelV3D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<double>*);
using GetVoxelV3F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*);
using GetVoxelV3I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<int32_t>*);
using GetVoxelV4D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<double>*);
using GetVoxelV4F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<float>*);
using GetVoxelV4I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<int32_t>*);
using GetVoxelM3D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat3<double>*);
using GetVoxelM3F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*);
using GetVoxelM4D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat4<double>*);
using GetVoxelM4F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*);
using GetVoxelStr = void(void*, void*, const openvdb::math::Vec3<float>*, AXString*);
return FunctionBuilder("getvoxel")
.addSignature<GetVoxelD>((GetVoxelD*)(getvoxel))
.addSignature<GetVoxelF>((GetVoxelF*)(getvoxel))
.addSignature<GetVoxelI64>((GetVoxelI64*)(getvoxel))
.addSignature<GetVoxelI32>((GetVoxelI32*)(getvoxel))
.addSignature<GetVoxelI16>((GetVoxelI16*)(getvoxel))
.addSignature<GetVoxelB>((GetVoxelB*)(getvoxel))
.addSignature<GetVoxelV2D>((GetVoxelV2D*)(getvoxel))
.addSignature<GetVoxelV2F>((GetVoxelV2F*)(getvoxel))
.addSignature<GetVoxelV2I>((GetVoxelV2I*)(getvoxel))
.addSignature<GetVoxelV3D>((GetVoxelV3D*)(getvoxel))
.addSignature<GetVoxelV3F>((GetVoxelV3F*)(getvoxel))
.addSignature<GetVoxelV3I>((GetVoxelV3I*)(getvoxel))
.addSignature<GetVoxelV4D>((GetVoxelV4D*)(getvoxel))
.addSignature<GetVoxelV4F>((GetVoxelV4F*)(getvoxel))
.addSignature<GetVoxelV4I>((GetVoxelV4I*)(getvoxel))
.addSignature<GetVoxelM3F>((GetVoxelM3F*)(getvoxel))
.addSignature<GetVoxelM3D>((GetVoxelM3D*)(getvoxel))
.addSignature<GetVoxelM4F>((GetVoxelM4F*)(getvoxel))
.addSignature<GetVoxelM4D>((GetVoxelM4D*)(getvoxel))
.addSignature<GetVoxelStr>((GetVoxelStr*)(getvoxelstr))
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(1, llvm::Attribute::NoAlias)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addParameterAttribute(3, llvm::Attribute::WriteOnly)
.addParameterAttribute(3, llvm::Attribute::NoAlias)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for setting the value of a voxel.")
.get();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
void insertVDBVolumeFunctions(FunctionRegistry& registry,
const FunctionOptions* options)
{
const bool create = options && !options->mLazyFunctions;
auto add = [&](const std::string& name,
const FunctionRegistry::ConstructorT creator,
const bool internal = false)
{
if (create) registry.insertAndCreate(name, creator, *options, internal);
else registry.insert(name, creator, internal);
};
// volume functions
add("getcoordx", axgetcoord<0>);
add("getcoordy", axgetcoord<1>);
add("getcoordz", axgetcoord<2>);
add("getvoxelpws", axgetvoxelpws);
add("getvoxel", axgetvoxel, true);
add("setvoxel", axsetvoxel, true);
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 18,118 | C++ | 48.370572 | 110 | 0.651176 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Functions.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/Functions.h
///
/// @authors Nick Avramoussis, Richard Jones, Francisco Gochez
///
/// @brief Contains the function objects that define the functions used in
/// compute function generation, to be inserted into the FunctionRegistry.
/// These define general purpose functions such as math functions.
///
#ifndef OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED
#include "FunctionRegistry.h"
#include "../compiler/CompilerOptions.h"
#include <openvdb/version.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief Creates a registry with the default set of registered functions
/// including math functions, point functions and volume functions
/// @param op The current function options
///
inline FunctionRegistry::UniquePtr createDefaultRegistry(const FunctionOptions* op = nullptr);
/// @brief Populates a function registry with all available "standard" AX
/// library function. This primarily consists of all mathematical ops
/// on AX containers (scalars, vectors, matrices) and other stl built-ins
/// @param reg The function registry to populate
/// @param options The current function options
///
void insertStandardFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr);
/// @brief Populates a function registry with all available OpenVDB Point AX
/// library function
/// @param reg The function registry to populate
/// @param options The current function options
///
void insertVDBPointFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr);
/// @brief Populates a function registry with all available OpenVDB Volume AX
/// library function
/// @param reg The function registry to populate
/// @param options The current function options
///
void insertVDBVolumeFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr);
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
inline FunctionRegistry::UniquePtr createDefaultRegistry(const FunctionOptions* op)
{
FunctionRegistry::UniquePtr registry(new FunctionRegistry);
insertStandardFunctions(*registry, op);
insertVDBPointFunctions(*registry, op);
insertVDBVolumeFunctions(*registry, op);
return registry;
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED
| 2,720 | C | 33.884615 | 95 | 0.720221 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionRegistry.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/FunctionRegistry.h
///
/// @authors Nick Avramoussis
///
/// @brief Contains the global function registration definition which
/// described all available user front end functions
///
#ifndef OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED
#include "FunctionTypes.h"
#include "Types.h"
#include "../compiler/CompilerOptions.h"
#include <openvdb/version.h>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief The function registry which is used for function code generation.
/// Each time a function is visited within the AST, its identifier is used as
/// a key into this registry for the corresponding function retrieval and
/// execution. Functions can be inserted into the registry using insert() with
/// a given identifier and pointer.
class FunctionRegistry
{
public:
using ConstructorT = FunctionGroup::UniquePtr(*)(const FunctionOptions&);
using Ptr = std::shared_ptr<FunctionRegistry>;
using UniquePtr = std::unique_ptr<FunctionRegistry>;
/// @brief An object to represent a registered function, storing its
/// constructor, a pointer to the function definition and whether it
/// should only be available internally (i.e. to a developer, not a user)
///
struct RegisteredFunction
{
/// @brief Constructor
/// @param creator The function definition used to create this function
/// @param internal Whether the function should be only internally accessible
RegisteredFunction(const ConstructorT& creator, const bool internal = false)
: mConstructor(creator), mFunction(), mInternal(internal) {}
/// @brief Create a function object using this creator of this function
/// @param op The current function options
inline void create(const FunctionOptions& op) { mFunction = mConstructor(op); }
/// @brief Return a pointer to this function definition
inline const FunctionGroup* function() const { return mFunction.get(); }
/// @brief Check whether this function should be only internally accesible
inline bool isInternal() const { return mInternal; }
private:
const ConstructorT mConstructor;
FunctionGroup::Ptr mFunction;
const bool mInternal;
};
using RegistryMap = std::unordered_map<std::string, RegisteredFunction>;
/// @brief Insert and register a function object to a function identifier.
/// @note Throws if the identifier is already registered
///
/// @param identifier The function identifier to register
/// @param creator The function to link to the provided identifier
/// @param internal Whether to mark the function as only internally accessible
void insert(const std::string& identifier,
const ConstructorT creator,
const bool internal = false);
/// @brief Insert and register a function object to a function identifier.
/// @note Throws if the identifier is already registered
///
/// @param identifier The function identifier to register
/// @param creator The function to link to the provided identifier
/// @param op FunctionOptions to pass the function constructor
/// @param internal Whether to mark the function as only internally accessible
void insertAndCreate(const std::string& identifier,
const ConstructorT creator,
const FunctionOptions& op,
const bool internal = false);
/// @brief Return the corresponding function from a provided function identifier
/// @note Returns a nullptr if no such function identifier has been
/// registered or if the function is marked as internal
///
/// @param identifier The function identifier
/// @param op FunctionOptions to pass the function constructor
/// @param allowInternalAccess Whether to look in the 'internal' functions
const FunctionGroup* getOrInsert(const std::string& identifier,
const FunctionOptions& op,
const bool allowInternalAccess);
/// @brief Return the corresponding function from a provided function identifier
/// @note Returns a nullptr if no such function identifier has been
/// registered or if the function is marked as internal
///
/// @param identifier The function identifier
/// @param allowInternalAccess Whether to look in the 'internal' functions
const FunctionGroup* get(const std::string& identifier,
const bool allowInternalAccess) const;
/// @brief Force the (re)creations of all function objects for all
/// registered functions
/// @param op The current function options
/// @param verify Checks functions are created and have valid identifiers/symbols
void createAll(const FunctionOptions& op, const bool verify = false);
/// @brief Return a const reference to the current registry map
inline const RegistryMap& map() const { return mMap; }
/// @brief Return whether or not the registry is empty
inline bool empty() const { return mMap.empty(); }
/// @brief Clear the underlying function registry
inline void clear() { mMap.clear(); }
private:
RegistryMap mMap;
};
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED
| 5,696 | C | 39.404255 | 87 | 0.696805 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ComputeGenerator.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/ComputeGenerator.cc
#include "ComputeGenerator.h"
#include "FunctionRegistry.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../ast/AST.h"
#include "../ast/Tokens.h"
#include "../compiler/CustomData.h"
#include "../Exceptions.h"
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/Pass.h>
#include <llvm/Support/MathExtras.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Transforms/Utils/BuildLibCalls.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace {
inline void
printType(const llvm::Type* type, llvm::raw_os_ostream& stream, const bool axTypes)
{
const ast::tokens::CoreType token =
axTypes ? tokenFromLLVMType(type) : ast::tokens::UNKNOWN;
if (token == ast::tokens::UNKNOWN) type->print(stream);
else stream << ast::tokens::typeStringFromToken(token);
}
inline void
printTypes(llvm::raw_os_ostream& stream,
const std::vector<llvm::Type*>& types,
const std::vector<const char*>& names = {},
const std::string sep = "; ",
const bool axTypes = true)
{
if (types.empty()) return;
auto typeIter = types.cbegin();
std::vector<const char*>::const_iterator nameIter;
if (!names.empty()) nameIter = names.cbegin();
for (; typeIter != types.cend() - 1; ++typeIter) {
printType(*typeIter, stream, axTypes);
if (!names.empty() && nameIter != names.cend()) {
if (*nameIter && (*nameIter)[0] != '\0') {
stream << ' ' << *nameIter;
}
++nameIter;
}
stream << sep;
}
printType(*typeIter, stream, axTypes);
if (!names.empty() && nameIter != names.cend()) {
if (*nameIter && (*nameIter)[0] != '\0') {
stream << ' ' << *nameIter;
}
}
}
}
const std::array<std::string, ComputeKernel::N_ARGS>&
ComputeKernel::getArgumentKeys()
{
static const std::array<std::string, ComputeKernel::N_ARGS> arguments = {
{ "custom_data" }
};
return arguments;
}
std::string ComputeKernel::getDefaultName() { return "ax.compute"; }
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
ComputeGenerator::ComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger)
: mModule(module)
, mContext(module.getContext())
, mBuilder(module.getContext())
, mValues()
, mBreakContinueStack()
, mScopeIndex(1)
, mSymbolTables()
, mFunction(nullptr)
, mOptions(options)
, mLog(logger)
, mFunctionRegistry(functionRegistry) {}
bool ComputeGenerator::generate(const ast::Tree& tree)
{
llvm::FunctionType* type =
llvmFunctionTypeFromSignature<ComputeKernel::Signature>(mContext);
mFunction = llvm::Function::Create(type,
llvm::Function::ExternalLinkage,
ComputeKernel::getDefaultName(),
&mModule);
// Set up arguments for initial entry
llvm::Function::arg_iterator argIter = mFunction->arg_begin();
const auto arguments = ComputeKernel::getArgumentKeys();
auto keyIter = arguments.cbegin();
for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) {
argIter->setName(*keyIter);
}
llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext,
"entry_" + ComputeKernel::getDefaultName(), mFunction);
mBuilder.SetInsertPoint(entry);
// if traverse is false, log should have error, but can error
// without stopping traversal, so check both
return this->traverse(&tree) && !mLog.hasError();
}
bool ComputeGenerator::visit(const ast::Block* block)
{
mScopeIndex++;
// traverse the contents of the block
const size_t children = block->children();
for (size_t i = 0; i < children; ++i) {
if (!this->traverse(block->child(i)) && mLog.atErrorLimit()) {
return false;
}
// reset the value stack for each statement
mValues = std::stack<llvm::Value*>();
}
mSymbolTables.erase(mScopeIndex);
mScopeIndex--;
return true;
}
bool ComputeGenerator::visit(const ast::CommaOperator* comma)
{
// traverse the contents of the comma expression
const size_t children = comma->children();
llvm::Value* value = nullptr;
bool hasErrored = false;
for (size_t i = 0; i < children; ++i) {
if (this->traverse(comma->child(i))) {
value = mValues.top(); mValues.pop();
}
else {
if (mLog.atErrorLimit()) return false;
hasErrored = true;
}
}
// only keep the last value
if (!value || hasErrored) return false;
mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::ConditionalStatement* cond)
{
llvm::BasicBlock* postIfBlock = llvm::BasicBlock::Create(mContext, "block", mFunction);
llvm::BasicBlock* thenBlock = llvm::BasicBlock::Create(mContext, "then", mFunction);
const bool hasElse = cond->hasFalse();
llvm::BasicBlock* elseBlock = hasElse ? llvm::BasicBlock::Create(mContext, "else", mFunction) : postIfBlock;
// generate conditional
if (this->traverse(cond->condition())) {
llvm::Value* condition = mValues.top(); mValues.pop();
if (condition->getType()->isPointerTy()) {
condition = mBuilder.CreateLoad(condition);
}
llvm::Type* conditionType = condition->getType();
// check the type of the condition branch is bool-convertable
if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) {
condition = boolComparison(condition, mBuilder);
mBuilder.CreateCondBr(condition, thenBlock, elseBlock);
} else {
if (!mLog.error("cannot convert non-scalar type to bool in condition", cond->condition())) return false;
}
} else if (mLog.atErrorLimit()) return false;
// generate if-then branch
mBuilder.SetInsertPoint(thenBlock);
if (!this->traverse(cond->trueBranch()) && mLog.atErrorLimit()) return false;
mBuilder.CreateBr(postIfBlock);
if (hasElse) {
// generate else-then branch
mBuilder.SetInsertPoint(elseBlock);
if (!this->traverse(cond->falseBranch()) && mLog.atErrorLimit()) return false;
mBuilder.CreateBr(postIfBlock);
}
// reset to continue block
mBuilder.SetInsertPoint(postIfBlock);
// reset the value stack
mValues = std::stack<llvm::Value*>();
return true;
}
bool ComputeGenerator::visit(const ast::TernaryOperator* tern)
{
llvm::BasicBlock* trueBlock = llvm::BasicBlock::Create(mContext, "ternary_true", mFunction);
llvm::BasicBlock* falseBlock = llvm::BasicBlock::Create(mContext, "ternary_false", mFunction);
llvm::BasicBlock* returnBlock = llvm::BasicBlock::Create(mContext, "ternary_return", mFunction);
llvm::Value* trueValue = nullptr;
llvm::Type* trueType = nullptr;
bool truePtr = false;
// generate conditional
bool conditionSuccess = this->traverse(tern->condition());
if (conditionSuccess) {
// get the condition
trueValue = mValues.top(); mValues.pop();
assert(trueValue);
trueType = trueValue->getType();
truePtr = trueType->isPointerTy();
llvm::Type* conditionType = truePtr ? trueType->getPointerElementType() : trueType;
llvm::Value* boolCondition = nullptr;
// check the type of the condition branch is bool-convertable
if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) {
boolCondition = truePtr ?
boolComparison(mBuilder.CreateLoad(trueValue), mBuilder) : boolComparison(trueValue, mBuilder);
mBuilder.CreateCondBr(boolCondition, trueBlock, falseBlock);
}
else {
if (!mLog.error("cannot convert non-scalar type to bool in condition", tern->condition())) return false;
conditionSuccess = false;
}
}
else if (mLog.atErrorLimit()) return false;
// generate true branch, if it exists otherwise take condition as true value
mBuilder.SetInsertPoint(trueBlock);
bool trueSuccess = conditionSuccess;
if (tern->hasTrue()) {
trueSuccess = this->traverse(tern->trueBranch());
if (trueSuccess) {
trueValue = mValues.top(); mValues.pop();// get true value from true expression
// update true type details
trueType = trueValue->getType();
}
else if (mLog.atErrorLimit()) return false;
}
llvm::BranchInst* trueBranch = mBuilder.CreateBr(returnBlock);
// generate false branch
mBuilder.SetInsertPoint(falseBlock);
bool falseSuccess = this->traverse(tern->falseBranch());
// even if the condition isnt successful but the others are, we continue to code gen to find type errors in branches
if (!(trueSuccess && falseSuccess)) return false;
llvm::BranchInst* falseBranch = mBuilder.CreateBr(returnBlock);
llvm::Value* falseValue = mValues.top(); mValues.pop();
llvm::Type* falseType = falseValue->getType();
assert(trueType);
// if both variables of same type do no casting or loading
if (trueType != falseType) {
// get the (contained) types of the expressions
truePtr = trueType->isPointerTy();
if (truePtr) trueType = trueType->getPointerElementType();
const bool falsePtr = falseType->isPointerTy();
if (falsePtr) falseType = falseType->getPointerElementType();
// if same contained type but one needs loading
// can only have one pointer, one not, for scalars right now, i.e. no loaded arrays or strings
if (trueType == falseType) {
assert(!(truePtr && falsePtr));
if (truePtr) {
mBuilder.SetInsertPoint(trueBranch);
trueValue = mBuilder.CreateLoad(trueValue);
}
else {
mBuilder.SetInsertPoint(falseBranch);
falseValue = mBuilder.CreateLoad(falseValue);
}
}
else { // needs casting
// get type for return
llvm::Type* returnType = nullptr;
const bool trueScalar = (trueType->isIntegerTy() || trueType->isFloatingPointTy());
if (trueScalar &&
(falseType->isIntegerTy() || falseType->isFloatingPointTy())) {
assert(trueType != falseType);
// SCALAR_SCALAR
returnType = typePrecedence(trueType, falseType);
// always load scalars here, even if they are the correct type
mBuilder.SetInsertPoint(trueBranch);
if (truePtr) trueValue = mBuilder.CreateLoad(trueValue);
trueValue = arithmeticConversion(trueValue, returnType, mBuilder);
mBuilder.SetInsertPoint(falseBranch);
if (falsePtr) falseValue = mBuilder.CreateLoad(falseValue);
falseValue = arithmeticConversion(falseValue, returnType, mBuilder);
}
else if (trueType->isArrayTy() && falseType->isArrayTy()
&& (trueType->getArrayNumElements() == falseType->getArrayNumElements())) {
// ARRAY_ARRAY
trueType = trueType->getArrayElementType();
falseType = falseType->getArrayElementType();
returnType = typePrecedence(trueType, falseType);
if (trueType != returnType) {
mBuilder.SetInsertPoint(trueBranch);
trueValue = arrayCast(trueValue, returnType, mBuilder);
}
else if (falseType != returnType) {
mBuilder.SetInsertPoint(falseBranch);
falseValue = arrayCast(falseValue, returnType, mBuilder);
}
}
else if (trueScalar && falseType->isArrayTy()) {
// SCALAR_ARRAY
returnType = typePrecedence(trueType, falseType->getArrayElementType());
mBuilder.SetInsertPoint(trueBranch);
if (truePtr) trueValue = mBuilder.CreateLoad(trueValue);
trueValue = arithmeticConversion(trueValue, returnType, mBuilder);
const size_t arraySize = falseType->getArrayNumElements();
if (arraySize == 9 || arraySize == 16) {
trueValue = scalarToMatrix(trueValue, mBuilder, arraySize == 9 ? 3 : 4);
}
else {
trueValue = arrayPack(trueValue, mBuilder, arraySize);
}
if (falseType->getArrayElementType() != returnType) {
mBuilder.SetInsertPoint(falseBranch);
falseValue = arrayCast(falseValue, returnType, mBuilder);
}
}
else if (trueType->isArrayTy() &&
(falseType->isIntegerTy() || falseType->isFloatingPointTy())) {
// ARRAY_SCALAR
returnType = typePrecedence(trueType->getArrayElementType(), falseType);
if (trueType->getArrayElementType() != returnType) {
mBuilder.SetInsertPoint(trueBranch);
trueValue = arrayCast(trueValue, returnType, mBuilder);
}
mBuilder.SetInsertPoint(falseBranch);
if (falsePtr) falseValue = mBuilder.CreateLoad(falseValue);
falseValue = arithmeticConversion(falseValue, returnType, mBuilder);
const size_t arraySize = trueType->getArrayNumElements();
if (arraySize == 9 || arraySize == 16) {
falseValue = scalarToMatrix(falseValue, mBuilder, arraySize == 9 ? 3 : 4);
}
else {
falseValue = arrayPack(falseValue, mBuilder, arraySize);
}
}
else {
mLog.error("unsupported implicit cast in ternary operation",
tern->hasTrue() ? tern->trueBranch() : tern->falseBranch());
return false;
}
}
}
else if (trueType->isVoidTy() && falseType->isVoidTy()) {
// void type ternary acts like if-else statement
// push void value to stop use of return from this expression
mBuilder.SetInsertPoint(returnBlock);
mValues.push(falseValue);
return conditionSuccess && trueSuccess && falseSuccess;
}
// reset to continue block
mBuilder.SetInsertPoint(returnBlock);
llvm::PHINode* ternary = mBuilder.CreatePHI(trueValue->getType(), 2, "ternary");
// if nesting branches the blocks for true and false branches may have been updated
// so get these again rather than reusing trueBlock/falseBlock
ternary->addIncoming(trueValue, trueBranch->getParent());
ternary->addIncoming(falseValue, falseBranch->getParent());
mValues.push(ternary);
return conditionSuccess && trueSuccess && falseSuccess;
}
bool ComputeGenerator::visit(const ast::Loop* loop)
{
mScopeIndex++;
llvm::BasicBlock* postLoopBlock = llvm::BasicBlock::Create(mContext, "block", mFunction);
llvm::BasicBlock* conditionBlock = llvm::BasicBlock::Create(mContext, "loop_condition", mFunction);
llvm::BasicBlock* bodyBlock = llvm::BasicBlock::Create(mContext, "loop_body", mFunction);
llvm::BasicBlock* postBodyBlock = conditionBlock;
const ast::tokens::LoopToken loopType = loop->loopType();
assert((loopType == ast::tokens::LoopToken::FOR ||
loopType == ast::tokens::LoopToken::WHILE ||
loopType == ast::tokens::LoopToken::DO) &&
"Unsupported loop type");
if (loopType == ast::tokens::LoopToken::FOR) {
// init -> condition -> body -> iter -> condition ... continue
// generate initial statement
if (loop->hasInit()) {
if (!this->traverse(loop->initial()) && mLog.atErrorLimit()) return false;
// reset the value stack
mValues = std::stack<llvm::Value*>();
}
mBuilder.CreateBr(conditionBlock);
// generate iteration
if (loop->hasIter()) {
llvm::BasicBlock* iterBlock = llvm::BasicBlock::Create(mContext, "loop_iteration", mFunction);
postBodyBlock = iterBlock;
mBuilder.SetInsertPoint(iterBlock);
if (!this->traverse(loop->iteration()) && mLog.atErrorLimit()) return false;
mBuilder.CreateBr(conditionBlock);
}
}
else if (loopType == ast::tokens::LoopToken::DO) {
// body -> condition -> body -> condition ... continue
mBuilder.CreateBr(bodyBlock);
}
else if (loopType == ast::tokens::LoopToken::WHILE) {
// condition -> body -> condition ... continue
mBuilder.CreateBr(conditionBlock);
}
// store the destinations for break and continue
mBreakContinueStack.push({postLoopBlock, postBodyBlock});
// generate loop body
mBuilder.SetInsertPoint(bodyBlock);
if (!this->traverse(loop->body()) && mLog.atErrorLimit()) return false;
mBuilder.CreateBr(postBodyBlock);
// generate condition
mBuilder.SetInsertPoint(conditionBlock);
if (this->traverse(loop->condition())) {
llvm::Value* condition = mValues.top(); mValues.pop();
if (condition->getType()->isPointerTy()) {
condition = mBuilder.CreateLoad(condition);
}
llvm::Type* conditionType = condition->getType();
// check the type of the condition branch is bool-convertable
if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) {
condition = boolComparison(condition, mBuilder);
mBuilder.CreateCondBr(condition, bodyBlock, postLoopBlock);
}
else {
if (!mLog.error("cannot convert non-scalar type to bool in condition", loop->condition())) return false;
}
// reset the value stack
mValues = std::stack<llvm::Value*>();
}
else if (mLog.atErrorLimit()) return false;
// reset to post loop block
mBuilder.SetInsertPoint(postLoopBlock);
// discard break and continue
mBreakContinueStack.pop();
// remove the symbol table created in this scope
mSymbolTables.erase(mScopeIndex);
mScopeIndex--;
// reset the value stack
mValues = std::stack<llvm::Value*>();
return true;
}
bool ComputeGenerator::visit(const ast::Keyword* node)
{
const ast::tokens::KeywordToken keyw = node->keyword();
assert((keyw == ast::tokens::KeywordToken::RETURN ||
keyw == ast::tokens::KeywordToken::BREAK ||
keyw == ast::tokens::KeywordToken::CONTINUE) &&
"Unsupported keyword");
if (keyw == ast::tokens::KeywordToken::RETURN) {
mBuilder.CreateRetVoid();
}
else if (keyw == ast::tokens::KeywordToken::BREAK ||
keyw == ast::tokens::KeywordToken::CONTINUE) {
// find the parent loop, if it exists
const ast::Node* child = node;
const ast::Node* parentLoop = node->parent();
while (parentLoop) {
if (parentLoop->nodetype() == ast::Node::NodeType::LoopNode) {
break;
}
child = parentLoop;
parentLoop = child->parent();
}
if (!parentLoop) {
if (!mLog.error("keyword \"" + ast::tokens::keywordNameFromToken(keyw)
+ "\" used outside of loop.", node)) return false;
}
else {
const std::pair<llvm::BasicBlock*, llvm::BasicBlock*>
breakContinue = mBreakContinueStack.top();
if (keyw == ast::tokens::KeywordToken::BREAK) {
assert(breakContinue.first);
mBuilder.CreateBr(breakContinue.first);
}
else if (keyw == ast::tokens::KeywordToken::CONTINUE) {
assert(breakContinue.second);
mBuilder.CreateBr(breakContinue.second);
}
}
}
llvm::BasicBlock* nullBlock = llvm::BasicBlock::Create(mContext, "null", mFunction);
// insert all remaining instructions in scope into a null block
// this will incorporate all instructions that follow until new insert point is set
mBuilder.SetInsertPoint(nullBlock);
return true;
}
bool ComputeGenerator::visit(const ast::BinaryOperator* node)
{
openvdb::ax::ast::tokens::OperatorToken opToken = node->operation();
// if AND or OR, need to handle short-circuiting
if (opToken == openvdb::ax::ast::tokens::OperatorToken::AND
|| opToken == openvdb::ax::ast::tokens::OperatorToken::OR) {
llvm::BranchInst* lhsBranch = nullptr;
llvm::BasicBlock* rhsBlock = llvm::BasicBlock::Create(mContext, "binary_rhs", mFunction);
llvm::BasicBlock* returnBlock = llvm::BasicBlock::Create(mContext, "binary_return", mFunction);
llvm::Value* lhs = nullptr;
bool lhsSuccess = this->traverse(node->lhs());
if (lhsSuccess) {
lhs = mValues.top(); mValues.pop();
llvm::Type* lhsType = lhs->getType();
if (lhsType->isPointerTy()) {
lhs = mBuilder.CreateLoad(lhs);
lhsType = lhsType->getPointerElementType();
}
if (lhsType->isFloatingPointTy() || lhsType->isIntegerTy()) {
lhs = boolComparison(lhs, mBuilder);
if (opToken == openvdb::ax::ast::tokens::OperatorToken::AND) {
lhsBranch = mBuilder.CreateCondBr(lhs, rhsBlock, returnBlock);
}
else {
lhsBranch = mBuilder.CreateCondBr(lhs, returnBlock, rhsBlock);
}
}
else {
mLog.error("cannot convert non-scalar lhs to bool", node->lhs());
lhsSuccess = false;
}
}
if (mLog.atErrorLimit()) return false;
mBuilder.SetInsertPoint(rhsBlock);
bool rhsSuccess = this->traverse(node->rhs());
if (rhsSuccess) {
llvm::Value* rhs = mValues.top(); mValues.pop();
llvm::Type* rhsType = rhs->getType();
if (rhsType->isPointerTy()) {
rhs = mBuilder.CreateLoad(rhs);
rhsType = rhsType->getPointerElementType();
}
if (rhsType->isFloatingPointTy() || rhsType->isIntegerTy()) {
rhs = boolComparison(rhs, mBuilder);
llvm::BranchInst* rhsBranch = mBuilder.CreateBr(returnBlock);
mBuilder.SetInsertPoint(returnBlock);
if (lhsBranch) {// i.e. lhs was successful
assert(rhs && lhs);
llvm::PHINode* result = mBuilder.CreatePHI(LLVMType<bool>::get(mContext), 2, "binary_op");
result->addIncoming(lhs, lhsBranch->getParent());
result->addIncoming(rhs, rhsBranch->getParent());
mValues.push(result);
}
}
else {
mLog.error("cannot convert non-scalar rhs to bool", node->rhs());
rhsSuccess = false;
}
}
return lhsSuccess && rhsSuccess;
}
else {
llvm::Value* lhs = nullptr;
if (this->traverse(node->lhs())) {
lhs = mValues.top(); mValues.pop();
}
else if (mLog.atErrorLimit()) return false;
llvm::Value* rhs = nullptr;
if (this->traverse(node->rhs())) {
rhs = mValues.top(); mValues.pop();
}
else if (mLog.atErrorLimit()) return false;
llvm::Value* result = nullptr;
if (!(lhs && rhs) || !this->binaryExpression(result, lhs, rhs, node->operation(), node)) return false;
if (result) {
mValues.push(result);
}
}
return true;
}
bool ComputeGenerator::visit(const ast::UnaryOperator* node)
{
// If the unary operation is a +, keep the value ptr on the stack and
// continue (avoid any new allocations or unecessary loads)
const ast::tokens::OperatorToken token = node->operation();
if (token == ast::tokens::PLUS) return true;
if (token != ast::tokens::MINUS &&
token != ast::tokens::BITNOT &&
token != ast::tokens::NOT) {
mLog.error("unrecognised unary operator \"" +
ast::tokens::operatorNameFromToken(token) + "\"", node);
return false;
}
// unary operator uses default traversal so value should be on the stack
llvm::Value* value = mValues.top();
llvm::Type* type = value->getType();
if (type->isPointerTy()) {
type = type->getPointerElementType();
if (type->isIntegerTy() || type->isFloatingPointTy()) {
value = mBuilder.CreateLoad(value);
}
}
llvm::Value* result = nullptr;
if (type->isIntegerTy()) {
if (token == ast::tokens::NOT) {
if (type->isIntegerTy(1)) result = mBuilder.CreateICmpEQ(value, llvm::ConstantInt::get(type, 0));
else result = mBuilder.CreateICmpEQ(value, llvm::ConstantInt::getSigned(type, 0));
}
else {
// if bool, cast to int32 for unary minus and bitnot
if (type->isIntegerTy(1)) {
type = LLVMType<int32_t>::get(mContext);
value = arithmeticConversion(value, type, mBuilder);
}
if (token == ast::tokens::MINUS) result = mBuilder.CreateNeg(value);
else if (token == ast::tokens::BITNOT) result = mBuilder.CreateNot(value);
}
}
else if (type->isFloatingPointTy()) {
if (token == ast::tokens::MINUS) result = mBuilder.CreateFNeg(value);
else if (token == ast::tokens::NOT) result = mBuilder.CreateFCmpOEQ(value, llvm::ConstantFP::get(type, 0));
else if (token == ast::tokens::BITNOT) {
mLog.error("unable to perform operation \""
+ ast::tokens::operatorNameFromToken(token) + "\" on floating point values", node);
return false;
}
}
else if (type->isArrayTy()) {
type = type->getArrayElementType();
std::vector<llvm::Value*> elements;
arrayUnpack(value, elements, mBuilder, /*load*/true);
assert(elements.size() > 0);
if (type->isIntegerTy()) {
if (token == ast::tokens::MINUS) {
for (llvm::Value*& element : elements) {
element = mBuilder.CreateNeg(element);
}
}
else if (token == ast::tokens::NOT) {
for (llvm::Value*& element : elements) {
element = mBuilder.CreateICmpEQ(element,
llvm::ConstantInt::getSigned(type, 0));
}
}
else if (token == ast::tokens::BITNOT) {
for (llvm::Value*& element : elements) {
element = mBuilder.CreateNot(element);
}
}
}
else if (type->isFloatingPointTy()) {
if (token == ast::tokens::MINUS) {
for (llvm::Value*& element : elements) {
element = mBuilder.CreateFNeg(element);
}
}
else {
//@todo support NOT?
mLog.error("unable to perform operation \""
+ ast::tokens::operatorNameFromToken(token) + "\" on arrays/vectors", node);
return false;
}
}
else {
mLog.error("unrecognised array element type", node);
return false;
}
result = arrayPack(elements, mBuilder);
}
else {
mLog.error("value is not a scalar or vector", node);
return false;
}
assert(result);
mValues.pop();
mValues.push(result);
return true;
}
bool ComputeGenerator::visit(const ast::AssignExpression* assign)
{
// default traversal, should have rhs and lhs on stack
// leave LHS on stack
llvm::Value* rhs = mValues.top(); mValues.pop();
llvm::Value* lhs = mValues.top();
llvm::Type* rhsType = rhs->getType();
if (assign->isCompound()) {
llvm::Value* rhsValue = nullptr;
if (!this->binaryExpression(rhsValue, lhs, rhs, assign->operation(), assign)) return false;
assert(rhsValue);
rhs = rhsValue;
rhsType = rhs->getType();
}
// rhs must be loaded for assignExpression() if it's a scalar
if (rhsType->isPointerTy()) {
rhsType = rhsType->getPointerElementType();
if (rhsType->isIntegerTy() || rhsType->isFloatingPointTy()) {
rhs = mBuilder.CreateLoad(rhs);
}
}
if (!this->assignExpression(lhs, rhs, assign)) return false;
return true;
}
bool ComputeGenerator::visit(const ast::Crement* node)
{
llvm::Value* value = mValues.top();
if (!value->getType()->isPointerTy()) {
mLog.error("unable to assign to an rvalue", node);
return false;
}
llvm::Value* rvalue = mBuilder.CreateLoad(value);
llvm::Type* type = rvalue->getType();
if (type->isIntegerTy(1) || (!type->isIntegerTy() && !type->isFloatingPointTy())) {
mLog.error("variable is an unsupported type for "
"crement. Must be a non-boolean scalar", node);
return false;
}
else {
llvm::Value* crement = nullptr;
assert((node->increment() || node->decrement()) && "unrecognised crement operation");
if (node->increment()) crement = LLVMType<int32_t>::get(mContext, 1);
else if (node->decrement()) crement = LLVMType<int32_t>::get(mContext, -1);
crement = arithmeticConversion(crement, type, mBuilder);
if (type->isIntegerTy()) crement = mBuilder.CreateAdd(rvalue, crement);
if (type->isFloatingPointTy()) crement = mBuilder.CreateFAdd(rvalue, crement);
mBuilder.CreateStore(crement, value);
// decide what to put on the expression stack
}
mValues.pop();
if (node->post()) mValues.push(rvalue);
else mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::FunctionCall* node)
{
const FunctionGroup* const function = this->getFunction(node->name());
if (!function) {
mLog.error("unable to locate function \"" + node->name() + "\"", node);
return false;
}
else {
const size_t args = node->children();
assert(mValues.size() >= args);
// initialize arguments. scalars are always passed by value, arrays
// and strings always by pointer
std::vector<llvm::Value*> arguments;
arguments.resize(args);
for (auto r = arguments.rbegin(); r != arguments.rend(); ++r) {
llvm::Value* arg = mValues.top(); mValues.pop();
llvm::Type* type = arg->getType();
if (type->isPointerTy()) {
type = type->getPointerElementType();
if (type->isIntegerTy() || type->isFloatingPointTy()) {
// pass by value
arg = mBuilder.CreateLoad(arg);
}
}
else {
// arrays should never be loaded
assert(!type->isArrayTy() && type != LLVMType<AXString>::get(mContext));
if (type->isIntegerTy() || type->isFloatingPointTy()) {
/*pass by value*/
}
}
*r = arg;
}
std::vector<llvm::Type*> inputTypes;
valuesToTypes(arguments, inputTypes);
Function::SignatureMatch match;
const Function::Ptr target = function->match(inputTypes, mContext, &match);
if (!target) {
assert(!function->list().empty()
&& "FunctionGroup has no function declarations");
std::ostringstream os;
if (match == Function::SignatureMatch::None) {
os << "wrong number of arguments. \"" << node->name() << "\""
<< " was called with: (";
llvm::raw_os_ostream stream(os);
printTypes(stream, inputTypes);
stream << ")";
}
else {
// match == Function::SignatureMatch::Size
os << "no matching function for ";
printSignature(os, inputTypes,
LLVMType<void>::get(mContext),
node->name().c_str(), {}, true);
}
os << " \ncandidates are: ";
for (const auto& sig : function->list()) {
os << std::endl;
sig->print(mContext, os, node->name().c_str());
}
mLog.error(os.str(), node);
return false;
}
else {
llvm::Value* result = nullptr;
if (match == Function::SignatureMatch::Implicit) {
if (!mLog.warning("implicit conversion in function call", node)) return false;
result = target->call(arguments, mBuilder, /*cast=*/true);
}
else {
// match == Function::SignatureMatch::Explicit
result = target->call(arguments, mBuilder, /*cast=*/false);
}
assert(result && "Function has been invoked with no valid llvm Value return");
mValues.push(result);
}
}
return true;
}
bool ComputeGenerator::visit(const ast::Cast* node)
{
llvm::Value* value = mValues.top(); mValues.pop();
llvm::Type* type =
value->getType()->isPointerTy() ?
value->getType()->getPointerElementType() :
value->getType();
if (!type->isIntegerTy() && !type->isFloatingPointTy()) {
mLog.error("unable to cast non scalar values", node);
return false;
}
else {
// If the value to cast is already the correct type, return
llvm::Type* targetType = llvmTypeFromToken(node->type(), mContext);
if (type == targetType) return true;
if (value->getType()->isPointerTy()) {
value = mBuilder.CreateLoad(value);
}
if (targetType->isIntegerTy(1)) {
// if target is bool, perform standard boolean conversion (*not* truncation).
value = boolComparison(value, mBuilder);
assert(value->getType()->isIntegerTy(1));
}
else {
value = arithmeticConversion(value, targetType, mBuilder);
}
mValues.push(value);
}
return true;
}
bool ComputeGenerator::visit(const ast::DeclareLocal* node)
{
// create storage for the local value.
llvm::Type* type = llvmTypeFromToken(node->type(), mContext);
llvm::Value* value = insertStaticAlloca(mBuilder, type);
// for strings, make sure we correctly initialize to the empty string.
// strings are the only variable type that are currently default allocated
// otherwise you can run into issues with binary operands
if (node->type() == ast::tokens::STRING) {
llvm::Value* loc = mBuilder.CreateGlobalStringPtr(""); // char*
llvm::Constant* constLoc = llvm::cast<llvm::Constant>(loc);
llvm::Constant* size = LLVMType<AXString::SizeType>::get
(mContext, static_cast<AXString::SizeType>(0));
llvm::Value* constStr = LLVMType<AXString>::get(mContext, constLoc, size);
mBuilder.CreateStore(constStr, value);
}
SymbolTable* current = mSymbolTables.getOrInsert(mScopeIndex);
const std::string& name = node->local()->name();
if (!current->insert(name, value)) {
mLog.error("local variable \"" + name +
"\" has already been declared", node);
return false;
}
if (mSymbolTables.find(name, mScopeIndex - 1)) {
if (!mLog.warning("declaration of variable \"" + name
+ "\" shadows a previous declaration", node)) return false;
}
// do this to ensure all AST nodes are visited
// shouldnt ever fail
if (this->traverse(node->local())) {
value = mValues.top(); mValues.pop();
}
else if (mLog.atErrorLimit()) return false;
if (node->hasInit()) {
if (this->traverse(node->init())) {
llvm::Value* init = mValues.top(); mValues.pop();
llvm::Type* initType = init->getType();
if (initType->isPointerTy()) {
initType = initType->getPointerElementType();
if (initType->isIntegerTy() || initType->isFloatingPointTy()) {
init = mBuilder.CreateLoad(init);
}
}
if (!this->assignExpression(value, init, node)) return false;
// note that loop conditions allow uses of initialized declarations
// and so require the value
if (value) mValues.push(value);
}
else if (mLog.atErrorLimit()) return false;
}
return true;
}
bool ComputeGenerator::visit(const ast::Local* node)
{
// Reverse iterate through the current blocks and use the first declaration found
// The current block number looks something like as follows
//
// ENTRY: Block 1
//
// if(...) // Block 3
// {
// if(...) {} // Block 5
// }
// else {} // Block 2
//
// Note that in block 5, block 2 variables will be queried. However block variables
// are constructed from the top down, so although the block number is used for
// reverse iterating, block 2 will not contain any information
//
llvm::Value* value = mSymbolTables.find(node->name());
if (value) {
mValues.push(value);
}
else {
mLog.error("variable \"" + node->name() + "\" hasn't been declared", node);
return false;
}
return true;
}
bool ComputeGenerator::visit(const ast::ArrayUnpack* node)
{
llvm::Value* value = mValues.top(); mValues.pop();
llvm::Value* component0 = mValues.top(); mValues.pop();
llvm::Value* component1 = nullptr;
if (node->isMatrixIndex()) {
component1 = mValues.top(); mValues.pop();
// if double indexing, the two component values will be
// pushed onto the stack with the first index last. i.e.
// top: expression
// 2nd index (if matrix access)
// bottom: 1st index
// so swap the components
std::swap(component0, component1);
}
llvm::Type* type = value->getType();
if (!type->isPointerTy() ||
!type->getPointerElementType()->isArrayTy()) {
mLog.error("variable is not a valid type for component access", node);
return false;
}
// type now guaranteed to be an array type
type = type->getPointerElementType();
const size_t size = type->getArrayNumElements();
if (component1 && size <= 4) {
{
mLog.error("attribute or local variable is not a compatible matrix type "
"for [,] indexing", node);
return false;
}
}
if (component0->getType()->isPointerTy()) {
component0 = mBuilder.CreateLoad(component0);
}
if (component1 && component1->getType()->isPointerTy()) {
component1 = mBuilder.CreateLoad(component1);
}
if (!component0->getType()->isIntegerTy() ||
(component1 && !component1->getType()->isIntegerTy())) {
std::ostringstream os;
llvm::raw_os_ostream stream(os);
component0->getType()->print(stream);
if (component1) {
stream << ", ";
component1->getType()->print(stream);
}
stream.flush();
{
mLog.error("unable to index into array with a non integer value. Types are ["
+ os.str() + "]", node);
return false;
}
}
llvm::Value* zero = LLVMType<int32_t>::get(mContext, 0);
if (!component1) {
value = mBuilder.CreateGEP(value, {zero, component0});
}
else {
// component0 = row, component1 = column. Index into the matrix array
// which is layed out in row major = (component0*dim + component1)
assert(size == 9 || size == 16);
const int32_t dim = size == 9 ? 3 : 4;
llvm::Value* offset =
LLVMType<int32_t>::get(mContext, static_cast<int32_t>(dim));
component0 = binaryOperator(component0, offset, ast::tokens::MULTIPLY, mBuilder);
component0 = binaryOperator(component0, component1, ast::tokens::PLUS, mBuilder);
value = mBuilder.CreateGEP(value, {zero, component0});
}
mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::ArrayPack* node)
{
const size_t num = node->children();
// if there is only one element on the stack, leave it as a pointer to a scalar
// or another array
if (num == 1) return true;
std::vector<llvm::Value*> values;
values.reserve(num);
for (size_t i = 0; i < num; ++i) {
llvm::Value* value = mValues.top(); mValues.pop();
if (value->getType()->isPointerTy()) {
value = mBuilder.CreateLoad(value);
}
values.push_back(value);
}
// reserve the values
// @todo this should probably be handled by the AST
std::reverse(values.begin(), values.end());
llvm::Value* array = arrayPackCast(values, mBuilder);
mValues.push(array);
return true;
}
bool ComputeGenerator::visit(const ast::Value<bool>* node)
{
llvm::Constant* value = LLVMType<bool>::get(mContext, node->value());
mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::Value<int16_t>* node)
{
return visit<int16_t>(node);
}
bool ComputeGenerator::visit(const ast::Value<int32_t>* node)
{
return visit<int32_t>(node);
}
bool ComputeGenerator::visit(const ast::Value<int64_t>* node)
{
return visit<int64_t>(node);
}
bool ComputeGenerator::visit(const ast::Value<float>* node)
{
return visit<float>(node);
}
bool ComputeGenerator::visit(const ast::Value<double>* node)
{
return visit<double>(node);
}
bool ComputeGenerator::visit(const ast::Value<std::string>* node)
{
assert(node->value().size() <
static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max()));
llvm::Value* loc = mBuilder.CreateGlobalStringPtr(node->value()); // char*
llvm::Constant* constLoc = llvm::cast<llvm::Constant>(loc);
llvm::Constant* size = LLVMType<AXString::SizeType>::get
(mContext, static_cast<AXString::SizeType>(node->value().size()));
llvm::Value* constStr = LLVMType<AXString>::get(mContext, constLoc, size);
// Always allocate an AXString here for easier passing to functions
// @todo shouldn't need an AXString for char* literals
llvm::Value* alloc = insertStaticAlloca(mBuilder, LLVMType<AXString>::get(mContext));
mBuilder.CreateStore(constStr, alloc);
mValues.push(alloc);
return true;
}
const FunctionGroup* ComputeGenerator::getFunction(const std::string &identifier,
const bool allowInternal)
{
return mFunctionRegistry.getOrInsert(identifier, mOptions, allowInternal);
}
template <typename ValueType>
typename std::enable_if<std::is_integral<ValueType>::value, bool>::type
ComputeGenerator::visit(const ast::Value<ValueType>* node)
{
using ContainerT = typename ast::Value<ValueType>::ContainerType;
static const ContainerT max =
static_cast<ContainerT>(std::numeric_limits<ValueType>::max());
if (node->asContainerType() > max) {
if (!mLog.warning("signed integer overflow in integer literal "
+ std::to_string(node->asContainerType()), node)) return false;
}
llvm::Constant* value = LLVMType<ValueType>::get(mContext, node->value());
mValues.push(value);
return true;
}
template <typename ValueType>
typename std::enable_if<std::is_floating_point<ValueType>::value, bool>::type
ComputeGenerator::visit(const ast::Value<ValueType>* node)
{
assert(std::isinf(node->value()) || node->value() >= 0.0);
llvm::Constant* value = LLVMType<ValueType>::get(mContext, node->value());
mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::ExternalVariable* node)
{
const std::string globalName = node->tokenname();
llvm::Value* ptrToAddress = this->globals().get(globalName);
if (!ptrToAddress) {
ptrToAddress = llvm::cast<llvm::GlobalVariable>
(mModule.getOrInsertGlobal(globalName, LLVMType<uintptr_t>::get(mContext)));
this->globals().insert(globalName, ptrToAddress);
}
llvm::Type* type = llvmTypeFromToken(node->type(), mContext);
llvm::Value* address = mBuilder.CreateLoad(ptrToAddress);
llvm::Value* value = mBuilder.CreateIntToPtr(address, type->getPointerTo(0));
if (type->isIntegerTy() || type->isFloatingPointTy()) {
value = mBuilder.CreateLoad(value);
}
mValues.push(value);
return true;
}
bool ComputeGenerator::visit(const ast::Tree*)
{
// In case we haven't returned already (i.e. we are NOT in a null block)
// we insert a ret void. If we are, this will just get cleaned up anyway below.
mBuilder.CreateRetVoid();
mBuilder.SetInsertPoint(&mFunction->back());
return true;
}
bool ComputeGenerator::visit(const ast::Attribute*)
{
assert(false && "Base ComputeGenerator attempted to generate code for an Attribute. "
"PointComputeGenerator or VolumeComputeGenerator should be used for "
"attribute accesses.");
return false;
}
bool ComputeGenerator::assignExpression(llvm::Value* lhs, llvm::Value*& rhs, const ast::Node* node)
{
llvm::Type* strtype = LLVMType<AXString>::get(mContext);
llvm::Type* ltype = lhs->getType();
llvm::Type* rtype = rhs->getType();
if (!ltype->isPointerTy()) {
mLog.error("unable to assign to an rvalue", node);
return false;
}
ltype = ltype->getPointerElementType();
if (rtype->isPointerTy()) rtype = rtype->getPointerElementType();
size_t lsize = ltype->isArrayTy() ? ltype->getArrayNumElements() : 1;
size_t rsize = rtype->isArrayTy() ? rtype->getArrayNumElements() : 1;
// Handle scalar->matrix promotion if necessary
// @todo promote all values (i.e. scalar to vectors) to make below branching
// easier. Need to verifier IR is able to optimise to the same logic
if (lsize == 9 || lsize == 16) {
if (rtype->isIntegerTy() || rtype->isFloatingPointTy()) {
if (rhs->getType()->isPointerTy()) {
rhs = mBuilder.CreateLoad(rhs);
}
rhs = arithmeticConversion(rhs, ltype->getArrayElementType(), mBuilder);
rhs = scalarToMatrix(rhs, mBuilder, lsize == 9 ? 3 : 4);
rtype = rhs->getType()->getPointerElementType();
rsize = lsize;
}
}
if (lsize != rsize) {
if (lsize > 1 && rsize > 1) {
mLog.error("unable to assign vector/array "
"attributes with mismatching sizes", node);
return false;
}
else if (lsize == 1) {
assert(rsize > 1);
mLog.error("cannot assign a scalar value "
"from a vector or matrix. Consider using the [] operator to "
"get a particular element", node);
return false;
}
}
// All remaining operators are either componentwise, string or invalid implicit casts
const bool string =
(ltype == strtype && rtype == strtype);
const bool componentwise = !string &&
(rtype->isFloatingPointTy() || rtype->isIntegerTy() || rtype->isArrayTy()) &&
(ltype->isFloatingPointTy() || ltype->isIntegerTy() || ltype->isArrayTy());
if (componentwise) {
assert(rsize == lsize || (rsize == 1 || lsize == 1));
const size_t resultsize = std::max(lsize, rsize);
if (ltype != rtype) {
llvm::Type* letype = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype;
llvm::Type* retype = rtype->isArrayTy() ? rtype->getArrayElementType() : rtype;
if (letype != retype) {
llvm::Type* highest = typePrecedence(letype, retype);
if (highest != letype) {
if (!mLog.warning("implicit conversion in assignment (possible truncation)", node)) return false;
}
}
}
// compute the componentwise precision
llvm::Type* opprec = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype;
// if target is bool, perform standard boolean conversion (*not* truncation).
// i.e. if rhs is anything but zero, lhs is true
// @todo zeroval should be at rhstype
if (opprec->isIntegerTy(1)) {
llvm::Value* newRhs = nullptr;
if (!this->binaryExpression(newRhs, LLVMType<int32_t>::get(mContext, 0), rhs, ast::tokens::NOTEQUALS, node)) return false;
if (!newRhs) return true;
rhs = newRhs;
assert(newRhs->getType()->isIntegerTy(1));
}
for (size_t i = 0; i < resultsize; ++i) {
llvm::Value* lelement = lsize == 1 ? lhs : mBuilder.CreateConstGEP2_64(lhs, 0, i);
llvm::Value* relement = rsize == 1 ? rhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(rhs, 0, i));
relement = arithmeticConversion(relement, opprec, mBuilder);
mBuilder.CreateStore(relement, lelement);
}
}
else if (string) {
// get the size of the rhs string
llvm::Type* strType = LLVMType<AXString>::get(mContext);
llvm::Value* rstrptr = nullptr;
llvm::Value* size = nullptr;
if (llvm::isa<llvm::Constant>(rhs)) {
llvm::Constant* zero =
llvm::cast<llvm::Constant>(LLVMType<int32_t>::get(mContext, 0));
llvm::Constant* constant = llvm::cast<llvm::Constant>(rhs)->getAggregateElement(zero); // char*
rstrptr = constant;
constant = constant->stripPointerCasts();
const size_t count = constant->getType()->getPointerElementType()->getArrayNumElements();
assert(count < static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max()));
size = LLVMType<AXString::SizeType>::get
(mContext, static_cast<AXString::SizeType>(count));
}
else {
rstrptr = mBuilder.CreateStructGEP(strType, rhs, 0); // char**
rstrptr = mBuilder.CreateLoad(rstrptr);
size = mBuilder.CreateStructGEP(strType, rhs, 1); // AXString::SizeType*
size = mBuilder.CreateLoad(size);
}
// total with term
llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1);
llvm::Value* totalTerm = binaryOperator(size, one, ast::tokens::PLUS, mBuilder);
// re-allocate the string array
llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), totalTerm);
llvm::Value* lstrptr = mBuilder.CreateStructGEP(strType, lhs, 0); // char**
llvm::Value* lsize = mBuilder.CreateStructGEP(strType, lhs, 1); // AXString::SizeType*
#if LLVM_VERSION_MAJOR >= 10
mBuilder.CreateMemCpy(string, /*dest-align*/llvm::MaybeAlign(0),
rstrptr, /*src-align*/llvm::MaybeAlign(0), totalTerm);
#elif LLVM_VERSION_MAJOR > 6
mBuilder.CreateMemCpy(string, /*dest-align*/0, rstrptr, /*src-align*/0, totalTerm);
#else
mBuilder.CreateMemCpy(string, rstrptr, totalTerm, /*align*/0);
#endif
mBuilder.CreateStore(string, lstrptr);
mBuilder.CreateStore(size, lsize);
}
else {
mLog.error("unsupported implicit cast in assignment", node);
return false;
}
return true;
}
bool ComputeGenerator::binaryExpression(llvm::Value*& result, llvm::Value* lhs, llvm::Value* rhs,
const ast::tokens::OperatorToken op, const ast::Node* node)
{
llvm::Type* strtype = LLVMType<AXString>::get(mContext);
llvm::Type* ltype = lhs->getType();
llvm::Type* rtype = rhs->getType();
if (ltype->isPointerTy()) ltype = ltype->getPointerElementType();
if (rtype->isPointerTy()) rtype = rtype->getPointerElementType();
size_t lsize = ltype->isArrayTy() ? ltype->getArrayNumElements() : 1;
size_t rsize = rtype->isArrayTy() ? rtype->getArrayNumElements() : 1;
// Handle scalar->matrix promotion if necessary
// @todo promote all values (i.e. scalar to vectors) to make below branching
// easier. Need to verifier IR is able to optimise to the same logic
if (lsize == 9 || lsize == 16) {
if (rtype->isIntegerTy() || rtype->isFloatingPointTy()) {
if (rhs->getType()->isPointerTy()) {
rhs = mBuilder.CreateLoad(rhs);
}
rhs = arithmeticConversion(rhs, ltype->getArrayElementType(), mBuilder);
rhs = scalarToMatrix(rhs, mBuilder, lsize == 9 ? 3 : 4);
rtype = rhs->getType()->getPointerElementType();
rsize = lsize;
}
}
if (rsize == 9 || rsize == 16) {
if (ltype->isIntegerTy() || ltype->isFloatingPointTy()) {
if (lhs->getType()->isPointerTy()) {
lhs = mBuilder.CreateLoad(lhs);
}
lhs = arithmeticConversion(lhs, rtype->getArrayElementType(), mBuilder);
lhs = scalarToMatrix(lhs, mBuilder, rsize == 9 ? 3 : 4);
ltype = lhs->getType()->getPointerElementType();
lsize = rsize;
}
}
//
const ast::tokens::OperatorType opType = ast::tokens::operatorType(op);
result = nullptr;
// Handle custom matrix operators
if (lsize >= 9 || rsize >= 9)
{
if (op == ast::tokens::MULTIPLY) {
if ((lsize == 9 && rsize == 9) ||
(lsize == 16 && rsize == 16)) {
// matrix matrix multiplication all handled through mmmult
result = this->getFunction("mmmult", /*internal*/true)->execute({lhs, rhs}, mBuilder);
}
else if ((lsize == 9 && rsize == 3) ||
(lsize == 16 && rsize == 3) ||
(lsize == 16 && rsize == 4)) {
// matrix vector multiplication all handled through pretransform
result = this->getFunction("pretransform")->execute({lhs, rhs}, mBuilder);
}
else if ((lsize == 3 && rsize == 9) ||
(lsize == 4 && rsize == 16) ||
(lsize == 4 && rsize == 16)) {
// vector matrix multiplication all handled through transform
result = this->getFunction("transform")->execute({lhs, rhs}, mBuilder);
}
else {
mLog.error("unsupported * operator on "
"vector/matrix sizes", node);
return false;
}
}
else if (op == ast::tokens::MORETHAN ||
op == ast::tokens::LESSTHAN ||
op == ast::tokens::MORETHANOREQUAL ||
op == ast::tokens::LESSTHANOREQUAL ||
op == ast::tokens::DIVIDE || // no / support for mats
op == ast::tokens::MODULO || // no % support for mats
opType == ast::tokens::LOGICAL ||
opType == ast::tokens::BITWISE) {
mLog.error("call to unsupported operator \""
+ ast::tokens::operatorNameFromToken(op) +
"\" with a vector/matrix argument", node);
return false;
}
}
if (!result) {
// Handle matrix/vector ops of mismatching sizes
if (lsize > 1 || rsize > 1) {
if (lsize != rsize && (lsize > 1 && rsize > 1)) {
mLog.error("unsupported binary operator on vector/matrix "
"arguments of mismatching sizes", node);
return false;
}
if (op == ast::tokens::MORETHAN ||
op == ast::tokens::LESSTHAN ||
op == ast::tokens::MORETHANOREQUAL ||
op == ast::tokens::LESSTHANOREQUAL ||
opType == ast::tokens::LOGICAL ||
opType == ast::tokens::BITWISE) {
mLog.error("call to unsupported operator \""
+ ast::tokens::operatorNameFromToken(op) +
"\" with a vector/matrix argument", node);
return false;
}
}
// Handle invalid floating point ops
if (rtype->isFloatingPointTy() || ltype->isFloatingPointTy()) {
if (opType == ast::tokens::BITWISE) {
mLog.error("call to unsupported operator \""
+ ast::tokens::operatorNameFromToken(op) +
"\" with a floating point argument", node);
return false;
}
}
}
// All remaining operators are either componentwise, string or invalid implicit casts
const bool componentwise = !result &&
(rtype->isFloatingPointTy() || rtype->isIntegerTy() || rtype->isArrayTy()) &&
(ltype->isFloatingPointTy() || ltype->isIntegerTy() || ltype->isArrayTy());
if (componentwise)
{
assert(ltype->isArrayTy() || ltype->isFloatingPointTy() || ltype->isIntegerTy());
assert(rtype->isArrayTy() || rtype->isFloatingPointTy() || rtype->isIntegerTy());
assert(rsize == lsize || (rsize == 1 || lsize == 1));
if (op == ast::tokens::DIVIDE || op == ast::tokens::MODULO) {
if (llvm::Constant* c = llvm::dyn_cast<llvm::Constant>(rhs)) {
if (c->isZeroValue()) {
if (op == ast::tokens::DIVIDE) {
if (!mLog.warning("division by zero is undefined", node)) return false;
}
else {
if (!mLog.warning("modulo by zero is undefined", node)) return false;
}
}
}
}
// compute the componentwise precision
llvm::Type* opprec = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype;
opprec = rtype->isArrayTy() ?
typePrecedence(opprec, rtype->getArrayElementType()) :
typePrecedence(opprec, rtype);
// if bool, the lowest precision and subsequent result should be int32
// for arithmetic, bitwise and certain other ops
// @note - no bool containers, so if the type is a container, it can't
// contain booleans
if (opprec->isIntegerTy(1)) {
if (opType == ast::tokens::ARITHMETIC ||
opType == ast::tokens::BITWISE ||
op == ast::tokens::MORETHAN ||
op == ast::tokens::LESSTHAN ||
op == ast::tokens::MORETHANOREQUAL ||
op == ast::tokens::LESSTHANOREQUAL) {
opprec = LLVMType<int32_t>::get(mContext);
}
}
// load scalars once
if (!ltype->isArrayTy()) {
if (lhs->getType()->isPointerTy()) {
lhs = mBuilder.CreateLoad(lhs);
}
}
if (!rtype->isArrayTy()) {
if (rhs->getType()->isPointerTy()) {
rhs = mBuilder.CreateLoad(rhs);
}
}
const size_t resultsize = std::max(lsize, rsize);
std::vector<llvm::Value*> elements;
elements.reserve(resultsize);
// handle floored modulo
Function::Ptr target;
auto runop = [&target, op, this](llvm::Value* a, llvm::Value* b) {
if (target) return target->call({a,b}, this->mBuilder, /*cast=*/false);
else return binaryOperator(a, b, op, this->mBuilder);
};
if (op == ast::tokens::MODULO) {
const FunctionGroup* mod = this->getFunction("floormod");
assert(mod);
target = mod->match({opprec,opprec}, mContext);
assert(target);
}
// perform op
for (size_t i = 0; i < resultsize; ++i) {
llvm::Value* lelement = lsize == 1 ? lhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(lhs, 0, i));
llvm::Value* relement = rsize == 1 ? rhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(rhs, 0, i));
lelement = arithmeticConversion(lelement, opprec, mBuilder);
relement = arithmeticConversion(relement, opprec, mBuilder);
elements.emplace_back(runop(lelement, relement));
}
// handle vec/mat results
if (resultsize > 1) {
if (op == ast::tokens::EQUALSEQUALS || op == ast::tokens::NOTEQUALS) {
const ast::tokens::OperatorToken reductionOp =
op == ast::tokens::EQUALSEQUALS ? ast::tokens::AND : ast::tokens::OR;
result = elements.front();
assert(result->getType() == LLVMType<bool>::get(mContext));
for (size_t i = 1; i < resultsize; ++i) {
result = binaryOperator(result, elements[i], reductionOp, mBuilder);
}
}
else {
// Create the allocation at the start of the function block
result = insertStaticAlloca(mBuilder,
llvm::ArrayType::get(opprec, resultsize));
for (size_t i = 0; i < resultsize; ++i) {
mBuilder.CreateStore(elements[i], mBuilder.CreateConstGEP2_64(result, 0, i));
}
}
}
else {
result = elements.front();
}
}
const bool string = !result &&
(ltype == strtype && rtype == strtype);
if (string)
{
if (op != ast::tokens::PLUS) {
mLog.error("unsupported string operation \""
+ ast::tokens::operatorNameFromToken(op) + "\"", node);
return false;
}
auto& B = mBuilder;
auto structToString = [&B, strtype](llvm::Value*& str) -> llvm::Value*
{
llvm::Value* size = nullptr;
if (llvm::isa<llvm::Constant>(str)) {
llvm::Constant* zero =
llvm::cast<llvm::Constant>(LLVMType<int32_t>::get(B.getContext(), 0));
llvm::Constant* constant = llvm::cast<llvm::Constant>(str)->getAggregateElement(zero); // char*
str = constant;
constant = constant->stripPointerCasts();
// array size should include the null terminator
llvm::Type* arrayType = constant->getType()->getPointerElementType();
assert(arrayType->getArrayNumElements() > 0);
const size_t count = arrayType->getArrayNumElements() - 1;
assert(count < static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max()));
size = LLVMType<AXString::SizeType>::get
(B.getContext(), static_cast<AXString::SizeType>(count));
}
else {
llvm::Value* rstrptr = B.CreateStructGEP(strtype, str, 0); // char**
rstrptr = B.CreateLoad(rstrptr);
size = B.CreateStructGEP(strtype, str, 1); // AXString::SizeType*
size = B.CreateLoad(size);
str = rstrptr;
}
return size;
};
// lhs and rhs get set to the char* arrays in structToString
llvm::Value* lhsSize = structToString(lhs);
llvm::Value* rhsSize = structToString(rhs);
// rhs with null terminator
llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1);
llvm::Value* rhsTermSize = binaryOperator(rhsSize, one, ast::tokens::PLUS, mBuilder);
// total and total with term
llvm::Value* total = binaryOperator(lhsSize, rhsSize, ast::tokens::PLUS, mBuilder);
llvm::Value* totalTerm = binaryOperator(lhsSize, rhsTermSize, ast::tokens::PLUS, mBuilder);
// get ptrs to the new structs values
result = insertStaticAlloca(mBuilder, strtype);
llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), totalTerm);
llvm::Value* strptr = mBuilder.CreateStructGEP(strtype, result, 0); // char**
llvm::Value* sizeptr = mBuilder.CreateStructGEP(strtype, result, 1); // AXString::SizeType*
// get rhs offset
llvm::Value* stringRhsOffset = mBuilder.CreateGEP(string, lhsSize);
// memcpy
#if LLVM_VERSION_MAJOR >= 10
mBuilder.CreateMemCpy(string, /*dest-align*/llvm::MaybeAlign(0),
lhs, /*src-align*/llvm::MaybeAlign(0), lhsSize);
mBuilder.CreateMemCpy(stringRhsOffset, /*dest-align*/llvm::MaybeAlign(0),
rhs, /*src-align*/llvm::MaybeAlign(0), rhsTermSize);
#elif LLVM_VERSION_MAJOR > 6
mBuilder.CreateMemCpy(string, /*dest-align*/0, lhs, /*src-align*/0, lhsSize);
mBuilder.CreateMemCpy(stringRhsOffset, /*dest-align*/0, rhs, /*src-align*/0, rhsTermSize);
#else
mBuilder.CreateMemCpy(string, lhs, lhsSize, /*align*/0);
mBuilder.CreateMemCpy(stringRhsOffset, rhs, rhsTermSize, /*align*/0);
#endif
mBuilder.CreateStore(string, strptr);
mBuilder.CreateStore(total, sizeptr);
}
if (!result) {
mLog.error("unsupported implicit cast in binary op", node);
return false;
}
return true;
}
} // namespace codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 66,173 | C++ | 37.228769 | 134 | 0.579013 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionRegistry.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/FunctionRegistry.cc
#include "FunctionRegistry.h"
#include "Functions.h"
#include "FunctionTypes.h"
#include "../Exceptions.h"
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
void FunctionRegistry::insert(const std::string& identifier,
const FunctionRegistry::ConstructorT creator, const bool internal)
{
if (!mMap.emplace(std::piecewise_construct,
std::forward_as_tuple(identifier),
std::forward_as_tuple(creator, internal)).second) {
OPENVDB_THROW(AXCompilerError, "A function already exists"
" with the provided identifier: \"" + identifier + "\"");
}
}
void FunctionRegistry::insertAndCreate(const std::string& identifier,
const FunctionRegistry::ConstructorT creator,
const FunctionOptions& op,
const bool internal)
{
auto inserted = mMap.emplace(std::piecewise_construct,
std::forward_as_tuple(identifier),
std::forward_as_tuple(creator, internal));
if (!inserted.second) {
OPENVDB_THROW(AXCompilerError, "A function already exists"
" with the provided token: \"" + identifier + "\"");
}
inserted.first->second.create(op);
}
const FunctionGroup* FunctionRegistry::getOrInsert(const std::string& identifier,
const FunctionOptions& op,
const bool allowInternalAccess)
{
auto iter = mMap.find(identifier);
if (iter == mMap.end()) return nullptr;
FunctionRegistry::RegisteredFunction& reg = iter->second;
if (!allowInternalAccess && reg.isInternal()) return nullptr;
if (!reg.function()) reg.create(op);
const FunctionGroup* const function = reg.function();
// initialize function dependencies if necessary
if (op.mLazyFunctions && function) {
for (const auto& decl : function->list()) {
const std::vector<const char*>& deps = decl->dependencies();
for (const auto& dep : deps) {
// if the function ptr doesn't exist, create it with getOrInsert.
// This provides internal access and ensures handling of cyclical
// dependencies do not cause a problem
const FunctionGroup* const internal = this->get(dep, true);
if (!internal) this->getOrInsert(dep, op, true);
}
}
}
return function;
}
const FunctionGroup* FunctionRegistry::get(const std::string& identifier, const bool allowInternalAccess) const
{
auto iter = mMap.find(identifier);
if (iter == mMap.end()) return nullptr;
if (!allowInternalAccess && iter->second.isInternal()) return nullptr;
return iter->second.function();
}
void FunctionRegistry::createAll(const FunctionOptions& op, const bool verify)
{
for (auto& it : mMap) it.second.create(op);
if (!verify) return;
std::set<std::string> symbols;
for (auto& it : mMap) {
const auto& func = it.second.function();
if (!func) {
OPENVDB_LOG_WARN("Unable to create function '" << it.first << "'.");
}
if (it.first != std::string(func->name())) {
OPENVDB_LOG_WARN("Registered function identifier does not match function name '" <<
it.first << "' -> '" << func->name() << "'.");
}
if (it.first.empty() || !func->name()) {
OPENVDB_LOG_WARN("Registered function has no identifier or name.");
}
if (func->list().empty()) {
OPENVDB_LOG_WARN("Function '" << it.first << "' has no declarations.");
}
for (const auto& decl : func->list()) {
if (symbols.count(std::string(decl->symbol()))) {
OPENVDB_LOG_WARN("Function '" << it.first << "' has a symbol clash. Symbol '" <<
decl->symbol() << "' already exists.");
}
symbols.insert(std::string(decl->symbol()));
}
}
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 4,256 | C++ | 34.181818 | 111 | 0.601504 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/PointComputeGenerator.cc
#include "PointComputeGenerator.h"
#include "FunctionRegistry.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../Exceptions.h"
#include "../ast/Scanners.h"
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Pass.h>
#include <llvm/Support/MathExtras.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
const std::array<std::string, PointKernel::N_ARGS>&
PointKernel::argumentKeys()
{
static const std::array<std::string, PointKernel::N_ARGS> arguments = {{
"custom_data",
"attribute_set",
"point_index",
"attribute_handles",
"group_handles",
"leaf_data"
}};
return arguments;
}
std::string PointKernel::getDefaultName() { return "ax.compute.point"; }
std::string PointRangeKernel::getDefaultName() { return "ax.compute.pointrange"; }
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
namespace codegen_internal {
PointComputeGenerator::PointComputeGenerator(llvm::Module& module,
const FunctionOptions& options,
FunctionRegistry& functionRegistry,
Logger& logger)
: ComputeGenerator(module, options, functionRegistry, logger) {}
AttributeRegistry::Ptr PointComputeGenerator::generate(const ast::Tree& tree)
{
llvm::FunctionType* type =
llvmFunctionTypeFromSignature<PointKernel::Signature>(mContext);
mFunction = llvm::Function::Create(type,
llvm::Function::ExternalLinkage,
PointKernel::getDefaultName(),
&mModule);
// Set up arguments for initial entry
llvm::Function::arg_iterator argIter = mFunction->arg_begin();
const auto arguments = PointKernel::argumentKeys();
auto keyIter = arguments.cbegin();
for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) {
argIter->setName(*keyIter);
}
type = llvmFunctionTypeFromSignature<PointRangeKernel::Signature>(mContext);
llvm::Function* rangeFunction = llvm::Function::Create(type,
llvm::Function::ExternalLinkage,
PointRangeKernel::getDefaultName(),
&mModule);
// Set up arguments for initial entry for the range function
std::vector<llvm::Value*> kPointRangeArguments;
argIter = rangeFunction->arg_begin();
for (; argIter != rangeFunction->arg_end(); ++argIter) {
kPointRangeArguments.emplace_back(llvm::cast<llvm::Value>(argIter));
}
{
// Generate the range function which calls mFunction point_count times
// For the pointRangeKernelSignature function, create a for loop which calls
// kPoint for every point index 0 to mPointCount. The argument types for
// pointRangeKernelSignature and kPoint are the same, but the 'point_index' argument for
// kPoint is the point index rather than the point range
auto iter = std::find(arguments.begin(), arguments.end(), "point_index");
assert(iter != arguments.end());
const size_t argumentIndex = std::distance(arguments.begin(), iter);
llvm::BasicBlock* preLoop = llvm::BasicBlock::Create(mContext,
"entry_" + PointRangeKernel::getDefaultName(), rangeFunction);
mBuilder.SetInsertPoint(preLoop);
llvm::Value* pointCountValue = kPointRangeArguments[argumentIndex];
llvm::Value* indexMinusOne = mBuilder.CreateSub(pointCountValue, mBuilder.getInt64(1));
llvm::BasicBlock* loop =
llvm::BasicBlock::Create(mContext, "loop_compute_point", rangeFunction);
mBuilder.CreateBr(loop);
mBuilder.SetInsertPoint(loop);
llvm::PHINode* incr = mBuilder.CreatePHI(mBuilder.getInt64Ty(), 2, "i");
incr->addIncoming(/*start*/mBuilder.getInt64(0), preLoop);
// Call kPoint with incr which will be updated per branch
// Map the function arguments. For the 'point_index' argument, we don't pull in the provided
// args, but instead use the value of incr. incr will correspond to the index of the
// point being accessed within the pointRangeKernelSignature loop.
std::vector<llvm::Value*> args(kPointRangeArguments);
args[argumentIndex] = incr;
mBuilder.CreateCall(mFunction, args);
llvm::Value* next = mBuilder.CreateAdd(incr, mBuilder.getInt64(1), "nextval");
llvm::Value* endCondition = mBuilder.CreateICmpULT(incr, indexMinusOne, "endcond");
llvm::BasicBlock* loopEnd = mBuilder.GetInsertBlock();
llvm::BasicBlock* postLoop =
llvm::BasicBlock::Create(mContext, "post_loop_compute_point", rangeFunction);
mBuilder.CreateCondBr(endCondition, loop, postLoop);
mBuilder.SetInsertPoint(postLoop);
incr->addIncoming(next, loopEnd);
mBuilder.CreateRetVoid();
mBuilder.ClearInsertionPoint();
}
llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext,
"entry_" + PointKernel::getDefaultName(), mFunction);
mBuilder.SetInsertPoint(entry);
// build the attribute registry
AttributeRegistry::Ptr registry = AttributeRegistry::create(tree);
// Visit all attributes and allocate them in local IR memory - assumes attributes
// have been verified by the ax compiler
// @note Call all attribute allocs at the start of this block so that llvm folds
// them into the function prologue (as a static allocation)
SymbolTable* localTable = this->mSymbolTables.getOrInsert(1);
// run allocations and update the symbol table
for (const AttributeRegistry::AccessData& data : registry->data()) {
llvm::Value* value = mBuilder.CreateAlloca(llvmTypeFromToken(data.type(), mContext));
assert(llvm::cast<llvm::AllocaInst>(value)->isStaticAlloca());
localTable->insert(data.tokenname(), value);
}
// insert getters for read variables
for (const AttributeRegistry::AccessData& data : registry->data()) {
if (!data.reads()) continue;
const std::string token = data.tokenname();
this->getAttributeValue(token, localTable->get(token));
}
// full code generation
// errors can stop traversal, but dont always, so check the log
if (!this->traverse(&tree) || mLog.hasError()) return nullptr;
// insert set code
std::vector<const AttributeRegistry::AccessData*> write;
for (const AttributeRegistry::AccessData& access : registry->data()) {
if (access.writes()) write.emplace_back(&access);
}
// if it doesn't write to any externally accessible data (i.e attributes)
// then early exit
if (write.empty()) return registry;
for (auto block = mFunction->begin(); block != mFunction->end(); ++block) {
// Only inset set calls if theres a valid return instruction in this block
llvm::Instruction* inst = block->getTerminator();
if (!inst || !llvm::isa<llvm::ReturnInst>(inst)) continue;
mBuilder.SetInsertPoint(inst);
// Insert set attribute instructions before termination
for (const AttributeRegistry::AccessData* access : write) {
const std::string token = access->tokenname();
llvm::Value* value = localTable->get(token);
// Expected to be used more than one (i.e. should never be zero)
assert(value->hasNUsesOrMore(1));
// Check to see if this value is still being used - it may have
// been cleaned up due to returns. If there's only one use, it's
// the original get of this attribute.
if (value->hasOneUse()) {
// @todo The original get can also be optimized out in this case
// this->globals().remove(variable.first);
// mModule.getGlobalVariable(variable.first)->eraseFromParent();
continue;
}
llvm::Type* type = value->getType()->getPointerElementType();
llvm::Type* strType = LLVMType<AXString>::get(mContext);
const bool usingString = type == strType;
llvm::Value* handlePtr = this->attributeHandleFromToken(token);
const FunctionGroup* const function = this->getFunction("setattribute", true);
// load the result (if its a scalar)
if (type->isIntegerTy() || type->isFloatingPointTy()) {
value = mBuilder.CreateLoad(value);
}
llvm::Value* pointidx = extractArgument(mFunction, "point_index");
assert(pointidx);
// construct function arguments
std::vector<llvm::Value*> args {
handlePtr, // handle
pointidx, // point index
value // set value
};
if (usingString) {
llvm::Value* leafdata = extractArgument(mFunction, "leaf_data");
assert(leafdata);
args.emplace_back(leafdata);
}
function->execute(args, mBuilder);
}
}
return registry;
}
bool PointComputeGenerator::visit(const ast::Attribute* node)
{
const std::string globalName = node->tokenname();
SymbolTable* localTable = this->mSymbolTables.getOrInsert(1);
llvm::Value* value = localTable->get(globalName);
assert(value);
mValues.push(value);
return true;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void PointComputeGenerator::getAttributeValue(const std::string& globalName, llvm::Value* location)
{
std::string name, type;
ast::Attribute::nametypeFromToken(globalName, &name, &type);
llvm::Value* handlePtr = this->attributeHandleFromToken(globalName);
llvm::Value* pointidx = extractArgument(mFunction, "point_index");
llvm::Value* leafdata = extractArgument(mFunction, "leaf_data");
assert(leafdata);
assert(pointidx);
std::vector<llvm::Value*> args;
const bool usingString = type == "string";
if (usingString) {
const FunctionGroup* const function = this->getFunction("strattribsize", true);
llvm::Value* size =
function->execute({handlePtr, pointidx, leafdata}, mBuilder);
// add room for the null terminator
llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1);
llvm::Value* sizeTerm = binaryOperator(size, one, ast::tokens::PLUS, mBuilder);
// re-allocate the string array and store the size. The copying will be performed by
// the getattribute function
llvm::Type* strType = LLVMType<AXString>::get(mContext);
llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), sizeTerm);
llvm::Value* lstrptr = mBuilder.CreateStructGEP(strType, location, 0); // char**
llvm::Value* lsize = mBuilder.CreateStructGEP(strType, location, 1); // AXString::SizeType*
mBuilder.CreateStore(string, lstrptr);
mBuilder.CreateStore(size, lsize);
args.reserve(4);
}
else {
args.reserve(3);
}
args.emplace_back(handlePtr);
args.emplace_back(pointidx);
args.emplace_back(location);
if (usingString) args.emplace_back(leafdata);
const FunctionGroup* const function = this->getFunction("getattribute", true);
function->execute(args, mBuilder);
}
llvm::Value* PointComputeGenerator::attributeHandleFromToken(const std::string& token)
{
// Visiting an attribute - get the attribute handle out of a vector of void pointers
// insert the attribute into the map of global variables and get a unique global representing
// the location which will hold the attribute handle offset.
llvm::Value* index = llvm::cast<llvm::GlobalVariable>
(mModule.getOrInsertGlobal(token, LLVMType<int64_t>::get(mContext)));
this->globals().insert(token, index);
// index into the void* array of handles and load the value.
// The result is a loaded void* value
index = mBuilder.CreateLoad(index);
llvm::Value* handles = extractArgument(mFunction, "attribute_handles");
assert(handles);
llvm::Value* handlePtr = mBuilder.CreateGEP(handles, index);
// return loaded void** = void*
return mBuilder.CreateLoad(handlePtr);
}
} // namespace codegen_internal
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 13,076 | C++ | 35.527933 | 100 | 0.641863 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ConstantFolding.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/ConstantFolding.h
///
/// @authors Nick Avramoussis
///
/// @brief Constant folding for C++ bindings.
///
#ifndef OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED
#define OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED
#include "Types.h"
#include <openvdb/version.h>
#include <llvm/IR/Constants.h>
#include <type_traits>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief Constant folding support structure
///
template <typename SignatureT,
size_t I = FunctionTraits<SignatureT>::N_ARGS>
struct ConstantFolder
{
using ArgT = typename FunctionTraits<SignatureT>::template Arg<I-1>;
using ArgumentValueType = typename ArgT::Type;
// @brief Attempts evaluate a given function with a provided set of constant llvm
// values. If successful, the function is invoked and the result is stored
// and returned in an llvm::Value.
// @details Currently only scalar constant folding is supported due to the way
// vectors and matrices are alloced. Functions which return void are also
// not supported for constant folding.
// @param args The vector of llvm constants that comprise the function arguments.
// Note that the size of this vector is expected to match the size of
// the required function arguments and the templated parameter I
// @param function The function to invoke if all arguments have a valid mapping.
// @param C The llvm Context
// @param ts The list of evaluated C types from the provided llvm constants. This
// is expected to be empty (not provided) on the first call to fold and
// is used on subsequent recursive calls.
template <typename ...Tys>
static llvm::Value*
fold(const std::vector<llvm::Constant*>& args,
const SignatureT& function,
llvm::LLVMContext& C,
Tys&&... ts)
{
assert(I-1 < args.size());
llvm::Constant* constant = args[I-1];
const llvm::Type* type = constant->getType();
if (type->isIntegerTy()) {
assert(llvm::isa<llvm::ConstantInt>(constant));
llvm::ConstantInt* cint =
llvm::cast<llvm::ConstantInt>(constant);
const uint64_t val = cint->getLimitedValue();
return call<uint64_t, ArgumentValueType>(args, function, C, val, ts...);
}
else if (type->isFloatTy() || type->isDoubleTy()) {
assert(llvm::isa<llvm::ConstantFP>(constant));
llvm::ConstantFP* cfp =
llvm::cast<llvm::ConstantFP>(constant);
const llvm::APFloat& apf = cfp->getValueAPF();
if (type->isFloatTy()) {
const float val = apf.convertToFloat();
return call<float, ArgumentValueType>(args, function, C, val, ts...);
}
if (type->isDoubleTy()) {
const double val = apf.convertToDouble();
return call<double, ArgumentValueType>(args, function, C, val, ts...);
}
}
else if (type->isArrayTy()) {
// @todo currently all arrays are alloced anyway which
// needs to be handled or changed
return nullptr;
}
// fallback
return nullptr;
}
private:
// @brief Specialization for supported implicit casting matching AX's supported
// scalar casting. Continues to traverse the constant argument list.
template <typename In, typename Out, typename ...Tys>
static typename std::enable_if<std::is_convertible<In, Out>::value, llvm::Value*>::type
call(const std::vector<llvm::Constant*>& args,
const SignatureT& function,
llvm::LLVMContext& C,
const In& arg,
Tys&&... ts)
{
using Next = ConstantFolder<SignatureT, I-1>;
return Next::fold(args, function, C, Out(arg), ts...);
}
// @brief Specialization for unsupported implicit casting. Bails out with a
// nullptr return.
template <typename In, typename Out, typename ...Tys>
static typename std::enable_if<!std::is_convertible<In, Out>::value, llvm::Value*>::type
call(const std::vector<llvm::Constant*>&,
const SignatureT&,
llvm::LLVMContext&,
const In&, Tys&&...)
{
return nullptr;
}
};
template <typename SignatureT>
struct ConstantFolder<SignatureT, 0>
{
// @brief The final call to fold when all arguments have been evaluated (or no
// arguments exist).
template <typename ...Tys>
static llvm::Value*
fold(const std::vector<llvm::Constant*>& args,
const SignatureT& function,
llvm::LLVMContext& C,
Tys&&... ts)
{
using ReturnT = typename FunctionTraits<SignatureT>::ReturnType;
return call<ReturnT>(args, function, C, ts...);
}
private:
// @brief Specialization for the invoking of the provided function if the return
// type is not void.
template <typename ReturnT, typename ...Tys>
static typename std::enable_if<!std::is_same<ReturnT, void>::value, llvm::Value*>::type
call(const std::vector<llvm::Constant*>&,
const SignatureT& function,
llvm::LLVMContext& C,
Tys&&... ts)
{
const ReturnT result = function(ts...);
return LLVMType<ReturnT>::get(C, result);
}
// @brief Specialization if the return type is void. No folding is supported.
template <typename ReturnT, typename ...Tys>
static typename std::enable_if<std::is_same<ReturnT, void>::value, llvm::Value*>::type
call(const std::vector<llvm::Constant*>&,
const SignatureT&,
llvm::LLVMContext&,
Tys&&...)
{
return nullptr;
}
};
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED
| 6,160 | C | 35.455621 | 92 | 0.622078 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/StandardFunctions.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/StandardFunctions.cc
///
/// @authors Nick Avramoussis, Richard Jones, Francisco Gochez
///
/// @brief Definitions for all standard functions supported by AX. A
/// standard function is one that is supported no matetr the input
/// primitive type and rely either solely on AX types or core AX
/// intrinsics.
#include "Functions.h"
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../Exceptions.h"
#include "../math/OpenSimplexNoise.h"
#include "../compiler/CompilerOptions.h"
#include "../compiler/CustomData.h"
#include <tbb/enumerable_thread_specific.h>
#include <llvm/IR/Intrinsics.h>
#include <unordered_map>
#include <functional>
#include <random>
#include <cmath>
#include <stddef.h>
#include <stdint.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace
{
// Reduce a size_t hash down into an unsigned int, taking all bits in the
// size_t into account. We achieve this by repeatedly XORing as many bytes
// that fit into an unsigned int, and then shift those bytes out of the
// hash. We repeat until we have no bits left in the hash.
template <typename SeedType>
inline SeedType hashToSeed(size_t hash) {
SeedType seed = 0;
do {
seed ^= (SeedType) hash;
} while (hash >>= sizeof(SeedType) * 8);
return seed;
}
struct SimplexNoise
{
// Open simplex noise - Visually axis-decorrelated coherent noise algorithm
// based on the simplectic honeycomb.
// See https://gist.github.com/KdotJPG/b1270127455a94ac5d19
inline static double noise(double x, double y, double z)
{
static const OSN::OSNoise noiseGenerator = OSN::OSNoise();
const double result = noiseGenerator.eval<double>(x, y, z);
// adjust result so that it lies between 0 and 1, since
// Noise::eval returns a number between -1 and 1
return (result + 1.0) * 0.5;
}
};
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
#define DEFINE_LLVM_FP_INTRINSIC(Identifier, Doc) \
inline FunctionGroup::UniquePtr llvm_##Identifier(const FunctionOptions& op) \
{ \
static auto generate = \
[](const std::vector<llvm::Value*>& args, \
llvm::IRBuilder<>& B) -> llvm::Value* \
{ \
llvm::Module* M = B.GetInsertBlock()->getParent()->getParent(); \
llvm::Function* function = \
llvm::Intrinsic::getDeclaration(M, \
llvm::Intrinsic::Identifier, args[0]->getType()); \
return B.CreateCall(function, args); \
}; \
\
return FunctionBuilder(#Identifier) \
.addSignature<double(double)>(generate, (double(*)(double))(std::Identifier)) \
.addSignature<float(float)>(generate, (float(*)(float))(std::Identifier)) \
.setArgumentNames({"n"}) \
.addFunctionAttribute(llvm::Attribute::ReadOnly) \
.addFunctionAttribute(llvm::Attribute::NoRecurse) \
.addFunctionAttribute(llvm::Attribute::NoUnwind) \
.addFunctionAttribute(llvm::Attribute::AlwaysInline) \
.setConstantFold(op.mConstantFoldCBindings) \
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) \
.setDocumentation(Doc) \
.get(); \
} \
#define DEFINE_AX_C_FP_BINDING(Identifier, Doc) \
inline FunctionGroup::UniquePtr ax##Identifier(const FunctionOptions& op) \
{ \
return FunctionBuilder(#Identifier) \
.addSignature<double(double)>((double(*)(double))(std::Identifier)) \
.addSignature<float(float)>((float(*)(float))(std::Identifier)) \
.setArgumentNames({"arg"}) \
.addFunctionAttribute(llvm::Attribute::ReadOnly) \
.addFunctionAttribute(llvm::Attribute::NoRecurse) \
.addFunctionAttribute(llvm::Attribute::NoUnwind) \
.addFunctionAttribute(llvm::Attribute::AlwaysInline) \
.setConstantFold(op.mConstantFoldCBindings) \
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) \
.setDocumentation(Doc) \
.get(); \
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Intrinsics
DEFINE_LLVM_FP_INTRINSIC(sqrt, "Computes the square root of arg.")
DEFINE_LLVM_FP_INTRINSIC(sin, "Computes the sine of arg (measured in radians).")
DEFINE_LLVM_FP_INTRINSIC(cos, "Computes the cosine of arg (measured in radians).")
DEFINE_LLVM_FP_INTRINSIC(log, "Computes the natural (base e) logarithm of arg.")
DEFINE_LLVM_FP_INTRINSIC(log10, "Computes the common (base-10) logarithm of arg.")
DEFINE_LLVM_FP_INTRINSIC(log2, "Computes the binary (base-2) logarithm of arg.")
DEFINE_LLVM_FP_INTRINSIC(exp, "Computes e (Euler's number, 2.7182818...) raised to the given power arg.")
DEFINE_LLVM_FP_INTRINSIC(exp2, "Computes 2 raised to the given power arg.")
DEFINE_LLVM_FP_INTRINSIC(fabs, "Computes the absolute value of a floating point value arg.")
DEFINE_LLVM_FP_INTRINSIC(floor, "Computes the largest integer value not greater than arg.")
DEFINE_LLVM_FP_INTRINSIC(ceil, "Computes the smallest integer value not less than arg.")
DEFINE_LLVM_FP_INTRINSIC(round, "Computes the nearest integer value to arg (in floating-point format),"
" rounding halfway cases away from zero.")
// pow created explicitly as it takes two arguments and performs slighlty different
// calls for integer exponents
inline FunctionGroup::UniquePtr llvm_pow(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
llvm::Type* overloadType = args[0]->getType();
llvm::Type* expType = args[1]->getType();
const llvm::Intrinsic::ID id =
expType->isIntegerTy() ? llvm::Intrinsic::powi : llvm::Intrinsic::pow;
llvm::Module* M = B.GetInsertBlock()->getParent()->getParent();
llvm::Function* function = llvm::Intrinsic::getDeclaration(M, id, overloadType);
return B.CreateCall(function, args);
};
return FunctionBuilder("pow")
.addSignature<double(double,double)>(generate, (double(*)(double,double))(std::pow))
.addSignature<float(float,float)>(generate, (float(*)(float,float))(std::pow))
.addSignature<double(double,int32_t)>(generate, (double(*)(double,int32_t))(std::pow))
.setArgumentNames({"base", "exp"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(false) // decl's differ
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Computes the value of the first argument raised to the power of the second argument.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Math
DEFINE_AX_C_FP_BINDING(cbrt, "Computes the cubic root of the input.")
inline FunctionGroup::UniquePtr axabs(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
llvm::Value* value = args.front();
llvm::Type* type = value->getType();
if (type->isFloatingPointTy()) {
return llvm_fabs(op)->execute(args, B);
}
// if negative flip all the bits and add 1 (xor with -1 and sub 1)
llvm::Value* shift = type == LLVMType<int32_t>::get(B.getContext()) ?
LLVMType<int32_t>::get(B.getContext(), 31) :
LLVMType<int64_t>::get(B.getContext(), 63);
// arithmetic shift right
llvm::Value* mask = B.CreateAShr(value, shift);
llvm::Value* xorResult = binaryOperator(value, mask, ast::tokens::BITXOR, B);
return binaryOperator(xorResult, mask, ast::tokens::MINUS, B);
};
// @note We also support fabs through the ax abs function
return FunctionBuilder("abs")
.addSignature<int64_t(int64_t)>(generate, (int64_t(*)(int64_t))(std::abs))
.addSignature<int32_t(int32_t)>(generate, (int32_t(*)(int32_t))(std::abs))
.addSignature<double(double)>(generate, (double(*)(double))(std::abs))
.addSignature<float(float)>(generate, (float(*)(float))(std::abs))
.setArgumentNames({"n"})
.addDependency("fabs")
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Computes the absolute value of an integer number.")
.get();
}
inline FunctionGroup::UniquePtr axdot(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> v1, v2;
arrayUnpack(args[0], v1, B, /*load*/true);
arrayUnpack(args[1], v2, B, /*load*/true);
v1[0] = binaryOperator(v1[0], v2[0], ast::tokens::MULTIPLY, B);
v1[1] = binaryOperator(v1[1], v2[1], ast::tokens::MULTIPLY, B);
v1[2] = binaryOperator(v1[2], v2[2], ast::tokens::MULTIPLY, B);
llvm::Value* result = binaryOperator(v1[0], v1[1], ast::tokens::PLUS, B);
result = binaryOperator(result, v1[2], ast::tokens::PLUS, B);
return result;
};
static auto dot = [](auto a, auto b) {
return a->dot(*b);
};
using DotD = double(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*);
using DotF = float(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*);
using DotI = int32_t(openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*);
return FunctionBuilder("dot")
.addSignature<DotD>(generate, (DotD*)(dot))
.addSignature<DotF>(generate, (DotF*)(dot))
.addSignature<DotI>(generate, (DotI*)(dot))
.setArgumentNames({"a", "b"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Computes the dot product of two vectors.")
.get();
}
inline FunctionGroup::UniquePtr axcross(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, left, right;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], left, B, /*load*/true);
arrayUnpack(args[2], right, B, /*load*/true);
assert(ptrs.size() == 3);
assert(left.size() == 3);
assert(right.size() == 3);
std::vector<llvm::Value*> results(3);
llvm::Value* tmp1 = binaryOperator(left[1], right[2], ast::tokens::MULTIPLY, B);
llvm::Value* tmp2 = binaryOperator(left[2], right[1], ast::tokens::MULTIPLY, B);
results[0] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B);
tmp1 = binaryOperator(left[2], right[0], ast::tokens::MULTIPLY, B);
tmp2 = binaryOperator(left[0], right[2], ast::tokens::MULTIPLY, B);
results[1] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B);
tmp1 = binaryOperator(left[0], right[1], ast::tokens::MULTIPLY, B);
tmp2 = binaryOperator(left[1], right[0], ast::tokens::MULTIPLY, B);
results[2] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B);
B.CreateStore(results[0], ptrs[0]);
B.CreateStore(results[1], ptrs[1]);
B.CreateStore(results[2], ptrs[2]);
return nullptr;
};
static auto cross = [](auto out, auto a, auto b) -> auto {
*out = a->cross(*b);
};
using CrossD = void(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*);
using CrossF = void(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*);
using CrossI = void(openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*);
return FunctionBuilder("cross")
.addSignature<CrossD, true>(generate, (CrossD*)(cross))
.addSignature<CrossF, true>(generate, (CrossF*)(cross))
.addSignature<CrossI, true>(generate, (CrossI*)(cross))
.setArgumentNames({"a", "b"})
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the length of the given vector")
.get();
}
inline FunctionGroup::UniquePtr axlengthsq(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> elements;
arrayUnpack(args[0], elements, B, /*load*/true);
assert(elements.size() >= 2);
llvm::Value* v1 = binaryOperator(elements[0], elements[0], ast::tokens::MULTIPLY, B);
llvm::Value* v2 = binaryOperator(elements[1], elements[1], ast::tokens::MULTIPLY, B);
llvm::Value* result = binaryOperator(v1, v2, ast::tokens::PLUS, B);
if (elements.size() > 2) {
llvm::Value* v3 = binaryOperator(elements[2], elements[2], ast::tokens::MULTIPLY, B);
result = binaryOperator(result, v3, ast::tokens::PLUS, B);
}
if (elements.size() > 3) {
llvm::Value* v4 = binaryOperator(elements[3], elements[3], ast::tokens::MULTIPLY, B);
result = binaryOperator(result, v4, ast::tokens::PLUS, B);
}
return result;
};
static auto lengthsq = [](auto in) -> auto { return in->lengthSqr(); };
return FunctionBuilder("lengthsq")
.addSignature<double(openvdb::math::Vec2<double>*)>(generate, lengthsq)
.addSignature<float(openvdb::math::Vec2<float>*)>(generate, lengthsq)
.addSignature<int32_t(openvdb::math::Vec2<int32_t>*)>(generate, lengthsq)
.addSignature<double(openvdb::math::Vec3<double>*)>(generate, lengthsq)
.addSignature<float(openvdb::math::Vec3<float>*)>(generate, lengthsq)
.addSignature<int32_t(openvdb::math::Vec3<int32_t>*)>(generate, lengthsq)
.addSignature<double(openvdb::math::Vec4<double>*)>(generate, lengthsq)
.addSignature<float(openvdb::math::Vec4<float>*)>(generate, lengthsq)
.addSignature<int32_t(openvdb::math::Vec4<int32_t>*)>(generate, lengthsq)
.setArgumentNames({"v"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the squared length of the given vector")
.get();
}
inline FunctionGroup::UniquePtr axlength(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
auto a = axlengthsq(op);
auto s = llvm_sqrt(op);
llvm::Value* lsq = a->execute(args, B);
return s->execute({lsq}, B);
};
static auto length = [](auto in) -> auto
{
using VecType = typename std::remove_pointer<decltype(in)>::type;
using ElementT = typename openvdb::VecTraits<VecType>::ElementType;
using RetT = typename std::conditional
<std::is_floating_point<ElementT>::value, ElementT, double>::type;
return std::sqrt(RetT(in->lengthSqr()));
};
return FunctionBuilder("length")
.addSignature<double(openvdb::math::Vec2<double>*)>(generate, length)
.addSignature<float(openvdb::math::Vec2<float>*)>(generate, length)
.addSignature<double(openvdb::math::Vec2<int32_t>*)>(generate, length)
.addSignature<double(openvdb::math::Vec3<double>*)>(generate, length)
.addSignature<float(openvdb::math::Vec3<float>*)>(generate, length)
.addSignature<double(openvdb::math::Vec3<int32_t>*)>(generate, length)
.addSignature<double(openvdb::math::Vec4<double>*)>(generate, length)
.addSignature<float(openvdb::math::Vec4<float>*)>(generate, length)
.addSignature<double(openvdb::math::Vec4<int32_t>*)>(generate, length)
.addDependency("lengthsq")
.addDependency("sqrt")
.setArgumentNames({"v"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the length of the given vector")
.get();
}
inline FunctionGroup::UniquePtr axnormalize(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
auto a = axlength(op);
llvm::Value* len = a->execute({args[1]}, B);
std::vector<llvm::Value*> ptrs, elements;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], elements, B, /*load*/true);
assert(ptrs.size() == 3);
assert(elements.size() == 3);
if (elements[0]->getType()->isIntegerTy()) {
arithmeticConversion(elements, LLVMType<double>::get(B.getContext()), B);
}
// the following is always done at fp precision
llvm::Value* one = llvm::ConstantFP::get(len->getType(), 1.0);
llvm::Value* oneDividedByLength = B.CreateFDiv(one, len);
elements[0] = B.CreateFMul(elements[0], oneDividedByLength);
elements[1] = B.CreateFMul(elements[1], oneDividedByLength);
elements[2] = B.CreateFMul(elements[2], oneDividedByLength);
B.CreateStore(elements[0], ptrs[0]);
B.CreateStore(elements[1], ptrs[1]);
B.CreateStore(elements[2], ptrs[2]);
return nullptr;
};
static auto norm = [](auto out, auto in) {
using VecType = typename std::remove_pointer<decltype(out)>::type;
using ElementT = typename openvdb::VecTraits<VecType>::ElementType;
*out = *in; // copy
out->normalize(ElementT(0.0));
};
using NormalizeD = void(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*);
using NormalizeF = void(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*);
using NormalizeI = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<int32_t>*);
return FunctionBuilder("normalize")
.addSignature<NormalizeD, true>(generate, (NormalizeD*)(norm))
.addSignature<NormalizeF, true>(generate, (NormalizeF*)(norm))
.addSignature<NormalizeI, true>(generate, (NormalizeI*)(norm))
.addDependency("length")
.setArgumentNames({"v"})
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the normalized result of the given vector.")
.get();
}
inline FunctionGroup::UniquePtr axlerp(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
assert(args.size() == 3);
llvm::Value* a = args[0], *b = args[1], *t = args[2];
llvm::Value* zero = llvm::ConstantFP::get(a->getType(), 0.0);
llvm::Value* one = llvm::ConstantFP::get(a->getType(), 1.0);
llvm::Function* base = B.GetInsertBlock()->getParent();
// @todo short-circuit?
llvm::Value* a1 = binaryOperator(a, zero, ast::tokens::LESSTHANOREQUAL, B);
llvm::Value* b1 = binaryOperator(b, zero, ast::tokens::MORETHANOREQUAL, B);
llvm::Value* a2 = binaryOperator(a, zero, ast::tokens::MORETHANOREQUAL, B);
llvm::Value* b2 = binaryOperator(b, zero, ast::tokens::LESSTHANOREQUAL, B);
a1 = binaryOperator(a1, b1, ast::tokens::AND, B);
a2 = binaryOperator(a2, b2, ast::tokens::AND, B);
a1 = binaryOperator(a1, a2, ast::tokens::OR, B);
llvm::BasicBlock* then = llvm::BasicBlock::Create(B.getContext(), "then", base);
llvm::BasicBlock* post = llvm::BasicBlock::Create(B.getContext(), "post", base);
B.CreateCondBr(a1, then, post);
B.SetInsertPoint(then);
llvm::Value* r = binaryOperator(one, t, ast::tokens::MINUS, B);
r = binaryOperator(r, a, ast::tokens::MULTIPLY, B);
llvm::Value* right = binaryOperator(t, b, ast::tokens::MULTIPLY, B);
r = binaryOperator(r, right, ast::tokens::PLUS, B);
B.CreateRet(r);
B.SetInsertPoint(post);
llvm::Value* tisone = binaryOperator(t, one, ast::tokens::EQUALSEQUALS, B);
then = llvm::BasicBlock::Create(B.getContext(), "then", base);
post = llvm::BasicBlock::Create(B.getContext(), "post", base);
B.CreateCondBr(tisone, then, post);
B.SetInsertPoint(then);
B.CreateRet(b);
B.SetInsertPoint(post);
// if nlerp
llvm::Value* x = binaryOperator(b, a, ast::tokens::MINUS, B);
x = binaryOperator(t, x, ast::tokens::MULTIPLY, B);
x = binaryOperator(a, x, ast::tokens::PLUS, B);
then = llvm::BasicBlock::Create(B.getContext(), "then", base);
post = llvm::BasicBlock::Create(B.getContext(), "post", base);
a1 = binaryOperator(t, one, ast::tokens::MORETHAN, B);
a2 = binaryOperator(b, a, ast::tokens::MORETHAN, B);
a1 = binaryOperator(a1, a2, ast::tokens::EQUALSEQUALS, B);
B.CreateCondBr(a1, then, post);
B.SetInsertPoint(then);
b1 = binaryOperator(b, x, ast::tokens::LESSTHAN, B);
B.CreateRet(B.CreateSelect(b1, x, b));
B.SetInsertPoint(post);
b1 = binaryOperator(x, b, ast::tokens::LESSTHAN, B);
return B.CreateRet(B.CreateSelect(b1, x, b));
};
// This lerp implementation is taken from clang and matches the C++20 standard
static auto lerp = [](auto a, auto b, auto t) -> auto
{
using ValueT = decltype(a);
// If there is a zero crossing with a,b do the more precise
// linear interpolation. This is only monotonic if there is
// a zero crossing
// Exact, monotonic, bounded, determinate, and (for a=b=0)
// consistent
if ((a <= 0 && b >= 0) || (a >= 0 && b <= 0)) {
return t * b + (ValueT(1.0) - t) * a;
}
// If t is exactly 1, return b (as the second impl doesn't
// guarantee this due to fp arithmetic)
if (t == ValueT(1.0)) return b;
// less precise interpolation when there is no crossing
// Exact at t=0, monotonic except near t=1, bounded,
// determinate, and consistent
const auto x = a + t * (b - a);
// Ensure b is preferred to another equal value (i.e. -0. vs. +0.),
// which avoids returning -0 for t==1 but +0 for other nearby
// values of t. This branching also stops nans being returns from
// inf inputs
// monotonic near t=1
if ((t > ValueT(1.0)) == (b > a)) return b < x ? x : b;
else return x < b ? x : b;
};
return FunctionBuilder("lerp")
.addSignature<double(double,double,double)>(generate, (double(*)(double,double,double))(lerp))
.addSignature<float(float,float,float)>(generate, (float(*)(float,float,float))(lerp))
.setArgumentNames({"a", "b", "amount"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Performs bilinear interpolation between the values. If the "
"amount is outside the range 0 to 1, the values will be extrapolated linearly. "
"If amount is 0, the first value is returned. If it is 1, the second value "
"is returned. This implementation is guaranteed to be monotonic.")
.get();
}
inline FunctionGroup::UniquePtr axmin(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
llvm::Value* result =
binaryOperator(args[0], args[1], ast::tokens::MORETHAN, B);
return B.CreateSelect(result, args[1], args[0]);
};
static auto min = [](auto a, auto b) -> auto {
return std::min(a, b);
};
return FunctionBuilder("min")
.addSignature<double(double,double)>(generate, (double(*)(double,double))(min))
.addSignature<float(float,float)>(generate, (float(*)(float,float))(min))
.addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(min))
.addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(min))
.setArgumentNames({"a", "b"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the smaller of the given values.")
.get();
}
inline FunctionGroup::UniquePtr axmax(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
llvm::Value* result =
binaryOperator(args[0], args[1], ast::tokens::MORETHAN, B);
return B.CreateSelect(result, args[0], args[1]);
};
static auto max = [](auto a, auto b) -> auto {
return std::max(a, b);
};
return FunctionBuilder("max")
.addSignature<double(double,double)>(generate, (double(*)(double,double))(max))
.addSignature<float(float,float)>(generate, (float(*)(float,float))(max))
.addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(max))
.addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(max))
.setArgumentNames({"a", "b"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the larger of the given values.")
.get();
}
inline FunctionGroup::UniquePtr axclamp(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
llvm::Value* min = axmax(op)->execute({args[0], args[1]}, B);
llvm::Value* result = axmin(op)->execute({min, args[2]}, B);
return result;
};
using ClampD = double(double, double, double);
using ClampF = float(float, float, float);
using ClampI = int32_t(int32_t, int32_t, int32_t);
using ClampL = int64_t(int64_t, int64_t, int64_t);
return FunctionBuilder("clamp")
.addSignature<ClampD>(generate, &openvdb::math::Clamp<double>)
.addSignature<ClampF>(generate, &openvdb::math::Clamp<float>)
.addSignature<ClampL>(generate, &openvdb::math::Clamp<int64_t>)
.addSignature<ClampI>(generate, &openvdb::math::Clamp<int32_t>)
.addDependency("min")
.addDependency("max")
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setArgumentNames({"in", "min", "max"})
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Clamps the first argument to the minimum second argument "
"value and maximum third argument value")
.get();
}
inline FunctionGroup::UniquePtr axfit(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// (outMax - outMin)(x - inMin)
// f(x) = ---------------------------- + outMin
// inMax - inMin
// if inMax == inMin, f(x) = (outMax + outMin) / 2.0
// NOTE: this also performs a clamp on the ordered input range
// @TODO revisit. If this is the best thing to do, should add conditional
// branching so that the clamping math is never executed when the value
// is inside
std::vector<llvm::Value*> argcopy(args);
// select the precision at which to perform
llvm::Type* precision = argcopy[0]->getType();
if (precision->isIntegerTy()) {
precision = LLVMType<double>::get(B.getContext());
}
// See if the input range has a valid magnitude .i.e. the values are not the same
llvm::Value* isInputRangeValid =
binaryOperator(argcopy[1], argcopy[2], ast::tokens::NOTEQUALS, B);
// clamp the input to the ORDERED inMin to inMax range
llvm::Value* minRangeComp =
binaryOperator(argcopy[1], argcopy[2], ast::tokens::LESSTHAN, B);
llvm::Value* minInputRange = B.CreateSelect(minRangeComp, argcopy[1], argcopy[2]);
llvm::Value* maxInputRange = B.CreateSelect(minRangeComp, argcopy[2], argcopy[1]);
// clamp
{
auto clamp = axclamp(op);
argcopy[0] = clamp->execute({ argcopy[0], minInputRange, maxInputRange }, B);
}
// cast all (the following requires floating point precision)
for (auto& arg : argcopy) arg = arithmeticConversion(arg, precision, B);
llvm::Value* valueMinusMin = B.CreateFSub(argcopy[0], argcopy[1]);
llvm::Value* inputRange = B.CreateFSub(argcopy[2], argcopy[1]);
llvm::Value* outputRange = B.CreateFSub(argcopy[4], argcopy[3]);
llvm::Value* result = B.CreateFMul(outputRange, valueMinusMin);
result = B.CreateFDiv(result, inputRange); // NOTE - This can cause division by zero
result = B.CreateFAdd(argcopy[3], result);
// calculate the output range over 2 and use this value if the input range is invalid
llvm::Value* outputRangeOverTwo = B.CreateFAdd(argcopy[3], argcopy[4]);
llvm::Value* two = llvm::ConstantFP::get(precision, 2.0);
outputRangeOverTwo = B.CreateFDiv(outputRangeOverTwo, two);
return B.CreateSelect(isInputRangeValid, result, outputRangeOverTwo);
};
using FitD = double(double, double, double, double, double);
using FitF = float(float, float, float, float, float);
using FitL = double(int64_t, int64_t, int64_t, int64_t, int64_t);
using FitI = double(int32_t, int32_t, int32_t, int32_t, int32_t);
return FunctionBuilder("fit")
.addSignature<FitD>(generate)
.addSignature<FitF>(generate)
.addSignature<FitL>(generate)
.addSignature<FitI>(generate)
.addDependency("clamp")
.setArgumentNames({"value", "omin", "omax", "nmin", "nmax"})
.setConstantFold(false)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Fit the first argument to the output range by "
"first clamping the value between the second and third input range "
"arguments and then remapping the result to the output range fourth and "
"fifth arguments")
.get();
}
inline FunctionGroup::UniquePtr axrand(const FunctionOptions& op)
{
struct Rand
{
static double rand(const std::mt19937_64::result_type* seed)
{
using ThreadLocalEngineContainer =
tbb::enumerable_thread_specific<std::mt19937_64>;
static ThreadLocalEngineContainer ThreadLocalEngines;
static std::uniform_real_distribution<double> Generator(0.0,1.0);
std::mt19937_64& engine = ThreadLocalEngines.local();
if (seed) {
engine.seed(static_cast<std::mt19937_64::result_type>(*seed));
}
return Generator(engine);
}
static double rand() { return Rand::rand(nullptr); }
static double rand(double seed)
{
const std::mt19937_64::result_type hash =
static_cast<std::mt19937_64::result_type>(std::hash<double>()(seed));
return Rand::rand(&hash);
}
static double rand(int64_t seed)
{
const std::mt19937_64::result_type hash =
static_cast<std::mt19937_64::result_type>(seed);
return Rand::rand(&hash);
}
};
return FunctionBuilder("rand")
.addSignature<double()>((double(*)())(Rand::rand))
.addSignature<double(double)>((double(*)(double))(Rand::rand))
.addSignature<double(int64_t)>((double(*)(int64_t))(Rand::rand))
.setArgumentNames({"seed"})
// We can't constant fold rand even if it's been called with a constant as
// it will leave the generator in a different state in comparison to other
// threads and, as it relies on an internal state, doesn't respect branching
// etc. We also can't use a different generate for constant calls as subsequent
// calls to rand() without an argument won't know to advance the generator.
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Creates a random number based on the provided "
"seed. The number will be in the range of 0 to 1. The same number is "
"produced for the same seed. Note that if rand is called without a seed "
"the previous state of the random number generator is advanced for the "
"currently processing element. This state is determined by the last call to "
"rand() with a given seed. If rand is not called with a seed, the generator "
"advances continuously across different elements which can produce non-"
"deterministic results. It is important that rand is always called with a "
"seed at least once for deterministic results.")
.get();
}
inline FunctionGroup::UniquePtr axrand32(const FunctionOptions& op)
{
struct Rand
{
static double rand(const std::mt19937::result_type* seed)
{
using ThreadLocalEngineContainer =
tbb::enumerable_thread_specific<std::mt19937>;
// Obtain thread-local engine (or create if it doesn't exist already).
static ThreadLocalEngineContainer ThreadLocalEngines;
static std::uniform_real_distribution<double> Generator(0.0,1.0);
std::mt19937& engine = ThreadLocalEngines.local();
if (seed) {
engine.seed(static_cast<std::mt19937::result_type>(*seed));
}
// Once we have seeded the random number generator, we then evaluate it,
// which returns a floating point number in the range [0,1)
return Generator(engine);
}
static double rand() { return Rand::rand(nullptr); }
static double rand(double seed)
{
// We initially hash the double-precision seed with `std::hash`. The
// important thing about the hash is that it produces a "reliable" hash value,
// taking into account a number of special cases for floating point numbers
// (e.g. -0 and +0 must return the same hash value, etc). Other than these
// special cases, this function will usually just copy the binary
// representation of a float into the resultant `size_t`
const size_t hash = std::hash<double>()(seed);
// Now that we have a reliable hash (with special floating-point cases taken
// care of), we proceed to use this hash to seed a random number generator.
// The generator takes an unsigned int, which is not guaranteed to be the
// same size as size_t.
//
// So, we must convert it. I should note that the OpenVDB math libraries will
// do this for us, but its implementation static_casts `size_t` to `unsigned int`,
// and because `std::hash` returns a binary copy of the original
// double-precision number in almost all cases, this ends up producing noticable
// patterns in the result (e.g. by truncating the upper 4 bytes, values of 1.0,
// 2.0, 3.0, and 4.0 all return the same hash value because their lower 4 bytes
// are all zero).
//
// We use the `hashToSeed` function to reduce our `size_t` to an `unsigned int`,
// whilst taking all bits in the `size_t` into account.
// On some architectures std::uint_fast32_t may be size_t, but we always hash to
// be consistent.
const std::mt19937::result_type uintseed =
static_cast<std::mt19937::result_type>(hashToSeed<uint32_t>(hash));
return Rand::rand(&uintseed);
}
static double rand(int32_t seed)
{
const std::mt19937::result_type uintseed =
static_cast<std::mt19937::result_type>(seed);
return Rand::rand(&uintseed);
}
};
return FunctionBuilder("rand32")
.addSignature<double()>((double(*)())(Rand::rand))
.addSignature<double(double)>((double(*)(double))(Rand::rand))
.addSignature<double(int32_t)>((double(*)(int32_t))(Rand::rand))
.setArgumentNames({"seed"})
// We can't constant fold rand even if it's been called with a constant as
// it will leave the generator in a different state in comparison to other
// threads and, as it relies on an internal state, doesn't respect branching
// etc. We also can't use a different generate for constant calls as subsequent
// calls to rand() without an argument won't know to advance the generator.
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Creates a random number based on the provided 32 bit "
"seed. The number will be in the range of 0 to 1. The same number is "
"produced for the same seed. "
"NOTE: This function does not share the same random number generator as "
"rand(). rand32() may provide a higher throughput on some architectures, "
"but will produce different results to rand(). "
"NOTE: If rand32 is called without a seed the previous state of the random "
"number generator is advanced for the currently processing element. This "
"state is determined by the last call to rand32() with a given seed. If "
"rand32 is not called with a seed, the generator advances continuously "
"across different elements which can produce non-deterministic results. "
"It is important that rand32 is always called with a seed at least once "
"for deterministic results.")
.get();
}
inline FunctionGroup::UniquePtr axsign(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// int r = (T(0) < val) - (val < T(0));
assert(args.size() == 1);
llvm::Value* arg = args.front();
llvm::Type* type = arg->getType();
llvm::Value* zero;
if (type->isIntegerTy()) {
zero = llvm::ConstantInt::get(type, static_cast<uint64_t>(0), /*signed*/true);
}
else {
assert(type->isFloatingPointTy());
zero = llvm::ConstantFP::get(type, static_cast<double>(0.0));
}
llvm::Value* c1 = binaryOperator(zero, arg, ast::tokens::LESSTHAN, B);
c1 = arithmeticConversion(c1, LLVMType<int32_t>::get(B.getContext()), B);
llvm::Value* c2 = binaryOperator(arg, zero, ast::tokens::LESSTHAN, B);
c2 = arithmeticConversion(c2, LLVMType<int32_t>::get(B.getContext()), B);
llvm::Value* r = binaryOperator(c1, c2, ast::tokens::MINUS, B);
return arithmeticConversion(r, LLVMType<int32_t>::get(B.getContext()), B);
};
return FunctionBuilder("sign")
.addSignature<int32_t(double)>(generate)
.addSignature<int32_t(float)>(generate)
.addSignature<int32_t(int64_t)>(generate)
.addSignature<int32_t(int32_t)>(generate)
.setArgumentNames({"n"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Implements signum, determining if the input is negative, zero "
"or positive. Returns -1 for a negative number, 0 for the number zero, and +1 "
"for a positive number. Note that this function does not check the sign of "
"floating point +/-0.0 values. See signbit().")
.get();
}
inline FunctionGroup::UniquePtr axsignbit(const FunctionOptions& op)
{
return FunctionBuilder("signbit")
.addSignature<bool(double)>((bool(*)(double))(std::signbit))
.addSignature<bool(float)>((bool(*)(float))(std::signbit))
.setArgumentNames({"n"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Determines if the given floating point number input is negative. "
"Returns true if arg is negative, false otherwise. Will return true for -0.0, "
"false for +0.0")
.get();
}
inline FunctionGroup::UniquePtr axtruncatemod(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
assert(args.size() == 2);
return binaryOperator(args[0], args[1], ast::tokens::MODULO, B);
};
return FunctionBuilder("truncatemod")
.addSignature<double(double,double)>(generate)
.addSignature<float(float,float)>(generate)
.addSignature<int64_t(int64_t,int64_t)>(generate)
.addSignature<int32_t(int32_t,int32_t)>(generate)
.addSignature<int16_t(int16_t,int16_t)>(generate)
.setArgumentNames({"dividend", "divisor"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Truncated modulo, where the result of the division operator "
"on (dividend / divisor) is truncated. The remainder is thus calculated with "
"D - d * trunc(D/d). This is equal to the C/C++ % implementation. This is NOT "
"equal to a%b in AX. See floormod(), euclideanmod().")
.get();
}
inline FunctionGroup::UniquePtr axfloormod(const FunctionOptions& op)
{
static auto ifmod = [](auto D, auto d) -> auto
{
using ValueType = decltype(D);
auto r = D % d; // tmod
if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d;
return ValueType(r);
};
static auto ffmod = [](auto D, auto d) -> auto
{
auto r = std::fmod(D, d);
if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d;
return r;
};
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
assert(args.size() == 2);
llvm::Value* D = args[0];
llvm::Value* d = args[1];
// tmod
llvm::Value* r = binaryOperator(D, d, ast::tokens::MODULO, B);
llvm::Value* zero = llvmConstant(0, D->getType());
llvm::Value* a1 = binaryOperator(r, zero, ast::tokens::MORETHAN, B);
llvm::Value* a2 = binaryOperator(d, zero, ast::tokens::LESSTHAN, B);
a1 = binaryOperator(a1, a2, ast::tokens::AND, B);
llvm::Value* b1 = binaryOperator(r, zero, ast::tokens::LESSTHAN, B);
llvm::Value* b2 = binaryOperator(d, zero, ast::tokens::MORETHAN, B);
b1 = binaryOperator(b1, b2, ast::tokens::AND, B);
a1 = binaryOperator(a1, b1, ast::tokens::OR, B);
llvm::Value* rplus = binaryOperator(r, d, ast::tokens::PLUS, B);
return B.CreateSelect(a1, rplus, r);
};
return FunctionBuilder("floormod")
.addSignature<double(double,double)>(generate, (double(*)(double,double))(ffmod))
.addSignature<float(float,float)>(generate, (float(*)(float,float))(ffmod))
.addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(ifmod))
.addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(ifmod))
.addSignature<int16_t(int16_t,int16_t)>(generate, (int16_t(*)(int16_t,int16_t))(ifmod))
.setArgumentNames({"dividend", "divisor"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Floored modulo, where the result of the division operator "
"on (dividend / divisor) is floored. The remainder is thus calculated with "
"D - d * floor(D/d). This is the implemented modulo % operator of AX. This is "
"equal to the python % implementation. See trucnatemod(), euclideanmod().")
.get();
}
inline FunctionGroup::UniquePtr axeuclideanmod(const FunctionOptions& op)
{
static auto iemod = [](auto D, auto d) -> auto
{
using ValueType = decltype(D);
auto r = D%d;
if (r < 0) {
if (d > 0) r = r + d;
else r = r - d;
}
return ValueType(r);
};
static auto femod = [](auto D, auto d) -> auto
{
auto r = std::fmod(D, d);
if (r < 0) {
if (d > 0) r = r + d;
else r = r - d;
}
return r;
};
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
assert(args.size() == 2);
llvm::Value* D = args[0], *d = args[1];
llvm::Value* r = binaryOperator(D, d, ast::tokens::MODULO, B); // tmod
llvm::Value* zero = llvmConstant(0, D->getType());
llvm::Value* a1 = binaryOperator(d, zero, ast::tokens::MORETHAN, B);
llvm::Value* rplus = binaryOperator(r, d, ast::tokens::PLUS, B);
llvm::Value* rminus = binaryOperator(r, d, ast::tokens::MINUS, B);
llvm::Value* rd = B.CreateSelect(a1, rplus, rminus);
a1 = binaryOperator(r, zero, ast::tokens::LESSTHAN, B);
return B.CreateSelect(a1, rd, r);
};
return FunctionBuilder("euclideanmod")
.addSignature<double(double,double)>(generate, (double(*)(double,double))(femod))
.addSignature<float(float,float)>(generate, (float(*)(float,float))(femod))
.addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(iemod))
.addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(iemod))
.addSignature<int16_t(int16_t,int16_t)>(generate, (int16_t(*)(int16_t,int16_t))(iemod))
.setArgumentNames({"dividend", "divisor"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Euclidean modulo, where by the result of the division operator "
"on (dividend / divisor) is floored or ceiled depending on its sign, guaranteeing "
"that the return value is always positive. The remainder is thus calculated with "
"D - d * (d < 0 ? ceil(D/d) : floor(D/d)). This is NOT equal to a%b in AX. See "
"truncatemod(), floormod().")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Matrix math
inline FunctionGroup::UniquePtr axdeterminant(const FunctionOptions& op)
{
// 3 by 3 determinant
static auto generate3 =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> m1;
arrayUnpack(args[0], m1, B, /*load*/true);
assert(m1.size() == 9);
llvm::Value* e1 = binaryOperator(m1[4], m1[8], ast::tokens::MULTIPLY, B);
llvm::Value* e2 = binaryOperator(m1[5], m1[7], ast::tokens::MULTIPLY, B);
llvm::Value* c0 = binaryOperator(e1, e2, ast::tokens::MINUS, B);
e1 = binaryOperator(m1[5], m1[6], ast::tokens::MULTIPLY, B);
e2 = binaryOperator(m1[3], m1[8], ast::tokens::MULTIPLY, B);
llvm::Value* c1 = binaryOperator(e1, e2, ast::tokens::MINUS, B);
e1 = binaryOperator(m1[3], m1[7], ast::tokens::MULTIPLY, B);
e2 = binaryOperator(m1[4], m1[6], ast::tokens::MULTIPLY, B);
llvm::Value* c2 = binaryOperator(e1, e2, ast::tokens::MINUS, B);
c0 = binaryOperator(m1[0], c0, ast::tokens::MULTIPLY, B);
c1 = binaryOperator(m1[1], c1, ast::tokens::MULTIPLY, B);
c2 = binaryOperator(m1[2], c2, ast::tokens::MULTIPLY, B);
c0 = binaryOperator(c0, c1, ast::tokens::PLUS, B);
c0 = binaryOperator(c0, c2, ast::tokens::PLUS, B);
return c0;
};
// 4 by 4 determinant
static auto generate4 =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> m1;
arrayUnpack(args[0], m1, B, /*load*/true);
assert(m1.size() == 16);
// @note Okay to alloca here as long as embed IR is false
llvm::Value* subMat = B.CreateAlloca(llvm::ArrayType::get(m1.front()->getType(), 9));
std::vector<llvm::Value*> elements;
arrayUnpack(subMat, elements, B, /*load elements*/false);
llvm::Value* result = llvm::ConstantFP::get(m1.front()->getType(), 0.0);
for (size_t i = 0; i < 4; ++i) {
size_t sourceIndex = 0, targetIndex = 0;
for (size_t j = 0; j < 4; ++j) {
for (size_t k = 0; k < 4; ++k) {
if ((k != i) && (j != 0)) {
B.CreateStore(m1[sourceIndex], elements[targetIndex]);
++targetIndex;
}
++sourceIndex;
}
}
llvm::Value* subResult = generate3({subMat}, B);
subResult = binaryOperator(m1[i], subResult, ast::tokens::MULTIPLY, B);
if (i % 2) result = binaryOperator(result, subResult, ast::tokens::MINUS, B);
else result = binaryOperator(result, subResult, ast::tokens::PLUS, B);
}
return result;
};
static auto determinant = [](auto mat) -> auto {
return mat->det();
};
using DeterminantM3D = double(openvdb::math::Mat3<double>*);
using DeterminantM3F = float(openvdb::math::Mat3<float>*);
using DeterminantM4D = double(openvdb::math::Mat4<double>*);
using DeterminantM4F = float(openvdb::math::Mat4<float>*);
return FunctionBuilder("determinant")
.addSignature<DeterminantM3D>(generate3, (DeterminantM3D*)(determinant))
.addSignature<DeterminantM3F>(generate3, (DeterminantM3F*)(determinant))
.addSignature<DeterminantM4D>(generate4, (DeterminantM4D*)(determinant))
.addSignature<DeterminantM4F>(generate4, (DeterminantM4F*)(determinant))
.setArgumentNames({"mat"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the determinant of a matrix.")
.get();
}
inline FunctionGroup::UniquePtr axdiag(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, arg1;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], arg1, B, /*load*/true);
const size_t size = arg1.size();
if (size == 3 || size == 4) {
//vector - convert to diagonal matrix
const size_t dim = size*size;
assert(ptrs.size() == dim);
llvm::Type* type = arg1.front()->getType();
llvm::Value* zero = type->isFloatTy() ? LLVMType<float>::get(B.getContext(), 0.0f)
: LLVMType<double>::get(B.getContext(), 0.0);
for (size_t i = 0, j = 0; i < dim; ++i) {
llvm::Value* m = zero;
if (i % (size + 1) == 0) {
m = arg1[j];
++j;
}
B.CreateStore(m, ptrs[i]);
}
}
else {
// matrix - convert to vector
assert(size == 9 || size == 16);
const size_t dim = size == 9 ? 3 : 4;
assert(ptrs.size() == dim);
for (size_t i = 0; i < dim; ++i) {
B.CreateStore(arg1[i+(i*dim)], ptrs[i]);
}
}
return nullptr;
};
static auto diag = [](auto result, const auto input)
{
using ValueType = typename std::remove_pointer<decltype(input)>::type;
using ResultType = typename std::remove_pointer<decltype(result)>::type;
using ElementT = typename openvdb::ValueTraits<ValueType>::ElementType;
using RElementT = typename openvdb::ValueTraits<ResultType>::ElementType;
static_assert(std::is_same<ElementT, RElementT>::value,
"Input and result arguments for diag are not the same type");
if (openvdb::ValueTraits<ValueType>::IsVec) {
// input is a vec, result is a matrix
const int size = openvdb::ValueTraits<ValueType>::Size;
int element = 0;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
assert(element < openvdb::ValueTraits<ResultType>::Elements);
if (i == j) result->asPointer()[element] = (input->asPointer())[i];
else result->asPointer()[element] = ElementT(0.0);
++element;
}
}
}
else {
assert(openvdb::ValueTraits<ValueType>::IsMat);
// input is a matrix, result is a vec
const int size = openvdb::ValueTraits<ValueType>::Size;
for (int i = 0; i < size; ++i) {
assert(i < openvdb::ValueTraits<ResultType>::Size);
result->asPointer()[i] = input->asPointer()[i+(i*size)];
}
}
};
using DiagV3M3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*);
using DiagV3M3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*);
using DiagV4M4D = void(openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*);
using DiagV4M4F = void(openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*);
using DiagM3V3D = void(openvdb::math::Mat3<double>*, openvdb::math::Vec3<double>*);
using DiagM3V3F = void(openvdb::math::Mat3<float>*, openvdb::math::Vec3<float>*);
using DiagM4V4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec4<double>*);
using DiagM4V4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec4<float>*);
return FunctionBuilder("diag")
.addSignature<DiagV3M3D, true>(generate, (DiagV3M3D*)(diag))
.addSignature<DiagV3M3F, true>(generate, (DiagV3M3F*)(diag))
.addSignature<DiagV4M4D, true>(generate, (DiagV4M4D*)(diag))
.addSignature<DiagV4M4F, true>(generate, (DiagV4M4F*)(diag))
.setArgumentNames({"vec"})
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.addSignature<DiagM3V3D, true>(generate, (DiagM3V3D*)(diag))
.addSignature<DiagM3V3F, true>(generate, (DiagM3V3F*)(diag))
.addSignature<DiagM4V4D, true>(generate, (DiagM4V4D*)(diag))
.addSignature<DiagM4V4F, true>(generate, (DiagM4V4F*)(diag))
.setArgumentNames({"mat"})
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Create a diagonal matrix from a vector, or return the diagonal "
"components of a matrix as a vector.")
.get();
}
inline FunctionGroup::UniquePtr axidentity3(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> elements;
arrayUnpack(args[0], elements, B, /*load elements*/false);
assert(elements.size() == 9);
llvm::Value* zero = LLVMType<float>::get(B.getContext(), 0.0f);
llvm::Value* one = LLVMType<float>::get(B.getContext(), 1.0f);
for (size_t i = 0; i < 9; ++i) {
llvm::Value* m = ((i == 0 || i == 4 || i == 8) ? one : zero);
B.CreateStore(m, elements[i]);
}
return nullptr;
};
return FunctionBuilder("identity3")
.addSignature<void(openvdb::math::Mat3<float>*), true>(generate)
.setConstantFold(false)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the 3x3 identity matrix")
.get();
}
inline FunctionGroup::UniquePtr axidentity4(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> elements;
arrayUnpack(args[0], elements, B, /*load elements*/false);
assert(elements.size() == 16);
llvm::Value* zero = LLVMType<float>::get(B.getContext(), 0.0f);
llvm::Value* one = LLVMType<float>::get(B.getContext(), 1.0f);
for (size_t i = 0; i < 16; ++i) {
llvm::Value* m = ((i == 0 || i == 5 || i == 10 || i == 15) ? one : zero);
B.CreateStore(m, elements[i]);
}
return nullptr;
};
return FunctionBuilder("identity4")
.addSignature<void(openvdb::math::Mat4<float>*), true>(generate)
.setConstantFold(false)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the 4x4 identity matrix")
.get();
}
inline FunctionGroup::UniquePtr axmmmult(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, m1, m2;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], m1, B, /*load*/true);
arrayUnpack(args[2], m2, B, /*load*/true);
assert(m1.size() == 9 || m1.size() == 16);
assert(ptrs.size() == m1.size());
assert(ptrs.size() == m2.size());
const size_t dim = m1.size() == 9 ? 3 : 4;
llvm::Value* e3 = nullptr, *e4 = nullptr;
for (size_t i = 0; i < dim; ++i) {
const size_t row = i*dim;
for (size_t j = 0; j < dim; ++j) {
llvm::Value* e1 = binaryOperator(m1[0+row], m2[j], ast::tokens::MULTIPLY, B);
llvm::Value* e2 = binaryOperator(m1[1+row], m2[dim+j], ast::tokens::MULTIPLY, B);
if (dim >=3) e3 = binaryOperator(m1[2+row], m2[(dim*2)+j], ast::tokens::MULTIPLY, B);
if (dim >=4) e4 = binaryOperator(m1[3+row], m2[(dim*3)+j], ast::tokens::MULTIPLY, B);
e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B);
if (dim >=3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B);
if (dim >=4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B);
B.CreateStore(e1, ptrs[row+j]);
}
}
return nullptr;
};
static auto mmmult = [](auto out, auto mat2, auto mat1) {
*out = (*mat1) * (*mat2);
};
using MMMultM3D = void(openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*);
using MMMultM3F = void(openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*);
using MMMultM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*);
using MMMultM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*);
return FunctionBuilder("mmmult")
.addSignature<MMMultM3D, true>(generate, (MMMultM3D*)(mmmult))
.addSignature<MMMultM3F, true>(generate, (MMMultM3F*)(mmmult))
.addSignature<MMMultM4D, true>(generate, (MMMultM4D*)(mmmult))
.addSignature<MMMultM4F, true>(generate, (MMMultM4F*)(mmmult))
.setArgumentNames({"a", "b"})
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Multiplies two matrices together and returns the result")
.get();
}
inline FunctionGroup::UniquePtr axpolardecompose(const FunctionOptions& op)
{
static auto polardecompose = [](auto in, auto orth, auto symm) -> bool {
bool success = false;
try {
success = openvdb::math::polarDecomposition(*in, *orth, *symm);
}
catch (const openvdb::ArithmeticError&) {
success = false;
}
return success;
};
using PolarDecompositionM3D =
bool(openvdb::math::Mat3<double>*,
openvdb::math::Mat3<double>*,
openvdb::math::Mat3<double>*);
using PolarDecompositionM3F =
bool(openvdb::math::Mat3<float>*,
openvdb::math::Mat3<float>*,
openvdb::math::Mat3<float>*);
return FunctionBuilder("polardecompose")
.addSignature<PolarDecompositionM3D>((PolarDecompositionM3D*)(polardecompose))
.addSignature<PolarDecompositionM3F>((PolarDecompositionM3F*)(polardecompose))
.setArgumentNames({"input", "unitary", "symmetric"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Decompose an invertible 3x3 matrix into its orthogonal (unitary) "
"matrix and symmetric matrix components. If the determinant of the unitary matrix "
"is 1 it is a rotation, otherwise if it is -1 there is some part reflection.")
.get();
}
inline FunctionGroup::UniquePtr axpostscale(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> m1, v1;
arrayUnpack(args[0], m1, B, /*load*/false);
arrayUnpack(args[1], v1, B, /*load*/true);
assert(m1.size() == 16);
assert(v1.size() == 3);
// modify first 3 elements in all mat rows
for (size_t row = 0; row < 4; ++row) {
for (size_t col = 0; col < 3; ++col) {
const size_t idx = (row*4) + col;
assert(idx <= 14);
llvm::Value* m1v = B.CreateLoad(m1[idx]);
m1v = binaryOperator(m1v, v1[col], ast::tokens::MULTIPLY, B);
B.CreateStore(m1v, m1[idx]);
}
}
// @warning this is invalid for embedded IR
return nullptr;
};
static auto postscale = [](auto mat, auto vec) {
mat->postScale(*vec);
};
using PostscaleM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*);
using PostscaleM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*);
return FunctionBuilder("postscale")
.addSignature<PostscaleM4D>(generate, (PostscaleM4D*)(postscale))
.addSignature<PostscaleM4F>(generate, (PostscaleM4F*)(postscale))
.setArgumentNames({"transform", "vec"})
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Post-scale a given matrix by the provided vector.")
.get();
}
inline FunctionGroup::UniquePtr axpretransform(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, m1, v1;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], m1, B, /*load*/true);
arrayUnpack(args[2], v1, B, /*load*/true);
const size_t vec = v1.size();
const size_t dim = (m1.size() == 9 ? 3 : 4);
assert(m1.size() == 9 || m1.size() == 16);
assert(vec == 3 || vec == 4);
assert(ptrs.size() == vec);
// mat * vec
llvm::Value* e3 = nullptr, *e4 = nullptr;
for (size_t i = 0; i < vec; ++i) {
llvm::Value* e1 = binaryOperator(v1[0], m1[0+(i*dim)], ast::tokens::MULTIPLY, B);
llvm::Value* e2 = binaryOperator(v1[1], m1[1+(i*dim)], ast::tokens::MULTIPLY, B);
if (dim >= 3) e3 = binaryOperator(v1[2], m1[2+(i*dim)], ast::tokens::MULTIPLY, B);
if (dim == 4) {
if (vec == 3) e4 = m1[3+(i*dim)];
else if (vec == 4) e4 = binaryOperator(v1[3], m1[3+(i*dim)], ast::tokens::MULTIPLY, B);
}
e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B);
if (e3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B);
if (e4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B);
B.CreateStore(e1, ptrs[i]);
}
return nullptr;
};
static auto transform = [](auto out, auto mat, auto vec) {
*out = mat->pretransform(*vec);
};
using PretransformM3DV3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*, openvdb::math::Vec3<double>*);
using PretransformM3FV3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*, openvdb::math::Vec3<float>*);
using PretransformM4DV3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*);
using PretransformM4FV3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*);
using PretransformM4DV4D = void(openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*, openvdb::math::Vec4<double>*);
using PretransformM4FV4F = void(openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*, openvdb::math::Vec4<float>*);
return FunctionBuilder("pretransform")
.addSignature<PretransformM3DV3D, true>(generate, (PretransformM3DV3D*)(transform))
.addSignature<PretransformM3FV3F, true>(generate, (PretransformM3FV3F*)(transform))
.addSignature<PretransformM4DV3D, true>(generate, (PretransformM4DV3D*)(transform))
.addSignature<PretransformM4FV3F, true>(generate, (PretransformM4FV3F*)(transform))
.addSignature<PretransformM4DV4D, true>(generate, (PretransformM4DV4D*)(transform))
.addSignature<PretransformM4FV4F, true>(generate, (PretransformM4FV4F*)(transform))
.setArgumentNames({"vec", "mat"})
.addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Return the transformed vector by transpose of this matrix. "
"This function is equivalent to pre-multiplying the matrix.")
.get();
}
inline FunctionGroup::UniquePtr axprescale(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> m1, v1;
arrayUnpack(args[0], m1, B, /*load*/false);
arrayUnpack(args[1], v1, B, /*load*/true);
assert(m1.size() == 16);
assert(v1.size() == 3);
// modify first 3 mat rows, all columns
for (size_t row = 0; row < 3; ++row) {
for (size_t col = 0; col < 4; ++col) {
const size_t idx = (row*4) + col;
assert(idx <= 11);
llvm::Value* m1v = B.CreateLoad(m1[idx]);
m1v = binaryOperator(m1v, v1[row], ast::tokens::MULTIPLY, B);
B.CreateStore(m1v, m1[idx]);
}
}
// @warning this is invalid for embedded IR
return nullptr;
};
static auto prescale = [](auto mat, auto vec) {
mat->preScale(*vec);
};
using PrescaleM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*);
using PrescaleM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*);
return FunctionBuilder("prescale")
.addSignature<PrescaleM4D>(generate, (PrescaleM4D*)(prescale))
.addSignature<PrescaleM4F>(generate, (PrescaleM4F*)(prescale))
.setArgumentNames({"transform", "vec"})
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Pre-scale a given matrix by the provided vector.")
.get();
}
inline FunctionGroup::UniquePtr axtrace(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> m1;
arrayUnpack(args[0], m1, B, /*load*/true);
const size_t dim = (m1.size() == 9 ? 3 : 4);
assert(m1.size() == 9 || m1.size() == 16);
llvm::Value* result = binaryOperator(m1[0], m1[1+dim], ast::tokens::PLUS, B);
result = binaryOperator(result, m1[2+(2*dim)], ast::tokens::PLUS, B);
if (dim == 4) {
result = binaryOperator(result, m1[3+(3*dim)], ast::tokens::PLUS, B);
}
return result;
};
static auto trace = [](const auto input) -> auto
{
using MatType = typename std::remove_pointer<decltype(input)>::type;
using ElementT = typename openvdb::ValueTraits<MatType>::ElementType;
ElementT value((*input)(static_cast<int>(0), static_cast<int>(0)));
for (size_t i = 1; i < MatType::numRows(); ++i) {
value += (*input)(static_cast<int>(i), static_cast<int>(i));
}
return value;
};
using TraceM3D = double(openvdb::math::Mat3<double>*);
using TraceM3F = float(openvdb::math::Mat3<float>*);
using TraceM4D = double(openvdb::math::Mat4<double>*);
using TraceM4F = float(openvdb::math::Mat4<float>*);
return FunctionBuilder("trace")
.addSignature<TraceM3D>(generate, (TraceM3D*)(trace))
.addSignature<TraceM3F>(generate, (TraceM3F*)(trace))
.addSignature<TraceM4D>(generate, (TraceM4D*)(trace))
.addSignature<TraceM4F>(generate, (TraceM4F*)(trace))
.setArgumentNames({"mat"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Return the trace of a matrix, the sum of the diagonal elements.")
.get();
}
inline FunctionGroup::UniquePtr axtransform(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, m1, v1;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], v1, B, /*load*/true);
arrayUnpack(args[2], m1, B, /*load*/true);
const size_t vec = v1.size();
const size_t dim = (m1.size() == 9 ? 3 : 4);
assert(m1.size() == 9 || m1.size() == 16);
assert(vec == 3 || vec == 4);
assert(ptrs.size() == vec);
// vec * mat
llvm::Value* e3 = nullptr, *e4 = nullptr;
for (size_t i = 0; i < vec; ++i) {
llvm::Value* e1 = binaryOperator(v1[0], m1[i+(0*dim)], ast::tokens::MULTIPLY, B);
llvm::Value* e2 = binaryOperator(v1[1], m1[i+(1*dim)], ast::tokens::MULTIPLY, B);
if (dim >= 3) e3 = binaryOperator(v1[2], m1[i+(2*dim)], ast::tokens::MULTIPLY, B);
if (dim == 4) {
if (vec == 3) e4 = m1[i+(3*dim)];
else if (vec == 4) e4 = binaryOperator(v1[3], m1[i+(3*dim)], ast::tokens::MULTIPLY, B);
}
e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B);
if (e3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B);
if (e4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B);
B.CreateStore(e1, ptrs[i]);
}
return nullptr;
};
static auto transform = [](auto out, auto vec, auto mat) {
*out = mat->transform(*vec);
};
using TransformV3DM3D = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*);
using TransformV3FM3F = void(openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*);
using TransformV3DM4D = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<double>*, openvdb::math::Mat4<double>*);
using TransformV3FM4F = void(openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*);
using TransformV4DM4D = void(openvdb::math::Vec4<double>*, openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*);
using TransformV4FM4F = void(openvdb::math::Vec4<float>*, openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*);
return FunctionBuilder("transform")
.addSignature<TransformV3DM3D, true>(generate, (TransformV3DM3D*)(transform))
.addSignature<TransformV3FM3F, true>(generate, (TransformV3FM3F*)(transform))
.addSignature<TransformV3DM4D, true>(generate, (TransformV3DM4D*)(transform))
.addSignature<TransformV3FM4F, true>(generate, (TransformV3FM4F*)(transform))
.addSignature<TransformV4DM4D, true>(generate, (TransformV4DM4D*)(transform))
.addSignature<TransformV4FM4F, true>(generate, (TransformV4FM4F*)(transform))
.setArgumentNames({"vec", "mat"})
.addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Return the transformed vector by the provided "
"matrix. This function is equivalent to post-multiplying the matrix, i.e. vec * mult.")
.get();
}
inline FunctionGroup::UniquePtr axtranspose(const FunctionOptions& op)
{
static auto generate =
[](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
std::vector<llvm::Value*> ptrs, m1;
arrayUnpack(args[0], ptrs, B, /*load*/false);
arrayUnpack(args[1], m1, B, /*load*/true);
assert(m1.size() == 9 || m1.size() == 16);
assert(ptrs.size() == m1.size());
const size_t dim = m1.size() == 9 ? 3 : 4;
for (size_t i = 0; i < dim; ++i) {
for (size_t j = 0; j < dim; ++j) {
const size_t source = (i*dim) + j;
const size_t target = (j*dim) + i;
B.CreateStore(m1[source], ptrs[target]);
}
}
return nullptr;
};
static auto transpose = [](auto out, auto in) {
*out = in->transpose();
};
using TransposeM3D = void(openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*);
using TransposeM3F = void(openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*);
using TransposeM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*);
using TransposeM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*);
return FunctionBuilder("transpose")
.addSignature<TransposeM3D, true>(generate, (TransposeM3D*)(transpose))
.addSignature<TransposeM3F, true>(generate, (TransposeM3F*)(transpose))
.addSignature<TransposeM4D, true>(generate, (TransposeM4D*)(transpose))
.addSignature<TransposeM4F, true>(generate, (TransposeM4F*)(transpose))
.setArgumentNames({"mat"})
.addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Returns the transpose of a matrix")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Noise
inline FunctionGroup::UniquePtr axsimplexnoise(const FunctionOptions& op)
{
static auto simplexnoisex = [](double x) -> double {
return SimplexNoise::noise(x, 0.0, 0.0);
};
static auto simplexnoisexy = [](double x, double y) -> double {
return SimplexNoise::noise(x, y, 0.0);
};
static auto simplexnoisexyz = [](double x, double y, double z) -> double {
return SimplexNoise::noise(x, y, z);
};
static auto simplexnoisev = [](const openvdb::math::Vec3<double>* v) -> double {
return SimplexNoise::noise((*v)[0], (*v)[1], (*v)[2]);
};
return FunctionBuilder("simplexnoise")
.addSignature<double(double)>(simplexnoisex)
.setArgumentNames({"x"})
.setConstantFold(false)
.addSignature<double(double, double)>(simplexnoisexy)
.setArgumentNames({"x", "y"})
.setConstantFold(false)
.addSignature<double(double,double,double)>(simplexnoisexyz)
.setArgumentNames({"x", "y", "z"})
.setConstantFold(false)
.addSignature<double(const openvdb::math::Vec3<double>*)>(simplexnoisev)
.setArgumentNames({"pos"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Compute simplex noise at coordinates x, y and z. Coordinates which are "
"not provided will be set to 0.")
.get();
}
inline FunctionGroup::UniquePtr axcurlsimplexnoise(const FunctionOptions& op)
{
using CurlSimplexNoiseV3D = void(double(*)[3], const double(*)[3]);
using CurlSimplexNoiseD = void(double(*)[3], double, double, double);
return FunctionBuilder("curlsimplexnoise")
.addSignature<CurlSimplexNoiseV3D, true>(
(CurlSimplexNoiseV3D*)(openvdb::ax::math::curlnoise<SimplexNoise>))
.setArgumentNames({"pos"})
.addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.addSignature<CurlSimplexNoiseD, true>(
(CurlSimplexNoiseD*)(openvdb::ax::math::curlnoise<SimplexNoise>))
.setArgumentNames({"pos"})
.addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::InlineHint)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Generates divergence-free 3D noise, computed using a "
"curl function on Simplex Noise.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Trig/Hyperbolic
/// @todo Depending on the platform, some of these methods may be available though
/// LLVM as "intrinsics". To avoid conflicts, we currently only expose the C
/// bindings. We should perhaps override the C Bindings if the method exists
/// in LLVM, so long as it's clear that these methods may produce different
/// results from stdlib.
/// @note See the following LLVM files for some details:
/// Analysis/TargetLibraryInfo.def
/// Analysis/ConstantFolding.cpp
/// Analysis/TargetLibraryInfo.cpp
///
DEFINE_AX_C_FP_BINDING(acos, "Computes the principal value of the arc cosine of the input.")
DEFINE_AX_C_FP_BINDING(acosh, "Computes the inverse hyperbolic cosine of the input.")
DEFINE_AX_C_FP_BINDING(asin, "Computes the principal value of the arc sine of the input.")
DEFINE_AX_C_FP_BINDING(asinh, "Computes the inverse hyperbolic sine of the input.")
DEFINE_AX_C_FP_BINDING(atan, "Computes the principal value of the arc tangent of the input.")
DEFINE_AX_C_FP_BINDING(atanh, "Computes the inverse hyperbolic tangent of the input.")
DEFINE_AX_C_FP_BINDING(cosh, "Computes the hyperbolic cosine of the input.")
DEFINE_AX_C_FP_BINDING(sinh, "Computes the hyperbolic sine of the input.")
DEFINE_AX_C_FP_BINDING(tanh, "Computes the hyperbolic tangent of the input.")
inline FunctionGroup::UniquePtr axtan(const FunctionOptions& op)
{
// @todo consider using this IR implementation over std::tan, however
// we then lose constant folding (as results don't match). Ideally
// this ir implementation should exist at compile time as a valid
// function for constant folding
//
// static auto generate =
// [](const std::vector<llvm::Value*>& args,
// const std::unordered_map<std::string, llvm::Value*>&,
// llvm::IRBuilder<>& B) -> llvm::Value*
// {
// llvm::Module* M = B.GetInsertBlock()->getParent()->getParent();
// llvm::Type* type = args[0]->getType();
// llvm::Function* sinFunction =
// llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::sin, type);
// llvm::Function* cosFunction =
// llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::cos, type);
// llvm::Value* sin = B.CreateCall(sinFunction, args[0]);
// llvm::Value* cos = B.CreateCall(cosFunction, args[0]);
// return binaryOperator(sin, cos, ast::tokens::DIVIDE, B);
// };
return FunctionBuilder("tan")
.addSignature<double(double)>((double(*)(double))(std::tan))
.addSignature<float(float)>((float(*)(float))(std::tan))
.setArgumentNames({"n"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Computes the tangent of arg (measured in radians).")
.get();
}
inline FunctionGroup::UniquePtr axatan2(const FunctionOptions& op)
{
return FunctionBuilder("atan2")
.addSignature<double(double,double)>((double(*)(double,double))(std::atan2))
.addSignature<float(float,float)>((float(*)(float,float))(std::atan2))
.setArgumentNames({"y", "x"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Computes the arc tangent of y/x using the signs of arguments "
"to determine the correct quadrant.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// String
inline FunctionGroup::UniquePtr axatoi(const FunctionOptions& op)
{
// WARNING: decltype removes the throw identifer from atoi. We should
// use this are automatically update the function attributes as appropriate
return FunctionBuilder("atoi")
.addSignature<decltype(std::atoi)>(std::atoi)
.setArgumentNames({"str"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Parses the string input interpreting its "
"content as an integral number, which is returned as a value of type int.")
.get();
}
inline FunctionGroup::UniquePtr axatof(const FunctionOptions& op)
{
// WARNING: decltype removes the throw identifer from atof. We should
// use this are automatically update the function attributes as appropriate
return FunctionBuilder("atof")
.addSignature<decltype(std::atof)>(std::atof)
.setArgumentNames({"str"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Parses the string input, interpreting its "
"content as a floating point number and returns its value as a double.")
.get();
}
inline FunctionGroup::UniquePtr axhash(const FunctionOptions& op)
{
static auto hash = [](const AXString* axstr) -> int64_t {
const std::string str(axstr->ptr, axstr->size);
return static_cast<int64_t>(std::hash<std::string>{}(str));
};
return FunctionBuilder("hash")
.addSignature<int64_t(const AXString*)>((int64_t(*)(const AXString*))(hash))
.setArgumentNames({"str"})
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::NoUnwind)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(op.mConstantFoldCBindings)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Return a hash of the provided string.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Utility
inline FunctionGroup::UniquePtr axprint(const FunctionOptions& op)
{
static auto print = [](auto v) { std::cout << v << std::endl; };
static auto printv = [](auto* v) { std::cout << *v << std::endl; };
static auto printstr = [](const AXString* axstr) {
const std::string str(axstr->ptr, axstr->size);
std::cout << str << std::endl;
};
return FunctionBuilder("print")
.addSignature<void(double)>((void(*)(double))(print))
.addSignature<void(float)>((void(*)(float))(print))
.addSignature<void(int64_t)>((void(*)(int64_t))(print))
.addSignature<void(int32_t)>((void(*)(int32_t))(print))
.setArgumentNames({"n"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(false /*never cf*/)
.addSignature<void(const AXString*)>((void(*)(const AXString*))(printstr))
.addSignature<void(openvdb::math::Vec2<int32_t>*)>((void(*)(openvdb::math::Vec2<int32_t>*))(printv))
.addSignature<void(openvdb::math::Vec2<float>*)>((void(*)(openvdb::math::Vec2<float>*))(printv))
.addSignature<void(openvdb::math::Vec2<double>*)>((void(*)(openvdb::math::Vec2<double>*))(printv))
.addSignature<void(openvdb::math::Vec3<int32_t>*)>((void(*)(openvdb::math::Vec3<int32_t>*))(printv))
.addSignature<void(openvdb::math::Vec3<float>*)>((void(*)(openvdb::math::Vec3<float>*))(printv))
.addSignature<void(openvdb::math::Vec3<double>*)>((void(*)(openvdb::math::Vec3<double>*))(printv))
.addSignature<void(openvdb::math::Vec4<int32_t>*)>((void(*)(openvdb::math::Vec4<int32_t>*))(printv))
.addSignature<void(openvdb::math::Vec4<float>*)>((void(*)(openvdb::math::Vec4<float>*))(printv))
.addSignature<void(openvdb::math::Vec4<double>*)>((void(*)(openvdb::math::Vec4<double>*))(printv))
.addSignature<void(openvdb::math::Mat3<float>*)>((void(*)(openvdb::math::Mat3<float>*))(printv))
.addSignature<void(openvdb::math::Mat3<double>*)>((void(*)(openvdb::math::Mat3<double>*))(printv))
.addSignature<void(openvdb::math::Mat4<float>*)>((void(*)(openvdb::math::Mat4<float>*))(printv))
.addSignature<void(openvdb::math::Mat4<double>*)>((void(*)(openvdb::math::Mat4<double>*))(printv))
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.setArgumentNames({"n"})
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.addFunctionAttribute(llvm::Attribute::AlwaysInline)
.setConstantFold(false /*never cf*/)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Prints the input to the standard output stream. "
"Warning: This will be run for every element.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Custom
inline FunctionGroup::UniquePtr ax_external(const FunctionOptions& op)
{
static auto find = [](auto out, const void* const data, const AXString* const name)
{
using ValueType = typename std::remove_pointer<decltype(out)>::type;
const ax::CustomData* const customData =
static_cast<const ax::CustomData*>(data);
const std::string nameStr(name->ptr, name->size);
const TypedMetadata<ValueType>* const metaData =
customData->getData<TypedMetadata<ValueType>>(nameStr);
*out = (metaData ? metaData->value() : zeroVal<ValueType>());
};
using FindF = void(float*, const void* const, const AXString* const);
using FindV3F = void(openvdb::math::Vec3<float>*, const void* const, const AXString* const);
return FunctionBuilder("_external")
.addSignature<FindF>((FindF*)(find))
.addSignature<FindV3F>((FindV3F*)(find))
.setArgumentNames({"str", "custom_data", "result"})
.addParameterAttribute(0, llvm::Attribute::NoAlias)
.addParameterAttribute(0, llvm::Attribute::WriteOnly)
.addParameterAttribute(1, llvm::Attribute::ReadOnly)
.addParameterAttribute(2, llvm::Attribute::ReadOnly)
.setConstantFold(false)
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Internal function for looking up a custom float value.")
.get();
}
inline FunctionGroup::UniquePtr axexternal(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out the custom data from the parent function
llvm::Function* compute = B.GetInsertBlock()->getParent();
assert(compute);
assert(std::string(compute->getName()).rfind("ax.compute", 0) == 0);
llvm::Value* arg = extractArgument(compute, 0);
assert(arg);
assert(arg->getName() == "custom_data");
std::vector<llvm::Value*> inputs;
inputs.reserve(2 + args.size());
inputs.emplace_back(insertStaticAlloca(B, LLVMType<float>::get(B.getContext())));
inputs.emplace_back(arg);
inputs.insert(inputs.end(), args.begin(), args.end());
ax_external(op)->execute(inputs, B);
return B.CreateLoad(inputs.front());
};
return FunctionBuilder("external")
.addSignature<float(const AXString*)>(generate)
.setArgumentNames({"str"})
.addDependency("_external")
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::ReadOnly)
.addFunctionAttribute(llvm::Attribute::NoRecurse)
.setConstantFold(false)
.setEmbedIR(true) // always embed as we pass through function param "custom_data"
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Find a custom user parameter with a given name of type 'float' "
"in the Custom data provided to the AX compiler. If the data can not be found, "
"or is not of the expected type 0.0f is returned.")
.get();
}
inline FunctionGroup::UniquePtr axexternalv(const FunctionOptions& op)
{
auto generate =
[op](const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) -> llvm::Value*
{
// Pull out the custom data from the parent function
llvm::Function* compute = B.GetInsertBlock()->getParent();
assert(compute);
assert(std::string(compute->getName()).rfind("ax.compute", 0) == 0);
llvm::Value* arg = extractArgument(compute, 0);
assert(arg);
assert(arg->getName() == "custom_data");
std::vector<llvm::Value*> inputs;
inputs.reserve(2 + args.size());
inputs.emplace_back(insertStaticAlloca(B, LLVMType<float[3]>::get(B.getContext())));
inputs.emplace_back(arg);
inputs.insert(inputs.end(), args.begin(), args.end());
ax_external(op)->execute(inputs, B);
return inputs.front();
};
return FunctionBuilder("externalv")
.addSignature<openvdb::math::Vec3<float>*(const AXString*)>(generate)
.setArgumentNames({"str"})
.addDependency("_external")
.addParameterAttribute(0, llvm::Attribute::ReadOnly)
.setConstantFold(false)
.setEmbedIR(true) // always embed as we pass through function param "custom_data"
.setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C)
.setDocumentation("Find a custom user parameter with a given name of type 'vector float' "
"in the Custom data provided to the AX compiler. If the data can not be found, or is "
"not of the expected type { 0.0f, 0.0f, 0.0f } is returned.")
.get();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void insertStandardFunctions(FunctionRegistry& registry,
const FunctionOptions* options)
{
const bool create = options && !options->mLazyFunctions;
auto add = [&](const std::string& name,
const FunctionRegistry::ConstructorT creator,
const bool internal = false)
{
if (create) registry.insertAndCreate(name, creator, *options, internal);
else registry.insert(name, creator, internal);
};
// llvm instrinsics
add("ceil", llvm_ceil);
add("cos", llvm_cos);
add("exp2", llvm_exp2);
add("exp", llvm_exp);
add("fabs", llvm_fabs);
add("floor", llvm_floor);
add("log10", llvm_log10);
add("log2", llvm_log2);
add("log", llvm_log);
add("pow", llvm_pow);
add("round", llvm_round);
add("sin", llvm_sin);
add("sqrt", llvm_sqrt);
// math
add("abs", axabs);
add("cbrt", axcbrt);
add("clamp", axclamp);
add("cross", axcross);
add("dot", axdot);
add("euclideanmod", axeuclideanmod);
add("fit", axfit);
add("floormod", axfloormod);
add("length", axlength);
add("lengthsq", axlengthsq);
add("lerp", axlerp);
add("max", axmax);
add("min", axmin);
add("normalize", axnormalize);
add("rand", axrand);
add("rand32", axrand32);
add("sign", axsign);
add("signbit", axsignbit);
add("truncatemod", axtruncatemod);
// matrix math
add("determinant", axdeterminant);
add("diag", axdiag);
add("identity3", axidentity3);
add("identity4", axidentity4);
add("mmmult", axmmmult, true);
add("polardecompose", axpolardecompose);
add("postscale", axpostscale);
add("prescale", axprescale);
add("pretransform", axpretransform);
add("trace", axtrace);
add("transform", axtransform);
add("transpose", axtranspose);
// noise
add("simplexnoise", axsimplexnoise);
add("curlsimplexnoise", axcurlsimplexnoise);
// trig
add("acos", axacos);
add("acosh", axacosh);
add("asin", axasin);
add("asinh", axasinh);
add("atan", axatan);
add("atan2", axatan2);
add("atanh", axatanh);
add("cosh", axcosh);
add("sinh", axsinh);
add("tan", axtan);
add("tanh", axtanh);
// string
add("atoi", axatoi);
add("atof", axatof);
add("hash", axhash);
// util
add("print", axprint);
// custom
add("_external", ax_external, true);
add("external", axexternal);
add("externalv", axexternalv);
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 106,984 | C++ | 44.955756 | 126 | 0.60223 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Types.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/Types.cc
///
/// @authors Nick Avramoussis
///
#include "Types.h"
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
/// @brief Returns an llvm IntegerType given a requested size and context
/// @param size The number of bits of the integer type
/// @param C The LLVMContext to request the Type from.
///
llvm::IntegerType*
llvmIntType(const uint32_t size, llvm::LLVMContext& C)
{
switch (size) {
case 1 : return llvm::cast<llvm::IntegerType>(LLVMType<bool>::get(C));
case 8 : return llvm::cast<llvm::IntegerType>(LLVMType<int8_t>::get(C));
case 16 : return llvm::cast<llvm::IntegerType>(LLVMType<int16_t>::get(C));
case 32 : return llvm::cast<llvm::IntegerType>(LLVMType<int32_t>::get(C));
case 64 : return llvm::cast<llvm::IntegerType>(LLVMType<int64_t>::get(C));
default : return llvm::Type::getIntNTy(C, size);
}
}
/// @brief Returns an llvm floating point Type given a requested size and context
/// @param size The size of the float to request, i.e. float - 32, double - 64 etc.
/// @param C The LLVMContext to request the Type from.
///
llvm::Type*
llvmFloatType(const uint32_t size, llvm::LLVMContext& C)
{
switch (size) {
case 32 : return LLVMType<float>::get(C);
case 64 : return LLVMType<double>::get(C);
default : OPENVDB_THROW(AXCodeGenError,
"Invalid float size requested from LLVM Context");
}
}
/// @brief Returns an llvm type representing a type defined by a string.
/// @note For string types, this function returns the element type, not the
/// object type! The llvm type representing a char block of memory
/// is LLVMType<char*>::get(C);
/// @param type The name of the type to request.
/// @param C The LLVMContext to request the Type from.
///
llvm::Type*
llvmTypeFromToken(const ast::tokens::CoreType& type,
llvm::LLVMContext& C)
{
switch (type) {
case ast::tokens::BOOL : return LLVMType<bool>::get(C);
case ast::tokens::INT16 : return LLVMType<int16_t>::get(C);
case ast::tokens::INT32 : return LLVMType<int32_t>::get(C);
case ast::tokens::INT64 : return LLVMType<int64_t>::get(C);
case ast::tokens::FLOAT : return LLVMType<float>::get(C);
case ast::tokens::DOUBLE : return LLVMType<double>::get(C);
case ast::tokens::VEC2I : return LLVMType<int32_t[2]>::get(C);
case ast::tokens::VEC2F : return LLVMType<float[2]>::get(C);
case ast::tokens::VEC2D : return LLVMType<double[2]>::get(C);
case ast::tokens::VEC3I : return LLVMType<int32_t[3]>::get(C);
case ast::tokens::VEC3F : return LLVMType<float[3]>::get(C);
case ast::tokens::VEC3D : return LLVMType<double[3]>::get(C);
case ast::tokens::VEC4I : return LLVMType<int32_t[4]>::get(C);
case ast::tokens::VEC4F : return LLVMType<float[4]>::get(C);
case ast::tokens::VEC4D : return LLVMType<double[4]>::get(C);
case ast::tokens::MAT3F : return LLVMType<float[9]>::get(C);
case ast::tokens::MAT3D : return LLVMType<double[9]>::get(C);
case ast::tokens::MAT4F : return LLVMType<float[16]>::get(C);
case ast::tokens::MAT4D : return LLVMType<double[16]>::get(C);
case ast::tokens::STRING : return LLVMType<AXString>::get(C);
case ast::tokens::UNKNOWN :
default :
OPENVDB_THROW(AXCodeGenError,
"Token type not recognised in request for LLVM type");
}
}
ast::tokens::CoreType
tokenFromLLVMType(const llvm::Type* type)
{
if (type->isPointerTy()) {
type = type->getPointerElementType();
}
if (type->isIntegerTy(1)) return ast::tokens::BOOL;
if (type->isIntegerTy(16)) return ast::tokens::INT16;
if (type->isIntegerTy(32)) return ast::tokens::INT32;
if (type->isIntegerTy(64)) return ast::tokens::INT64;
if (type->isFloatTy()) return ast::tokens::FLOAT;
if (type->isDoubleTy()) return ast::tokens::DOUBLE;
if (type->isArrayTy()) {
const ast::tokens::CoreType elementType =
tokenFromLLVMType(type->getArrayElementType());
const size_t size = type->getArrayNumElements();
if (size == 2) {
if (elementType == ast::tokens::INT32) return ast::tokens::VEC2I;
if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC2F;
if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC2D;
}
else if (size == 3) {
if (elementType == ast::tokens::INT32) return ast::tokens::VEC3I;
if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC3F;
if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC3D;
}
else if (size == 4) {
if (elementType == ast::tokens::INT32) return ast::tokens::VEC4I;
if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC4F;
if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC4D;
}
else if (size == 9) {
if (elementType == ast::tokens::FLOAT) return ast::tokens::MAT3F;
if (elementType == ast::tokens::DOUBLE) return ast::tokens::MAT3D;
}
else if (size == 16) {
if (elementType == ast::tokens::FLOAT) return ast::tokens::MAT4F;
if (elementType == ast::tokens::DOUBLE) return ast::tokens::MAT4D;
}
}
if (type == LLVMType<AXString>::get(type->getContext())) {
return ast::tokens::STRING;
}
return ast::tokens::UNKNOWN;
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 5,893 | C++ | 40.801418 | 84 | 0.61344 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionTypes.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file codegen/FunctionTypes.cc
#include "FunctionTypes.h"
#include "Types.h"
#include "Utils.h"
#include "../Exceptions.h"
#include <openvdb/util/Name.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Support/raw_os_ostream.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
namespace {
inline void
printType(const llvm::Type* type, llvm::raw_os_ostream& stream, const bool axTypes)
{
const ast::tokens::CoreType token =
axTypes ? tokenFromLLVMType(type) : ast::tokens::UNKNOWN;
if (token == ast::tokens::UNKNOWN) type->print(stream);
else stream << ast::tokens::typeStringFromToken(token);
}
inline void
printTypes(llvm::raw_os_ostream& stream,
const std::vector<llvm::Type*>& types,
const std::vector<const char*>& names = {},
const std::string sep = "; ",
const bool axTypes = false)
{
if (types.empty()) return;
auto typeIter = types.cbegin();
std::vector<const char*>::const_iterator nameIter;
if (!names.empty()) nameIter = names.cbegin();
for (; typeIter != types.cend() - 1; ++typeIter) {
printType(*typeIter, stream, axTypes);
if (!names.empty() && nameIter != names.cend()) {
if (*nameIter && (*nameIter)[0] != '\0') {
stream << ' ' << *nameIter;
}
++nameIter;
}
stream << sep;
}
printType(*typeIter, stream, axTypes);
if (!names.empty() && nameIter != names.cend()) {
if (*nameIter && (*nameIter)[0] != '\0') {
stream << ' ' << *nameIter;
}
}
}
}
void
printSignature(std::ostream& os,
const std::vector<llvm::Type*>& signature,
const llvm::Type* returnType,
const char* name,
const std::vector<const char*>& names,
const bool axTypes)
{
llvm::raw_os_ostream stream(os);
printType(returnType, stream, axTypes);
if (name && name[0] != '\0') {
stream << " " << name;
}
stream << '(';
printTypes(stream, signature, names, "; ", axTypes);
stream << ')';
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
llvm::Function*
Function::create(llvm::LLVMContext& C, llvm::Module* M) const
{
if (M) {
if (llvm::Function* function = M->getFunction(this->symbol())) {
return function;
}
}
std::vector<llvm::Type*> parms;
parms.reserve(this->size());
llvm::Type* ret = this->types(parms, C);
llvm::FunctionType* type =
llvm::FunctionType::get(ret, parms,
false); // varargs
llvm::Function* function =
llvm::Function::Create(type,
llvm::Function::ExternalLinkage,
this->symbol(),
M);
function->setAttributes(this->flattenAttrs(C));
return function;
}
llvm::Value*
Function::call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast) const
{
llvm::BasicBlock* block = B.GetInsertBlock();
assert(block);
llvm::Function* currentFunction = block->getParent();
assert(currentFunction);
llvm::Module* M = currentFunction->getParent();
assert(M);
llvm::Function* function = this->create(B.getContext(), M);
std::vector<llvm::Value*> inputs(args);
if (cast) {
std::vector<llvm::Type*> types;
this->types(types, B.getContext());
this->cast(inputs, types, B);
}
return B.CreateCall(function, inputs);
}
Function::SignatureMatch
Function::match(const std::vector<llvm::Type*>& inputs, llvm::LLVMContext& C) const
{
// these checks mean we can design the match function signature to not
// require the llvm context and instead pull it out of the type vector
// which is guaranteed to not be empty
if (inputs.size() != this->size()) return None;
if (inputs.empty() && this->size() == 0) return Explicit;
assert(!inputs.empty());
//llvm::LLVMContext& C = inputs.front()->getContext();
std::vector<llvm::Type*> signature;
this->types(signature, C);
if (inputs == signature) return Explicit;
llvm::Type* strType = LLVMType<AXString>::get(C);
// try implicit - signature should not be empty here
for (size_t i = 0; i < signature.size(); ++i) {
llvm::Type* from = inputs[i];
llvm::Type* to = signature[i];
// if exactly matching, continue
if (from == to) continue;
// if arg is a ptr and is not marked as readonly, fail - memory will be modified
if (to->isPointerTy() && !this->hasParamAttribute(i,
llvm::Attribute::AttrKind::ReadOnly)) return Size;
// compare contained types if both are pointers
if (from->isPointerTy() && to->isPointerTy()) {
from = from->getContainedType(0);
to = to->getContainedType(0);
}
// allow for string->char*. Note that this is only allowed from inputs->signature
if (from == strType && to == LLVMType<char>::get(C)) continue;
if (!isValidCast(from, to)) return Size;
}
return Implicit;
}
void
Function::print(llvm::LLVMContext& C,
std::ostream& os,
const char* name,
const bool axTypes) const
{
std::vector<llvm::Type*> current;
llvm::Type* ret = this->types(current, C);
std::vector<const char*> names;
names.reserve(this->size());
for (size_t i = 0; i < this->size(); ++i) {
names.emplace_back(this->argName(i));
}
printSignature(os, current, ret, name, names, axTypes);
}
void
Function::cast(std::vector<llvm::Value*>& args,
const std::vector<llvm::Type*>& types,
llvm::IRBuilder<>& B)
{
llvm::LLVMContext& C = B.getContext();
for (size_t i = 0; i < args.size(); ++i) {
if (i >= types.size()) break;
llvm::Value*& value = args[i];
llvm::Type* type = value->getType();
if (type->isIntegerTy() || type->isFloatingPointTy()) {
if (types[i]->isIntegerTy(1)) {
// assume boolean target value
value = boolComparison(value, B);
}
else {
value = arithmeticConversion(value, types[i], B);
}
}
else if (type->getContainedType(0)->isArrayTy()) {
llvm::Type* arrayType = getBaseContainedType(types[i]);
value = arrayCast(value, arrayType->getArrayElementType(), B);
}
else {
if (types[i] == LLVMType<char*>::get(C)) {
llvm::Type* strType = LLVMType<AXString>::get(C);
if (type->getContainedType(0) == strType) {
value = B.CreateStructGEP(strType, value, 0); // char**
value = B.CreateLoad(value); // char*
}
}
}
}
}
llvm::AttributeList
Function::flattenAttrs(llvm::LLVMContext& C) const
{
if (!mAttributes) return llvm::AttributeList();
auto buildSetFromKinds = [&C](llvm::AttrBuilder& ab,
const std::vector<llvm::Attribute::AttrKind>& kinds)
-> llvm::AttributeSet {
for (auto& attr : kinds) {
ab.addAttribute(attr);
}
const llvm::AttributeSet set = llvm::AttributeSet::get(C, ab);
ab.clear();
return set;
};
llvm::AttrBuilder ab;
const llvm::AttributeSet fn = buildSetFromKinds(ab, mAttributes->mFnAttrs);
const llvm::AttributeSet ret = buildSetFromKinds(ab, mAttributes->mRetAttrs);
std::vector<llvm::AttributeSet> parms(this->size());
for (auto& idxAttr : mAttributes->mParamAttrs) {
const size_t idx = idxAttr.first;
if (idx >= this->size()) continue;
parms[idx] = buildSetFromKinds(ab, idxAttr.second);
}
return llvm::AttributeList::get(C, fn, ret, parms);
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
llvm::Function*
IRFunctionBase::create(llvm::LLVMContext& C, llvm::Module* M) const
{
if (this->hasEmbedIR()) return nullptr;
llvm::Function* F = this->Function::create(C, M);
assert(F);
// return if the function has already been generated or if no
// module has been provided (just the function prototype requested)
if (!F->empty() || !M) return F;
// generate the body
llvm::BasicBlock* BB =
llvm::BasicBlock::Create(C,
"entry_" + std::string(this->symbol()), F);
std::vector<llvm::Value*> fnargs;
fnargs.reserve(this->size());
for (auto arg = F->arg_begin(), arg_end = F->arg_end();
arg != arg_end; ++arg) {
fnargs.emplace_back(llvm::cast<llvm::Value>(arg));
}
// create a new builder per function (its lightweight)
// @todo could pass in the builder similar to Function::call
llvm::IRBuilder<> B(BB);
llvm::Value* lastInstruction = mGen(fnargs, B);
// Allow the user to return a nullptr, an actual value or a return
// instruction from the generator callback. This facilitates the same
// generator being used for inline IR
// if nullptr, insert a ret void inst, otherwise if it's not a return
// instruction, either return the value if its supported or insert a
// ret void
if (!lastInstruction) {
// @note if the ret type is not expected to be void, this will
// cause verifyResultType to throw
lastInstruction = B.CreateRetVoid();
}
else if (!llvm::isa<llvm::ReturnInst>(lastInstruction)) {
assert(lastInstruction);
if (lastInstruction->getType()->isVoidTy()) {
lastInstruction = B.CreateRetVoid();
}
else {
lastInstruction = B.CreateRet(lastInstruction);
}
}
assert(lastInstruction);
assert(llvm::isa<llvm::ReturnInst>(lastInstruction));
// pull out the ret type - is null if void
llvm::Value* rvalue =
llvm::cast<llvm::ReturnInst>
(lastInstruction)->getReturnValue();
llvm::Type* type = rvalue ? rvalue->getType() :
llvm::Type::getVoidTy(C);
this->verifyResultType(type, F->getReturnType());
return F;
}
llvm::Value* IRFunctionBase::call(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B,
const bool cast) const
{
if (!this->hasEmbedIR()) {
return this->Function::call(args, B, cast);
}
std::vector<llvm::Value*> inputs(args);
if (cast) {
std::vector<llvm::Type*> types;
this->types(types, B.getContext());
this->cast(inputs, types, B);
}
llvm::Value* result = mGen(inputs, B);
if (result) {
// only verify if result is not nullptr to
// allow for embedded instructions
std::vector<llvm::Type*> unused;
this->verifyResultType(result->getType(),
this->types(unused, B.getContext()));
}
return result;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
Function::Ptr
FunctionGroup::match(const std::vector<llvm::Type*>& types,
llvm::LLVMContext& C,
Function::SignatureMatch* type) const
{
Function::Ptr targetFunction;
if (type) *type = Function::SignatureMatch::None;
for (const auto& function : mFunctionList) {
const Function::SignatureMatch matchtype = function->match(types, C);
if (type) *type = std::max(matchtype, *type);
if (matchtype == Function::SignatureMatch::None) continue;
else if (matchtype == Function::SignatureMatch::Size) continue;
else if (matchtype == Function::SignatureMatch::Explicit) {
return function;
}
else if (matchtype == Function::SignatureMatch::Implicit) {
if (!targetFunction) targetFunction = function;
}
}
return targetFunction;
}
llvm::Value*
FunctionGroup::execute(const std::vector<llvm::Value*>& args,
llvm::IRBuilder<>& B) const
{
std::vector<llvm::Type*> inputTypes;
valuesToTypes(args, inputTypes);
llvm::LLVMContext& C = B.getContext();
Function::SignatureMatch match;
const Function::Ptr target = this->match(inputTypes, C, &match);
llvm::Value* result = nullptr;
if (!target) return result;
if (match == Function::SignatureMatch::Implicit) {
result = target->call(args, B, /*cast=*/true);
}
else {
// match == Function::SignatureMatch::Explicit
result = target->call(args, B, /*cast=*/false);
}
assert(result);
return result;
}
} // namespace codegen
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 12,977 | C++ | 29.753554 | 89 | 0.574324 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/PointExecutable.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/PointExecutable.cc
#include "PointExecutable.h"
#include "../Exceptions.h"
// @TODO refactor so we don't have to include PointComputeGenerator.h,
// but still have the functions defined in one place
#include "../codegen/PointComputeGenerator.h"
#include "../codegen/PointLeafLocalData.h"
#include <openvdb/Types.h>
#include <openvdb/points/AttributeArray.h>
#include <openvdb/points/PointAttribute.h>
#include <openvdb/points/PointConversion.h> // ConversionTraits
#include <openvdb/points/PointDataGrid.h>
#include <openvdb/points/PointGroup.h>
#include <openvdb/points/PointMask.h>
#include <openvdb/points/PointMove.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
struct PointExecutable::Settings
{
bool mCreateMissing = true;
size_t mGrainSize = 1;
std::string mGroup = "";
};
namespace {
/// @brief Point Kernel types
///
using KernelFunctionPtr = std::add_pointer<codegen::PointKernel::Signature>::type;
using FunctionTraitsT = codegen::PointKernel::FunctionTraitsT;
using ReturnT = FunctionTraitsT::ReturnType;
using PointLeafLocalData = codegen::codegen_internal::PointLeafLocalData;
/// @brief The arguments of the generated function
///
struct PointFunctionArguments
{
using LeafT = points::PointDataTree::LeafNodeType;
/// @brief Base untyped handle struct for container storage
struct Handles
{
using UniquePtr = std::unique_ptr<Handles>;
virtual ~Handles() = default;
};
/// @brief A wrapper around a VDB Points Attribute Handle, allowing for
/// typed storage of a read or write handle. This is used for
/// automatic memory management and void pointer passing into the
/// generated point functions
template <typename ValueT>
struct TypedHandle final : public Handles
{
using UniquePtr = std::unique_ptr<TypedHandle<ValueT>>;
using HandleTraits = points::point_conversion_internal::ConversionTraits<ValueT>;
using HandleT = typename HandleTraits::Handle;
~TypedHandle() override final = default;
inline void*
initReadHandle(const LeafT& leaf, const size_t pos) {
mHandle = HandleTraits::handleFromLeaf(leaf, static_cast<Index>(pos));
return static_cast<void*>(mHandle.get());
}
inline void*
initWriteHandle(LeafT& leaf, const size_t pos) {
mHandle = HandleTraits::writeHandleFromLeaf(leaf, static_cast<Index>(pos));
return static_cast<void*>(mHandle.get());
}
private:
typename HandleT::Ptr mHandle;
};
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
PointFunctionArguments(const KernelFunctionPtr function,
const CustomData* const customData,
const points::AttributeSet& attributeSet,
PointLeafLocalData* const leafLocalData)
: mFunction(function)
, mCustomData(customData)
, mAttributeSet(&attributeSet)
, mVoidAttributeHandles()
, mAttributeHandles()
, mVoidGroupHandles()
, mGroupHandles()
, mLeafLocalData(leafLocalData) {}
/// @brief Given a built version of the function signature, automatically
/// bind the current arguments and return a callable function
/// which takes no arguments
inline auto bind()
{
return [&](const uint64_t index) -> ReturnT {
return mFunction(static_cast<FunctionTraitsT::Arg<0>::Type>(mCustomData),
static_cast<FunctionTraitsT::Arg<1>::Type>(mAttributeSet),
static_cast<FunctionTraitsT::Arg<2>::Type>(index),
static_cast<FunctionTraitsT::Arg<3>::Type>(mVoidAttributeHandles.data()),
static_cast<FunctionTraitsT::Arg<4>::Type>(mVoidGroupHandles.data()),
static_cast<FunctionTraitsT::Arg<5>::Type>(mLeafLocalData));
};
}
template <typename ValueT>
inline void addHandle(const LeafT& leaf, const size_t pos)
{
typename TypedHandle<ValueT>::UniquePtr handle(new TypedHandle<ValueT>());
mVoidAttributeHandles.emplace_back(handle->initReadHandle(leaf, pos));
mAttributeHandles.emplace_back(std::move(handle));
}
template <typename ValueT>
inline void addWriteHandle(LeafT& leaf, const size_t pos)
{
typename TypedHandle<ValueT>::UniquePtr handle(new TypedHandle<ValueT>());
mVoidAttributeHandles.emplace_back(handle->initWriteHandle(leaf, pos));
mAttributeHandles.emplace_back(std::move(handle));
}
inline void addGroupHandle(const LeafT& leaf, const std::string& name)
{
assert(leaf.attributeSet().descriptor().hasGroup(name));
mGroupHandles.emplace_back(new points::GroupHandle(leaf.groupHandle(name)));
mVoidGroupHandles.emplace_back(static_cast<void*>(mGroupHandles.back().get()));
}
inline void addGroupWriteHandle(LeafT& leaf, const std::string& name)
{
assert(leaf.attributeSet().descriptor().hasGroup(name));
mGroupHandles.emplace_back(new points::GroupWriteHandle(leaf.groupWriteHandle(name)));
mVoidGroupHandles.emplace_back(static_cast<void*>(mGroupHandles.back().get()));
}
inline void addNullGroupHandle() { mVoidGroupHandles.emplace_back(nullptr); }
inline void addNullAttribHandle() { mVoidAttributeHandles.emplace_back(nullptr); }
private:
const KernelFunctionPtr mFunction;
const CustomData* const mCustomData;
const points::AttributeSet* const mAttributeSet;
std::vector<void*> mVoidAttributeHandles;
std::vector<Handles::UniquePtr> mAttributeHandles;
std::vector<void*> mVoidGroupHandles;
#if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER > 7 || \
(OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER >= 7 && \
OPENVDB_LIBRARY_MINOR_VERSION_NUMBER >= 1))
std::vector<points::GroupHandle::UniquePtr> mGroupHandles;
#else
std::vector<std::unique_ptr<points::GroupHandle>> mGroupHandles;
#endif
PointLeafLocalData* const mLeafLocalData;
};
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
template<typename FilterT = openvdb::points::NullFilter>
struct PointExecuterDeformer
{
PointExecuterDeformer(const std::string& positionAttribute,
const FilterT& filter = FilterT())
: mFilter(filter)
, mPws(nullptr)
, mPositionAttribute(positionAttribute) {}
PointExecuterDeformer(const PointExecuterDeformer& other)
: mFilter(other.mFilter)
, mPws(nullptr)
, mPositionAttribute(other.mPositionAttribute) {}
template <typename LeafT>
void reset(const LeafT& leaf, const size_t)
{
mFilter.reset(leaf);
mPws.reset(new points::AttributeHandle<Vec3f>(leaf.constAttributeArray(mPositionAttribute)));
}
template <typename IterT>
void apply(Vec3d& position, const IterT& iter) const
{
if (mFilter.valid(iter)) {
assert(mPws);
position = Vec3d(mPws->get(*iter));
}
}
FilterT mFilter;
points::AttributeHandle<Vec3f>::UniquePtr mPws;
const std::string& mPositionAttribute;
};
template <typename ValueType>
inline void
addAttributeHandleTyped(PointFunctionArguments& args,
openvdb::points::PointDataTree::LeafNodeType& leaf,
const std::string& name,
const bool write)
{
const openvdb::points::AttributeSet& attributeSet = leaf.attributeSet();
const size_t pos = attributeSet.find(name);
assert(pos != openvdb::points::AttributeSet::INVALID_POS);
if (write) args.addWriteHandle<ValueType>(leaf, pos);
else args.addHandle<ValueType>(leaf, pos);
}
#ifndef NDEBUG
inline bool supported(const ast::tokens::CoreType type)
{
switch (type) {
case ast::tokens::BOOL : return true;
case ast::tokens::CHAR : return true;
case ast::tokens::INT16 : return true;
case ast::tokens::INT32 : return true;
case ast::tokens::INT64 : return true;
case ast::tokens::FLOAT : return true;
case ast::tokens::DOUBLE : return true;
case ast::tokens::VEC2I : return true;
case ast::tokens::VEC2F : return true;
case ast::tokens::VEC2D : return true;
case ast::tokens::VEC3I : return true;
case ast::tokens::VEC3F : return true;
case ast::tokens::VEC3D : return true;
case ast::tokens::VEC4I : return true;
case ast::tokens::VEC4F : return true;
case ast::tokens::VEC4D : return true;
case ast::tokens::MAT3F : return true;
case ast::tokens::MAT3D : return true;
case ast::tokens::MAT4F : return true;
case ast::tokens::MAT4D : return true;
case ast::tokens::STRING : return true;
case ast::tokens::UNKNOWN :
default : return false;
}
}
#endif
inline void
addAttributeHandle(PointFunctionArguments& args,
openvdb::points::PointDataTree::LeafNodeType& leaf,
const std::string& name,
const ast::tokens::CoreType type,
const bool write)
{
// assert so the executer can be marked as noexcept (assuming nothing throws in compute)
assert(supported(type) && "Could not retrieve attribute handle from unsupported type");
switch (type) {
case ast::tokens::BOOL : return addAttributeHandleTyped<bool>(args, leaf, name, write);
case ast::tokens::CHAR : return addAttributeHandleTyped<char>(args, leaf, name, write);
case ast::tokens::INT16 : return addAttributeHandleTyped<int16_t>(args, leaf, name, write);
case ast::tokens::INT32 : return addAttributeHandleTyped<int32_t>(args, leaf, name, write);
case ast::tokens::INT64 : return addAttributeHandleTyped<int64_t>(args, leaf, name, write);
case ast::tokens::FLOAT : return addAttributeHandleTyped<float>(args, leaf, name, write);
case ast::tokens::DOUBLE : return addAttributeHandleTyped<double>(args, leaf, name, write);
case ast::tokens::VEC2I : return addAttributeHandleTyped<math::Vec2<int32_t>>(args, leaf, name, write);
case ast::tokens::VEC2F : return addAttributeHandleTyped<math::Vec2<float>>(args, leaf, name, write);
case ast::tokens::VEC2D : return addAttributeHandleTyped<math::Vec2<double>>(args, leaf, name, write);
case ast::tokens::VEC3I : return addAttributeHandleTyped<math::Vec3<int32_t>>(args, leaf, name, write);
case ast::tokens::VEC3F : return addAttributeHandleTyped<math::Vec3<float>>(args, leaf, name, write);
case ast::tokens::VEC3D : return addAttributeHandleTyped<math::Vec3<double>>(args, leaf, name, write);
case ast::tokens::VEC4I : return addAttributeHandleTyped<math::Vec4<int32_t>>(args, leaf, name, write);
case ast::tokens::VEC4F : return addAttributeHandleTyped<math::Vec4<float>>(args, leaf, name, write);
case ast::tokens::VEC4D : return addAttributeHandleTyped<math::Vec4<double>>(args, leaf, name, write);
case ast::tokens::MAT3F : return addAttributeHandleTyped<math::Mat3<float>>(args, leaf, name, write);
case ast::tokens::MAT3D : return addAttributeHandleTyped<math::Mat3<double>>(args, leaf, name, write);
case ast::tokens::MAT4F : return addAttributeHandleTyped<math::Mat4<float>>(args, leaf, name, write);
case ast::tokens::MAT4D : return addAttributeHandleTyped<math::Mat4<double>>(args, leaf, name, write);
case ast::tokens::STRING : return addAttributeHandleTyped<std::string>(args, leaf, name, write);
case ast::tokens::UNKNOWN :
default : return;
}
}
/// @brief VDB Points executer for a compiled function pointer
struct PointExecuterOp
{
using LeafManagerT = openvdb::tree::LeafManager<openvdb::points::PointDataTree>;
using LeafNode = openvdb::points::PointDataTree::LeafNodeType;
using Descriptor = openvdb::points::AttributeSet::Descriptor;
using GroupFilter = openvdb::points::GroupFilter;
using GroupIndex = Descriptor::GroupIndex;
PointExecuterOp(const AttributeRegistry& attributeRegistry,
const CustomData* const customData,
const KernelFunctionPtr computeFunction,
const math::Transform& transform,
const GroupIndex& groupIndex,
std::vector<PointLeafLocalData::UniquePtr>& leafLocalData,
const std::string& positionAttribute,
const std::pair<bool,bool>& positionAccess)
: mAttributeRegistry(attributeRegistry)
, mCustomData(customData)
, mComputeFunction(computeFunction)
, mTransform(transform)
, mGroupIndex(groupIndex)
, mLeafLocalData(leafLocalData)
, mPositionAttribute(positionAttribute)
, mPositionAccess(positionAccess) {}
template<typename FilterT = openvdb::points::NullFilter>
inline std::unique_ptr<points::AttributeWriteHandle<Vec3f>>
initPositions(LeafNode& leaf, const FilterT& filter = FilterT()) const
{
const points::AttributeHandle<Vec3f>::UniquePtr
positions(new points::AttributeHandle<Vec3f>(leaf.constAttributeArray("P")));
std::unique_ptr<points::AttributeWriteHandle<Vec3f>>
pws(new points::AttributeWriteHandle<Vec3f>(leaf.attributeArray(mPositionAttribute)));
for (auto iter = leaf.beginIndexAll(filter); iter; ++iter) {
const Index idx = *iter;
const openvdb::Vec3f pos = positions->get(idx) + iter.getCoord().asVec3s();
pws->set(idx, mTransform.indexToWorld(pos));
}
return pws;
}
void operator()(LeafNode& leaf, size_t idx) const
{
const size_t count = leaf.getLastValue();
const points::AttributeSet& set = leaf.attributeSet();
auto& leafLocalData = mLeafLocalData[idx];
leafLocalData.reset(new PointLeafLocalData(count));
PointFunctionArguments args(mComputeFunction, mCustomData, set, leafLocalData.get());
// add attributes based on the order and existence in the attribute registry
for (const auto& iter : mAttributeRegistry.data()) {
const std::string& name = (iter.name() == "P" ? mPositionAttribute : iter.name());
addAttributeHandle(args, leaf, name, iter.type(), iter.writes());
}
// add groups
const auto& map = set.descriptor().groupMap();
if (!map.empty()) {
// add all groups based on their offset within the attribute set - the offset can
// then be used as a key when retrieving groups from the linearized array, which
// is provided by the attribute set argument
std::map<size_t, std::string> orderedGroups;
for (const auto& iter : map) {
orderedGroups[iter.second] = iter.first;
}
// add a handle at every offset up to and including the max offset. If the
// offset is not in use, we just use a null pointer as this will never be
// accessed
const size_t maxOffset = orderedGroups.crbegin()->first;
auto iter = orderedGroups.begin();
for (size_t i = 0; i <= maxOffset; ++i) {
if (iter->first == i) {
args.addGroupWriteHandle(leaf, iter->second);
++iter;
}
else {
// empty handle at this index
args.addNullGroupHandle();
}
}
}
const bool group = mGroupIndex.first != points::AttributeSet::INVALID_POS;
// if we are using position we need to initialise the world space storage
std::unique_ptr<points::AttributeWriteHandle<Vec3f>> pws;
if (mPositionAccess.first || mPositionAccess.second) {
if (group) {
const GroupFilter filter(mGroupIndex);
pws = this->initPositions(leaf, filter);
}
else {
pws = this->initPositions(leaf);
}
}
const auto run = args.bind();
if (group) {
const GroupFilter filter(mGroupIndex);
auto iter = leaf.beginIndex<LeafNode::ValueAllCIter, GroupFilter>(filter);
for (; iter; ++iter) run(*iter);
}
else {
// the Compute function performs unsigned integer arithmetic and will wrap
// if count == 0 inside ComputeGenerator::genComputeFunction()
if (count > 0) run(count);
}
// if not writing to position (i.e. post sorting) collapse the temporary attribute
if (pws && !mPositionAccess.second) {
pws->collapse();
pws.reset();
}
// as multiple groups can be stored in a single array, attempt to compact the
// arrays directly so that we're not trying to call compact multiple times
// unsuccessfully
leafLocalData->compact();
}
void operator()(const LeafManagerT::LeafRange& range) const
{
for (auto leaf = range.begin(); leaf; ++leaf) {
(*this)(*leaf, leaf.pos());
}
}
private:
const AttributeRegistry& mAttributeRegistry;
const CustomData* const mCustomData;
const KernelFunctionPtr mComputeFunction;
const math::Transform& mTransform;
const GroupIndex& mGroupIndex;
std::vector<PointLeafLocalData::UniquePtr>& mLeafLocalData;
const std::string& mPositionAttribute;
const std::pair<bool,bool>& mPositionAccess;
};
void appendMissingAttributes(points::PointDataGrid& grid,
const AttributeRegistry& registry)
{
auto typePairFromToken =
[](const ast::tokens::CoreType type) -> NamePair {
switch (type) {
case ast::tokens::BOOL : return points::TypedAttributeArray<bool>::attributeType();
case ast::tokens::CHAR : return points::TypedAttributeArray<char>::attributeType();
case ast::tokens::INT16 : return points::TypedAttributeArray<int16_t>::attributeType();
case ast::tokens::INT32 : return points::TypedAttributeArray<int32_t>::attributeType();
case ast::tokens::INT64 : return points::TypedAttributeArray<int64_t>::attributeType();
case ast::tokens::FLOAT : return points::TypedAttributeArray<float>::attributeType();
case ast::tokens::DOUBLE : return points::TypedAttributeArray<double>::attributeType();
case ast::tokens::VEC2I : return points::TypedAttributeArray<math::Vec2<int32_t>>::attributeType();
case ast::tokens::VEC2F : return points::TypedAttributeArray<math::Vec2<float>>::attributeType();
case ast::tokens::VEC2D : return points::TypedAttributeArray<math::Vec2<double>>::attributeType();
case ast::tokens::VEC3I : return points::TypedAttributeArray<math::Vec3<int32_t>>::attributeType();
case ast::tokens::VEC3F : return points::TypedAttributeArray<math::Vec3<float>>::attributeType();
case ast::tokens::VEC3D : return points::TypedAttributeArray<math::Vec3<double>>::attributeType();
case ast::tokens::VEC4I : return points::TypedAttributeArray<math::Vec4<int32_t>>::attributeType();
case ast::tokens::VEC4F : return points::TypedAttributeArray<math::Vec4<float>>::attributeType();
case ast::tokens::VEC4D : return points::TypedAttributeArray<math::Vec4<double>>::attributeType();
case ast::tokens::MAT3F : return points::TypedAttributeArray<math::Mat3<float>>::attributeType();
case ast::tokens::MAT3D : return points::TypedAttributeArray<math::Mat3<double>>::attributeType();
case ast::tokens::MAT4F : return points::TypedAttributeArray<math::Mat4<float>>::attributeType();
case ast::tokens::MAT4D : return points::TypedAttributeArray<math::Mat4<double>>::attributeType();
case ast::tokens::STRING : return points::StringAttributeArray::attributeType();
case ast::tokens::UNKNOWN :
default : {
return NamePair();
}
}
};
const auto leafIter = grid.tree().cbeginLeaf();
assert(leafIter);
// append attributes
for (const auto& iter : registry.data()) {
const std::string& name = iter.name();
const points::AttributeSet::Descriptor& desc = leafIter->attributeSet().descriptor();
const size_t pos = desc.find(name);
if (pos != points::AttributeSet::INVALID_POS) {
const NamePair& type = desc.type(pos);
const ast::tokens::CoreType typetoken =
ast::tokens::tokenFromTypeString(type.first);
if (typetoken != iter.type() &&
!(type.second == "str" && iter.type() == ast::tokens::STRING)) {
OPENVDB_THROW(AXExecutionError, "Mismatching attributes types. \"" + name +
"\" exists of type \"" + type.first + "\" but has been "
"accessed with type \"" + ast::tokens::typeStringFromToken(iter.type()) + "\"");
}
continue;
}
assert(supported(iter.type()));
const NamePair type = typePairFromToken(iter.type());
points::appendAttribute(grid.tree(), name, type);
}
}
void checkAttributesExist(const points::PointDataGrid& grid,
const AttributeRegistry& registry)
{
const auto leafIter = grid.tree().cbeginLeaf();
assert(leafIter);
const points::AttributeSet::Descriptor& desc = leafIter->attributeSet().descriptor();
for (const auto& iter : registry.data()) {
const std::string& name = iter.name();
const size_t pos = desc.find(name);
if (pos == points::AttributeSet::INVALID_POS) {
OPENVDB_THROW(AXExecutionError, "Attribute \"" + name +
"\" does not exist on grid \"" + grid.getName() + "\"");
}
}
}
} // anonymous namespace
PointExecutable::PointExecutable(const std::shared_ptr<const llvm::LLVMContext>& context,
const std::shared_ptr<const llvm::ExecutionEngine>& engine,
const AttributeRegistry::ConstPtr& attributeRegistry,
const CustomData::ConstPtr& customData,
const std::unordered_map<std::string, uint64_t>& functions)
: mContext(context)
, mExecutionEngine(engine)
, mAttributeRegistry(attributeRegistry)
, mCustomData(customData)
, mFunctionAddresses(functions)
, mSettings(new Settings)
{
assert(mContext);
assert(mExecutionEngine);
assert(mAttributeRegistry);
}
PointExecutable::PointExecutable(const PointExecutable& other)
: mContext(other.mContext)
, mExecutionEngine(other.mExecutionEngine)
, mAttributeRegistry(other.mAttributeRegistry)
, mCustomData(other.mCustomData)
, mFunctionAddresses(other.mFunctionAddresses)
, mSettings(new Settings(*other.mSettings)) {}
PointExecutable::~PointExecutable() {}
void PointExecutable::execute(openvdb::points::PointDataGrid& grid) const
{
using LeafManagerT = openvdb::tree::LeafManager<openvdb::points::PointDataTree>;
const auto leafIter = grid.tree().cbeginLeaf();
if (!leafIter) return;
// create any missing attributes
if (mSettings->mCreateMissing) appendMissingAttributes(grid, *mAttributeRegistry);
else checkAttributesExist(grid, *mAttributeRegistry);
const std::pair<bool,bool> positionAccess =
mAttributeRegistry->accessPattern("P", ast::tokens::VEC3F);
const bool usingPosition = positionAccess.first || positionAccess.second;
// create temporary world space position attribute if P is being accessed
// @todo should avoid actually adding this attribute to the tree as its temporary
std::string positionAttribute = "P";
if (usingPosition /*mAttributeRegistry->isWritable("P", ast::tokens::VEC3F)*/) {
const points::AttributeSet::Descriptor& desc =
leafIter->attributeSet().descriptor();
positionAttribute = desc.uniqueName("__P");
points::appendAttribute<openvdb::Vec3f>(grid.tree(), positionAttribute);
}
const bool usingGroup = !mSettings->mGroup.empty();
openvdb::points::AttributeSet::Descriptor::GroupIndex groupIndex;
if (usingGroup) groupIndex = leafIter->attributeSet().groupIndex(mSettings->mGroup);
else groupIndex.first = openvdb::points::AttributeSet::INVALID_POS;
// extract appropriate function pointer
KernelFunctionPtr compute = nullptr;
const auto iter = usingGroup ?
mFunctionAddresses.find(codegen::PointKernel::getDefaultName()) :
mFunctionAddresses.find(codegen::PointRangeKernel::getDefaultName());
if (iter != mFunctionAddresses.end()) {
compute = reinterpret_cast<KernelFunctionPtr>(iter->second);
}
if (!compute) {
OPENVDB_THROW(AXCompilerError,
"No code has been successfully compiled for execution.");
}
const math::Transform& transform = grid.transform();
LeafManagerT leafManager(grid.tree());
std::vector<PointLeafLocalData::UniquePtr> leafLocalData(leafManager.leafCount());
const bool threaded = mSettings->mGrainSize > 0;
PointExecuterOp executerOp(*mAttributeRegistry,
mCustomData.get(), compute, transform, groupIndex,
leafLocalData, positionAttribute, positionAccess);
leafManager.foreach(executerOp, threaded, mSettings->mGrainSize);
// Check to see if any new data has been added and apply it accordingly
std::set<std::string> groups;
bool newStrings = false;
{
points::StringMetaInserter
inserter(leafIter->attributeSet().descriptorPtr()->getMetadata());
for (const auto& data : leafLocalData) {
data->getGroups(groups);
newStrings |= data->insertNewStrings(inserter);
}
}
// append and copy over newly created groups
// @todo We should just be able to steal the arrays and compact
// groups but the API for this isn't very nice at the moment
for (const auto& name : groups) {
points::appendGroup(grid.tree(), name);
}
// add new groups and set strings
leafManager.foreach(
[&groups, &leafLocalData, newStrings] (auto& leaf, size_t idx) {
PointLeafLocalData::UniquePtr& data = leafLocalData[idx];
for (const auto& name : groups) {
// Attempt to get the group handle out of the leaf local data form this
// leaf. This may not exist as although all of the unique set are appended
// to the tree (above), not every leaf may have been directly touched
// by every new group. Some leaf nodes may not require any bit mask copying
points::GroupWriteHandle* tmpHandle = data->get(name);
if (!tmpHandle) continue;
points::GroupWriteHandle handle = leaf.groupWriteHandle(name);
if (tmpHandle->isUniform()) {
handle.collapse(tmpHandle->get(0));
}
else {
const openvdb::Index size = tmpHandle->size();
for (openvdb::Index i = 0; i < size; ++i) {
handle.set(i, tmpHandle->get(i));
}
}
}
if (newStrings) {
const MetaMap& metadata = leaf.attributeSet().descriptor().getMetadata();
const PointLeafLocalData::StringArrayMap& stringArrayMap = data->getStringArrayMap();
for (const auto& arrayIter : stringArrayMap) {
points::StringAttributeWriteHandle::Ptr handle =
points::StringAttributeWriteHandle::create(*(arrayIter.first), metadata);
for (const auto& iter : arrayIter.second) {
handle->set(static_cast<Index>(iter.first), iter.second);
}
}
}
}, threaded, mSettings->mGrainSize);
if (positionAccess.second) {
// if position is writable, sort the points
if (usingGroup) {
openvdb::points::GroupFilter filter(groupIndex);
PointExecuterDeformer<openvdb::points::GroupFilter> deformer(positionAttribute, filter);
openvdb::points::movePoints(grid, deformer);
}
else {
PointExecuterDeformer<> deformer(positionAttribute);
openvdb::points::movePoints(grid, deformer);
}
}
if (usingPosition) {
// remove temporary world space storage
points::dropAttribute(grid.tree(), positionAttribute);
}
}
/////////////////////////////////////////////
/////////////////////////////////////////////
void PointExecutable::setCreateMissing(const bool flag)
{
mSettings->mCreateMissing = flag;
}
bool PointExecutable::getCreateMissing() const
{
return mSettings->mCreateMissing;
}
void PointExecutable::setGrainSize(const size_t grain)
{
mSettings->mGrainSize = grain;
}
size_t PointExecutable::getGrainSize() const
{
return mSettings->mGrainSize;
}
void PointExecutable::setGroupExecution(const std::string& group)
{
mSettings->mGroup = group;
}
const std::string& PointExecutable::getGroupExecution() const
{
return mSettings->mGroup;
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 30,050 | C++ | 40.278846 | 113 | 0.633178 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/VolumeExecutable.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/VolumeExecutable.cc
#include "VolumeExecutable.h"
#include "../Exceptions.h"
// @TODO refactor so we don't have to include VolumeComputeGenerator.h,
// but still have the functions defined in one place
#include "../codegen/VolumeComputeGenerator.h"
#include <openvdb/Exceptions.h>
#include <openvdb/Types.h>
#include <openvdb/math/Coord.h>
#include <openvdb/math/Transform.h>
#include <openvdb/math/Vec3.h>
#include <openvdb/tree/ValueAccessor.h>
#include <openvdb/tree/LeafManager.h>
#include <openvdb/tree/NodeManager.h>
#include <tbb/parallel_for.h>
#include <memory>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
struct VolumeExecutable::Settings
{
Index mTreeExecutionLevel = 0;
bool mCreateMissing = true;
IterType mValueIterator = IterType::ON;
size_t mGrainSize = 1;
};
namespace {
/// @brief Volume Kernel types
///
using KernelFunctionPtr = std::add_pointer<codegen::VolumeKernel::Signature>::type;
using FunctionTraitsT = codegen::VolumeKernel::FunctionTraitsT;
using ReturnT = FunctionTraitsT::ReturnType;
template <typename ValueT>
using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type;
using SupportedTypeList = openvdb::TypeList<
ConverterT<double>,
ConverterT<float>,
ConverterT<int64_t>,
ConverterT<int32_t>,
ConverterT<int16_t>,
ConverterT<bool>,
ConverterT<openvdb::math::Vec2<double>>,
ConverterT<openvdb::math::Vec2<float>>,
ConverterT<openvdb::math::Vec2<int32_t>>,
ConverterT<openvdb::math::Vec3<double>>,
ConverterT<openvdb::math::Vec3<float>>,
ConverterT<openvdb::math::Vec3<int32_t>>,
ConverterT<openvdb::math::Vec4<double>>,
ConverterT<openvdb::math::Vec4<float>>,
ConverterT<openvdb::math::Vec4<int32_t>>,
ConverterT<openvdb::math::Mat3<double>>,
ConverterT<openvdb::math::Mat3<float>>,
ConverterT<openvdb::math::Mat4<double>>,
ConverterT<openvdb::math::Mat4<float>>,
ConverterT<std::string>>;
/// The arguments of the generated function
struct VolumeFunctionArguments
{
struct Accessors
{
using UniquePtr = std::unique_ptr<Accessors>;
virtual ~Accessors() = default;
};
template <typename TreeT>
struct TypedAccessor final : public Accessors
{
using UniquePtr = std::unique_ptr<TypedAccessor<TreeT>>;
TypedAccessor(TreeT& tree)
: mAccessor(new tree::ValueAccessor<TreeT>(tree)) {}
~TypedAccessor() override final = default;
inline void* get() const { return static_cast<void*>(mAccessor.get()); }
const std::unique_ptr<tree::ValueAccessor<TreeT>> mAccessor;
};
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
VolumeFunctionArguments(const KernelFunctionPtr function,
const size_t index,
void* const accessor,
const CustomData* const customData)
: mFunction(function)
, mIdx(index)
, mAccessor(accessor)
, mCustomData(customData)
, mVoidAccessors()
, mAccessors()
, mVoidTransforms() {}
/// @brief Given a built version of the function signature, automatically
/// bind the current arguments and return a callable function
/// which takes no arguments
inline auto bind()
{
return [&](const openvdb::Coord& ijk, const openvdb::Vec3f& pos) -> ReturnT {
return mFunction(static_cast<FunctionTraitsT::Arg<0>::Type>(mCustomData),
reinterpret_cast<FunctionTraitsT::Arg<1>::Type>(ijk.data()),
reinterpret_cast<FunctionTraitsT::Arg<2>::Type>(pos.asV()),
static_cast<FunctionTraitsT::Arg<3>::Type>(mVoidAccessors.data()),
static_cast<FunctionTraitsT::Arg<4>::Type>(mVoidTransforms.data()),
static_cast<FunctionTraitsT::Arg<5>::Type>(mIdx),
mAccessor);
};
}
template <typename TreeT>
inline void
addAccessor(TreeT& tree)
{
typename TypedAccessor<TreeT>::UniquePtr accessor(new TypedAccessor<TreeT>(tree));
mVoidAccessors.emplace_back(accessor->get());
mAccessors.emplace_back(std::move(accessor));
}
inline void
addTransform(math::Transform& transform)
{
mVoidTransforms.emplace_back(static_cast<void*>(&transform));
}
private:
const KernelFunctionPtr mFunction;
const size_t mIdx;
void* const mAccessor;
const CustomData* const mCustomData;
std::vector<void*> mVoidAccessors;
std::vector<Accessors::UniquePtr> mAccessors;
std::vector<void*> mVoidTransforms;
};
inline bool supported(const ast::tokens::CoreType type)
{
switch (type) {
case ast::tokens::BOOL : return true;
case ast::tokens::INT16 : return true;
case ast::tokens::INT32 : return true;
case ast::tokens::INT64 : return true;
case ast::tokens::FLOAT : return true;
case ast::tokens::DOUBLE : return true;
case ast::tokens::VEC2I : return true;
case ast::tokens::VEC2F : return true;
case ast::tokens::VEC2D : return true;
case ast::tokens::VEC3I : return true;
case ast::tokens::VEC3F : return true;
case ast::tokens::VEC3D : return true;
case ast::tokens::VEC4I : return true;
case ast::tokens::VEC4F : return true;
case ast::tokens::VEC4D : return true;
case ast::tokens::MAT3F : return true;
case ast::tokens::MAT3D : return true;
case ast::tokens::MAT4F : return true;
case ast::tokens::MAT4D : return true;
case ast::tokens::STRING : return true;
case ast::tokens::UNKNOWN :
default : return false;
}
}
inline void
retrieveAccessor(VolumeFunctionArguments& args,
openvdb::GridBase* grid,
const ast::tokens::CoreType& type)
{
// assert so the executer can be marked as noexcept (assuming nothing throws in compute)
assert(supported(type) && "Could not retrieve accessor from unsupported type");
switch (type) {
case ast::tokens::BOOL : { args.addAccessor(static_cast<ConverterT<bool>*>(grid)->tree()); return; }
case ast::tokens::INT16 : { args.addAccessor(static_cast<ConverterT<int16_t>*>(grid)->tree()); return; }
case ast::tokens::INT32 : { args.addAccessor(static_cast<ConverterT<int32_t>*>(grid)->tree()); return; }
case ast::tokens::INT64 : { args.addAccessor(static_cast<ConverterT<int64_t>*>(grid)->tree()); return; }
case ast::tokens::FLOAT : { args.addAccessor(static_cast<ConverterT<float>*>(grid)->tree()); return; }
case ast::tokens::DOUBLE : { args.addAccessor(static_cast<ConverterT<double>*>(grid)->tree()); return; }
case ast::tokens::VEC2D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<double>>*>(grid)->tree()); return; }
case ast::tokens::VEC2F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<float>>*>(grid)->tree()); return; }
case ast::tokens::VEC2I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<int32_t>>*>(grid)->tree()); return; }
case ast::tokens::VEC3D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<double>>*>(grid)->tree()); return; }
case ast::tokens::VEC3F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<float>>*>(grid)->tree()); return; }
case ast::tokens::VEC3I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<int32_t>>*>(grid)->tree()); return; }
case ast::tokens::VEC4D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<double>>*>(grid)->tree()); return; }
case ast::tokens::VEC4F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<float>>*>(grid)->tree()); return; }
case ast::tokens::VEC4I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<int32_t>>*>(grid)->tree()); return; }
case ast::tokens::MAT3D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat3<double>>*>(grid)->tree()); return; }
case ast::tokens::MAT3F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat3<float>>*>(grid)->tree()); return; }
case ast::tokens::MAT4D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat4<double>>*>(grid)->tree()); return; }
case ast::tokens::MAT4F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat4<float>>*>(grid)->tree()); return; }
case ast::tokens::STRING : { args.addAccessor(static_cast<ConverterT<std::string>*>(grid)->tree()); return; }
case ast::tokens::UNKNOWN :
default : return;
}
}
inline openvdb::GridBase::Ptr
createGrid(const ast::tokens::CoreType& type)
{
// assert so the executer can be marked as noexcept (assuming nothing throws in compute)
assert(supported(type) && "Could not retrieve accessor from unsupported type");
switch (type) {
case ast::tokens::BOOL : return ConverterT<bool>::create();
case ast::tokens::INT16 : return ConverterT<int16_t>::create();
case ast::tokens::INT32 : return ConverterT<int32_t>::create();
case ast::tokens::INT64 : return ConverterT<int64_t>::create();
case ast::tokens::FLOAT : return ConverterT<float>::create();
case ast::tokens::DOUBLE : return ConverterT<double>::create();
case ast::tokens::VEC2D : return ConverterT<openvdb::math::Vec2<double>>::create();
case ast::tokens::VEC2F : return ConverterT<openvdb::math::Vec2<float>>::create();
case ast::tokens::VEC2I : return ConverterT<openvdb::math::Vec2<int32_t>>::create();
case ast::tokens::VEC3D : return ConverterT<openvdb::math::Vec3<double>>::create();
case ast::tokens::VEC3F : return ConverterT<openvdb::math::Vec3<float>>::create();
case ast::tokens::VEC3I : return ConverterT<openvdb::math::Vec3<int32_t>>::create();
case ast::tokens::VEC4D : return ConverterT<openvdb::math::Vec4<double>>::create();
case ast::tokens::VEC4F : return ConverterT<openvdb::math::Vec4<float>>::create();
case ast::tokens::VEC4I : return ConverterT<openvdb::math::Vec4<int32_t>>::create();
case ast::tokens::MAT3D : return ConverterT<openvdb::math::Mat3<double>>::create();
case ast::tokens::MAT3F : return ConverterT<openvdb::math::Mat3<float>>::create();
case ast::tokens::MAT4D : return ConverterT<openvdb::math::Mat4<double>>::create();
case ast::tokens::MAT4F : return ConverterT<openvdb::math::Mat4<float>>::create();
case ast::tokens::STRING : return ConverterT<std::string>::create();
case ast::tokens::UNKNOWN :
default : return nullptr;
}
}
template <typename TreeT, typename LeafIterTraitsT>
struct VolumeExecuterOp
{
using LeafManagerT = tree::LeafManager<TreeT>;
using LeafRangeT = typename LeafManagerT::LeafRange;
VolumeExecuterOp(const AttributeRegistry& attributeRegistry,
const CustomData* const customData,
const math::Transform& assignedVolumeTransform,
const KernelFunctionPtr computeFunction,
openvdb::GridBase** grids,
TreeT& tree,
const size_t idx,
const Index level)
: mAttributeRegistry(attributeRegistry)
, mCustomData(customData)
, mComputeFunction(computeFunction)
, mTransform(assignedVolumeTransform)
, mGrids(grids)
, mIdx(idx)
, mTree(tree)
, mLevel(level) {
assert(mGrids);
}
// For use with a NodeManager
// @note The enable_if shouldn't be necessary but the partitioner
// through TBB refuses to call the LeafRange operator with a
// const reference argument.
template <typename NodeType, typename =
typename std::enable_if<!std::is_same<NodeType, LeafRangeT>::value>::type>
void operator()(NodeType& node) const
{
// if the current node level does not match, skip
// @todo only run over the given level, avoid caching other nodes
assert(node.getLevel() > 0);
if (node.getLevel() != mLevel) return;
openvdb::tree::ValueAccessor<TreeT> acc(mTree);
VolumeFunctionArguments args(mComputeFunction,
mIdx, static_cast<void*>(&acc), mCustomData);
openvdb::GridBase** read = mGrids;
for (const auto& iter : mAttributeRegistry.data()) {
assert(read);
retrieveAccessor(args, *read, iter.type());
args.addTransform((*read)->transform());
++read;
}
const auto run = args.bind();
(*this)(node, run);
}
// For use with a LeafManager, when the target execution level is 0
void operator()(const typename LeafManagerT::LeafRange& range) const
{
openvdb::tree::ValueAccessor<TreeT> acc(mTree);
VolumeFunctionArguments args(mComputeFunction,
mIdx, static_cast<void*>(&acc), mCustomData);
openvdb::GridBase** read = mGrids;
for (const auto& iter : mAttributeRegistry.data()) {
assert(read);
retrieveAccessor(args, *read, iter.type());
args.addTransform((*read)->transform());
++read;
}
const auto run = args.bind();
for (auto leaf = range.begin(); leaf; ++leaf) {
(*this)(*leaf, run);
}
}
template <typename NodeType, typename FuncT>
void operator()(NodeType& node, const FuncT& axfunc) const
{
using IterT = typename LeafIterTraitsT::template NodeConverter<NodeType>::Type;
using IterTraitsT = tree::IterTraits<NodeType, IterT>;
for (auto iter = IterTraitsT::begin(node); iter; ++iter) {
const openvdb::Coord& coord = iter.getCoord();
const openvdb::Vec3f& pos = mTransform.indexToWorld(coord);
axfunc(coord, pos);
}
}
private:
const AttributeRegistry& mAttributeRegistry;
const CustomData* const mCustomData;
const KernelFunctionPtr mComputeFunction;
const math::Transform& mTransform;
openvdb::GridBase** const mGrids;
const size_t mIdx;
TreeT& mTree;
const Index mLevel; // only used with NodeManagers
};
void registerVolumes(GridPtrVec& grids,
GridPtrVec& writeableGrids,
GridPtrVec& readGrids,
const AttributeRegistry& registry,
const bool createMissing)
{
for (auto& iter : registry.data()) {
openvdb::GridBase::Ptr matchedGrid;
bool matchedName(false);
ast::tokens::CoreType type = ast::tokens::UNKNOWN;
for (const auto& grid : grids) {
if (grid->getName() != iter.name()) continue;
matchedName = true;
type = ast::tokens::tokenFromTypeString(grid->valueType());
if (type != iter.type()) continue;
matchedGrid = grid;
break;
}
if (createMissing && !matchedGrid) {
matchedGrid = createGrid(iter.type());
if (matchedGrid) {
matchedGrid->setName(iter.name());
grids.emplace_back(matchedGrid);
matchedName = true;
type = iter.type();
}
}
if (!matchedName && !matchedGrid) {
OPENVDB_THROW(AXExecutionError, "Missing grid \"" +
ast::tokens::typeStringFromToken(iter.type()) + "@" + iter.name() + "\".");
}
if (matchedName && !matchedGrid) {
OPENVDB_THROW(AXExecutionError, "Mismatching grid access type. \"@" + iter.name() +
"\" exists but has been accessed with type \"" +
ast::tokens::typeStringFromToken(iter.type()) + "\".");
}
assert(matchedGrid);
if (!supported(type)) {
OPENVDB_THROW(AXExecutionError, "Could not register volume '"
+ matchedGrid->getName() + "' as it has an unknown or unsupported value type '"
+ matchedGrid->valueType() + "'");
}
// Populate the write/read grids based on the access registry. If a
// grid is being written to and has non self usage, (influences
// another grids value which isn't it's own) it must be deep copied
// @todo implement better execution order detection which could minimize
// the number of deep copies required
if (iter.writes() && iter.affectsothers()) {
// if affectsothers(), it's also read from at some point
assert(iter.reads());
readGrids.push_back(matchedGrid->deepCopyGrid());
writeableGrids.push_back(matchedGrid);
}
else {
if (iter.writes()) {
writeableGrids.push_back(matchedGrid);
}
readGrids.push_back(matchedGrid);
}
}
}
template<typename LeafT> struct ValueOnIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueOnIter>; };
template<typename LeafT> struct ValueAllIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueAllIter>; };
template<typename LeafT> struct ValueOffIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueOffIter>; };
template <template <typename> class IterT, typename GridT>
inline void run(openvdb::GridBase& grid,
openvdb::GridBase** readptrs,
const KernelFunctionPtr kernel,
const AttributeRegistry& registry,
const CustomData* const custom,
const VolumeExecutable::Settings& S)
{
using TreeType = typename GridT::TreeType;
using IterType = IterT<typename TreeType::LeafNodeType>;
const ast::tokens::CoreType type =
ast::tokens::tokenFromTypeString(grid.valueType());
const int64_t idx = registry.accessIndex(grid.getName(), type);
assert(idx >= 0);
GridT& typed = static_cast<GridT&>(grid);
VolumeExecuterOp<TreeType, typename IterType::IterTraitsT>
executerOp(registry, custom, grid.transform(),
kernel, readptrs, typed.tree(), idx, S.mTreeExecutionLevel);
const bool thread = S.mGrainSize > 0;
if (S.mTreeExecutionLevel == 0) {
// execute over the topology of the grid currently being modified.
tree::LeafManager<TreeType> leafManager(typed.tree());
if (thread) tbb::parallel_for(leafManager.leafRange(S.mGrainSize), executerOp);
else executerOp(leafManager.leafRange());
}
else {
// no leaf nodes
tree::NodeManager<TreeType, TreeType::RootNodeType::LEVEL-1> manager(typed.tree());
manager.foreachBottomUp(executerOp, thread, S.mGrainSize);
}
}
template <template <typename> class IterT>
inline void run(const openvdb::GridPtrVec& writeableGrids,
const openvdb::GridPtrVec& readGrids,
const KernelFunctionPtr kernel,
const AttributeRegistry& registry,
const CustomData* const custom,
const VolumeExecutable::Settings& S)
{
// extract grid pointers from shared pointer container
assert(readGrids.size() == registry.data().size());
std::vector<openvdb::GridBase*> readptrs;
readptrs.reserve(readGrids.size());
for (auto& grid : readGrids) readptrs.emplace_back(grid.get());
for (const auto& grid : writeableGrids) {
const bool success = grid->apply<SupportedTypeList>([&](auto& typed) {
using GridType = typename std::decay<decltype(typed)>::type;
run<IterT, GridType>(*grid, readptrs.data(), kernel, registry, custom, S);
});
if (!success) {
OPENVDB_THROW(AXExecutionError, "Could not retrieve volume '" + grid->getName()
+ "' as it has an unknown or unsupported value type '" + grid->valueType()
+ "'");
}
}
}
} // anonymous namespace
VolumeExecutable::VolumeExecutable(const std::shared_ptr<const llvm::LLVMContext>& context,
const std::shared_ptr<const llvm::ExecutionEngine>& engine,
const AttributeRegistry::ConstPtr& accessRegistry,
const CustomData::ConstPtr& customData,
const std::unordered_map<std::string, uint64_t>& functionAddresses)
: mContext(context)
, mExecutionEngine(engine)
, mAttributeRegistry(accessRegistry)
, mCustomData(customData)
, mFunctionAddresses(functionAddresses)
, mSettings(new Settings)
{
assert(mContext);
assert(mExecutionEngine);
assert(mAttributeRegistry);
}
VolumeExecutable::VolumeExecutable(const VolumeExecutable& other)
: mContext(other.mContext)
, mExecutionEngine(other.mExecutionEngine)
, mAttributeRegistry(other.mAttributeRegistry)
, mCustomData(other.mCustomData)
, mFunctionAddresses(other.mFunctionAddresses)
, mSettings(new Settings(*other.mSettings)) {}
VolumeExecutable::~VolumeExecutable() {}
void VolumeExecutable::execute(openvdb::GridPtrVec& grids) const
{
openvdb::GridPtrVec readGrids, writeableGrids;
registerVolumes(grids, writeableGrids, readGrids, *mAttributeRegistry, mSettings->mCreateMissing);
const auto iter = mFunctionAddresses.find(codegen::VolumeKernel::getDefaultName());
KernelFunctionPtr kernel = nullptr;
if (iter != mFunctionAddresses.end()) {
kernel = reinterpret_cast<KernelFunctionPtr>(iter->second);
}
if (kernel == nullptr) {
OPENVDB_THROW(AXCompilerError,
"No AX kernel found for execution.");
}
if (mSettings->mValueIterator == IterType::ON)
run<ValueOnIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else if (mSettings->mValueIterator == IterType::OFF)
run<ValueOffIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else if (mSettings->mValueIterator == IterType::ALL)
run<ValueAllIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else {
OPENVDB_THROW(AXExecutionError,
"Unrecognised voxel iterator.");
}
}
void VolumeExecutable::execute(openvdb::GridBase& grid) const
{
const auto data = mAttributeRegistry->data();
if (data.empty()) return;
for (auto& iter : mAttributeRegistry->data()) {
if (grid.getName() != iter.name()) {
OPENVDB_THROW(LookupError, "Missing grid \"" +
ast::tokens::typeStringFromToken(iter.type()) + "@" + iter.name() + "\".");
}
const ast::tokens::CoreType type = ast::tokens::tokenFromTypeString(grid.valueType());
if (type != iter.type()) {
OPENVDB_THROW(TypeError, "Mismatching grid access type. \"@" + iter.name() +
"\" exists but has been accessed with type \"" +
ast::tokens::typeStringFromToken(iter.type()) + "\".");
}
if (!supported(type)) {
OPENVDB_THROW(TypeError, "Could not register volume '"
+ grid.getName() + "' as it has an unknown or unsupported value type '"
+ grid.valueType() + "'");
}
}
assert(mAttributeRegistry->data().size() == 1);
const auto iter = mFunctionAddresses.find(codegen::VolumeKernel::getDefaultName());
KernelFunctionPtr kernel = nullptr;
if (iter != mFunctionAddresses.end()) {
kernel = reinterpret_cast<KernelFunctionPtr>(iter->second);
}
if (kernel == nullptr) {
OPENVDB_THROW(AXCompilerError,
"No code has been successfully compiled for execution.");
}
const bool success = grid.apply<SupportedTypeList>([&](auto& typed) {
using GridType = typename std::decay<decltype(typed)>::type;
openvdb::GridBase* grids = &grid;
if (mSettings->mValueIterator == IterType::ON)
run<ValueOnIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else if (mSettings->mValueIterator == IterType::OFF)
run<ValueOffIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else if (mSettings->mValueIterator == IterType::ALL)
run<ValueAllIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings);
else
OPENVDB_THROW(AXExecutionError,"Unrecognised voxel iterator.");
});
if (!success) {
OPENVDB_THROW(TypeError, "Could not retrieve volume '" + grid.getName()
+ "' as it has an unknown or unsupported value type '" + grid.valueType()
+ "'");
}
}
/////////////////////////////////////////////
/////////////////////////////////////////////
void VolumeExecutable::setCreateMissing(const bool flag)
{
mSettings->mCreateMissing = flag;
}
bool VolumeExecutable::getCreateMissing() const
{
return mSettings->mCreateMissing;
}
void VolumeExecutable::setTreeExecutionLevel(const Index level)
{
// use the default implementation of FloatTree for reference
if (level >= FloatTree::DEPTH) {
OPENVDB_THROW(RuntimeError,
"Invalid tree execution level in VolumeExecutable.");
}
mSettings->mTreeExecutionLevel = level;
}
Index VolumeExecutable::getTreeExecutionLevel() const
{
return mSettings->mTreeExecutionLevel;
}
void VolumeExecutable::setValueIterator(const VolumeExecutable::IterType& iter)
{
mSettings->mValueIterator = iter;
}
VolumeExecutable::IterType VolumeExecutable::getValueIterator() const
{
return mSettings->mValueIterator;
}
void VolumeExecutable::setGrainSize(const size_t grain)
{
mSettings->mGrainSize = grain;
}
size_t VolumeExecutable::getGrainSize() const
{
return mSettings->mGrainSize;
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 26,225 | C++ | 39.914197 | 135 | 0.63428 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/CustomData.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/CustomData.h
///
/// @authors Nick Avramoussis, Francisco Gochez
///
/// @brief Access to the CustomData class which can provide custom user
/// user data to the OpenVDB AX Compiler.
///
#ifndef OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <openvdb/Metadata.h>
#include <openvdb/Types.h>
#include <unordered_map>
#include <memory>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @brief The backend representation of strings in AX. This is also how
/// strings are passed from the AX code generation to functions.
struct AXString
{
// usually size_t. Used to match the implementation of std:string
using SizeType = std::allocator<char>::size_type;
const char* ptr = nullptr;
SizeType size = 0;
};
/// @brief The custom data class is a simple container for named openvdb metadata. Its primary use
/// case is passing arbitrary "external" data to an AX executable object when calling
/// Compiler::compile. For example, it is the mechanism by which we pass data held inside of a
/// parent DCC to executable AX code.
class CustomData
{
public:
using Ptr = std::shared_ptr<CustomData>;
using ConstPtr = std::shared_ptr<const CustomData>;
using UniquePtr = std::unique_ptr<CustomData>;
CustomData() : mData() {}
static UniquePtr create()
{
UniquePtr data(new CustomData);
return data;
}
/// @brief Reset the custom data. This will clear and delete all previously added data.
/// @note When used the Compiler::compile method, this should not be used prior to executing
/// the built executable object
inline void reset()
{
mData.clear();
}
/// @brief Checks whether or not data of given name has been inserted
inline bool
hasData(const Name& name)
{
const auto iter = mData.find(name);
return (iter != mData.end());
}
/// @brief Checks whether or not data of given name and type has been inserted
template <typename TypedDataCacheT>
inline bool
hasData(const Name& name)
{
const auto iter = mData.find(name);
if (iter == mData.end()) return false;
const TypedDataCacheT* const typed =
dynamic_cast<const TypedDataCacheT* const>(iter->second.get());
return typed != nullptr;
}
/// @brief Retrieves a const pointer to data of given name. If it does not
/// exist, returns nullptr
inline const Metadata::ConstPtr
getData(const Name& name) const
{
const auto iter = mData.find(name);
if (iter == mData.end()) return Metadata::ConstPtr();
return iter->second;
}
/// @brief Retrieves a const pointer to data of given name and type. If it does not
/// exist, returns nullptr
/// @param name Name of the data entry
/// @returns Object of given type and name. If the type does not match, nullptr is returned.
template <typename TypedDataCacheT>
inline const TypedDataCacheT*
getData(const Name& name) const
{
Metadata::ConstPtr data = getData(name);
if (!data) return nullptr;
const TypedDataCacheT* const typed =
dynamic_cast<const TypedDataCacheT* const>(data.get());
return typed;
}
/// @brief Retrieves or inserts typed metadata. If thedata exists, it is dynamic-casted to the
/// expected type, which may result in a nullptr. If the data does not exist it is guaranteed
/// to be inserted and returned. The value of the inserted data can then be modified
template <typename TypedDataCacheT>
inline TypedDataCacheT*
getOrInsertData(const Name& name)
{
const auto iter = mData.find(name);
if (iter == mData.end()) {
Metadata::Ptr data(new TypedDataCacheT());
mData[name] = data;
return static_cast<TypedDataCacheT* const>(data.get());
}
else {
return dynamic_cast<TypedDataCacheT* const>(iter->second.get());
}
}
/// @brief Inserts data of specified type with given name.
/// @param name Name of the data
/// @param data Shared pointer to the data
/// @note If an entry of the given name already exists, will copy the data into the existing
/// entry rather than overwriting the pointer
template <typename TypedDataCacheT>
inline void
insertData(const Name& name,
const typename TypedDataCacheT::Ptr data)
{
if (hasData(name)) {
TypedDataCacheT* const dataToSet =
getOrInsertData<TypedDataCacheT>(name);
if (!dataToSet) {
OPENVDB_THROW(TypeError, "Custom data \"" + name + "\" already exists with a different type.");
}
dataToSet->value() = data->value();
}
else {
mData[name] = data->copy();
}
}
/// @brief Inserts data with given name.
/// @param name Name of the data
/// @param data The metadata
/// @note If an entry of the given name already exists, will copy the data into the existing
/// entry rather than overwriting the pointer
inline void
insertData(const Name& name,
const Metadata::Ptr data)
{
const auto iter = mData.find(name);
if (iter == mData.end()) {
mData[name] = data;
}
else {
iter->second->copy(*data);
}
}
private:
std::unordered_map<Name, Metadata::Ptr> mData;
};
struct AXStringMetadata : public StringMetadata
{
using Ptr = openvdb::SharedPtr<AXStringMetadata>;
using ConstPtr = openvdb::SharedPtr<const AXStringMetadata>;
AXStringMetadata(const std::string& string)
: StringMetadata(string)
, mData()
{
this->initialize();
}
// delegate, ensure valid string initialization
AXStringMetadata() : AXStringMetadata("") {}
AXStringMetadata(const AXStringMetadata& other)
: StringMetadata(other)
, mData()
{
this->initialize();
}
~AXStringMetadata() override {}
openvdb::Metadata::Ptr copy() const override {
openvdb::Metadata::Ptr metadata(new AXStringMetadata());
metadata->copy(*this);
return metadata;
}
void copy(const openvdb::Metadata& other) override {
const AXStringMetadata* t = dynamic_cast<const AXStringMetadata*>(&other);
if (t == nullptr) OPENVDB_THROW(openvdb::TypeError, "Incompatible type during copy");
this->StringMetadata::setValue(t->StringMetadata::value());
this->initialize();
}
void setValue(const std::string& string)
{
this->StringMetadata::setValue(string);
this->initialize();
}
ax::AXString& value() { return mData; }
const ax::AXString& value() const { return mData; }
protected:
void readValue(std::istream& is, openvdb::Index32 size) override {
StringMetadata::readValue(is, size);
this->initialize();
}
private:
void initialize()
{
mData.ptr = StringMetadata::value().c_str();
mData.size = StringMetadata::value().size();
}
ax::AXString mData;
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED
| 7,640 | C | 30.315574 | 111 | 0.631152 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/VolumeExecutable.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/VolumeExecutable.h
///
/// @authors Nick Avramoussis, Francisco Gochez, Richard Jones
///
/// @brief The VolumeExecutable, produced by the OpenVDB AX Compiler for
/// execution over Numerical OpenVDB Grids.
///
#ifndef OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED
#include "CustomData.h"
#include "AttributeRegistry.h"
#include <openvdb/version.h>
#include <openvdb/Grid.h>
#include <unordered_map>
class TestVolumeExecutable;
namespace llvm {
class ExecutionEngine;
class LLVMContext;
}
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
class Compiler;
/// @brief Object that encapsulates compiled AX code which can be executed on a collection of
/// VDB volume grids
class VolumeExecutable
{
public:
using Ptr = std::shared_ptr<VolumeExecutable>;
~VolumeExecutable();
/// @brief Copy constructor. Shares the LLVM constructs but deep copies the
/// settings. Multiple copies of an executor can be used at the same time
/// safely.
VolumeExecutable(const VolumeExecutable& other);
////////////////////////////////////////////////////////
/// @brief Execute AX code on target grids
void execute(openvdb::GridPtrVec& grids) const;
void execute(openvdb::GridBase& grid) const;
////////////////////////////////////////////////////////
/// @brief Set the behaviour when missing grids are accessed. Default
/// behaviour is true, which creates them with default transforms and
/// background values
/// @param flag Enables or disables the creation of missing attributes
void setCreateMissing(const bool flag);
/// @return Whether this executable will generate new grids.
bool getCreateMissing() const;
/// @brief Set the execution level for this executable. This controls what
/// nodes are processed when execute is called. Possible values depend on
/// the OpenVDB configuration in use however a value of 0 is the default
/// and will always correspond to the lowest level (leaf-level).
/// @note A value larger that the number of levels in the tree (i.e. larger
/// than the tree depth) will cause this method to throw a runtime error.
/// @warning Executing over tiles with compiled code designed for voxel
/// level access may produce incorrect results. This is typically the
/// case when accessing VDBs with mismatching topology. Consider
/// voxelizing tiles where necessary.
/// @param level The tree execution level to set
void setTreeExecutionLevel(const Index level);
/// @return The tree execution level. Default is 0 i.e. the leaf level
Index getTreeExecutionLevel() const;
enum class IterType { ON, OFF, ALL };
/// @brief Set the value iterator type to use with this executable. Options
/// are ON, OFF, ALL. Default is ON.
/// @param iter The value iterator type to set
void setValueIterator(const IterType& iter);
/// @return The current value iterator type
IterType getValueIterator() const;
/// @brief Set the threading grain size. Default is 1. A value of 0 has the
/// effect of disabling multi-threading.
/// @param grain The grain size
void setGrainSize(const size_t grain);
/// @return The current grain size
size_t getGrainSize() const;
////////////////////////////////////////////////////////
// foward declaration of settings for this executable
struct Settings;
private:
friend class Compiler;
friend class ::TestVolumeExecutable;
/// @brief Constructor, expected to be invoked by the compiler. Should not
/// be invoked directly.
/// @param context Shared pointer to an llvm:LLVMContext associated with the
/// execution engine
/// @param engine Shared pointer to an llvm::ExecutionEngine used to build
/// functions. Context should be the associated LLVMContext
/// @param accessRegistry Registry of volumes accessed by AX code
/// @param customData Custom data which will be shared by this executable.
/// It can be used to retrieve external data from within the AX code
/// @param functions A map of function names to physical memory addresses
/// which were built by llvm using engine
VolumeExecutable(const std::shared_ptr<const llvm::LLVMContext>& context,
const std::shared_ptr<const llvm::ExecutionEngine>& engine,
const AttributeRegistry::ConstPtr& accessRegistry,
const CustomData::ConstPtr& customData,
const std::unordered_map<std::string, uint64_t>& functions);
private:
// The Context and ExecutionEngine must exist _only_ for object lifetime
// management. The ExecutionEngine must be destroyed before the Context
const std::shared_ptr<const llvm::LLVMContext> mContext;
const std::shared_ptr<const llvm::ExecutionEngine> mExecutionEngine;
const AttributeRegistry::ConstPtr mAttributeRegistry;
const CustomData::ConstPtr mCustomData;
const std::unordered_map<std::string, uint64_t> mFunctionAddresses;
std::unique_ptr<Settings> mSettings;
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED
| 5,446 | C | 38.18705 | 93 | 0.695006 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Compiler.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/Compiler.h
///
/// @authors Nick Avramoussis, Francisco Gochez, Richard Jones
///
/// @brief The OpenVDB AX Compiler class provides methods to generate
/// AX executables from a provided AX AST (or directly from a given
/// string). The class object exists to cache various structures,
/// primarily LLVM constructs, which benefit from existing across
/// additional compilation runs.
///
#ifndef OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED
#include "CompilerOptions.h"
#include "CustomData.h"
#include "Logger.h"
#include "../ax.h" // backward compat support for initialize()
#include "../ast/Parse.h"
#include <openvdb/version.h>
#include <memory>
#include <sstream>
// forward
namespace llvm {
class LLVMContext;
}
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace codegen {
// forward
class FunctionRegistry;
}
/// @brief The compiler class. This holds an llvm context and set of compiler
/// options, and constructs executable objects (e.g. PointExecutable or
/// VolumeExecutable) from a syntax tree or snippet of code.
class Compiler
{
public:
using Ptr = std::shared_ptr<Compiler>;
using UniquePtr = std::unique_ptr<Compiler>;
/// @brief Construct a compiler object with given settings
/// @param options CompilerOptions object with various settings
Compiler(const CompilerOptions& options = CompilerOptions());
~Compiler() = default;
/// @brief Static method for creating Compiler objects
static UniquePtr create(const CompilerOptions& options = CompilerOptions());
/// @brief Compile a given AST into an executable object of the given type.
/// @param syntaxTree An abstract syntax tree to compile
/// @param logger Logger for errors and warnings during compilation, this
/// should be linked to an ast::Tree and populated with AST node + line
/// number mappings for this Tree, e.g. during ast::parse(). This Tree can
/// be different from the syntaxTree argument.
/// @param data Optional external/custom data which is to be referenced by
/// the executable object. It allows one to reference data held elsewhere,
/// such as inside of a DCC, from inside the AX code
/// @note If the logger has not been populated with AST node and line
/// mappings, all messages will appear without valid line and column
/// numbers.
template <typename ExecutableT>
typename ExecutableT::Ptr
compile(const ast::Tree& syntaxTree,
Logger& logger,
const CustomData::Ptr data = CustomData::Ptr());
/// @brief Compile a given snippet of AX code into an executable object of
/// the given type.
/// @param code A string of AX code
/// @param logger Logger for errors and warnings during compilation, will be
/// cleared of existing data
/// @param data Optional external/custom data which is to be referenced by
/// the executable object. It allows one to reference data held elsewhere,
/// such as inside of a DCC, from inside the AX code
/// @note If compilation is unsuccessful, will return nullptr. Logger can
/// then be queried for errors.
template <typename ExecutableT>
typename ExecutableT::Ptr
compile(const std::string& code,
Logger& logger,
const CustomData::Ptr data = CustomData::Ptr())
{
logger.clear();
const ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger);
if (syntaxTree) return compile<ExecutableT>(*syntaxTree, logger, data);
else return nullptr;
}
/// @brief Compile a given snippet of AX code into an executable object of
/// the given type.
/// @param code A string of AX code
/// @param data Optional external/custom data which is to be referenced by
/// the executable object. It allows one to reference data held elsewhere,
/// such as inside of a DCC, from inside the AX code
/// @note Parser errors are handled separately from compiler errors.
/// Each are collected and produce runtime errors.
template <typename ExecutableT>
typename ExecutableT::Ptr
compile(const std::string& code,
const CustomData::Ptr data = CustomData::Ptr())
{
std::vector<std::string> errors;
openvdb::ax::Logger logger(
[&errors] (const std::string& error) {
errors.emplace_back(error + "\n");
},
// ignore warnings
[] (const std::string&) {}
);
const ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger);
typename ExecutableT::Ptr exe;
if (syntaxTree) {
exe = this->compile<ExecutableT>(*syntaxTree, logger, data);
}
if (!errors.empty()) {
std::ostringstream os;
for (const auto& e : errors) os << e << "\n";
OPENVDB_THROW(AXCompilerError, os.str());
}
assert(exe);
return exe;
}
/// @brief Compile a given AST into an executable object of the given type.
/// @param syntaxTree An abstract syntax tree to compile
/// @param data Optional external/custom data which is to be referenced by
/// the executable object. It allows one to reference data held elsewhere,
/// such as inside of a DCC, from inside the AX code
/// @note Any errors encountered are collected into a single runtime error
template <typename ExecutableT>
typename ExecutableT::Ptr
compile(const ast::Tree& syntaxTree,
const CustomData::Ptr data = CustomData::Ptr())
{
std::vector<std::string> errors;
openvdb::ax::Logger logger(
[&errors] (const std::string& error) {
errors.emplace_back(error + "\n");
},
// ignore warnings
[] (const std::string&) {}
);
auto exe = compile<ExecutableT>(syntaxTree, logger, data);
if (!errors.empty()) {
std::ostringstream os;
for (const auto& e : errors) os << e << "\n";
OPENVDB_THROW(AXCompilerError, os.str());
}
assert(exe);
return exe;
}
/// @brief Sets the compiler's function registry object.
/// @param functionRegistry A unique pointer to a FunctionRegistry object.
/// The compiler will take ownership of the registry that was passed in.
/// @todo Perhaps allow one to register individual functions into this
/// class rather than the entire registry at once, and/or allow one to
/// extract a pointer to the registry and update it manually.
void setFunctionRegistry(std::unique_ptr<codegen::FunctionRegistry>&& functionRegistry);
///////////////////////////////////////////////////////////////////////////
private:
std::shared_ptr<llvm::LLVMContext> mContext;
const CompilerOptions mCompilerOptions;
std::shared_ptr<codegen::FunctionRegistry> mFunctionRegistry;
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED
| 7,279 | C | 36.720207 | 92 | 0.65215 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Logger.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/Logger.cc
#include "Logger.h"
#include <stack>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
struct Logger::Settings
{
size_t mMaxErrors = 0;
bool mWarningsAsErrors = false;
// message formatting settings
bool mNumbered = true;
const char* mErrorPrefix = "error: ";
const char* mWarningPrefix = "warning: ";
bool mPrintLines = false;
};
/// @brief Wrapper around a code snippet to print individual lines from a multi
/// line string
/// @note Assumes a null terminated c-style string input
struct Logger::SourceCode
{
SourceCode(const char* string = nullptr)
: mString(string)
, mOffsets()
, mLines() {
reset(string);
}
/// @brief Print a line of the multi-line string to the stream
/// @note If no string hs been provided, will do nothing
/// @param line Line number to print
/// @param os Output stream
void getLine(const size_t num, std::ostream* os)
{
if (num < 1) return;
if (mOffsets.empty()) getLineOffsets();
if (num > mLines) return;
const size_t start = mOffsets[num - 1];
const size_t end = mOffsets[num];
for (size_t i = start; i < end - 1; ++i) *os << mString[i];
}
void reset(const char* string)
{
mString = string;
mOffsets.clear();
mLines = 0;
}
bool hasString() const { return static_cast<bool>(mString); }
private:
void getLineOffsets()
{
if (!mString) return;
mOffsets.emplace_back(0);
size_t offset = 1;
const char* iter = mString;
while (*iter != '\0') {
if (*iter == '\n') mOffsets.emplace_back(offset);
++iter; ++offset;
}
mOffsets.emplace_back(offset);
mLines = mOffsets.size();
}
const char* mString;
std::vector<size_t> mOffsets;
size_t mLines;
};
namespace {
/// @brief Return a stack denoting the position in the tree of this node
/// Where each node is represented by its childidx of its parent
/// This gives a branching path to follow to reach this node from the
/// tree root
/// @parm node Node pointer to create position stack for
inline std::stack<size_t> pathStackFromNode(const ast::Node* node)
{
std::stack<size_t> path;
const ast::Node* child = node;
const ast::Node* parent = node->parent();
while (parent) {
path.emplace(child->childidx());
child = parent;
parent = child->parent();
}
return path;
}
/// @brief Iterate through a tree, following the branch numbers from the path
/// stack, returning a Node* to the node at this position
/// @parm path Stack of child branches to follow
/// @parm tree Tree containing node to return
inline const ast::Node* nodeFromPathStack(std::stack<size_t>& path,
const ast::Tree& tree)
{
const ast::Node* node = &tree;
while (node) {
if (path.empty()) return node;
node = node->child(path.top());
path.pop();
}
return nullptr;
}
/// @brief Given any node and a tree and node to location map, return the line
/// and column number for the nodes equivalent (in terms of position in the
/// tree) from the supplied tree
/// @note Requires the map to have been populated for all nodes in the supplied
/// tree, otherwise will return 0:0
inline const Logger::CodeLocation
nodeToCodeLocation(const ast::Node* node,
const ast::Tree::ConstPtr tree,
const std::unordered_map
<const ax::ast::Node*, Logger::CodeLocation>& map)
{
if (!tree) return Logger::CodeLocation(0,0);
assert(node);
std::stack<size_t> pathStack = pathStackFromNode(node);
const ast::Node* nodeInMap = nodeFromPathStack(pathStack, *tree);
const auto locationIter = map.find(nodeInMap);
if (locationIter == map.end()) return Logger::CodeLocation(0,0);
return locationIter->second;
}
std::string format(const std::string& message,
const Logger::CodeLocation& loc,
const size_t numMessage,
const bool numbered,
const bool printLines,
Logger::SourceCode* sourceCode)
{
std::stringstream ss;
if (numbered) ss << "[" << numMessage + 1 << "] ";
ss << message;
if (loc.first > 0) {
ss << " " << loc.first << ":" << loc.second;
if (printLines && sourceCode) {
ss << "\n";
sourceCode->getLine(loc.first, &ss);
ss << "\n";
for (size_t i = 0; i < loc.second - 1; ++i) ss << "-";
ss << "^";
}
}
return ss.str();
}
}
Logger::Logger(const Logger::OutputFunction& errors,
const Logger::OutputFunction& warnings)
: mErrorOutput(errors)
, mWarningOutput(warnings)
, mNumErrors(0)
, mNumWarnings(0)
, mSettings(new Logger::Settings())
, mCode() {}
Logger::~Logger() {}
void Logger::setSourceCode(const char* code)
{
mCode.reset(new SourceCode(code));
}
bool Logger::error(const std::string& message,
const Logger::CodeLocation& lineCol)
{
// already exceeded the error limit
if (this->atErrorLimit()) return false;
mErrorOutput(format(this->getErrorPrefix() + message,
lineCol,
this->errors(),
this->getNumberedOutput(),
this->getPrintLines(),
this->mCode.get()));
++mNumErrors;
// now exceeds the limit
if (this->atErrorLimit()) return false;
else return true;
}
bool Logger::error(const std::string& message,
const ax::ast::Node* node)
{
return this->error(message, nodeToCodeLocation(node, mTreePtr, mNodeToLineColMap));
}
bool Logger::warning(const std::string& message,
const Logger::CodeLocation& lineCol)
{
if (this->getWarningsAsErrors()) {
return this->error(message + " [warning-as-error]", lineCol);
}
else {
mWarningOutput(format(this->getWarningPrefix() + message,
lineCol,
this->warnings(),
this->getNumberedOutput(),
this->getPrintLines(),
this->mCode.get()));
++mNumWarnings;
return true;
}
}
bool Logger::warning(const std::string& message,
const ax::ast::Node* node)
{
return this->warning(message, nodeToCodeLocation(node, mTreePtr, mNodeToLineColMap));
}
void Logger::setWarningsAsErrors(const bool warnAsError)
{
mSettings->mWarningsAsErrors = warnAsError;
}
bool Logger::getWarningsAsErrors() const
{
return mSettings->mWarningsAsErrors;
}
void Logger::setMaxErrors(const size_t maxErrors)
{
mSettings->mMaxErrors = maxErrors;
}
size_t Logger::getMaxErrors() const
{
return mSettings->mMaxErrors;
}
void Logger::setNumberedOutput(const bool numbered)
{
mSettings->mNumbered = numbered;
}
void Logger::setErrorPrefix(const char* prefix)
{
mSettings->mErrorPrefix = prefix;
}
void Logger::setWarningPrefix(const char* prefix)
{
mSettings->mWarningPrefix = prefix;
}
void Logger::setPrintLines(const bool print)
{
mSettings->mPrintLines = print;
}
bool Logger::getNumberedOutput() const
{
return mSettings->mNumbered;
}
const char* Logger::getErrorPrefix() const
{
return mSettings->mErrorPrefix;
}
const char* Logger::getWarningPrefix() const
{
return mSettings->mWarningPrefix;
}
bool Logger::getPrintLines() const
{
return mSettings->mPrintLines;
}
void Logger::clear()
{
mCode.reset();
mNumErrors = 0;
mNumWarnings = 0;
mNodeToLineColMap.clear();
mTreePtr = nullptr;
}
void Logger::setSourceTree(openvdb::ax::ast::Tree::ConstPtr tree)
{
mTreePtr = tree;
}
void Logger::addNodeLocation(const ax::ast::Node* node, const Logger::CodeLocation& location)
{
mNodeToLineColMap.emplace(node, location);
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 8,366 | C++ | 25.903537 | 93 | 0.60447 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Compiler.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/Compiler.cc
#include "Compiler.h"
#include "PointExecutable.h"
#include "VolumeExecutable.h"
#include "../ast/Scanners.h"
#include "../codegen/Functions.h"
#include "../codegen/PointComputeGenerator.h"
#include "../codegen/VolumeComputeGenerator.h"
#include "../Exceptions.h"
#include <openvdb/Exceptions.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Config/llvm-config.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Mangler.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/PassManager.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/MC/SubtargetFeature.h>
#include <llvm/Passes/PassBuilder.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Support/SourceMgr.h> // SMDiagnostic
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
// @note As of adding support for LLVM 5.0 we not longer explicitly
// perform standrd compiler passes (-std-compile-opts) based on the changes
// to the opt binary in the llvm codebase (tools/opt.cpp). We also no
// longer explicitly perform:
// - llvm::createStripSymbolsPass()
// And have never performed any specific target machine analysis passes
//
// @todo Properly identify the IPO passes that we would benefit from using
// as well as what user controls would otherwise be appropriate
#include <llvm/Transforms/IPO.h> // Inter-procedural optimization passes
#include <llvm/Transforms/IPO/AlwaysInliner.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
namespace
{
/// @brief Initialize a target machine for the host platform. Returns a nullptr
/// if a target could not be created.
/// @note This logic is based off the Kaleidoscope tutorial below with extensions
/// for CPU and CPU featrue set targetting
/// https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.html
inline std::unique_ptr<llvm::TargetMachine> initializeTargetMachine()
{
const std::string TargetTriple = llvm::sys::getDefaultTargetTriple();
std::string Error;
const llvm::Target* Target = llvm::TargetRegistry::lookupTarget(TargetTriple, Error);
if (!Target) {
OPENVDB_LOG_DEBUG_RUNTIME("Unable to retrieve target machine information. "
"No target specific optimization will be performed: " << Error);
return nullptr;
}
// default cpu with no additional features = "generic"
const llvm::StringRef& CPU = llvm::sys::getHostCPUName();
llvm::SubtargetFeatures Features;
llvm::StringMap<bool> HostFeatures;
if (llvm::sys::getHostCPUFeatures(HostFeatures))
for (auto &F : HostFeatures)
Features.AddFeature(F.first(), F.second);
// default options
llvm::TargetOptions opt;
const llvm::Optional<llvm::Reloc::Model> RM =
llvm::Optional<llvm::Reloc::Model>();
std::unique_ptr<llvm::TargetMachine> TargetMachine(
Target->createTargetMachine(TargetTriple, CPU, Features.getString(), opt, RM));
return TargetMachine;
}
#ifndef USE_NEW_PASS_MANAGER
void addStandardLinkPasses(llvm::legacy::PassManagerBase& passes)
{
llvm::PassManagerBuilder builder;
builder.VerifyInput = true;
builder.Inliner = llvm::createFunctionInliningPass();
builder.populateLTOPassManager(passes);
}
/// This routine adds optimization passes based on selected optimization level
///
void addOptimizationPasses(llvm::legacy::PassManagerBase& passes,
llvm::legacy::FunctionPassManager& functionPasses,
llvm::TargetMachine* targetMachine,
const unsigned optLevel,
const unsigned sizeLevel,
const bool disableInline = false,
const bool disableUnitAtATime = false,
const bool disableLoopUnrolling = false,
const bool disableLoopVectorization = false,
const bool disableSLPVectorization = false)
{
llvm::PassManagerBuilder builder;
builder.OptLevel = optLevel;
builder.SizeLevel = sizeLevel;
if (disableInline) {
// No inlining pass
} else if (optLevel > 1) {
builder.Inliner =
llvm::createFunctionInliningPass(optLevel, sizeLevel,
/*DisableInlineHotCallSite*/false);
} else {
builder.Inliner = llvm::createAlwaysInlinerLegacyPass();
}
#if LLVM_VERSION_MAJOR < 9
// Enable IPO. This corresponds to gcc's -funit-at-a-time
builder.DisableUnitAtATime = disableUnitAtATime;
#else
// unused from llvm 9
(void)(disableUnitAtATime);
#endif
// Disable loop unrolling in all relevant passes
builder.DisableUnrollLoops =
disableLoopUnrolling ? disableLoopUnrolling : optLevel == 0;
// See the following link for more info on vectorizers
// http://llvm.org/docs/Vectorizers.html
// (-vectorize-loops, -loop-vectorize)
builder.LoopVectorize =
disableLoopVectorization ? false : optLevel > 1 && sizeLevel < 2;
builder.SLPVectorize =
disableSLPVectorization ? false : optLevel > 1 && sizeLevel < 2;
// If a target machine is provided, allow the target to modify the pass manager
// e.g. by calling PassManagerBuilder::addExtension.
if (targetMachine) {
targetMachine->adjustPassManager(builder);
}
builder.populateFunctionPassManager(functionPasses);
builder.populateModulePassManager(passes);
}
void LLVMoptimise(llvm::Module* module,
const unsigned optLevel,
const unsigned sizeLevel,
const bool verify,
llvm::TargetMachine* TM)
{
// Pass manager setup and IR optimisations - Do target independent optimisations
// only - i.e. the following do not require an llvm TargetMachine analysis pass
llvm::legacy::PassManager passes;
llvm::TargetLibraryInfoImpl TLII(llvm::Triple(module->getTargetTriple()));
passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
// Add internal analysis passes from the target machine.
if (TM) passes.add(llvm::createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
else passes.add(llvm::createTargetTransformInfoWrapperPass(llvm::TargetIRAnalysis()));
llvm::legacy::FunctionPassManager functionPasses(module);
if (TM) functionPasses.add(llvm::createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
else functionPasses.add(llvm::createTargetTransformInfoWrapperPass(llvm::TargetIRAnalysis()));
if (verify) functionPasses.add(llvm::createVerifierPass());
addStandardLinkPasses(passes);
addOptimizationPasses(passes, functionPasses, TM, optLevel, sizeLevel);
functionPasses.doInitialization();
for (llvm::Function& function : *module) {
functionPasses.run(function);
}
functionPasses.doFinalization();
if (verify) passes.add(llvm::createVerifierPass());
passes.run(*module);
}
void LLVMoptimise(llvm::Module* module,
const llvm::PassBuilder::OptimizationLevel opt,
const bool verify,
llvm::TargetMachine* TM)
{
unsigned optLevel = 0, sizeLevel = 0;
// llvm::PassBuilder::OptimizationLevel is an enum in llvm 10
// and earlier, a class in llvm 11 and later (which holds
// various member data about the optimization level)
#if LLVM_VERSION_MAJOR < 11
switch (opt) {
case llvm::PassBuilder::OptimizationLevel::O0 : {
optLevel = 0; sizeLevel = 0;
break;
}
case llvm::PassBuilder::OptimizationLevel::O1 : {
optLevel = 1; sizeLevel = 0;
break;
}
case llvm::PassBuilder::OptimizationLevel::O2 : {
optLevel = 2; sizeLevel = 0;
break;
}
case llvm::PassBuilder::OptimizationLevel::Os : {
optLevel = 2; sizeLevel = 1;
break;
}
case llvm::PassBuilder::OptimizationLevel::Oz : {
optLevel = 2; sizeLevel = 2;
break;
}
case llvm::PassBuilder::OptimizationLevel::O3 : {
optLevel = 3; sizeLevel = 0;
break;
}
default : {}
}
#else
optLevel = opt.getSpeedupLevel();
sizeLevel = opt.getSizeLevel();
#endif
LLVMoptimise(module, optLevel, sizeLevel, verify, TM);
}
#else
void LLVMoptimise(llvm::Module* module,
const llvm::PassBuilder::OptimizationLevel optLevel,
const bool verify,
llvm::TargetMachine* TM)
{
// use the PassBuilder for optimisation pass management
// see llvm's llvm/Passes/PassBuilder.h, tools/opt/NewPMDriver.cpp
// and clang's CodeGen/BackEndUtil.cpp for more info/examples
llvm::PassBuilder PB(TM);
llvm::LoopAnalysisManager LAM;
llvm::FunctionAnalysisManager FAM;
llvm::CGSCCAnalysisManager cGSCCAM;
llvm::ModuleAnalysisManager MAM;
// register all of the analysis passes available by default
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(cGSCCAM);
PB.registerFunctionAnalyses(FAM);
PB.registerLoopAnalyses(LAM);
// the analysis managers above are interdependent so
// register dependent managers with each other via proxies
PB.crossRegisterProxies(LAM, FAM, cGSCCAM, MAM);
// the PassBuilder does not produce -O0 pipelines, so do that ourselves
if (optLevel == llvm::PassBuilder::OptimizationLevel::O0) {
// matching clang -O0, only add inliner pass
// ref: clang CodeGen/BackEndUtil.cpp EmitAssemblyWithNewPassManager
llvm::ModulePassManager MPM;
MPM.addPass(llvm::AlwaysInlinerPass());
if (verify) MPM.addPass(llvm::VerifierPass());
MPM.run(*module, MAM);
}
else {
// create a clang-like optimisation pipeline for -O1, 2, s, z, 3
llvm::ModulePassManager MPM =
PB.buildPerModuleDefaultPipeline(optLevel);
if (verify) MPM.addPass(llvm::VerifierPass());
MPM.run(*module, MAM);
}
}
#endif
void optimiseAndVerify(llvm::Module* module,
const bool verify,
const CompilerOptions::OptLevel optLevel,
llvm::TargetMachine* TM)
{
if (verify) {
llvm::raw_os_ostream out(std::cout);
if (llvm::verifyModule(*module, &out)) {
OPENVDB_THROW(AXCompilerError, "Generated LLVM IR is not valid.");
}
}
switch (optLevel) {
case CompilerOptions::OptLevel::O0 : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O0, verify, TM);
break;
}
case CompilerOptions::OptLevel::O1 : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O1, verify, TM);
break;
}
case CompilerOptions::OptLevel::O2 : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O2, verify, TM);
break;
}
case CompilerOptions::OptLevel::Os : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::Os, verify, TM);
break;
}
case CompilerOptions::OptLevel::Oz : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::Oz, verify, TM);
break;
}
case CompilerOptions::OptLevel::O3 : {
LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O3, verify, TM);
break;
}
case CompilerOptions::OptLevel::NONE :
default : {}
}
}
void initializeGlobalFunctions(const codegen::FunctionRegistry& registry,
llvm::ExecutionEngine& engine,
llvm::Module& module)
{
/// @note This is a copy of ExecutionEngine::getMangledName. LLVM's ExecutionEngine
/// provides two signatures for updating global mappings, one which takes a void* and
/// another which takes a uint64_t address. When providing function mappings,
/// it is potentially unsafe to cast pointers-to-functions to pointers-to-objects
/// as they are not guaranteed to have the same size on some (albiet non "standard")
/// platforms. getMangledName is protected, so a copy exists here to allows us to
/// call the uint64_t method.
/// @note This is only caught by -pendantic so this work around may be overkill
auto getMangledName = [](const llvm::GlobalValue* GV,
const llvm::ExecutionEngine& E) -> std::string
{
llvm::SmallString<128> FullName;
const llvm::DataLayout& DL =
GV->getParent()->getDataLayout().isDefault()
? E.getDataLayout()
: GV->getParent()->getDataLayout();
llvm::Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
return std::string(FullName.str());
};
/// @note Could use InstallLazyFunctionCreator here instead as follows:
///
/// engine.InstallLazyFunctionCreator([](const std::string& name) -> void * {
/// // Loop through register and find matching symbol
/// });
///
/// However note that if functions have been compiled with mLazyFunctions that the
/// below code using addGlobalMapping() only adds mapping for instantiated
/// functions anyway.
///
/// @note Depending on how functions are inserted into LLVM (Linkage Type) in
/// the future, InstallLazyFunctionCreator may be required
for (const auto& iter : registry.map()) {
const codegen::FunctionGroup* const function = iter.second.function();
if (!function) continue;
const codegen::FunctionGroup::FunctionList& list = function->list();
for (const codegen::Function::Ptr& decl : list) {
// llvmFunction may not exists if compiled without mLazyFunctions
const llvm::Function* llvmFunction = module.getFunction(decl->symbol());
// if the function has an entry block, it's not a C binding - this is a
// quick check to improve performance (so we don't call virtual methods
// for every function)
if (!llvmFunction) continue;
if (llvmFunction->size() > 0) continue;
const codegen::CFunctionBase* binding =
dynamic_cast<const codegen::CFunctionBase*>(decl.get());
if (!binding) {
OPENVDB_LOG_WARN("Function with symbol \"" << decl->symbol() << "\" has "
"no function body and is not a C binding.");
continue;
}
const uint64_t address = binding->address();
if (address == 0) {
OPENVDB_THROW(AXCompilerError, "No available mapping for C Binding "
"with symbol \"" << decl->symbol() << "\"");
}
const std::string mangled =
getMangledName(llvm::cast<llvm::GlobalValue>(llvmFunction), engine);
// error if updateGlobalMapping returned a previously mapped address, as
// we've overwritten something
const uint64_t oldAddress = engine.updateGlobalMapping(mangled, address);
if (oldAddress != 0 && oldAddress != address) {
OPENVDB_THROW(AXCompilerError, "Function registry mapping error - "
"multiple functions are using the same symbol \"" << decl->symbol()
<< "\".");
}
}
}
#ifndef NDEBUG
// Loop through all functions and check to see if they have valid engine mappings.
// This can occur if lazy functions don't initialize their dependencies properly.
// @todo Really we should just loop through the module functions to begin with
// to init engine mappings - it would probably be faster but we'd have to do
// some string manip and it would assume function names have been set up
// correctly
const auto& list = module.getFunctionList();
for (const auto& F : list) {
if (F.size() > 0) continue;
// Some LLVM functions may also not be defined at this stage which is expected
if (!F.getName().startswith("ax")) continue;
const std::string mangled =
getMangledName(llvm::cast<llvm::GlobalValue>(&F), engine);
const uint64_t address =
engine.getAddressToGlobalIfAvailable(mangled);
assert(address != 0 && "Unbound function!");
}
#endif
}
void verifyTypedAccesses(const ast::Tree& tree, openvdb::ax::Logger& logger)
{
// verify the attributes and external variables requested in the syntax tree
// only have a single type. Note that the executer will also throw a runtime
// error if the same attribute is accessed with different types, but as that's
// currently not a valid state on a PointDataGrid, error in compilation as well
// @todo - introduce a framework for supporting custom preprocessors
std::unordered_map<std::string, std::string> nameType;
auto attributeOp =
[&nameType, &logger](const ast::Attribute& node) -> bool {
auto iter = nameType.find(node.name());
if (iter == nameType.end()) {
nameType[node.name()] = node.typestr();
}
else if (iter->second != node.typestr()) {
logger.error("failed to compile ambiguous @ parameters. "
"\"" + node.name() + "\" has been accessed with different type elsewhere.", &node);
}
return true;
};
ast::visitNodeType<ast::Attribute>(tree, attributeOp);
nameType.clear();
auto externalOp =
[&nameType, &logger](const ast::ExternalVariable& node) -> bool {
auto iter = nameType.find(node.name());
if (iter == nameType.end()) {
nameType[node.name()] = node.typestr();
}
else if (iter->second != node.typestr()) {
logger.error("failed to compile ambiguous $ parameters. "
"\"" + node.name() + "\" has been accessed with different type elsewhere.", &node);
}
return true;
};
ast::visitNodeType<ast::ExternalVariable>(tree, externalOp);
}
inline void
registerAccesses(const codegen::SymbolTable& globals, const AttributeRegistry& registry)
{
std::string name, type;
for (const auto& global : globals.map()) {
// detect if this global variable is an attribute access
const std::string& token = global.first;
if (!ast::Attribute::nametypeFromToken(token, &name, &type)) continue;
const ast::tokens::CoreType typetoken =
ast::tokens::tokenFromTypeString(type);
// add the access to the registry - this will force the executables
// to always request or create the data type
const size_t index = registry.accessIndex(name, typetoken);
// should always be a GlobalVariable.
assert(llvm::isa<llvm::GlobalVariable>(global.second));
// Assign the attribute index global a valid index.
// @note executionEngine->addGlobalMapping() can also be used if the indices
// ever need to vary positions without having to force a recompile (previously
// was used unnecessarily)
llvm::GlobalVariable* variable =
llvm::cast<llvm::GlobalVariable>(global.second);
assert(variable->getValueType()->isIntegerTy(64));
variable->setInitializer(llvm::ConstantInt::get(variable->getValueType(), index));
variable->setConstant(true); // is not written to at runtime
}
}
template <typename T, typename MetadataType = TypedMetadata<T>>
inline llvm::Constant*
initializeMetadataPtr(CustomData& data,
const std::string& name,
llvm::LLVMContext& C)
{
MetadataType* meta = data.getOrInsertData<MetadataType>(name);
if (meta) return codegen::LLVMType<T>::get(C, &(meta->value()));
return nullptr;
}
inline void
registerExternalGlobals(const codegen::SymbolTable& globals, CustomData::Ptr& dataPtr, llvm::LLVMContext& C)
{
auto initializerFromToken =
[&](const ast::tokens::CoreType type, const std::string& name, CustomData& data) -> llvm::Constant* {
switch (type) {
case ast::tokens::BOOL : return initializeMetadataPtr<bool>(data, name, C);
case ast::tokens::INT32 : return initializeMetadataPtr<int32_t>(data, name, C);
case ast::tokens::INT64 : return initializeMetadataPtr<int64_t>(data, name, C);
case ast::tokens::FLOAT : return initializeMetadataPtr<float>(data, name, C);
case ast::tokens::DOUBLE : return initializeMetadataPtr<double>(data, name, C);
case ast::tokens::VEC2I : return initializeMetadataPtr<math::Vec2<int32_t>>(data, name, C);
case ast::tokens::VEC2F : return initializeMetadataPtr<math::Vec2<float>>(data, name, C);
case ast::tokens::VEC2D : return initializeMetadataPtr<math::Vec2<double>>(data, name, C);
case ast::tokens::VEC3I : return initializeMetadataPtr<math::Vec3<int32_t>>(data, name, C);
case ast::tokens::VEC3F : return initializeMetadataPtr<math::Vec3<float>>(data, name, C);
case ast::tokens::VEC3D : return initializeMetadataPtr<math::Vec3<double>>(data, name, C);
case ast::tokens::VEC4I : return initializeMetadataPtr<math::Vec4<int32_t>>(data, name, C);
case ast::tokens::VEC4F : return initializeMetadataPtr<math::Vec4<float>>(data, name, C);
case ast::tokens::VEC4D : return initializeMetadataPtr<math::Vec4<double>>(data, name, C);
case ast::tokens::MAT3F : return initializeMetadataPtr<math::Mat3<float>>(data, name, C);
case ast::tokens::MAT3D : return initializeMetadataPtr<math::Mat3<double>>(data, name, C);
case ast::tokens::MAT4F : return initializeMetadataPtr<math::Mat4<float>>(data, name, C);
case ast::tokens::MAT4D : return initializeMetadataPtr<math::Mat4<double>>(data, name, C);
case ast::tokens::STRING : return initializeMetadataPtr<ax::AXString, ax::AXStringMetadata>(data, name, C);
case ast::tokens::UNKNOWN :
default : {
// grammar guarantees this is unreachable as long as all types are supported
OPENVDB_THROW(AXCompilerError, "Attribute type unsupported or not recognised");
}
}
};
std::string name, typestr;
for (const auto& global : globals.map()) {
const std::string& token = global.first;
if (!ast::ExternalVariable::nametypeFromToken(token, &name, &typestr)) continue;
const ast::tokens::CoreType typetoken =
ast::tokens::tokenFromTypeString(typestr);
// if we have any external variables, the custom data must be initialized to at least hold
// zero values (initialized by the default metadata types)
if (!dataPtr) dataPtr.reset(new CustomData);
// should always be a GlobalVariable.
assert(llvm::isa<llvm::GlobalVariable>(global.second));
llvm::GlobalVariable* variable = llvm::cast<llvm::GlobalVariable>(global.second);
assert(variable->getValueType() == codegen::LLVMType<uintptr_t>::get(C));
llvm::Constant* initializer = initializerFromToken(typetoken, name, *dataPtr);
if (!initializer) {
OPENVDB_THROW(AXCompilerError, "Custom data \"" + name + "\" already exists with a "
"different type.");
}
variable->setInitializer(initializer);
variable->setConstant(true); // is not written to at runtime
}
}
struct PointDefaultModifier :
public openvdb::ax::ast::Visitor<PointDefaultModifier, /*non-const*/false>
{
using openvdb::ax::ast::Visitor<PointDefaultModifier, false>::traverse;
using openvdb::ax::ast::Visitor<PointDefaultModifier, false>::visit;
PointDefaultModifier() = default;
virtual ~PointDefaultModifier() = default;
const std::set<std::string> autoVecAttribs {"P", "v", "N", "Cd"};
bool visit(ast::Attribute* attrib) {
if (!attrib->inferred()) return true;
if (autoVecAttribs.find(attrib->name()) == autoVecAttribs.end()) return true;
openvdb::ax::ast::Attribute::UniquePtr
replacement(new openvdb::ax::ast::Attribute(attrib->name(), ast::tokens::VEC3F, true));
if (!attrib->replace(replacement.get())) {
OPENVDB_THROW(AXCompilerError,
"Auto conversion of inferred attributes failed.");
}
replacement.release();
return true;
}
};
} // anonymous namespace
/////////////////////////////////////////////////////////////////////////////
Compiler::Compiler(const CompilerOptions& options)
: mContext()
, mCompilerOptions(options)
, mFunctionRegistry()
{
mContext.reset(new llvm::LLVMContext);
mFunctionRegistry = codegen::createDefaultRegistry(&options.mFunctionOptions);
}
Compiler::UniquePtr Compiler::create(const CompilerOptions &options)
{
UniquePtr compiler(new Compiler(options));
return compiler;
}
void Compiler::setFunctionRegistry(std::unique_ptr<codegen::FunctionRegistry>&& functionRegistry)
{
mFunctionRegistry = std::move(functionRegistry);
}
template<>
PointExecutable::Ptr
Compiler::compile<PointExecutable>(const ast::Tree& syntaxTree,
Logger& logger,
const CustomData::Ptr customData)
{
openvdb::SharedPtr<ast::Tree> tree(syntaxTree.copy());
PointDefaultModifier modifier;
modifier.traverse(tree.get());
verifyTypedAccesses(*tree, logger);
// initialize the module and generate LLVM IR
std::unique_ptr<llvm::Module> module(new llvm::Module("module", *mContext));
std::unique_ptr<llvm::TargetMachine> TM = initializeTargetMachine();
if (TM) {
module->setDataLayout(TM->createDataLayout());
module->setTargetTriple(TM->getTargetTriple().normalize());
}
codegen::codegen_internal::PointComputeGenerator
codeGenerator(*module, mCompilerOptions.mFunctionOptions,
*mFunctionRegistry, logger);
AttributeRegistry::Ptr attributes = codeGenerator.generate(*tree);
// if there has been a compilation error through user error, exit
if (!attributes) {
assert(logger.hasError());
return nullptr;
}
// map accesses (always do this prior to optimising as globals may be removed)
registerAccesses(codeGenerator.globals(), *attributes);
CustomData::Ptr validCustomData(customData);
registerExternalGlobals(codeGenerator.globals(), validCustomData, *mContext);
// optimise
llvm::Module* modulePtr = module.get();
optimiseAndVerify(modulePtr, mCompilerOptions.mVerify, mCompilerOptions.mOptLevel, TM.get());
// @todo re-constant fold!! although constant folding will work with constant
// expressions prior to optimisation, expressions like "int a = 1; cosh(a);"
// will still keep a call to cosh. This is because the current AX folding
// only checks for an immediate constant expression and for C bindings,
// like cosh, llvm its unable to optimise the call out (as it isn't aware
// of the function body). What llvm can do, however, is change this example
// into "cosh(1)" which we can then handle.
// create the llvm execution engine which will build our function pointers
std::string error;
std::shared_ptr<llvm::ExecutionEngine>
executionEngine(llvm::EngineBuilder(std::move(module))
.setEngineKind(llvm::EngineKind::JIT)
.setErrorStr(&error)
.create());
if (!executionEngine) {
OPENVDB_THROW(AXCompilerError, "Failed to create LLVMExecutionEngine: " + error);
}
// map functions
initializeGlobalFunctions(*mFunctionRegistry, *executionEngine, *modulePtr);
// finalize mapping
executionEngine->finalizeObject();
// get the built function pointers
const std::vector<std::string> functionNames {
codegen::PointKernel::getDefaultName(),
codegen::PointRangeKernel::getDefaultName()
};
std::unordered_map<std::string, uint64_t> functionMap;
for (const std::string& name : functionNames) {
const uint64_t address = executionEngine->getFunctionAddress(name);
if (!address) {
OPENVDB_THROW(AXCompilerError, "Failed to compile compute function \"" + name + "\"");
}
functionMap[name] = address;
}
// create final executable object
PointExecutable::Ptr
executable(new PointExecutable(mContext,
executionEngine,
attributes,
validCustomData,
functionMap));
return executable;
}
template<>
VolumeExecutable::Ptr
Compiler::compile<VolumeExecutable>(const ast::Tree& syntaxTree,
Logger& logger,
const CustomData::Ptr customData)
{
verifyTypedAccesses(syntaxTree, logger);
// initialize the module and generate LLVM IR
std::unique_ptr<llvm::Module> module(new llvm::Module("module", *mContext));
std::unique_ptr<llvm::TargetMachine> TM = initializeTargetMachine();
if (TM) {
module->setDataLayout(TM->createDataLayout());
module->setTargetTriple(TM->getTargetTriple().normalize());
}
codegen::codegen_internal::VolumeComputeGenerator
codeGenerator(*module, mCompilerOptions.mFunctionOptions,
*mFunctionRegistry, logger);
AttributeRegistry::Ptr attributes = codeGenerator.generate(syntaxTree);
// if there has been a compilation error through user error, exit
if (!attributes) {
assert(logger.hasError());
return nullptr;
}
// map accesses (always do this prior to optimising as globals may be removed)
registerAccesses(codeGenerator.globals(), *attributes);
CustomData::Ptr validCustomData(customData);
registerExternalGlobals(codeGenerator.globals(), validCustomData, *mContext);
llvm::Module* modulePtr = module.get();
optimiseAndVerify(modulePtr, mCompilerOptions.mVerify, mCompilerOptions.mOptLevel, TM.get());
std::string error;
std::shared_ptr<llvm::ExecutionEngine>
executionEngine(llvm::EngineBuilder(std::move(module))
.setEngineKind(llvm::EngineKind::JIT)
.setErrorStr(&error)
.create());
if (!executionEngine) {
OPENVDB_THROW(AXCompilerError, "Failed to create LLVMExecutionEngine: " + error);
}
// map functions
initializeGlobalFunctions(*mFunctionRegistry, *executionEngine,
*modulePtr);
// finalize mapping
executionEngine->finalizeObject();
const std::string name = codegen::VolumeKernel::getDefaultName();
const uint64_t address = executionEngine->getFunctionAddress(name);
if (!address) {
OPENVDB_THROW(AXCompilerError, "Failed to compile compute function \"" + name + "\"");
}
std::unordered_map<std::string, uint64_t> functionMap;
functionMap[name] = address;
// create final executable object
VolumeExecutable::Ptr
executable(new VolumeExecutable(mContext,
executionEngine,
attributes,
validCustomData,
functionMap));
return executable;
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 32,049 | C++ | 37.801453 | 120 | 0.649069 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/PointExecutable.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/PointExecutable.h
///
/// @authors Nick Avramoussis, Francisco Gochez, Richard Jones
///
/// @brief The PointExecutable, produced by the OpenVDB AX Compiler for
/// execution over OpenVDB Points Grids.
///
#ifndef OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED
#include "CustomData.h"
#include "AttributeRegistry.h"
#include <openvdb/openvdb.h>
#include <openvdb/version.h>
#include <openvdb/points/PointDataGrid.h>
#include <unordered_map>
class TestPointExecutable;
namespace llvm {
class ExecutionEngine;
class LLVMContext;
}
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
class Compiler;
/// @brief Object that encapsulates compiled AX code which can be executed on a target point grid
class PointExecutable
{
public:
using Ptr = std::shared_ptr<PointExecutable>;
~PointExecutable();
/// @brief Copy constructor. Shares the LLVM constructs but deep copies the
/// settings. Multiple copies of an executor can be used at the same time
/// safely.
PointExecutable(const PointExecutable& other);
////////////////////////////////////////////////////////
/// @brief executes compiled AX code on target grid
void execute(points::PointDataGrid& grid) const;
////////////////////////////////////////////////////////
/// @brief Set a specific point group to execute over. The default is none,
/// which corresponds to all points. Note that this can also be compiled
/// into the AX function using the ingroup("mygroup") method.
/// @warning If the group does not exist during execute, a runtime error
/// will be thrown.
/// @param name The name of the group to execute over
void setGroupExecution(const std::string& name);
/// @return The points group to be processed. Default is empty, which is
/// all points.
const std::string& getGroupExecution() const;
/// @brief Set the behaviour when missing point attributes are accessed.
/// Default behaviour is true, which creates them with default initial
/// values. If false, a missing attribute runtime error will be thrown
/// on missing accesses.
/// @param flag Enables or disables the creation of missing attributes
void setCreateMissing(const bool flag);
/// @return Whether this executable will generate new point attributes.
bool getCreateMissing() const;
/// @brief Set the threading grain size. Default is 1. A value of 0 has the
/// effect of disabling multi-threading.
/// @param grain The grain size
void setGrainSize(const size_t grain);
/// @return The current grain size
size_t getGrainSize() const;
////////////////////////////////////////////////////////
// foward declaration of settings for this executable
struct Settings;
private:
friend class Compiler;
friend class ::TestPointExecutable;
/// @brief Constructor, expected to be invoked by the compiler. Should not
/// be invoked directly.
/// @param context Shared pointer to an llvm:LLVMContext associated with the
/// execution engine
/// @param engine Shared pointer to an llvm::ExecutionEngine used to build
/// functions. Context should be the associated LLVMContext
/// @param attributeRegistry Registry of attributes accessed by AX code
/// @param customData Custom data which will be shared by this executable.
/// It can be used to retrieve external data from within the AX code
/// @param functions A map of function names to physical memory addresses
/// which were built by llvm using engine
PointExecutable(const std::shared_ptr<const llvm::LLVMContext>& context,
const std::shared_ptr<const llvm::ExecutionEngine>& engine,
const AttributeRegistry::ConstPtr& attributeRegistry,
const CustomData::ConstPtr& customData,
const std::unordered_map<std::string, uint64_t>& functions);
private:
// The Context and ExecutionEngine must exist _only_ for object lifetime
// management. The ExecutionEngine must be destroyed before the Context
const std::shared_ptr<const llvm::LLVMContext> mContext;
const std::shared_ptr<const llvm::ExecutionEngine> mExecutionEngine;
const AttributeRegistry::ConstPtr mAttributeRegistry;
const CustomData::ConstPtr mCustomData;
const std::unordered_map<std::string, uint64_t> mFunctionAddresses;
std::unique_ptr<Settings> mSettings;
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED
| 4,845 | C | 37.15748 | 97 | 0.687307 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Logger.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/Logger.h
///
/// @authors Richard Jones
///
/// @brief Logging system to collect errors and warnings throughout the
/// different stages of parsing and compilation.
///
#ifndef OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED
#include "../ast/AST.h"
#include <openvdb/version.h>
#include <functional>
#include <string>
#include <unordered_map>
class TestLogger;
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @brief Logger for collecting errors and warnings that occur during AX
/// compilation.
///
/// @details Error and warning output can be customised using the function
/// pointer arguments. These require a function that takes the formatted error
/// or warning string and handles the output, returning void.
/// e.g.
/// void streamCerr(const std::string& message) {
/// std::cerr << message << std::endl;
/// }
///
/// The Logger handles formatting of messages, tracking of number of errors or
/// warnings and retrieval of errored lines of code to be printed if needed.
/// Use of the Logger to track new errors or warnings can be done either with
/// the line/column numbers directly (e.g during lexing and parsing where the
/// code is being iterated through) or referring to the AST node using its
/// position in the Tree (e.g. during codegen where only the AST node is known
/// directly, not the corresponding line/column numbers). To find the line or
/// column numbers for events logged using AST nodes, the Logger stores a map
/// of Node* to line and column numbers. This must be populated e.g. during
/// parsing, to allow resolution of code locations when they are not
/// explicitly available. The Logger also stores a pointer to the AST Tree
/// that these nodes belong to and the code used to create it.
class Logger
{
public:
using Ptr = std::shared_ptr<Logger>;
using CodeLocation = std::pair<size_t, size_t>;
using OutputFunction = std::function<void(const std::string&)>;
/// @brief Construct a Logger with optional error and warning output
/// functions, defaults stream errors to std::cerr and suppress warnings
/// @param errors Optional error output function
/// @param warnings Optional warning output function
Logger(const OutputFunction& errors =
[](const std::string& msg){
std::cerr << msg << std::endl;
},
const OutputFunction& warnings = [](const std::string&){});
~Logger();
/// @brief Log a compiler error and its offending code location.
/// @param message The error message
/// @param lineCol The line/column number of the offending code
/// @return true if non-fatal and can continue to capture future messages.
/// @todo: add logging of non position specific errors
bool error(const std::string& message, const CodeLocation& lineCol);
/// @brief Log a compiler error using the offending AST node. Used in AST
/// traversal.
/// @param message The error message
/// @param node The offending AST node causing the error
/// @return true if non-fatal and can continue to capture future messages.
bool error(const std::string& message, const ax::ast::Node* node);
/// @brief Log a compiler warning and its offending code location.
/// @param message The warning message
/// @param lineCol The line/column number of the offending code
/// @return true if non-fatal and can continue to capture future messages.
bool warning(const std::string& message, const CodeLocation& lineCol);
/// @brief Log a compiler warning using the offending AST node. Used in AST
/// traversal.
/// @param message The warning message
/// @param node The offending AST node causing the warning
/// @return true if non-fatal and can continue to capture future messages.
bool warning(const std::string& message, const ax::ast::Node* node);
///
/// @brief Returns the number of errors that have been encountered
inline size_t errors() const { return mNumErrors; }
/// @brief Returns the number of warnings that have been encountered
inline size_t warnings() const { return mNumWarnings; }
/// @brief Returns true if an error has been found, false otherwise
inline bool hasError() const { return this->errors() > 0; }
/// @brief Returns true if a warning has been found, false otherwise
inline bool hasWarning() const { return this->warnings() > 0; }
/// @brief Returns true if it has errored and the max errors has been hit
inline bool atErrorLimit() const {
return this->getMaxErrors() > 0 && this->errors() >= this->getMaxErrors();
}
/// @brief Clear the tree-code mapping and reset the number of errors/warnings
/// @note The tree-code mapping must be repopulated to retrieve line and
/// column numbers during AST traversal i.e. code generation. The
/// openvdb::ax::ast::parse() function does this for a given input code
/// string.
void clear();
/// @brief Set any warnings that are encountered to be promoted to errors
/// @param warnAsError If true, warnings will be treated as errors
void setWarningsAsErrors(const bool warnAsError = false);
/// @brief Returns if warning are promoted to errors
bool getWarningsAsErrors() const;
/// @brief Sets the maximum number of errors that are allowed before
/// compilation should exit
/// @param maxErrors The number of allowed errors
void setMaxErrors(const size_t maxErrors = 0);
/// @brief Returns the number of allowed errors
size_t getMaxErrors() const;
/// Error/warning formatting options
/// @brief Set whether the output should number the errors/warnings
/// @param numbered If true, messages will be numbered
void setNumberedOutput(const bool numbered = true);
/// @brief Set a prefix for each error message
void setErrorPrefix(const char* prefix = "error: ");
/// @brief Set a prefix for each warning message
void setWarningPrefix(const char* prefix = "warning: ");
/// @brief Set whether the output should include the offending line of code
/// @param print If true, offending lines of code will be appended to the
/// output message
void setPrintLines(const bool print = true);
/// @brief Returns whether the messages will be numbered
bool getNumberedOutput() const;
/// @brief Returns the prefix for each error message
const char* getErrorPrefix() const;
/// @brief Returns the prefix for each warning message
const char* getWarningPrefix() const;
/// @brief Returns whether the messages will include the line of offending code
bool getPrintLines() const;
/// @brief Set the source code that lines can be printed from if an error or
/// warning is raised
/// @param code The AX code as a c-style string
void setSourceCode(const char* code);
/// These functions are only to be used during parsing to allow line and
/// column number retrieval during later stages of compilation when working
/// solely with an AST
/// @brief Set the AST source tree which will be used as reference for the
/// locations of nodes when resolving line and column numbers during AST
/// traversal
/// @note To be used just by ax::parse before any AST modifications to
/// ensure traversal of original source tree is possible, when adding
/// messages using Node* which may correspond to modified trees
/// @param tree Pointer to const AST
void setSourceTree(openvdb::ax::ast::Tree::ConstPtr tree);
/// @brief Add a node to the code location map
/// @param node Pointer to AST node
/// @param location Line and column number in code
void addNodeLocation(const ax::ast::Node* node, const CodeLocation& location);
// forward declaration
struct Settings;
struct SourceCode;
private:
friend class ::TestLogger;
std::function<void(const std::string&)> mErrorOutput;
std::function<void(const std::string&)> mWarningOutput;
size_t mNumErrors;
size_t mNumWarnings;
std::unique_ptr<Settings> mSettings;
// components needed for verbose error info i.e. line/column numbers and
// lines from source code
std::unique_ptr<SourceCode> mCode;
ax::ast::Tree::ConstPtr mTreePtr;
std::unordered_map<const ax::ast::Node*, CodeLocation> mNodeToLineColMap;
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED
| 8,761 | C | 40.526066 | 83 | 0.696496 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/AttributeRegistry.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0/
/// @file compiler/AttributeRegistry.h
///
/// @authors Nick Avramoussis, Francisco Gochez
///
/// @brief These classes contain lists of expected attributes and volumes
/// which are populated by compiler during its internal code generation.
/// These will then be requested from the inputs to the executable
/// when execute is called. In this way, accesses are requested at
/// execution time, allowing the executable objects to be shared and
/// stored.
///
#ifndef OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED
#include "../ast/AST.h"
#include "../ast/Tokens.h"
#include "../ast/Scanners.h"
#include <openvdb/version.h>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @brief This class stores a list of access names, types and their dependency
/// connections.
///
class AttributeRegistry
{
public:
using Ptr = std::shared_ptr<AttributeRegistry>;
using ConstPtr = std::shared_ptr<const AttributeRegistry>;
/// @brief Registered access details, including its name, type and whether
/// a write handle is required
///
struct AccessData
{
/// @brief Storage for access name, type and writesTo details
/// @param name The name of the access
/// @param type The typename of the access
/// @param readsFrom Whether the access is read from
/// @param writesTo Whether the access is writte to
AccessData(const Name& name,
const ast::tokens::CoreType type,
const bool readsFrom,
const bool writesTo)
: mAttrib(name, type)
, mAccess(readsFrom, writesTo)
, mUses()
, mDependencies() {}
bool reads() const { return mAccess.first; }
bool writes() const { return mAccess.second; }
const std::string tokenname() const { return mAttrib.tokenname(); }
const std::string& name() const { return mAttrib.name(); }
ast::tokens::CoreType type() const { return mAttrib.type(); }
const std::vector<const AccessData*>& deps() const { return mDependencies; }
const std::vector<const AccessData*>& uses() const { return mUses; }
bool dependson(const AccessData* data) const {
for (auto& dep : mDependencies) {
if (dep == data) return true;
}
return false;
}
bool affectsothers() const {
for (auto& dep : mUses) {
if (dep != this) return true;
}
return false;
}
private:
friend AttributeRegistry;
const ast::Attribute mAttrib;
const std::pair<bool, bool> mAccess;
std::vector<const AccessData*> mUses; // Accesses which depend on this access
std::vector<const AccessData*> mDependencies; // Accesses which this access depends on
};
using AccessDataVec = std::vector<AccessData>;
inline static AttributeRegistry::Ptr create(const ast::Tree& tree);
inline bool isReadable(const std::string& name, const ast::tokens::CoreType type) const
{
return this->accessPattern(name, type).first;
}
/// @brief Returns whether or not an access is required to be written to.
/// If no access with this name has been registered, returns false
/// @param name The name of the access
/// @param type The type of the access
inline bool isWritable(const std::string& name, const ast::tokens::CoreType type) const
{
return this->accessPattern(name, type).second;
}
inline std::pair<bool,bool>
accessPattern(const std::string& name, const ast::tokens::CoreType type) const
{
for (const auto& data : mAccesses) {
if ((type == ast::tokens::UNKNOWN || data.type() == type)
&& data.name() == name) {
return data.mAccess;
}
}
return std::pair<bool,bool>(false,false);
}
/// @brief Returns whether or not an access is registered.
/// @param name The name of the access
/// @param type The type of the access
inline bool isRegistered(const std::string& name, const ast::tokens::CoreType type) const
{
return this->accessIndex(name, type) != -1;
}
/// @brief Returns whether or not an access is registered.
/// @param name The name of the access
/// @param type The type of the access
inline int64_t
accessIndex(const std::string& name,
const ast::tokens::CoreType type) const
{
int64_t i = 0;
for (const auto& data : mAccesses) {
if (data.type() == type && data.name() == name) {
return i;
}
++i;
}
return -1;
}
/// @brief Returns a const reference to the vector of registered accesss
inline const AccessDataVec& data() const { return mAccesses; }
void print(std::ostream& os) const;
private:
AttributeRegistry() : mAccesses() {}
/// @brief Add an access to the registry, returns an index into
/// the registry for that access
/// @param name The name of the access
/// @param type The typename of the access
/// @param writesTo Whether the access is required to be writeable
///
inline void
addData(const Name& name,
const ast::tokens::CoreType type,
const bool readsfrom,
const bool writesto) {
mAccesses.emplace_back(name, type, readsfrom, writesto);
}
AccessDataVec mAccesses;
};
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
inline AttributeRegistry::Ptr AttributeRegistry::create(const ast::Tree& tree)
{
AttributeRegistry::Ptr registry(new AttributeRegistry());
std::vector<std::string> read, write, all;
ast::catalogueAttributeTokens(tree, &read, &write, &all);
size_t idx = 0;
std::unordered_map<std::string, size_t> indexmap;
auto dataBuilder =
[&](const std::vector<std::string>& attribs,
const bool readFlag,
const bool writeFlag)
{
std::string name, type;
for (const auto& attrib : attribs) {
ast::Attribute::nametypeFromToken(attrib, &name, &type);
const ast::tokens::CoreType typetoken =
ast::tokens::tokenFromTypeString(type);
registry->addData(name, typetoken, readFlag, writeFlag);
indexmap[attrib] = idx++;
}
};
// insert all data
dataBuilder(read, true, false);
dataBuilder(write, false, true);
dataBuilder(all, true, true);
auto depBuilder = [&](const std::vector<std::string>& attribs) {
std::string name, type;
for (const auto& attrib : attribs) {
ast::Attribute::nametypeFromToken(attrib, &name, &type);
const ast::tokens::CoreType typetoken =
ast::tokens::tokenFromTypeString(type);
std::vector<std::string> deps;
ast::attributeDependencyTokens(tree, name, typetoken, deps);
if (deps.empty()) continue;
assert(indexmap.find(attrib) != indexmap.cend());
const size_t index = indexmap.at(attrib);
AccessData& access = registry->mAccesses[index];
for (const std::string& dep : deps) {
assert(indexmap.find(dep) != indexmap.cend());
const size_t depindex = indexmap.at(dep);
access.mDependencies.emplace_back(®istry->mAccesses[depindex]);
}
}
};
// initialize dependencies
depBuilder(read);
depBuilder(write);
depBuilder(all);
// Update usage from deps
for (AccessData& access : registry->mAccesses) {
for (const AccessData& next : registry->mAccesses) {
// don't skip self depends as it may write to itself
// i.e. @a = @a + 1; should add a self usage
if (next.dependson(&access)) {
access.mUses.emplace_back(&next);
}
}
}
return registry;
}
inline void AttributeRegistry::print(std::ostream& os) const
{
size_t idx = 0;
for (const auto& data : mAccesses) {
os << "Attribute: " << data.name() << ", type: " <<
ast::tokens::typeStringFromToken(data.type()) << '\n';
os << " " << "Index : " << idx << '\n';
os << std::boolalpha;
os << " " << "Reads From : " << data.reads() << '\n';
os << " " << "Writes To : " << data.writes() << '\n';
os << std::noboolalpha;
os << " " << "Dependencies : " << data.mDependencies.size() << '\n';
for (const auto& dep : data.mDependencies) {
os << " " << "Attribute: " << dep->name() << " type: " <<
ast::tokens::typeStringFromToken(dep->type()) << '\n';
}
os << " " << "Usage : " << data.mUses.size() << '\n';
for (const auto& dep : data.mUses) {
os << " " << "Attribute: " << dep->name() << " type: " <<
ast::tokens::typeStringFromToken(dep->type()) << '\n';
}
os << '\n';
++idx;
}
}
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED
| 9,597 | C | 32.915194 | 94 | 0.579139 |
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/CompilerOptions.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file compiler/CompilerOptions.h
///
/// @authors Nick Avramoussis
///
/// @brief OpenVDB AX Compiler Options
///
#ifndef OPENVDB_AX_COMPILER_COMPILER_OPTIONS_HAS_BEEN_INCLUDED
#define OPENVDB_AX_COMPILER_COMPILER_OPTIONS_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include <openvdb/version.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace ax {
/// @brief Options that control how functions behave
struct FunctionOptions
{
/// @brief Enable the constant folding of C bindings. Functions may use this setting
/// to determine whether they are allowed to be called during code generation
/// to evaluate call sites with purely constant arguments and replace the call
/// with the result.
/// @note This does not impact IR functions which we leave to LLVM's CF during
/// IR optimization.
/// @note We used to bind IR methods to corresponding C bindings, however it can be
/// very easy to implement incorrectly, leading to discrepancies in the CF
/// results. Fundamentally, LLVM's support for CF IR is far superior and our
/// framework only supports some types of folding (see codegen/ConstantFolding.h)
bool mConstantFoldCBindings = true;
/// @brief When enabled, functions which have IR builder instruction definitions will
/// prioritise those over any registered external calls
bool mPrioritiseIR = true;
/// @brief When enabled, the function registry is only populated on a function visit.
/// At the end of code generation, only functions which have been instantiated
/// will exist in the function map.
bool mLazyFunctions = true;
};
/// @brief Settings which control how a Compiler class object behaves
struct CompilerOptions
{
/// @brief Controls the llvm compiler optimization level
enum class OptLevel
{
NONE, // Do not run any optimization passes
O0, // Optimization level 0. Similar to clang -O0
O1, // Optimization level 1. Similar to clang -O1
O2, // Optimization level 2. Similar to clang -O2
Os, // Like -O2 with extra optimizations for size. Similar to clang -Os
Oz, // Like -Os but reduces code size further. Similar to clang -Oz
O3 // Optimization level 3. Similar to clang -O3
};
OptLevel mOptLevel = OptLevel::O3;
/// @brief If this flag is true, the generated llvm module will be verified when compilation
/// occurs, resulting in an exception being thrown if it is not valid
bool mVerify = true;
/// @brief Options for the function registry
FunctionOptions mFunctionOptions = FunctionOptions();
};
} // namespace ax
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_AX_COMPILER_FUNCTION_REGISTRY_OPTIONS_HAS_BEEN_INCLUDED
| 2,989 | C | 38.342105 | 96 | 0.694881 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.