file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
arhix52/Strelka/src/HdStrelka/RendererPlugin.cpp | #include "RendererPlugin.h"
#include "RenderDelegate.h"
#include <pxr/imaging/hd/rendererPluginRegistry.h>
#include <pxr/base/plug/plugin.h>
#include "pxr/base/plug/thisPlugin.h"
#include <log.h>
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfType)
{
HdRendererPluginRegistry::Define<HdStrelkaRendererPlugin>();
}
HdStrelkaRendererPlugin::HdStrelkaRendererPlugin()
{
const PlugPluginPtr plugin = PLUG_THIS_PLUGIN;
const std::string& resourcePath = plugin->GetResourcePath();
STRELKA_INFO("Resource path: {}", resourcePath.c_str());
const std::string shaderPath = resourcePath + "/shaders";
const std::string mtlxmdlPath = resourcePath + "/mtlxmdl";
const std::string mtlxlibPath = resourcePath + "/mtlxlib";
// m_translator = std::make_unique<MaterialNetworkTranslator>(mtlxlibPath);
const char* envUSDPath = std::getenv("USD_DIR");
if (!envUSDPath)
{
STRELKA_FATAL("Please, set USD_DIR variable\n");
assert(0);
m_isSupported = false;
}
else
{
const std::string USDPath(envUSDPath);
m_translator = std::make_unique<MaterialNetworkTranslator>(USDPath + "/libraries");
m_isSupported = true;
}
}
HdStrelkaRendererPlugin::~HdStrelkaRendererPlugin()
{
}
HdRenderDelegate* HdStrelkaRendererPlugin::CreateRenderDelegate()
{
HdRenderSettingsMap settingsMap = {};
return new HdStrelkaRenderDelegate(settingsMap, *m_translator);
}
HdRenderDelegate* HdStrelkaRendererPlugin::CreateRenderDelegate(const HdRenderSettingsMap& settingsMap)
{
return new HdStrelkaRenderDelegate(settingsMap, *m_translator);
}
void HdStrelkaRendererPlugin::DeleteRenderDelegate(HdRenderDelegate* renderDelegate)
{
delete renderDelegate;
}
bool HdStrelkaRendererPlugin::IsSupported(bool gpuEnabled) const
{
return m_isSupported;
}
PXR_NAMESPACE_CLOSE_SCOPE
|
arhix52/Strelka/src/materialmanager/mdlMaterialCompiler.cpp | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "mdlMaterialCompiler.h"
#include <mi/mdl_sdk.h>
#include <atomic>
#include <cassert>
#include <iostream>
namespace oka
{
std::string _makeModuleName(const std::string& identifier)
{
return "::" + identifier;
}
MdlMaterialCompiler::MdlMaterialCompiler(MdlRuntime& runtime)
{
mLogger = mi::base::Handle<MdlLogger>(runtime.getLogger());
mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(runtime.getDatabase());
mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(runtime.getTransaction());
mFactory = mi::base::Handle<mi::neuraylib::IMdl_factory>(runtime.getFactory());
mImpExpApi = mi::base::Handle<mi::neuraylib::IMdl_impexp_api>(runtime.getImpExpApi());
}
bool MdlMaterialCompiler::createModule(const std::string& identifier,
std::string& moduleName)
{
mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context());
moduleName = _makeModuleName(identifier);
mi::Sint32 result = mImpExpApi->load_module(mTransaction.get(), moduleName.c_str(), context.get());
mLogger->flushContextMessages(context.get());
return result == 0 || result == 1;
}
bool MdlMaterialCompiler::createMaterialInstace(const char* moduleName, const char* identifier, mi::base::Handle<mi::neuraylib::IFunction_call>& matInstance)
{
mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context());
mi::base::Handle<const mi::IString> moduleDbName(mFactory->get_db_module_name(moduleName));
mi::base::Handle<const mi::neuraylib::IModule> module(mTransaction->access<mi::neuraylib::IModule>(moduleDbName->get_c_str()));
assert(module);
std::string materialDbName = std::string(moduleDbName->get_c_str()) + "::" + identifier;
mi::base::Handle<const mi::IArray> funcs(module->get_function_overloads(materialDbName.c_str(), (const mi::neuraylib::IExpression_list*)nullptr));
if (funcs->get_length() == 0)
{
std::string errorMsg = std::string("Material with identifier ") + identifier + " not found in MDL module\n";
mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, errorMsg.c_str());
return false;
}
if (funcs->get_length() > 1)
{
std::string errorMsg = std::string("Ambigious material identifier ") + identifier + " for MDL module\n";
mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, errorMsg.c_str());
return false;
}
mi::base::Handle<const mi::IString> exactMaterialDbName(funcs->get_element<mi::IString>(0));
// get material definition from database
mi::base::Handle<const mi::neuraylib::IFunction_definition> matDefinition(mTransaction->access<mi::neuraylib::IFunction_definition>(exactMaterialDbName->get_c_str()));
if (!matDefinition)
{
return false;
}
mi::Sint32 result;
// instantiate material with default parameters and store in database
matInstance = matDefinition->create_function_call(nullptr, &result);
if (result != 0 || !matInstance)
{
return false;
}
return true;
}
bool MdlMaterialCompiler::compileMaterial(mi::base::Handle<mi::neuraylib::IFunction_call>& instance, mi::base::Handle<mi::neuraylib::ICompiled_material>& compiledMaterial)
{
if (!instance)
{
// TODO: log error
return false;
}
mi::base::Handle<mi::neuraylib::IMdl_execution_context> context(mFactory->create_execution_context());
// performance optimizations available only in class compilation mode
// (all parameters are folded in instance mode)
context->set_option("fold_all_bool_parameters", true);
// context->set_option("fold_all_enum_parameters", true);
context->set_option("ignore_noinline", true);
context->set_option("fold_ternary_on_df", true);
auto flags = mi::neuraylib::IMaterial_instance::CLASS_COMPILATION;
// auto flags = mi::neuraylib::IMaterial_instance::DEFAULT_OPTIONS;
mi::base::Handle<mi::neuraylib::IMaterial_instance> material_instance2(
instance->get_interface<mi::neuraylib::IMaterial_instance>());
compiledMaterial = mi::base::Handle<mi::neuraylib::ICompiled_material>(material_instance2->create_compiled_material(flags, context.get()));
mLogger->flushContextMessages(context.get());
return true;
}
mi::base::Handle<mi::neuraylib::IMdl_factory>& MdlMaterialCompiler::getFactory()
{
return mFactory;
}
mi::base::Handle<mi::neuraylib::ITransaction>& MdlMaterialCompiler::getTransaction()
{
return mTransaction;
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/material.mdl | |
arhix52/Strelka/src/materialmanager/mdlNeurayLoader.cpp | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "mdlNeurayLoader.h"
#include <mi/mdl_sdk.h>
#ifdef MI_PLATFORM_WINDOWS
# include <mi/base/miwindows.h>
#else
# include <dlfcn.h>
#endif
#include "iostream"
#include <string>
namespace oka
{
MdlNeurayLoader::MdlNeurayLoader()
: mDsoHandle(nullptr), mNeuray(nullptr)
{
}
MdlNeurayLoader::~MdlNeurayLoader()
{
if (mNeuray)
{
mNeuray->shutdown();
mNeuray.reset();
}
if (mDsoHandle)
{
unloadDso();
}
}
bool MdlNeurayLoader::init(const char* resourcePath, const char* imagePluginPath)
{
if (!loadDso(resourcePath))
{
return false;
}
if (!loadNeuray())
{
return false;
}
if (!loadPlugin(imagePluginPath))
{
return false;
}
return mNeuray->start() == 0;
}
mi::base::Handle<mi::neuraylib::INeuray> MdlNeurayLoader::getNeuray() const
{
return mNeuray;
}
bool MdlNeurayLoader::loadPlugin(const char* imagePluginPath)
{
// init plugin for texture support
mi::base::Handle<mi::neuraylib::INeuray> neuray(getNeuray());
mi::base::Handle<mi::neuraylib::IPlugin_configuration> configPl(neuray->get_api_component<mi::neuraylib::IPlugin_configuration>());
if (configPl->load_plugin_library(imagePluginPath)) // This function can only be called before the MDL SDK has been started.
{
std::cout << "Plugin file path not found, translation not possible" << std::endl;
return false;
}
return true;
}
bool MdlNeurayLoader::loadDso(const char* resourcePath)
{
std::string dsoFilename = std::string(resourcePath) + std::string("/libmdl_sdk" MI_BASE_DLL_FILE_EXT);
#ifdef MI_PLATFORM_WINDOWS
HMODULE handle = LoadLibraryA(dsoFilename.c_str());
if (!handle)
{
LPTSTR buffer = NULL;
LPCTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
0, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0))
{
message = buffer;
}
fprintf(stderr, "Failed to load library (%u): %s", error_code, message);
if (buffer)
{
LocalFree(buffer);
}
return false;
}
#else
void* handle = dlopen(dsoFilename.c_str(), RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "%s\n", dlerror());
return false;
}
#endif
mDsoHandle = handle;
return true;
}
bool MdlNeurayLoader::loadNeuray()
{
#ifdef MI_PLATFORM_WINDOWS
void* symbol = GetProcAddress(reinterpret_cast<HMODULE>(mDsoHandle), "mi_factory");
if (!symbol)
{
LPTSTR buffer = NULL;
LPCTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
0, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0))
{
message = buffer;
}
fprintf(stderr, "GetProcAddress error (%u): %s", error_code, message);
if (buffer)
{
LocalFree(buffer);
}
return false;
}
#else
void* symbol = dlsym(mDsoHandle, "mi_factory");
if (!symbol)
{
fprintf(stderr, "%s\n", dlerror());
return false;
}
#endif
mNeuray = mi::base::Handle<mi::neuraylib::INeuray>(mi::neuraylib::mi_factory<mi::neuraylib::INeuray>(symbol));
if (mNeuray.is_valid_interface())
{
return true;
}
mi::base::Handle<mi::neuraylib::IVersion> version(mi::neuraylib::mi_factory<mi::neuraylib::IVersion>(symbol));
if (!version)
{
fprintf(stderr, "Error: Incompatible library.\n");
}
else
{
fprintf(stderr, "Error: Library version %s does not match header version %s.\n", version->get_product_version(), MI_NEURAYLIB_PRODUCT_VERSION_STRING);
}
return false;
}
void MdlNeurayLoader::unloadDso()
{
#ifdef MI_PLATFORM_WINDOWS
if (FreeLibrary(reinterpret_cast<HMODULE>(mDsoHandle)))
{
return;
}
LPTSTR buffer = 0;
LPCTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
0, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, 0))
{
message = buffer;
}
fprintf(stderr, "Failed to unload library (%u): %s", error_code, message);
if (buffer)
{
LocalFree(buffer);
}
#else
if (dlclose(mDsoHandle) != 0)
{
printf("%s\n", dlerror());
}
#endif
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/materialmanager.cpp | #include "materialmanager.h"
#include "materials.h"
#include <mi/mdl_sdk.h>
#include "mdlPtxCodeGen.h"
#include "mdlLogger.h"
#include "mdlMaterialCompiler.h"
#include "mdlNeurayLoader.h"
#include "mdlRuntime.h"
#include "mtlxMdlCodeGen.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <log.h>
namespace fs = std::filesystem;
namespace oka
{
struct MaterialManager::Module
{
std::string moduleName;
std::string identifier;
};
struct MaterialManager::MaterialInstance
{
mi::base::Handle<mi::neuraylib::IFunction_call> instance;
};
struct MaterialManager::CompiledMaterial
{
mi::base::Handle<mi::neuraylib::ICompiled_material> compiledMaterial;
std::string name;
};
struct MaterialManager::TargetCode
{
struct InternalMaterial
{
mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode;
std::string codePtx;
CompiledMaterial* compiledMaterial;
mi::base::Uuid hash;
uint32_t hash32;
uint32_t functionNum;
bool isUnique = false;
mi::base::Handle<mi::neuraylib::ITarget_argument_block> arg_block;
mi::Size argument_block_layout_index = -1;
uint32_t arg_block_offset = -1; // offset for arg block in argBlockData
uint32_t ro_offset = -1;
};
std::vector<InternalMaterial> internalMaterials;
std::unordered_map<uint32_t, uint32_t> uidToInternalIndex;
std::unordered_map<CompiledMaterial*, uint32_t> ptrToInternalIndex;
std::vector<Mdl_resource_info> resourceInfo;
std::vector<oka::MdlPtxCodeGen::InternalMaterialInfo> internalsInfo;
std::vector<const mi::neuraylib::ICompiled_material*> compiledMaterials;
bool isInitialized = false;
// MDL data for GPU buffers
std::vector<MdlMaterial> mdlMaterials;
std::vector<uint8_t> argBlockData;
std::vector<uint8_t> roData;
};
struct MaterialManager::TextureDescription
{
std::string dbName;
mi::base::Handle<const mi::neuraylib::IType_texture> textureType;
};
class Resource_callback : public mi::base::Interface_implement<mi::neuraylib::ITarget_resource_callback>
{
public:
/// Constructor.
Resource_callback(mi::base::Handle<mi::neuraylib::ITransaction>& transaction,
const mi::base::Handle<const mi::neuraylib::ITarget_code>& target_code)
: m_transaction(transaction), m_target_code(target_code)
{
}
/// Destructor.
virtual ~Resource_callback() = default;
/// Returns a resource index for the given resource value usable by the target code
/// resource handler for the corresponding resource type.
///
/// \param resource the resource value
///
/// \returns a resource index or 0 if no resource index can be returned
mi::Uint32 get_resource_index(mi::neuraylib::IValue_resource const* resource) override
{
// check whether we already know the resource index
auto it = m_resource_cache.find(resource);
if (it != m_resource_cache.end())
return it->second;
const char* filePath = resource->get_file_path();
// handle resources already known by the target code
mi::Uint32 res_idx = m_target_code->get_known_resource_index(m_transaction.get(), resource);
if (res_idx > 0)
{
// only accept body resources
switch (resource->get_kind())
{
case mi::neuraylib::IValue::VK_TEXTURE:
if (res_idx < m_target_code->get_texture_count())
return res_idx;
break;
case mi::neuraylib::IValue::VK_LIGHT_PROFILE:
if (res_idx < m_target_code->get_light_profile_count())
return res_idx;
break;
case mi::neuraylib::IValue::VK_BSDF_MEASUREMENT:
if (res_idx < m_target_code->get_bsdf_measurement_count())
return res_idx;
break;
default:
return 0u; // invalid kind
}
}
// invalid (or empty) resource
const char* name = resource->get_value();
if (!name)
{
return 0;
}
switch (resource->get_kind())
{
case mi::neuraylib::IValue::VK_TEXTURE: {
mi::base::Handle<mi::neuraylib::IValue_texture const> val_texture(
resource->get_interface<mi::neuraylib::IValue_texture const>());
if (!val_texture)
return 0u; // unknown resource
mi::base::Handle<const mi::neuraylib::IType_texture> texture_type(val_texture->get_type());
mi::neuraylib::ITarget_code::Texture_shape shape =
mi::neuraylib::ITarget_code::Texture_shape(texture_type->get_shape());
// m_compile_result.textures.emplace_back(resource->get_value(), shape);
// res_idx = m_compile_result.textures.size() - 1;
break;
}
case mi::neuraylib::IValue::VK_LIGHT_PROFILE:
// m_compile_result.light_profiles.emplace_back(resource->get_value());
// res_idx = m_compile_result.light_profiles.size() - 1;
break;
case mi::neuraylib::IValue::VK_BSDF_MEASUREMENT:
// m_compile_result.bsdf_measurements.emplace_back(resource->get_value());
// res_idx = m_compile_result.bsdf_measurements.size() - 1;
break;
default:
return 0u; // invalid kind
}
m_resource_cache[resource] = res_idx;
return res_idx;
}
/// Returns a string identifier for the given string value usable by the target code.
///
/// The value 0 is always the "not known string".
///
/// \param s the string value
mi::Uint32 get_string_index(mi::neuraylib::IValue_string const* s) override
{
char const* str_val = s->get_value();
if (str_val == nullptr)
return 0u;
for (mi::Size i = 0, n = m_target_code->get_string_constant_count(); i < n; ++i)
{
if (strcmp(m_target_code->get_string_constant(i), str_val) == 0)
return mi::Uint32(i);
}
// string not known by code
return 0u;
}
private:
mi::base::Handle<mi::neuraylib::ITransaction> m_transaction;
mi::base::Handle<const mi::neuraylib::ITarget_code> m_target_code;
std::unordered_map<mi::neuraylib::IValue_resource const*, mi::Uint32> m_resource_cache;
};
class MaterialManager::Context
{
public:
Context()
{
configurePaths();
};
~Context(){};
// paths is array of resource pathes + mdl path
bool addMdlSearchPath(const char* paths[], uint32_t numPaths)
{
mRuntime = std::make_unique<oka::MdlRuntime>();
if (!mRuntime->init(paths, numPaths, mPathso.c_str(), mImagePluginPath.c_str()))
{
return false;
}
mMtlxCodeGen = std::make_unique<oka::MtlxMdlCodeGen>(mtlxLibPath.generic_string().c_str(), mRuntime.get());
mMatCompiler = std::make_unique<oka::MdlMaterialCompiler>(*mRuntime);
mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(mRuntime->getTransaction());
mNeuray = mRuntime->getNeuray();
mCodeGen = std::make_unique<MdlPtxCodeGen>();
mCodeGen->init(*mRuntime);
std::vector<char> data;
{
const fs::path cwdPath = fs::current_path();
const fs::path precompiledPath = cwdPath / "optix/shaders/OptixRender_radiance_closest_hit.bc";
std::ifstream file(precompiledPath.c_str(), std::ios::in | std::ios::binary);
if (!file.is_open())
{
STRELKA_FATAL("Cannot open precompiled closest hit file.\n");
return false;
}
file.seekg(0, std::ios::end);
data.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(data.data(), data.size());
}
if (!mCodeGen->setOptionBinary("llvm_renderer_module", data.data(), data.size()))
{
STRELKA_ERROR("Unable to set binary options!");
return false;
}
return true;
}
Module* createMtlxModule(const char* mtlSrc)
{
assert(mMtlxCodeGen);
std::unique_ptr<Module> module = std::make_unique<Module>();
bool res = mMtlxCodeGen->translate(mtlSrc, mMdlSrc, module->identifier);
if (res)
{
std::string mtlxFile = "./data/materials/mtlx/" + module->identifier + ".mtlx";
std::string mdlFile = "./data/materials/mtlx/" + module->identifier + ".mdl";
auto dumpToFile = [](const std::string& fileName, const std::string& content) {
std::ofstream material(fileName.c_str());
if (!material.is_open())
{
STRELKA_ERROR("can not create file: {}", fileName.c_str());
return;
}
material << content;
material.close();
return;
};
dumpToFile(mtlxFile, mtlSrc);
dumpToFile(mdlFile, mMdlSrc);
if (!mMatCompiler->createModule(module->identifier, module->moduleName))
{
STRELKA_ERROR("failed to create MDL module: {} identifier: {}", module->moduleName.c_str(),
module->identifier.c_str());
return nullptr;
}
return module.release();
}
else
{
STRELKA_ERROR("failed to translate MaterialX -> MDL");
return nullptr;
}
};
Module* createModule(const char* file)
{
std::unique_ptr<Module> module = std::make_unique<Module>();
const fs::path materialFile = file;
module->identifier = materialFile.stem().string();
if (!mMatCompiler->createModule(module->identifier, module->moduleName))
{
return nullptr;
}
return module.release();
};
void destroyModule(Module* module)
{
assert(module);
delete module;
};
MaterialInstance* createMaterialInstance(MaterialManager::Module* module, const char* materialName)
{
assert(module);
assert(materialName);
std::unique_ptr<MaterialInstance> material = std::make_unique<MaterialInstance>();
if (strcmp(materialName, "") == 0) // mtlx
{
materialName = module->identifier.c_str();
}
if (!mMatCompiler->createMaterialInstace(module->moduleName.c_str(), materialName, material->instance))
{
return nullptr;
}
return material.release();
}
void destroyMaterialInstance(MaterialInstance* matInst)
{
assert(matInst);
delete matInst;
}
void dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material)
{
assert(targetCode);
assert(targetCode->isInitialized);
assert(material);
const uint32_t internalIndex = materialIdx;// targetCode->ptrToInternalIndex.at(material);
const mi::Size argLayoutIndex = targetCode->internalMaterials[internalIndex].argument_block_layout_index;
mi::base::Handle<const mi::neuraylib::ITarget_value_layout> arg_layout(
targetCode->internalMaterials[internalIndex].targetCode->get_argument_block_layout(argLayoutIndex));
if (targetCode->internalMaterials[internalIndex].arg_block == nullptr)
{
STRELKA_ERROR("Material : {} has no arg block!\n", material->name.c_str());
return;
}
char* baseArgBlockData = targetCode->internalMaterials[internalIndex].arg_block->get_data();
const mi::Size argBlockOffset = targetCode->internalMaterials[internalIndex].arg_block_offset;
const mi::Size paramCount = material->compiledMaterial->get_parameter_count();
STRELKA_DEBUG("Material name: {0}\t param count: {1}", material->name.c_str(), paramCount);
for (int pi = 0; pi < paramCount; ++pi)
{
const char* name = material->compiledMaterial->get_parameter_name(pi);
STRELKA_DEBUG("# {0}: Param name: {1}", pi, name);
mi::neuraylib::Target_value_layout_state valLayoutState = arg_layout->get_nested_state(pi);
mi::neuraylib::IValue::Kind kind;
mi::Size arg_size;
const mi::Size offsetInArgBlock = arg_layout->get_layout(kind, arg_size, valLayoutState);
STRELKA_DEBUG("\t offset = {0} \t size = {1}", offsetInArgBlock, arg_size);
// char* data = baseArgBlockData + offsetInArgBlock;
const uint8_t* data = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock;
switch (kind)
{
case mi::neuraylib::IValue::Kind::VK_FLOAT: {
float val = *((float*)data);
STRELKA_DEBUG("\t type float");
STRELKA_DEBUG("\t val = {}", val);
break;
}
case mi::neuraylib::IValue::Kind::VK_INT: {
int val = *((int*)data);
STRELKA_DEBUG("\t type int");
STRELKA_DEBUG("\t val = {}", val);
break;
}
case mi::neuraylib::IValue::Kind::VK_BOOL: {
bool val = *((bool*)data);
STRELKA_DEBUG("\t type bool");
STRELKA_DEBUG("\t val = {}", val);
break;
}
case mi::neuraylib::IValue::Kind::VK_COLOR: {
float* val = (float*)data;
STRELKA_DEBUG("\t type color");
STRELKA_DEBUG("\t val = ({}, {}, {})", val[0], val[1], val[2]);
break;
}
case mi::neuraylib::IValue::Kind::VK_TEXTURE: {
STRELKA_DEBUG("\t type texture");
int val = *((int*)data);
STRELKA_DEBUG("\t val = {}", val);
break;
}
default:
break;
}
// uint8_t* dst = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock;
// memcpy(dst, param.value.data(), param.value.size());
// isParamFound = true;
}
}
bool setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param)
{
assert(targetCode);
assert(targetCode->isInitialized);
assert(material);
bool isParamFound = false;
for (int pi = 0; pi < material->compiledMaterial->get_parameter_count(); ++pi)
{
if (!strcmp(material->compiledMaterial->get_parameter_name(pi), param.name.c_str()))
{
const uint32_t internalIndex = materialIdx; //targetCode->ptrToInternalIndex[material];
const mi::Size argLayoutIndex = targetCode->internalMaterials[internalIndex].argument_block_layout_index;
mi::base::Handle<const mi::neuraylib::ITarget_value_layout> arg_layout(
targetCode->internalMaterials[internalIndex].targetCode->get_argument_block_layout(argLayoutIndex));
mi::neuraylib::Target_value_layout_state valLayoutState = arg_layout->get_nested_state(pi);
mi::neuraylib::IValue::Kind kind;
mi::Size arg_size;
const mi::Size offsetInArgBlock = arg_layout->get_layout(kind, arg_size, valLayoutState);
assert(arg_size == param.value.size()); // TODO: should match, otherwise error
const mi::Size argBlockOffset = targetCode->internalMaterials[internalIndex].arg_block_offset;
uint8_t* dst = targetCode->argBlockData.data() + argBlockOffset + offsetInArgBlock;
memcpy(dst, param.value.data(), param.value.size());
isParamFound = true;
break;
}
}
return isParamFound;
}
TextureDescription* createTextureDescription(const char* name, const char* gammaMode)
{
assert(name);
float gamma = 1.0;
const char* texGamma = "";
if (strcmp(gammaMode, "srgb") == 0)
{
gamma = 2.2f;
texGamma = "_srgb";
}
else if (strcmp(gammaMode, "linear") == 0)
{
gamma = 1.0f;
texGamma = "_linear";
}
std::string textureDbName = std::string(name) + std::string(texGamma);
mi::base::Handle<const mi::neuraylib::ITexture> texAccess = mi::base::Handle<const mi::neuraylib::ITexture>(
mMatCompiler->getTransaction()->access<mi::neuraylib::ITexture>(textureDbName.c_str()));
// check if it is in DB
if (!texAccess.is_valid_interface())
{
// Load it
mi::base::Handle<mi::neuraylib::ITexture> tex(
mMatCompiler->getTransaction()->create<mi::neuraylib::ITexture>("Texture"));
mi::base::Handle<mi::neuraylib::IImage> image(
mMatCompiler->getTransaction()->create<mi::neuraylib::IImage>("Image"));
if (image->reset_file(name) != 0)
{
// TODO: report error could not find texture!
return nullptr;
}
std::string imageName = textureDbName + std::string("_image");
mMatCompiler->getTransaction()->store(image.get(), imageName.c_str());
tex->set_image(imageName.c_str());
tex->set_gamma(gamma);
mMatCompiler->getTransaction()->store(tex.get(), textureDbName.c_str());
}
mi::base::Handle<mi::neuraylib::IType_factory> typeFactory(
mMatCompiler->getFactory()->create_type_factory(mMatCompiler->getTransaction().get()));
// TODO: texture could be 1D, 3D
mi::base::Handle<const mi::neuraylib::IType_texture> textureType(
typeFactory->create_texture(mi::neuraylib::IType_texture::TS_2D));
TextureDescription* texDesc = new TextureDescription;
texDesc->dbName = textureDbName;
texDesc->textureType = textureType;
return texDesc;
}
const char* getTextureDbName(TextureDescription* texDesc)
{
return texDesc->dbName.c_str();
}
CompiledMaterial* compileMaterial(MaterialInstance* matInstance)
{
assert(matInstance);
std::unique_ptr<CompiledMaterial> material = std::make_unique<CompiledMaterial>();
if (!mMatCompiler->compileMaterial(matInstance->instance, material->compiledMaterial))
{
return nullptr;
}
material->name = matInstance->instance->get_function_definition();
return material.release();
};
void destroyCompiledMaterial(CompiledMaterial* materials)
{
assert(materials);
delete materials;
}
const char* getName(CompiledMaterial* compMaterial)
{
return compMaterial->name.c_str();
}
TargetCode* generateTargetCode(CompiledMaterial** materials, const uint32_t numMaterials)
{
TargetCode* targetCode = new TargetCode;
std::unordered_map<uint32_t, uint32_t> uidToFunctionNum;
std::vector<TargetCode::InternalMaterial>& internalMaterials = targetCode->internalMaterials;
internalMaterials.resize(numMaterials);
std::vector<const mi::neuraylib::ICompiled_material*> materialsToCompile;
for (int i = 0; i < numMaterials; ++i)
{
internalMaterials[i].compiledMaterial = materials[i];
internalMaterials[i].hash = materials[i]->compiledMaterial->get_hash();
internalMaterials[i].hash32 = uuid_hash32(internalMaterials[i].hash);
uint32_t functionNum = -1;
bool isUnique = false;
if (uidToFunctionNum.find(internalMaterials[i].hash32) != uidToFunctionNum.end())
{
functionNum = uidToFunctionNum[internalMaterials[i].hash32];
}
else
{
functionNum = uidToFunctionNum.size();
uidToFunctionNum[internalMaterials[i].hash32] = functionNum;
isUnique = true;
materialsToCompile.push_back(internalMaterials[i].compiledMaterial->compiledMaterial.get());
// log output
STRELKA_DEBUG("Material to compile: {}", getName(internalMaterials[i].compiledMaterial));
}
internalMaterials[i].isUnique = isUnique;
internalMaterials[i].functionNum = functionNum;
targetCode->uidToInternalIndex[internalMaterials[i].hash32] = i;
targetCode->ptrToInternalIndex[materials[i]] = i;
}
const uint32_t numMaterialsToCompile = materialsToCompile.size();
STRELKA_INFO("Num Materials to compile: {}", numMaterialsToCompile);
std::vector<oka::MaterialManager::TargetCode::InternalMaterial> compiledInternalMaterials(numMaterialsToCompile);
for (int i = 0; i < numMaterialsToCompile; ++i)
{
oka::MdlPtxCodeGen::InternalMaterialInfo internalsInfo;
compiledInternalMaterials[i].targetCode =
mCodeGen->translate(materialsToCompile[i], compiledInternalMaterials[i].codePtx, internalsInfo);
compiledInternalMaterials[i].argument_block_layout_index = internalsInfo.argument_block_index;
}
targetCode->mdlMaterials.resize(numMaterials);
for (uint32_t i = 0; i < numMaterials; ++i)
{
const uint32_t compiledOrder = internalMaterials[i].functionNum;
assert(compiledOrder < numMaterialsToCompile);
internalMaterials[i].argument_block_layout_index = compiledInternalMaterials[compiledOrder].argument_block_layout_index;
internalMaterials[i].targetCode = compiledInternalMaterials[compiledOrder].targetCode;
internalMaterials[i].codePtx = compiledInternalMaterials[compiledOrder].codePtx;
targetCode->mdlMaterials[i].functionId = compiledOrder;
}
targetCode->argBlockData = loadArgBlocks(targetCode);
targetCode->roData = loadROData(targetCode);
// uint32_t texCount = targetCode->targetCode->get_texture_count();
// if (texCount > 0)
// {
// targetCode->resourceInfo.resize(texCount);
// for (uint32_t i = 0; i < texCount; ++i)
// {
// targetCode->resourceInfo[i].gpu_resource_array_start = i;
// const char* texUrl = targetCode->targetCode->get_texture_url(i);
// const int texBody = targetCode->targetCode->get_body_texture_count();
// const char* texName = getTextureName(targetCode, i);
// // const float* data = getTextureData(targetCode, i);
// // uint32_t width = getTextureWidth(targetCode, i);
// // uint32_t height = getTextureHeight(targetCode, i);
// // const char* type = getTextureType(targetCode, i);
// printf("Material texture name: %s\n", texName);
// }
// }
// else
//{
// targetCode->resourceInfo.resize(1);
// }
targetCode->isInitialized = true;
return targetCode;
};
int registerResource(TargetCode* targetCode, int index)
{
Mdl_resource_info ri{ 0 };
ri.gpu_resource_array_start = index;
targetCode->resourceInfo.push_back(ri);
return (int)targetCode->resourceInfo.size(); // resource id 0 is reserved for invalid, but we store resources
// from 0 internally
}
const char* getShaderCode(const TargetCode* targetCode, uint32_t materialIdx)
{
const uint32_t compiledOrder = targetCode->internalMaterials[materialIdx].functionNum;
return targetCode->internalMaterials[compiledOrder].codePtx.c_str();
}
uint32_t getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId)
{
return targetCode->internalMaterials[materialId].arg_block_offset;
}
uint32_t getReadOnlyBlockOffset(const TargetCode* targetCode, uint32_t materialId)
{
return targetCode->internalMaterials[materialId].ro_offset;
}
uint32_t getReadOnlyBlockSize(const TargetCode* shaderCode)
{
return shaderCode->roData.size();
}
const uint8_t* getReadOnlyBlockData(const TargetCode* targetCode)
{
return targetCode->roData.data();
}
uint32_t getArgBufferSize(const TargetCode* shaderCode)
{
return shaderCode->argBlockData.size();
}
const uint8_t* getArgBufferData(const TargetCode* targetCode)
{
return targetCode->argBlockData.data();
}
uint32_t getResourceInfoSize(const TargetCode* targetCode)
{
return targetCode->resourceInfo.size() * sizeof(Mdl_resource_info);
}
const uint8_t* getResourceInfoData(const TargetCode* targetCode)
{
return reinterpret_cast<const uint8_t*>(targetCode->resourceInfo.data());
}
uint32_t getMdlMaterialSize(const TargetCode* targetCode)
{
return targetCode->mdlMaterials.size() * sizeof(MdlMaterial);
}
const uint8_t* getMdlMaterialData(const TargetCode* targetCode)
{
return reinterpret_cast<const uint8_t*>(targetCode->mdlMaterials.data());
}
uint32_t getTextureCount(const TargetCode* targetCode, uint32_t materialId)
{
return targetCode->internalMaterials[materialId].targetCode->get_texture_count();
}
const char* getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
assert(index); // index == 0 is invalid
return targetCode->internalMaterials[materialId].targetCode->get_texture(index);
}
const float* getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
// assert(index); // index == 0 is invalid
assert(mTransaction);
auto cachedCanvas = m_indexToCanvas.find(index);
if (cachedCanvas == m_indexToCanvas.end())
{
mi::base::Handle<mi::neuraylib::IImage_api> image_api(mNeuray->get_api_component<mi::neuraylib::IImage_api>());
mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>(
targetCode->internalMaterials[materialId].targetCode->get_texture(index)));
mi::base::Handle<const mi::neuraylib::IImage> image(
mTransaction->access<mi::neuraylib::IImage>(texture->get_image()));
mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0));
char const* image_type = image->get_type(0, 0);
// if (canvas->get_tiles_size_x() != 1 || canvas->get_tiles_size_y() != 1)
// {
// mLogger->message(mi::base::MESSAGE_SEVERITY_ERROR, "The example does not support tiled images!");
// return nullptr;
// }
if (texture->get_effective_gamma(0, 0) != 1.0f)
{
// Copy/convert to float4 canvas and adjust gamma from "effective gamma" to 1.
mi::base::Handle<mi::neuraylib::ICanvas> gamma_canvas(image_api->convert(canvas.get(), "Color"));
gamma_canvas->set_gamma(texture->get_effective_gamma(0, 0));
image_api->adjust_gamma(gamma_canvas.get(), 1.0f);
canvas = gamma_canvas;
}
else if (strcmp(image_type, "Color") != 0 && strcmp(image_type, "Float32<4>") != 0)
{
// Convert to expected format
canvas = image_api->convert(canvas.get(), "Color");
}
m_indexToCanvas[index] = canvas;
cachedCanvas = m_indexToCanvas.find(index);
}
mi::Float32 const* data = nullptr;
mi::neuraylib::ITarget_code::Texture_shape texture_shape =
targetCode->internalMaterials[materialId].targetCode->get_texture_shape(index);
if (texture_shape == mi::neuraylib::ITarget_code::Texture_shape_2d)
{
mi::base::Handle<const mi::neuraylib::ITile> tile(cachedCanvas->second->get_tile());
data = static_cast<mi::Float32 const*>(tile->get_data());
}
return data;
}
const char* getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
// assert(index); // index == 0 is invalid
mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>(
targetCode->internalMaterials[materialId].targetCode->get_texture(index)));
mi::base::Handle<const mi::neuraylib::IImage> image(
mTransaction->access<mi::neuraylib::IImage>(texture->get_image()));
char const* imageType = image->get_type(0, 0);
return imageType;
}
uint32_t getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
// assert(index); // index == 0 is invalid
mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>(
targetCode->internalMaterials[materialId].targetCode->get_texture(index)));
mi::base::Handle<const mi::neuraylib::IImage> image(
mTransaction->access<mi::neuraylib::IImage>(texture->get_image()));
mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0));
mi::Uint32 texWidth = canvas->get_resolution_x();
return texWidth;
}
uint32_t getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
// assert(index); // index == 0 is invalid
mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>(
targetCode->internalMaterials[materialId].targetCode->get_texture(index)));
mi::base::Handle<const mi::neuraylib::IImage> image(
mTransaction->access<mi::neuraylib::IImage>(texture->get_image()));
mi::base::Handle<const mi::neuraylib::ICanvas> canvas(image->get_canvas(0, 0, 0));
mi::Uint32 texHeight = canvas->get_resolution_y();
return texHeight;
}
uint32_t getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
// assert(index); // index == 0 is invalid
mi::base::Handle<mi::neuraylib::IImage_api> image_api(mNeuray->get_api_component<mi::neuraylib::IImage_api>());
mi::base::Handle<const mi::neuraylib::ITexture> texture(mTransaction->access<mi::neuraylib::ITexture>(
targetCode->internalMaterials[materialId].targetCode->get_texture(index)));
mi::base::Handle<const mi::neuraylib::IImage> image(
mTransaction->access<mi::neuraylib::IImage>(texture->get_image()));
char const* imageType = image->get_type(0, 0);
int cpp = image_api->get_components_per_pixel(imageType);
int bpc = image_api->get_bytes_per_component(imageType);
int bpp = cpp * bpc;
return bpp;
}
private:
std::string mImagePluginPath;
std::string mPathso;
std::string mMdlSrc;
fs::path mtlxLibPath;
std::unordered_map<uint32_t, mi::base::Handle<const mi::neuraylib::ICanvas>> m_indexToCanvas;
void configurePaths()
{
using namespace std;
const fs::path cwd = fs::current_path();
#ifdef MI_PLATFORM_WINDOWS
mPathso = cwd.string();
mImagePluginPath = cwd.string() + "/nv_openimageio.dll";
#else
mPathso = cwd.string();
mImagePluginPath = cwd.string() + "/nv_openimageio.so";
#endif
}
std::unique_ptr<oka::MdlPtxCodeGen> mCodeGen = nullptr;
std::unique_ptr<oka::MdlMaterialCompiler> mMatCompiler = nullptr;
std::unique_ptr<oka::MdlRuntime> mRuntime = nullptr;
std::unique_ptr<oka::MtlxMdlCodeGen> mMtlxCodeGen = nullptr;
mi::base::Handle<mi::neuraylib::ITransaction> mTransaction;
mi::base::Handle<oka::MdlLogger> mLogger;
mi::base::Handle<mi::neuraylib::INeuray> mNeuray;
std::vector<uint8_t> loadArgBlocks(TargetCode* targetCode);
std::vector<uint8_t> loadROData(TargetCode* targetCode);
};
MaterialManager::MaterialManager()
{
mContext = std::make_unique<Context>();
}
MaterialManager::~MaterialManager()
{
mContext.reset(nullptr);
};
bool MaterialManager::addMdlSearchPath(const char* paths[], uint32_t numPaths)
{
return mContext->addMdlSearchPath(paths, numPaths);
}
MaterialManager::Module* MaterialManager::createModule(const char* file)
{
return mContext->createModule(file);
}
MaterialManager::Module* MaterialManager::createMtlxModule(const char* file)
{
return mContext->createMtlxModule(file);
}
void MaterialManager::destroyModule(MaterialManager::Module* module)
{
return mContext->destroyModule(module);
}
MaterialManager::MaterialInstance* MaterialManager::createMaterialInstance(MaterialManager::Module* module,
const char* materialName)
{
return mContext->createMaterialInstance(module, materialName);
}
void MaterialManager::destroyMaterialInstance(MaterialManager::MaterialInstance* matInst)
{
return mContext->destroyMaterialInstance(matInst);
}
MaterialManager::TextureDescription* MaterialManager::createTextureDescription(const char* name, const char* gamma)
{
return mContext->createTextureDescription(name, gamma);
}
const char* MaterialManager::getTextureDbName(TextureDescription* texDesc)
{
return mContext->getTextureDbName(texDesc);
}
void MaterialManager::dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material)
{
return mContext->dumpParams(targetCode, materialIdx, material);
}
bool MaterialManager::setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param)
{
return mContext->setParam(targetCode, materialIdx, material, param);
}
MaterialManager::CompiledMaterial* MaterialManager::compileMaterial(MaterialManager::MaterialInstance* matInstance)
{
return mContext->compileMaterial(matInstance);
}
void MaterialManager::destroyCompiledMaterial(MaterialManager::CompiledMaterial* material)
{
return mContext->destroyCompiledMaterial(material);
}
const char* MaterialManager::getName(CompiledMaterial* compMaterial)
{
return mContext->getName(compMaterial);
}
MaterialManager::TargetCode* MaterialManager::generateTargetCode(CompiledMaterial** materials, uint32_t numMaterials)
{
return mContext->generateTargetCode(materials, numMaterials);
}
const char* MaterialManager::getShaderCode(const TargetCode* targetCode, uint32_t materialId) // get shader code
{
return mContext->getShaderCode(targetCode, materialId);
}
uint32_t MaterialManager::getReadOnlyBlockSize(const TargetCode* targetCode)
{
return mContext->getReadOnlyBlockSize(targetCode);
}
const uint8_t* MaterialManager::getReadOnlyBlockData(const TargetCode* targetCode)
{
return mContext->getReadOnlyBlockData(targetCode);
}
uint32_t MaterialManager::getArgBufferSize(const TargetCode* targetCode)
{
return mContext->getArgBufferSize(targetCode);
}
const uint8_t* MaterialManager::getArgBufferData(const TargetCode* targetCode)
{
return mContext->getArgBufferData(targetCode);
}
uint32_t MaterialManager::getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId)
{
return mContext->getArgBlockOffset(targetCode, materialId);
}
uint32_t MaterialManager::getReadOnlyOffset(const TargetCode* targetCode, uint32_t materialId)
{
return mContext->getArgBlockOffset(targetCode, materialId);
}
uint32_t MaterialManager::getResourceInfoSize(const TargetCode* targetCode)
{
return mContext->getResourceInfoSize(targetCode);
}
const uint8_t* MaterialManager::getResourceInfoData(const TargetCode* targetCode)
{
return mContext->getResourceInfoData(targetCode);
}
int MaterialManager::registerResource(TargetCode* targetCode, int index)
{
return mContext->registerResource(targetCode, index);
}
uint32_t MaterialManager::getMdlMaterialSize(const TargetCode* targetCode)
{
return mContext->getMdlMaterialSize(targetCode);
}
const uint8_t* MaterialManager::getMdlMaterialData(const TargetCode* targetCode)
{
return mContext->getMdlMaterialData(targetCode);
}
uint32_t MaterialManager::getTextureCount(const TargetCode* targetCode, uint32_t materialId)
{
return mContext->getTextureCount(targetCode, materialId);
}
const char* MaterialManager::getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureName(targetCode, materialId, index);
}
const float* MaterialManager::getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureData(targetCode, materialId, index);
}
const char* MaterialManager::getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureType(targetCode, materialId, index);
}
uint32_t MaterialManager::getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureWidth(targetCode, materialId, index);
}
uint32_t MaterialManager::getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureHeight(targetCode, materialId, index);
}
uint32_t MaterialManager::getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index)
{
return mContext->getTextureBytesPerTexel(targetCode, materialId, index);
}
inline size_t round_to_power_of_two(size_t value, size_t power_of_two_factor)
{
return (value + (power_of_two_factor - 1)) & ~(power_of_two_factor - 1);
}
std::vector<uint8_t> MaterialManager::Context::loadArgBlocks(TargetCode* targetCode)
{
std::vector<uint8_t> res;
for (int i = 0; i < targetCode->internalMaterials.size(); ++i)
{
mi::base::Handle<const mi::neuraylib::ITarget_code>& mdlTargetCode = targetCode->internalMaterials[i].targetCode;
mi::base::Handle<Resource_callback> callback(new Resource_callback(mTransaction, mdlTargetCode));
// const uint32_t compiledIndex = targetCode->internalMaterials[i].functionNum;
const mi::Size argLayoutIndex = targetCode->internalMaterials[i].argument_block_layout_index;
const mi::Size layoutCount = mdlTargetCode->get_argument_layout_count();
if (argLayoutIndex != static_cast<mi::Size>(-1) && argLayoutIndex < layoutCount)
{
mi::neuraylib::ICompiled_material* compiledMaterial =
targetCode->internalMaterials[i].compiledMaterial->compiledMaterial.get();
targetCode->internalMaterials[i].arg_block =
mdlTargetCode->create_argument_block(argLayoutIndex, compiledMaterial, callback.get());
if (!targetCode->internalMaterials[i].arg_block)
{
std::cerr << ("Failed to create material argument block: ") << std::endl;
res.resize(4);
return res;
}
// create a buffer to provide those parameters to the shader
// align to 4 bytes and pow of two
const size_t buffer_size = round_to_power_of_two(targetCode->internalMaterials[i].arg_block->get_size(), 4);
std::vector<uint8_t> argBlockData = std::vector<uint8_t>(buffer_size, 0);
memcpy(argBlockData.data(), targetCode->internalMaterials[i].arg_block->get_data(),
targetCode->internalMaterials[i].arg_block->get_size());
// set offset in common arg block buffer
targetCode->internalMaterials[i].arg_block_offset = (uint32_t)res.size();
targetCode->mdlMaterials[i].arg_block_offset = (int)res.size();
res.insert(res.end(), argBlockData.begin(), argBlockData.end());
}
}
if (res.empty())
{
res.resize(4);
}
return res;
}
std::vector<uint8_t> MaterialManager::Context::loadROData(TargetCode* targetCode)
{
std::vector<uint8_t> roData;
for (int i = 0; i < targetCode->internalMaterials.size(); ++i)
{
const size_t segCount = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_count();
targetCode->internalMaterials[i].ro_offset = roData.size();
for (size_t s = 0; s < segCount; ++s)
{
const char* data = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_data(s);
size_t dataSize = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_size(s);
const char* name = targetCode->internalMaterials[i].targetCode->get_ro_data_segment_name(s);
std::cerr << "MDL segment [" << s << "] name : " << name << std::endl;
if (dataSize != 0)
{
roData.insert(roData.end(), data, data + dataSize);
}
}
}
if (roData.empty())
{
roData.resize(4);
}
return roData;
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/mdlPtxCodeGen.cpp | #include "mdlPtxCodeGen.h"
#include "materials.h"
#include <mi/mdl_sdk.h>
#include <cassert>
#include <sstream>
#include <log.h>
namespace oka
{
const char* SCATTERING_FUNC_NAME = "mdl_bsdf_scattering";
const char* EMISSION_FUNC_NAME = "mdl_edf_emission";
const char* EMISSION_INTENSITY_FUNC_NAME = "mdl_edf_emission_intensity";
const char* MATERIAL_STATE_NAME = "Shading_state_material";
bool MdlPtxCodeGen::init(MdlRuntime& runtime)
{
mi::base::Handle<mi::neuraylib::IMdl_backend_api> backendApi(runtime.getBackendApi());
mBackend = mi::base::Handle<mi::neuraylib::IMdl_backend>(
backendApi->get_backend(mi::neuraylib::IMdl_backend_api::MB_CUDA_PTX));
if (!mBackend.is_valid_interface())
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "CUDA backend not supported by MDL runtime");
return false;
}
// 75 - Turing
// 86 - Ampere
// 89 - Ada
if (mBackend->set_option("sm_version", "75") != 0)
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option sm_version failed");
return false;
}
if (mBackend->set_option("num_texture_spaces", "2") != 0)
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option num_texture_spaces failed");
return false;
}
if (mBackend->set_option("num_texture_results", "16") != 0)
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option num_texture_results failed");
return false;
}
if (mBackend->set_option("tex_lookup_call_mode", "direct_call") != 0)
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "ERROR: Setting PTX option tex_lookup_call_mode failed");
return false;
}
mLogger = mi::base::Handle<MdlLogger>(runtime.getLogger());
mLoader = std::move(runtime.mLoader);
mi::base::Handle<mi::neuraylib::IMdl_factory> factory(runtime.getFactory());
mContext = mi::base::Handle<mi::neuraylib::IMdl_execution_context>(factory->create_execution_context());
mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(runtime.getDatabase());
mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(runtime.getTransaction());
return true;
}
mi::base::Handle<const mi::neuraylib::ITarget_code> MdlPtxCodeGen::translate(
const mi::neuraylib::ICompiled_material* material, std::string& ptxSrc, InternalMaterialInfo& internalsInfo)
{
assert(material);
mi::base::Handle<mi::neuraylib::ILink_unit> linkUnit(mBackend->create_link_unit(mTransaction.get(), mContext.get()));
mLogger->flushContextMessages(mContext.get());
if (!linkUnit)
{
throw "Failed to create link unit";
}
mi::Size argBlockIndex;
if (!appendMaterialToLinkUnit(0, material, linkUnit.get(), argBlockIndex))
{
throw "Failed to append material to the link unit";
}
internalsInfo.argument_block_index = argBlockIndex;
mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode(
mBackend->translate_link_unit(linkUnit.get(), mContext.get()));
mLogger->flushContextMessages(mContext.get());
if (!targetCode)
{
throw "No target code";
}
ptxSrc = targetCode->get_code();
return targetCode;
}
mi::base::Handle<const mi::neuraylib::ITarget_code> MdlPtxCodeGen::translate(
const std::vector<const mi::neuraylib::ICompiled_material*>& materials,
std::string& ptxSrc,
std::vector<InternalMaterialInfo>& internalsInfo)
{
mi::base::Handle<mi::neuraylib::ILink_unit> linkUnit(mBackend->create_link_unit(mTransaction.get(), mContext.get()));
mLogger->flushContextMessages(mContext.get());
if (!linkUnit)
{
throw "Failed to create link unit";
}
uint32_t materialCount = materials.size();
internalsInfo.resize(materialCount);
mi::Size argBlockIndex;
for (uint32_t i = 0; i < materialCount; i++)
{
const mi::neuraylib::ICompiled_material* material = materials.at(i);
assert(material);
if (!appendMaterialToLinkUnit(i, material, linkUnit.get(), argBlockIndex))
{
throw "Failed to append material to the link unit";
}
internalsInfo[i].argument_block_index = argBlockIndex;
}
mi::base::Handle<const mi::neuraylib::ITarget_code> targetCode(
mBackend->translate_link_unit(linkUnit.get(), mContext.get()));
mLogger->flushContextMessages(mContext.get());
if (!targetCode)
{
throw "No target code";
}
ptxSrc = targetCode->get_code();
return targetCode;
}
bool MdlPtxCodeGen::appendMaterialToLinkUnit(uint32_t idx,
const mi::neuraylib::ICompiled_material* compiledMaterial,
mi::neuraylib::ILink_unit* linkUnit,
mi::Size& argBlockIndex)
{
std::string idxStr = std::to_string(idx);
auto scatteringFuncName = std::string("mdlcode");
auto emissionFuncName = std::string(EMISSION_FUNC_NAME) + "_" + idxStr;
auto emissionIntensityFuncName = std::string(EMISSION_INTENSITY_FUNC_NAME) + "_" + idxStr;
// Here we need to detect if current material for hair, if so, replace name in function description
mi::base::Handle<mi::neuraylib::IExpression const> hairExpr(compiledMaterial->lookup_sub_expression("hair"));
bool isHair = false;
if (hairExpr != nullptr)
{
if (hairExpr->get_kind() != mi::neuraylib::IExpression::EK_CONSTANT)
{
isHair = true;
}
}
std::vector<mi::neuraylib::Target_function_description> genFunctions;
genFunctions.push_back(mi::neuraylib::Target_function_description( isHair ? "hair" : "surface.scattering", scatteringFuncName.c_str()));
genFunctions.push_back(
mi::neuraylib::Target_function_description("surface.emission.emission", emissionFuncName.c_str()));
genFunctions.push_back(
mi::neuraylib::Target_function_description("surface.emission.intensity", emissionIntensityFuncName.c_str()));
mi::Sint32 result =
linkUnit->add_material(compiledMaterial, genFunctions.data(), genFunctions.size(), mContext.get());
mLogger->flushContextMessages(mContext.get());
if (result == 0)
{
argBlockIndex = genFunctions[0].argument_block_index;
}
return result == 0;
}
bool MdlPtxCodeGen::setOptionBinary(const char* name, const char* data, size_t size)
{
if (mBackend->set_option_binary(name, data, size) != 0)
{
return false;
}
// limit functions for which PTX code is generated to the entry functions
if (mBackend->set_option("visible_functions", "__closesthit__radiance") != 0)
{
STRELKA_ERROR("Setting PTX option visible_functions failed");
return false;
}
return true;
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/mtlxMdlCodeGen.cpp | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "mtlxMdlCodeGen.h"
#include <MaterialXCore/Definition.h>
#include <MaterialXCore/Document.h>
#include <MaterialXCore/Library.h>
#include <MaterialXCore/Material.h>
#include <MaterialXFormat/File.h>
#include <MaterialXFormat/Util.h>
#include <MaterialXGenMdl/MdlShaderGenerator.h>
#include <MaterialXGenShader/DefaultColorManagementSystem.h>
#include <MaterialXGenShader/GenContext.h>
#include <MaterialXGenShader/GenOptions.h>
#include <MaterialXGenShader/Library.h>
#include <MaterialXGenShader/Shader.h>
#include <MaterialXGenShader/Util.h>
#include <unordered_set>
#include <log.h>
namespace mx = MaterialX;
namespace oka
{
class MdlStringResolver;
using MdlStringResolverPtr = std::shared_ptr<MdlStringResolver>;
// Original source from https://github.com/NVIDIA/MDL-SDK/blob/190249748ddfe75b133b9da9028cc6272928c1b5/examples/mdl_sdk/dxr/mdl_d3d12/materialx/mdl_generator.cpp#L53
class MdlStringResolver : public mx::StringResolver
{
public:
/// Create a new string resolver.
static MdlStringResolverPtr create()
{
return MdlStringResolverPtr(new MdlStringResolver());
}
~MdlStringResolver() = default;
void initialize(mx::DocumentPtr document, mi::neuraylib::IMdl_configuration* config)
{
// remove duplicates and keep order by using a set
auto less = [](const mx::FilePath& lhs, const mx::FilePath& rhs) { return lhs.asString() < rhs.asString(); };
std::set<mx::FilePath, decltype(less)> mtlx_paths(less);
m_mtlx_document_paths.clear();
m_mdl_search_paths.clear();
// use the source search paths as base
mx::FilePath p = mx::FilePath(document->getSourceUri()).getParentPath().getNormalized();
mtlx_paths.insert(p);
m_mtlx_document_paths.append(p);
for (auto sp : mx::getSourceSearchPath(document))
{
sp = sp.getNormalized();
if(sp.exists() && mtlx_paths.insert(sp).second)
m_mtlx_document_paths.append(sp);
}
// add all search paths known to MDL
for (size_t i = 0, n = config->get_mdl_paths_length(); i < n; i++)
{
mi::base::Handle<const mi::IString> sp_istring(config->get_mdl_path(i));
p = mx::FilePath(sp_istring->get_c_str()).getNormalized();
if (p.exists() && mtlx_paths.insert(p).second)
m_mtlx_document_paths.append(p);
// keep a list of MDL search paths for resource resolution
m_mdl_search_paths.append(p);
}
}
std::string resolve(const std::string& str, const std::string& type) const override
{
mx::FilePath normalizedPath = mx::FilePath(str).getNormalized();
// in case the path is absolute we need to find a proper search path to put the file in
if (normalizedPath.isAbsolute())
{
// find the highest priority search path that is a prefix of the resource path
for (const auto& sp : m_mdl_search_paths)
{
if (sp.size() > normalizedPath.size())
continue;
bool isParent = true;
for (size_t i = 0; i < sp.size(); ++i)
{
if (sp[i] != normalizedPath[i])
{
isParent = false;
break;
}
}
if (!isParent)
continue;
// found a search path that is a prefix of the resource
std::string resource_path =
normalizedPath.asString(mx::FilePath::FormatPosix).substr(
sp.asString(mx::FilePath::FormatPosix).size());
if (resource_path[0] != '/')
resource_path = "/" + resource_path;
return resource_path;
}
}
STRELKA_ERROR("MaterialX resource can not be accessed through an MDL search path. \n Dropping the resource from the Material. Resource Path: {} ", normalizedPath.asString());
// drop the resource by returning the empty string.
// alternatively, the resource could be copied into an MDL search path,
// maybe even only temporary.
return "";
}
// Get the MaterialX paths used to load the current document as well the current MDL search
// paths in order to resolve resources by the MaterialX SDK.
const mx::FileSearchPath& get_search_paths() const { return m_mtlx_document_paths; }
private:
// List of paths from which MaterialX can locate resources.
// This includes the document folder and the search paths used to load the document.
mx::FileSearchPath m_mtlx_document_paths;
// List of MDL search paths from which we can locate resources.
// This is only a subset of the MaterialX document paths and needs to be extended by using the
// `--mdl_path` option when starting the application if needed.
mx::FileSearchPath m_mdl_search_paths;
};
MtlxMdlCodeGen::MtlxMdlCodeGen(const char* mtlxlibPath, MdlRuntime* mdlRuntime)
: mMtlxlibPath(mtlxlibPath),
mMdlRuntime(mdlRuntime)
{
// Init shadergen.
mShaderGen = mx::MdlShaderGenerator::create();
std::string target = mShaderGen->getTarget();
// MaterialX libs.
mStdLib = mx::createDocument();
mx::FilePathVec libFolders;
mx::loadLibraries(libFolders, mMtlxlibPath, mStdLib);
// Color management.
mx::DefaultColorManagementSystemPtr colorSystem = mx::DefaultColorManagementSystem::create(target);
colorSystem->loadLibrary(mStdLib);
mShaderGen->setColorManagementSystem(colorSystem);
// Unit management.
mx::UnitSystemPtr unitSystem = mx::UnitSystem::create(target);
unitSystem->loadLibrary(mStdLib);
mx::UnitConverterRegistryPtr unitRegistry = mx::UnitConverterRegistry::create();
mx::UnitTypeDefPtr distanceTypeDef = mStdLib->getUnitTypeDef("distance");
unitRegistry->addUnitConverter(distanceTypeDef, mx::LinearUnitConverter::create(distanceTypeDef));
mx::UnitTypeDefPtr angleTypeDef = mStdLib->getUnitTypeDef("angle");
unitRegistry->addUnitConverter(angleTypeDef, mx::LinearUnitConverter::create(angleTypeDef));
unitSystem->setUnitConverterRegistry(unitRegistry);
mShaderGen->setUnitSystem(unitSystem);
}
mx::TypedElementPtr _FindSurfaceShaderElement(mx::DocumentPtr doc)
{
// Find renderable element.
std::vector<mx::TypedElementPtr> renderableElements;
mx::findRenderableElements(doc, renderableElements);
if (renderableElements.size() != 1)
{
return nullptr;
}
// Extract surface shader node.
mx::TypedElementPtr renderableElement = renderableElements.at(0);
mx::NodePtr node = renderableElement->asA<mx::Node>();
if (node && node->getType() == mx::MATERIAL_TYPE_STRING)
{
auto shaderNodes = mx::getShaderNodes(node, mx::SURFACE_SHADER_TYPE_STRING);
if (!shaderNodes.empty())
{
renderableElement = *shaderNodes.begin();
}
}
mx::ElementPtr surfaceElement = doc->getDescendant(renderableElement->getNamePath());
if (!surfaceElement)
{
return nullptr;
}
return surfaceElement->asA<mx::TypedElement>();
}
bool MtlxMdlCodeGen::translate(const char* mtlxSrc, std::string& mdlSrc, std::string& subIdentifier)
{
// Don't cache the context because it is thread-local.
mx::GenContext context(mShaderGen);
context.registerSourceCodeSearchPath(mMtlxlibPath);
mx::GenOptions& contextOptions = context.getOptions();
contextOptions.targetDistanceUnit = "meter";
mx::ShaderPtr shader = nullptr;
try
{
mx::DocumentPtr doc = mx::createDocument();
doc->importLibrary(mStdLib);
mx::readFromXmlString(doc, mtlxSrc); // originally from string
auto custom_resolver = MdlStringResolver::create();
custom_resolver->initialize(doc, mMdlRuntime->getConfig().get());
mx::flattenFilenames(doc, custom_resolver->get_search_paths(), custom_resolver);
mx::TypedElementPtr element = _FindSurfaceShaderElement(doc);
if (!element)
{
return false;
}
subIdentifier = element->getName();
shader = mShaderGen->generate(subIdentifier, element, context);
}
catch (const std::exception& ex)
{
STRELKA_ERROR("Exception generating MDL code: {}", ex.what());
}
if (!shader)
{
return false;
}
mx::ShaderStage pixelStage = shader->getStage(mx::Stage::PIXEL);
mdlSrc = pixelStage.getSourceCode();
return true;
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/mdlRuntime.cpp | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "mdlRuntime.h"
#include <mi/mdl_sdk.h>
#include <vector>
namespace oka
{
MdlRuntime::MdlRuntime()
{
}
MdlRuntime::~MdlRuntime()
{
if (mTransaction)
{
mTransaction->commit();
}
}
bool MdlRuntime::init(const char* paths[], uint32_t numPaths, const char* neurayPath, const char* imagePluginPath)
{
mLoader = std::make_unique<MdlNeurayLoader>();
if (!mLoader->init(neurayPath, imagePluginPath))
{
return false;
}
mi::base::Handle<mi::neuraylib::INeuray> neuray(mLoader->getNeuray());
mConfig = neuray->get_api_component<mi::neuraylib::IMdl_configuration>();
mi::base::Handle<mi::neuraylib::ILogging_configuration> logging_conf(
neuray->get_api_component<mi::neuraylib::ILogging_configuration>());
mLogger = mi::base::Handle<MdlLogger>(new MdlLogger());
logging_conf->set_receiving_logger(mLogger.get());
for (uint32_t i = 0; i < numPaths; i++)
{
if (mConfig->add_mdl_path(paths[i]) != 0 || mConfig->add_resource_path(paths[i]) != 0)
{
mLogger->message(mi::base::MESSAGE_SEVERITY_FATAL, "MDL file path not found, translation not possible");
return false;
}
}
mDatabase = mi::base::Handle<mi::neuraylib::IDatabase>(neuray->get_api_component<mi::neuraylib::IDatabase>());
mi::base::Handle<mi::neuraylib::IScope> scope(mDatabase->get_global_scope());
mTransaction = mi::base::Handle<mi::neuraylib::ITransaction>(scope->create_transaction());
mFactory = mi::base::Handle<mi::neuraylib::IMdl_factory>(neuray->get_api_component<mi::neuraylib::IMdl_factory>());
mImpExpApi = mi::base::Handle<mi::neuraylib::IMdl_impexp_api>(neuray->get_api_component<mi::neuraylib::IMdl_impexp_api>());
mBackendApi = mi::base::Handle<mi::neuraylib::IMdl_backend_api>(neuray->get_api_component<mi::neuraylib::IMdl_backend_api>());
return true;
}
mi::base::Handle<mi::neuraylib::IMdl_configuration> MdlRuntime::getConfig()
{
return mConfig;
}
mi::base::Handle<mi::neuraylib::INeuray> MdlRuntime::getNeuray()
{
return mLoader->getNeuray();
}
mi::base::Handle<MdlLogger> MdlRuntime::getLogger()
{
return mLogger;
}
mi::base::Handle<mi::neuraylib::IDatabase> MdlRuntime::getDatabase()
{
return mDatabase;
}
mi::base::Handle<mi::neuraylib::ITransaction> MdlRuntime::getTransaction()
{
return mTransaction;
}
mi::base::Handle<mi::neuraylib::IMdl_factory> MdlRuntime::getFactory()
{
return mFactory;
}
mi::base::Handle<mi::neuraylib::IMdl_impexp_api> MdlRuntime::getImpExpApi()
{
return mImpExpApi;
}
mi::base::Handle<mi::neuraylib::IMdl_backend_api> MdlRuntime::getBackendApi()
{
return mBackendApi;
}
} // namespace oka
|
arhix52/Strelka/src/materialmanager/CMakeLists.txt | cmake_minimum_required(VERSION 3.20)
find_package(MaterialX REQUIRED)
find_package(glm REQUIRED)
set(MATERIALLIB_NAME materialmanager)
# Material Manager
set(MATERIALMANAGER_SOURCES
${ROOT_HOME}/include/materialmanager/materialmanager.h
${ROOT_HOME}/include/materialmanager/mdlNeurayLoader.h
${ROOT_HOME}/include/materialmanager/mdlRuntime.h
${ROOT_HOME}/include/materialmanager/mdlPtxCodeGen.h
${ROOT_HOME}/include/materialmanager/mtlxMdlCodeGen.h
${ROOT_HOME}/include/materialmanager/mdlLogger.h
${ROOT_HOME}/include/materialmanager/mdlMaterialCompiler.h
${ROOT_HOME}/src/materialmanager/materialmanager.cpp
${ROOT_HOME}/src/materialmanager/mdlNeurayLoader.cpp
${ROOT_HOME}/src/materialmanager/mdlMaterialCompiler.cpp
${ROOT_HOME}/src/materialmanager/mdlRuntime.cpp
${ROOT_HOME}/src/materialmanager/mdlPtxCodeGen.cpp
${ROOT_HOME}/src/materialmanager/mtlxMdlCodeGen.cpp
${ROOT_HOME}/src/materialmanager/mdlLogger.cpp)
include_directories(${ROOT_HOME}/external/mdl-sdk/include)
add_library(${MATERIALLIB_NAME} STATIC ${MATERIALMANAGER_SOURCES})
target_include_directories(
${MATERIALLIB_NAME}
PUBLIC ${ROOT_HOME}/include/materialmanager
PRIVATE ${ROOT_HOME}/include/render/)
target_link_libraries(
${MATERIALLIB_NAME} PRIVATE logger MaterialXCore MaterialXFormat
MaterialXGenMdl glm::glm)
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"${OUTPUT_DIRECTORY}/optix/shaders")
if(WIN32 OR LINUX)
set(clang_PATH $ENV{clang_PATH})
find_program(clang_PATH clang)
message(STATUS "clang_PATH: ${clang_PATH}")
set(OptiX_INSTALL_DIR $ENV{OPTIX_DIR})
message(STATUS "OptiX SDK DIR: ${OptiX_INSTALL_DIR}")
find_package(OptiX REQUIRED)
message(STATUS "OptiX Include DIR: ${OptiX_INCLUDE}")
include_directories(${OptiX_INCLUDE})
if (WIN32)
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
COMMAND
${CMAKE_COMMAND} -E copy
"${ROOT_HOME}/external/mdl-sdk/nt-x86-64/lib/libmdl_sdk.dll"
"${OUTPUT_DIRECTORY}")
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
COMMAND
${CMAKE_COMMAND} -E copy
"${ROOT_HOME}/external/mdl-sdk/nt-x86-64/lib/nv_openimageio.dll"
"${OUTPUT_DIRECTORY}")
endif(WIN32)
if (LINUX)
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
COMMAND
${CMAKE_COMMAND} -E copy
"${ROOT_HOME}/external/mdl-sdk/linux-x86-64/lib/libmdl_sdk.so"
"${OUTPUT_DIRECTORY}")
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
COMMAND
${CMAKE_COMMAND} -E copy
"${ROOT_HOME}/external/mdl-sdk/linux-x86-64/lib/nv_openimageio.so"
"${OUTPUT_DIRECTORY}")
endif(LINUX)
set(_CLANG_FLAGS ${_CLANG_FLAGS} --cuda-path=${CUDA_TOOLKIT_ROOT_DIR})
# generate bytecode for closest hit radiance shader Note: the
# _ALLOW_COMPILER_AND_STL_VERSION_MISMATCH define is needed to allow
# compilation with Clang 7 and VS2019 headers
add_custom_command(
TARGET ${MATERIALLIB_NAME}
PRE_BUILD
# OUTPUT OptixRender_radiance_closest_hit.d
# OptixRender_radiance_closest_hit.bc Target: Ada: sm_89 - unsupported by
# clang 12 Ampere: sm_86 unsupported by clang 12 Turing: sm_75
COMMAND ${CMAKE_COMMAND} -E echo
"Compile OptixRender_radiance_closest_hit bytecode using clang..."
COMMAND
${clang_PATH} -I ${OptiX_INCLUDE} -I ${ROOT_HOME}/external/mdl-sdk/include
-I ${ROOT_HOME}/src/render/ -I ${ROOT_HOME}/src/render/optix/
-I ${ROOT_HOME}/include/render -I ${ROOT_HOME}
-Wno-unknown-cuda-version
-std=c++17
-I /usr/include/c++/11/
${_CLANG_FLAGS}
-D_ALLOW_COMPILER_AND_STL_VERSION_MISMATCH -emit-llvm -c -O3 -ffast-math
-fcuda-flush-denormals-to-zero -fno-vectorize --cuda-gpu-arch=sm_75
--cuda-device-only
${ROOT_HOME}/src/render/optix/OptixRender_radiance_closest_hit.cu -o
${OUTPUT_DIRECTORY}/optix/shaders/OptixRender_radiance_closest_hit.bc -MD
-MT ${OUTPUT_DIRECTORY}/optix/shaders/OptixRender_radiance_closest_hit.bc
-MP -MF
${OUTPUT_DIRECTORY}/optix/shaders/OptixRender_radiance_closest_hit.d
WORKING_DIRECTORY ${CMAKE_CFG_INTDIR}
DEPENDS "OptixRender_radiance_closest_hit.cu" ${PROJECT_SOURCES} VERBATIM)
endif()
|
arhix52/Strelka/src/materialmanager/mdlLogger.cpp | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "mdlLogger.h"
#include <log.h>
namespace oka
{
const char* _miMessageSeverityToCStr(mi::base::Message_severity severity)
{
switch (severity)
{
case mi::base::MESSAGE_SEVERITY_FATAL:
return "fatal";
case mi::base::MESSAGE_SEVERITY_ERROR:
return "error";
case mi::base::MESSAGE_SEVERITY_WARNING:
return "warning";
case mi::base::MESSAGE_SEVERITY_INFO:
return "info";
case mi::base::MESSAGE_SEVERITY_VERBOSE:
return "verbose";
case mi::base::MESSAGE_SEVERITY_DEBUG:
return "debug";
default:
break;
}
return "";
}
const char* _miMessageKindToCStr(mi::neuraylib::IMessage::Kind kind)
{
switch (kind)
{
case mi::neuraylib::IMessage::MSG_INTEGRATION:
return "MDL SDK";
case mi::neuraylib::IMessage::MSG_IMP_EXP:
return "Importer/Exporter";
case mi::neuraylib::IMessage::MSG_COMILER_BACKEND:
return "Compiler Backend";
case mi::neuraylib::IMessage::MSG_COMILER_CORE:
return "Compiler Core";
case mi::neuraylib::IMessage::MSG_COMPILER_ARCHIVE_TOOL:
return "Compiler Archive Tool";
case mi::neuraylib::IMessage::MSG_COMPILER_DAG:
return "Compiler DAG generator";
default:
break;
}
return "";
}
void MdlLogger::message(mi::base::Message_severity level,
const char* moduleCategory,
const mi::base::Message_details& details,
const char* message)
{
#ifdef NDEBUG
const mi::base::Message_severity minLogLevel = mi::base::MESSAGE_SEVERITY_WARNING;
#else
const mi::base::Message_severity minLogLevel = mi::base::MESSAGE_SEVERITY_VERBOSE;
#endif
if (level <= minLogLevel)
{
// const char* s_severity = _miMessageSeverityToCStr(level);
// FILE* os = (level <= mi::base::MESSAGE_SEVERITY_ERROR) ? stderr : stdout;
// fprintf(os, "[%s] (%s) %s\n", s_severity, moduleCategory, message);
switch (level)
{
case mi::base::MESSAGE_SEVERITY_FATAL:
STRELKA_FATAL("MDL: ({0}) {1}", moduleCategory, message);
break;
case mi::base::MESSAGE_SEVERITY_ERROR:
STRELKA_ERROR("MDL: ({0}) {1}", moduleCategory, message);
break;
case mi::base::MESSAGE_SEVERITY_WARNING:
STRELKA_WARNING("MDL: ({0}) {1}", moduleCategory, message);
break;
case mi::base::MESSAGE_SEVERITY_INFO:
STRELKA_INFO("MDL: ({0}) {1}", moduleCategory, message);
break;
case mi::base::MESSAGE_SEVERITY_VERBOSE:
STRELKA_TRACE("MDL: ({0}) {1}", moduleCategory, message);
break;
case mi::base::MESSAGE_SEVERITY_DEBUG:
STRELKA_DEBUG("MDL: ({0}) {1}", moduleCategory, message);
break;
default:
break;
}
}
}
void MdlLogger::message(mi::base::Message_severity level, const char* moduleCategory, const char* message)
{
this->message(level, moduleCategory, mi::base::Message_details{}, message);
}
void MdlLogger::message(mi::base::Message_severity level, const char* message)
{
const char* MODULE_CATEGORY = "shadergen";
this->message(level, MODULE_CATEGORY, message);
}
void MdlLogger::flushContextMessages(mi::neuraylib::IMdl_execution_context* context)
{
for (mi::Size i = 0, n = context->get_messages_count(); i < n; ++i)
{
mi::base::Handle<const mi::neuraylib::IMessage> message(context->get_message(i));
const char* s_msg = message->get_string();
const char* s_kind = _miMessageKindToCStr(message->get_kind());
this->message(message->get_severity(), s_kind, s_msg);
}
context->clear_messages();
}
} // namespace oka
|
arhix52/Strelka/src/render/CMakeLists.txt | cmake_minimum_required(VERSION 3.22)
set(RENDERLIB_NAME render)
find_package(glm REQUIRED)
find_package(stb REQUIRED)
# include(${ROOT_HOME}/cmake/StaticAnalyzers.cmake)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(RENDER_SOURCES_COMMON ${ROOT_HOME}/include/render/render.h
${ROOT_HOME}/src/render/render.cpp)
if(WIN32 OR LINUX)
enable_language(CUDA)
find_package(CUDA REQUIRED)
message(STATUS "CUDA Toolkit Root: ${CUDA_TOOLKIT_ROOT_DIR}")
message(STATUS "CUDA Include DIR: ${CUDA_INCLUDE_DIRS}")
# Search for the OptiX libraries and include files.
set(OptiX_INSTALL_DIR $ENV{OPTIX_DIR})
message(STATUS "OptiX SDK DIR: ${OptiX_INSTALL_DIR}")
# Search for the OptiX libraries and include files.
find_package(OptiX REQUIRED)
message(STATUS "OptiX Include DIR: ${OptiX_INCLUDE}")
include_directories(${OptiX_INCLUDE})
# Hack to get intellisense working for CUDA includes
if(MSVC)
set(CMAKE_VS_SDK_INCLUDE_DIRECTORIES
"$(VC_IncludePath);$(WindowsSDK_IncludePath);${OptiX_INCLUDE}")
endif()
set(RENDER_SOURCES
${RENDER_SOURCES_COMMON}
${ROOT_HOME}/include/render/Camera.h
${ROOT_HOME}/include/render/materials.h
${ROOT_HOME}/include/render/Lights.h
${ROOT_HOME}/src/render/Camera.cpp
${ROOT_HOME}/src/render/optix/OptixBuffer.h
${ROOT_HOME}/src/render/optix/OptixBuffer.cpp
${ROOT_HOME}/src/render/optix/OptixRender.h
${ROOT_HOME}/src/render/optix/OptixRender.cpp)
set(RENDER_OPTIX_SOURCES ${ROOT_HOME}/include/render/optix/OptixRenderParams.h
${ROOT_HOME}/src/render/optix/OptixRender.cu)
include_directories(${ROOT_HOME}/include/render)
include_directories(${ROOT_HOME}/src/render/optix)
include_directories(${ROOT_HOME})
# Create the rules to build the PTX and/or OPTIX files.
cuda_wrap_srcs(
${RENDERLIB_NAME}
OPTIXIR
generated_files2
${RENDER_OPTIX_SOURCES}
${cmake_options}
OPTIONS
${options})
list(APPEND generated_files ${generated_files2})
set(RENDER_CUDA_SOURCES
${ROOT_HOME}/src/render/optix/postprocessing/Tonemappers.h
${ROOT_HOME}/src/render/optix/postprocessing/Tonemappers.cu
)
add_library(${RENDERLIB_NAME} STATIC ${RENDER_SOURCES} ${generated_files} ${RENDER_CUDA_SOURCES})
endif()
if(WIN32 OR LINUX)
target_include_directories(${RENDERLIB_NAME} PUBLIC ${OptiX_INCLUDE})
target_include_directories(${RENDERLIB_NAME} PUBLIC ${CUDA_INCLUDE_DIRS})
add_custom_command(
TARGET ${RENDERLIB_NAME}
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory "${OUTPUT_DIRECTORY}/optix")
add_custom_command(
TARGET ${RENDERLIB_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${generated_files}
"${OUTPUT_DIRECTORY}/optix")
target_link_libraries(${RENDERLIB_NAME} PUBLIC ${CUDA_LIBRARIES} scene
materialmanager glm::glm stb::stb)
endif()
if(APPLE)
set(RENDER_SOURCES
${RENDER_SOURCES_COMMON}
${ROOT_HOME}/src/render/metal/MetalRender.h
${ROOT_HOME}/src/render/metal/MetalRender.cpp
${ROOT_HOME}/src/render/metal/MetalBuffer.h
${ROOT_HOME}/src/render/metal/MetalBuffer.cpp)
add_library(${RENDERLIB_NAME} STATIC ${RENDER_SOURCES})
target_include_directories(${RENDERLIB_NAME}
PUBLIC ${ROOT_HOME}/external/metal-cpp/)
target_include_directories(${RENDERLIB_NAME}
PUBLIC ${ROOT_HOME}/external/metal-cpp-extensions/)
target_link_libraries(${RENDERLIB_NAME} PUBLIC "-framework Foundation")
target_link_libraries(${RENDERLIB_NAME} PUBLIC "-framework QuartzCore")
target_link_libraries(${RENDERLIB_NAME} PUBLIC "-framework Metal")
target_link_libraries(${RENDERLIB_NAME} PUBLIC "-framework MetalKit")
target_link_libraries(${RENDERLIB_NAME} PUBLIC glm::glm stb::stb)
add_custom_command(
TARGET ${RENDERLIB_NAME}
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"${OUTPUT_DIRECTORY}/metal/shaders")
add_custom_command(
TARGET ${RENDERLIB_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/src/render/metal/shaders/fullScreen.metal ${OUTPUT_DIRECTORY}/metal/shaders
)
set(METAL_SOURCES ${ROOT_HOME}/src/render/metal/shaders/pathtrace.metal)
set(METAL_SOURCES_TM ${ROOT_HOME}/src/render/metal/shaders/tonemapper.metal)
add_custom_command(
OUTPUT ${OUTPUT_DIRECTORY}/metal/shaders/pathtrace.metallib PRE_BUILD
OUTPUT ${OUTPUT_DIRECTORY}/metal/shaders/tonemapper.metallib PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"${OUTPUT_DIRECTORY}/metal/shaders"
COMMAND ${CMAKE_COMMAND} -E echo "Compile metal shaders..."
COMMAND xcrun -sdk macosx metal -Wall -c ${METAL_SOURCES} -o pathtrace.air -I
${ROOT_HOME}/src/render/metal/shaders
COMMAND xcrun -sdk macosx metal -Wall -c ${METAL_SOURCES_TM} -o tonemapper.air -I
${ROOT_HOME}/src/render/metal/shaders
COMMAND ${CMAKE_COMMAND} -E echo "Link metal shaders..."
COMMAND xcrun -sdk macosx metallib pathtrace.air -o
${OUTPUT_DIRECTORY}/metal/shaders/pathtrace.metallib
COMMAND xcrun -sdk macosx metallib tonemapper.air -o
${OUTPUT_DIRECTORY}/metal/shaders/tonemapper.metallib
WORKING_DIRECTORY ${CMAKE_CFG_INTDIR}
MAIN_DEPENDENCY ${METAL_SOURCES}
VERBATIM)
add_custom_command(
OUTPUT ${OUTPUT_DIRECTORY}/metal/shaders/tonemapper.metallib PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E echo "Compile Tonemapper metal shaders..."
COMMAND xcrun -sdk macosx metal -Wall -c ${METAL_SOURCES_TM} -o tonemapper.air -I
${ROOT_HOME}/src/render/metal/shaders
COMMAND ${CMAKE_COMMAND} -E echo "Link Tonemapper metal shaders..."
COMMAND xcrun -sdk macosx metallib tonemapper.air -o
${OUTPUT_DIRECTORY}/metal/shaders/tonemapper.metallib
WORKING_DIRECTORY ${CMAKE_CFG_INTDIR}
MAIN_DEPENDENCY ${METAL_SOURCES_TM}
VERBATIM)
# target_sources(${RENDERLIB_NAME}
# PUBLIC ${OUTPUT_DIRECTORY}/metal/shaders/pathtrace.metallib)
endif(APPLE)
target_link_libraries(${RENDERLIB_NAME} PUBLIC logger)
target_include_directories(${RENDERLIB_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${RENDERLIB_NAME} PUBLIC ${ROOT_HOME}/include/render)
target_include_directories(${RENDERLIB_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(${RENDERLIB_NAME} PUBLIC ${ROOT_HOME}/external/mdl-sdk/include)
|
arhix52/Strelka/src/render/Camera.cpp | |
arhix52/Strelka/src/render/render.cpp | #include "render.h"
#ifdef __APPLE__
# include "metal/MetalRender.h"
#else
# include "optix/OptixRender.h"
#endif
using namespace oka;
Render* RenderFactory::createRender(const RenderType type)
{
#ifdef __APPLE__
if (type == RenderType::eMetal)
{
return new MetalRender();
}
// unsupported
return nullptr;
#else
if (type == RenderType::eOptiX)
{
return new OptiXRender();
}
return nullptr;
#endif
}
|
arhix52/Strelka/src/render/optix/RandomSampler.h | #pragma once
#include <stdint.h>
// source:
// https://github.com/mmp/pbrt-v4/blob/5acc5e46cf4b5c3382babd6a3b93b87f54d79b0a/src/pbrt/util/float.h#L46C1-L47C1
static constexpr float FloatOneMinusEpsilon = 0x1.fffffep-1;
__device__ const unsigned int primeNumbers[32] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131,
};
enum struct SampleDimension : uint32_t
{
ePixelX,
ePixelY,
eLightId,
eLightPointX,
eLightPointY,
eBSDF0,
eBSDF1,
eBSDF2,
eBSDF3,
eRussianRoulette,
eNUM_DIMENSIONS
};
struct SamplerState
{
uint32_t seed;
uint32_t sampleIdx;
uint32_t depth;
};
#define MAX_BOUNCES 128
// Based on: https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
__device__ inline unsigned int pcg_hash(unsigned int seed)
{
unsigned int state = seed * 747796405u + 2891336453u;
unsigned int word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
return (word >> 22u) ^ word;
}
// __device__ inline unsigned hash_combine(unsigned a, unsigned b)
// {
// return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
// }
__device__ __inline__ uint32_t hash_combine(uint32_t seed, uint32_t v)
{
return seed ^ (v + (seed << 6) + (seed >> 2));
}
__device__ inline unsigned int hash_with(unsigned int seed, unsigned int hash)
{
// Wang hash
seed = (seed ^ 61u) ^ hash;
seed += seed << 3;
seed ^= seed >> 4;
seed *= 0x27d4eb2du;
return seed;
}
// Generate random unsigned int in [0, 2^24)
static __host__ __device__ __inline__ unsigned int lcg(unsigned int& prev)
{
const unsigned int LCG_A = 1664525u;
const unsigned int LCG_C = 1013904223u;
prev = (LCG_A * prev + LCG_C);
return prev & 0x00FFFFFF;
}
// jenkins hash
static __device__ unsigned int jenkins_hash(unsigned int a)
{
a = (a + 0x7ED55D16) + (a << 12);
a = (a ^ 0xC761C23C) ^ (a >> 19);
a = (a + 0x165667B1) + (a << 5);
a = (a + 0xD3A2646C) ^ (a << 9);
a = (a + 0xFD7046C5) + (a << 3);
a = (a ^ 0xB55A4F09) ^ (a >> 16);
return a;
}
__device__ __inline__ uint32_t hash(uint32_t x)
{
// finalizer from murmurhash3
x ^= x >> 16;
x *= 0x85ebca6bu;
x ^= x >> 13;
x *= 0xc2b2ae35u;
x ^= x >> 16;
return x;
}
static __device__ float halton(uint32_t index, uint32_t base)
{
const float s = 1.0f / float(base);
unsigned int i = index;
float result = 0.0f;
float f = s;
while (i)
{
const unsigned int digit = i % base;
result += f * float(digit);
i = (i - digit) / base;
f *= s;
}
return clamp(result, 0.0f, FloatOneMinusEpsilon);
}
// source https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
// "Insert" a 0 bit after each of the 16 low bits of x
__device__ __inline__ uint32_t Part1By1(uint32_t x)
{
x &= 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210
x = (x ^ (x << 8)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210
x = (x ^ (x << 4)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210
x = (x ^ (x << 2)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
x = (x ^ (x << 1)) & 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
return x;
}
__device__ __inline__ uint32_t EncodeMorton2(uint32_t x, uint32_t y)
{
return (Part1By1(y) << 1) + Part1By1(x);
}
static __device__ SamplerState initSampler(uint32_t pixelX, uint32_t pixelY, uint32_t linearPixelIndex, uint32_t pixelSampleIndex, uint32_t maxSampleCount, uint32_t seed)
{
SamplerState sampler{};
sampler.seed = seed;
// sampler.sampleIdx = pixelSampleIndex + linearPixelIndex * maxSampleCount;
sampler.sampleIdx = EncodeMorton2(pixelX, pixelY) * maxSampleCount + pixelSampleIndex;
return sampler;
}
__device__ const uint32_t sb_matrix[5][32] = {
0x80000000, 0x40000000, 0x20000000, 0x10000000, 0x08000000, 0x04000000, 0x02000000, 0x01000000,
0x00800000, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000,
0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100,
0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001,
0x80000000, 0xc0000000, 0xa0000000, 0xf0000000, 0x88000000, 0xcc000000, 0xaa000000, 0xff000000,
0x80800000, 0xc0c00000, 0xa0a00000, 0xf0f00000, 0x88880000, 0xcccc0000, 0xaaaa0000, 0xffff0000,
0x80008000, 0xc000c000, 0xa000a000, 0xf000f000, 0x88008800, 0xcc00cc00, 0xaa00aa00, 0xff00ff00,
0x80808080, 0xc0c0c0c0, 0xa0a0a0a0, 0xf0f0f0f0, 0x88888888, 0xcccccccc, 0xaaaaaaaa, 0xffffffff,
0x80000000, 0xc0000000, 0x60000000, 0x90000000, 0xe8000000, 0x5c000000, 0x8e000000, 0xc5000000,
0x68800000, 0x9cc00000, 0xee600000, 0x55900000, 0x80680000, 0xc09c0000, 0x60ee0000, 0x90550000,
0xe8808000, 0x5cc0c000, 0x8e606000, 0xc5909000, 0x6868e800, 0x9c9c5c00, 0xeeee8e00, 0x5555c500,
0x8000e880, 0xc0005cc0, 0x60008e60, 0x9000c590, 0xe8006868, 0x5c009c9c, 0x8e00eeee, 0xc5005555,
0x80000000, 0xc0000000, 0x20000000, 0x50000000, 0xf8000000, 0x74000000, 0xa2000000, 0x93000000,
0xd8800000, 0x25400000, 0x59e00000, 0xe6d00000, 0x78080000, 0xb40c0000, 0x82020000, 0xc3050000,
0x208f8000, 0x51474000, 0xfbea2000, 0x75d93000, 0xa0858800, 0x914e5400, 0xdbe79e00, 0x25db6d00,
0x58800080, 0xe54000c0, 0x79e00020, 0xb6d00050, 0x800800f8, 0xc00c0074, 0x200200a2, 0x50050093,
0x80000000, 0x40000000, 0x20000000, 0xb0000000, 0xf8000000, 0xdc000000, 0x7a000000, 0x9d000000,
0x5a800000, 0x2fc00000, 0xa1600000, 0xf0b00000, 0xda880000, 0x6fc40000, 0x81620000, 0x40bb0000,
0x22878000, 0xb3c9c000, 0xfb65a000, 0xddb2d000, 0x78022800, 0x9c0b3c00, 0x5a0fb600, 0x2d0ddb00,
0xa2878080, 0xf3c9c040, 0xdb65a020, 0x6db2d0b0, 0x800228f8, 0x400b3cdc, 0x200fb67a, 0xb00ddb9d,
};
__device__ __inline__ uint32_t sobol_uint(uint32_t index, uint32_t dim)
{
uint32_t X = 0;
for (int bit = 0; bit < 32; bit++)
{
int mask = (index >> bit) & 1;
X ^= mask * sb_matrix[dim][bit];
}
return X;
}
__device__ __inline__ float sobol(uint32_t index, uint32_t dim)
{
return min(sobol_uint(index, dim) * 0x1p-32f, FloatOneMinusEpsilon);
}
__device__ __inline__ uint32_t laine_karras_permutation(uint32_t value, uint32_t seed)
{
value += seed;
value ^= value * 0x6c50b47cu;
value ^= value * 0xb82f1e52u;
value ^= value * 0xc7afe638u;
value ^= value * 0x8d22f6e6u;
return value;
}
__device__ __inline__ uint32_t ReverseBits(uint32_t value)
{
#ifdef __CUDACC__
return __brev(value);
#else
value = (((value & 0xaaaaaaaa) >> 1) | ((value & 0x55555555) << 1));
value = (((value & 0xcccccccc) >> 2) | ((value & 0x33333333) << 2));
value = (((value & 0xf0f0f0f0) >> 4) | ((value & 0x0f0f0f0f) << 4));
value = (((value & 0xff00ff00) >> 8) | ((value & 0x00ff00ff) << 8));
return ((value >> 16) | (value << 16));
#endif
}
__device__ __inline__ uint32_t nested_uniform_scramble(uint32_t value, uint32_t seed)
{
value = ReverseBits(value);
value = laine_karras_permutation(value, seed);
value = ReverseBits(value);
return value;
}
__device__ __inline__ float sobol_scramble(uint32_t index, uint32_t dim, uint32_t seed)
{
seed = hash(seed);
index = nested_uniform_scramble(index, seed);
uint32_t result = nested_uniform_scramble(sobol_uint(index, dim), hash_combine(seed, dim));
return min(result * 0x1p-32f, FloatOneMinusEpsilon);
}
template <SampleDimension Dim>
__device__ __inline__ float random(SamplerState& state)
{
const uint32_t dimension = (uint32_t(Dim) + state.depth * uint32_t(SampleDimension::eNUM_DIMENSIONS)) % 5;
return sobol_scramble(state.sampleIdx, dimension, state.seed + state.depth);
}
|
arhix52/Strelka/src/render/optix/OptixBuffer.h | #pragma once
#include "buffer.h"
#include <stdint.h>
#include <vector>
namespace oka
{
class OptixBuffer : public Buffer
{
public:
OptixBuffer(void* devicePtr, BufferFormat format, uint32_t width, uint32_t height);
virtual ~OptixBuffer();
void resize(uint32_t width, uint32_t height) override;
void* map() override;
void unmap() override;
void* getNativePtr()
{
return mDeviceData;
}
protected:
void* mDeviceData = nullptr;
uint32_t mDeviceIndex = 0;
};
} // namespace oka
|
arhix52/Strelka/src/render/optix/OptixRenderParams.h | #pragma once
#include <optix_types.h>
#include <vector_types.h>
#include <sutil/Matrix.h>
#include "RandomSampler.h"
#include "Lights.h"
#define GEOMETRY_MASK_TRIANGLE 1
#define GEOMETRY_MASK_CURVE 2
#define GEOMETRY_MASK_LIGHT 4
#define GEOMETRY_MASK_GEOMETRY (GEOMETRY_MASK_TRIANGLE | GEOMETRY_MASK_CURVE)
#define RAY_MASK_PRIMARY (GEOMETRY_MASK_GEOMETRY | GEOMETRY_MASK_LIGHT)
#define RAY_MASK_SHADOW GEOMETRY_MASK_GEOMETRY
#define RAY_MASK_SECONDARY GEOMETRY_MASK_GEOMETRY
struct Vertex
{
float3 position;
uint32_t tangent;
uint32_t normal;
uint32_t uv;
float pad0;
float pad1;
};
struct SceneData
{
Vertex* vb;
uint32_t* ib;
UniformLight* lights;
uint32_t numLights;
};
struct Params
{
uint32_t subframe_index;
uint32_t samples_per_launch;
uint32_t maxSampleCount;
float4* image;
float4* accum;
float4* diffuse;
uint16_t* diffuseCounter;
float4* specular;
uint16_t* specularCounter;
uint32_t image_width;
uint32_t image_height;
uint32_t max_depth;
uint32_t rectLightSamplingMethod;
float3 exposure;
float clipToView[16];
float viewToWorld[16];
OptixTraversableHandle handle;
SceneData scene;
bool enableAccumulation;
// developers settings:
uint32_t debug;
float shadowRayTmin;
float materialRayTmin;
};
enum class EventType: uint8_t
{
eUndef,
eAbsorb,
eDiffuse,
eSpecular,
eLast,
};
struct PerRayData
{
SamplerState sampler;
uint32_t linearPixelIndex;
uint32_t sampleIndex;
uint32_t depth; // bounce
float3 radiance;
float3 throughput;
float3 origin;
float3 dir;
bool inside;
bool specularBounce;
float lastBsdfPdf;
EventType firstEventType;
};
enum RayType
{
RAY_TYPE_RADIANCE = 0,
RAY_TYPE_OCCLUSION = 1,
RAY_TYPE_COUNT
};
struct RayGenData
{
// No data needed
};
struct MissData
{
float3 bg_color;
};
struct HitGroupData
{
int32_t indexOffset;
int32_t indexCount;
int32_t vertexOffset;
int32_t lightId; // only for lights. -1 for others
CUdeviceptr argData;
CUdeviceptr roData;
CUdeviceptr resHandler;
float4 world_to_object[4] = {};
float4 object_to_world[4] = {};
};
|
arhix52/Strelka/src/render/optix/texture_support_cuda.h | /******************************************************************************
* Copyright 2022 NVIDIA Corporation. All rights reserved.
*****************************************************************************/
// examples/mdl_sdk/shared/texture_support_cuda.h
//
// This file contains the implementations and the vtables of the texture access functions.
#ifndef TEXTURE_SUPPORT_CUDA_H
#define TEXTURE_SUPPORT_CUDA_H
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
#include <mi/neuraylib/target_code_types.h>
#define USE_SMOOTHERSTEP_FILTER
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define M_ONE_OVER_PI 0.318309886183790671538
typedef mi::neuraylib::tct_deriv_float tct_deriv_float;
typedef mi::neuraylib::tct_deriv_float2 tct_deriv_float2;
typedef mi::neuraylib::tct_deriv_arr_float_2 tct_deriv_arr_float_2;
typedef mi::neuraylib::tct_deriv_arr_float_3 tct_deriv_arr_float_3;
typedef mi::neuraylib::tct_deriv_arr_float_4 tct_deriv_arr_float_4;
typedef mi::neuraylib::Shading_state_material_with_derivs Shading_state_material_with_derivs;
typedef mi::neuraylib::Shading_state_material Shading_state_material;
typedef mi::neuraylib::Texture_handler_base Texture_handler_base;
typedef mi::neuraylib::Tex_wrap_mode Tex_wrap_mode;
typedef mi::neuraylib::Mbsdf_part Mbsdf_part;
// Custom structure representing an MDL texture, containing filtered and unfiltered CUDA texture
// objects and the size of the texture.
struct Texture
{
explicit Texture()
: filtered_object(0)
, unfiltered_object(0)
, size(make_uint3(0, 0, 0))
, inv_size(make_float3(0.0f, 0.0f, 0.0f))
{}
explicit Texture(
cudaTextureObject_t filtered_object,
cudaTextureObject_t unfiltered_object,
uint3 size)
: filtered_object(filtered_object)
, unfiltered_object(unfiltered_object)
, size(size)
, inv_size(make_float3(1.0f / size.x, 1.0f / size.y, 1.0f / size.z))
{}
cudaTextureObject_t filtered_object; // uses filter mode cudaFilterModeLinear
cudaTextureObject_t unfiltered_object; // uses filter mode cudaFilterModePoint
uint3 size; // size of the texture, needed for texel access
float3 inv_size; // the inverse values of the size of the texture
};
// Custom structure representing an MDL BSDF measurement.
struct Mbsdf
{
unsigned has_data[2]; // true if there is a measurement for this part
cudaTextureObject_t eval_data[2]; // uses filter mode cudaFilterModeLinear
float max_albedo[2]; // max albedo used to limit the multiplier
float* sample_data[2]; // CDFs for sampling a BSDF measurement
float* albedo_data[2]; // max albedo for each theta (isotropic)
uint2 angular_resolution[2]; // size of the dataset, needed for texel access
float2 inv_angular_resolution[2]; // the inverse values of the size of the dataset
unsigned num_channels[2]; // number of color channels (1 or 3)
};
// Structure representing a Light Profile
struct Lightprofile
{
explicit Lightprofile()
: angular_resolution(make_uint2(0, 0))
, inv_angular_resolution(make_float2(0.0f, 0.0f))
, theta_phi_start(make_float2(0.0f, 0.0f))
, theta_phi_delta(make_float2(0.0f, 0.0f))
, theta_phi_inv_delta(make_float2(0.0f, 0.0f))
, candela_multiplier(0.0f)
, total_power(0.0f)
, eval_data(0)
{
}
uint2 angular_resolution; // angular resolution of the grid
float2 inv_angular_resolution; // inverse angular resolution of the grid
float2 theta_phi_start; // start of the grid
float2 theta_phi_delta; // angular step size
float2 theta_phi_inv_delta; // inverse step size
float candela_multiplier; // factor to rescale the normalized data
float total_power;
cudaTextureObject_t eval_data; // normalized data sampled on grid
float* cdf_data; // CDFs for sampling a light profile
};
// The texture handler structure required by the MDL SDK with custom additional fields.
struct Texture_handler : Texture_handler_base {
// additional data for the texture access functions can be provided here
size_t num_textures; // the number of textures used by the material
// (without the invalid texture)
Texture const *textures; // the textures used by the material
// (without the invalid texture)
size_t num_mbsdfs; // the number of mbsdfs used by the material
// (without the invalid mbsdf)
Mbsdf const *mbsdfs; // the mbsdfs used by the material
// (without the invalid mbsdf)
size_t num_lightprofiles; // number of elements in the lightprofiles field
// (without the invalid light profile)
Lightprofile const *lightprofiles; // a device pointer to a list of mbsdfs objects, if used
// (without the invalid light profile)
};
// The texture handler structure required by the MDL SDK with custom additional fields.
struct Texture_handler_deriv : mi::neuraylib::Texture_handler_deriv_base {
// additional data for the texture access functions can be provided here
size_t num_textures; // the number of textures used by the material
// (without the invalid texture)
Texture const *textures; // the textures used by the material
// (without the invalid texture)
size_t num_mbsdfs; // the number of mbsdfs used by the material
// (without the invalid texture)
Mbsdf const *mbsdfs; // the mbsdfs used by the material
// (without the invalid texture)
size_t num_lightprofiles; // number of elements in the lightprofiles field
// (without the invalid light profile)
Lightprofile const *lightprofiles; // a device pointer to a list of mbsdfs objects, if used
// (without the invalid light profile)
};
#if defined(__CUDACC__)
// Stores a float4 in a float[4] array.
__device__ inline void store_result4(float res[4], const float4 &v)
{
res[0] = v.x;
res[1] = v.y;
res[2] = v.z;
res[3] = v.w;
}
// Stores a float in all elements of a float[4] array.
__device__ inline void store_result4(float res[4], float s)
{
res[0] = res[1] = res[2] = res[3] = s;
}
// Stores the given float values in a float[4] array.
__device__ inline void store_result4(
float res[4], float v0, float v1, float v2, float v3)
{
res[0] = v0;
res[1] = v1;
res[2] = v2;
res[3] = v3;
}
// Stores a float3 in a float[3] array.
__device__ inline void store_result3(float res[3], float3 const&v)
{
res[0] = v.x;
res[1] = v.y;
res[2] = v.z;
}
// Stores a float4 in a float[3] array, ignoring v.w.
__device__ inline void store_result3(float res[3], const float4 &v)
{
res[0] = v.x;
res[1] = v.y;
res[2] = v.z;
}
// Stores a float in all elements of a float[3] array.
__device__ inline void store_result3(float res[3], float s)
{
res[0] = res[1] = res[2] = s;
}
// Stores the given float values in a float[3] array.
__device__ inline void store_result3(float res[3], float v0, float v1, float v2)
{
res[0] = v0;
res[1] = v1;
res[2] = v2;
}
// Stores the luminance if a given float[3] in a float.
__device__ inline void store_result1(float* res, float3 const& v)
{
// store luminance
*res = 0.212671 * v.x + 0.715160 * v.y + 0.072169 * v.z;
}
// Stores the luminance if a given float[3] in a float.
__device__ inline void store_result1(float* res, float v0, float v1, float v2)
{
// store luminance
*res = 0.212671 * v0 + 0.715160 * v1 + 0.072169 * v2;
}
// Stores a given float in a float
__device__ inline void store_result1(float* res, float s)
{
*res = s;
}
// ------------------------------------------------------------------------------------------------
// Textures
// ------------------------------------------------------------------------------------------------
// Applies wrapping and cropping to the given coordinate.
// Note: This macro returns if wrap mode is clip and the coordinate is out of range.
#define WRAP_AND_CROP_OR_RETURN_BLACK(val, inv_dim, wrap_mode, crop_vals, store_res_func) \
do { \
if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_REPEAT && \
(crop_vals)[0] == 0.0f && (crop_vals)[1] == 1.0f ) { \
/* Do nothing, use texture sampler default behavior */ \
} \
else \
{ \
if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_REPEAT ) \
val = val - floorf(val); \
else { \
if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_CLIP && (val < 0.0f || val >= 1.0f) ) { \
store_res_func(result, 0.0f); \
return; \
} \
else if ( (wrap_mode) == mi::neuraylib::TEX_WRAP_MIRRORED_REPEAT ) { \
float floored_val = floorf(val); \
if ( (int(floored_val) & 1) != 0 ) \
val = 1.0f - (val - floored_val); \
else \
val = val - floored_val; \
} \
float inv_hdim = 0.5f * (inv_dim); \
val = fminf(fmaxf(val, inv_hdim), 1.f - inv_hdim); \
} \
val = val * ((crop_vals)[1] - (crop_vals)[0]) + (crop_vals)[0]; \
} \
} while ( 0 )
#ifdef USE_SMOOTHERSTEP_FILTER
// Modify texture coordinates to get better texture filtering,
// see http://www.iquilezles.org/www/articles/texture/texture.htm
#define APPLY_SMOOTHERSTEP_FILTER() \
do { \
u = u * tex.size.x + 0.5f; \
v = v * tex.size.y + 0.5f; \
\
float u_i = floorf(u), v_i = floorf(v); \
float u_f = u - u_i; \
float v_f = v - v_i; \
u_f = u_f * u_f * u_f * (u_f * (u_f * 6.f - 15.f) + 10.f); \
v_f = v_f * v_f * v_f * (v_f * (v_f * 6.f - 15.f) + 10.f); \
u = u_i + u_f; \
v = v_i + v_f; \
\
u = (u - 0.5f) * tex.inv_size.x; \
v = (v - 0.5f) * tex.inv_size.y; \
} while ( 0 )
#else
#define APPLY_SMOOTHERSTEP_FILTER()
#endif
// Implementation of tex::lookup_float4() for a texture_2d texture.
extern "C" __device__ void tex_lookup_float4_2d(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[2],
Tex_wrap_mode const wrap_u,
Tex_wrap_mode const wrap_v,
float const crop_u[2],
float const crop_v[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord[0], v = coord[1];
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4);
APPLY_SMOOTHERSTEP_FILTER();
store_result4(result, tex2D<float4>(tex.filtered_object, u, v));
}
// Implementation of tex::lookup_float4() for a texture_2d texture.
extern "C" __device__ void tex_lookup_deriv_float4_2d(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
tct_deriv_float2 const *coord,
Tex_wrap_mode const wrap_u,
Tex_wrap_mode const wrap_v,
float const crop_u[2],
float const crop_v[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord->val.x, v = coord->val.y;
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4);
APPLY_SMOOTHERSTEP_FILTER();
store_result4(result, tex2DGrad<float4>(tex.filtered_object, u, v, coord->dx, coord->dy));
}
// Implementation of tex::lookup_float3() for a texture_2d texture.
extern "C" __device__ void tex_lookup_float3_2d(
float result[3],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[2],
Tex_wrap_mode const wrap_u,
Tex_wrap_mode const wrap_v,
float const crop_u[2],
float const crop_v[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result3(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord[0], v = coord[1];
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3);
APPLY_SMOOTHERSTEP_FILTER();
store_result3(result, tex2D<float4>(tex.filtered_object, u, v));
}
// Implementation of tex::lookup_float3() for a texture_2d texture.
extern "C" __device__ void tex_lookup_deriv_float3_2d(
float result[3],
Texture_handler_base const *self_base,
unsigned texture_idx,
tct_deriv_float2 const *coord,
Tex_wrap_mode const wrap_u,
Tex_wrap_mode const wrap_v,
float const crop_u[2],
float const crop_v[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result3(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord->val.x, v = coord->val.y;
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3);
APPLY_SMOOTHERSTEP_FILTER();
store_result3(result, tex2DGrad<float4>(tex.filtered_object, u, v, coord->dx, coord->dy));
}
// Implementation of tex::texel_float4() for a texture_2d texture.
// Note: uvtile and/or animated textures are not supported
extern "C" __device__ void tex_texel_float4_2d(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
int const coord[2],
int const /*uv_tile*/[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
store_result4(result, tex2D<float4>(
tex.unfiltered_object,
float(coord[0]) * tex.inv_size.x,
float(coord[1]) * tex.inv_size.y));
}
// Implementation of tex::lookup_float4() for a texture_3d texture.
extern "C" __device__ void tex_lookup_float4_3d(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[3],
Tex_wrap_mode wrap_u,
Tex_wrap_mode wrap_v,
Tex_wrap_mode wrap_w,
float const crop_u[2],
float const crop_v[2],
float const crop_w[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord[0], v = coord[1], w = coord[2];
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result4);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result4);
WRAP_AND_CROP_OR_RETURN_BLACK(w, tex.inv_size.z, wrap_w, crop_w, store_result4);
store_result4(result, tex3D<float4>(tex.filtered_object, u, v, w));
}
// Implementation of tex::lookup_float3() for a texture_3d texture.
extern "C" __device__ void tex_lookup_float3_3d(
float result[3],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[3],
Tex_wrap_mode wrap_u,
Tex_wrap_mode wrap_v,
Tex_wrap_mode wrap_w,
float const crop_u[2],
float const crop_v[2],
float const crop_w[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result3(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
float u = coord[0], v = coord[1], w = coord[2];
WRAP_AND_CROP_OR_RETURN_BLACK(u, tex.inv_size.x, wrap_u, crop_u, store_result3);
WRAP_AND_CROP_OR_RETURN_BLACK(v, tex.inv_size.y, wrap_v, crop_v, store_result3);
WRAP_AND_CROP_OR_RETURN_BLACK(w, tex.inv_size.z, wrap_w, crop_w, store_result3);
store_result3(result, tex3D<float4>(tex.filtered_object, u, v, w));
}
// Implementation of tex::texel_float4() for a texture_3d texture.
extern "C" __device__ void tex_texel_float4_3d(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
const int coord[3],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
store_result4(result, tex3D<float4>(
tex.unfiltered_object,
float(coord[0]) * tex.inv_size.x,
float(coord[1]) * tex.inv_size.y,
float(coord[2]) * tex.inv_size.z));
}
// Implementation of tex::lookup_float4() for a texture_cube texture.
extern "C" __device__ void tex_lookup_float4_cube(
float result[4],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[3])
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result4(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
store_result4(result, texCubemap<float4>(tex.filtered_object, coord[0], coord[1], coord[2]));
}
// Implementation of tex::lookup_float3() for a texture_cube texture.
extern "C" __device__ void tex_lookup_float3_cube(
float result[3],
Texture_handler_base const *self_base,
unsigned texture_idx,
float const coord[3])
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
store_result3(result, 0.0f);
return;
}
Texture const &tex = self->textures[texture_idx - 1];
store_result3(result, texCubemap<float4>(tex.filtered_object, coord[0], coord[1], coord[2]));
}
// Implementation of resolution_2d function needed by generated code.
// Note: uvtile and/or animated textures are not supported
extern "C" __device__ void tex_resolution_2d(
int result[2],
Texture_handler_base const *self_base,
unsigned texture_idx,
int const /*uv_tile*/[2],
float /*frame*/)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if ( texture_idx == 0 || texture_idx - 1 >= self->num_textures ) {
// invalid texture returns zero
result[0] = 0;
result[1] = 0;
return;
}
Texture const &tex = self->textures[texture_idx - 1];
result[0] = tex.size.x;
result[1] = tex.size.y;
}
// Implementation of resolution_3d function needed by generated code.
extern "C" __device__ void tex_resolution_3d(
int result[3],
Texture_handler_base const *self_base,
unsigned texture_idx,
float /*frame*/)
{
Texture_handler const* self = static_cast<Texture_handler const*>(self_base);
if (texture_idx == 0 || texture_idx - 1 >= self->num_textures) {
// invalid texture returns zero
result[0] = 0;
result[1] = 0;
result[2] = 0;
}
Texture const& tex = self->textures[texture_idx - 1];
result[0] = tex.size.x;
result[1] = tex.size.y;
result[2] = tex.size.z;
}
// Implementation of texture_isvalid().
extern "C" __device__ bool tex_texture_isvalid(
Texture_handler_base const *self_base,
unsigned texture_idx)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
return texture_idx != 0 && texture_idx - 1 < self->num_textures;
}
// Implementation of frame function needed by generated code.
extern "C" __device__ void tex_frame(
int result[2],
Texture_handler_base const *self_base,
unsigned texture_idx)
{
Texture_handler const* self = static_cast<Texture_handler const*>(self_base);
if (texture_idx == 0 || texture_idx - 1 >= self->num_textures) {
// invalid texture returns zero
result[0] = 0;
result[1] = 0;
}
// Texture const& tex = self->textures[texture_idx - 1];
result[0] = 0;
result[1] = 0;
}
// ------------------------------------------------------------------------------------------------
// Light Profiles
// ------------------------------------------------------------------------------------------------
// Implementation of light_profile_power() for a light profile.
extern "C" __device__ float df_light_profile_power(
Texture_handler_base const *self_base,
unsigned light_profile_idx)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles)
return 0.0f; // invalid light profile returns zero
const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1];
return lp.total_power;
}
// Implementation of light_profile_maximum() for a light profile.
extern "C" __device__ float df_light_profile_maximum(
Texture_handler_base const *self_base,
unsigned light_profile_idx)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles)
return 0.0f; // invalid light profile returns zero
const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1];
return lp.candela_multiplier;
}
// Implementation of light_profile_isvalid() for a light profile.
extern "C" __device__ bool df_light_profile_isvalid(
Texture_handler_base const *self_base,
unsigned light_profile_idx)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
return light_profile_idx != 0 && light_profile_idx - 1 < self->num_lightprofiles;
}
// binary search through CDF
__device__ inline unsigned sample_cdf(
const float* cdf,
unsigned cdf_size,
float xi)
{
unsigned li = 0;
unsigned ri = cdf_size - 1;
unsigned m = (li + ri) / 2;
while (ri > li)
{
if (xi < cdf[m])
ri = m;
else
li = m + 1;
m = (li + ri) / 2;
}
return m;
}
// Implementation of df::light_profile_evaluate() for a light profile.
extern "C" __device__ float df_light_profile_evaluate(
Texture_handler_base const *self_base,
unsigned light_profile_idx,
float const theta_phi[2])
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles)
return 0.0f; // invalid light profile returns zero
const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1];
// map theta to 0..1 range
float u = (theta_phi[0] - lp.theta_phi_start.x) *
lp.theta_phi_inv_delta.x * lp.inv_angular_resolution.x;
// converting input phi from -pi..pi to 0..2pi
float phi = (theta_phi[1] > 0.0f) ? theta_phi[1] : (float(2.0 * M_PI) + theta_phi[1]);
// floorf wraps phi range into 0..2pi
phi = phi - lp.theta_phi_start.y -
floorf((phi - lp.theta_phi_start.y) * float(0.5 / M_PI)) * float(2.0 * M_PI);
// (phi < 0.0f) is no problem, this is handle by the (black) border
// since it implies lp.theta_phi_start.y > 0 (and we really have "no data" below that)
float v = phi * lp.theta_phi_inv_delta.y * lp.inv_angular_resolution.y;
// half pixel offset
// see https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#linear-filtering
u += 0.5f * lp.inv_angular_resolution.x;
v += 0.5f * lp.inv_angular_resolution.y;
// wrap_mode: border black would be an alternative (but it produces artifacts at low res)
if (u < 0.0f || u > 1.0f || v < 0.0f || v > 1.0f) return 0.0f;
return tex2D<float>(lp.eval_data, u, v) * lp.candela_multiplier;
}
// Implementation of df::light_profile_sample() for a light profile.
extern "C" __device__ void df_light_profile_sample(
float result[3], // output: theta, phi, pdf
Texture_handler_base const *self_base,
unsigned light_profile_idx,
float const xi[3]) // uniform random values
{
result[0] = -1.0f; // negative theta means no emission
result[1] = -1.0f;
result[2] = 0.0f;
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles)
return; // invalid light profile returns zero
const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1];
uint2 res = lp.angular_resolution;
// sample theta_out
//-------------------------------------------
float xi0 = xi[0];
const float* cdf_data_theta = lp.cdf_data; // CDF theta
unsigned idx_theta = sample_cdf(cdf_data_theta, res.x - 1, xi0); // binary search
float prob_theta = cdf_data_theta[idx_theta];
if (idx_theta > 0)
{
const float tmp = cdf_data_theta[idx_theta - 1];
prob_theta -= tmp;
xi0 -= tmp;
}
xi0 /= prob_theta; // rescale for re-usage
// sample phi_out
//-------------------------------------------
float xi1 = xi[1];
const float* cdf_data_phi = cdf_data_theta + (res.x - 1) // CDF theta block
+ (idx_theta * (res.y - 1)); // selected CDF for phi
const unsigned idx_phi = sample_cdf(cdf_data_phi, res.y - 1, xi1); // binary search
float prob_phi = cdf_data_phi[idx_phi];
if (idx_phi > 0)
{
const float tmp = cdf_data_phi[idx_phi - 1];
prob_phi -= tmp;
xi1 -= tmp;
}
xi1 /= prob_phi; // rescale for re-usage
// compute theta and phi
//-------------------------------------------
// sample uniformly within the patch (grid cell)
const float2 start = lp.theta_phi_start;
const float2 delta = lp.theta_phi_delta;
const float cos_theta_0 = cosf(start.x + float(idx_theta) * delta.x);
const float cos_theta_1 = cosf(start.x + float(idx_theta + 1u) * delta.x);
// n = \int_{\theta_0}^{\theta_1} \sin{\theta} \delta \theta
// = 1 / (\cos{\theta_0} - \cos{\theta_1})
//
// \xi = n * \int_{\theta_0}^{\theta_1} \sin{\theta} \delta \theta
// => \cos{\theta} = (1 - \xi) \cos{\theta_0} + \xi \cos{\theta_1}
const float cos_theta = (1.0f - xi1) * cos_theta_0 + xi1 * cos_theta_1;
result[0] = acosf(cos_theta);
result[1] = start.y + (float(idx_phi) + xi0) * delta.y;
// align phi
if (result[1] > float(2.0 * M_PI)) result[1] -= float(2.0 * M_PI); // wrap
if (result[1] > float(1.0 * M_PI)) result[1] = float(-2.0 * M_PI) + result[1]; // to [-pi, pi]
// compute pdf
//-------------------------------------------
result[2] = prob_theta * prob_phi / (delta.y * (cos_theta_0 - cos_theta_1));
}
// Implementation of df::light_profile_pdf() for a light profile.
extern "C" __device__ float df_light_profile_pdf(
Texture_handler_base const *self_base,
unsigned light_profile_idx,
float const theta_phi[2])
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (light_profile_idx == 0 || light_profile_idx - 1 >= self->num_lightprofiles)
return 0.0f; // invalid light profile returns zero
const Lightprofile& lp = self->lightprofiles[light_profile_idx - 1];
// CDF data
const uint2 res = lp.angular_resolution;
const float* cdf_data_theta = lp.cdf_data;
// map theta to 0..1 range
const float theta = theta_phi[0] - lp.theta_phi_start.x;
const int idx_theta = int(theta * lp.theta_phi_inv_delta.x);
// converting input phi from -pi..pi to 0..2pi
float phi = (theta_phi[1] > 0.0f) ? theta_phi[1] : (float(2.0 * M_PI) + theta_phi[1]);
// floorf wraps phi range into 0..2pi
phi = phi - lp.theta_phi_start.y -
floorf((phi - lp.theta_phi_start.y) * float(0.5 / M_PI)) * float(2.0 * M_PI);
// (phi < 0.0f) is no problem, this is handle by the (black) border
// since it implies lp.theta_phi_start.y > 0 (and we really have "no data" below that)
const int idx_phi = int(phi * lp.theta_phi_inv_delta.y);
// wrap_mode: border black would be an alternative (but it produces artifacts at low res)
if (idx_theta < 0 || idx_theta > (res.x - 2) || idx_phi < 0 || idx_phi >(res.x - 2))
return 0.0f;
// get probability for theta
//-------------------------------------------
float prob_theta = cdf_data_theta[idx_theta];
if (idx_theta > 0)
{
const float tmp = cdf_data_theta[idx_theta - 1];
prob_theta -= tmp;
}
// get probability for phi
//-------------------------------------------
const float* cdf_data_phi = cdf_data_theta
+ (res.x - 1) // CDF theta block
+ (idx_theta * (res.y - 1)); // selected CDF for phi
float prob_phi = cdf_data_phi[idx_phi];
if (idx_phi > 0)
{
const float tmp = cdf_data_phi[idx_phi - 1];
prob_phi -= tmp;
}
// compute probability to select a position in the sphere patch
const float2 start = lp.theta_phi_start;
const float2 delta = lp.theta_phi_delta;
const float cos_theta_0 = cos(start.x + float(idx_theta) * delta.x);
const float cos_theta_1 = cos(start.x + float(idx_theta + 1u) * delta.x);
return prob_theta * prob_phi / (delta.y * (cos_theta_0 - cos_theta_1));
}
// ------------------------------------------------------------------------------------------------
// BSDF Measurements
// ------------------------------------------------------------------------------------------------
// Implementation of bsdf_measurement_isvalid() for an MBSDF.
extern "C" __device__ bool df_bsdf_measurement_isvalid(
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
return bsdf_measurement_index != 0 && bsdf_measurement_index - 1 < self->num_mbsdfs;
}
// Implementation of df::bsdf_measurement_resolution() function needed by generated code,
// which retrieves the angular and chromatic resolution of the given MBSDF.
// The returned triple consists of: number of equi-spaced steps of theta_i and theta_o,
// number of equi-spaced steps of phi, and number of color channels (1 or 3).
extern "C" __device__ void df_bsdf_measurement_resolution(
unsigned result[3],
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index,
Mbsdf_part part)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs)
{
// invalid MBSDF returns zero
result[0] = 0;
result[1] = 0;
result[2] = 0;
return;
}
Mbsdf const &bm = self->mbsdfs[bsdf_measurement_index - 1];
const unsigned part_index = static_cast<unsigned>(part);
// check for the part
if (bm.has_data[part_index] == 0)
{
result[0] = 0;
result[1] = 0;
result[2] = 0;
return;
}
// pass out the information
result[0] = bm.angular_resolution[part_index].x;
result[1] = bm.angular_resolution[part_index].y;
result[2] = bm.num_channels[part_index];
}
__device__ inline float3 bsdf_compute_uvw(const float theta_phi_in[2],
const float theta_phi_out[2])
{
// assuming each phi is between -pi and pi
float u = theta_phi_out[1] - theta_phi_in[1];
if (u < 0.0) u += float(2.0 * M_PI);
if (u > float(1.0 * M_PI)) u = float(2.0 * M_PI) - u;
u *= M_ONE_OVER_PI;
const float v = theta_phi_out[0] * float(2.0 / M_PI);
const float w = theta_phi_in[0] * float(2.0 / M_PI);
return make_float3(u, v, w);
}
template<typename T>
__device__ inline T bsdf_measurement_lookup(const cudaTextureObject_t& eval_volume,
const float theta_phi_in[2],
const float theta_phi_out[2])
{
// 3D volume on the GPU (phi_delta x theta_out x theta_in)
const float3 uvw = bsdf_compute_uvw(theta_phi_in, theta_phi_out);
return tex3D<T>(eval_volume, uvw.x, uvw.y, uvw.z);
}
// Implementation of df::bsdf_measurement_evaluate() for an MBSDF.
extern "C" __device__ void df_bsdf_measurement_evaluate(
float result[3],
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index,
float const theta_phi_in[2],
float const theta_phi_out[2],
Mbsdf_part part)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs)
{
// invalid MBSDF returns zero
store_result3(result, 0.0f);
return;
}
const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1];
const unsigned part_index = static_cast<unsigned>(part);
// check for the parta
if (bm.has_data[part_index] == 0)
{
store_result3(result, 0.0f);
return;
}
// handle channels
if (bm.num_channels[part_index] == 3)
{
const float4 sample = bsdf_measurement_lookup<float4>(
bm.eval_data[part_index], theta_phi_in, theta_phi_out);
store_result3(result, sample.x, sample.y, sample.z);
}
else
{
const float sample = bsdf_measurement_lookup<float>(
bm.eval_data[part_index], theta_phi_in, theta_phi_out);
store_result3(result, sample);
}
}
// Implementation of df::bsdf_measurement_sample() for an MBSDF.
extern "C" __device__ void df_bsdf_measurement_sample(
float result[3], // output: theta, phi, pdf
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index,
float const theta_phi_out[2],
float const xi[3], // uniform random values
Mbsdf_part part)
{
result[0] = -1.0f; // negative theta means absorption
result[1] = -1.0f;
result[2] = 0.0f;
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs)
return; // invalid MBSDFs returns zero
const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1];
unsigned part_index = static_cast<unsigned>(part);
if (bm.has_data[part_index] == 0)
return; // check for the part
// CDF data
uint2 res = bm.angular_resolution[part_index];
const float* sample_data = bm.sample_data[part_index];
// compute the theta_in index (flipping input and output, BSDFs are symmetric)
unsigned idx_theta_in = unsigned(theta_phi_out[0] * M_ONE_OVER_PI * 2.0f * float(res.x));
idx_theta_in = min(idx_theta_in, res.x - 1);
// sample theta_out
//-------------------------------------------
float xi0 = xi[0];
const float* cdf_theta = sample_data + idx_theta_in * res.x;
unsigned idx_theta_out = sample_cdf(cdf_theta, res.x, xi0); // binary search
float prob_theta = cdf_theta[idx_theta_out];
if (idx_theta_out > 0)
{
const float tmp = cdf_theta[idx_theta_out - 1];
prob_theta -= tmp;
xi0 -= tmp;
}
xi0 /= prob_theta; // rescale for re-usage
// sample phi_out
//-------------------------------------------
float xi1 = xi[1];
const float* cdf_phi = sample_data +
(res.x * res.x) + // CDF theta block
(idx_theta_in * res.x + idx_theta_out) * res.y; // selected CDF phi
// select which half-circle to choose with probability 0.5
const bool flip = (xi1 > 0.5f);
if (flip)
xi1 = 1.0f - xi1;
xi1 *= 2.0f;
unsigned idx_phi_out = sample_cdf(cdf_phi, res.y, xi1); // binary search
float prob_phi = cdf_phi[idx_phi_out];
if (idx_phi_out > 0)
{
const float tmp = cdf_phi[idx_phi_out - 1];
prob_phi -= tmp;
xi1 -= tmp;
}
xi1 /= prob_phi; // rescale for re-usage
// compute theta and phi out
//-------------------------------------------
const float2 inv_res = bm.inv_angular_resolution[part_index];
const float s_theta = float(0.5 * M_PI) * inv_res.x;
const float s_phi = float(1.0 * M_PI) * inv_res.y;
const float cos_theta_0 = cosf(float(idx_theta_out) * s_theta);
const float cos_theta_1 = cosf(float(idx_theta_out + 1u) * s_theta);
const float cos_theta = cos_theta_0 * (1.0f - xi1) + cos_theta_1 * xi1;
result[0] = acosf(cos_theta);
result[1] = (float(idx_phi_out) + xi0) * s_phi;
if (flip)
result[1] = float(2.0 * M_PI) - result[1]; // phi \in [0, 2pi]
// align phi
result[1] += (theta_phi_out[1] > 0) ? theta_phi_out[1] : (float(2.0 * M_PI) + theta_phi_out[1]);
if (result[1] > float(2.0 * M_PI)) result[1] -= float(2.0 * M_PI);
if (result[1] > float(1.0 * M_PI)) result[1] = float(-2.0 * M_PI) + result[1]; // to [-pi, pi]
// compute pdf
//-------------------------------------------
result[2] = prob_theta * prob_phi * 0.5f
/ (s_phi * (cos_theta_0 - cos_theta_1));
}
// Implementation of df::bsdf_measurement_pdf() for an MBSDF.
extern "C" __device__ float df_bsdf_measurement_pdf(
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index,
float const theta_phi_in[2],
float const theta_phi_out[2],
Mbsdf_part part)
{
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs)
return 0.0f; // invalid MBSDF returns zero
const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1];
unsigned part_index = static_cast<unsigned>(part);
// check for the part
if (bm.has_data[part_index] == 0)
return 0.0f;
// CDF data and resolution
const float* sample_data = bm.sample_data[part_index];
uint2 res = bm.angular_resolution[part_index];
// compute indices in the CDF data
float3 uvw = bsdf_compute_uvw(theta_phi_in, theta_phi_out); // phi_delta, theta_out, theta_in
unsigned idx_theta_in = unsigned(theta_phi_in[0] * M_ONE_OVER_PI * 2.0f * float(res.x));
unsigned idx_theta_out = unsigned(theta_phi_out[0] * M_ONE_OVER_PI * 2.0f * float(res.x));
unsigned idx_phi_out = unsigned(uvw.x * float(res.y));
idx_theta_in = min(idx_theta_in, res.x - 1);
idx_theta_out = min(idx_theta_out, res.x - 1);
idx_phi_out = min(idx_phi_out, res.y - 1);
// get probability to select theta_out
const float* cdf_theta = sample_data + idx_theta_in * res.x;
float prob_theta = cdf_theta[idx_theta_out];
if (idx_theta_out > 0)
{
const float tmp = cdf_theta[idx_theta_out - 1];
prob_theta -= tmp;
}
// get probability to select phi_out
const float* cdf_phi = sample_data +
(res.x * res.x) + // CDF theta block
(idx_theta_in * res.x + idx_theta_out) * res.y; // selected CDF phi
float prob_phi = cdf_phi[idx_phi_out];
if (idx_phi_out > 0)
{
const float tmp = cdf_phi[idx_phi_out - 1];
prob_phi -= tmp;
}
// compute probability to select a position in the sphere patch
float2 inv_res = bm.inv_angular_resolution[part_index];
const float s_theta = float(0.5 * M_PI) * inv_res.x;
const float s_phi = float(1.0 * M_PI) * inv_res.y;
const float cos_theta_0 = cosf(float(idx_theta_out) * s_theta);
const float cos_theta_1 = cosf(float(idx_theta_out + 1u) * s_theta);
return prob_theta * prob_phi * 0.5f
/ (s_phi * (cos_theta_0 - cos_theta_1));
}
__device__ inline void df_bsdf_measurement_albedo(
float result[2], // output: max (in case of color) albedo
// for the selected direction ([0]) and
// global ([1])
Texture_handler const *self,
unsigned bsdf_measurement_index,
float const theta_phi[2],
Mbsdf_part part)
{
const Mbsdf& bm = self->mbsdfs[bsdf_measurement_index - 1];
const unsigned part_index = static_cast<unsigned>(part);
// check for the part
if (bm.has_data[part_index] == 0)
return;
const uint2 res = bm.angular_resolution[part_index];
unsigned idx_theta = unsigned(theta_phi[0] * float(2.0 / M_PI) * float(res.x));
idx_theta = min(idx_theta, res.x - 1u);
result[0] = bm.albedo_data[part_index][idx_theta];
result[1] = bm.max_albedo[part_index];
}
// Implementation of df::bsdf_measurement_albedos() for an MBSDF.
extern "C" __device__ void df_bsdf_measurement_albedos(
float result[4], // output: [0] albedo refl. for theta_phi
// [1] max albedo refl. global
// [2] albedo trans. for theta_phi
// [3] max albedo trans. global
Texture_handler_base const *self_base,
unsigned bsdf_measurement_index,
float const theta_phi[2])
{
result[0] = 0.0f;
result[1] = 0.0f;
result[2] = 0.0f;
result[3] = 0.0f;
Texture_handler const *self = static_cast<Texture_handler const *>(self_base);
if (bsdf_measurement_index == 0 || bsdf_measurement_index - 1 >= self->num_mbsdfs)
return; // invalid MBSDF returns zero
df_bsdf_measurement_albedo(
&result[0],
self,
bsdf_measurement_index,
theta_phi,
mi::neuraylib::MBSDF_DATA_REFLECTION);
df_bsdf_measurement_albedo(
&result[2],
self,
bsdf_measurement_index,
theta_phi,
mi::neuraylib::MBSDF_DATA_TRANSMISSION);
}
// ------------------------------------------------------------------------------------------------
// Normal adaption (dummy functions)
//
// Can be enabled via backend option "use_renderer_adapt_normal".
// ------------------------------------------------------------------------------------------------
#ifndef TEX_SUPPORT_NO_DUMMY_ADAPTNORMAL
// Implementation of adapt_normal().
extern "C" __device__ void adapt_normal(
float result[3],
Texture_handler_base const *self_base,
Shading_state_material *state,
float const normal[3])
{
// just return original normal
result[0] = normal[0];
result[1] = normal[1];
result[2] = normal[2];
}
#endif // TEX_SUPPORT_NO_DUMMY_ADAPTNORMAL
// ------------------------------------------------------------------------------------------------
// Scene data (dummy functions)
// ------------------------------------------------------------------------------------------------
#ifndef TEX_SUPPORT_NO_DUMMY_SCENEDATA
// Implementation of scene_data_isvalid().
extern "C" __device__ bool scene_data_isvalid(
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id)
{
return false;
}
// Implementation of scene_data_lookup_float4().
extern "C" __device__ void scene_data_lookup_float4(
float result[4],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
float const default_value[4],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
result[2] = default_value[2];
result[3] = default_value[3];
}
// Implementation of scene_data_lookup_float3().
extern "C" __device__ void scene_data_lookup_float3(
float result[3],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
float const default_value[3],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
result[2] = default_value[2];
}
// Implementation of scene_data_lookup_color().
extern "C" __device__ void scene_data_lookup_color(
float result[3],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
float const default_value[3],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
result[2] = default_value[2];
}
// Implementation of scene_data_lookup_float2().
extern "C" __device__ void scene_data_lookup_float2(
float result[2],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
float const default_value[2],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
}
// Implementation of scene_data_lookup_float().
extern "C" __device__ float scene_data_lookup_float(
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
float const default_value,
bool uniform_lookup)
{
// just return default value
return default_value;
}
// Implementation of scene_data_lookup_int4().
extern "C" __device__ void scene_data_lookup_int4(
int result[4],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
int const default_value[4],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
result[2] = default_value[2];
result[3] = default_value[3];
}
// Implementation of scene_data_lookup_int3().
extern "C" __device__ void scene_data_lookup_int3(
int result[3],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
int const default_value[3],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
result[2] = default_value[2];
}
// Implementation of scene_data_lookup_int2().
extern "C" __device__ void scene_data_lookup_int2(
int result[2],
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
int const default_value[2],
bool uniform_lookup)
{
// just return default value
result[0] = default_value[0];
result[1] = default_value[1];
}
// Implementation of scene_data_lookup_int().
extern "C" __device__ int scene_data_lookup_int(
Texture_handler_base const *self_base,
Shading_state_material *state,
unsigned scene_data_id,
int default_value,
bool uniform_lookup)
{
// just return default value
return default_value;
}
// Implementation of scene_data_lookup_float4() with derivatives.
extern "C" __device__ void scene_data_lookup_deriv_float4(
tct_deriv_arr_float_4 *result,
Texture_handler_base const *self_base,
Shading_state_material_with_derivs *state,
unsigned scene_data_id,
tct_deriv_arr_float_4 const *default_value,
bool uniform_lookup)
{
// just return default value
*result = *default_value;
}
// Implementation of scene_data_lookup_float3() with derivatives.
extern "C" __device__ void scene_data_lookup_deriv_float3(
tct_deriv_arr_float_3 *result,
Texture_handler_base const *self_base,
Shading_state_material_with_derivs *state,
unsigned scene_data_id,
tct_deriv_arr_float_3 const *default_value,
bool uniform_lookup)
{
// just return default value
*result = *default_value;
}
// Implementation of scene_data_lookup_color() with derivatives.
extern "C" __device__ void scene_data_lookup_deriv_color(
tct_deriv_arr_float_3 *result,
Texture_handler_base const *self_base,
Shading_state_material_with_derivs *state,
unsigned scene_data_id,
tct_deriv_arr_float_3 const *default_value,
bool uniform_lookup)
{
// just return default value
*result = *default_value;
}
// Implementation of scene_data_lookup_float2() with derivatives.
extern "C" __device__ void scene_data_lookup_deriv_float2(
tct_deriv_arr_float_2 *result,
Texture_handler_base const *self_base,
Shading_state_material_with_derivs *state,
unsigned scene_data_id,
tct_deriv_arr_float_2 const *default_value,
bool uniform_lookup)
{
// just return default value
*result = *default_value;
}
// Implementation of scene_data_lookup_float() with derivatives.
extern "C" __device__ void scene_data_lookup_deriv_float(
tct_deriv_float *result,
Texture_handler_base const *self_base,
Shading_state_material_with_derivs *state,
unsigned scene_data_id,
tct_deriv_float const *default_value,
bool uniform_lookup)
{
// just return default value
*result = *default_value;
}
#endif // TEX_SUPPORT_NO_DUMMY_SCENEDATA
// ------------------------------------------------------------------------------------------------
// Vtables
// ------------------------------------------------------------------------------------------------
#ifndef TEX_SUPPORT_NO_VTABLES
// The vtable containing all texture access handlers required by the generated code
// in "vtable" mode.
__device__ mi::neuraylib::Texture_handler_vtable tex_vtable = {
tex_lookup_float4_2d,
tex_lookup_float3_2d,
tex_texel_float4_2d,
tex_lookup_float4_3d,
tex_lookup_float3_3d,
tex_texel_float4_3d,
tex_lookup_float4_cube,
tex_lookup_float3_cube,
tex_resolution_2d,
tex_resolution_3d,
tex_texture_isvalid,
tex_frame,
df_light_profile_power,
df_light_profile_maximum,
df_light_profile_isvalid,
df_light_profile_evaluate,
df_light_profile_sample,
df_light_profile_pdf,
df_bsdf_measurement_isvalid,
df_bsdf_measurement_resolution,
df_bsdf_measurement_evaluate,
df_bsdf_measurement_sample,
df_bsdf_measurement_pdf,
df_bsdf_measurement_albedos,
adapt_normal,
scene_data_isvalid,
scene_data_lookup_float,
scene_data_lookup_float2,
scene_data_lookup_float3,
scene_data_lookup_float4,
scene_data_lookup_int,
scene_data_lookup_int2,
scene_data_lookup_int3,
scene_data_lookup_int4,
scene_data_lookup_color,
};
// The vtable containing all texture access handlers required by the generated code
// in "vtable" mode with derivatives.
__device__ mi::neuraylib::Texture_handler_deriv_vtable tex_deriv_vtable = {
tex_lookup_deriv_float4_2d,
tex_lookup_deriv_float3_2d,
tex_texel_float4_2d,
tex_lookup_float4_3d,
tex_lookup_float3_3d,
tex_texel_float4_3d,
tex_lookup_float4_cube,
tex_lookup_float3_cube,
tex_resolution_2d,
tex_resolution_3d,
tex_texture_isvalid,
tex_frame,
df_light_profile_power,
df_light_profile_maximum,
df_light_profile_isvalid,
df_light_profile_evaluate,
df_light_profile_sample,
df_light_profile_pdf,
df_bsdf_measurement_isvalid,
df_bsdf_measurement_resolution,
df_bsdf_measurement_evaluate,
df_bsdf_measurement_sample,
df_bsdf_measurement_pdf,
df_bsdf_measurement_albedos,
adapt_normal,
scene_data_isvalid,
scene_data_lookup_float,
scene_data_lookup_float2,
scene_data_lookup_float3,
scene_data_lookup_float4,
scene_data_lookup_int,
scene_data_lookup_int2,
scene_data_lookup_int3,
scene_data_lookup_int4,
scene_data_lookup_color,
scene_data_lookup_deriv_float,
scene_data_lookup_deriv_float2,
scene_data_lookup_deriv_float3,
scene_data_lookup_deriv_float4,
scene_data_lookup_deriv_color,
};
#endif // TEX_SUPPORT_NO_VTABLES
#endif // __CUDACC__
#endif // TEXTURE_SUPPORT_CUDA_H
|
arhix52/Strelka/src/render/optix/OptixRender.h | #pragma once
#include "render.h"
#include <optix.h>
#include "OptixRenderParams.h"
#include <iostream>
#include <iomanip>
#include <scene/scene.h>
#include "common.h"
#include "buffer.h"
#include <materialmanager.h>
struct Texture;
namespace oka
{
enum RayType
{
RAY_TYPE_RADIANCE = 0,
RAY_TYPE_OCCLUSION = 1,
RAY_TYPE_COUNT
};
struct PathTracerState
{
OptixDeviceContext context = 0;
OptixTraversableHandle ias_handle;
CUdeviceptr d_instances = 0;
OptixTraversableHandle gas_handle = 0; // Traversable handle for triangle AS
CUdeviceptr d_gas_output_buffer = 0; // Triangle AS memory
CUdeviceptr d_vertices = 0;
OptixModuleCompileOptions module_compile_options = {};
OptixModule ptx_module = 0;
OptixPipelineCompileOptions pipeline_compile_options = {};
OptixPipeline pipeline = 0;
OptixModule m_catromCurveModule = 0;
OptixProgramGroup raygen_prog_group = 0;
OptixProgramGroup radiance_miss_group = 0;
OptixProgramGroup occlusion_miss_group = 0;
OptixProgramGroup radiance_default_hit_group = 0;
std::vector<OptixProgramGroup> radiance_hit_groups;
OptixProgramGroup occlusion_hit_group = 0;
OptixProgramGroup light_hit_group = 0;
CUstream stream = 0;
Params params = {};
Params prevParams = {};
CUdeviceptr d_params = 0;
OptixShaderBindingTable sbt = {};
};
class OptiXRender : public Render
{
private:
struct Mesh
{
OptixTraversableHandle gas_handle = 0;
CUdeviceptr d_gas_output_buffer = 0;
};
struct Curve
{
OptixTraversableHandle gas_handle = 0;
CUdeviceptr d_gas_output_buffer = 0;
};
struct Instance
{
OptixInstance instance;
};
// optix material
struct Material
{
OptixProgramGroup programGroup;
CUdeviceptr d_argData = 0;
size_t d_argDataSize = 0;
CUdeviceptr d_roData = 0;
size_t d_roSize = 0;
CUdeviceptr d_textureHandler;
};
struct View
{
oka::Camera::Matrices mCamMatrices;
};
View mPrevView;
PathTracerState mState;
bool mEnableValidation;
Mesh* createMesh(const oka::Mesh& mesh);
Curve* createCurve(const oka::Curve& curve);
bool compactAccel(CUdeviceptr& buffer, OptixTraversableHandle& handle, CUdeviceptr result, size_t outputSizeInBytes);
std::vector<Mesh*> mOptixMeshes;
std::vector<Curve*> mOptixCurves;
CUdeviceptr d_vb = 0;
CUdeviceptr d_ib = 0;
CUdeviceptr d_lights = 0;
CUdeviceptr d_points = 0;
CUdeviceptr d_widths = 0;
CUdeviceptr d_materialRoData = 0;
CUdeviceptr d_materialArgData = 0;
CUdeviceptr d_texturesHandler = 0;
CUdeviceptr d_texturesData = 0;
CUdeviceptr d_param = 0;
void createVertexBuffer();
void createIndexBuffer();
// curve utils
void createPointsBuffer();
void createWidthsBuffer();
void createLightBuffer();
Texture loadTextureFromFile(const std::string& fileName);
bool createOptixMaterials();
Material& getMaterial(int id);
MaterialManager mMaterialManager;
std::vector<Material> mMaterials;
void updatePathtracerParams(const uint32_t width, const uint32_t height);
public:
OptiXRender(/* args */);
~OptiXRender();
void init() override;
void render(Buffer* output_buffer) override;
Buffer* createBuffer(const BufferDesc& desc) override;
void createContext();
void createAccelerationStructure();
void createModule();
void createProgramGroups();
void createPipeline();
void createSbt();
OptixProgramGroup createRadianceClosestHitProgramGroup(PathTracerState& state,
char const* module_code,
size_t module_size);
};
} // namespace oka
|
arhix52/Strelka/src/render/optix/OptixBuffer.cpp | #include "OptixBuffer.h"
#include <cuda.h>
#include <cuda_runtime_api.h>
using namespace oka;
oka::OptixBuffer::OptixBuffer(void* devicePtr, BufferFormat format, uint32_t width, uint32_t height)
{
mDeviceData = devicePtr;
mFormat = format;
mWidth = width;
mHeight = height;
}
oka::OptixBuffer::~OptixBuffer()
{
// TODO:
if (mDeviceData)
{
cudaFree(mDeviceData);
}
}
void oka::OptixBuffer::resize(uint32_t width, uint32_t height)
{
if (mDeviceData)
{
cudaFree(mDeviceData);
}
mWidth = width;
mHeight = height;
const size_t bufferSize = mWidth * mHeight * getElementSize();
cudaMalloc(reinterpret_cast<void**>(&mDeviceData), bufferSize);
}
void* oka::OptixBuffer::map()
{
const size_t bufferSize = mWidth * mHeight * getElementSize();
mHostData.resize(bufferSize);
cudaMemcpy(static_cast<void*>(mHostData.data()), mDeviceData, bufferSize, cudaMemcpyDeviceToHost);
return nullptr;
}
void oka::OptixBuffer::unmap()
{
}
|
arhix52/Strelka/src/render/optix/OptixRender.cpp | #include "OptixRender.h"
#include "OptixBuffer.h"
#include <optix_function_table_definition.h>
#include <optix_stubs.h>
#include <optix_stack_size.h>
#include <glm/glm.hpp>
#include <glm/mat4x3.hpp>
#include <glm/gtx/compatibility.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/matrix_major_storage.hpp>
#include <glm/ext/matrix_relational.hpp>
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <vector_types.h>
#include <vector_functions.h>
#include <sutil/vec_math_adv.h>
#include "texture_support_cuda.h"
#include <filesystem>
#include <array>
#include <string>
#include <sstream>
#include <fstream>
#include <log.h>
#include "postprocessing/Tonemappers.h"
#include "Camera.h"
static void context_log_cb(unsigned int level, const char* tag, const char* message, void* /*cbdata */)
{
switch (level)
{
case 1:
STRELKA_FATAL("OptiX [{0}]: {1}", tag, message);
break;
case 2:
STRELKA_ERROR("OptiX [{0}]: {1}", tag, message);
break;
case 3:
STRELKA_WARNING("OptiX [{0}]: {1}", tag, message);
break;
case 4:
STRELKA_INFO("OptiX [{0}]: {1}", tag, message);
break;
default:
break;
}
}
static inline void optixCheck(OptixResult res, const char* call, const char* file, unsigned int line)
{
if (res != OPTIX_SUCCESS)
{
STRELKA_ERROR("OptiX call {0} failed: {1}:{2}", call, file, line);
assert(0);
}
}
static inline void optixCheckLog(OptixResult res,
const char* log,
size_t sizeof_log,
size_t sizeof_log_returned,
const char* call,
const char* file,
unsigned int line)
{
if (res != OPTIX_SUCCESS)
{
STRELKA_FATAL("OptiX call {0} failed: {1}:{2} : {3}", call, file, line, log);
assert(0);
}
}
inline void cudaCheck(cudaError_t error, const char* call, const char* file, unsigned int line)
{
if (error != cudaSuccess)
{
STRELKA_FATAL("CUDA call ({0}) failed with error: {1} {2}:{3}", call, cudaGetErrorString(error), file, line);
assert(0);
}
}
inline void cudaSyncCheck(const char* file, unsigned int line)
{
cudaDeviceSynchronize();
cudaError_t error = cudaGetLastError();
if (error != cudaSuccess)
{
STRELKA_FATAL("CUDA error on synchronize with error {0} , {1}:{2}", cudaGetErrorString(error), file, line);
assert(0);
}
}
//------------------------------------------------------------------------------
//
// OptiX error-checking
//
//------------------------------------------------------------------------------
#define OPTIX_CHECK(call) optixCheck(call, #call, __FILE__, __LINE__)
#define OPTIX_CHECK_LOG(call) optixCheckLog(call, log, sizeof(log), sizeof_log, #call, __FILE__, __LINE__)
#define CUDA_CHECK(call) cudaCheck(call, #call, __FILE__, __LINE__)
#define CUDA_SYNC_CHECK() cudaSyncCheck(__FILE__, __LINE__)
using namespace oka;
namespace fs = std::filesystem;
template <typename T>
struct SbtRecord
{
__align__(OPTIX_SBT_RECORD_ALIGNMENT) char header[OPTIX_SBT_RECORD_HEADER_SIZE];
T data;
};
typedef SbtRecord<RayGenData> RayGenSbtRecord;
typedef SbtRecord<MissData> MissSbtRecord;
typedef SbtRecord<HitGroupData> HitGroupSbtRecord;
void configureCamera(::Camera& cam, const uint32_t width, const uint32_t height)
{
cam.setEye({ 0.0f, 0.0f, 2.0f });
cam.setLookat({ 0.0f, 0.0f, 0.0f });
cam.setUp({ 0.0f, 1.0f, 3.0f });
cam.setFovY(45.0f);
cam.setAspectRatio((float)width / (float)height);
}
static bool readSourceFile(std::string& str, const fs::path& filename)
{
// Try to open file
std::ifstream file(filename.c_str(), std::ios::binary);
if (file.good())
{
// Found usable source file
std::vector<unsigned char> buffer = std::vector<unsigned char>(std::istreambuf_iterator<char>(file), {});
str.assign(buffer.begin(), buffer.end());
return true;
}
return false;
}
OptiXRender::OptiXRender(/* args */)
{
}
OptiXRender::~OptiXRender()
{
}
void OptiXRender::createContext()
{
// Initialize CUDA
CUDA_CHECK(cudaFree(0));
CUstream stream;
CUDA_CHECK(cudaStreamCreate(&stream));
mState.stream = stream;
OptixDeviceContext context;
CUcontext cu_ctx = 0; // zero means take the current context
OPTIX_CHECK(optixInit());
OptixDeviceContextOptions options = {};
options.logCallbackFunction = &context_log_cb;
options.logCallbackLevel = 4;
if (mEnableValidation)
{
options.validationMode = OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_ALL;
}
else
{
options.validationMode = OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_OFF;
}
OPTIX_CHECK(optixDeviceContextCreate(cu_ctx, &options, &context));
mState.context = context;
}
bool OptiXRender::compactAccel(CUdeviceptr& buffer,
OptixTraversableHandle& handle,
CUdeviceptr result,
size_t outputSizeInBytes)
{
bool flag = false;
size_t compacted_size;
CUDA_CHECK(cudaMemcpy(&compacted_size, (void*)result, sizeof(size_t), cudaMemcpyDeviceToHost));
CUdeviceptr compactedOutputBuffer;
if (compacted_size < outputSizeInBytes)
{
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&compactedOutputBuffer), compacted_size));
// use handle as input and output
OPTIX_CHECK(optixAccelCompact(mState.context, 0, handle, compactedOutputBuffer, compacted_size, &handle));
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(buffer)));
buffer = compactedOutputBuffer;
flag = true;
}
return flag;
}
OptiXRender::Curve* OptiXRender::createCurve(const oka::Curve& curve)
{
Curve* rcurve = new Curve();
OptixAccelBuildOptions accel_options = {};
accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_ALLOW_RANDOM_VERTEX_ACCESS |
OPTIX_BUILD_FLAG_PREFER_FAST_TRACE;
accel_options.operation = OPTIX_BUILD_OPERATION_BUILD;
const uint32_t pointsCount = mScene->getCurvesPoint().size(); // total points count in points buffer
const int degree = 3;
// each oka::Curves could contains many curves
const uint32_t numCurves = curve.mVertexCountsCount;
std::vector<int> segmentIndices;
uint32_t offsetInsideCurveArray = 0;
for (int curveIndex = 0; curveIndex < numCurves; ++curveIndex)
{
const std::vector<uint32_t>& vertexCounts = mScene->getCurvesVertexCounts();
const uint32_t numControlPoints = vertexCounts[curve.mVertexCountsStart + curveIndex];
const int segmentsCount = numControlPoints - degree;
for (int i = 0; i < segmentsCount; ++i)
{
int index = curve.mPointsStart + offsetInsideCurveArray + i;
segmentIndices.push_back(index);
}
offsetInsideCurveArray += numControlPoints;
}
const size_t segmentIndicesSize = sizeof(int) * segmentIndices.size();
CUdeviceptr d_segmentIndices = 0;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_segmentIndices), segmentIndicesSize));
CUDA_CHECK(cudaMemcpy(
reinterpret_cast<void*>(d_segmentIndices), segmentIndices.data(), segmentIndicesSize, cudaMemcpyHostToDevice));
// Curve build input.
OptixBuildInput curve_input = {};
curve_input.type = OPTIX_BUILD_INPUT_TYPE_CURVES;
switch (degree)
{
case 1:
curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_LINEAR;
break;
case 2:
curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_QUADRATIC_BSPLINE;
break;
case 3:
curve_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_CUBIC_BSPLINE;
break;
}
curve_input.curveArray.numPrimitives = segmentIndices.size();
curve_input.curveArray.vertexBuffers = &d_points;
curve_input.curveArray.numVertices = pointsCount;
curve_input.curveArray.vertexStrideInBytes = sizeof(glm::float3);
curve_input.curveArray.widthBuffers = &d_widths;
curve_input.curveArray.widthStrideInBytes = sizeof(float);
curve_input.curveArray.normalBuffers = 0;
curve_input.curveArray.normalStrideInBytes = 0;
curve_input.curveArray.indexBuffer = d_segmentIndices;
curve_input.curveArray.indexStrideInBytes = sizeof(int);
curve_input.curveArray.flag = OPTIX_GEOMETRY_FLAG_NONE;
curve_input.curveArray.primitiveIndexOffset = 0;
// curve_input.curveArray.endcapFlags = OPTIX_CURVE_ENDCAP_ON;
OptixAccelBufferSizes gas_buffer_sizes;
OPTIX_CHECK(optixAccelComputeMemoryUsage(mState.context, &accel_options, &curve_input,
1, // Number of build inputs
&gas_buffer_sizes));
CUdeviceptr d_temp_buffer_gas;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_temp_buffer_gas), gas_buffer_sizes.tempSizeInBytes));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&rcurve->d_gas_output_buffer), gas_buffer_sizes.outputSizeInBytes));
CUdeviceptr compactedSizeBuffer;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t)));
OptixAccelEmitDesc property = {};
property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE;
property.result = compactedSizeBuffer;
OPTIX_CHECK(optixAccelBuild(mState.context, 0, // CUDA stream
&accel_options, &curve_input,
1, // num build inputs
d_temp_buffer_gas, gas_buffer_sizes.tempSizeInBytes, rcurve->d_gas_output_buffer,
gas_buffer_sizes.outputSizeInBytes, &rcurve->gas_handle,
&property, // emitted property list
1)); // num emitted properties
compactAccel(rcurve->d_gas_output_buffer, rcurve->gas_handle, property.result, gas_buffer_sizes.outputSizeInBytes);
// We can now free the scratch space buffer used during build and the vertex
// inputs, since they are not needed by our trivial shading method
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_temp_buffer_gas)));
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_segmentIndices)));
return rcurve;
}
OptiXRender::Mesh* OptiXRender::createMesh(const oka::Mesh& mesh)
{
OptixTraversableHandle gas_handle;
CUdeviceptr d_gas_output_buffer;
{
// Use default options for simplicity. In a real use case we would want to
// enable compaction, etc
OptixAccelBuildOptions accel_options = {};
accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE;
accel_options.operation = OPTIX_BUILD_OPERATION_BUILD;
// std::vector<oka::Scene::Vertex>& vertices = mScene->getVertices();
// std::vector<uint32_t>& indices = mScene->getIndices();
const CUdeviceptr verticesDataStart = d_vb + mesh.mVbOffset * sizeof(oka::Scene::Vertex);
CUdeviceptr indicesDataStart = d_ib + mesh.mIndex * sizeof(uint32_t);
// Our build input is a simple list of non-indexed triangle vertices
const uint32_t triangle_input_flags[1] = { OPTIX_GEOMETRY_FLAG_NONE };
OptixBuildInput triangle_input = {};
triangle_input.type = OPTIX_BUILD_INPUT_TYPE_TRIANGLES;
triangle_input.triangleArray.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3;
triangle_input.triangleArray.numVertices = mesh.mVertexCount;
triangle_input.triangleArray.vertexBuffers = &verticesDataStart;
triangle_input.triangleArray.vertexStrideInBytes = sizeof(oka::Scene::Vertex);
triangle_input.triangleArray.indexBuffer = indicesDataStart;
triangle_input.triangleArray.indexFormat = OptixIndicesFormat::OPTIX_INDICES_FORMAT_UNSIGNED_INT3;
triangle_input.triangleArray.indexStrideInBytes = sizeof(uint32_t) * 3;
triangle_input.triangleArray.numIndexTriplets = mesh.mCount / 3;
// triangle_input.triangleArray.
triangle_input.triangleArray.flags = triangle_input_flags;
triangle_input.triangleArray.numSbtRecords = 1;
OptixAccelBufferSizes gas_buffer_sizes;
OPTIX_CHECK(optixAccelComputeMemoryUsage(mState.context, &accel_options, &triangle_input,
1, // Number of build inputs
&gas_buffer_sizes));
CUdeviceptr d_temp_buffer_gas;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_temp_buffer_gas), gas_buffer_sizes.tempSizeInBytes));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_gas_output_buffer), gas_buffer_sizes.outputSizeInBytes));
CUdeviceptr compactedSizeBuffer;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t)));
OptixAccelEmitDesc property = {};
property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE;
property.result = compactedSizeBuffer;
OPTIX_CHECK(optixAccelBuild(mState.context,
0, // CUDA stream
&accel_options, &triangle_input,
1, // num build inputs
d_temp_buffer_gas, gas_buffer_sizes.tempSizeInBytes, d_gas_output_buffer,
gas_buffer_sizes.outputSizeInBytes, &gas_handle,
&property, // emitted property list
1 // num emitted properties
));
compactAccel(d_gas_output_buffer, gas_handle, property.result, gas_buffer_sizes.outputSizeInBytes);
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_temp_buffer_gas)));
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(compactedSizeBuffer)));
}
Mesh* rmesh = new Mesh();
rmesh->d_gas_output_buffer = d_gas_output_buffer;
rmesh->gas_handle = gas_handle;
return rmesh;
}
void OptiXRender::createAccelerationStructure()
{
const std::vector<oka::Mesh>& meshes = mScene->getMeshes();
const std::vector<oka::Curve>& curves = mScene->getCurves();
const std::vector<oka::Instance>& instances = mScene->getInstances();
if (meshes.empty() && curves.empty())
{
return;
}
// TODO: add proper clear and free resources
mOptixMeshes.clear();
for (int i = 0; i < meshes.size(); ++i)
{
Mesh* m = createMesh(meshes[i]);
mOptixMeshes.push_back(m);
}
mOptixCurves.clear();
for (int i = 0; i < curves.size(); ++i)
{
Curve* c = createCurve(curves[i]);
mOptixCurves.push_back(c);
}
std::vector<OptixInstance> optixInstances;
glm::mat3x4 identity = glm::identity<glm::mat3x4>();
for (int i = 0; i < instances.size(); ++i)
{
OptixInstance oi = {};
const oka::Instance& curr = instances[i];
if (curr.type == oka::Instance::Type::eMesh)
{
oi.traversableHandle = mOptixMeshes[curr.mMeshId]->gas_handle;
oi.visibilityMask = GEOMETRY_MASK_TRIANGLE;
}
else if (curr.type == oka::Instance::Type::eCurve)
{
oi.traversableHandle = mOptixCurves[curr.mCurveId]->gas_handle;
oi.visibilityMask = GEOMETRY_MASK_CURVE;
}
else if (curr.type == oka::Instance::Type::eLight)
{
oi.traversableHandle = mOptixMeshes[curr.mMeshId]->gas_handle;
oi.visibilityMask = GEOMETRY_MASK_LIGHT;
}
else
{
assert(0);
}
// fill common instance data
memcpy(oi.transform, glm::value_ptr(glm::float3x4(glm::rowMajor4(curr.transform))), sizeof(float) * 12);
oi.sbtOffset = static_cast<unsigned int>(i * RAY_TYPE_COUNT);
optixInstances.push_back(oi);
}
size_t instances_size_in_bytes = sizeof(OptixInstance) * optixInstances.size();
CUDA_CHECK(cudaMalloc((void**)&mState.d_instances, instances_size_in_bytes));
CUDA_CHECK(
cudaMemcpy((void*)mState.d_instances, optixInstances.data(), instances_size_in_bytes, cudaMemcpyHostToDevice));
OptixBuildInput ias_instance_input = {};
ias_instance_input.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES;
ias_instance_input.instanceArray.instances = mState.d_instances;
ias_instance_input.instanceArray.numInstances = static_cast<int>(optixInstances.size());
OptixAccelBuildOptions ias_accel_options = {};
ias_accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE;
ias_accel_options.motionOptions.numKeys = 1;
ias_accel_options.operation = OPTIX_BUILD_OPERATION_BUILD;
OptixAccelBufferSizes ias_buffer_sizes;
OPTIX_CHECK(
optixAccelComputeMemoryUsage(mState.context, &ias_accel_options, &ias_instance_input, 1, &ias_buffer_sizes));
// non-compacted output
CUdeviceptr d_buffer_temp_output_ias_and_compacted_size;
auto roundUp = [](size_t x, size_t y) { return ((x + y - 1) / y) * y; };
size_t compactedSizeOffset = roundUp(ias_buffer_sizes.outputSizeInBytes, 8ull);
CUDA_CHECK(
cudaMalloc(reinterpret_cast<void**>(&d_buffer_temp_output_ias_and_compacted_size), compactedSizeOffset + 8));
CUdeviceptr d_ias_temp_buffer;
// bool needIASTempBuffer = ias_buffer_sizes.tempSizeInBytes > state.temp_buffer_size;
// if( needIASTempBuffer )
{
CUDA_CHECK(cudaMalloc((void**)&d_ias_temp_buffer, ias_buffer_sizes.tempSizeInBytes));
}
// else
// {
// d_ias_temp_buffer = state.d_temp_buffer;
// }
CUdeviceptr compactedSizeBuffer;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>((&compactedSizeBuffer)), sizeof(uint64_t)));
OptixAccelEmitDesc property = {};
property.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE;
property.result = compactedSizeBuffer;
OPTIX_CHECK(optixAccelBuild(mState.context, 0, &ias_accel_options, &ias_instance_input, 1, d_ias_temp_buffer,
ias_buffer_sizes.tempSizeInBytes, d_buffer_temp_output_ias_and_compacted_size,
ias_buffer_sizes.outputSizeInBytes, &mState.ias_handle, &property, 1));
compactAccel(d_buffer_temp_output_ias_and_compacted_size, mState.ias_handle, property.result,
ias_buffer_sizes.outputSizeInBytes);
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(compactedSizeBuffer)));
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_ias_temp_buffer)));
}
void OptiXRender::createModule()
{
OptixModule module = nullptr;
OptixPipelineCompileOptions pipeline_compile_options = {};
OptixModuleCompileOptions module_compile_options = {};
{
if (mEnableValidation)
{
module_compile_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_0;
module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL;
}
else
{
module_compile_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_DEFAULT;
module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE;
}
pipeline_compile_options.usesMotionBlur = false;
pipeline_compile_options.traversableGraphFlags = OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_SINGLE_LEVEL_INSTANCING;
pipeline_compile_options.numPayloadValues = 2;
pipeline_compile_options.numAttributeValues = 2;
if (mEnableValidation) // Enables debug exceptions during optix launches. This may incur
// significant performance cost and should only be done during
// development.
pipeline_compile_options.exceptionFlags =
OPTIX_EXCEPTION_FLAG_USER | OPTIX_EXCEPTION_FLAG_TRACE_DEPTH | OPTIX_EXCEPTION_FLAG_STACK_OVERFLOW;
else
{
pipeline_compile_options.exceptionFlags = OPTIX_EXCEPTION_FLAG_NONE;
}
pipeline_compile_options.pipelineLaunchParamsVariableName = "params";
pipeline_compile_options.usesPrimitiveTypeFlags =
OPTIX_PRIMITIVE_TYPE_FLAGS_TRIANGLE | OPTIX_PRIMITIVE_TYPE_FLAGS_ROUND_CUBIC_BSPLINE;
size_t inputSize = 0;
std::string optixSource;
const fs::path cwdPath = fs::current_path();
const fs::path precompiledOptixPath = cwdPath / "optix/render_generated_OptixRender.cu.optixir";
readSourceFile(optixSource, precompiledOptixPath);
const char* input = optixSource.c_str();
inputSize = optixSource.size();
char log[2048]; // For error reporting from OptiX creation functions
size_t sizeof_log = sizeof(log);
OPTIX_CHECK_LOG(optixModuleCreate(mState.context, &module_compile_options, &pipeline_compile_options,
input, inputSize, log, &sizeof_log, &module));
}
mState.ptx_module = module;
mState.pipeline_compile_options = pipeline_compile_options;
mState.module_compile_options = module_compile_options;
// hair modules
OptixBuiltinISOptions builtinISOptions = {};
builtinISOptions.buildFlags = OPTIX_BUILD_FLAG_NONE;
// builtinISOptions.curveEndcapFlags = OPTIX_CURVE_ENDCAP_ON;
builtinISOptions.builtinISModuleType = OPTIX_PRIMITIVE_TYPE_ROUND_CUBIC_BSPLINE;
OPTIX_CHECK(optixBuiltinISModuleGet(mState.context, &mState.module_compile_options, &mState.pipeline_compile_options,
&builtinISOptions, &mState.m_catromCurveModule));
}
OptixProgramGroup OptiXRender::createRadianceClosestHitProgramGroup(PathTracerState& state,
char const* module_code,
size_t module_size)
{
char log[2048];
size_t sizeof_log = sizeof(log);
OptixModule mat_module = nullptr;
OPTIX_CHECK_LOG(optixModuleCreate(state.context, &state.module_compile_options, &state.pipeline_compile_options,
module_code, module_size, log, &sizeof_log, &mat_module));
OptixProgramGroupOptions program_group_options = {};
OptixProgramGroupDesc hit_prog_group_desc = {};
hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
hit_prog_group_desc.hitgroup.moduleCH = mat_module;
hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__radiance";
hit_prog_group_desc.hitgroup.moduleIS = mState.m_catromCurveModule;
hit_prog_group_desc.hitgroup.entryFunctionNameIS = 0; // automatically supplied for built-in module
sizeof_log = sizeof(log);
OptixProgramGroup ch_hit_group = nullptr;
OPTIX_CHECK_LOG(optixProgramGroupCreate(state.context, &hit_prog_group_desc,
/*numProgramGroups=*/1, &program_group_options, log, &sizeof_log,
&ch_hit_group));
return ch_hit_group;
}
void OptiXRender::createProgramGroups()
{
OptixProgramGroupOptions program_group_options = {}; // Initialize to zeros
OptixProgramGroupDesc raygen_prog_group_desc = {}; //
raygen_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
raygen_prog_group_desc.raygen.module = mState.ptx_module;
raygen_prog_group_desc.raygen.entryFunctionName = "__raygen__rg";
char log[2048]; // For error reporting from OptiX creation functions
size_t sizeof_log = sizeof(log);
OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &raygen_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &mState.raygen_prog_group));
OptixProgramGroupDesc miss_prog_group_desc = {};
miss_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS;
miss_prog_group_desc.miss.module = mState.ptx_module;
miss_prog_group_desc.miss.entryFunctionName = "__miss__ms";
sizeof_log = sizeof(log);
OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &miss_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &mState.radiance_miss_group));
memset(&miss_prog_group_desc, 0, sizeof(OptixProgramGroupDesc));
miss_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS;
miss_prog_group_desc.miss.module = nullptr; // NULL miss program for occlusion rays
miss_prog_group_desc.miss.entryFunctionName = nullptr;
sizeof_log = sizeof(log);
OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &miss_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &mState.occlusion_miss_group));
OptixProgramGroupDesc hit_prog_group_desc = {};
hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module;
hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__ch";
sizeof_log = sizeof(log);
OptixProgramGroup radiance_hit_group;
OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &hit_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &radiance_hit_group));
mState.radiance_default_hit_group = radiance_hit_group;
OptixProgramGroupDesc light_hit_prog_group_desc = {};
light_hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
light_hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module;
light_hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__light";
sizeof_log = sizeof(log);
OptixProgramGroup light_hit_group;
OPTIX_CHECK_LOG(optixProgramGroupCreate(mState.context, &light_hit_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &light_hit_group));
mState.light_hit_group = light_hit_group;
memset(&hit_prog_group_desc, 0, sizeof(OptixProgramGroupDesc));
hit_prog_group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
hit_prog_group_desc.hitgroup.moduleCH = mState.ptx_module;
hit_prog_group_desc.hitgroup.entryFunctionNameCH = "__closesthit__occlusion";
hit_prog_group_desc.hitgroup.moduleIS = mState.m_catromCurveModule;
hit_prog_group_desc.hitgroup.entryFunctionNameIS = 0; // automatically supplied for built-in module
sizeof_log = sizeof(log);
OPTIX_CHECK(optixProgramGroupCreate(mState.context, &hit_prog_group_desc,
1, // num program groups
&program_group_options, log, &sizeof_log, &mState.occlusion_hit_group));
}
void OptiXRender::createPipeline()
{
OptixPipeline pipeline = nullptr;
{
const uint32_t max_trace_depth = 2;
std::vector<OptixProgramGroup> program_groups = {};
program_groups.push_back(mState.raygen_prog_group);
program_groups.push_back(mState.radiance_miss_group);
program_groups.push_back(mState.radiance_default_hit_group);
program_groups.push_back(mState.occlusion_miss_group);
program_groups.push_back(mState.occlusion_hit_group);
program_groups.push_back(mState.light_hit_group);
for (auto& m : mMaterials)
{
program_groups.push_back(m.programGroup);
}
OptixPipelineLinkOptions pipeline_link_options = {};
pipeline_link_options.maxTraceDepth = max_trace_depth;
// if (mEnableValidation)
// {
// pipeline_link_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL;
// }
// else
// {
// pipeline_link_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE;
// }
char log[2048]; // For error reporting from OptiX creation functions
size_t sizeof_log = sizeof(log);
OPTIX_CHECK_LOG(optixPipelineCreate(mState.context, &mState.pipeline_compile_options, &pipeline_link_options,
program_groups.data(), program_groups.size(), log, &sizeof_log, &pipeline));
OptixStackSizes stack_sizes = {};
for (auto& prog_group : program_groups)
{
OPTIX_CHECK(optixUtilAccumulateStackSizes(prog_group, &stack_sizes, pipeline));
}
uint32_t direct_callable_stack_size_from_traversal;
uint32_t direct_callable_stack_size_from_state;
uint32_t continuation_stack_size;
OPTIX_CHECK(optixUtilComputeStackSizes(&stack_sizes, max_trace_depth,
0, // maxCCDepth
0, // maxDCDepth
&direct_callable_stack_size_from_traversal,
&direct_callable_stack_size_from_state, &continuation_stack_size));
OPTIX_CHECK(optixPipelineSetStackSize(pipeline, direct_callable_stack_size_from_traversal,
direct_callable_stack_size_from_state, continuation_stack_size,
2 // maxTraversableDepth
));
}
mState.pipeline = pipeline;
}
void OptiXRender::createSbt()
{
OptixShaderBindingTable sbt = {};
{
CUdeviceptr raygen_record;
const size_t raygen_record_size = sizeof(RayGenSbtRecord);
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&raygen_record), raygen_record_size));
RayGenSbtRecord rg_sbt;
OPTIX_CHECK(optixSbtRecordPackHeader(mState.raygen_prog_group, &rg_sbt));
CUDA_CHECK(
cudaMemcpy(reinterpret_cast<void*>(raygen_record), &rg_sbt, raygen_record_size, cudaMemcpyHostToDevice));
CUdeviceptr miss_record;
const uint32_t miss_record_count = RAY_TYPE_COUNT;
size_t miss_record_size = sizeof(MissSbtRecord) * miss_record_count;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&miss_record), miss_record_size));
std::vector<MissSbtRecord> missGroupDataCpu(miss_record_count);
MissSbtRecord& ms_sbt = missGroupDataCpu[RAY_TYPE_RADIANCE];
// ms_sbt.data.bg_color = { 0.5f, 0.5f, 0.5f };
ms_sbt.data.bg_color = { 0.0f, 0.0f, 0.0f };
OPTIX_CHECK(optixSbtRecordPackHeader(mState.radiance_miss_group, &ms_sbt));
MissSbtRecord& ms_sbt_occlusion = missGroupDataCpu[RAY_TYPE_OCCLUSION];
ms_sbt_occlusion.data = { 0.0f, 0.0f, 0.0f };
OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_miss_group, &ms_sbt_occlusion));
CUDA_CHECK(cudaMemcpy(
reinterpret_cast<void*>(miss_record), missGroupDataCpu.data(), miss_record_size, cudaMemcpyHostToDevice));
uint32_t hitGroupRecordCount = RAY_TYPE_COUNT;
CUdeviceptr hitgroup_record = 0;
size_t hitgroup_record_size = hitGroupRecordCount * sizeof(HitGroupSbtRecord);
const std::vector<oka::Instance>& instances = mScene->getInstances();
std::vector<HitGroupSbtRecord> hitGroupDataCpu(hitGroupRecordCount); // default sbt record
if (!instances.empty())
{
const std::vector<oka::Mesh>& meshes = mScene->getMeshes();
hitGroupRecordCount = instances.size() * RAY_TYPE_COUNT;
hitgroup_record_size = sizeof(HitGroupSbtRecord) * hitGroupRecordCount;
hitGroupDataCpu.resize(hitGroupRecordCount);
for (int i = 0; i < instances.size(); ++i)
{
const oka::Instance& instance = instances[i];
int hg_index = i * RAY_TYPE_COUNT + RAY_TYPE_RADIANCE;
HitGroupSbtRecord& hg_sbt = hitGroupDataCpu[hg_index];
// replace unknown material on default
const int materialIdx = instance.mMaterialId == -1 ? 0 : instance.mMaterialId;
const Material& mat = getMaterial(materialIdx);
if (instance.type == oka::Instance::Type::eLight)
{
hg_sbt.data.lightId = instance.mLightId;
const OptixProgramGroup& lightPg = mState.light_hit_group;
OPTIX_CHECK(optixSbtRecordPackHeader(lightPg, &hg_sbt));
}
else
{
const OptixProgramGroup& hitMaterial = mat.programGroup;
OPTIX_CHECK(optixSbtRecordPackHeader(hitMaterial, &hg_sbt));
}
// write all needed data for instances
hg_sbt.data.argData = mat.d_argData;
hg_sbt.data.roData = mat.d_roData;
hg_sbt.data.resHandler = mat.d_textureHandler;
if (instance.type == oka::Instance::Type::eMesh)
{
const oka::Mesh& mesh = meshes[instance.mMeshId];
hg_sbt.data.indexCount = mesh.mCount;
hg_sbt.data.indexOffset = mesh.mIndex;
hg_sbt.data.vertexOffset = mesh.mVbOffset;
hg_sbt.data.lightId = -1;
}
memcpy(hg_sbt.data.object_to_world, glm::value_ptr(glm::float4x4(glm::rowMajor4(instance.transform))),
sizeof(float4) * 4);
glm::mat4 world_to_object = glm::inverse(instance.transform);
memcpy(hg_sbt.data.world_to_object, glm::value_ptr(glm::float4x4(glm::rowMajor4(world_to_object))),
sizeof(float4) * 4);
// write data for visibility ray
hg_index = i * RAY_TYPE_COUNT + RAY_TYPE_OCCLUSION;
HitGroupSbtRecord& hg_sbt_occlusion = hitGroupDataCpu[hg_index];
OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_hit_group, &hg_sbt_occlusion));
}
}
else
{
// stub record
HitGroupSbtRecord& hg_sbt = hitGroupDataCpu[RAY_TYPE_RADIANCE];
OPTIX_CHECK(optixSbtRecordPackHeader(mState.radiance_default_hit_group, &hg_sbt));
HitGroupSbtRecord& hg_sbt_occlusion = hitGroupDataCpu[RAY_TYPE_OCCLUSION];
OPTIX_CHECK(optixSbtRecordPackHeader(mState.occlusion_hit_group, &hg_sbt_occlusion));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&hitgroup_record), hitgroup_record_size));
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(hitgroup_record), hitGroupDataCpu.data(), hitgroup_record_size,
cudaMemcpyHostToDevice));
sbt.raygenRecord = raygen_record;
sbt.missRecordBase = miss_record;
sbt.missRecordStrideInBytes = sizeof(MissSbtRecord);
sbt.missRecordCount = RAY_TYPE_COUNT;
sbt.hitgroupRecordBase = hitgroup_record;
sbt.hitgroupRecordStrideInBytes = sizeof(HitGroupSbtRecord);
sbt.hitgroupRecordCount = hitGroupRecordCount;
}
mState.sbt = sbt;
}
void OptiXRender::updatePathtracerParams(const uint32_t width, const uint32_t height)
{
bool needRealloc = false;
if (mState.params.image_width != width || mState.params.image_height != height)
{
// new dimensions!
needRealloc = true;
// reset rendering
getSharedContext().mSubframeIndex = 0;
}
mState.params.image_width = width;
mState.params.image_height = height;
if (needRealloc)
{
getSharedContext().mSettingsManager->setAs<bool>("render/pt/isResized", true);
if (mState.params.accum)
{
CUDA_CHECK(cudaFree((void*)mState.params.accum));
}
if (mState.params.diffuse)
{
CUDA_CHECK(cudaFree((void*)mState.params.diffuse));
}
if (mState.params.specular)
{
CUDA_CHECK(cudaFree((void*)mState.params.specular));
}
if (mState.d_params)
{
CUDA_CHECK(cudaFree((void*)mState.d_params));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.d_params), sizeof(Params)));
const size_t frameSize = mState.params.image_width * mState.params.image_height;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.accum), frameSize * sizeof(float4)));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.diffuse), frameSize * sizeof(float4)));
CUDA_CHECK(cudaMemset(mState.params.diffuse, 0, frameSize * sizeof(float4)));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.diffuseCounter), frameSize * sizeof(uint16_t)));
CUDA_CHECK(cudaMemset(mState.params.diffuseCounter, 0, frameSize * sizeof(uint16_t)));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.specular), frameSize * sizeof(float4)));
CUDA_CHECK(cudaMemset(mState.params.specular, 0, frameSize * sizeof(float4)));
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&mState.params.specularCounter), frameSize * sizeof(uint16_t)));
CUDA_CHECK(cudaMemset(mState.params.specularCounter, 0, frameSize * sizeof(uint16_t)));
}
}
void OptiXRender::render(Buffer* output)
{
if (getSharedContext().mFrameNumber == 0)
{
createOptixMaterials();
createPipeline();
createVertexBuffer();
createIndexBuffer();
// upload all curve data
createPointsBuffer();
createWidthsBuffer();
createAccelerationStructure();
createSbt();
createLightBuffer();
}
const uint32_t width = output->width();
const uint32_t height = output->height();
updatePathtracerParams(width, height);
oka::Camera& camera = mScene->getCamera(0);
camera.updateAspectRatio(width / (float)height);
camera.updateViewMatrix();
View currView = {};
currView.mCamMatrices = camera.matrices;
if (glm::any(glm::notEqual(currView.mCamMatrices.perspective, mPrevView.mCamMatrices.perspective)) ||
glm::any(glm::notEqual(currView.mCamMatrices.view, mPrevView.mCamMatrices.view)))
{
// need reset
getSharedContext().mSubframeIndex = 0;
}
SettingsManager& settings = *getSharedContext().mSettingsManager;
bool settingsChanged = false;
static uint32_t rectLightSamplingMethodPrev = 0;
const uint32_t rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod");
settingsChanged = (rectLightSamplingMethodPrev != rectLightSamplingMethod);
rectLightSamplingMethodPrev = rectLightSamplingMethod;
static bool enableAccumulationPrev = 0;
bool enableAccumulation = settings.getAs<bool>("render/pt/enableAcc");
settingsChanged |= (enableAccumulationPrev != enableAccumulation);
enableAccumulationPrev = enableAccumulation;
static uint32_t sspTotalPrev = 0;
const uint32_t sspTotal = settings.getAs<uint32_t>("render/pt/sppTotal");
settingsChanged |= (sspTotalPrev > sspTotal); // reset only if new spp less than already accumulated
sspTotalPrev = sspTotal;
const float gamma = settings.getAs<float>("render/post/gamma");
const ToneMapperType tonemapperType = (ToneMapperType)settings.getAs<uint32_t>("render/pt/tonemapperType");
if (settingsChanged)
{
getSharedContext().mSubframeIndex = 0;
}
Params& params = mState.params;
params.scene.vb = (Vertex*)d_vb;
params.scene.ib = (uint32_t*)d_ib;
params.scene.lights = (UniformLight*)d_lights;
params.scene.numLights = mScene->getLights().size();
params.image = (float4*)((OptixBuffer*)output)->getNativePtr();
params.samples_per_launch = settings.getAs<uint32_t>("render/pt/spp");
params.handle = mState.ias_handle;
params.max_depth = settings.getAs<uint32_t>("render/pt/depth");
params.rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod");
params.enableAccumulation = settings.getAs<bool>("render/pt/enableAcc");
params.debug = settings.getAs<uint32_t>("render/pt/debug");
params.shadowRayTmin = settings.getAs<float>("render/pt/dev/shadowRayTmin");
params.materialRayTmin = settings.getAs<float>("render/pt/dev/materialRayTmin");
memcpy(params.viewToWorld, glm::value_ptr(glm::transpose(glm::inverse(camera.matrices.view))), sizeof(params.viewToWorld));
memcpy(params.clipToView, glm::value_ptr(glm::transpose(camera.matrices.invPerspective)), sizeof(params.clipToView));
params.subframe_index = getSharedContext().mSubframeIndex;
// Photometric Units from iray documentation
// Controls the sensitivity of the “camera film” and is expressed as an index; the ISO number of the film, also
// known as “film speed.” The higher this value, the greater the exposure. If this is set to a non-zero value,
// “Photographic” mode is enabled. If this is set to 0, “Arbitrary” mode is enabled, and all color scaling is then
// strictly defined by the value of cm^2 Factor.
float filmIso = settings.getAs<float>("render/post/tonemapper/filmIso");
// The candela per meter square factor
float cm2_factor = settings.getAs<float>("render/post/tonemapper/cm2_factor");
// The fractional aperture number; e.g., 11 means aperture “f/11.” It adjusts the size of the opening of the “camera
// iris” and is expressed as a ratio. The higher this value, the lower the exposure.
float fStop = settings.getAs<float>("render/post/tonemapper/fStop");
// Controls the duration, in fractions of a second, that the “shutter” is open; e.g., the value 100 means that the
// “shutter” is open for 1/100th of a second. The higher this value, the greater the exposure
float shutterSpeed = settings.getAs<float>("render/post/tonemapper/shutterSpeed");
// Specifies the main color temperature of the light sources; the color that will be mapped to “white” on output,
// e.g., an incoming color of this hue/saturation will be mapped to grayscale, but its intensity will remain
// unchanged. This is similar to white balance controls on digital cameras.
float3 whitePoint { 1.0f, 1.0f, 1.0f };
float3 exposureValue = all(whitePoint) ? 1.0f / whitePoint : make_float3(1.0f);
const float lum = dot(exposureValue, make_float3(0.299f, 0.587f, 0.114f));
if (filmIso > 0.0f)
{
// See https://www.nayuki.io/page/the-photographic-exposure-equation
exposureValue *= cm2_factor * filmIso / (shutterSpeed * fStop * fStop) / 100.0f;
}
else
{
exposureValue *= cm2_factor;
}
exposureValue /= lum;
params.exposure = exposureValue;
const uint32_t totalSpp = settings.getAs<uint32_t>("render/pt/sppTotal");
const uint32_t samplesPerLaunch = settings.getAs<uint32_t>("render/pt/spp");
const int32_t leftSpp = totalSpp - getSharedContext().mSubframeIndex;
// if accumulation is off then launch selected samples per pixel
uint32_t samplesThisLaunch =
enableAccumulation ? std::min((int32_t)samplesPerLaunch, leftSpp) : samplesPerLaunch;
if (params.debug == 1)
{
samplesThisLaunch = 1;
enableAccumulation = false;
}
params.samples_per_launch = samplesThisLaunch;
params.enableAccumulation = enableAccumulation;
params.maxSampleCount = totalSpp;
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(mState.d_params), ¶ms, sizeof(params), cudaMemcpyHostToDevice));
if (samplesThisLaunch != 0)
{
OPTIX_CHECK(optixLaunch(
mState.pipeline, mState.stream, mState.d_params, sizeof(Params), &mState.sbt, width, height, /*depth=*/1));
CUDA_SYNC_CHECK();
if (enableAccumulation)
{
getSharedContext().mSubframeIndex += samplesThisLaunch;
}
else
{
getSharedContext().mSubframeIndex = 0;
}
}
else
{
// just copy latest accumulated raw radiance to destination
if (params.debug == 0)
{
CUDA_CHECK(cudaMemcpy(params.image, params.accum,
mState.params.image_width * mState.params.image_height * sizeof(float4),
cudaMemcpyDeviceToDevice));
}
if (params.debug == 2)
{
CUDA_CHECK(cudaMemcpy(params.image, params.diffuse,
mState.params.image_width * mState.params.image_height * sizeof(float4),
cudaMemcpyDeviceToDevice));
}
if (params.debug == 3)
{
CUDA_CHECK(cudaMemcpy(params.image, params.specular,
mState.params.image_width * mState.params.image_height * sizeof(float4),
cudaMemcpyDeviceToDevice));
}
}
if (params.debug != 1)
{
// do not run post processing for debug output
tonemap(tonemapperType, exposureValue, gamma, params.image, width, height);
}
output->unmap();
getSharedContext().mFrameNumber++;
mPrevView = currView;
mState.prevParams = mState.params;
}
void OptiXRender::init()
{
// TODO: move USD_DIR to settings
const char* envUSDPath = std::getenv("USD_DIR");
mEnableValidation = getSharedContext().mSettingsManager->getAs<bool>("render/enableValidation");
fs::path usdMdlLibPath;
if (envUSDPath)
{
usdMdlLibPath = (fs::path(envUSDPath) / fs::path("libraries/mdl/")).make_preferred();
}
const fs::path cwdPath = fs::current_path();
STRELKA_DEBUG("cwdPath: {}", cwdPath.string().c_str());
const fs::path mtlxPath = (cwdPath / fs::path("data/materials/mtlx")).make_preferred();
STRELKA_DEBUG("mtlxPath: {}", mtlxPath.string().c_str());
const fs::path mdlPath = (cwdPath / fs::path("data/materials/mdl")).make_preferred();
const std::string usdMdlLibPathStr = usdMdlLibPath.string();
const std::string mtlxPathStr = mtlxPath.string().c_str();
const std::string mdlPathStr = mdlPath.string().c_str();
const char* paths[] = { usdMdlLibPathStr.c_str(), mtlxPathStr.c_str(), mdlPathStr.c_str() };
bool res = mMaterialManager.addMdlSearchPath(paths, sizeof(paths) / sizeof(char*));
if (!res)
{
STRELKA_FATAL("Wrong mdl paths configuration!");
assert(0);
return;
}
// default material
{
oka::Scene::MaterialDescription defaultMaterial{};
defaultMaterial.file = "default.mdl";
defaultMaterial.name = "default_material";
defaultMaterial.type = oka::Scene::MaterialDescription::Type::eMdl;
mScene->addMaterial(defaultMaterial);
}
createContext();
// createAccelerationStructure();
createModule();
createProgramGroups();
createPipeline();
// createSbt();
}
Buffer* OptiXRender::createBuffer(const BufferDesc& desc)
{
const size_t size = desc.height * desc.width * Buffer::getElementSize(desc.format);
assert(size != 0);
void* devicePtr = nullptr;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&devicePtr), size));
OptixBuffer* res = new OptixBuffer(devicePtr, desc.format, desc.width, desc.height);
return res;
}
void OptiXRender::createPointsBuffer()
{
const std::vector<glm::float3>& points = mScene->getCurvesPoint();
std::vector<float3> data(points.size());
for (int i = 0; i < points.size(); ++i)
{
data[i] = make_float3(points[i].x, points[i].y, points[i].z);
}
const size_t size = data.size() * sizeof(float3);
if (d_points)
{
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_points)));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_points), size));
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_points), data.data(), size, cudaMemcpyHostToDevice));
}
void OptiXRender::createWidthsBuffer()
{
const std::vector<float>& data = mScene->getCurvesWidths();
const size_t size = data.size() * sizeof(float);
if (d_widths)
{
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_widths)));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_widths), size));
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_widths), data.data(), size, cudaMemcpyHostToDevice));
}
void OptiXRender::createVertexBuffer()
{
const std::vector<oka::Scene::Vertex>& vertices = mScene->getVertices();
const size_t vbsize = vertices.size() * sizeof(oka::Scene::Vertex);
if (d_vb)
{
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_vb)));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_vb), vbsize));
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_vb), vertices.data(), vbsize, cudaMemcpyHostToDevice));
}
void OptiXRender::createIndexBuffer()
{
const std::vector<uint32_t>& indices = mScene->getIndices();
const size_t ibsize = indices.size() * sizeof(uint32_t);
if (d_ib)
{
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_ib)));
}
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_ib), ibsize));
CUDA_CHECK(cudaMemcpy(reinterpret_cast<void*>(d_ib), indices.data(), ibsize, cudaMemcpyHostToDevice));
}
void OptiXRender::createLightBuffer()
{
const std::vector<Scene::Light>& lightDescs = mScene->getLights();
const size_t lightBufferSize = lightDescs.size() * sizeof(Scene::Light);
if (d_lights)
{
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_lights)));
}
if (lightBufferSize)
{
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_lights), lightBufferSize));
CUDA_CHECK(
cudaMemcpy(reinterpret_cast<void*>(d_lights), lightDescs.data(), lightBufferSize, cudaMemcpyHostToDevice));
}
}
Texture OptiXRender::loadTextureFromFile(const std::string& fileName)
{
int texWidth, texHeight, texChannels;
stbi_uc* data = stbi_load(fileName.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
if (!data)
{
STRELKA_ERROR("Unable to load texture from file: {}", fileName.c_str());
return Texture();
}
// convert to float4 format
// TODO: add compression here:
// std::vector<float> floatData(texWidth * texHeight * 4);
// for (int i = 0; i < texHeight; ++i)
// {
// for (int j = 0; j < texWidth; ++j)
// {
// const size_t linearPixelIndex = (i * texWidth + j) * 4;
// auto remapToFloat = [](const unsigned char v)
// {
// return float(v) / 255.0f;
// };
// floatData[linearPixelIndex + 0] = remapToFloat(data[linearPixelIndex + 0]);
// floatData[linearPixelIndex + 1] = remapToFloat(data[linearPixelIndex + 1]);
// floatData[linearPixelIndex + 2] = remapToFloat(data[linearPixelIndex + 2]);
// floatData[linearPixelIndex + 3] = remapToFloat(data[linearPixelIndex + 3]);
// }
// }
const void* dataPtr = data;
cudaChannelFormatDesc channel_desc = cudaCreateChannelDesc<uchar4>();
cudaResourceDesc res_desc{};
memset(&res_desc, 0, sizeof(res_desc));
cudaArray_t device_tex_array;
CUDA_CHECK(cudaMallocArray(&device_tex_array, &channel_desc, texWidth, texHeight));
CUDA_CHECK(cudaMemcpy2DToArray(device_tex_array, 0, 0, dataPtr, texWidth * sizeof(char) * 4,
texWidth * sizeof(char) * 4, texHeight, cudaMemcpyHostToDevice));
res_desc.resType = cudaResourceTypeArray;
res_desc.res.array.array = device_tex_array;
// Create filtered texture object
cudaTextureDesc tex_desc;
memset(&tex_desc, 0, sizeof(tex_desc));
cudaTextureAddressMode addr_mode = cudaAddressModeWrap;
tex_desc.addressMode[0] = addr_mode;
tex_desc.addressMode[1] = addr_mode;
tex_desc.addressMode[2] = addr_mode;
tex_desc.filterMode = cudaFilterModeLinear;
tex_desc.readMode = cudaReadModeNormalizedFloat;
tex_desc.normalizedCoords = 1;
if (res_desc.resType == cudaResourceTypeMipmappedArray)
{
tex_desc.mipmapFilterMode = cudaFilterModeLinear;
tex_desc.maxAnisotropy = 16;
tex_desc.minMipmapLevelClamp = 0.f;
tex_desc.maxMipmapLevelClamp = 1000.f; // default value in OpenGL
}
cudaTextureObject_t tex_obj = 0;
CUDA_CHECK(cudaCreateTextureObject(&tex_obj, &res_desc, &tex_desc, nullptr));
// Create unfiltered texture object if necessary (cube textures have no texel functions)
cudaTextureObject_t tex_obj_unfilt = 0;
// if (texture_shape != mi::neuraylib::ITarget_code::Texture_shape_cube)
{
// Use a black border for access outside of the texture
tex_desc.addressMode[0] = cudaAddressModeBorder;
tex_desc.addressMode[1] = cudaAddressModeBorder;
tex_desc.addressMode[2] = cudaAddressModeBorder;
tex_desc.filterMode = cudaFilterModePoint;
CUDA_CHECK(cudaCreateTextureObject(&tex_obj_unfilt, &res_desc, &tex_desc, nullptr));
}
return Texture(tex_obj, tex_obj_unfilt, make_uint3(texWidth, texHeight, 1));
}
bool OptiXRender::createOptixMaterials()
{
std::unordered_map<std::string, MaterialManager::Module*> mNameToModule;
std::unordered_map<std::string, MaterialManager::MaterialInstance*> mNameToInstance;
std::unordered_map<std::string, MaterialManager::CompiledMaterial*> mNameToCompiled;
std::unordered_map<std::string, MaterialManager::TargetCode*> mNameToTargetCode;
std::vector<MaterialManager::CompiledMaterial*> compiledMaterials;
MaterialManager::TargetCode* targetCode;
std::vector<Scene::MaterialDescription>& matDescs = mScene->getMaterials();
for (uint32_t i = 0; i < matDescs.size(); ++i)
{
oka::Scene::MaterialDescription& currMatDesc = matDescs[i];
if (currMatDesc.type == oka::Scene::MaterialDescription::Type::eMdl)
{
if (auto it = mNameToCompiled.find(currMatDesc.name); it != mNameToCompiled.end())
{
compiledMaterials.emplace_back(it->second);
continue;
}
MaterialManager::Module* mdlModule = nullptr;
if (mNameToModule.find(currMatDesc.file) != mNameToModule.end())
{
mdlModule = mNameToModule[currMatDesc.file];
}
else
{
mdlModule = mMaterialManager.createModule(currMatDesc.file.c_str());
if (mdlModule == nullptr)
{
STRELKA_ERROR("Unable to load MDL file: {}, Force replaced to default.mdl", currMatDesc.file.c_str());
mdlModule = mNameToModule["default.mdl"];
}
mNameToModule[currMatDesc.file] = mdlModule;
}
assert(mdlModule);
MaterialManager::MaterialInstance* materialInst = nullptr;
if (mNameToInstance.find(currMatDesc.name) != mNameToInstance.end())
{
materialInst = mNameToInstance[currMatDesc.name];
}
else
{
materialInst = mMaterialManager.createMaterialInstance(mdlModule, currMatDesc.name.c_str());
mNameToInstance[currMatDesc.name] = materialInst;
}
assert(materialInst);
MaterialManager::CompiledMaterial* materialComp = nullptr;
{
materialComp = mMaterialManager.compileMaterial(materialInst);
mNameToCompiled[currMatDesc.name] = materialComp;
}
assert(materialComp);
compiledMaterials.push_back(materialComp);
}
else
{
MaterialManager::Module* mdlModule = mMaterialManager.createMtlxModule(currMatDesc.code.c_str());
assert(mdlModule);
MaterialManager::MaterialInstance* materialInst = mMaterialManager.createMaterialInstance(mdlModule, "");
assert(materialInst);
MaterialManager::CompiledMaterial* materialComp = mMaterialManager.compileMaterial(materialInst);
assert(materialComp);
compiledMaterials.push_back(materialComp);
// MaterialManager::TargetCode* mdlTargetCode = mMaterialManager.generateTargetCode(&materialComp, 1);
// assert(mdlTargetCode);
// mNameToTargetCode[currMatDesc.name] = mdlTargetCode;
// targetCodes.push_back(mdlTargetCode);
}
}
targetCode = mMaterialManager.generateTargetCode(compiledMaterials.data(), compiledMaterials.size());
std::vector<Texture> materialTextures;
const auto searchPath = getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath");
fs::path resourcePath = fs::path(getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath"));
for (uint32_t i = 0; i < matDescs.size(); ++i)
{
for (const auto& param : matDescs[i].params)
{
bool res = false;
if (param.type == MaterialManager::Param::Type::eTexture)
{
std::string texPath(param.value.size(), 0);
memcpy(texPath.data(), param.value.data(), param.value.size());
// int texId = getTexManager()->loadTextureMdl(texPath);
fs::path fullTextureFilePath = resourcePath / texPath;
::Texture tex = loadTextureFromFile(fullTextureFilePath.string());
materialTextures.push_back(tex);
int texId = 0;
int resId = mMaterialManager.registerResource(targetCode, texId);
assert(resId > 0);
MaterialManager::Param newParam;
newParam.name = param.name;
newParam.type = MaterialManager::Param::Type::eInt;
newParam.value.resize(sizeof(resId));
memcpy(newParam.value.data(), &resId, sizeof(resId));
res = mMaterialManager.setParam(targetCode, i, compiledMaterials[i], newParam);
}
else
{
res = mMaterialManager.setParam(targetCode, i, compiledMaterials[i], param);
}
if (!res)
{
STRELKA_ERROR(
"Unable to set parameter: {0} for material: {1}", param.name.c_str(), matDescs[i].name.c_str());
// assert(0);
}
}
mMaterialManager.dumpParams(targetCode, i, compiledMaterials[i]);
}
const uint8_t* argData = mMaterialManager.getArgBufferData(targetCode);
const size_t argDataSize = mMaterialManager.getArgBufferSize(targetCode);
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_materialArgData), argDataSize));
CUDA_CHECK(cudaMemcpy((void*)d_materialArgData, argData, argDataSize, cudaMemcpyHostToDevice));
const uint8_t* roData = mMaterialManager.getReadOnlyBlockData(targetCode);
const size_t roDataSize = mMaterialManager.getReadOnlyBlockSize(targetCode);
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_materialRoData), roDataSize));
CUDA_CHECK(cudaMemcpy((void*)d_materialRoData, roData, roDataSize, cudaMemcpyHostToDevice));
const size_t texturesBuffSize = sizeof(Texture) * materialTextures.size();
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_texturesData), texturesBuffSize));
CUDA_CHECK(cudaMemcpy((void*)d_texturesData, materialTextures.data(), texturesBuffSize, cudaMemcpyHostToDevice));
Texture_handler resourceHandler;
resourceHandler.num_textures = materialTextures.size();
resourceHandler.textures = (const Texture*)d_texturesData;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_texturesHandler), sizeof(Texture_handler)));
CUDA_CHECK(cudaMemcpy((void*)d_texturesHandler, &resourceHandler, sizeof(Texture_handler), cudaMemcpyHostToDevice));
std::unordered_map<MaterialManager::CompiledMaterial*, OptixProgramGroup> compiledToOptixPG;
for (int i = 0; i < compiledMaterials.size(); ++i)
{
if (compiledToOptixPG.find(compiledMaterials[i]) == compiledToOptixPG.end())
{
const char* codeData = mMaterialManager.getShaderCode(targetCode, i);
assert(codeData);
const size_t codeSize = strlen(codeData);
assert(codeSize);
OptixProgramGroup pg = createRadianceClosestHitProgramGroup(mState, codeData, codeSize);
compiledToOptixPG[compiledMaterials[i]] = pg;
}
Material optixMaterial;
optixMaterial.programGroup = compiledToOptixPG[compiledMaterials[i]];
optixMaterial.d_argData = d_materialArgData + mMaterialManager.getArgBlockOffset(targetCode, i);
optixMaterial.d_argDataSize = argDataSize;
optixMaterial.d_roData = d_materialRoData + mMaterialManager.getReadOnlyOffset(targetCode, i);
optixMaterial.d_roSize = roDataSize;
optixMaterial.d_textureHandler = d_texturesHandler;
mMaterials.push_back(optixMaterial);
}
return true;
}
OptiXRender::Material& OptiXRender::getMaterial(int id)
{
assert(id < mMaterials.size());
return mMaterials[id];
}
|
arhix52/Strelka/src/render/optix/postprocessing/Utils.h | #pragma once
#include <sutil/vec_math.h>
// utility function for accumulation and HDR <=> LDR
__device__ __inline__ float3 tonemap(float3 color, const float3 exposure)
{
color *= exposure;
return color / (color + 1.0f);
}
__device__ __inline__ float3 inverseTonemap(const float3 color, const float3 exposure)
{
return color / (exposure - color * exposure);
}
|
arhix52/Strelka/src/render/optix/postprocessing/Tonemappers.h | #pragma once
#include <sutil/vec_math.h>
#include <stdint.h>
enum class ToneMapperType : uint32_t
{
eNone = 0,
eReinhard,
eACES,
eFilmic,
};
extern "C" void tonemap(const ToneMapperType type,
const float3 exposure,
const float gamma,
float4* image,
const uint32_t width,
const uint32_t height);
|
arhix52/Strelka/src/render/metal/MetalBuffer.h | #pragma once
#include "buffer.h"
#include <Metal/Metal.hpp>
namespace oka
{
class MetalBuffer : public Buffer
{
public:
MetalBuffer(MTL::Buffer* buff, BufferFormat format, uint32_t width, uint32_t height);
~MetalBuffer() override;
void resize(uint32_t width, uint32_t height) override;
void* map() override;
void unmap() override;
MTL::Buffer* getNativePtr()
{
return mBuffer;
}
void* getHostPointer() override
{
return map();
}
size_t getHostDataSize() override
{
return mBuffer->length();
}
protected:
MTL::Buffer* mBuffer;
};
} // namespace oka |
arhix52/Strelka/src/render/metal/MetalBuffer.cpp |
#include "MetalBuffer.h"
using namespace oka;
oka::MetalBuffer::MetalBuffer(MTL::Buffer* buff, BufferFormat format, uint32_t width, uint32_t height) : mBuffer(buff)
{
mFormat = format;
mWidth = width;
mHeight = height;
}
oka::MetalBuffer::~MetalBuffer()
{
mBuffer->release();
}
void oka::MetalBuffer::resize(uint32_t width, uint32_t height)
{
}
void* oka::MetalBuffer::map()
{
return mBuffer->contents();
}
void oka::MetalBuffer::unmap()
{
}
|
arhix52/Strelka/src/render/metal/MetalRender.cpp | #define NS_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#define MTK_PRIVATE_IMPLEMENTATION
#include <Metal/Metal.hpp>
#include "MetalRender.h"
#include "MetalBuffer.h"
#include <cassert>
#include <filesystem>
#include <glm/glm.hpp>
#include <glm/mat4x3.hpp>
#include <glm/gtx/compatibility.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/matrix_major_storage.hpp>
#include <glm/ext/matrix_relational.hpp>
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <log.h>
#include <simd/simd.h>
#include "shaders/ShaderTypes.h"
using namespace oka;
namespace fs = std::filesystem;
MetalRender::MetalRender(/* args */) = default;
MetalRender::~MetalRender() = default;
void MetalRender::init()
{
mDevice = MTL::CreateSystemDefaultDevice();
mCommandQueue = mDevice->newCommandQueue();
buildComputePipeline();
buildTonemapperPipeline();
}
MTL::Texture* MetalRender::loadTextureFromFile(const std::string& fileName)
{
int texWidth = 0;
int texHeight = 0;
int texChannels = 0;
stbi_uc* data = stbi_load(fileName.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
if (data == nullptr)
{
STRELKA_ERROR("Unable to load texture from file: {}", fileName.c_str());
return nullptr;
}
MTL::TextureDescriptor* pTextureDesc = MTL::TextureDescriptor::alloc()->init();
pTextureDesc->setWidth(texWidth);
pTextureDesc->setHeight(texHeight);
pTextureDesc->setPixelFormat(MTL::PixelFormatRGBA8Unorm);
pTextureDesc->setTextureType(MTL::TextureType2D);
pTextureDesc->setStorageMode(MTL::StorageModeManaged);
pTextureDesc->setUsage(MTL::ResourceUsageSample | MTL::ResourceUsageRead);
MTL::Texture* pTexture = mDevice->newTexture(pTextureDesc);
const MTL::Region region = MTL::Region::Make3D(0, 0, 0, texWidth, texHeight, 1);
pTexture->replaceRegion(region, 0, data, 4ull * texWidth);
pTextureDesc->release();
return pTexture;
}
void MetalRender::createMetalMaterials()
{
using simd::float3;
const std::vector<Scene::MaterialDescription>& matDescs = mScene->getMaterials();
std::vector<Material> gpuMaterials;
const fs::path resourcePath = getSharedContext().mSettingsManager->getAs<std::string>("resource/searchPath");
for (const Scene::MaterialDescription& currMatDesc : matDescs)
{
Material material = {};
material.diffuse = { 1.0f, 1.0f, 1.0f };
for (const auto& param : currMatDesc.params)
{
if (param.name == "diffuse_color" || param.name == "diffuseColor" || param.name == "diffuse_color_constant")
{
memcpy(&material.diffuse, param.value.data(), sizeof(float) * 3);
}
if (param.type == MaterialManager::Param::Type::eTexture)
{
std::string texPath(param.value.size(), 0);
memcpy(texPath.data(), param.value.data(), param.value.size());
const fs::path fullTextureFilePath = resourcePath / texPath;
if (param.name == "diffuse_texture")
{
MTL::Texture* diffuseTex = loadTextureFromFile(fullTextureFilePath.string());
mMaterialTextures.push_back(diffuseTex);
material.diffuseTexture = diffuseTex->gpuResourceID();
}
if (param.name == "normalmap_texture")
{
MTL::Texture* normalTex = loadTextureFromFile(fullTextureFilePath.string());
mMaterialTextures.push_back(normalTex);
material.normalTexture = normalTex->gpuResourceID();
}
}
}
gpuMaterials.push_back(material);
}
const size_t materialsDataSize = sizeof(Material) * gpuMaterials.size();
mMaterialBuffer = mDevice->newBuffer(materialsDataSize, MTL::ResourceStorageModeManaged);
memcpy(mMaterialBuffer->contents(), gpuMaterials.data(), materialsDataSize);
mMaterialBuffer->didModifyRange(NS::Range::Make(0, mMaterialBuffer->length()));
}
void MetalRender::render(Buffer* output)
{
using simd::float3;
using simd::float4;
using simd::float4x4;
NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init();
if (getSharedContext().mFrameNumber == 0)
{
buildBuffers();
createMetalMaterials();
createAccelerationStructures();
// create accum buffer, we don't need cpu access, make it device only
mAccumulationBuffer = mDevice->newBuffer(
output->width() * output->height() * output->getElementSize(), MTL::ResourceStorageModePrivate);
}
mFrameIndex = (mFrameIndex + 1) % kMaxFramesInFlight;
// Update camera state:
const uint32_t width = output->width();
const uint32_t height = output->height();
oka::Camera& camera = mScene->getCamera(1);
camera.updateAspectRatio(width / (float)height);
camera.updateViewMatrix();
View currView = {};
currView.mCamMatrices = camera.matrices;
if (glm::any(glm::notEqual(currView.mCamMatrices.perspective, mPrevView.mCamMatrices.perspective)) ||
glm::any(glm::notEqual(currView.mCamMatrices.view, mPrevView.mCamMatrices.view)))
{
// need reset
getSharedContext().mSubframeIndex = 0;
}
SettingsManager& settings = *getSharedContext().mSettingsManager;
MTL::Buffer* pUniformBuffer = mUniformBuffers[mFrameIndex];
MTL::Buffer* pUniformTMBuffer = mUniformTMBuffers[mFrameIndex];
Uniforms* pUniformData = reinterpret_cast<Uniforms*>(pUniformBuffer->contents());
UniformsTonemap* pUniformTonemap = reinterpret_cast<UniformsTonemap*>(pUniformTMBuffer->contents());
pUniformData->frameIndex = mFrameIndex;
pUniformData->subframeIndex = getSharedContext().mSubframeIndex;
pUniformData->height = height;
pUniformData->width = width;
pUniformData->numLights = mScene->getLightsDesc().size();
pUniformData->samples_per_launch = settings.getAs<uint32_t>("render/pt/spp");
pUniformData->enableAccumulation = (uint32_t)settings.getAs<bool>("render/pt/enableAcc");
pUniformData->missColor = float3(0.0f);
pUniformData->maxDepth = settings.getAs<uint32_t>("render/pt/depth");
pUniformData->debug = settings.getAs<uint32_t>("render/pt/debug");
pUniformTonemap->width = width;
pUniformTonemap->height = height;
pUniformTonemap->tonemapperType = settings.getAs<uint32_t>("render/pt/tonemapperType");
pUniformTonemap->gamma = settings.getAs<float>("render/post/gamma");
bool settingsChanged = false;
static uint32_t rectLightSamplingMethodPrev = 0;
pUniformData->rectLightSamplingMethod = settings.getAs<uint32_t>("render/pt/rectLightSamplingMethod");
settingsChanged = (rectLightSamplingMethodPrev != pUniformData->rectLightSamplingMethod);
rectLightSamplingMethodPrev = pUniformData->rectLightSamplingMethod;
static bool enableAccumulationPrev = false;
const bool enableAccumulation = settings.getAs<bool>("render/pt/enableAcc");
settingsChanged |= (enableAccumulationPrev != enableAccumulation);
enableAccumulationPrev = enableAccumulation;
static uint32_t sspTotalPrev = 0;
const uint32_t sspTotal = settings.getAs<uint32_t>("render/pt/sppTotal");
settingsChanged |= (sspTotalPrev > sspTotal); // reset only if new spp less than already accumulated
sspTotalPrev = sspTotal;
if (settingsChanged)
{
getSharedContext().mSubframeIndex = 0;
}
glm::float4x4 invView = glm::inverse(camera.matrices.view);
for (int column = 0; column < 4; column++)
{
for (int row = 0; row < 4; row++)
{
pUniformData->viewToWorld.columns[column][row] = invView[column][row];
}
}
for (int column = 0; column < 4; column++)
{
for (int row = 0; row < 4; row++)
{
pUniformData->clipToView.columns[column][row] = camera.matrices.invPerspective[column][row];
}
}
pUniformData->subframeIndex = getSharedContext().mSubframeIndex;
// Photometric Units from iray documentation
// Controls the sensitivity of the “camera film” and is expressed as an index; the ISO number of the film, also
// known as “film speed.” The higher this value, the greater the exposure. If this is set to a non-zero value,
// “Photographic” mode is enabled. If this is set to 0, “Arbitrary” mode is enabled, and all color scaling is then
// strictly defined by the value of cm^2 Factor.
float filmIso = settings.getAs<float>("render/post/tonemapper/filmIso");
// The candela per meter square factor
float cm2_factor = settings.getAs<float>("render/post/tonemapper/cm2_factor");
// The fractional aperture number; e.g., 11 means aperture “f/11.” It adjusts the size of the opening of the “camera
// iris” and is expressed as a ratio. The higher this value, the lower the exposure.
float fStop = settings.getAs<float>("render/post/tonemapper/fStop");
// Controls the duration, in fractions of a second, that the “shutter” is open; e.g., the value 100 means that the
// “shutter” is open for 1/100th of a second. The higher this value, the greater the exposure
float shutterSpeed = settings.getAs<float>("render/post/tonemapper/shutterSpeed");
// Specifies the main color temperature of the light sources; the color that will be mapped to “white” on output,
// e.g., an incoming color of this hue/saturation will be mapped to grayscale, but its intensity will remain
// unchanged. This is similar to white balance controls on digital cameras.
float3 whitePoint{ 1.0f, 1.0f, 1.0f };
auto all = [](float3 v) { return v.x > 0.0f && v.y > 0.0f && v.z > 0.0f; };
float3 exposureValue = all(whitePoint) ? 1.0f / whitePoint : float3(1.0f);
const float lum = simd::dot(exposureValue, float3{ 0.299f, 0.587f, 0.114f });
if (filmIso > 0.0f)
{
// See https://www.nayuki.io/page/the-photographic-exposure-equation
exposureValue *= cm2_factor * filmIso / (shutterSpeed * fStop * fStop) / 100.0f;
}
else
{
exposureValue *= cm2_factor;
}
exposureValue /= lum;
pUniformTonemap->exposureValue = exposureValue;
pUniformData->exposureValue = exposureValue; // need for proper accumulation
const uint32_t totalSpp = settings.getAs<uint32_t>("render/pt/sppTotal");
const uint32_t samplesPerLaunch = settings.getAs<uint32_t>("render/pt/spp");
const int32_t leftSpp = totalSpp - getSharedContext().mSubframeIndex;
// if accumulation is off then launch selected samples per pixel
const uint32_t samplesThisLaunch =
enableAccumulation ? std::min((int32_t)samplesPerLaunch, leftSpp) : samplesPerLaunch;
if (samplesThisLaunch != 0)
{
pUniformData->samples_per_launch = samplesThisLaunch;
pUniformBuffer->didModifyRange(NS::Range::Make(0, sizeof(Uniforms)));
pUniformTMBuffer->didModifyRange(NS::Range::Make(0, sizeof(UniformsTonemap)));
MTL::CommandBuffer* pCmd = mCommandQueue->commandBuffer();
MTL::ComputeCommandEncoder* pComputeEncoder = pCmd->computeCommandEncoder();
pComputeEncoder->useResource(mMaterialBuffer, MTL::ResourceUsageRead);
pComputeEncoder->useResource(mLightBuffer, MTL::ResourceUsageRead);
pComputeEncoder->useResource(mInstanceAccelerationStructure, MTL::ResourceUsageRead);
for (const MTL::AccelerationStructure* primitiveAccel : mPrimitiveAccelerationStructures)
{
pComputeEncoder->useResource(primitiveAccel, MTL::ResourceUsageRead);
}
for (auto& materialTexture : mMaterialTextures)
{
pComputeEncoder->useResource(materialTexture, MTL::ResourceUsageRead);
}
pComputeEncoder->useResource(((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageWrite);
pComputeEncoder->setComputePipelineState(mPathTracingPSO);
pComputeEncoder->setBuffer(pUniformBuffer, 0, 0);
pComputeEncoder->setBuffer(mInstanceBuffer, 0, 1);
pComputeEncoder->setAccelerationStructure(mInstanceAccelerationStructure, 2);
pComputeEncoder->setBuffer(mLightBuffer, 0, 3);
pComputeEncoder->setBuffer(mMaterialBuffer, 0, 4);
// Output
pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 5);
pComputeEncoder->setBuffer(mAccumulationBuffer, 0, 6);
{
const MTL::Size gridSize = MTL::Size(width, height, 1);
const NS::UInteger threadGroupSize = mPathTracingPSO->maxTotalThreadsPerThreadgroup();
const MTL::Size threadgroupSize(threadGroupSize, 1, 1);
pComputeEncoder->dispatchThreads(gridSize, threadgroupSize);
}
// Disable tonemapping for debug output
if (pUniformData->debug == 0)
{
pComputeEncoder->setComputePipelineState(mTonemapperPSO);
pComputeEncoder->useResource(
((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageRead | MTL::ResourceUsageWrite);
pComputeEncoder->setBuffer(pUniformTMBuffer, 0, 0);
pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 1);
{
const MTL::Size gridSize = MTL::Size(width, height, 1);
const NS::UInteger threadGroupSize = mTonemapperPSO->maxTotalThreadsPerThreadgroup();
const MTL::Size threadgroupSize(threadGroupSize, 1, 1);
pComputeEncoder->dispatchThreads(gridSize, threadgroupSize);
}
}
pComputeEncoder->endEncoding();
pCmd->commit();
pCmd->waitUntilCompleted();
if (enableAccumulation)
{
getSharedContext().mSubframeIndex += samplesThisLaunch;
}
else
{
getSharedContext().mSubframeIndex = 0;
}
}
else
{
MTL::CommandBuffer* pCmd = mCommandQueue->commandBuffer();
MTL::BlitCommandEncoder* pBlitEncoder = pCmd->blitCommandEncoder();
pBlitEncoder->copyFromBuffer(
mAccumulationBuffer, 0, ((MetalBuffer*)output)->getNativePtr(), 0, width * height * sizeof(float4));
pBlitEncoder->endEncoding();
// Disable tonemapping for debug output
if (pUniformData->debug == 0)
{
MTL::ComputeCommandEncoder* pComputeEncoder = pCmd->computeCommandEncoder();
pComputeEncoder->setComputePipelineState(mTonemapperPSO);
pComputeEncoder->useResource(
((MetalBuffer*)output)->getNativePtr(), MTL::ResourceUsageRead | MTL::ResourceUsageWrite);
pComputeEncoder->setBuffer(pUniformTMBuffer, 0, 0);
pComputeEncoder->setBuffer(((MetalBuffer*)output)->getNativePtr(), 0, 1);
{
const MTL::Size gridSize = MTL::Size(width, height, 1);
const NS::UInteger threadGroupSize = mTonemapperPSO->maxTotalThreadsPerThreadgroup();
const MTL::Size threadgroupSize(threadGroupSize, 1, 1);
pComputeEncoder->dispatchThreads(gridSize, threadgroupSize);
}
pComputeEncoder->endEncoding();
}
pCmd->commit();
pCmd->waitUntilCompleted();
}
pPool->release();
mPrevView = currView;
getSharedContext().mFrameNumber++;
}
Buffer* MetalRender::createBuffer(const BufferDesc& desc)
{
assert(mDevice);
const size_t size = desc.height * desc.width * Buffer::getElementSize(desc.format);
assert(size != 0);
MTL::Buffer* buff = mDevice->newBuffer(size, MTL::ResourceStorageModeManaged);
assert(buff);
MetalBuffer* res = new MetalBuffer(buff, desc.format, desc.width, desc.height);
assert(res);
return res;
}
void MetalRender::buildComputePipeline()
{
NS::Error* pError = nullptr;
MTL::Library* pComputeLibrary =
mDevice->newLibrary(NS::String::string("./metal/shaders/pathtrace.metallib", NS::UTF8StringEncoding), &pError);
if (!pComputeLibrary)
{
STRELKA_FATAL("{}", pError->localizedDescription()->utf8String());
assert(false);
}
MTL::Function* pPathTraceFn =
pComputeLibrary->newFunction(NS::String::string("raytracingKernel", NS::UTF8StringEncoding));
mPathTracingPSO = mDevice->newComputePipelineState(pPathTraceFn, &pError);
if (!mPathTracingPSO)
{
STRELKA_FATAL("{}", pError->localizedDescription()->utf8String());
assert(false);
}
pPathTraceFn->release();
pComputeLibrary->release();
}
void MetalRender::buildTonemapperPipeline()
{
NS::Error* pError = nullptr;
MTL::Library* pComputeLibrary =
mDevice->newLibrary(NS::String::string("./metal/shaders/tonemapper.metallib", NS::UTF8StringEncoding), &pError);
if (!pComputeLibrary)
{
STRELKA_FATAL("{}", pError->localizedDescription()->utf8String());
assert(false);
}
MTL::Function* pTonemapperFn =
pComputeLibrary->newFunction(NS::String::string("toneMappingComputeShader", NS::UTF8StringEncoding));
mTonemapperPSO = mDevice->newComputePipelineState(pTonemapperFn, &pError);
if (!mTonemapperPSO)
{
STRELKA_FATAL("{}", pError->localizedDescription()->utf8String());
assert(false);
}
pTonemapperFn->release();
pComputeLibrary->release();
}
void MetalRender::buildBuffers()
{
const std::vector<Scene::Vertex>& vertices = mScene->getVertices();
const std::vector<uint32_t>& indices = mScene->getIndices();
const std::vector<Scene::Light>& lightDescs = mScene->getLights();
static_assert(sizeof(Scene::Light) == sizeof(UniformLight));
const size_t lightBufferSize = sizeof(Scene::Light) * lightDescs.size();
const size_t vertexDataSize = sizeof(Scene::Vertex) * vertices.size();
const size_t indexDataSize = sizeof(uint32_t) * indices.size();
MTL::Buffer* pLightBuffer = mDevice->newBuffer(lightBufferSize, MTL::ResourceStorageModeManaged);
MTL::Buffer* pVertexBuffer = mDevice->newBuffer(vertexDataSize, MTL::ResourceStorageModeManaged);
MTL::Buffer* pIndexBuffer = mDevice->newBuffer(indexDataSize, MTL::ResourceStorageModeManaged);
mLightBuffer = pLightBuffer;
mVertexBuffer = pVertexBuffer;
mIndexBuffer = pIndexBuffer;
memcpy(mLightBuffer->contents(), lightDescs.data(), lightBufferSize);
memcpy(mVertexBuffer->contents(), vertices.data(), vertexDataSize);
memcpy(mIndexBuffer->contents(), indices.data(), indexDataSize);
mLightBuffer->didModifyRange(NS::Range::Make(0, mLightBuffer->length()));
mVertexBuffer->didModifyRange(NS::Range::Make(0, mVertexBuffer->length()));
mIndexBuffer->didModifyRange(NS::Range::Make(0, mIndexBuffer->length()));
for (MTL::Buffer*& uniformBuffer : mUniformBuffers)
{
uniformBuffer = mDevice->newBuffer(sizeof(Uniforms), MTL::ResourceStorageModeManaged);
}
for (MTL::Buffer*& uniformBuffer : mUniformTMBuffers)
{
uniformBuffer = mDevice->newBuffer(sizeof(UniformsTonemap), MTL::ResourceStorageModeManaged);
}
}
MTL::AccelerationStructure* MetalRender::createAccelerationStructure(MTL::AccelerationStructureDescriptor* descriptor)
{
NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init();
// Query for the sizes needed to store and build the acceleration structure.
const MTL::AccelerationStructureSizes accelSizes = mDevice->accelerationStructureSizes(descriptor);
// Allocate an acceleration structure large enough for this descriptor. This doesn't actually
// build the acceleration structure, it just allocates memory.
MTL::AccelerationStructure* accelerationStructure =
mDevice->newAccelerationStructure(accelSizes.accelerationStructureSize);
// Allocate scratch space Metal uses to build the acceleration structure.
// Use MTLResourceStorageModePrivate for best performance because the sample
// doesn't need access to the buffer's contents.
MTL::Buffer* scratchBuffer = mDevice->newBuffer(accelSizes.buildScratchBufferSize, MTL::ResourceStorageModePrivate);
// Create a command buffer to perform the acceleration structure build.
MTL::CommandBuffer* commandBuffer = mCommandQueue->commandBuffer();
// Create an acceleration structure command encoder.
MTL::AccelerationStructureCommandEncoder* commandEncoder = commandBuffer->accelerationStructureCommandEncoder();
// Allocate a buffer for Metal to write the compacted accelerated structure's size into.
MTL::Buffer* compactedSizeBuffer = mDevice->newBuffer(sizeof(uint32_t), MTL::ResourceStorageModeShared);
// Schedule the actual acceleration structure build.
commandEncoder->buildAccelerationStructure(accelerationStructure, descriptor, scratchBuffer, 0UL);
// Compute and write the compacted acceleration structure size into the buffer. You
// need to already have a built accelerated structure because Metal determines the compacted
// size based on the final size of the acceleration structure. Compacting an acceleration
// structure can potentially reclaim significant amounts of memory because Metal must
// create the initial structure using a conservative approach.
commandEncoder->writeCompactedAccelerationStructureSize(accelerationStructure, compactedSizeBuffer, 0UL);
// End encoding and commit the command buffer so the GPU can start building the
// acceleration structure.
commandEncoder->endEncoding();
commandBuffer->commit();
// The sample waits for Metal to finish executing the command buffer so that it can
// read back the compacted size.
// Note: Don't wait for Metal to finish executing the command buffer if you aren't compacting
// the acceleration structure because doing so requires CPU/GPU synchronization. You don't have
// to compact acceleration structures, but it's helpful when creating large static acceleration
// structures, such as static scene geometry. Avoid compacting acceleration structures that
// you rebuild every frame because the synchronization cost may be significant.
commandBuffer->waitUntilCompleted();
const uint32_t compactedSize = *(uint32_t*)compactedSizeBuffer->contents();
// commandBuffer->release();
// commandEncoder->release();
// Allocate a smaller acceleration structure based on the returned size.
MTL::AccelerationStructure* compactedAccelerationStructure = mDevice->newAccelerationStructure(compactedSize);
// Create another command buffer and encoder.
commandBuffer = mCommandQueue->commandBuffer();
commandEncoder = commandBuffer->accelerationStructureCommandEncoder();
// Encode the command to copy and compact the acceleration structure into the
// smaller acceleration structure.
commandEncoder->copyAndCompactAccelerationStructure(accelerationStructure, compactedAccelerationStructure);
// End encoding and commit the command buffer. You don't need to wait for Metal to finish
// executing this command buffer as long as you synchronize any ray-intersection work
// to run after this command buffer completes. The sample relies on Metal's default
// dependency tracking on resources to automatically synchronize access to the new
// compacted acceleration structure.
commandEncoder->endEncoding();
commandBuffer->commit();
// commandEncoder->release();
// commandBuffer->release();
accelerationStructure->release();
scratchBuffer->release();
compactedSizeBuffer->release();
pPool->release();
return compactedAccelerationStructure->retain();
}
constexpr simd_float4x4 makeIdentity()
{
using simd::float4;
return (simd_float4x4){ (float4){ 1.f, 0.f, 0.f, 0.f }, (float4){ 0.f, 1.f, 0.f, 0.f },
(float4){ 0.f, 0.f, 1.f, 0.f }, (float4){ 0.f, 0.f, 0.f, 1.f } };
}
MetalRender::Mesh* MetalRender::createMesh(const oka::Mesh& mesh)
{
MetalRender::Mesh* result = new MetalRender::Mesh();
const uint32_t triangleCount = mesh.mCount / 3;
const std::vector<Scene::Vertex>& vertices = mScene->getVertices();
const std::vector<uint32_t>& indices = mScene->getIndices();
std::vector<Triangle> triangleData(triangleCount);
for (int i = 0; i < triangleCount; ++i)
{
Triangle& curr = triangleData[i];
const uint32_t i0 = indices[mesh.mIndex + i * 3 + 0];
const uint32_t i1 = indices[mesh.mIndex + i * 3 + 1];
const uint32_t i2 = indices[mesh.mIndex + i * 3 + 2];
// Positions
using simd::float3;
curr.positions[0] = { vertices[mesh.mVbOffset + i0].pos.x, vertices[mesh.mVbOffset + i0].pos.y,
vertices[mesh.mVbOffset + i0].pos.z };
curr.positions[1] = { vertices[mesh.mVbOffset + i1].pos.x, vertices[mesh.mVbOffset + i1].pos.y,
vertices[mesh.mVbOffset + i1].pos.z };
curr.positions[2] = { vertices[mesh.mVbOffset + i2].pos.x, vertices[mesh.mVbOffset + i2].pos.y,
vertices[mesh.mVbOffset + i2].pos.z };
// Normals
curr.normals[0] = vertices[mesh.mVbOffset + i0].normal;
curr.normals[1] = vertices[mesh.mVbOffset + i1].normal;
curr.normals[2] = vertices[mesh.mVbOffset + i2].normal;
// Tangents
curr.tangent[0] = vertices[mesh.mVbOffset + i0].tangent;
curr.tangent[1] = vertices[mesh.mVbOffset + i1].tangent;
curr.tangent[2] = vertices[mesh.mVbOffset + i2].tangent;
// UVs
curr.uv[0] = vertices[mesh.mVbOffset + i0].uv;
curr.uv[1] = vertices[mesh.mVbOffset + i1].uv;
curr.uv[2] = vertices[mesh.mVbOffset + i2].uv;
}
MTL::Buffer* perPrimitiveBuffer =
mDevice->newBuffer(triangleData.size() * sizeof(Triangle), MTL::ResourceStorageModeManaged);
memcpy(perPrimitiveBuffer->contents(), triangleData.data(), sizeof(Triangle) * triangleData.size());
perPrimitiveBuffer->didModifyRange(NS::Range(0, perPrimitiveBuffer->length()));
MTL::AccelerationStructureTriangleGeometryDescriptor* geomDescriptor =
MTL::AccelerationStructureTriangleGeometryDescriptor::alloc()->init();
geomDescriptor->setVertexBuffer(mVertexBuffer);
geomDescriptor->setVertexBufferOffset(mesh.mVbOffset * sizeof(Scene::Vertex));
geomDescriptor->setVertexStride(sizeof(Scene::Vertex));
geomDescriptor->setIndexBuffer(mIndexBuffer);
geomDescriptor->setIndexBufferOffset(mesh.mIndex * sizeof(uint32_t));
geomDescriptor->setIndexType(MTL::IndexTypeUInt32);
geomDescriptor->setTriangleCount(triangleCount);
// Setup per primitive data
geomDescriptor->setPrimitiveDataBuffer(perPrimitiveBuffer);
geomDescriptor->setPrimitiveDataBufferOffset(0);
geomDescriptor->setPrimitiveDataElementSize(sizeof(Triangle));
geomDescriptor->setPrimitiveDataStride(sizeof(Triangle));
const NS::Array* geomDescriptors = NS::Array::array((const NS::Object* const*)&geomDescriptor, 1UL);
MTL::PrimitiveAccelerationStructureDescriptor* primDescriptor =
MTL::PrimitiveAccelerationStructureDescriptor::alloc()->init();
primDescriptor->setGeometryDescriptors(geomDescriptors);
result->mGas = createAccelerationStructure(primDescriptor);
primDescriptor->release();
geomDescriptor->release();
perPrimitiveBuffer->release();
return result;
}
void MetalRender::createAccelerationStructures()
{
NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init();
const std::vector<oka::Mesh>& meshes = mScene->getMeshes();
const std::vector<oka::Curve>& curves = mScene->getCurves();
const std::vector<oka::Instance>& instances = mScene->getInstances();
if (meshes.empty() && curves.empty())
{
return;
}
for (const oka::Mesh& currMesh : meshes)
{
MetalRender::Mesh* metalMesh = createMesh(currMesh);
mMetalMeshes.push_back(metalMesh);
mPrimitiveAccelerationStructures.push_back(metalMesh->mGas);
}
mInstanceBuffer = mDevice->newBuffer(
sizeof(MTL::AccelerationStructureUserIDInstanceDescriptor) * instances.size(), MTL::ResourceStorageModeManaged);
MTL::AccelerationStructureUserIDInstanceDescriptor* instanceDescriptors =
(MTL::AccelerationStructureUserIDInstanceDescriptor*)mInstanceBuffer->contents();
for (int i = 0; i < instances.size(); ++i)
{
const Instance& curr = instances[i];
instanceDescriptors[i].accelerationStructureIndex = curr.mMeshId;
instanceDescriptors[i].options = MTL::AccelerationStructureInstanceOptionOpaque;
instanceDescriptors[i].intersectionFunctionTableOffset = 0;
instanceDescriptors[i].userID = curr.type == Instance::Type::eLight ? curr.mLightId : curr.mMaterialId;
instanceDescriptors[i].mask = curr.type == Instance::Type::eLight ? GEOMETRY_MASK_LIGHT : GEOMETRY_MASK_TRIANGLE;
for (int column = 0; column < 4; column++)
{
for (int row = 0; row < 3; row++)
{
instanceDescriptors[i].transformationMatrix.columns[column][row] = curr.transform[column][row];
}
}
}
mInstanceBuffer->didModifyRange(NS::Range::Make(0, mInstanceBuffer->length()));
const NS::Array* instancedAccelerationStructures = NS::Array::array(
(const NS::Object* const*)mPrimitiveAccelerationStructures.data(), mPrimitiveAccelerationStructures.size());
MTL::InstanceAccelerationStructureDescriptor* accelDescriptor =
MTL::InstanceAccelerationStructureDescriptor::descriptor();
accelDescriptor->setInstancedAccelerationStructures(instancedAccelerationStructures);
accelDescriptor->setInstanceCount(instances.size());
accelDescriptor->setInstanceDescriptorBuffer(mInstanceBuffer);
accelDescriptor->setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorTypeUserID);
mInstanceAccelerationStructure = createAccelerationStructure(accelDescriptor);
pPool->release();
}
|
arhix52/Strelka/src/render/metal/MetalRender.h | #pragma once
#include "render.h"
#include <Metal/Metal.hpp>
#include <MetalKit/MetalKit.hpp>
namespace oka
{
static constexpr size_t kMaxFramesInFlight = 3;
class MetalRender : public Render
{
public:
MetalRender(/* args */);
~MetalRender() override;
void init() override;
void render(Buffer* output) override;
Buffer* createBuffer(const BufferDesc& desc) override;
void* getNativeDevicePtr() override
{
return mDevice;
}
private:
struct Mesh
{
MTL::AccelerationStructure* mGas;
};
Mesh* createMesh(const oka::Mesh& mesh);
struct View
{
oka::Camera::Matrices mCamMatrices;
};
View mPrevView;
MTL::Device* mDevice;
MTL::CommandQueue* mCommandQueue;
MTL::Library* mShaderLibrary;
MTL::ComputePipelineState* mPathTracingPSO;
MTL::ComputePipelineState* mTonemapperPSO;
MTL::Buffer* mAccumulationBuffer;
MTL::Buffer* mLightBuffer;
MTL::Buffer* mVertexBuffer;
MTL::Buffer* mUniformBuffers[kMaxFramesInFlight];
MTL::Buffer* mUniformTMBuffers[kMaxFramesInFlight];
MTL::Buffer* mIndexBuffer;
uint32_t mTriangleCount;
std::vector<MetalRender::Mesh*> mMetalMeshes;
std::vector<MTL::AccelerationStructure*> mPrimitiveAccelerationStructures;
MTL::AccelerationStructure* mInstanceAccelerationStructure;
MTL::Buffer* mInstanceBuffer;
MTL::Buffer* mMaterialBuffer;
std::vector<MTL::Texture*> mMaterialTextures;
uint32_t mFrameIndex;
void buildComputePipeline();
void buildTonemapperPipeline();
void buildBuffers();
MTL::Texture* loadTextureFromFile(const std::string& fileName);
void createMetalMaterials();
MTL::AccelerationStructure* createAccelerationStructure(MTL::AccelerationStructureDescriptor* descriptor);
void createAccelerationStructures();
};
} // namespace oka
|
arhix52/Strelka/src/render/metal/shaders/random.h | #pragma once
#include <simd/simd.h>
using namespace metal;
float uintToFloat(uint x)
{
return as_type<float>(0x3f800000 | (x >> 9)) - 1.f;
}
enum class SampleDimension : uint32_t
{
ePixelX,
ePixelY,
eLightId,
eLightPointX,
eLightPointY,
eBSDF0,
eBSDF1,
eBSDF2,
eBSDF3,
eRussianRoulette,
eNUM_DIMENSIONS
};
struct SamplerState
{
uint32_t seed;
uint32_t sampleIdx;
uint32_t depth;
};
#define MAX_BOUNCES 128
// Based on: https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
inline unsigned pcg_hash(unsigned seed) {
unsigned state = seed * 747796405u + 2891336453u;
unsigned word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
return (word >> 22u) ^ word;
}
inline unsigned hash_with(unsigned seed, unsigned hash) {
// Wang hash
seed = (seed ^ 61) ^ hash;
seed += seed << 3;
seed ^= seed >> 4;
seed *= 0x27d4eb2d;
return seed;
}
// jenkins hash
unsigned int hash(unsigned int a)
{
a = (a + 0x7ED55D16) + (a << 12);
a = (a ^ 0xC761C23C) ^ (a >> 19);
a = (a + 0x165667B1) + (a << 5);
a = (a + 0xD3A2646C) ^ (a << 9);
a = (a + 0xFD7046C5) + (a << 3);
a = (a ^ 0xB55A4F09) ^ (a >> 16);
return a;
}
uint32_t hash2(uint32_t x, uint32_t seed)
{
x ^= x * 0x3d20adea;
x += seed;
x *= (seed >> 16) | 1;
x ^= x * 0x05526c56;
x ^= x * 0x53a22864;
return x;
}
uint jenkinsHash(uint x)
{
x += x << 10;
x ^= x >> 6;
x += x << 3;
x ^= x >> 11;
x += x << 15;
return x;
}
constant unsigned int primeNumbers[32] =
{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131
};
float halton(uint32_t index, uint32_t base)
{
const float s = 1.0f / float(base);
unsigned int i = index;
float result = 0.0f;
float f = s;
while (i)
{
const unsigned int digit = i % base;
result += f * float(digit);
i = (i - digit) / base;
f *= s;
}
return clamp(result, 0.0f, 1.0f - 1e-6f); // TODO: 1minusEps
}
static SamplerState initSampler(uint32_t linearPixelIndex, uint32_t pixelSampleIndex, uint32_t seed)
{
SamplerState sampler {};
sampler.seed = hash(linearPixelIndex); //^ 0x736caf6fu;
sampler.sampleIdx = pixelSampleIndex;
sampler.depth = 0;
return sampler;
}
template <SampleDimension Dim>
static float random(thread SamplerState& state)
{
const uint32_t dimension = uint32_t(Dim) + state.depth * uint32_t(SampleDimension::eNUM_DIMENSIONS);
const uint32_t base = primeNumbers[dimension & 31u];
return halton(state.seed + state.sampleIdx, base);
}
uint xorshift(thread uint& rngState)
{
rngState ^= rngState << 13;
rngState ^= rngState >> 17;
rngState ^= rngState << 5;
return rngState;
}
template<unsigned int N>
static __inline__ unsigned int tea( unsigned int val0, unsigned int val1 )
{
unsigned int v0 = val0;
unsigned int v1 = val1;
unsigned int s0 = 0;
for( unsigned int n = 0; n < N; n++ )
{
s0 += 0x9e3779b9;
v0 += ((v1<<4)+0xa341316c)^(v1+s0)^((v1>>5)+0xc8013ea4);
v1 += ((v0<<4)+0xad90777d)^(v0+s0)^((v0>>5)+0x7e95761e);
}
return v0;
}
// Generate random unsigned int in [0, 2^24)
static __inline__ unsigned int lcg(thread unsigned int &prev)
{
const unsigned int LCG_A = 1664525u;
const unsigned int LCG_C = 1013904223u;
prev = (LCG_A * prev + LCG_C);
return prev & 0x00FFFFFF;
}
static __inline__ unsigned int lcg2(thread unsigned int &prev)
{
prev = (prev*8121 + 28411) % 134456;
return prev;
}
// Generate random float in [0, 1)
static __inline__ float rnd(thread unsigned int &prev)
{
return ((float) lcg(prev) / (float) 0x01000000);
}
static __inline__ unsigned int rot_seed( unsigned int seed, unsigned int frame )
{
return seed ^ frame;
}
// Implementetion from Ray Tracing gems
// https://github.com/boksajak/referencePT/blob/master/shaders/PathTracer.hlsl
uint initRNG(uint2 pixelCoords, uint2 resolution, uint frameNumber)
{
uint t = dot(float2(pixelCoords), float2(1, resolution.x));
uint seed = t ^ jenkinsHash(frameNumber);
// uint seed = dot(pixelCoords, uint2(1, resolution.x)) ^ jenkinsHash(frameNumber);
return jenkinsHash(seed);
}
uint owen_scramble_rev(uint x, uint seed)
{
x ^= x * 0x3d20adea;
x += seed;
x *= (seed >> 16) | 1;
x ^= x * 0x05526c56;
x ^= x * 0x53a22864;
return x;
}
|
arhix52/Strelka/src/render/metal/shaders/lights.h | #pragma once
#include <metal_stdlib>
#include <simd/simd.h>
#include "ShaderTypes.h"
using namespace metal;
struct LightSampleData
{
float3 pointOnLight;
float pdf;
float3 normal;
float area;
float3 L;
float distToLight;
};
__inline__ float misWeightBalance(const float a, const float b)
{
return 1.0f / ( 1.0f + (b / a) );
}
static float calcLightArea(device const UniformLight& l)
{
float area = 0.0f;
if (l.type == 0) // rectangle area
{
float3 e1 = float3(l.points[1]) - float3(l.points[0]);
float3 e2 = float3(l.points[3]) - float3(l.points[0]);
area = length(cross(e1, e2));
}
else if (l.type == 1) // disc area
{
area = l.points[0].x * l.points[0].x * M_PI_F; // pi * radius^2
}
else if (l.type == 2) // sphere area
{
area = l.points[0].x * l.points[0].x * 4.0f * M_PI_F; // 4 * pi * radius^2
}
return area;
}
static float3 calcLightNormal(device const UniformLight& l, thread const float3& hitPoint)
{
float3 norm = float3(0.0f);
if (l.type == 0)
{
float3 e1 = float3(l.points[1]) - float3(l.points[0]);
float3 e2 = float3(l.points[3]) - float3(l.points[0]);
norm = -normalize(cross(e1, e2));
}
else if (l.type == 1)
{
norm = float3(l.normal);
}
else if (l.type == 2)
{
norm = normalize(hitPoint - float3(l.points[1]));
}
return norm;
}
static void fillLightData(device const UniformLight& l, thread const float3& hitPoint, thread LightSampleData& lightSampleData)
{
lightSampleData.area = calcLightArea(l);
lightSampleData.normal = calcLightNormal(l, hitPoint);
const float3 toLight = lightSampleData.pointOnLight - hitPoint;
const float lenToLight = length(toLight);
lightSampleData.L = toLight / lenToLight;
lightSampleData.distToLight = lenToLight;
}
struct SphQuad
{
float3 o, x, y, z;
float z0, z0sq;
float x0, y0, y0sq; // rectangle coords in ’R’
float x1, y1, y1sq;
float b0, b1, b0sq, k;
float S;
};
// Precomputation of constants for the spherical rectangle Q.
static SphQuad init(device const UniformLight& l, const float3 o)
{
SphQuad squad;
float3 ex = float3(l.points[1]) - float3(l.points[0]);
float3 ey = float3(l.points[3]) - float3(l.points[0]);
float3 s = float3(l.points[0]);
float exl = length(ex);
float eyl = length(ey);
squad.o = o;
squad.x = ex / exl;
squad.y = ey / eyl;
squad.z = cross(squad.x, squad.y);
// compute rectangle coords in local reference system
float3 d = s - o;
squad.z0 = dot(d, squad.z);
// flip ’z’ to make it point against ’Q’
if (squad.z0 > 0.0f)
{
squad.z *= -1.0f;
squad.z0 *= -1.0f;
}
squad.z0sq = squad.z0 * squad.z0;
squad.x0 = dot(d, squad.x);
squad.y0 = dot(d, squad.y);
squad.x1 = squad.x0 + exl;
squad.y1 = squad.y0 + eyl;
squad.y0sq = squad.y0 * squad.y0;
squad.y1sq = squad.y1 * squad.y1;
// create vectors to four vertices
float3 v00 = { squad.x0, squad.y0, squad.z0 };
float3 v01 = { squad.x0, squad.y1, squad.z0 };
float3 v10 = { squad.x1, squad.y0, squad.z0 };
float3 v11 = { squad.x1, squad.y1, squad.z0 };
// compute normals to edges
float3 n0 = normalize(cross(v00, v10));
float3 n1 = normalize(cross(v10, v11));
float3 n2 = normalize(cross(v11, v01));
float3 n3 = normalize(cross(v01, v00));
// compute internal angles (gamma_i)
float g0 = fast::acos(-dot(n0, n1));
float g1 = fast::acos(-dot(n1, n2));
float g2 = fast::acos(-dot(n2, n3));
float g3 = fast::acos(-dot(n3, n0));
// compute predefined constants
squad.b0 = n0.z;
squad.b1 = n2.z;
squad.b0sq = squad.b0 * squad.b0;
const float twoPi = 2.0f * M_PI_F;
squad.k = twoPi - g2 - g3;
// compute solid angle from internal angles
squad.S = g0 + g1 - squad.k;
return squad;
}
static float3 SphQuadSample(const SphQuad squad, const float2 uv)
{
float u = uv.x;
float v = uv.y;
// 1. compute cu
float au = u * squad.S + squad.k;
float fu = (cos(au) * squad.b0 - squad.b1) / sin(au);
float cu = 1 / sqrt(fu * fu + squad.b0sq) * (fu > 0 ? 1 : -1);
cu = clamp(cu, -1.0f, 1.0f); // avoid NaNs
// 2. compute xu
float xu = -(cu * squad.z0) / sqrt(1 - cu * cu);
xu = clamp(xu, squad.x0, squad.x1); // avoid Infs
// 3. compute yv
float d = sqrt(xu * xu + squad.z0sq);
float h0 = squad.y0 / sqrt(d * d + squad.y0sq);
float h1 = squad.y1 / sqrt(d * d + squad.y1sq);
float hv = h0 + v * (h1 - h0);
float hv2 = hv * hv;
float eps = 1e-6f;
float yv = (hv2 < 1.0f - eps) ? (hv * d) / sqrt(1.0f - hv2) : squad.y1;
// 4. transform (xu, yv, z0) to world coords
return (squad.o + xu * squad.x + yv * squad.y + squad.z0 * squad.z);
}
static LightSampleData SampleRectLight(device const UniformLight& l, thread const float2& u, thread const float3& hitPoint)
{
LightSampleData lightSampleData;
float3 e1 = float3(l.points[1]) - float3(l.points[0]);
float3 e2 = float3(l.points[3]) - float3(l.points[0]);
// https://www.arnoldrenderer.com/research/egsr2013_spherical_rectangle.pdf
SphQuad quad = init(l, hitPoint);
if (quad.S <= 0.0f)
{
lightSampleData.pdf = 0.0f;
lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
return lightSampleData;
}
if (quad.S < 1e-3f)
{
// light too small, use uniform
lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData;
}
lightSampleData.pointOnLight = SphQuadSample(quad, u);
fillLightData(l, hitPoint, lightSampleData);
lightSampleData.pdf = max(0.0f, 1.0f / quad.S);
return lightSampleData;
}
static __inline__ LightSampleData SampleRectLightUniform(device const UniformLight& l, thread const float2& u, thread const float3& hitPoint)
{
LightSampleData lightSampleData;
// uniform sampling
float3 e1 = float3(l.points[1]) - float3(l.points[0]);
float3 e2 = float3(l.points[3]) - float3(l.points[0]);
lightSampleData.pointOnLight = float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData;
}
static __inline__ float getRectLightPdf(device const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint)
{
LightSampleData lightSampleData {};
lightSampleData.pointOnLight = lightHitPoint;
fillLightData(l, surfaceHitPoint, lightSampleData);
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData.pdf;
}
static void createCoordinateSystem(thread const float3& N, thread float3& Nt, thread float3& Nb) {
if (fabs(N.x) > fabs(N.y)) {
float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z);
Nt = float3(-N.z * invLen, 0.0f, N.x * invLen);
} else {
float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z);
Nt = float3(0.0f, N.z * invLen, -N.y * invLen);
}
Nb = cross(N, Nt);
}
static __inline__ float getDirectLightPdf(float angle)
{
return 1.0f / (2.0f * M_PI_F * (1.0f - cos(angle)));
}
static __inline__ float getSphereLightPdf()
{
return 1.0f / (4.0f * M_PI_F);
}
static float3 SampleCone(float2 uv, float angle, float3 direction, thread float& pdf) {
float phi = 2.0 * M_PI_F * uv.x;
float cosTheta = 1.0 - uv.y * (1.0 - cos(angle));
// Convert spherical coordinates to 3D direction
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
float3 u, v;
createCoordinateSystem(direction, u, v);
float3 sampledDir = normalize(cos(phi) * sinTheta * u + sin(phi) * sinTheta * v + cosTheta * direction);
// Calculate the PDF for the sampled direction
pdf = getDirectLightPdf(angle);
return sampledDir;
}
static __inline__ LightSampleData SampleDistantLight(device const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
float pdf = 0.0f;
float3 coneSample = SampleCone(u, l.halfAngle, -float3(l.normal), pdf);
lightSampleData.area = 0.0f;
lightSampleData.distToLight = 1e9;
lightSampleData.L = coneSample;
lightSampleData.normal = float3(l.normal);
lightSampleData.pdf = pdf;
lightSampleData.pointOnLight = coneSample;
return lightSampleData;
}
static __inline__ LightSampleData SampleSphereLight(device const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
// Generate a random direction on the sphere using solid angle sampling
float cosTheta = 1.0f - 2.0f * u.x; // cosTheta is uniformly distributed between [-1, 1]
float sinTheta = sqrt(1.0f - cosTheta * cosTheta);
float phi = 2.0f * M_PI_F * u.y; // phi is uniformly distributed between [0, 2*pi]
const float radius = l.points[0].x;
// Convert spherical coordinates to Cartesian coordinates
float3 sphereDirection = float3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);
// Scale the direction by the radius of the sphere and move it to the light position
float3 lightPoint = float3(l.points[1]) + radius * sphereDirection;
// Calculate the direction from the hit point to the sampled point on the light
lightSampleData.L = normalize(lightPoint - hitPoint);
// Calculate the distance to the light
lightSampleData.distToLight = length(lightPoint - hitPoint);
lightSampleData.area = 0.0f;
lightSampleData.normal = sphereDirection;
lightSampleData.pdf = 1.0f / (4.0f * M_PI_F);
lightSampleData.pointOnLight = lightPoint;
return lightSampleData;
}
static __inline__ float getLightPdf(device const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint)
{
switch (l.type)
{
case 0:
// Rect
return getRectLightPdf(l, lightHitPoint, surfaceHitPoint);
break;
case 2:
// sphere
return getSphereLightPdf();
break;
case 3:
// Distant
return getDirectLightPdf(l.halfAngle);
break;
default:
break;
}
return 0.0f;
}
|
arhix52/Strelka/src/render/metal/shaders/tonemappers.h | #pragma once
#include <simd/simd.h>
using namespace metal;
enum class ToneMapperType : uint32_t
{
eNone = 0,
eReinhard,
eACES,
eFilmic,
};
// https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl
// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
static constant float3x3 ACESInputMat =
{
{0.59719, 0.35458, 0.04823},
{0.07600, 0.90834, 0.01566},
{0.02840, 0.13383, 0.83777}
};
// ODT_SAT => XYZ => D60_2_D65 => sRGB
static constant float3x3 ACESOutputMat =
{
{ 1.60475, -0.53108, -0.07367},
{-0.10208, 1.10813, -0.00605},
{-0.00327, -0.07276, 1.07602}
};
float3 RRTAndODTFit(float3 v)
{
float3 a = v * (v + 0.0245786f) - 0.000090537f;
float3 b = v * (0.983729f * v + 0.4329510f) + 0.238081f;
return a / b;
}
float3 ACESFitted(float3 color)
{
color = transpose(ACESInputMat) * color;
// Apply RRT and ODT
color = RRTAndODTFit(color);
color = transpose(ACESOutputMat) * color;
// Clamp to [0, 1]
color = saturate(color);
return color;
}
// https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/
float3 ACESFilm(float3 x)
{
float a = 2.51f;
float b = 0.03f;
float c = 2.43f;
float d = 0.59f;
float e = 0.14f;
return saturate((x*(a*x+b))/(x*(c*x+d)+e));
}
// original implementation https://github.com/NVIDIAGameWorks/Falcor/blob/5236495554f57a734cc815522d95ae9a7dfe458a/Source/RenderPasses/ToneMapper/ToneMapping.ps.slang
float calcLuminance(float3 color)
{
return dot(color, float3(0.299, 0.587, 0.114));
}
float3 reinhard(float3 color)
{
float luminance = calcLuminance(color);
// float reinhard = luminance / (luminance + 1);
return color / (luminance + 1.0f);
}
float gammaFloat(const float c, const float gamma)
{
if (isnan(c))
{
return 0.0f;
}
if (c > 1.0f)
{
return 1.0f;
}
else if (c < 0.0f)
{
return 0.0f;
}
else if (c < 0.0031308f)
{
return 12.92f * c;
}
else
{
return 1.055f * pow(c, 1.0f / gamma) - 0.055f;
}
}
float3 srgbGamma(const float3 color, const float gamma)
{
return float3(gammaFloat(color.r, gamma), gammaFloat(color.g, gamma), gammaFloat(color.b, gamma));
}
// utility function for accumulation and HDR <=> LDR
float3 tonemap(float3 color, const float3 exposure)
{
color *= exposure;
return color / (color + 1.0f);
}
float3 inverseTonemap(const float3 color, const float3 exposure)
{
return color / (exposure - color * exposure);
}
|
arhix52/Strelka/src/render/metal/shaders/ShaderTypes.h | #ifndef ShaderTypes_h
#define ShaderTypes_h
#include <simd/simd.h>
#ifndef __METAL_VERSION__
#ifdef __cplusplus
#include <Metal/MTLTypes.hpp>
#endif
#endif
#define GEOMETRY_MASK_TRIANGLE 1
#define GEOMETRY_MASK_CURVE 2
#define GEOMETRY_MASK_LIGHT 4
#define GEOMETRY_MASK_GEOMETRY (GEOMETRY_MASK_TRIANGLE | GEOMETRY_MASK_CURVE)
#define RAY_MASK_PRIMARY (GEOMETRY_MASK_GEOMETRY | GEOMETRY_MASK_LIGHT)
#define RAY_MASK_SHADOW GEOMETRY_MASK_GEOMETRY
#define RAY_MASK_SECONDARY GEOMETRY_MASK_GEOMETRY
#ifndef __METAL_VERSION__
struct packed_float3
{
# ifdef __cplusplus
packed_float3() = default;
packed_float3(vector_float3 v) : x(v.x), y(v.y), z(v.z)
{
}
# endif
float x;
float y;
float z;
};
#endif
enum class DebugMode : uint32_t
{
eNone = 0,
eNormal,
};
struct Vertex
{
vector_float3 pos;
uint32_t tangent;
uint32_t normal;
uint32_t uv;
float pad0;
float pad1;
};
struct Uniforms
{
simd::float4x4 viewToWorld;
simd::float4x4 clipToView;
vector_float3 missColor;
uint32_t width;
uint32_t height;
uint32_t frameIndex;
uint32_t subframeIndex;
uint32_t numLights;
uint32_t enableAccumulation;
uint32_t samples_per_launch;
uint32_t maxDepth;
uint32_t rectLightSamplingMethod;
uint32_t tonemapperType; // 0 - "None", "Reinhard", "ACES", "Filmic"
float gamma; // 0 - off
vector_float3 exposureValue;
uint32_t debug;
};
struct UniformsTonemap
{
uint32_t width;
uint32_t height;
uint32_t tonemapperType; // 0 - "None", "Reinhard", "ACES", "Filmic"
float gamma; // 0 - off
vector_float3 exposureValue;
};
struct Triangle
{
vector_float3 positions[3];
uint32_t normals[3];
uint32_t tangent[3];
uint32_t uv[3];
};
// GPU side structure
struct UniformLight
{
vector_float4 points[4];
vector_float4 color;
vector_float4 normal;
int type;
float halfAngle;
float pad0;
float pad1;
};
struct Material
{
simd::float3 diffuse;
#ifdef __METAL_VERSION__
texture2d<float> diffuseTexture;
texture2d<float> normalTexture;
#else
MTL::ResourceID diffuseTexture; // uint64_t - alignment 8
MTL::ResourceID normalTexture;
#endif
};
#endif
|
arhix52/Strelka/src/settings/CMakeLists.txt | cmake_minimum_required(VERSION 3.16)
# Settings
set(SETTINGSLIB_SOURCES
${ROOT_HOME}/include/settings/settings.h
${ROOT_HOME}/src/settings/settings.cpp
)
set(SETTINGSLIB_NAME settings)
add_library(${SETTINGSLIB_NAME} OBJECT ${SETTINGSLIB_SOURCES})
target_include_directories(${SETTINGSLIB_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${SETTINGSLIB_NAME} PUBLIC ${ROOT_HOME}/external/glm)
|
arhix52/Strelka/src/settings/settings.cpp | #include "settings/settings.h"
namespace oka
{
} // namespace oka
|
arhix52/Strelka/src/app/CMakeLists.txt | cmake_minimum_required(VERSION 3.16)
find_package(cxxopts REQUIRED)
# Application
set(RUNNER_SOURCES
${ROOT_HOME}/src/app/main.cpp
# ${ROOT_HOME}/src/hdRunner/SimpleRenderTask.h
# ${ROOT_HOME}/src/hdRunner/SimpleRenderTask.cpp
)
set(RUNNER_NAME runner)
add_executable(${RUNNER_NAME} ${RUNNER_SOURCES})
set_target_properties(
${RUNNER_NAME}
PROPERTIES
LINKER_LANGUAGE CXX
CXX_STANDARD 17
CXX_STANDARD_REQUIRED TRUE
CXX_EXTENSIONS OFF
)
if( WIN32 )
target_compile_definitions( ${RUNNER_NAME} PUBLIC GLAD_GLAPI_EXPORT )
endif()
# target_include_directories(${PROJECT_NAME} PUBLIC ${Vulkan_INCLUDE_DIR})
# target_include_directories(${RUNNER_NAME} PUBLIC ${ROOT_HOME}/external/glfw/include)
# target_include_directories(${RUNNER_NAME} PUBLIC ${ROOT_HOME}/external/cxxopts/include)
target_include_directories(${RUNNER_NAME} PUBLIC ${ROOT_HOME}/include/)
# target_include_directories(${RUNNER_NAME} PUBLIC ${ROOT_HOME}/include/display)
# target_include_directories(${RUNNER_NAME} PUBLIC hd)
target_link_libraries(${RUNNER_NAME} PUBLIC
cxxopts::cxxopts
scene
sceneloader
settings
display
render
logger
) # Link the executable to library (if it uses it).
|
arhix52/Strelka/src/app/main.cpp | #include <display/Display.h>
#include <render/common.h>
#include <render/buffer.h>
#include <render/Render.h>
#include <sceneloader/gltfloader.h>
#include <log.h>
#include <logmanager.h>
#include <cxxopts.hpp>
#include <filesystem>
class CameraController : public oka::InputHandler
{
oka::Camera mCam;
glm::quat mOrientation;
glm::float3 mPosition;
glm::float3 mWorldUp;
glm::float3 mWorldForward;
float rotationSpeed = 0.025f;
float movementSpeed = 1.0f;
double pitch = 0.0;
double yaw = 0.0;
double max_pitch_rate = 5;
double max_yaw_rate = 5;
public:
virtual ~CameraController() = default;
struct
{
bool left = false;
bool right = false;
bool up = false;
bool down = false;
bool forward = false;
bool back = false;
} keys;
struct MouseButtons
{
bool left = false;
bool right = false;
bool middle = false;
} mouseButtons;
glm::float2 mMousePos;
// // local cameras axis
// glm::float3 getFront() const
// {
// return mOrientation.Transform(GfVec3d(0.0, 0.0, -1.0));
// }
// glm::float3 getUp() const
// {
// return mOrientation.Transform(GfVec3d(0.0, 1.0, 0.0));
// }
// glm::float3 getRight() const
// {
// return mOrientation.Transform(GfVec3d(1.0, 0.0, 0.0));
// }
// // global camera axis depending on scene settings
// GfVec3d getWorldUp() const
// {
// return mWorldUp;
// }
// GfVec3d getWorldForward() const
// {
// return mWorldForward;
// }
bool moving()
{
return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right ||
mouseButtons.left || mouseButtons.middle;
}
void update(double deltaTime, float speed)
{
mCam.rotationSpeed = rotationSpeed;
mCam.movementSpeed = speed;
mCam.update(deltaTime);
// movementSpeed = speed;
// if (moving())
// {
// const float moveSpeed = deltaTime * movementSpeed;
// if (keys.up)
// mPosition += getWorldUp() * moveSpeed;
// if (keys.down)
// mPosition -= getWorldUp() * moveSpeed;
// if (keys.left)
// mPosition -= getRight() * moveSpeed;
// if (keys.right)
// mPosition += getRight() * moveSpeed;
// if (keys.forward)
// mPosition += getFront() * moveSpeed;
// if (keys.back)
// mPosition -= getFront() * moveSpeed;
// updateViewMatrix();
// }
}
// void rotate(double rightAngle, double upAngle)
// {
// GfRotation a(getRight(), upAngle * rotationSpeed);
// GfRotation b(getWorldUp(), rightAngle * rotationSpeed);
// GfRotation c = a * b;
// GfQuatd cq = c.GetQuat();
// cq.Normalize();
// mOrientation = cq * mOrientation;
// mOrientation.Normalize();
// updateViewMatrix();
// }
// void translate(GfVec3d delta)
// {
// // mPosition += mOrientation.Transform(delta);
// // updateViewMatrix();
// mCam.translate()
// }
void updateViewMatrix()
{
// GfMatrix4d view(1.0);
// view.SetRotateOnly(mOrientation);
// view.SetTranslateOnly(mPosition);
// mGfCam.SetTransform(view);
mCam.updateViewMatrix();
}
oka::Camera& getCamera()
{
return mCam;
}
CameraController(oka::Camera& cam, bool isYup)
{
if (isYup)
{
cam.setWorldUp(glm::float3(0.0, 1.0, 0.0));
cam.setWorldForward(glm::float3(0.0, 0.0, -1.0));
}
else
{
cam.setWorldUp(glm::float3(0.0, 0.0, 1.0));
cam.setWorldForward(glm::float3(0.0, 1.0, 0.0));
}
mCam = cam;
// GfMatrix4d xform = mGfCam.GetTransform();
// xform.Orthonormalize();
// mOrientation = xform.ExtractRotationQuat();
// mOrientation.Normalize();
// mPosition = xform.ExtractTranslation();
}
void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) override
{
const bool keyState = ((GLFW_REPEAT == action) || (GLFW_PRESS == action)) ? true : false;
switch (key)
{
case GLFW_KEY_W: {
mCam.keys.forward = keyState;
break;
}
case GLFW_KEY_S: {
mCam.keys.back = keyState;
break;
}
case GLFW_KEY_A: {
mCam.keys.left = keyState;
break;
}
case GLFW_KEY_D: {
mCam.keys.right = keyState;
break;
}
case GLFW_KEY_Q: {
mCam.keys.up = keyState;
break;
}
case GLFW_KEY_E: {
mCam.keys.down = keyState;
break;
}
default:
break;
}
}
void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) override
{
if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
if (action == GLFW_PRESS)
{
mCam.mouseButtons.right = true;
}
else if (action == GLFW_RELEASE)
{
mCam.mouseButtons.right = false;
}
}
else if (button == GLFW_MOUSE_BUTTON_LEFT)
{
if (action == GLFW_PRESS)
{
mCam.mouseButtons.left = true;
}
else if (action == GLFW_RELEASE)
{
mCam.mouseButtons.left = false;
}
}
}
void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) override
{
const float dx = mCam.mousePos[0] - xpos;
const float dy = mCam.mousePos[1] - ypos;
// ImGuiIO& io = ImGui::GetIO();
// bool handled = io.WantCaptureMouse;
// if (handled)
//{
// camera.mousePos = glm::vec2((float)xpos, (float)ypos);
// return;
//}
if (mCam.mouseButtons.right)
{
mCam.rotate(-dx, -dy);
}
if (mCam.mouseButtons.left)
{
mCam.translate(glm::float3(-0.0, 0.0, -dy * .005 * movementSpeed));
}
if (mCam.mouseButtons.middle)
{
mCam.translate(glm::float3(-dx * 0.01, -dy * 0.01, 0.0f));
}
mCam.mousePos[0] = xpos;
mCam.mousePos[1] = ypos;
}
};
int main(int argc, const char* argv[])
{
const oka::Logmanager loggerManager;
cxxopts::Options options("Strelka -s <Scene path>", "commands");
// clang-format off
options.add_options()
("s, scene", "scene path", cxxopts::value<std::string>()->default_value(""))
("i, iteration", "Iteration to capture", cxxopts::value<int32_t>()->default_value("-1"))
("h, help", "Print usage")("t, spp_total", "spp total", cxxopts::value<int32_t>()->default_value("64"))
("f, spp_subframe", "spp subframe", cxxopts::value<int32_t>()->default_value("1"))
("c, need_screenshot", "Screenshot after spp total", cxxopts::value<bool>()->default_value("false"))
("v, validation", "Enable Validation", cxxopts::value<bool>()->default_value("false"));
// clang-format on
options.parse_positional({ "s" });
auto result = options.parse(argc, argv);
if (result.count("help"))
{
std::cout << options.help() << std::endl;
return 0;
}
// check params
const std::string sceneFile(result["s"].as<std::string>());
if (sceneFile.empty())
{
STRELKA_FATAL("Specify scene file name");
return 1;
}
if (!std::filesystem::exists(sceneFile))
{
STRELKA_FATAL("Specified scene file: {} doesn't exist", sceneFile.c_str());
return -1;
}
const std::filesystem::path sceneFilePath = { sceneFile.c_str() };
const std::string resourceSearchPath = sceneFilePath.parent_path().string();
STRELKA_DEBUG("Resource search path {}", resourceSearchPath);
auto* ctx = new oka::SharedContext();
// Set up rendering context.
uint32_t imageWidth = 1024;
uint32_t imageHeight = 768;
ctx->mSettingsManager = new oka::SettingsManager();
ctx->mSettingsManager->setAs<uint32_t>("render/width", imageWidth);
ctx->mSettingsManager->setAs<uint32_t>("render/height", imageHeight);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/depth", 4);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", result["t"].as<int32_t>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/spp", result["f"].as<int32_t>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/iteration", 0);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", 0); // 0 - none, 1 - random, 2 -
// stratified sampling, 3 - optimized
// stratified sampling
ctx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", 0); // 0 - reinhard, 1 - aces, 2 - filmic
ctx->mSettingsManager->setAs<uint32_t>("render/pt/debug", 0); // 0 - none, 1 - normals
ctx->mSettingsManager->setAs<float>("render/cameraSpeed", 1.0f);
ctx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", 0.5f);
ctx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", true);
ctx->mSettingsManager->setAs<bool>("render/pt/enableAcc", true);
ctx->mSettingsManager->setAs<bool>("render/pt/enableTonemap", true);
ctx->mSettingsManager->setAs<bool>("render/pt/isResized", false);
ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false);
ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", result["c"].as<bool>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/rectLightSamplingMethod", 0);
ctx->mSettingsManager->setAs<bool>("render/enableValidation", result["v"].as<bool>());
ctx->mSettingsManager->setAs<std::string>("resource/searchPath", resourceSearchPath);
// Postprocessing settings:
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/filmIso", 100.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/cm2_factor", 1.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/fStop", 4.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/shutterSpeed", 100.0f);
ctx->mSettingsManager->setAs<float>("render/post/gamma", 2.4f); // 0.0f - off
// Dev settings:
ctx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", 0.0f); // offset to avoid self-collision in light
// sampling
ctx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", 0.0f); // offset to avoid self-collision in
oka::Display* display = oka::DisplayFactory::createDisplay();
display->init(imageWidth, imageHeight, ctx);
oka::RenderType type = oka::RenderType::eOptiX;
oka::Render* render = oka::RenderFactory::createRender(type);
oka::Scene scene;
oka::GltfLoader sceneLoader;
sceneLoader.loadGltf(sceneFilePath.string(), scene);
CameraController cameraController(scene.getCamera(0), true);
oka::Camera camera;
camera.name = "Main";
camera.fov = 45;
camera.position = glm::vec3(0, 0, -10);
camera.mOrientation = glm::quat(glm::vec3(0,0,0));
camera.updateViewMatrix();
scene.addCamera(camera);
render->setScene(&scene);
render->setSharedContext(ctx);
render->init();
ctx->mRender = render;
oka::BufferDesc desc{};
desc.format = oka::BufferFormat::FLOAT4;
desc.width = imageWidth;
desc.height = imageHeight;
oka::Buffer* outputBuffer = ctx->mRender->createBuffer(desc);
display->setInputHandler(&cameraController);
while (!display->windowShouldClose())
{
auto start = std::chrono::high_resolution_clock::now();
display->pollEvents();
static auto prevTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
const double deltaTime = std::chrono::duration<double, std::milli>(currentTime - prevTime).count() / 1000.0;
const auto cameraSpeed = ctx->mSettingsManager->getAs<float>("render/cameraSpeed");
cameraController.update(deltaTime, cameraSpeed);
prevTime = currentTime;
scene.updateCamera(cameraController.getCamera(), 0);
display->onBeginFrame();
render->render(outputBuffer);
outputBuffer->map();
oka::ImageBuffer outputImage;
outputImage.data = outputBuffer->getHostPointer();
outputImage.dataSize = outputBuffer->getHostDataSize();
outputImage.height = outputBuffer->height();
outputImage.width = outputBuffer->width();
outputImage.pixel_format = oka::BufferFormat::FLOAT4;
display->drawFrame(outputImage); // blit rendered image to swapchain
display->drawUI(); // render ui to swapchain image in window resolution
display->onEndFrame(); // submit command buffer and present
outputBuffer->unmap();
const uint32_t currentSpp = ctx->mSubframeIndex;
auto finish = std::chrono::high_resolution_clock::now();
const double frameTime = std::chrono::duration<double, std::milli>(finish - start).count();
display->setWindowTitle((std::string("Strelka") + " [" + std::to_string(frameTime) + " ms]" + " [" +
std::to_string(currentSpp) + " spp]")
.c_str()); }
display->destroy();
return 0;
}
|
arhix52/Strelka/src/hdRunner/SimpleRenderTask.h | #pragma once
#include <pxr/pxr.h>
#include <pxr/imaging/hd/task.h>
#include <pxr/imaging/hd/renderPass.h>
#include <pxr/imaging/hd/renderPassState.h>
PXR_NAMESPACE_OPEN_SCOPE
class SimpleRenderTask final : public HdTask
{
public:
SimpleRenderTask(const HdRenderPassSharedPtr& renderPass,
const HdRenderPassStateSharedPtr& renderPassState,
const TfTokenVector& renderTags);
void Sync(HdSceneDelegate* sceneDelegate,
HdTaskContext* taskContext,
HdDirtyBits* dirtyBits) override;
void Prepare(HdTaskContext* taskContext,
HdRenderIndex* renderIndex) override;
void Execute(HdTaskContext* taskContext) override;
const TfTokenVector& GetRenderTags() const override;
private:
HdRenderPassSharedPtr m_renderPass;
HdRenderPassStateSharedPtr m_renderPassState;
TfTokenVector m_renderTags;
};
PXR_NAMESPACE_CLOSE_SCOPE
|
arhix52/Strelka/src/hdRunner/CMakeLists.txt | cmake_minimum_required(VERSION 3.20)
find_package(cxxopts REQUIRED)
find_package(USD REQUIRED HINTS ${USD_DIR} NAMES pxr)
message(STATUS "USD LIBRARY: ${USD_DIR}")
set(HD_RUNNER_NAME HydraRunner)
# WAR: https://github.com/PixarAnimationStudios/OpenUSD/issues/2634
add_compile_definitions(BOOST_NO_CXX98_FUNCTION_BASE)
# Application
set(HD_RUNNER_SOURCES
${ROOT_HOME}/src/hdRunner/main.cpp
${ROOT_HOME}/src/hdRunner/SimpleRenderTask.h
${ROOT_HOME}/src/hdRunner/SimpleRenderTask.cpp)
add_executable(${HD_RUNNER_NAME} ${HD_RUNNER_SOURCES})
set_target_properties(
${HD_RUNNER_NAME}
PROPERTIES LINKER_LANGUAGE CXX
CXX_STANDARD 17
CXX_STANDARD_REQUIRED TRUE
CXX_EXTENSIONS OFF)
add_custom_command(
TARGET ${HD_RUNNER_NAME}
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"${OUTPUT_DIRECTORY}/data/materials/mtlx")
add_custom_command(
TARGET ${HD_RUNNER_NAME}
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"${OUTPUT_DIRECTORY}/data/materials/mdl")
target_include_directories(${HD_RUNNER_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${HD_RUNNER_NAME} PUBLIC hd)
target_link_libraries(
${HD_RUNNER_NAME}
PUBLIC cxxopts::cxxopts
scene
settings
display
render
logger
ar
cameraUtil
hd
hf
hgi
hio
usd
usdGeom
usdImaging) # Link the executable to library (if it uses it).
if(WIN32)
# Add the linker options to suppress the MSVCRT conflict warning
target_link_options(${HD_RUNNER_NAME} PRIVATE "/NODEFAULTLIB:MSVCRT")
target_link_options(${HD_RUNNER_NAME} PRIVATE "/NODEFAULTLIB:LIBCMT")
target_link_libraries(${HD_RUNNER_NAME} PUBLIC ${OPENGL_LIBRARIES})
endif()
|
arhix52/Strelka/src/hdRunner/SimpleRenderTask.cpp | #include "SimpleRenderTask.h"
PXR_NAMESPACE_OPEN_SCOPE
SimpleRenderTask::SimpleRenderTask(const HdRenderPassSharedPtr& renderPass,
const HdRenderPassStateSharedPtr& renderPassState,
const TfTokenVector& renderTags)
: HdTask(SdfPath::EmptyPath()), m_renderPass(renderPass), m_renderPassState(renderPassState), m_renderTags(renderTags)
{
}
void SimpleRenderTask::Sync(HdSceneDelegate* sceneDelegate,
HdTaskContext* taskContext,
HdDirtyBits* dirtyBits)
{
TF_UNUSED(sceneDelegate);
TF_UNUSED(taskContext);
m_renderPass->Sync();
*dirtyBits = HdChangeTracker::Clean;
}
void SimpleRenderTask::Prepare(HdTaskContext* taskContext,
HdRenderIndex* renderIndex)
{
TF_UNUSED(taskContext);
const HdResourceRegistrySharedPtr& resourceRegistry = renderIndex->GetResourceRegistry();
m_renderPassState->Prepare(resourceRegistry);
//m_renderPass->Prepare(m_renderTags);
}
void SimpleRenderTask::Execute(HdTaskContext* taskContext)
{
TF_UNUSED(taskContext);
m_renderPass->Execute(m_renderPassState, m_renderTags);
}
const TfTokenVector& SimpleRenderTask::GetRenderTags() const
{
return m_renderTags;
}
PXR_NAMESPACE_CLOSE_SCOPE
|
arhix52/Strelka/src/hdRunner/main.cpp | #include "SimpleRenderTask.h"
#include <pxr/base/gf/gamma.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/base/tf/stopwatch.h>
#include <pxr/imaging/hd/camera.h>
#include <pxr/imaging/hd/engine.h>
#include <pxr/imaging/hd/pluginRenderDelegateUniqueHandle.h>
#include <pxr/imaging/hd/renderBuffer.h>
#include <pxr/imaging/hd/renderDelegate.h>
#include <pxr/imaging/hd/renderIndex.h>
#include <pxr/imaging/hd/renderPass.h>
#include <pxr/imaging/hd/renderPassState.h>
#include <pxr/imaging/hd/rendererPlugin.h>
#include <pxr/imaging/hd/rendererPluginRegistry.h>
#include <pxr/imaging/hf/pluginDesc.h>
#include <pxr/imaging/hgi/hgi.h>
#include <pxr/imaging/hgi/tokens.h>
#include <pxr/imaging/hio/image.h>
#include <pxr/imaging/hio/imageRegistry.h>
#include <pxr/imaging/hio/types.h>
#include <pxr/pxr.h>
#include <pxr/usd/ar/resolver.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/camera.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usdImaging/usdImaging/delegate.h>
#include <render/common.h>
#include <render/buffer.h>
#include <display/Display.h>
#include <log.h>
#include <logmanager.h>
#include <algorithm>
#include <cxxopts.hpp>
#include <iostream>
#include <filesystem>
// #include <cuda_runtime.h>
PXR_NAMESPACE_USING_DIRECTIVE
TF_DEFINE_PRIVATE_TOKENS(_AppTokens, (HdStrelkaDriver)(HdStrelkaRendererPlugin));
HdRendererPluginHandle GetHdStrelkaPlugin()
{
HdRendererPluginRegistry& registry = HdRendererPluginRegistry::GetInstance();
const TfToken& pluginId = _AppTokens->HdStrelkaRendererPlugin;
HdRendererPluginHandle plugin = registry.GetOrCreateRendererPlugin(pluginId);
return plugin;
}
HdCamera* FindCamera(UsdStageRefPtr& stage, HdRenderIndex* renderIndex, SdfPath& cameraPath)
{
UsdPrimRange primRange = stage->TraverseAll();
for (auto prim = primRange.cbegin(); prim != primRange.cend(); prim++)
{
if (!prim->IsA<UsdGeomCamera>())
{
continue;
}
cameraPath = prim->GetPath();
break;
}
auto* camera = (HdCamera*)dynamic_cast<HdCamera*>(renderIndex->GetSprim(HdTokens->camera, cameraPath));
return camera;
}
std::vector<std::pair<HdCamera*, SdfPath>> FindAllCameras(UsdStageRefPtr& stage, HdRenderIndex* renderIndex)
{
UsdPrimRange primRange = stage->TraverseAll();
HdCamera* camera{};
SdfPath cameraPath{};
std::vector<std::pair<HdCamera*, SdfPath>> cameras{};
for (auto prim = primRange.cbegin(); prim != primRange.cend(); prim++)
{
if (!prim->IsA<UsdGeomCamera>())
{
continue;
}
cameraPath = prim->GetPath();
camera = (HdCamera*)dynamic_cast<HdCamera*>(renderIndex->GetSprim(HdTokens->camera, cameraPath));
cameras.emplace_back(camera, cameraPath);
}
return cameras;
}
class CameraController : public oka::InputHandler
{
GfCamera mGfCam;
GfQuatd mOrientation;
GfVec3d mPosition;
GfVec3d mWorldUp;
GfVec3d mWorldForward;
float rotationSpeed = 0.025f;
float movementSpeed = 1.0f;
double pitch = 0.0;
double yaw = 0.0;
double max_pitch_rate = 5;
double max_yaw_rate = 5;
public:
virtual ~CameraController() = default;
struct
{
bool left = false;
bool right = false;
bool up = false;
bool down = false;
bool forward = false;
bool back = false;
} keys;
struct MouseButtons
{
bool left = false;
bool right = false;
bool middle = false;
} mouseButtons;
GfVec2d mMousePos;
// local cameras axis
GfVec3d getFront() const
{
return mOrientation.Transform(GfVec3d(0.0, 0.0, -1.0));
}
GfVec3d getUp() const
{
return mOrientation.Transform(GfVec3d(0.0, 1.0, 0.0));
}
GfVec3d getRight() const
{
return mOrientation.Transform(GfVec3d(1.0, 0.0, 0.0));
}
// global camera axis depending on scene settings
GfVec3d getWorldUp() const
{
return mWorldUp;
}
GfVec3d getWorldForward() const
{
return mWorldForward;
}
bool moving()
{
return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right ||
mouseButtons.left || mouseButtons.middle;
}
void update(double deltaTime, float speed)
{
movementSpeed = speed;
if (moving())
{
const float moveSpeed = deltaTime * movementSpeed;
if (keys.up)
mPosition += getWorldUp() * moveSpeed;
if (keys.down)
mPosition -= getWorldUp() * moveSpeed;
if (keys.left)
mPosition -= getRight() * moveSpeed;
if (keys.right)
mPosition += getRight() * moveSpeed;
if (keys.forward)
mPosition += getFront() * moveSpeed;
if (keys.back)
mPosition -= getFront() * moveSpeed;
updateViewMatrix();
}
}
void rotate(double rightAngle, double upAngle)
{
GfRotation a(getRight(), upAngle * rotationSpeed);
GfRotation b(getWorldUp(), rightAngle * rotationSpeed);
GfRotation c = a * b;
GfQuatd cq = c.GetQuat();
cq.Normalize();
mOrientation = cq * mOrientation;
mOrientation.Normalize();
updateViewMatrix();
}
void translate(GfVec3d delta)
{
mPosition += mOrientation.Transform(delta);
updateViewMatrix();
}
void updateViewMatrix()
{
GfMatrix4d view(1.0);
view.SetRotateOnly(mOrientation);
view.SetTranslateOnly(mPosition);
mGfCam.SetTransform(view);
}
GfCamera& getCamera()
{
return mGfCam;
}
CameraController(UsdGeomCamera& cam, bool isYup)
{
if (isYup)
{
mWorldUp = GfVec3d(0.0, 1.0, 0.0);
mWorldForward = GfVec3d(0.0, 0.0, -1.0);
}
else
{
mWorldUp = GfVec3d(0.0, 0.0, 1.0);
mWorldForward = GfVec3d(0.0, 1.0, 0.0);
}
mGfCam = cam.GetCamera(0.0);
GfMatrix4d xform = mGfCam.GetTransform();
xform.Orthonormalize();
mOrientation = xform.ExtractRotationQuat();
mOrientation.Normalize();
mPosition = xform.ExtractTranslation();
}
void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) override
{
const bool keyState = ((GLFW_REPEAT == action) || (GLFW_PRESS == action)) ? true : false;
switch (key)
{
case GLFW_KEY_W: {
keys.forward = keyState;
break;
}
case GLFW_KEY_S: {
keys.back = keyState;
break;
}
case GLFW_KEY_A: {
keys.left = keyState;
break;
}
case GLFW_KEY_D: {
keys.right = keyState;
break;
}
case GLFW_KEY_Q: {
keys.up = keyState;
break;
}
case GLFW_KEY_E: {
keys.down = keyState;
break;
}
default:
break;
}
}
void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) override
{
if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
if (action == GLFW_PRESS)
{
mouseButtons.right = true;
}
else if (action == GLFW_RELEASE)
{
mouseButtons.right = false;
}
}
else if (button == GLFW_MOUSE_BUTTON_LEFT)
{
if (action == GLFW_PRESS)
{
mouseButtons.left = true;
}
else if (action == GLFW_RELEASE)
{
mouseButtons.left = false;
}
}
}
void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) override
{
const float dx = mMousePos[0] - xpos;
const float dy = mMousePos[1] - ypos;
// ImGuiIO& io = ImGui::GetIO();
// bool handled = io.WantCaptureMouse;
// if (handled)
//{
// camera.mousePos = glm::vec2((float)xpos, (float)ypos);
// return;
//}
if (mouseButtons.right)
{
rotate(dx, dy);
}
if (mouseButtons.left)
{
translate(GfVec3d(-0.0, 0.0, -dy * .005 * movementSpeed));
}
if (mouseButtons.middle)
{
translate(GfVec3d(-dx * 0.01, -dy * 0.01, 0.0f));
}
mMousePos[0] = xpos;
mMousePos[1] = ypos;
}
};
class RenderSurfaceController : public oka::ResizeHandler
{
uint32_t imageWidth = 800;
uint32_t imageHeight = 600;
oka::SettingsManager* mSettingsManager = nullptr;
std::array<HdRenderBuffer*, 3> mRenderBuffers;
bool mDirty[3] = { true };
bool mInUse[3] = { false };
public:
RenderSurfaceController(oka::SettingsManager* settingsManager, std::array<HdRenderBuffer*, 3>& renderBuffers)
: mSettingsManager(settingsManager), mRenderBuffers(renderBuffers)
{
imageWidth = mSettingsManager->getAs<uint32_t>("render/width");
imageHeight = mSettingsManager->getAs<uint32_t>("render/height");
}
void framebufferResize(int newWidth, int newHeight)
{
assert(mSettingsManager);
mSettingsManager->setAs<uint32_t>("render/width", newWidth);
mSettingsManager->setAs<uint32_t>("render/height", newHeight);
imageWidth = newWidth;
imageHeight = newHeight;
for (bool& i : mDirty)
{
i = true;
}
// reallocateBuffers();
}
bool isDirty(uint32_t index)
{
return mDirty[index];
}
void acquire(uint32_t index)
{
mInUse[index] = true;
}
void release(uint32_t index)
{
mInUse[index] = false;
}
HdRenderBuffer* getRenderBuffer(uint32_t index)
{
assert(index < 3);
if (mDirty[index] && !mInUse[index])
{
mRenderBuffers[index]->Allocate(GfVec3i(imageWidth, imageHeight, 1), HdFormatFloat32Vec4, false);
mDirty[index] = false;
}
return mRenderBuffers[index];
}
};
void setDefaultCamera(UsdGeomCamera& cam)
{
// y - up, camera looks at (0, 0, 0)
std::vector<float> r0 = { 0, -1, 0, 0 };
std::vector<float> r1 = { 0, 0, 1, 0 };
std::vector<float> r2 = { -1, 0, 0, 0 };
std::vector<float> r3 = { 0, 0, 0, 1 };
GfMatrix4d xform(r0, r1, r2, r3);
GfCamera mGfCam{};
mGfCam.SetTransform(xform);
GfRange1f clippingRange = GfRange1f{ 0.1, 1000 };
mGfCam.SetClippingRange(clippingRange);
mGfCam.SetVerticalAperture(20.25);
mGfCam.SetVerticalApertureOffset(0);
mGfCam.SetHorizontalAperture(36);
mGfCam.SetHorizontalApertureOffset(0);
mGfCam.SetFocalLength(50);
GfCamera::Projection projection = GfCamera::Projection::Perspective;
mGfCam.SetProjection(projection);
cam.SetFromCamera(mGfCam, 0.0);
}
bool saveScreenshot(std::string& outputFilePath, unsigned char* mappedMem, uint32_t imageWidth, uint32_t imageHeight)
{
TF_VERIFY(mappedMem != nullptr);
int pixelCount = imageWidth * imageHeight;
// Write image to file.
TfStopwatch timerWrite;
timerWrite.Start();
HioImageSharedPtr image = HioImage::OpenForWriting(outputFilePath);
if (!image)
{
STRELKA_ERROR("Unable to open output file for writing!");
return false;
}
HioImage::StorageSpec storage;
storage.width = (int)imageWidth;
storage.height = (int)imageHeight;
storage.depth = (int)1;
storage.format = HioFormat::HioFormatFloat32Vec4;
storage.flipped = true;
storage.data = mappedMem;
VtDictionary metadata;
image->Write(storage, metadata);
timerWrite.Stop();
STRELKA_INFO("Wrote image {}", timerWrite.GetSeconds());
return true;
}
int main(int argc, const char* argv[])
{
const oka::Logmanager loggerManager;
// config. options
cxxopts::Options options("Strelka -s <USD Scene path>", "commands");
// clang-format off
options.add_options()
("s, scene", "scene path", cxxopts::value<std::string>()->default_value(""))
("i, iteration", "Iteration to capture", cxxopts::value<int32_t>()->default_value("-1"))
("h, help", "Print usage")("t, spp_total", "spp total", cxxopts::value<int32_t>()->default_value("64"))
("f, spp_subframe", "spp subframe", cxxopts::value<int32_t>()->default_value("1"))
("c, need_screenshot", "Screenshot after spp total", cxxopts::value<bool>()->default_value("false"))
("v, validation", "Enable Validation", cxxopts::value<bool>()->default_value("false"));
// clang-format on
options.parse_positional({ "s" });
auto result = options.parse(argc, argv);
if (result.count("help"))
{
std::cout << options.help() << std::endl;
return 0;
}
// check params
const std::string usdFile(result["s"].as<std::string>());
if (usdFile.empty())
{
STRELKA_FATAL("Specify usd file name");
return 1;
}
if (!std::filesystem::exists(usdFile))
{
STRELKA_FATAL("Specified usd file: {} doesn't exist", usdFile.c_str());
return -1;
}
const std::filesystem::path usdFilePath = { usdFile.c_str() };
const std::string resourceSearchPath = usdFilePath.parent_path().string();
STRELKA_DEBUG("Resource path {}", resourceSearchPath);
const int32_t iterationToCapture(result["i"].as<int32_t>());
// Init plugin.
const HdRendererPluginHandle pluginHandle = GetHdStrelkaPlugin();
if (!pluginHandle)
{
STRELKA_FATAL("HdStrelka plugin not found!");
return EXIT_FAILURE;
}
if (!pluginHandle->IsSupported())
{
STRELKA_FATAL("HdStrelka plugin is not supported!");
return EXIT_FAILURE;
}
HdDriverVector drivers;
// Set up rendering context.
uint32_t imageWidth = 1024;
uint32_t imageHeight = 768;
auto* ctx = new oka::SharedContext(); // &display.getSharedContext();
ctx->mSettingsManager = new oka::SettingsManager();
ctx->mSettingsManager->setAs<uint32_t>("render/width", imageWidth);
ctx->mSettingsManager->setAs<uint32_t>("render/height", imageHeight);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/depth", 4);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", result["t"].as<int32_t>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/spp", result["f"].as<int32_t>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/iteration", 0);
ctx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", 0); // 0 - none, 1 - random, 2 -
// stratified sampling, 3 - optimized
// stratified sampling
ctx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", 0); // 0 - reinhard, 1 - aces, 2 - filmic
ctx->mSettingsManager->setAs<uint32_t>("render/pt/debug", 0); // 0 - none, 1 - normals
ctx->mSettingsManager->setAs<float>("render/cameraSpeed", 1.0f);
ctx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", 0.5f);
ctx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", true);
ctx->mSettingsManager->setAs<bool>("render/pt/enableAcc", true);
ctx->mSettingsManager->setAs<bool>("render/pt/enableTonemap", true);
ctx->mSettingsManager->setAs<bool>("render/pt/isResized", false);
ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false);
ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", result["c"].as<bool>());
ctx->mSettingsManager->setAs<uint32_t>("render/pt/rectLightSamplingMethod", 0);
ctx->mSettingsManager->setAs<bool>("render/enableValidation", result["v"].as<bool>());
ctx->mSettingsManager->setAs<std::string>("resource/searchPath", resourceSearchPath);
// Postprocessing settings:
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/filmIso", 100.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/cm2_factor", 1.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/fStop", 4.0f);
ctx->mSettingsManager->setAs<float>("render/post/tonemapper/shutterSpeed", 100.0f);
ctx->mSettingsManager->setAs<float>("render/post/gamma", 2.4f); // 0.0f - off
// Dev settings:
ctx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", 0.0f); // offset to avoid self-collision in light
// sampling
ctx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", 0.0f); // offset to avoid self-collision in
// bsdf sampling
HdDriver driver;
driver.name = _AppTokens->HdStrelkaDriver;
driver.driver = VtValue(ctx);
drivers.push_back(&driver);
HdRenderDelegate* renderDelegate = pluginHandle->CreateRenderDelegate();
TF_VERIFY(renderDelegate);
renderDelegate->SetDrivers(drivers);
oka::Display* display = oka::DisplayFactory::createDisplay();
display->init(imageWidth, imageHeight, ctx);
// Handle cmdline args.
// Load scene.
TfStopwatch timerLoad;
timerLoad.Start();
// ArGetResolver().ConfigureResolverForAsset(settings.sceneFilePath);
const std::string& usdPath = usdFile;
UsdStageRefPtr stage = UsdStage::Open(usdPath);
timerLoad.Stop();
if (!stage)
{
STRELKA_FATAL("Unable to open USD stage file.");
return EXIT_FAILURE;
}
STRELKA_INFO("USD scene loaded {}", timerLoad.GetSeconds());
// Print the up-axis
const TfToken upAxis = UsdGeomGetStageUpAxis(stage);
STRELKA_INFO("Stage up-axis: {}", (std::string)upAxis);
// Print the stage's linear units, or "meters per unit"
STRELKA_INFO("Meters per unit: {}", UsdGeomGetStageMetersPerUnit(stage));
HdRenderIndex* renderIndex = HdRenderIndex::New(renderDelegate, HdDriverVector());
TF_VERIFY(renderIndex);
UsdImagingDelegate sceneDelegate(renderIndex, SdfPath::AbsoluteRootPath());
sceneDelegate.Populate(stage->GetPseudoRoot());
sceneDelegate.SetTime(0);
sceneDelegate.SetRefineLevelFallback(4);
const double meterPerUnit = UsdGeomGetStageMetersPerUnit(stage);
// Init camera from scene
SdfPath cameraPath = SdfPath::EmptyPath();
HdCamera* camera = FindCamera(stage, renderIndex, cameraPath);
UsdGeomCamera cam;
if (camera)
{
cam = UsdGeomCamera::Get(stage, cameraPath);
}
else
{
// Init default camera
cameraPath = SdfPath("/defaultCamera");
cam = UsdGeomCamera::Define(stage, cameraPath);
setDefaultCamera(cam);
}
CameraController cameraController(cam, upAxis == UsdGeomTokens->y);
// std::vector<std::pair<HdCamera*, SdfPath>> cameras = FindAllCameras(stage, renderIndex);
std::array<HdRenderBuffer*, 3> renderBuffers{};
for (int i = 0; i < 3; ++i)
{
renderBuffers[i] = (HdRenderBuffer*)renderDelegate->CreateFallbackBprim(HdPrimTypeTokens->renderBuffer);
renderBuffers[i]->Allocate(GfVec3i(imageWidth, imageHeight, 1), HdFormatFloat32Vec4, false);
}
CameraUtilFraming framing;
framing.dataWindow = GfRect2i(GfVec2i(0, 0), GfVec2i(imageWidth, imageHeight));
framing.displayWindow = GfRange2f(GfVec2f(0.0f, 0.0f), GfVec2f((float)imageWidth, (float)imageHeight));
framing.pixelAspectRatio = 1.0f;
const std::optional<CameraUtilConformWindowPolicy> overrideWindowPolicy(CameraUtilFit);
// TODO: add UI control here
TfTokenVector renderTags{ HdRenderTagTokens->geometry, HdRenderTagTokens->render };
HdRprimCollection renderCollection(HdTokens->geometry, HdReprSelector(HdReprTokens->refined));
HdRenderPassSharedPtr renderPass = renderDelegate->CreateRenderPass(renderIndex, renderCollection);
std::shared_ptr<HdRenderPassState> renderPassState[3];
std::shared_ptr<SimpleRenderTask> renderTasks[3];
for (int i = 0; i < 3; ++i)
{
renderPassState[i] = std::make_shared<HdRenderPassState>();
renderPassState[i]->SetCamera(camera);
renderPassState[i]->SetFraming(framing);
renderPassState[i]->SetOverrideWindowPolicy(overrideWindowPolicy);
HdRenderPassAovBindingVector aovBindings(1);
aovBindings[0].aovName = HdAovTokens->color;
aovBindings[0].renderBuffer = renderBuffers[i];
renderPassState[i]->SetAovBindings(aovBindings);
renderTasks[i] = std::make_shared<SimpleRenderTask>(renderPass, renderPassState[i], renderTags);
}
// Perform rendering.
TfStopwatch timerRender;
timerRender.Start();
HdEngine engine;
display->setInputHandler(&cameraController);
RenderSurfaceController surfaceController(ctx->mSettingsManager, renderBuffers);
display->setResizeHandler(&surfaceController);
uint64_t frameCount = 0;
while (!display->windowShouldClose())
{
auto start = std::chrono::high_resolution_clock::now();
HdTaskSharedPtrVector tasks;
const uint32_t versionId = frameCount % oka::MAX_FRAMES_IN_FLIGHT;
// relocation?
surfaceController.acquire(versionId);
if (surfaceController.isDirty(versionId))
{
HdRenderPassAovBindingVector aovBindings(1);
aovBindings[0].aovName = HdAovTokens->color;
surfaceController.release(versionId);
aovBindings[0].renderBuffer = surfaceController.getRenderBuffer(versionId);
surfaceController.acquire(versionId);
renderPassState[versionId]->SetAovBindings(aovBindings);
renderTasks[versionId] =
std::make_shared<SimpleRenderTask>(renderPass, renderPassState[versionId], renderTags);
}
tasks.push_back(renderTasks[versionId]);
sceneDelegate.SetTime(1.0f);
display->pollEvents();
static auto prevTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
const double deltaTime = std::chrono::duration<double, std::milli>(currentTime - prevTime).count() / 1000.0;
const auto cameraSpeed = ctx->mSettingsManager->getAs<float>("render/cameraSpeed");
cameraController.update(deltaTime, cameraSpeed);
prevTime = currentTime;
cam.SetFromCamera(cameraController.getCamera(), 0.0);
display->onBeginFrame();
engine.Execute(renderIndex, &tasks); // main path tracing rendering in fixed render resolution
auto* outputBuffer =
surfaceController.getRenderBuffer(versionId)->GetResource(false).UncheckedGet<oka::Buffer*>();
oka::ImageBuffer outputImage;
// upload to host
outputBuffer->map();
outputImage.data = outputBuffer->getHostPointer();
outputImage.dataSize = outputBuffer->getHostDataSize();
outputImage.height = outputBuffer->height();
outputImage.width = outputBuffer->width();
outputImage.pixel_format = outputBuffer->getFormat();
const auto totalSpp = ctx->mSettingsManager->getAs<uint32_t>("render/pt/sppTotal");
const uint32_t currentSpp = ctx->mSubframeIndex;
bool needScreenshot = ctx->mSettingsManager->getAs<bool>("render/pt/needScreenshot");
if (ctx->mSettingsManager->getAs<bool>("render/pt/screenshotSPP") && (currentSpp == totalSpp))
{
needScreenshot = true;
// need to store screen only once
ctx->mSettingsManager->setAs<bool>("render/pt/screenshotSPP", false);
}
if (needScreenshot)
{
const std::size_t foundSlash = usdPath.find_last_of("/\\");
const std::size_t foundDot = usdPath.find_last_of('.');
std::string fileName = usdPath.substr(0, foundDot);
fileName = fileName.substr(foundSlash + 1);
auto generateName = [&](const uint32_t attempt) {
std::string outputFilePath = fileName + "_" + std::to_string(currentSpp) + "i_" +
std::to_string(ctx->mSettingsManager->getAs<uint32_t>("render/pt/depth")) +
"d_" + std::to_string(totalSpp) + "spp_" + std::to_string(attempt) + ".png";
return outputFilePath;
};
uint32_t attempt = 0;
std::string outputFilePath;
do
{
outputFilePath = generateName(attempt++);
} while (std::filesystem::exists(std::filesystem::path(outputFilePath.c_str())));
unsigned char* mappedMem = (unsigned char*)outputImage.data;
if (saveScreenshot(outputFilePath, mappedMem, outputImage.width, outputImage.height))
{
ctx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", false);
}
}
display->drawFrame(outputImage); // blit rendered image to swapchain
display->drawUI(); // render ui to swapchain image in window resolution
display->onEndFrame(); // submit command buffer and present
auto finish = std::chrono::high_resolution_clock::now();
const double frameTime = std::chrono::duration<double, std::milli>(finish - start).count();
surfaceController.release(versionId);
display->setWindowTitle((std::string("Strelka") + " [" + std::to_string(frameTime) + " ms]" + " [" +
std::to_string(currentSpp) + " spp]")
.c_str());
++frameCount;
}
// renderBuffer->Resolve();
// TF_VERIFY(renderBuffer->IsConverged());
timerRender.Stop();
display->destroy();
STRELKA_INFO("Rendering finished {}", timerRender.GetSeconds());
for (int i = 0; i < 3; ++i)
{
renderDelegate->DestroyBprim(renderBuffers[i]);
}
return EXIT_SUCCESS;
}
|
arhix52/Strelka/src/scene/camera.cpp | #include "camera.h"
#include <glm/gtx/quaternion.hpp>
#include <glm-wrapper.hpp>
namespace oka
{
void Camera::updateViewMatrix()
{
const glm::float4x4 rotM{ mOrientation };
const glm::float4x4 transM = glm::translate(glm::float4x4(1.0f), -position);
if (type == CameraType::firstperson)
{
matrices.view = rotM * transM;
}
else
{
matrices.view = transM * rotM;
}
updated = true;
}
glm::float3 Camera::getFront() const
{
return glm::conjugate(mOrientation) * glm::float3(0.0f, 0.0f, -1.0f);
}
glm::float3 Camera::getUp() const
{
return glm::conjugate(mOrientation) * glm::float3(0.0f, 1.0f, 0.0f);
}
glm::float3 Camera::getRight() const
{
return glm::conjugate(mOrientation) * glm::float3(1.0f, 0.0f, 0.0f);
}
bool Camera::moving() const
{
return keys.left || keys.right || keys.up || keys.down || keys.forward || keys.back || mouseButtons.right || mouseButtons.left || mouseButtons.middle;
}
float Camera::getNearClip() const
{
return znear;
}
float Camera::getFarClip() const
{
return zfar;
}
void Camera::setFov(float fov)
{
this->fov = fov;
}
// original implementation: https://vincent-p.github.io/notes/20201216234910-the_projection_matrix_in_vulkan/
glm::float4x4 perspective(float fov, float aspect_ratio, float n, float f, glm::float4x4* inverse)
{
const float focal_length = 1.0f / std::tan(glm::radians(fov) / 2.0f);
const float x = focal_length / aspect_ratio;
const float y = focal_length;
const float A = n / (f - n);
const float B = f * A;
//glm::float4x4 projection = glm::perspective(fov, aspect_ratio, n, f);
//if (inverse)
//{
// *inverse = glm::inverse(projection);
//}
glm::float4x4 projection({
x,
0.0f,
0.0f,
0.0f,
0.0f,
y,
0.0f,
0.0f,
0.0f,
0.0f,
A,
B,
0.0f,
0.0f,
-1.0f,
0.0f,
});
if (inverse)
{
*inverse = glm::transpose(glm::float4x4({ // glm inverse
1 / x,
0.0f,
0.0f,
0.0f,
0.0f,
1 / y,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
-1.0f,
0.0f,
0.0f,
1 / B,
A / B,
}));
}
return glm::transpose(projection);
}
void Camera::setPerspective(float _fov, float _aspect, float _znear, float _zfar)
{
fov = _fov;
znear = _znear;
zfar = _zfar;
// swap near and far plane for reverse z
matrices.perspective = perspective(fov, _aspect, zfar, znear, &matrices.invPerspective);
}
void Camera::setWorldUp(const glm::float3 up)
{
mWorldUp = up;
}
glm::float3 Camera::getWorldUp()
{
return mWorldUp;
}
void Camera::setWorldForward(const glm::float3 forward)
{
mWorldForward = forward;
}
glm::float3 Camera::getWorldForward()
{
return mWorldForward;
}
glm::float4x4& Camera::getPerspective()
{
return matrices.perspective;
}
glm::float4x4 Camera::getView()
{
return matrices.view;
}
void Camera::updateAspectRatio(float _aspect)
{
setPerspective(fov, _aspect, znear, zfar);
}
void Camera::setPosition(glm::float3 _position)
{
position = _position;
updateViewMatrix();
}
glm::float3 Camera::getPosition()
{
return position;
}
void Camera::setRotation(glm::quat rotation)
{
mOrientation = rotation;
updateViewMatrix();
}
void Camera::rotate(float rightAngle, float upAngle)
{
const glm::quat a = glm::angleAxis(glm::radians(upAngle) * rotationSpeed, glm::float3(1.0f, 0.0f, 0.0f));
const glm::quat b = glm::angleAxis(glm::radians(rightAngle) * rotationSpeed, glm::float3(0.0f, 1.0f, 0.0f));
// const glm::quat a = glm::angleAxis(glm::radians(upAngle) * rotationSpeed, getRight());
// const glm::quat b = glm::angleAxis(glm::radians(rightAngle) * rotationSpeed, getWorldUp());
// auto c = a * b;
// c = glm::normalize(c);
mOrientation = glm::normalize(a * mOrientation * b);
// mOrientation = glm::normalize(c * mOrientation);
updateViewMatrix();
}
glm::quat Camera::getOrientation()
{
return mOrientation;
}
void Camera::setTranslation(glm::float3 translation)
{
position = translation;
updateViewMatrix();
}
void Camera::translate(glm::float3 delta)
{
position += glm::conjugate(mOrientation) * delta;
updateViewMatrix();
}
void Camera::update(float deltaTime)
{
updated = false;
if (type == CameraType::firstperson)
{
if (moving())
{
float moveSpeed = deltaTime * movementSpeed;
if (keys.up)
position += getWorldUp() * moveSpeed;
if (keys.down)
position -= getWorldUp() * moveSpeed;
if (keys.left)
position -= getRight() * moveSpeed;
if (keys.right)
position += getRight() * moveSpeed;
if (keys.forward)
position += getFront() * moveSpeed;
if (keys.back)
position -= getFront() * moveSpeed;
updateViewMatrix();
}
}
}
} // namespace oka
|
arhix52/Strelka/src/scene/CMakeLists.txt | cmake_minimum_required(VERSION 3.20)
find_package(glm REQUIRED)
# include(${ROOT_HOME}/cmake/StaticAnalyzers.cmake)
# Scene
set(SCENE_SOURCES
${ROOT_HOME}/include/scene/scene.h
${ROOT_HOME}/include/scene/camera.h
${ROOT_HOME}/src/scene/scene.cpp
${ROOT_HOME}/src/scene/camera.cpp
)
set(SCENELIB_NAME scene)
add_library(${SCENELIB_NAME} OBJECT ${SCENE_SOURCES})
target_include_directories(${SCENELIB_NAME} PUBLIC ${ROOT_HOME}/external/glm)
target_include_directories(${SCENELIB_NAME} PUBLIC ${ROOT_HOME}/include/scene)
target_include_directories(${SCENELIB_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${SCENELIB_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${SCENELIB_NAME} PUBLIC glm::glm)
|
arhix52/Strelka/src/scene/scene.cpp | #include "scene.h"
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/norm.hpp>
#include <algorithm>
#include <array>
#include <filesystem>
#include <map>
#include <utility>
namespace fs = std::filesystem;
namespace oka
{
uint32_t Scene::createMesh(const std::vector<Vertex>& vb, const std::vector<uint32_t>& ib)
{
std::scoped_lock lock(mMeshMutex);
Mesh* mesh = nullptr;
uint32_t meshId = -1;
if (mDelMesh.empty())
{
meshId = mMeshes.size(); // add mesh to storage
mMeshes.push_back({});
mesh = &mMeshes.back();
}
else
{
meshId = mDelMesh.top(); // get index from stack
mDelMesh.pop(); // del taken index from stack
mesh = &mMeshes[meshId];
}
mesh->mIndex = mIndices.size(); // Index of 1st index in index buffer
mesh->mCount = ib.size(); // amount of indices in mesh
mesh->mVbOffset = mVertices.size();
mesh->mVertexCount = vb.size();
// const uint32_t ibOffset = mVertices.size(); // adjust indices for global index buffer
// for (int i = 0; i < ib.size(); ++i)
// {
// mIndices.push_back(ibOffset + ib[i]);
// }
mIndices.insert(mIndices.end(), ib.begin(), ib.end());
mVertices.insert(mVertices.end(), vb.begin(), vb.end()); // copy vertices
return meshId;
}
uint32_t Scene::createInstance(const Instance::Type type,
const uint32_t geomId,
const uint32_t materialId,
const glm::mat4& transform,
const uint32_t lightId)
{
std::scoped_lock lock(mInstanceMutex);
Instance* inst = nullptr;
uint32_t instId = -1;
if (mDelInstances.empty())
{
instId = mInstances.size(); // add instance to storage
mInstances.push_back({});
inst = &mInstances.back();
}
else
{
instId = mDelInstances.top(); // get index from stack
mDelInstances.pop(); // del taken index from stack
inst = &mInstances[instId];
}
inst->type = type;
if (inst->type == Instance::Type::eMesh || inst->type == Instance::Type::eLight)
{
inst->mMeshId = geomId;
}
else if (inst->type == Instance::Type::eCurve)
{
inst->mCurveId = geomId;
}
inst->mMaterialId = materialId;
inst->transform = transform;
inst->mLightId = lightId;
mOpaqueInstances.push_back(instId);
return instId;
}
uint32_t Scene::addMaterial(const MaterialDescription& material)
{
// TODO: fix here
uint32_t res = mMaterialsDescs.size();
mMaterialsDescs.push_back(material);
return res;
}
std::string Scene::getSceneFileName()
{
fs::path p(modelPath);
return p.filename().string();
};
std::string Scene::getSceneDir()
{
fs::path p(modelPath);
return p.parent_path().string();
};
// valid range of coordinates [-1; 1]
uint32_t packNormals(const glm::float3& normal)
{
uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f);
packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10;
packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20;
return packed;
}
uint32_t Scene::createRectLightMesh()
{
if (mRectLightMeshId != -1)
{
return mRectLightMeshId;
}
std::vector<Scene::Vertex> vb;
Scene::Vertex v1, v2, v3, v4;
v1.pos = glm::float4(0.5f, 0.5f, 0.0f, 1.0f); // top right 0
v2.pos = glm::float4(-0.5f, 0.5f, 0.0f, 1.0f); // top left 1
v3.pos = glm::float4(-0.5f, -0.5f, 0.0f, 1.0f); // bottom left 2
v4.pos = glm::float4(0.5f, -0.5f, 0.0f, 1.0f); // bottom right 3
glm::float3 normal = glm::float3(0.f, 0.f, 1.f);
v1.normal = v2.normal = v3.normal = v4.normal = packNormals(normal);
std::vector<uint32_t> ib = { 0, 1, 2, 2, 3, 0 };
vb.push_back(v1);
vb.push_back(v2);
vb.push_back(v3);
vb.push_back(v4);
uint32_t meshId = createMesh(vb, ib);
assert(meshId != -1);
return meshId;
}
uint32_t Scene::createSphereLightMesh()
{
if (mSphereLightMeshId != -1)
{
return mSphereLightMeshId;
}
std::vector<Scene::Vertex> vertices;
std::vector<uint32_t> indices;
const int segments = 16;
const int rings = 16;
const float radius = 1.0f;
// Generate vertices and normals
for (int i = 0; i <= rings; ++i)
{
float theta = static_cast<float>(i) * static_cast<float>(M_PI) / static_cast<float>(rings);
float sinTheta = sin(theta);
float cosTheta = cos(theta);
for (int j = 0; j <= segments; ++j)
{
float phi = static_cast<float>(j) * 2.0f * static_cast<float>(M_PI) / static_cast<float>(segments);
float sinPhi = sin(phi);
float cosPhi = cos(phi);
float x = cosPhi * sinTheta;
float y = cosTheta;
float z = sinPhi * sinTheta;
glm::float3 pos = { radius * x, radius * y, radius * z };
glm::float3 normal = { x, y, z };
vertices.push_back(Scene::Vertex{ pos, 0, packNormals(normal) });
}
}
// Generate indices
for (int i = 0; i < rings; ++i)
{
for (int j = 0; j < segments; ++j)
{
int p0 = i * (segments + 1) + j;
int p1 = p0 + 1;
int p2 = (i + 1) * (segments + 1) + j;
int p3 = p2 + 1;
indices.push_back(p0);
indices.push_back(p1);
indices.push_back(p2);
indices.push_back(p2);
indices.push_back(p1);
indices.push_back(p3);
}
}
const uint32_t meshId = createMesh(vertices, indices);
assert(meshId != -1);
return meshId;
}
uint32_t Scene::createDiscLightMesh()
{
if (mDiskLightMeshId != -1)
{
return mDiskLightMeshId;
}
std::vector<Scene::Vertex> vertices;
std::vector<uint32_t> indices;
Scene::Vertex v1, v2;
v1.pos = glm::float4(0.f, 0.f, 0.f, 1.f);
v2.pos = glm::float4(1.0f, 0.f, 0.f, 1.f);
glm::float3 normal = glm::float3(0.f, 0.f, 1.f);
v1.normal = v2.normal = packNormals(normal);
vertices.push_back(v1); // central point
vertices.push_back(v2); // first point
const float diskRadius = 1.0f; // param
const float step = 2.0f * M_PI / 16;
float angle = 0;
for (int i = 0; i < 16; ++i)
{
indices.push_back(0); // each triangle have central point
indices.push_back(vertices.size() - 1); // prev vertex
angle += step;
const float x = cos(angle) * diskRadius;
const float y = sin(angle) * diskRadius;
Scene::Vertex v;
v.pos = glm::float4(x, y, 0.0f, 1.0f);
v.normal = packNormals(normal);
vertices.push_back(v);
indices.push_back(vertices.size() - 1); // added vertex
}
uint32_t meshId = createMesh(vertices, indices);
assert(meshId != -1);
return meshId;
}
void Scene::updateAnimation(const float time)
{
if (mAnimations.empty())
{
return;
}
auto& animation = mAnimations[0];
for (auto& channel : animation.channels)
{
assert(channel.node < mNodes.size());
auto& sampler = animation.samplers[channel.samplerIndex];
if (sampler.inputs.size() > sampler.outputsVec4.size())
{
continue;
}
for (size_t i = 0; i < sampler.inputs.size() - 1; i++)
{
if ((time >= sampler.inputs[i]) && (time <= sampler.inputs[i + 1]))
{
float u = std::max(0.0f, time - sampler.inputs[i]) / (sampler.inputs[i + 1] - sampler.inputs[i]);
if (u <= 1.0f)
{
switch (channel.path)
{
case AnimationChannel::PathType::TRANSLATION: {
glm::vec4 trans = glm::mix(sampler.outputsVec4[i], sampler.outputsVec4[i + 1], u);
mNodes[channel.node].translation = glm::float3(trans);
break;
}
case AnimationChannel::PathType::SCALE: {
glm::vec4 scale = glm::mix(sampler.outputsVec4[i], sampler.outputsVec4[i + 1], u);
mNodes[channel.node].scale = glm::float3(scale);
break;
}
case AnimationChannel::PathType::ROTATION: {
float floatRotation[4] = { (float)sampler.outputsVec4[i][3], (float)sampler.outputsVec4[i][0],
(float)sampler.outputsVec4[i][1], (float)sampler.outputsVec4[i][2] };
float floatRotation1[4] = { (float)sampler.outputsVec4[i + 1][3],
(float)sampler.outputsVec4[i + 1][0],
(float)sampler.outputsVec4[i + 1][1],
(float)sampler.outputsVec4[i + 1][2] };
glm::quat q1 = glm::make_quat(floatRotation);
glm::quat q2 = glm::make_quat(floatRotation1);
mNodes[channel.node].rotation = glm::normalize(glm::slerp(q1, q2, u));
break;
}
}
}
}
}
}
mCameras[0].matrices.view = getTransform(mCameras[0].node);
}
uint32_t Scene::createLight(const UniformLightDesc& desc)
{
uint32_t lightId = (uint32_t)mLights.size();
Light l;
mLights.push_back(l);
mLightDesc.push_back(desc);
updateLight(lightId, desc);
// TODO: only for rect light
// Lazy init light mesh
glm::float4x4 scaleMatrix = glm::float4x4(0.f);
uint32_t currentLightMeshId = 0;
if (desc.type == 0)
{
mRectLightMeshId = createRectLightMesh();
currentLightMeshId = mRectLightMeshId;
scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.width, desc.height, 1.0f));
}
else if (desc.type == 1)
{
mDiskLightMeshId = createDiscLightMesh();
currentLightMeshId = mDiskLightMeshId;
scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius));
}
else if (desc.type == 2)
{
mSphereLightMeshId = createSphereLightMesh();
currentLightMeshId = mSphereLightMeshId;
scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius));
}
else if (desc.type == 3)
{
// distant light
currentLightMeshId = 0; // empty
scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius));
}
const glm::float4x4 transform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc);
uint32_t instId = createInstance(Instance::Type::eLight, currentLightMeshId, (uint32_t)-1, transform, lightId);
assert(instId != -1);
mLightIdToInstanceId[lightId] = instId;
return lightId;
}
void Scene::updateLight(const uint32_t lightId, const UniformLightDesc& desc)
{
const float intensityPerPoint = desc.intensity; // light intensity
// transform to GPU light
// Rect Light
if (desc.type == 0)
{
const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(desc.width, desc.height, 1.0f));
const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc);
mLights[lightId].points[0] = localTransform * glm::float4(0.5f, 0.5f, 0.0f, 1.0f);
mLights[lightId].points[1] = localTransform * glm::float4(-0.5f, 0.5f, 0.0f, 1.0f);
mLights[lightId].points[2] = localTransform * glm::float4(-0.5f, -0.5f, 0.0f, 1.0f);
mLights[lightId].points[3] = localTransform * glm::float4(0.5f, -0.5f, 0.0f, 1.0f);
mLights[lightId].type = 0;
}
else if (desc.type == 1)
{
// Disk Light
const glm::float4x4 scaleMatrix =
glm::scale(glm::float4x4(1.0f), glm::float3(desc.radius, desc.radius, desc.radius));
const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc);
mLights[lightId].points[0] = glm::float4(desc.radius, 0.f, 0.f, 0.f); // save radius
mLights[lightId].points[1] = localTransform * glm::float4(0.f, 0.f, 0.f, 1.f); // save O
mLights[lightId].points[2] = localTransform * glm::float4(1.f, 0.f, 0.f, 0.f); // OXws
mLights[lightId].points[3] = localTransform * glm::float4(0.f, 1.f, 0.f, 0.f); // OYws
glm::float4 normal = localTransform * glm::float4(0, 0, 1.f, 0.0f);
mLights[lightId].normal = normal;
mLights[lightId].type = 1;
}
else if (desc.type == 2)
{
// Sphere Light
const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), glm::float3(1.0f, 1.0f, 1.0f));
const glm::float4x4 localTransform = desc.useXform ? scaleMatrix * desc.xform : getTransform(desc);
mLights[lightId].points[0] = glm::float4(desc.radius, 0.f, 0.f, 0.f); // save radius
mLights[lightId].points[1] = localTransform * glm::float4(0.f, 0.f, 0.f, 1.f); // save O
mLights[lightId].type = 2;
}
else if (desc.type == 3)
{
// distant light https://openusd.org/release/api/class_usd_lux_distant_light.html
mLights[lightId].type = 3;
mLights[lightId].halfAngle = desc.halfAngle;
const glm::float4x4 scaleMatrix = glm::float4x4(1.0f);
const glm::float4x4 localTransform = desc.useXform ? desc.xform * scaleMatrix : getTransform(desc);
mLights[lightId].normal = glm::normalize(localTransform * glm::float4(0.0f, 0.0f, -1.0f, 0.0f)); // -Z
}
mLights[lightId].color = glm::float4(desc.color, 1.0f) * intensityPerPoint;
}
void Scene::removeInstance(const uint32_t instId)
{
mDelInstances.push(instId); // marked as removed
}
void Scene::removeMesh(const uint32_t meshId)
{
mDelMesh.push(meshId); // marked as removed
}
void Scene::removeMaterial(const uint32_t materialId)
{
mDelMaterial.push(materialId); // marked as removed
}
std::vector<uint32_t>& Scene::getOpaqueInstancesToRender(const glm::float3& camPos)
{
return mOpaqueInstances;
}
std::vector<uint32_t>& Scene::getTransparentInstancesToRender(const glm::float3& camPos)
{
return mTransparentInstances;
}
std::set<uint32_t> Scene::getDirtyInstances()
{
return this->mDirtyInstances;
}
bool Scene::getFrMod()
{
return this->FrMod;
}
void Scene::updateInstanceTransform(uint32_t instId, glm::float4x4 newTransform)
{
Instance& inst = mInstances[instId];
inst.transform = newTransform;
mDirtyInstances.insert(instId);
}
void Scene::beginFrame()
{
FrMod = true;
mDirtyInstances.clear();
}
void Scene::endFrame()
{
FrMod = false;
}
uint32_t Scene::createCurve(const Curve::Type type,
const std::vector<uint32_t>& vertexCounts,
const std::vector<glm::float3>& points,
const std::vector<float>& widths)
{
Curve c = {};
c.mPointsStart = mCurvePoints.size();
c.mPointsCount = points.size();
mCurvePoints.insert(mCurvePoints.end(), points.begin(), points.end());
c.mVertexCountsStart = mCurveVertexCounts.size();
c.mVertexCountsCount = vertexCounts.size();
mCurveVertexCounts.insert(mCurveVertexCounts.end(), vertexCounts.begin(), vertexCounts.end());
if (!widths.empty())
{
c.mWidthsCount = widths.size();
c.mWidthsStart = mCurveWidths.size();
mCurveWidths.insert(mCurveWidths.end(), widths.begin(), widths.end());
}
else
{
c.mWidthsCount = -1;
c.mWidthsStart = -1;
}
uint32_t res = mCurves.size();
mCurves.push_back(c);
return res;
}
} // namespace oka
|
arhix52/Strelka/src/log/logmanager.cpp | #include "logmanager.h"
#include <spdlog/spdlog.h>
#include <spdlog/cfg/env.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <memory>
#include <vector>
oka::Logmanager::Logmanager()
{
initialize();
}
oka::Logmanager::~Logmanager()
{
shutdown();
}
void oka::Logmanager::initialize()
{
auto logger = spdlog::get("Strelka");
if (!logger)
{
spdlog::cfg::load_env_levels();
auto consolesink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("strelka.log");
std::vector<spdlog::sink_ptr> sinks = { consolesink, fileSink };
logger = std::make_shared<spdlog::logger>("Strelka", sinks.begin(), sinks.end());
// TODO: env var doesn't work on linux
logger->set_level(spdlog::level::trace);
logger->flush_on(spdlog::level::trace);
#if defined(WIN32)
logger->set_level(spdlog::level::trace);
logger->flush_on(spdlog::level::trace);
#endif
spdlog::register_logger(logger);
}
}
void oka::Logmanager::shutdown()
{
spdlog::shutdown();
}
|
arhix52/Strelka/src/log/CMakeLists.txt | cmake_minimum_required(VERSION 3.22)
set(LOGLIB_NAME logger)
set(LOGLIB_SOURCES
${ROOT_HOME}/include/log/log.h
${ROOT_HOME}/include/log/logmanager.h
${ROOT_HOME}/src/log/logmanager.cpp)
find_package(spdlog REQUIRED)
add_library(${LOGLIB_NAME} STATIC ${LOGLIB_SOURCES})
target_include_directories(${LOGLIB_NAME} PUBLIC ${ROOT_HOME}/include/log)
# target_include_directories(${LOGLIB_NAME} PUBLIC spdlog::spdlog)
target_link_libraries(${LOGLIB_NAME} PUBLIC spdlog::spdlog)
|
arhix52/Strelka/src/sceneloader/gltfloader.cpp | #include "gltfloader.h"
#include "camera.h"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define TINYGLTF_IMPLEMENTATION
#include "tiny_gltf.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/compatibility.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <iostream>
#include <log/log.h>
namespace fs = std::filesystem;
#include "nlohmann/json.hpp"
using json = nlohmann::json;
namespace oka
{
// valid range of coordinates [-10; 10]
uint32_t packUV(const glm::float2& uv)
{
int32_t packed = (uint32_t)((uv.x + 10.0f) / 20.0f * 16383.99999f);
packed += (uint32_t)((uv.y + 10.0f) / 20.0f * 16383.99999f) << 16;
return packed;
}
// valid range of coordinates [-1; 1]
uint32_t packNormal(const glm::float3& normal)
{
uint32_t packed = (uint32_t)((normal.x + 1.0f) / 2.0f * 511.99999f);
packed += (uint32_t)((normal.y + 1.0f) / 2.0f * 511.99999f) << 10;
packed += (uint32_t)((normal.z + 1.0f) / 2.0f * 511.99999f) << 20;
return packed;
}
// valid range of coordinates [-10; 10]
uint32_t packTangent(const glm::float3& tangent)
{
uint32_t packed = (uint32_t)((tangent.x + 10.0f) / 20.0f * 511.99999f);
packed += (uint32_t)((tangent.y + 10.0f) / 20.0f * 511.99999f) << 10;
packed += (uint32_t)((tangent.z + 10.0f) / 20.0f * 511.99999f) << 20;
return packed;
}
glm::float2 unpackUV(uint32_t val)
{
glm::float2 uv;
uv.y = ((val & 0xffff0000) >> 16) / 16383.99999f * 10.0f - 5.0f;
uv.x = (val & 0x0000ffff) / 16383.99999f * 10.0f - 5.0f;
return uv;
}
void computeTangent(std::vector<Scene::Vertex>& vertices,
const std::vector<uint32_t>& indices)
{
const size_t lastIndex = indices.size();
Scene::Vertex& v0 = vertices[indices[lastIndex - 3]];
Scene::Vertex& v1 = vertices[indices[lastIndex - 2]];
Scene::Vertex& v2 = vertices[indices[lastIndex - 1]];
glm::float2 uv0 = unpackUV(v0.uv);
glm::float2 uv1 = unpackUV(v1.uv);
glm::float2 uv2 = unpackUV(v2.uv);
glm::float3 deltaPos1 = v1.pos - v0.pos;
glm::float3 deltaPos2 = v2.pos - v0.pos;
glm::vec2 deltaUV1 = uv1 - uv0;
glm::vec2 deltaUV2 = uv2 - uv0;
glm::vec3 tangent{ 0.0f, 0.0f, 1.0f };
const float d = deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x;
if (abs(d) > 1e-6)
{
float r = 1.0f / d;
tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y) * r;
}
glm::uint32_t packedTangent = packTangent(tangent);
v0.tangent = packedTangent;
v1.tangent = packedTangent;
v2.tangent = packedTangent;
}
void processPrimitive(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Primitive& primitive, const glm::float4x4& transform, const float globalScale)
{
using namespace std;
assert(primitive.attributes.find("POSITION") != primitive.attributes.end());
const tinygltf::Accessor& positionAccessor = model.accessors[primitive.attributes.find("POSITION")->second];
const tinygltf::BufferView& positionView = model.bufferViews[positionAccessor.bufferView];
const float* positionData = reinterpret_cast<const float*>(&model.buffers[positionView.buffer].data[positionAccessor.byteOffset + positionView.byteOffset]);
assert(positionData != nullptr);
const uint32_t vertexCount = static_cast<uint32_t>(positionAccessor.count);
assert(vertexCount != 0);
const int byteStride = positionAccessor.ByteStride(positionView);
assert(byteStride > 0); // -1 means invalid glTF
int posStride = byteStride / sizeof(float);
// Normals
const float* normalsData = nullptr;
int normalStride = 0;
if (primitive.attributes.find("NORMAL") != primitive.attributes.end())
{
const tinygltf::Accessor& normalAccessor = model.accessors[primitive.attributes.find("NORMAL")->second];
const tinygltf::BufferView& normView = model.bufferViews[normalAccessor.bufferView];
normalsData = reinterpret_cast<const float*>(&(model.buffers[normView.buffer].data[normalAccessor.byteOffset + normView.byteOffset]));
assert(normalsData != nullptr);
normalStride = normalAccessor.ByteStride(normView) / sizeof(float);
assert(normalStride > 0);
}
// UVs
const float* texCoord0Data = nullptr;
int texCoord0Stride = 0;
if (primitive.attributes.find("TEXCOORD_0") != primitive.attributes.end())
{
const tinygltf::Accessor& uvAccessor = model.accessors[primitive.attributes.find("TEXCOORD_0")->second];
const tinygltf::BufferView& uvView = model.bufferViews[uvAccessor.bufferView];
texCoord0Data = reinterpret_cast<const float*>(&(model.buffers[uvView.buffer].data[uvAccessor.byteOffset + uvView.byteOffset]));
texCoord0Stride = uvAccessor.ByteStride(uvView) / sizeof(float);
}
int matId = primitive.material;
if (matId == -1)
{
matId = 0; // TODO: should be index of default material
}
glm::float3 sum = glm::float3(0.0f, 0.0f, 0.0f);
std::vector<oka::Scene::Vertex> vertices;
vertices.reserve(vertexCount);
for (uint32_t v = 0; v < vertexCount; ++v)
{
oka::Scene::Vertex vertex{};
vertex.pos = glm::make_vec3(&positionData[v * posStride]) * globalScale;
vertex.normal = packNormal(glm::normalize(glm::vec3(normalsData ? glm::make_vec3(&normalsData[v * normalStride]) : glm::vec3(0.0f))));
vertex.uv = packUV(texCoord0Data ? glm::make_vec2(&texCoord0Data[v * texCoord0Stride]) : glm::vec3(0.0f));
vertices.push_back(vertex);
sum += vertex.pos;
}
const glm::float3 massCenter = sum / (float)vertexCount;
uint32_t indexCount = 0;
std::vector<uint32_t> indices;
const bool hasIndices = (primitive.indices != -1);
assert(hasIndices); // currently support only this mode
if (hasIndices)
{
const tinygltf::Accessor& accessor = model.accessors[primitive.indices > -1 ? primitive.indices : 0];
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
indexCount = static_cast<uint32_t>(accessor.count);
assert(indexCount != 0 && (indexCount % 3 == 0));
const void* dataPtr = &(buffer.data[accessor.byteOffset + bufferView.byteOffset]);
indices.reserve(indexCount);
switch (accessor.componentType)
{
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: {
const uint32_t* buf = static_cast<const uint32_t*>(dataPtr);
for (size_t index = 0; index < indexCount; index++)
{
indices.push_back(buf[index]);
}
computeTangent(vertices, indices);
break;
}
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: {
const uint16_t* buf = static_cast<const uint16_t*>(dataPtr);
for (size_t index = 0; index < indexCount; index++)
{
indices.push_back(buf[index]);
}
computeTangent(vertices, indices);
break;
}
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: {
const uint8_t* buf = static_cast<const uint8_t*>(dataPtr);
for (size_t index = 0; index < indexCount; index++)
{
indices.push_back(buf[index]);
}
computeTangent(vertices, indices);
break;
}
default:
std::cerr << "Index component type " << accessor.componentType << " not supported!" << std::endl;
return;
}
}
uint32_t meshId = scene.createMesh(vertices, indices);
assert(meshId != -1);
uint32_t instId = scene.createInstance(Instance::Type::eMesh, meshId, matId, transform);
assert(instId != -1);
}
void processMesh(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Mesh& mesh, const glm::float4x4& transform, const float globalScale)
{
using namespace std;
cout << "Mesh name: " << mesh.name << endl;
cout << "Primitive count: " << mesh.primitives.size() << endl;
for (size_t i = 0; i < mesh.primitives.size(); ++i)
{
processPrimitive(model, scene, mesh.primitives[i], transform, globalScale);
}
}
glm::float4x4 getTransform(const tinygltf::Node& node, const float globalScale)
{
if (node.matrix.empty())
{
glm::float3 scale{ 1.0f };
if (!node.scale.empty())
{
scale = glm::float3((float)node.scale[0], (float)node.scale[1], (float)node.scale[2]);
// check that scale is uniform, otherwise we have to support it in shader
// assert(scale.x == scale.y && scale.y == scale.z);
}
glm::quat rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
if (!node.rotation.empty())
{
const float floatRotation[4] = {
(float)node.rotation[3],
(float)node.rotation[0],
(float)node.rotation[1],
(float)node.rotation[2],
};
rotation = glm::make_quat(floatRotation);
}
glm::float3 translation{ 0.0f };
if (!node.translation.empty())
{
translation = glm::float3((float)node.translation[0], (float)node.translation[1], (float)node.translation[2]);
translation *= globalScale;
}
const glm::float4x4 translationMatrix = glm::translate(glm::float4x4(1.0f), translation);
const glm::float4x4 rotationMatrix{ rotation };
const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), scale);
const glm::float4x4 localTransform = translationMatrix * rotationMatrix * scaleMatrix;
return localTransform;
}
else
{
glm::float4x4 localTransform = glm::make_mat4(node.matrix.data());
return localTransform;
}
}
void processNode(const tinygltf::Model& model, oka::Scene& scene, const tinygltf::Node& node, const uint32_t currentNodeId, const glm::float4x4& baseTransform, const float globalScale)
{
using namespace std;
cout << "Node name: " << node.name << endl;
const glm::float4x4 localTransform = getTransform(node, globalScale);
const glm::float4x4 globalTransform = baseTransform * localTransform;
if (node.mesh != -1) // mesh exist
{
const tinygltf::Mesh& mesh = model.meshes[node.mesh];
processMesh(model, scene, mesh, globalTransform, globalScale);
}
else if (node.camera != -1) // camera node
{
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(globalTransform, scale, rotation, translation, skew, perspective);
rotation = glm::conjugate(rotation);
scene.getCamera(node.camera).node = currentNodeId;
scene.getCamera(node.camera).position = translation * scale;
scene.getCamera(node.camera).mOrientation = rotation;
scene.getCamera(node.camera).updateViewMatrix();
}
for (int i = 0; i < node.children.size(); ++i)
{
scene.mNodes[node.children[i]].parent = currentNodeId;
processNode(model, scene, model.nodes[node.children[i]], node.children[i], globalTransform, globalScale);
}
}
oka::Scene::MaterialDescription convertToOmniPBR(const tinygltf::Model& model, const tinygltf::Material& material)
{
const std::string& fileUri = "OmniPBR.mdl";
const std::string& name = "OmniPBR";
oka::Scene::MaterialDescription materialDesc{};
materialDesc.file = fileUri;
materialDesc.name = name;
materialDesc.type = oka::Scene::MaterialDescription::Type::eMdl;
materialDesc.color =
glm::float3(material.pbrMetallicRoughness.baseColorFactor[0], material.pbrMetallicRoughness.baseColorFactor[1],
material.pbrMetallicRoughness.baseColorFactor[2]);
materialDesc.hasColor = true;
oka::MaterialManager::Param colorParam = {};
colorParam.name = "diffuse_color_constant";
colorParam.type = oka::MaterialManager::Param::Type::eFloat3;
colorParam.value.resize(sizeof(float) * 3);
memcpy(colorParam.value.data(), glm::value_ptr(materialDesc.color), sizeof(float) * 3);
materialDesc.params.push_back(colorParam);
auto addFloat = [&](float value, const char* materialParamName) {
oka::MaterialManager::Param param{};
param.name = materialParamName;
param.type = oka::MaterialManager::Param::Type::eFloat;
param.value.resize(sizeof(float));
*((float*)param.value.data()) = value;
materialDesc.params.push_back(param);
};
addFloat((float)material.pbrMetallicRoughness.roughnessFactor, "reflection_roughness_constant");
addFloat((float)material.pbrMetallicRoughness.metallicFactor, "metallic_constant");
auto addTexture = [&](int texId, const char* materialParamName) {
const auto imageId = model.textures[texId].source;
const auto textureUri = model.images[imageId].uri;
oka::MaterialManager::Param paramTexture{};
paramTexture.name = materialParamName;
paramTexture.type = oka::MaterialManager::Param::Type::eTexture;
paramTexture.value.resize(textureUri.size());
memcpy(paramTexture.value.data(), textureUri.data(), textureUri.size());
materialDesc.params.push_back(paramTexture);
};
auto texId = material.pbrMetallicRoughness.baseColorTexture.index;
if (texId >= 0)
{
addTexture(texId, "diffuse_texture");
}
auto normalTexId = material.normalTexture.index;
if (normalTexId >= 0)
{
addTexture(normalTexId, "normalmap_texture");
}
return materialDesc;
}
oka::Scene::MaterialDescription convertToOmniGlass(const tinygltf::Model& model, const tinygltf::Material& material)
{
oka::Scene::MaterialDescription materialDesc{};
materialDesc.file = "OmniGlass.mdl";
materialDesc.name = "OmniGlass";
materialDesc.type = oka::Scene::MaterialDescription::Type::eMdl;
oka::MaterialManager::Param param{};
param.name = "enable_opacity";
param.type = oka::MaterialManager::Param::Type::eBool;
param.value.resize(sizeof(bool));
*((bool*)param.value.data()) = true;
materialDesc.params.push_back(param);
// materialDesc.color =
// glm::float3(material.pbrMetallicRoughness.baseColorFactor[0], material.pbrMetallicRoughness.baseColorFactor[1],
// material.pbrMetallicRoughness.baseColorFactor[2]);
// oka::MaterialManager::Param colorParam = {};
// colorParam.name = "glass_color";
// colorParam.type = oka::MaterialManager::Param::Type::eFloat3;
// colorParam.value.resize(sizeof(float) * 3);
// memcpy(colorParam.value.data(), glm::value_ptr(materialDesc.color), sizeof(float) * 3);
// materialDesc.params.push_back(colorParam);
auto addBool = [&](bool value, const char* materialParamName) {
oka::MaterialManager::Param param{};
param.name = materialParamName;
param.type = oka::MaterialManager::Param::Type::eBool;
param.value.resize(sizeof(float));
*((bool*)param.value.data()) = value;
materialDesc.params.push_back(param);
};
addBool(false, "thin_walled");
auto addFloat = [&](float value, const char* materialParamName) {
oka::MaterialManager::Param param{};
param.name = materialParamName;
param.type = oka::MaterialManager::Param::Type::eFloat;
param.value.resize(sizeof(float));
*((float*)param.value.data()) = value;
materialDesc.params.push_back(param);
};
addFloat((float)material.pbrMetallicRoughness.roughnessFactor, "frosting_roughness");
return materialDesc;
}
void loadMaterials(const tinygltf::Model& model, oka::Scene& scene)
{
for (const tinygltf::Material& material : model.materials)
{
if (material.alphaMode == "OPAQUE")
{
scene.addMaterial(convertToOmniPBR(model, material));
}
else
{
scene.addMaterial(convertToOmniGlass(model, material));
}
}
}
void loadCameras(const tinygltf::Model& model, oka::Scene& scene)
{
for (uint32_t i = 0; i < model.cameras.size(); ++i)
{
const tinygltf::Camera& cameraGltf = model.cameras[i];
if (strcmp(cameraGltf.type.c_str(), "perspective") == 0)
{
oka::Camera camera;
camera.fov = cameraGltf.perspective.yfov * (180.0f / 3.1415926f);
camera.znear = cameraGltf.perspective.znear;
camera.zfar = cameraGltf.perspective.zfar;
camera.name = cameraGltf.name;
scene.addCamera(camera);
}
else
{
// not supported
}
}
if (scene.getCameraCount() == 0)
{
// add default camera
Camera camera;
camera.updateViewMatrix();
scene.addCamera(camera);
}
}
void loadAnimation(const tinygltf::Model& model, oka::Scene& scene)
{
std::vector<oka::Scene::Animation> animations;
using namespace std;
for (const tinygltf::Animation& animation : model.animations)
{
oka::Scene::Animation anim{};
cout << "Animation name: " << animation.name << endl;
for (const tinygltf::AnimationSampler& sampler : animation.samplers)
{
oka::Scene::AnimationSampler samp{};
{
const tinygltf::Accessor& accessor = model.accessors[sampler.input];
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
assert(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT);
const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
const float* buf = static_cast<const float*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
samp.inputs.push_back(buf[index]);
}
for (auto input : samp.inputs)
{
if (input < anim.start)
{
anim.start = input;
};
if (input > anim.end)
{
anim.end = input;
}
}
}
{
const tinygltf::Accessor& accessor = model.accessors[sampler.output];
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
assert(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT);
const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
switch (accessor.type)
{
case TINYGLTF_TYPE_VEC3: {
const glm::vec3* buf = static_cast<const glm::vec3*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
samp.outputsVec4.push_back(glm::vec4(buf[index], 0.0f));
}
break;
}
case TINYGLTF_TYPE_VEC4: {
const glm::vec4* buf = static_cast<const glm::vec4*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
samp.outputsVec4.push_back(buf[index]);
}
break;
}
default: {
std::cout << "unknown type" << std::endl;
break;
}
}
anim.samplers.push_back(samp);
}
}
for (const tinygltf::AnimationChannel& channel : animation.channels)
{
oka::Scene::AnimationChannel chan{};
if (channel.target_path == "rotation")
{
chan.path = oka::Scene::AnimationChannel::PathType::ROTATION;
}
if (channel.target_path == "translation")
{
chan.path = oka::Scene::AnimationChannel::PathType::TRANSLATION;
}
if (channel.target_path == "scale")
{
chan.path = oka::Scene::AnimationChannel::PathType::SCALE;
}
if (channel.target_path == "weights")
{
std::cout << "weights not yet supported, skipping channel" << std::endl;
continue;
}
chan.samplerIndex = channel.sampler;
chan.node = channel.target_node;
if (chan.node < 0)
{
std::cout << "skipping channel" << std::endl;
continue;
}
anim.channels.push_back(chan);
}
animations.push_back(anim);
}
scene.mAnimations = animations;
}
void loadNodes(const tinygltf::Model& model, oka::Scene& scene, const float globalScale = 1.0f)
{
for (const auto& node : model.nodes)
{
oka::Scene::Node n{};
n.name = node.name;
n.children = node.children;
glm::float3 scale{ 1.0f };
if (!node.scale.empty())
{
scale = glm::float3((float)node.scale[0], (float)node.scale[1], (float)node.scale[2]);
// check that scale is uniform, otherwise we have to support it in shader
// assert(scale.x == scale.y && scale.y == scale.z);
}
n.scale = scale;
//glm::quat rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
glm::quat rotation = glm::quat_cast(glm::float4x4(1.0f));
if (!node.rotation.empty())
{
const float floatRotation[4] = {
(float)node.rotation[3],
(float)node.rotation[0],
(float)node.rotation[1],
(float)node.rotation[2],
};
rotation = glm::make_quat(floatRotation);
}
n.rotation = rotation;
glm::float3 translation{ 0.0f };
if (!node.translation.empty())
{
translation = glm::float3((float)node.translation[0], (float)node.translation[1], (float)node.translation[2]);
translation *= globalScale;
}
n.translation = translation;
scene.mNodes.push_back(n);
}
}
oka::Scene::UniformLightDesc parseFromJson(const json& light)
{
oka::Scene::UniformLightDesc desc{};
const auto position = light["position"];
desc.position = glm::float3(position[0], position[1], position[2]);
const auto orientation = light["orientation"];
desc.orientation = glm::float3(orientation[0], orientation[1], orientation[2]);
desc.width = float(light["width"]);
desc.height = light["height"];
const auto color = light["color"];
desc.color = glm::float3(color[0], color[1], color[2]);
desc.intensity = float(light["intensity"]);
desc.useXform = false;
desc.type = 0;
return desc;
}
bool loadLightsFromJson(const std::string& modelPath, oka::Scene& scene)
{
std::string fileName = modelPath.substr(0, modelPath.rfind('.')); // w/o extension
std::string jsonPath = fileName + "_light" + ".json";
if (fs::exists(jsonPath))
{
STRELKA_INFO("Found light file, loading lights from it");
std::ifstream i(jsonPath);
json light;
i >> light;
for (const auto& light : light["lights"])
{
Scene::UniformLightDesc desc = parseFromJson(light);
scene.createLight(desc);
}
return true;
}
return false;
}
bool GltfLoader::loadGltf(const std::string& modelPath, oka::Scene& scene)
{
if (modelPath.empty())
{
return false;
}
using namespace std;
tinygltf::Model model;
tinygltf::TinyGLTF gltf_ctx;
std::string err;
std::string warn;
bool res = gltf_ctx.LoadASCIIFromFile(&model, &err, &warn, modelPath.c_str());
if (!res)
{
STRELKA_ERROR("Unable to load file: {}", modelPath);
return res;
}
int sceneId = model.defaultScene;
loadMaterials(model, scene);
if (loadLightsFromJson(modelPath, scene) == false)
{
STRELKA_WARNING("No light is scene, adding default distant light");
oka::Scene::UniformLightDesc lightDesc {};
// lightDesc.xform = glm::mat4(1.0f);
// lightDesc.useXform = true;
lightDesc.useXform = false;
lightDesc.position = glm::float3(0.0f, 0.0f, 0.0f);
lightDesc.orientation = glm::float3(-45.0f, 15.0f, 0.0f);
lightDesc.type = 3; // distant light
lightDesc.halfAngle = 10.0f * 0.5f * (M_PI / 180.0f);
lightDesc.intensity = 100000;
lightDesc.color = glm::float3(1.0);
scene.createLight(lightDesc);
}
loadCameras(model, scene);
const float globalScale = 1.0f;
loadNodes(model, scene, globalScale);
for (int i = 0; i < model.scenes[sceneId].nodes.size(); ++i)
{
const int rootNodeIdx = model.scenes[sceneId].nodes[i];
processNode(model, scene, model.nodes[rootNodeIdx], rootNodeIdx, glm::float4x4(1.0f), globalScale);
}
loadAnimation(model, scene);
return res;
}
} // namespace oka
|
arhix52/Strelka/src/sceneloader/CMakeLists.txt | cmake_minimum_required(VERSION 3.20)
find_package(glm REQUIRED)
find_package(TinyGLTF REQUIRED)
find_package(nlohmann_json REQUIRED)
# include(${ROOT_HOME}/cmake/StaticAnalyzers.cmake)
# Scene
set(SCENELOADER_SOURCES
${ROOT_HOME}/include/sceneloader/gltfloader.h
${ROOT_HOME}/src/sceneloader/gltfloader.cpp
)
set(SCENELOADER_NAME sceneloader)
add_library(${SCENELOADER_NAME} OBJECT ${SCENELOADER_SOURCES})
target_include_directories(${SCENELOADER_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${SCENELOADER_NAME} PUBLIC ${ROOT_HOME}/include/sceneloader/)
target_include_directories(${SCENELOADER_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${SCENELOADER_NAME} PUBLIC logger scene glm::glm TinyGLTF::TinyGLTF nlohmann_json::nlohmann_json)
|
arhix52/Strelka/src/display/DisplayFactory.cpp | #ifdef __APPLE__
#include "metal/glfwdisplay.h"
#else
#include "opengl/glfwdisplay.h"
#endif
using namespace oka;
Display* DisplayFactory::createDisplay()
{
return new glfwdisplay();
}
|
arhix52/Strelka/src/display/CMakeLists.txt | cmake_minimum_required(VERSION 3.22)
set(DISPLAYLIB_NAME display)
find_package(glad REQUIRED)
find_package(imgui REQUIRED)
find_package(glfw3 REQUIRED)
find_package(glm REQUIRED)
set(DISPLAY_SOURCES_COMMON
${ROOT_HOME}/include/display/Display.h ${ROOT_HOME}/src/display/Display.cpp
${ROOT_HOME}/src/display/DisplayFactory.cpp)
if(WIN32 OR LINUX)
set(IMGUI_SOURCES
# Imgui
${ROOT_HOME}/external/imgui/imgui_impl_glfw.cpp
${ROOT_HOME}/external/imgui/imgui_impl_opengl3.cpp
${ROOT_HOME}/external/imgui/imgui_impl_glfw.h
${ROOT_HOME}/external/imgui/imgui_impl_opengl3.h)
set(DISPLAY_SOURCES
${DISPLAY_SOURCES_COMMON} ${ROOT_HOME}/src/display/opengl/glfwdisplay.h
${ROOT_HOME}/src/display/opengl/glfwdisplay.cpp)
add_library(${DISPLAYLIB_NAME} STATIC ${DISPLAY_SOURCES} ${IMGUI_SOURCES})
target_include_directories(${DISPLAYLIB_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${DISPLAYLIB_NAME}
PUBLIC ${ROOT_HOME}/include/display)
target_include_directories(${DISPLAYLIB_NAME}
PUBLIC ${ROOT_HOME}/external/imgui/)
target_link_libraries(${DISPLAYLIB_NAME}
PUBLIC ${OPENGL_LIBRARIES}
imgui::imgui glfw glm::glm glad::glad)
endif()
if(APPLE)
set(DISPLAY_SOURCES
${DISPLAY_SOURCES_COMMON} ${ROOT_HOME}/src/display/metal/glfwdisplay.h
${ROOT_HOME}/src/display/metal/glfwdisplay.mm
${ROOT_HOME}/src/display/metal/metalcpphelp.cpp)
set(IMGUI_SOURCES
# Imgui
${ROOT_HOME}/external/imgui/imgui_impl_glfw.cpp
${ROOT_HOME}/external/imgui/imgui_impl_metal.mm
${ROOT_HOME}/external/imgui/imgui_impl_opengl3.cpp
${ROOT_HOME}/external/imgui/imgui_impl_glfw.h
${ROOT_HOME}/external/imgui/imgui_impl_metal.h
${ROOT_HOME}/external/imgui/imgui_impl_opengl3.h)
add_library(${DISPLAYLIB_NAME} STATIC ${DISPLAY_SOURCES} ${IMGUI_SOURCES})
target_include_directories(${DISPLAYLIB_NAME}
PUBLIC ${ROOT_HOME}/external/imgui/)
target_include_directories(${DISPLAYLIB_NAME} PUBLIC ${ROOT_HOME}/include/)
target_include_directories(${DISPLAYLIB_NAME}
PUBLIC ${ROOT_HOME}/include/display)
target_include_directories(${DISPLAYLIB_NAME}
PUBLIC ${ROOT_HOME}/external/metal-cpp/)
target_include_directories(${DISPLAYLIB_NAME} PUBLIC ${ROOT_HOME})
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC "-framework Foundation")
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC "-framework QuartzCore")
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC "-framework CoreGraphics")
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC "-framework Metal")
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC "-framework MetalKit")
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC logger)
target_link_libraries(${DISPLAYLIB_NAME} PUBLIC imgui::imgui glfw glm::glm)
endif()
|
arhix52/Strelka/src/display/Display.cpp | #include "Display.h"
#include "imgui.h"
#include "imgui_impl_glfw.h"
using namespace oka;
void Display::framebufferResizeCallback(GLFWwindow* window, int width, int height)
{
assert(window);
if (width == 0 || height == 0)
{
return;
}
auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window));
// app->framebufferResized = true;
ResizeHandler* handler = app->getResizeHandler();
if (handler)
{
handler->framebufferResize(width, height);
}
}
void Display::keyCallback(GLFWwindow* window,
[[maybe_unused]] int key,
[[maybe_unused]] int scancode,
[[maybe_unused]] int action,
[[maybe_unused]] int mods)
{
assert(window);
auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window));
InputHandler* handler = app->getInputHandler();
assert(handler);
handler->keyCallback(key, scancode, action, mods);
}
void Display::mouseButtonCallback(GLFWwindow* window,
[[maybe_unused]] int button,
[[maybe_unused]] int action,
[[maybe_unused]] int mods)
{
assert(window);
auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window));
InputHandler* handler = app->getInputHandler();
if (handler)
{
handler->mouseButtonCallback(button, action, mods);
}
}
void Display::handleMouseMoveCallback(GLFWwindow* window, [[maybe_unused]] double xpos, [[maybe_unused]] double ypos)
{
assert(window);
auto app = reinterpret_cast<Display*>(glfwGetWindowUserPointer(window));
InputHandler* handler = app->getInputHandler();
if (handler)
{
handler->handleMouseMoveCallback(xpos, ypos);
}
}
void Display::scrollCallback(GLFWwindow* window, [[maybe_unused]] double xoffset, [[maybe_unused]] double yoffset)
{
assert(window);
}
void Display::drawUI()
{
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuiIO& io = ImGui::GetIO();
const char* debugItems[] = { "None", "Normals", "Diffuse AOV", "Specular AOV" };
static int currentDebugItemId = 0;
/*
bool openFD = false;
static uint32_t showPropertiesId = -1;
static uint32_t lightId = -1;
static bool isLight = false;
static bool openInspector = false;
const char* stratifiedSamplingItems[] = { "None", "Random", "Stratified", "Optimized" };
static int currentSamplingItemId = 1;
*/
ImGui::Begin("Menu:"); // begin window
if (ImGui::BeginCombo("Debug view", debugItems[currentDebugItemId]))
{
for (int n = 0; n < IM_ARRAYSIZE(debugItems); n++)
{
bool is_selected = (currentDebugItemId == n);
if (ImGui::Selectable(debugItems[n], is_selected))
{
currentDebugItemId = n;
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/debug", currentDebugItemId);
if (ImGui::TreeNode("Path Tracer"))
{
const char* rectlightSamplingMethodItems[] = { "Uniform", "Advanced" };
static int currentRectlightSamplingMethodItemId = 0;
if (ImGui::BeginCombo("Rect Light Sampling", rectlightSamplingMethodItems[currentRectlightSamplingMethodItemId]))
{
for (int n = 0; n < IM_ARRAYSIZE(rectlightSamplingMethodItems); n++)
{
bool is_selected = (currentRectlightSamplingMethodItemId == n);
if (ImGui::Selectable(rectlightSamplingMethodItems[n], is_selected))
{
currentRectlightSamplingMethodItemId = n;
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
mCtx->mSettingsManager->setAs<uint32_t>(
"render/pt/rectLightSamplingMethod", currentRectlightSamplingMethodItemId);
uint32_t maxDepth = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/depth");
ImGui::SliderInt("Max Depth", (int*)&maxDepth, 1, 16);
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/depth", maxDepth);
uint32_t sppTotal = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/sppTotal");
ImGui::SliderInt("SPP Total", (int*)&sppTotal, 1, 10000);
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/sppTotal", sppTotal);
uint32_t sppSubframe = mCtx->mSettingsManager->getAs<uint32_t>("render/pt/spp");
ImGui::SliderInt("SPP Subframe", (int*)&sppSubframe, 1, 32);
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/spp", sppSubframe);
bool enableAccumulation = mCtx->mSettingsManager->getAs<bool>("render/pt/enableAcc");
ImGui::Checkbox("Enable Path Tracer Acc", &enableAccumulation);
mCtx->mSettingsManager->setAs<bool>("render/pt/enableAcc", enableAccumulation);
/*
if (ImGui::BeginCombo("Stratified Sampling", stratifiedSamplingItems[currentSamplingItemId]))
{
for (int n = 0; n < IM_ARRAYSIZE(stratifiedSamplingItems); n++)
{
bool is_selected = (currentSamplingItemId == n);
if (ImGui::Selectable(stratifiedSamplingItems[n], is_selected))
{
currentSamplingItemId = n;
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/stratifiedSamplingType", currentSamplingItemId);
*/
ImGui::TreePop();
}
if (ImGui::Button("Capture Screen"))
{
mCtx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", true);
}
float cameraSpeed = mCtx->mSettingsManager->getAs<float>("render/cameraSpeed");
ImGui::InputFloat("Camera Speed", (float*)&cameraSpeed, 0.5);
mCtx->mSettingsManager->setAs<float>("render/cameraSpeed", cameraSpeed);
const char* tonemapItems[] = { "None", "Reinhard", "ACES", "Filmic" };
static int currentTonemapItemId = 1;
if (ImGui::BeginCombo("Tonemap", tonemapItems[currentTonemapItemId]))
{
for (int n = 0; n < IM_ARRAYSIZE(tonemapItems); n++)
{
bool is_selected = (currentTonemapItemId == n);
if (ImGui::Selectable(tonemapItems[n], is_selected))
{
currentTonemapItemId = n;
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
mCtx->mSettingsManager->setAs<uint32_t>("render/pt/tonemapperType", currentTonemapItemId);
float gamma = mCtx->mSettingsManager->getAs<float>("render/post/gamma");
ImGui::InputFloat("Gamma", (float*)&gamma, 0.5);
mCtx->mSettingsManager->setAs<float>("render/post/gamma", gamma);
float materialRayTmin = mCtx->mSettingsManager->getAs<float>("render/pt/dev/materialRayTmin");
ImGui::InputFloat("Material ray T min", (float*)&materialRayTmin, 0.1);
mCtx->mSettingsManager->setAs<float>("render/pt/dev/materialRayTmin", materialRayTmin);
float shadowRayTmin = mCtx->mSettingsManager->getAs<float>("render/pt/dev/shadowRayTmin");
ImGui::InputFloat("Shadow ray T min", (float*)&shadowRayTmin, 0.1);
mCtx->mSettingsManager->setAs<float>("render/pt/dev/shadowRayTmin", shadowRayTmin);
/*
bool enableUpscale = mCtx->mSettingsManager->getAs<bool>("render/pt/enableUpscale");
ImGui::Checkbox("Enable Upscale", &enableUpscale);
mCtx->mSettingsManager->setAs<bool>("render/pt/enableUpscale", enableUpscale);
float upscaleFactor = 0.0f;
if (enableUpscale)
{
upscaleFactor = 0.5f;
}
else
{
upscaleFactor = 1.0f;
}
mCtx->mSettingsManager->setAs<float>("render/pt/upscaleFactor", upscaleFactor);
if (ImGui::Button("Capture Screen"))
{
mCtx->mSettingsManager->setAs<bool>("render/pt/needScreenshot", true);
}
// bool isRecreate = ImGui::Button("Recreate BVH");
// renderConfig.recreateBVH = isRecreate ? true : false;
*/
ImGui::End(); // end window
// Rendering
ImGui::Render();
}
|
arhix52/Strelka/src/display/metal/metalcpphelp.cpp | #define NS_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
// #define MTK_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#include <Metal/Metal.hpp>
#include <QuartzCore/QuartzCore.hpp>
|
arhix52/Strelka/src/display/metal/glfwdisplay.h | #pragma once
#define GLFW_INCLUDE_NONE
#define GLFW_EXPOSE_NATIVE_COCOA
#include "Display.h"
#include <Metal/Metal.hpp>
#include <QuartzCore/QuartzCore.hpp>
namespace oka
{
class glfwdisplay : public Display
{
public:
glfwdisplay()
{
}
virtual ~glfwdisplay()
{
}
virtual void init(int width, int height, oka::SharedContext* ctx) override;
virtual void destroy() override;
virtual void onBeginFrame() override;
virtual void onEndFrame() override;
virtual void drawFrame(ImageBuffer& result) override;
virtual void drawUI() override;
private:
static constexpr size_t kMaxFramesInFlight = 3;
MTL::Device* _pDevice;
MTL::CommandQueue* _pCommandQueue;
MTL::Library* _pShaderLibrary;
MTL::RenderPipelineState* _pPSO;
MTL::Texture* mTexture;
uint32_t mTexWidth = 32;
uint32_t mTexHeight = 32;
dispatch_semaphore_t _semaphore;
CA::MetalLayer* layer;
MTL::RenderPassDescriptor *renderPassDescriptor;
MTL::Texture* buildTexture(uint32_t width, uint32_t heigth);
void buildShaders();
MTL::CommandBuffer* commandBuffer;
MTL::RenderCommandEncoder* renderEncoder;
CA::MetalDrawable* drawable;
};
} // namespace oka
|
arhix52/Strelka/src/display/opengl/glfwdisplay.h | #pragma once
#include <glad/glad.h>
#include "Display.h"
namespace oka
{
class glfwdisplay : public Display
{
private:
/* data */
GLuint m_render_tex = 0u;
GLuint m_program = 0u;
GLint m_render_tex_uniform_loc = -1;
GLuint m_quad_vertex_buffer = 0;
GLuint m_dislpayPbo = 0;
static const std::string s_vert_source;
static const std::string s_frag_source;
public:
glfwdisplay(/* args */);
virtual ~glfwdisplay();
public:
virtual void init(int width, int height, oka::SharedContext* ctx) override;
void destroy();
void onBeginFrame();
void onEndFrame();
void drawFrame(ImageBuffer& result);
void drawUI();
void display(const int32_t screen_res_x,
const int32_t screen_res_y,
const int32_t framebuf_res_x,
const int32_t framebuf_res_y,
const uint32_t pbo) const;
};
} // namespace oka
|
arhix52/Strelka/src/display/opengl/glfwdisplay.cpp | #include "glfwdisplay.h"
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#define GL_SILENCE_DEPRECATION
#include <sstream>
using namespace oka;
inline const char* getGLErrorString(GLenum error)
{
switch (error)
{
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
// case GL_STACK_OVERFLOW: return "Stack overflow";
// case GL_STACK_UNDERFLOW: return "Stack underflow";
case GL_OUT_OF_MEMORY:
return "Out of memory";
// case GL_TABLE_TOO_LARGE: return "Table too large";
default:
return "Unknown GL error";
}
}
inline void glCheck(const char* call, const char* file, unsigned int line)
{
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
std::stringstream ss;
ss << "GL error " << getGLErrorString(err) << " at " << file << "(" << line << "): " << call << '\n';
std::cerr << ss.str() << std::endl;
// throw Exception(ss.str().c_str());
assert(0);
}
}
#define GL_CHECK(call) \
do \
{ \
call; \
glCheck(#call, __FILE__, __LINE__); \
} while (false)
const std::string glfwdisplay::s_vert_source = R"(
#version 330 core
layout(location = 0) in vec3 vertexPosition_modelspace;
out vec2 UV;
void main()
{
gl_Position = vec4(vertexPosition_modelspace,1);
UV = (vec2( vertexPosition_modelspace.x, vertexPosition_modelspace.y )+vec2(1,1))/2.0;
}
)";
const std::string glfwdisplay::s_frag_source = R"(
#version 330 core
in vec2 UV;
out vec3 color;
uniform sampler2D render_tex;
uniform bool correct_gamma;
void main()
{
color = texture( render_tex, UV ).xyz;
}
)";
GLuint createGLShader(const std::string& source, GLuint shader_type)
{
GLuint shader = glCreateShader(shader_type);
{
const GLchar* source_data = reinterpret_cast<const GLchar*>(source.data());
glShaderSource(shader, 1, &source_data, nullptr);
glCompileShader(shader);
GLint is_compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &is_compiled);
if (is_compiled == GL_FALSE)
{
GLint max_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length);
std::string info_log(max_length, '\0');
GLchar* info_log_data = reinterpret_cast<GLchar*>(&info_log[0]);
glGetShaderInfoLog(shader, max_length, nullptr, info_log_data);
glDeleteShader(shader);
std::cerr << "Compilation of shader failed: " << info_log << std::endl;
return 0;
}
}
// GL_CHECK_ERRORS();
return shader;
}
GLuint createGLProgram(const std::string& vert_source, const std::string& frag_source)
{
GLuint vert_shader = createGLShader(vert_source, GL_VERTEX_SHADER);
if (vert_shader == 0)
return 0;
GLuint frag_shader = createGLShader(frag_source, GL_FRAGMENT_SHADER);
if (frag_shader == 0)
{
glDeleteShader(vert_shader);
return 0;
}
GLuint program = glCreateProgram();
glAttachShader(program, vert_shader);
glAttachShader(program, frag_shader);
glLinkProgram(program);
GLint is_linked = 0;
glGetProgramiv(program, GL_LINK_STATUS, &is_linked);
if (is_linked == GL_FALSE)
{
GLint max_length = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &max_length);
std::string info_log(max_length, '\0');
GLchar* info_log_data = reinterpret_cast<GLchar*>(&info_log[0]);
glGetProgramInfoLog(program, max_length, nullptr, info_log_data);
std::cerr << "Linking of program failed: " << info_log << std::endl;
glDeleteProgram(program);
glDeleteShader(vert_shader);
glDeleteShader(frag_shader);
return 0;
}
glDetachShader(program, vert_shader);
glDetachShader(program, frag_shader);
// GL_CHECK_ERRORS();
return program;
}
GLint getGLUniformLocation(GLuint program, const std::string& name)
{
GLint loc = glGetUniformLocation(program, name.c_str());
return loc;
}
glfwdisplay::glfwdisplay(/* args */)
{
}
glfwdisplay::~glfwdisplay()
{
}
void glfwdisplay::init(int width, int height, oka::SharedContext* ctx)
{
mWindowWidth = width;
mWindowHeight = height;
mCtx = ctx;
glfwInit();
const char* glsl_version = "#version 130";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
mWindow = glfwCreateWindow(mWindowWidth, mWindowHeight, "Strelka", nullptr, nullptr);
glfwSetWindowUserPointer(mWindow, this);
glfwSetFramebufferSizeCallback(mWindow, framebufferResizeCallback);
glfwSetKeyCallback(mWindow, keyCallback);
glfwSetMouseButtonCallback(mWindow, mouseButtonCallback);
glfwSetCursorPosCallback(mWindow, handleMouseMoveCallback);
glfwSetScrollCallback(mWindow, scrollCallback);
glfwMakeContextCurrent(mWindow);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
assert(0);
}
GLuint m_vertex_array;
GL_CHECK(glGenVertexArrays(1, &m_vertex_array));
GL_CHECK(glBindVertexArray(m_vertex_array));
m_program = createGLProgram(s_vert_source, s_frag_source);
m_render_tex_uniform_loc = getGLUniformLocation(m_program, "render_tex");
GL_CHECK(glGenTextures(1, &m_render_tex));
GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_render_tex));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
static const GLfloat g_quad_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
};
GL_CHECK(glGenBuffers(1, &m_quad_vertex_buffer));
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_quad_vertex_buffer));
GL_CHECK(glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW));
// GL_CHECK_ERRORS();
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io;
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// ImGui::StyleColorsLight();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(mWindow, true);
ImGui_ImplOpenGL3_Init(glsl_version);
}
void glfwdisplay::display(const int32_t screen_res_x,
const int32_t screen_res_y,
const int32_t framebuf_res_x,
const int32_t framebuf_res_y,
const uint32_t pbo) const
{
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0));
GL_CHECK(glViewport(0, 0, framebuf_res_x, framebuf_res_y));
GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
GL_CHECK(glUseProgram(m_program));
// Bind our texture in Texture Unit 0
GL_CHECK(glActiveTexture(GL_TEXTURE0));
GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_render_tex));
GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo));
GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 4)); // TODO!!!!!!
size_t elmt_size = 4 * sizeof(float); // pixelFormatSize(m_image_format);
if (elmt_size % 8 == 0)
glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
else if (elmt_size % 4 == 0)
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
else if (elmt_size % 2 == 0)
glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
else
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
bool convertToSrgb = true;
// if (m_image_format == BufferImageFormat::UNSIGNED_BYTE4)
// {
// // input is assumed to be in srgb since it is only 1 byte per channel in
// // size
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, screen_res_x, screen_res_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
// convertToSrgb = false;
// }
// else if (m_image_format == BufferImageFormat::FLOAT3)
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, screen_res_x, screen_res_y, 0, GL_RGB, GL_FLOAT, nullptr);
// else if (m_image_format == BufferImageFormat::FLOAT4)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, screen_res_x, screen_res_y, 0, GL_RGBA, GL_FLOAT, nullptr);
convertToSrgb = false;
// else
// throw Exception("Unknown buffer format");
GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
GL_CHECK(glUniform1i(m_render_tex_uniform_loc, 0));
// 1st attribute buffer : vertices
GL_CHECK(glEnableVertexAttribArray(0));
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_quad_vertex_buffer));
GL_CHECK(glVertexAttribPointer(0, // attribute 0. No particular reason for 0,
// but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
));
if (convertToSrgb)
GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB));
else
GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB));
// Draw the triangles !
GL_CHECK(glDrawArrays(GL_TRIANGLES, 0,
6)); // 2*3 indices starting at 0 -> 2 triangles
GL_CHECK(glDisableVertexAttribArray(0));
GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB));
// GL_CHECK_ERRORS();
}
void glfwdisplay::drawFrame(ImageBuffer& result)
{
glClear(GL_COLOR_BUFFER_BIT);
int framebuf_res_x = 0, framebuf_res_y = 0;
glfwGetFramebufferSize(mWindow, &framebuf_res_x, &framebuf_res_y);
if (m_dislpayPbo == 0)
{
GL_CHECK(glGenBuffers(1, &m_dislpayPbo));
}
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_dislpayPbo));
GL_CHECK(glBufferData(GL_ARRAY_BUFFER, result.dataSize, result.data, GL_STREAM_DRAW));
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0));
display(result.width, result.height, framebuf_res_x, framebuf_res_y, m_dislpayPbo);
}
void glfwdisplay::destroy()
{
}
void glfwdisplay::onBeginFrame()
{
}
void glfwdisplay::onEndFrame()
{
glfwSwapBuffers(mWindow);
}
void glfwdisplay::drawUI()
{
ImGui_ImplOpenGL3_NewFrame();
Display::drawUI();
int display_w, display_h;
glfwGetFramebufferSize(mWindow, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
|
arhix52/Strelka/cmake/StaticAnalyzers.cmake | if (NOT RELEASE)
find_program(CLANGTIDY clang-tidy)
if (CLANGTIDY)
message(STATUS "Using clang-tidy")
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY})
else ()
message(SEND_ERROR "clang-tidy requested but executable not found")
endif ()
# message(STATUS "Using address sanitizer")
# set(CMAKE_CXX_FLAGS
# "${CMAKE_CXX_FLAGS} -O0 -fsanitize=address -g")
endif ()
|
arhix52/Strelka/cmake/FindCUDA.cmake | #.rst:
# FindCUDA
# --------
#
# Tools for building CUDA C files: libraries and build dependencies.
#
# This script locates the NVIDIA CUDA C tools. It should work on linux,
# windows, and mac and should be reasonably up to date with CUDA C
# releases.
#
# This script makes use of the standard find_package arguments of
# <VERSION>, REQUIRED and QUIET. CUDA_FOUND will report if an
# acceptable version of CUDA was found.
#
# The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if
# the prefix cannot be determined by the location of nvcc in the system
# path and REQUIRED is specified to find_package(). To use a different
# installed version of the toolkit set the environment variable
# CUDA_BIN_PATH before running cmake (e.g.
# CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default
# /usr/local/cuda) or set CUDA_TOOLKIT_ROOT_DIR after configuring. If
# you change the value of CUDA_TOOLKIT_ROOT_DIR, various components that
# depend on the path will be relocated.
#
# It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain
# platforms, or to use a cuda runtime not installed in the default
# location. In newer versions of the toolkit the cuda library is
# included with the graphics driver- be sure that the driver version
# matches what is needed by the cuda runtime version.
#
# The following variables affect the behavior of the macros in the
# script (in alphebetical order). Note that any of these flags can be
# changed multiple times in the same directory before calling
# CUDA_ADD_EXECUTABLE, CUDA_ADD_LIBRARY, CUDA_COMPILE, CUDA_COMPILE_PTX,
# CUDA_COMPILE_FATBIN, CUDA_COMPILE_CUBIN or CUDA_WRAP_SRCS::
#
# CUDA_64_BIT_DEVICE_CODE (Default matches host bit size)
# -- Set to ON to compile for 64 bit device code, OFF for 32 bit device code.
# Note that making this different from the host code when generating object
# or C files from CUDA code just won't work, because size_t gets defined by
# nvcc in the generated source. If you compile to PTX and then load the
# file yourself, you can mix bit sizes between device and host.
#
# CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default ON)
# -- Set to ON if you want the custom build rule to be attached to the source
# file in Visual Studio. Turn OFF if you add the same cuda file to multiple
# targets.
#
# This allows the user to build the target from the CUDA file; however, bad
# things can happen if the CUDA source file is added to multiple targets.
# When performing parallel builds it is possible for the custom build
# command to be run more than once and in parallel causing cryptic build
# errors. VS runs the rules for every source file in the target, and a
# source can have only one rule no matter how many projects it is added to.
# When the rule is run from multiple targets race conditions can occur on
# the generated file. Eventually everything will get built, but if the user
# is unaware of this behavior, there may be confusion. It would be nice if
# this script could detect the reuse of source files across multiple targets
# and turn the option off for the user, but no good solution could be found.
#
# CUDA_BUILD_CUBIN (Default OFF)
# -- Set to ON to enable and extra compilation pass with the -cubin option in
# Device mode. The output is parsed and register, shared memory usage is
# printed during build.
#
# CUDA_BUILD_EMULATION (Default OFF for device mode)
# -- Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files
# when CUDA_BUILD_EMULATION is TRUE.
#
# CUDA_ENABLE_BATCHING (Default OFF)
# -- Set to ON to enable batch compilation of CUDA source files. This only has
# effect on Visual Studio targets
#
# CUDA_GENERATED_OUTPUT_DIR (Default CMAKE_CURRENT_BINARY_DIR)
# -- Set to the path you wish to have the generated files placed. If it is
# blank output files will be placed in CMAKE_CURRENT_BINARY_DIR.
# Intermediate files will always be placed in
# CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
#
# CUDA_GENERATE_DEPENDENCIES_DURING_CONFIGURE (Default ON for VS,
# OFF otherwise)
# -- Instead of waiting until build time compute dependencies, do it during
# configure time. Note that dependencies are still generated during
# build, so that if they change the build system can be updated. This
# mainly removes the need for configuring once after the first build to
# load the dependies into the build system.
#
# CUDA_CHECK_DEPENDENCIES_DURING_COMPILE (Default ON for VS,
# OFF otherwise)
# -- During build, the file level dependencies are checked. If all
# dependencies are older than the generated file, the generated file isn't
# compiled but touched (time stamp updated) so the driving build system
# thinks it has been compiled.
#
# CUDA_HOST_COMPILATION_CPP (Default ON)
# -- Set to OFF for C compilation of host code.
#
# CUDA_HOST_COMPILER (Default CMAKE_C_COMPILER, $(VCInstallDir)/bin for VS)
# -- Set the host compiler to be used by nvcc. Ignored if -ccbin or
# --compiler-bindir is already present in the CUDA_NVCC_FLAGS or
# CUDA_NVCC_FLAGS_<CONFIG> variables. For Visual Studio targets
# $(VCInstallDir)/bin is a special value that expands out to the path when
# the command is run from within VS.
#
# CUDA_NVCC_FLAGS
# CUDA_NVCC_FLAGS_<CONFIG>
# -- Additional NVCC command line arguments. NOTE: multiple arguments must be
# semi-colon delimited (e.g. --compiler-options;-Wall)
#
# CUDA_PROPAGATE_HOST_FLAGS (Default ON)
# -- Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration
# dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the
# host compiler through nvcc's -Xcompiler flag. This helps make the
# generated host code match the rest of the system better. Sometimes
# certain flags give nvcc problems, and this will help you turn the flag
# propagation off. This does not affect the flags supplied directly to nvcc
# via CUDA_NVCC_FLAGS or through the OPTION flags specified through
# CUDA_ADD_LIBRARY, CUDA_ADD_EXECUTABLE, or CUDA_WRAP_SRCS. Flags used for
# shared library compilation are not affected by this flag.
#
# CUDA_SEPARABLE_COMPILATION (Default OFF)
# -- If set this will enable separable compilation for all CUDA runtime object
# files. If used outside of CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY
# (e.g. calling CUDA_WRAP_SRCS directly),
# CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME and
# CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS should be called.
#
# CUDA_SOURCE_PROPERTY_FORMAT
# -- If this source file property is set, it can override the format specified
# to CUDA_WRAP_SRCS (OBJ, PTX, CUBIN, or FATBIN). If an input source file
# is not a .cu file, setting this file will cause it to be treated as a .cu
# file. See documentation for set_source_files_properties on how to set
# this property.
#
# CUDA_USE_STATIC_CUDA_RUNTIME (Default ON)
# -- When enabled the static version of the CUDA runtime library will be used
# in CUDA_LIBRARIES. If the version of CUDA configured doesn't support
# this option, then it will be silently disabled.
#
# CUDA_VERBOSE_BUILD (Default OFF)
# -- Set to ON to see all the commands used when building the CUDA file. When
# using a Makefile generator the value defaults to VERBOSE (run make
# VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will
# always print the output.
#
# The script creates the following macros (in alphebetical order)::
#
# CUDA_ADD_CUFFT_TO_TARGET( cuda_target )
# -- Adds the cufft library to the target (can be any target). Handles whether
# you are in emulation mode or not.
#
# CUDA_ADD_CUBLAS_TO_TARGET( cuda_target )
# -- Adds the cublas library to the target (can be any target). Handles
# whether you are in emulation mode or not.
#
# CUDA_ADD_EXECUTABLE( cuda_target file0 file1 ...
# [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
# -- Creates an executable "cuda_target" which is made up of the files
# specified. All of the non CUDA C files are compiled using the standard
# build rules specified by CMAKE and the cuda files are compiled to object
# files using nvcc and the host compiler. In addition CUDA_INCLUDE_DIRS is
# added automatically to include_directories(). Some standard CMake target
# calls can be used on the target after calling this macro
# (e.g. set_target_properties and target_link_libraries), but setting
# properties that adjust compilation flags will not affect code compiled by
# nvcc. Such flags should be modified before calling CUDA_ADD_EXECUTABLE,
# CUDA_ADD_LIBRARY or CUDA_WRAP_SRCS.
#
# CUDA_ADD_LIBRARY( cuda_target file0 file1 ...
# [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
# -- Same as CUDA_ADD_EXECUTABLE except that a library is created.
#
# CUDA_BUILD_CLEAN_TARGET()
# -- Creates a convience target that deletes all the dependency files
# generated. You should make clean after running this target to ensure the
# dependency files get regenerated.
#
# CUDA_COMPILE( generated_files file0 file1 ... [STATIC | SHARED | MODULE]
# [OPTIONS ...] )
# -- Returns a list of generated files from the input source files to be used
# with ADD_LIBRARY or ADD_EXECUTABLE.
#
# CUDA_COMPILE_PTX( generated_files file0 file1 ... [OPTIONS ...] )
# -- Returns a list of PTX files generated from the input source files.
#
# CUDA_COMPILE_FATBIN( generated_files file0 file1 ... [OPTIONS ...] )
# -- Returns a list of FATBIN files generated from the input source files.
#
# CUDA_COMPILE_CUBIN( generated_files file0 file1 ... [OPTIONS ...] )
# -- Returns a list of CUBIN files generated from the input source files.
#
# CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME( output_file_var
# cuda_target
# object_files )
# -- Compute the name of the intermediate link file used for separable
# compilation. This file name is typically passed into
# CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS. output_file_var is produced
# based on cuda_target the list of objects files that need separable
# compilation as specified by object_files. If the object_files list is
# empty, then output_file_var will be empty. This function is called
# automatically for CUDA_ADD_LIBRARY and CUDA_ADD_EXECUTABLE. Note that
# this is a function and not a macro.
#
# CUDA_INCLUDE_DIRECTORIES( path0 path1 ... )
# -- Sets the directories that should be passed to nvcc
# (e.g. nvcc -Ipath0 -Ipath1 ... ). These paths usually contain other .cu
# files.
#
#
# CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS( output_file_var cuda_target
# nvcc_flags object_files)
# -- Generates the link object required by separable compilation from the given
# object files. This is called automatically for CUDA_ADD_EXECUTABLE and
# CUDA_ADD_LIBRARY, but can be called manually when using CUDA_WRAP_SRCS
# directly. When called from CUDA_ADD_LIBRARY or CUDA_ADD_EXECUTABLE the
# nvcc_flags passed in are the same as the flags passed in via the OPTIONS
# argument. The only nvcc flag added automatically is the bitness flag as
# specified by CUDA_64_BIT_DEVICE_CODE. Note that this is a function
# instead of a macro.
#
# CUDA_SELECT_NVCC_ARCH_FLAGS(out_variable [target_CUDA_architectures])
# -- Selects GPU arch flags for nvcc based on target_CUDA_architectures
# target_CUDA_architectures : Auto | Common | All | LIST(ARCH_AND_PTX ...)
# - "Auto" detects local machine GPU compute arch at runtime.
# - "Common" and "All" cover common and entire subsets of architectures
# ARCH_AND_PTX : NAME | NUM.NUM | NUM.NUM(NUM.NUM) | NUM.NUM+PTX
# NAME: Fermi Kepler Maxwell Kepler+Tegra Kepler+Tesla Maxwell+Tegra Pascal
# NUM: Any number. Only those pairs are currently accepted by NVCC though:
# 2.0 2.1 3.0 3.2 3.5 3.7 5.0 5.2 5.3 6.0 6.2
# Returns LIST of flags to be added to CUDA_NVCC_FLAGS in ${out_variable}
# Additionally, sets ${out_variable}_readable to the resulting numeric list
# Example:
# CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS 3.0 3.5+PTX 5.2(5.0) Maxwell)
# LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})
#
# More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA
# Note that this is a function instead of a macro.
#
# CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
# [STATIC | SHARED | MODULE] [OPTIONS ...] )
# -- This is where all the magic happens. CUDA_ADD_EXECUTABLE,
# CUDA_ADD_LIBRARY, CUDA_COMPILE, and CUDA_COMPILE_PTX all call this
# function under the hood.
#
# Given the list of files (file0 file1 ... fileN) this macro generates
# custom commands that generate either PTX or linkable objects (use "PTX" or
# "OBJ" for the format argument to switch). Files that don't end with .cu
# or have the HEADER_FILE_ONLY property are ignored.
#
# The arguments passed in after OPTIONS are extra command line options to
# give to nvcc. You can also specify per configuration options by
# specifying the name of the configuration followed by the options. General
# options must precede configuration specific options. Not all
# configurations need to be specified, only the ones provided will be used.
#
# OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
# DEBUG -g
# RELEASE --use_fast_math
# RELWITHDEBINFO --use_fast_math;-g
# MINSIZEREL --use_fast_math
#
# For certain configurations (namely VS generating object files with
# CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will
# be produced for the given cuda file. This is because when you add the
# cuda file to Visual Studio it knows that this file produces an object file
# and will link in the resulting object file automatically.
#
# This script will also generate a separate cmake script that is used at
# build time to invoke nvcc. This is for several reasons.
#
# 1. nvcc can return negative numbers as return values which confuses
# Visual Studio into thinking that the command succeeded. The script now
# checks the error codes and produces errors when there was a problem.
#
# 2. nvcc has been known to not delete incomplete results when it
# encounters problems. This confuses build systems into thinking the
# target was generated when in fact an unusable file exists. The script
# now deletes the output files if there was an error.
#
# 3. By putting all the options that affect the build into a file and then
# make the build rule dependent on the file, the output files will be
# regenerated when the options change.
#
# This script also looks at optional arguments STATIC, SHARED, or MODULE to
# determine when to target the object compilation for a shared library.
# BUILD_SHARED_LIBS is ignored in CUDA_WRAP_SRCS, but it is respected in
# CUDA_ADD_LIBRARY. On some systems special flags are added for building
# objects intended for shared libraries. A preprocessor macro,
# <target_name>_EXPORTS is defined when a shared library compilation is
# detected.
#
# Flags passed into add_definitions with -D or /D are passed along to nvcc.
#
#
#
# The script defines the following variables::
#
# CUDA_VERSION_MAJOR -- The major version of cuda as reported by nvcc.
# CUDA_VERSION_MINOR -- The minor version.
# CUDA_VERSION
# CUDA_VERSION_STRING -- CUDA_VERSION_MAJOR.CUDA_VERSION_MINOR
# CUDA_HAS_FP16 -- Whether a short float (float16,fp16) is supported.
#
# CUDA_TOOLKIT_ROOT_DIR -- Path to the CUDA Toolkit (defined if not set).
# CUDA_SDK_ROOT_DIR -- Path to the CUDA SDK. Use this to find files in the
# SDK. This script will not directly support finding
# specific libraries or headers, as that isn't
# supported by NVIDIA. If you want to change
# libraries when the path changes see the
# FindCUDA.cmake script for an example of how to clear
# these variables. There are also examples of how to
# use the CUDA_SDK_ROOT_DIR to locate headers or
# libraries, if you so choose (at your own risk).
# CUDA_INCLUDE_DIRS -- Include directory for cuda headers. Added automatically
# for CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY.
# CUDA_LIBRARIES -- Cuda RT library.
# CUDA_CUDA_LIBRARY -- Cuda driver API library.
# CUDA_CUFFT_LIBRARIES -- Device or emulation library for the Cuda FFT
# implementation (alternative to:
# CUDA_ADD_CUFFT_TO_TARGET macro)
# CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
# implementation (alternative to:
# CUDA_ADD_CUBLAS_TO_TARGET macro).
# CUDA_cudart_static_LIBRARY -- Statically linkable cuda runtime library.
# Only available for CUDA version 5.5+
# CUDA_cudadevrt_LIBRARY -- Device runtime library.
# Required for separable compilation.
# CUDA_cupti_LIBRARY -- CUDA Profiling Tools Interface library.
# Only available for CUDA version 4.0+.
# CUDA_curand_LIBRARY -- CUDA Random Number Generation library.
# Only available for CUDA version 3.2+.
# CUDA_cusolver_LIBRARY -- CUDA Direct Solver library.
# Only available for CUDA version 7.0+.
# CUDA_cusparse_LIBRARY -- CUDA Sparse Matrix library.
# Only available for CUDA version 3.2+.
# CUDA_npp_LIBRARY -- NVIDIA Performance Primitives lib.
# Only available for CUDA version 4.0+.
# CUDA_nppc_LIBRARY -- NVIDIA Performance Primitives lib (core).
# Only available for CUDA version 5.5+.
# CUDA_nppi_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
# Only available for CUDA version 5.5+.
# CUDA_npps_LIBRARY -- NVIDIA Performance Primitives lib (signal processing).
# Only available for CUDA version 5.5+.
# CUDA_nvcuvenc_LIBRARY -- CUDA Video Encoder library.
# Only available for CUDA version 3.2+.
# Windows only.
# CUDA_nvcuvid_LIBRARY -- CUDA Video Decoder library.
# Only available for CUDA version 3.2+.
# Windows only.
#
# James Bigler, NVIDIA Corp (nvidia.com - jbigler)
# Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
#
# Copyright (c) 2008 - 2021 NVIDIA Corporation. All rights reserved.
#
# Copyright (c) 2007-2009
# Scientific Computing and Imaging Institute, University of Utah
#
# This code is licensed under the MIT License. See the FindCUDA.cmake script
# for the text of the license.
# The MIT License
#
# License for the specific language governing rights and limitations under
# 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.
#
###############################################################################
# FindCUDA.cmake
# This macro helps us find the location of helper files we will need the full path to
macro(CUDA_FIND_HELPER_FILE _name _extension)
set(_full_name "${_name}.${_extension}")
# CMAKE_CURRENT_LIST_FILE contains the full path to the file currently being
# processed. Using this variable, we can pull out the current path, and
# provide a way to get access to the other files we need local to here.
get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
set(CUDA_${_name} "${CMAKE_CURRENT_LIST_DIR}/FindCUDA/${_full_name}")
if(NOT EXISTS "${CUDA_${_name}}")
set(error_message "${_full_name} not found in ${CMAKE_CURRENT_LIST_DIR}/FindCUDA")
if(CUDA_FIND_REQUIRED)
message(FATAL_ERROR "${error_message}")
else()
if(NOT CUDA_FIND_QUIETLY)
message(STATUS "${error_message}")
endif()
endif()
endif()
# Set this variable as internal, so the user isn't bugged with it.
set(CUDA_${_name} ${CUDA_${_name}} CACHE INTERNAL "Location of ${_full_name}" FORCE)
endmacro()
#####################################################################
## CUDA_INCLUDE_NVCC_DEPENDENCIES
##
# So we want to try and include the dependency file if it exists. If
# it doesn't exist then we need to create an empty one, so we can
# include it.
# If it does exist, then we need to check to see if all the files it
# depends on exist. If they don't then we should clear the dependency
# file and regenerate it later. This covers the case where a header
# file has disappeared or moved.
macro(CUDA_INCLUDE_NVCC_DEPENDENCIES dependency_file)
set(CUDA_NVCC_DEPEND)
set(CUDA_NVCC_DEPEND_REGENERATE FALSE)
# Include the dependency file. Create it first if it doesn't exist . The
# INCLUDE puts a dependency that will force CMake to rerun and bring in the
# new info when it changes. DO NOT REMOVE THIS (as I did and spent a few
# hours figuring out why it didn't work.
if(NOT EXISTS ${dependency_file})
file(WRITE ${dependency_file} "#FindCUDA.cmake generated file. Do not edit.\n")
endif()
# Always include this file to force CMake to run again next
# invocation and rebuild the dependencies.
#message("including dependency_file = ${dependency_file}")
include(${dependency_file})
# Now we need to verify the existence of all the included files
# here. If they aren't there we need to just blank this variable and
# make the file regenerate again.
# if(DEFINED CUDA_NVCC_DEPEND)
# message("CUDA_NVCC_DEPEND set")
# else()
# message("CUDA_NVCC_DEPEND NOT set")
# endif()
if(CUDA_NVCC_DEPEND)
#message("CUDA_NVCC_DEPEND found")
foreach(f ${CUDA_NVCC_DEPEND})
# message("searching for ${f}")
if(NOT EXISTS ${f})
#message("file ${f} not found")
set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
endif()
endforeach()
else()
#message("CUDA_NVCC_DEPEND false")
# No dependencies, so regenerate the file.
set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
endif()
#message("CUDA_NVCC_DEPEND_REGENERATE = ${CUDA_NVCC_DEPEND_REGENERATE}")
# No incoming dependencies, so we need to generate them. Make the
# output depend on the dependency file itself, which should cause the
# rule to re-run.
if(CUDA_NVCC_DEPEND_REGENERATE)
set(CUDA_NVCC_DEPEND ${dependency_file})
#message("Generating an empty dependency_file: ${dependency_file}")
file(WRITE ${dependency_file} "#FindCUDA.cmake generated file. Do not edit.\n")
endif()
endmacro()
###############################################################################
###############################################################################
# Setup variables' defaults
###############################################################################
###############################################################################
# Allow the user to specify if the device code is supposed to be 32 or 64 bit.
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(CUDA_64_BIT_DEVICE_CODE_DEFAULT ON)
else()
set(CUDA_64_BIT_DEVICE_CODE_DEFAULT OFF)
endif()
option(CUDA_64_BIT_DEVICE_CODE "Compile device code in 64 bit mode" ${CUDA_64_BIT_DEVICE_CODE_DEFAULT})
# Attach the build rule to the source file in VS. This option
option(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE "Attach the build rule to the CUDA source file. Enable only when the CUDA source file is added to at most one target." ON)
# Prints out extra information about the cuda file during compilation
option(CUDA_BUILD_CUBIN "Generate and parse .cubin files in Device mode." OFF)
# Set whether we are using emulation or device mode.
option(CUDA_BUILD_EMULATION "Build in Emulation mode" OFF)
# Enable batch builds
option(CUDA_ENABLE_BATCHING "Compile CUDA source files in parallel" OFF)
if(CUDA_ENABLE_BATCHING)
find_package(PythonInterp)
if(NOT PYTHONINTERP_FOUND)
message(SEND_ERROR "CUDA_ENABLE_BATCHING is enabled, but python wasn't found. Disabling")
set(CUDA_ENABLE_BATCHING OFF CACHE BOOL "Compile CUDA source files in parallel" FORCE)
endif()
endif()
# Where to put the generated output.
set(CUDA_GENERATED_OUTPUT_DIR "" CACHE PATH "Directory to put all the output files. If blank it will default to the CMAKE_CURRENT_BINARY_DIR")
if(CMAKE_GENERATOR MATCHES "Visual Studio")
set(_cuda_dependencies_default ON)
else()
set(_cuda_dependencies_default OFF)
endif()
option(CUDA_GENERATE_DEPENDENCIES_DURING_CONFIGURE "Generate dependencies during configure time instead of only during build time." ${_cuda_dependencies_default})
option(CUDA_CHECK_DEPENDENCIES_DURING_COMPILE "Checks the dependencies during compilation and suppresses generation if the dependencies have been met." ${_cuda_dependencies_default})
# Parse HOST_COMPILATION mode.
option(CUDA_HOST_COMPILATION_CPP "Generated file extension" ON)
# Extra user settable flags
set(CUDA_NVCC_FLAGS "" CACHE STRING "Semi-colon delimit multiple arguments.")
if(CMAKE_GENERATOR MATCHES "Visual Studio")
set(_CUDA_MSVC_HOST_COMPILER "$(VCInstallDir)Tools/MSVC/$(VCToolsVersion)/bin/Host$(Platform)/$(PlatformTarget)")
if(MSVC_VERSION LESS 1910)
set(_CUDA_MSVC_HOST_COMPILER "$(VCInstallDir)bin")
endif()
set(CUDA_HOST_COMPILER "${_CUDA_MSVC_HOST_COMPILER}" CACHE FILEPATH "Host side compiler used by NVCC")
else()
if(APPLE
AND "${CMAKE_C_COMPILER_ID}" MATCHES "Clang"
AND "${CMAKE_C_COMPILER}" MATCHES "/cc$")
# Using cc which is symlink to clang may let NVCC think it is GCC and issue
# unhandled -dumpspecs option to clang. Also in case neither
# CMAKE_C_COMPILER is defined (project does not use C language) nor
# CUDA_HOST_COMPILER is specified manually we should skip -ccbin and let
# nvcc use its own default C compiler.
# Only care about this on APPLE with clang to avoid
# following symlinks to things like ccache
if(DEFINED CMAKE_C_COMPILER AND NOT DEFINED CUDA_HOST_COMPILER)
get_filename_component(c_compiler_realpath "${CMAKE_C_COMPILER}" REALPATH)
# if the real path does not end up being clang then
# go back to using CMAKE_C_COMPILER
if(NOT "${c_compiler_realpath}" MATCHES "/clang$")
set(c_compiler_realpath "${CMAKE_C_COMPILER}")
endif()
else()
set(c_compiler_realpath "")
endif()
set(CUDA_HOST_COMPILER "${c_compiler_realpath}" CACHE FILEPATH "Host side compiler used by NVCC")
else()
set(CUDA_HOST_COMPILER "${CMAKE_C_COMPILER}"
CACHE FILEPATH "Host side compiler used by NVCC")
endif()
endif()
# Set up CUDA_VC_VARS_ALL_BAT if it hasn't been specified.
# set CUDA_VC_VARS_ALL_BAT explicitly to avoid any attempts to locate it via this algorithm.
if(MSVC AND NOT CUDA_VC_VARS_ALL_BAT AND CUDA_ENABLE_BATCHING)
get_filename_component(_cuda_dependency_ccbin_dir "${CMAKE_CXX_COMPILER}" DIRECTORY)
#message(STATUS "_cuda_dependency_ccbin_dir = ${_cuda_dependency_ccbin_dir}")
# In VS 6-12 (1200-1800) the versions were 6 off. Starting in VS 14 (1900) it's only 5.
if(MSVC_VERSION VERSION_LESS 1900)
math(EXPR vs_major_version "${MSVC_VERSION} / 100 - 6")
find_file( CUDA_VC_VARS_ALL_BAT vcvarsall.bat PATHS "${_cuda_dependency_ccbin_dir}/../.." NO_DEFAULT_PATH )
elseif(MSVC_VERSION VERSION_EQUAL 1900)
# Visual Studio 2015
set(vs_major_version "15")
find_file( CUDA_VC_VARS_ALL_BAT vcvarsall.bat PATHS "${_cuda_dependency_ccbin_dir}/../.." NO_DEFAULT_PATH )
elseif(MSVC_VERSION VERSION_LESS 1920)
# Visual Studio 2017
set(vs_major_version "15")
find_file( CUDA_VC_VARS_ALL_BAT vcvarsall.bat PATHS "${_cuda_dependency_ccbin_dir}/../../../../../../Auxiliary/Build" NO_DEFAULT_PATH )
else()
# Visual Studio 2019
set(vs_major_version "16")
find_file( CUDA_VC_VARS_ALL_BAT vcvarsall.bat PATHS "${_cuda_dependency_ccbin_dir}/../../../../../../Auxiliary/Build" NO_DEFAULT_PATH )
endif()
if( NOT CUDA_VC_VARS_ALL_BAT )
# See if we can get VS install location from the registry. Registry searches can only
# be accomplished via a CACHE variable, unfortunately.
get_filename_component(_cuda_vs_dir_tmp "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\${vs_major_version}.0\\Setup\\VS;ProductDir]" REALPATH CACHE)
if( _cuda_vs_dir_tmp )
set( CUDA_VS_DIR ${_cuda_vs_dir_tmp} )
unset( _cuda_vs_dir_tmp CACHE )
endif()
find_file( CUDA_VC_VARS_ALL_BAT vcvarsall.bat PATHS ${CUDA_VS_DIR}/VC/bin ${CUDA_VS_DIR}/VC/Auxiliary/Build NO_DEFAULT_PATH )
endif()
if( NOT CUDA_VC_VARS_ALL_BAT )
message(FATAL_ERROR "Cannot find path to vcvarsall.bat. Looked in ${CUDA_VS_DIR}/VC/bin ${CUDA_VS_DIR}/VC/Auxiliary/Build")
endif()
#message("CUDA_VS_DIR = ${CUDA_VS_DIR}, CUDA_VC_VARS_ALL_BAT = ${CUDA_VC_VARS_ALL_BAT}")
endif()
# Propagate the host flags to the host compiler via -Xcompiler
option(CUDA_PROPAGATE_HOST_FLAGS "Propage C/CXX_FLAGS and friends to the host compiler via -Xcompile" ON)
# Enable CUDA_SEPARABLE_COMPILATION
option(CUDA_SEPARABLE_COMPILATION "Compile CUDA objects with separable compilation enabled. Requires CUDA 5.0+" OFF)
# Specifies whether the commands used when compiling the .cu file will be printed out.
option(CUDA_VERBOSE_BUILD "Print out the commands run while compiling the CUDA source file. With the Makefile generator this defaults to VERBOSE variable specified on the command line, but can be forced on with this option." OFF)
mark_as_advanced(
CUDA_64_BIT_DEVICE_CODE
CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE
CUDA_GENERATED_OUTPUT_DIR
CUDA_HOST_COMPILATION_CPP
CUDA_NVCC_FLAGS
CUDA_PROPAGATE_HOST_FLAGS
CUDA_BUILD_CUBIN
CUDA_BUILD_EMULATION
CUDA_VERBOSE_BUILD
CUDA_SEPARABLE_COMPILATION
)
# Makefile and similar generators don't define CMAKE_CONFIGURATION_TYPES, so we
# need to add another entry for the CMAKE_BUILD_TYPE. We also need to add the
# standerd set of 4 build types (Debug, MinSizeRel, Release, and RelWithDebInfo)
# for completeness. We need run this loop in order to accomodate the addition
# of extra configuration types. Duplicate entries will be removed by
# REMOVE_DUPLICATES.
set(CUDA_configuration_types ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE} Debug MinSizeRel Release RelWithDebInfo)
list(REMOVE_DUPLICATES CUDA_configuration_types)
foreach(config ${CUDA_configuration_types})
string(TOUPPER ${config} config_upper)
set(CUDA_NVCC_FLAGS_${config_upper} "" CACHE STRING "Semi-colon delimit multiple arguments.")
mark_as_advanced(CUDA_NVCC_FLAGS_${config_upper})
endforeach()
###############################################################################
###############################################################################
# Locate CUDA, Set Build Type, etc.
###############################################################################
###############################################################################
macro(cuda_unset_include_and_libraries)
unset(CUDA_TOOLKIT_INCLUDE CACHE)
unset(CUDA_CUDART_LIBRARY CACHE)
unset(CUDA_CUDA_LIBRARY CACHE)
# Make sure you run this before you unset CUDA_VERSION.
if(CUDA_VERSION VERSION_EQUAL "3.0")
# This only existed in the 3.0 version of the CUDA toolkit
unset(CUDA_CUDARTEMU_LIBRARY CACHE)
endif()
if( DEFINED CUDA_NVASM_EXECUTABLE )
unset(CUDA_NVASM_EXECUTABLE)
endif()
if( DEFINED CUDA_FATBINARY_EXECUTABLE )
unset(CUDA_FATBINARY_EXECUTABLE)
endif()
unset(CUDA_cudart_static_LIBRARY CACHE)
unset(CUDA_cudadevrt_LIBRARY CACHE)
unset(CUDA_cublas_LIBRARY CACHE)
unset(CUDA_cublas_device_LIBRARY CACHE)
unset(CUDA_cublasemu_LIBRARY CACHE)
unset(CUDA_cufft_LIBRARY CACHE)
unset(CUDA_cufftemu_LIBRARY CACHE)
unset(CUDA_cupti_LIBRARY CACHE)
unset(CUDA_curand_LIBRARY CACHE)
unset(CUDA_cusolver_LIBRARY CACHE)
unset(CUDA_cusparse_LIBRARY CACHE)
unset(CUDA_npp_LIBRARY CACHE)
unset(CUDA_nppc_LIBRARY CACHE)
unset(CUDA_nppi_LIBRARY CACHE)
unset(CUDA_npps_LIBRARY CACHE)
unset(CUDA_nvcuvenc_LIBRARY CACHE)
unset(CUDA_nvcuvid_LIBRARY CACHE)
unset(CUDA_nvrtc_LIBRARY CACHE)
unset(CUDA_USE_STATIC_CUDA_RUNTIME CACHE)
unset(CUDA_GPU_DETECT_OUTPUT CACHE)
endmacro()
# Check to see if the CUDA_TOOLKIT_ROOT_DIR and CUDA_SDK_ROOT_DIR have changed,
# if they have then clear the cache variables, so that will be detected again.
if(NOT "${CUDA_TOOLKIT_ROOT_DIR}" STREQUAL "${CUDA_TOOLKIT_ROOT_DIR_INTERNAL}")
unset(CUDA_TOOLKIT_TARGET_DIR CACHE)
unset(CUDA_NVCC_EXECUTABLE CACHE)
cuda_unset_include_and_libraries()
unset(CUDA_VERSION CACHE)
endif()
if(NOT "${CUDA_TOOLKIT_TARGET_DIR}" STREQUAL "${CUDA_TOOLKIT_TARGET_DIR_INTERNAL}")
cuda_unset_include_and_libraries()
endif()
#
# End of unset()
#
#
# Start looking for things
#
# Search for the cuda distribution.
if(NOT CUDA_TOOLKIT_ROOT_DIR AND NOT CMAKE_CROSSCOMPILING)
# Search in the CUDA_BIN_PATH first.
find_path(CUDA_TOOLKIT_ROOT_DIR
NAMES nvcc nvcc.exe
PATHS
ENV CUDA_TOOLKIT_ROOT
ENV CUDA_PATH
ENV CUDA_BIN_PATH
PATH_SUFFIXES bin bin64
DOC "Toolkit location."
NO_DEFAULT_PATH
)
# Now search default paths
find_path(CUDA_TOOLKIT_ROOT_DIR
NAMES nvcc nvcc.exe
PATHS /opt/cuda/bin
/usr/local/bin
/usr/local/cuda/bin
DOC "Toolkit location."
)
if (CUDA_TOOLKIT_ROOT_DIR)
string(REGEX REPLACE "[/\\\\]?bin[64]*[/\\\\]?$" "" CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR})
# We need to force this back into the cache.
set(CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR} CACHE PATH "Toolkit location." FORCE)
set(CUDA_TOOLKIT_TARGET_DIR ${CUDA_TOOLKIT_ROOT_DIR})
endif()
if (NOT EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
if(CUDA_FIND_REQUIRED)
message(FATAL_ERROR "Specify CUDA_TOOLKIT_ROOT_DIR")
elseif(NOT CUDA_FIND_QUIETLY)
message("CUDA_TOOLKIT_ROOT_DIR not found or specified")
endif()
endif ()
endif ()
if(CMAKE_CROSSCOMPILING)
SET (CUDA_TOOLKIT_ROOT $ENV{CUDA_TOOLKIT_ROOT})
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "armv7-a")
# Support for NVPACK
set (CUDA_TOOLKIT_TARGET_NAME "armv7-linux-androideabi")
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm")
# Support for arm cross compilation
set(CUDA_TOOLKIT_TARGET_NAME "armv7-linux-gnueabihf")
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64")
# Support for aarch64 cross compilation
if (ANDROID_ARCH_NAME STREQUAL "arm64")
set(CUDA_TOOLKIT_TARGET_NAME "aarch64-linux-androideabi")
else()
set(CUDA_TOOLKIT_TARGET_NAME "aarch64-linux")
endif (ANDROID_ARCH_NAME STREQUAL "arm64")
endif()
if (EXISTS "${CUDA_TOOLKIT_ROOT}/targets/${CUDA_TOOLKIT_TARGET_NAME}")
set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT}/targets/${CUDA_TOOLKIT_TARGET_NAME}" CACHE PATH "CUDA Toolkit target location.")
SET (CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT})
mark_as_advanced(CUDA_TOOLKIT_TARGET_DIR)
endif()
# add known CUDA targetr root path to the set of directories we search for programs, libraries and headers
set( CMAKE_FIND_ROOT_PATH "${CUDA_TOOLKIT_TARGET_DIR};${CMAKE_FIND_ROOT_PATH}")
macro( cuda_find_host_program )
find_host_program( ${ARGN} )
endmacro()
else()
# for non-cross-compile, find_host_program == find_program and CUDA_TOOLKIT_TARGET_DIR == CUDA_TOOLKIT_ROOT_DIR
macro( cuda_find_host_program )
find_program( ${ARGN} )
endmacro()
SET (CUDA_TOOLKIT_TARGET_DIR ${CUDA_TOOLKIT_ROOT_DIR})
endif()
# CUDA_NVCC_EXECUTABLE
cuda_find_host_program(CUDA_NVCC_EXECUTABLE
NAMES nvcc
PATHS "${CUDA_TOOLKIT_ROOT_DIR}"
ENV CUDA_PATH
ENV CUDA_BIN_PATH
PATH_SUFFIXES bin bin64
NO_DEFAULT_PATH
)
# Search default search paths, after we search our own set of paths.
cuda_find_host_program(CUDA_NVCC_EXECUTABLE nvcc)
mark_as_advanced(CUDA_NVCC_EXECUTABLE)
# CUDA_NVASM_EXECUTABLE
cuda_find_host_program(CUDA_NVASM_EXECUTABLE
NAMES nvasm_internal
PATHS "${CUDA_TOOLKIT_ROOT_DIR}"
ENV CUDA_PATH
ENV CUDA_BIN_PATH
PATH_SUFFIXES bin bin64
NO_DEFAULT_PATH
)
# Search default search paths, after we search our own set of paths.
cuda_find_host_program(CUDA_NVASM_EXECUTABLE nvasm_internal)
mark_as_advanced(CUDA_NVASM_EXECUTABLE)
# Find fatbinary from CUDA
cuda_find_host_program(CUDA_FATBINARY_EXECUTABLE
NAMES fatbinary
PATHS "${CUDA_TOOLKIT_ROOT_DIR}"
ENV CUDA_PATH
ENV CUDA_BIN_PATH
PATH_SUFFIXES bin bin64
NO_DEFAULT_PATH
)
# Search default search paths, after we search our own set of paths.
cuda_find_host_program(CUDA_FATBINARY_EXECUTABLE fatbinary)
mark_as_advanced(CUDA_FATBINARY_EXECUTABLE)
if(CUDA_NVCC_EXECUTABLE AND NOT CUDA_VERSION)
# Compute the version.
execute_process (COMMAND ${CUDA_NVCC_EXECUTABLE} "--version" OUTPUT_VARIABLE NVCC_OUT)
string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR ${NVCC_OUT})
string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR ${NVCC_OUT})
set(CUDA_VERSION "${CUDA_VERSION_MAJOR}.${CUDA_VERSION_MINOR}" CACHE STRING "Version of CUDA as computed from nvcc.")
mark_as_advanced(CUDA_VERSION)
else()
# Need to set these based off of the cached value
string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR "${CUDA_VERSION}")
string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR "${CUDA_VERSION}")
endif()
# Always set this convenience variable
set(CUDA_VERSION_STRING "${CUDA_VERSION}")
# Here we need to determine if the version we found is acceptable. We will
# assume that is unless CUDA_FIND_VERSION_EXACT or CUDA_FIND_VERSION is
# specified. The presence of either of these options checks the version
# string and signals if the version is acceptable or not.
set(_cuda_version_acceptable TRUE)
#
if(CUDA_FIND_VERSION_EXACT AND NOT CUDA_VERSION VERSION_EQUAL CUDA_FIND_VERSION)
set(_cuda_version_acceptable FALSE)
endif()
#
if(CUDA_FIND_VERSION AND CUDA_VERSION VERSION_LESS CUDA_FIND_VERSION)
set(_cuda_version_acceptable FALSE)
endif()
#
if(NOT _cuda_version_acceptable)
set(_cuda_error_message "Requested CUDA version ${CUDA_FIND_VERSION}, but found unacceptable version ${CUDA_VERSION}")
if(CUDA_FIND_REQUIRED)
message("${_cuda_error_message}")
elseif(NOT CUDA_FIND_QUIETLY)
message("${_cuda_error_message}")
endif()
endif()
# CUDA_TOOLKIT_INCLUDE
find_path(CUDA_TOOLKIT_INCLUDE
device_functions.h # Header included in toolkit
PATHS ${CUDA_TOOLKIT_TARGET_DIR}
ENV CUDA_PATH
ENV CUDA_INC_PATH
PATH_SUFFIXES include
NO_DEFAULT_PATH
)
# Search default search paths, after we search our own set of paths.
find_path(CUDA_TOOLKIT_INCLUDE device_functions.h)
mark_as_advanced(CUDA_TOOLKIT_INCLUDE)
if (CUDA_VERSION VERSION_GREATER "7.0" OR EXISTS "${CUDA_TOOLKIT_INCLUDE}/cuda_fp16.h")
set(CUDA_HAS_FP16 TRUE)
else()
set(CUDA_HAS_FP16 FALSE)
endif()
# Set the user list of include dir to nothing to initialize it.
set (CUDA_NVCC_INCLUDE_ARGS_USER "")
set (CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_INCLUDE})
macro(cuda_find_library_local_first_with_path_ext _var _names _doc _path_ext )
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
# CUDA 3.2+ on Windows moved the library directories, so we need the new
# and old paths.
set(_cuda_64bit_lib_dir "${_path_ext}lib/x64" "${_path_ext}lib64" "${_path_ext}libx64" )
endif()
# CUDA 3.2+ on Windows moved the library directories, so we need to new
# (lib/Win32) and the old path (lib).
find_library(${_var}
NAMES ${_names}
PATHS "${CUDA_TOOLKIT_TARGET_DIR}"
ENV CUDA_PATH
ENV CUDA_LIB_PATH
PATH_SUFFIXES ${_cuda_64bit_lib_dir} "${_path_ext}lib/Win32" "${_path_ext}lib" "${_path_ext}libWin32"
DOC ${_doc}
NO_DEFAULT_PATH
)
if (NOT CMAKE_CROSSCOMPILING)
# Search default search paths, after we search our own set of paths.
find_library(${_var}
NAMES ${_names}
PATHS "/usr/lib/nvidia-current"
DOC ${_doc}
)
endif()
endmacro()
macro(cuda_find_library_local_first _var _names _doc)
cuda_find_library_local_first_with_path_ext( "${_var}" "${_names}" "${_doc}" "" )
endmacro()
macro(find_library_local_first _var _names _doc )
cuda_find_library_local_first( "${_var}" "${_names}" "${_doc}" "" )
endmacro()
# CUDA_LIBRARIES
cuda_find_library_local_first(CUDA_CUDART_LIBRARY cudart "\"cudart\" library")
if(CUDA_VERSION VERSION_EQUAL "3.0")
# The cudartemu library only existed for the 3.0 version of CUDA.
cuda_find_library_local_first(CUDA_CUDARTEMU_LIBRARY cudartemu "\"cudartemu\" library")
mark_as_advanced(
CUDA_CUDARTEMU_LIBRARY
)
endif()
if(NOT CUDA_VERSION VERSION_LESS "5.5")
cuda_find_library_local_first(CUDA_cudart_static_LIBRARY cudart_static "static CUDA runtime library")
mark_as_advanced(CUDA_cudart_static_LIBRARY)
endif()
if(CUDA_cudart_static_LIBRARY)
# If static cudart available, use it by default, but provide a user-visible option to disable it.
option(CUDA_USE_STATIC_CUDA_RUNTIME "Use the static version of the CUDA runtime library if available" ON)
set(CUDA_CUDART_LIBRARY_VAR CUDA_cudart_static_LIBRARY)
else()
# If not available, silently disable the option.
set(CUDA_USE_STATIC_CUDA_RUNTIME OFF CACHE INTERNAL "")
set(CUDA_CUDART_LIBRARY_VAR CUDA_CUDART_LIBRARY)
endif()
if(NOT CUDA_VERSION VERSION_LESS "5.0")
cuda_find_library_local_first(CUDA_cudadevrt_LIBRARY cudadevrt "\"cudadevrt\" library")
mark_as_advanced(CUDA_cudadevrt_LIBRARY)
endif()
if(CUDA_USE_STATIC_CUDA_RUNTIME)
if(UNIX)
# Check for the dependent libraries. Here we look for pthreads.
if (DEFINED CMAKE_THREAD_PREFER_PTHREAD)
set(_cuda_cmake_thread_prefer_pthread ${CMAKE_THREAD_PREFER_PTHREAD})
endif()
set(CMAKE_THREAD_PREFER_PTHREAD 1)
# Many of the FindXYZ CMake comes with makes use of try_compile with int main(){return 0;}
# as the source file. Unfortunately this causes a warning with -Wstrict-prototypes and
# -Werror causes the try_compile to fail. We will just temporarily disable other flags
# when doing the find_package command here.
set(_cuda_cmake_c_flags ${CMAKE_C_FLAGS})
set(CMAKE_C_FLAGS "-fPIC")
find_package(Threads REQUIRED)
set(CMAKE_C_FLAGS ${_cuda_cmake_c_flags})
if (DEFINED _cuda_cmake_thread_prefer_pthread)
set(CMAKE_THREAD_PREFER_PTHREAD ${_cuda_cmake_thread_prefer_pthread})
unset(_cuda_cmake_thread_prefer_pthread)
else()
unset(CMAKE_THREAD_PREFER_PTHREAD)
endif()
if (NOT APPLE)
#On Linux, you must link against librt when using the static cuda runtime.
find_library(CUDA_rt_LIBRARY rt)
# CMake has a CMAKE_DL_LIBS, but I'm not sure what version of CMake provides this
find_library(CUDA_dl_LIBRARY dl)
if (NOT CUDA_rt_LIBRARY)
message(WARNING "Expecting to find librt for libcudart_static, but didn't find it.")
endif()
if (NOT CUDA_dl_LIBRARY)
message(WARNING "Expecting to find libdl for libcudart_static, but didn't find it.")
endif()
endif()
endif()
endif()
# CUPTI library showed up in cuda toolkit 4.0
if(NOT CUDA_VERSION VERSION_LESS "4.0")
cuda_find_library_local_first_with_path_ext(CUDA_cupti_LIBRARY cupti "\"cupti\" library" "extras/CUPTI/")
mark_as_advanced(CUDA_cupti_LIBRARY)
endif()
# Set the CUDA_LIBRARIES variable. This is the set of stuff to link against if you are
# using the CUDA runtime. For the dynamic version of the runtime, most of the
# dependencies are brough in, but for the static version there are additional libraries
# and linker commands needed.
# Initialize to empty
set(CUDA_LIBRARIES)
if(APPLE)
# We need to add the path to cudart to the linker using rpath, since the library name
# for the cuda libraries is prepended with @rpath. We need to add the path to the
# toolkit before we add the path to the driver below, so that we find our toolkit's code
# first.
if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
get_filename_component(_cuda_path_to_cudart "${CUDA_CUDARTEMU_LIBRARY}" PATH)
else()
get_filename_component(_cuda_path_to_cudart "${CUDA_CUDART_LIBRARY}" PATH)
endif()
if(_cuda_path_to_cudart)
list(APPEND CUDA_LIBRARIES -Wl,-rpath "-Wl,${_cuda_path_to_cudart}")
endif()
endif()
# If we are using emulation mode and we found the cudartemu library then use
# that one instead of cudart.
if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
list(APPEND CUDA_LIBRARIES ${CUDA_CUDARTEMU_LIBRARY})
elseif(CUDA_USE_STATIC_CUDA_RUNTIME AND CUDA_cudart_static_LIBRARY)
list(APPEND CUDA_LIBRARIES ${CUDA_cudart_static_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
if (CUDA_rt_LIBRARY)
list(APPEND CUDA_LIBRARIES ${CUDA_rt_LIBRARY})
endif()
if (CUDA_dl_LIBRARY)
list(APPEND CUDA_LIBRARIES ${CUDA_dl_LIBRARY})
endif()
if(APPLE)
# We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
# the static cuda runtime can find it at runtime.
list(APPEND CUDA_LIBRARIES -Wl,-rpath,/usr/local/cuda/lib)
endif()
else()
list(APPEND CUDA_LIBRARIES ${CUDA_CUDART_LIBRARY})
endif()
# 1.1 toolkit on linux doesn't appear to have a separate library on
# some platforms.
cuda_find_library_local_first(CUDA_CUDA_LIBRARY cuda "\"cuda\" library (older versions only).")
mark_as_advanced(
CUDA_CUDA_LIBRARY
CUDA_CUDART_LIBRARY
)
#######################
# Look for some of the toolkit helper libraries
macro(FIND_CUDA_HELPER_LIBS _name)
cuda_find_library_local_first(CUDA_${_name}_LIBRARY ${_name} "\"${_name}\" library")
mark_as_advanced(CUDA_${_name}_LIBRARY)
endmacro()
#######################
# Disable emulation for v3.1 onward
if(CUDA_VERSION VERSION_GREATER "3.0")
if(CUDA_BUILD_EMULATION)
message(FATAL_ERROR "CUDA_BUILD_EMULATION is not supported in version 3.1 and onwards. You must disable it to proceed. You have version ${CUDA_VERSION}.")
endif()
endif()
# Search for additional CUDA toolkit libraries.
if(CUDA_VERSION VERSION_LESS "3.1")
# Emulation libraries aren't available in version 3.1 onward.
find_cuda_helper_libs(cufftemu)
find_cuda_helper_libs(cublasemu)
endif()
find_cuda_helper_libs(cufft)
find_cuda_helper_libs(cublas)
if(NOT CUDA_VERSION VERSION_LESS "3.2")
# cusparse showed up in version 3.2
find_cuda_helper_libs(cusparse)
find_cuda_helper_libs(curand)
if (WIN32)
find_cuda_helper_libs(nvcuvenc)
find_cuda_helper_libs(nvcuvid)
endif()
endif()
if(CUDA_VERSION VERSION_GREATER "5.0")
find_cuda_helper_libs(cublas_device)
# In CUDA 5.5 NPP was splitted onto 3 separate libraries.
find_cuda_helper_libs(nppc)
find_cuda_helper_libs(nppi)
find_cuda_helper_libs(npps)
set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppi_LIBRARY};${CUDA_npps_LIBRARY}")
elseif(NOT CUDA_VERSION VERSION_LESS "4.0")
find_cuda_helper_libs(npp)
endif()
if(NOT CUDA_VERSION VERSION_LESS "7.0")
# cusolver showed up in version 7.0
find_cuda_helper_libs(cusolver)
endif()
if(NOT CUDA_VERSION VERSION_LESS "7.5")
find_cuda_helper_libs(nvrtc)
endif()
if (CUDA_BUILD_EMULATION)
set(CUDA_CUFFT_LIBRARIES ${CUDA_cufftemu_LIBRARY})
set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublasemu_LIBRARY})
else()
set(CUDA_CUFFT_LIBRARIES ${CUDA_cufft_LIBRARY})
set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublas_LIBRARY} ${CUDA_cublas_device_LIBRARY})
endif()
########################
# Look for the SDK stuff. As of CUDA 3.0 NVSDKCUDA_ROOT has been replaced with
# NVSDKCOMPUTE_ROOT with the old CUDA C contents moved into the C subdirectory
find_path(CUDA_SDK_ROOT_DIR common/inc/cutil.h
HINTS
"$ENV{NVSDKCOMPUTE_ROOT}/C"
ENV NVSDKCUDA_ROOT
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Installed Products\\NVIDIA SDK 10\\Compute;InstallDir]"
PATHS
"/Developer/GPU\ Computing/C"
)
# Keep the CUDA_SDK_ROOT_DIR first in order to be able to override the
# environment variables.
set(CUDA_SDK_SEARCH_PATH
"${CUDA_SDK_ROOT_DIR}"
"${CUDA_TOOLKIT_ROOT_DIR}/local/NVSDK0.2"
"${CUDA_TOOLKIT_ROOT_DIR}/NVSDK0.2"
"${CUDA_TOOLKIT_ROOT_DIR}/NV_CUDA_SDK"
"$ENV{HOME}/NVIDIA_CUDA_SDK"
"$ENV{HOME}/NVIDIA_CUDA_SDK_MACOSX"
"/Developer/CUDA"
)
# Example of how to find an include file from the CUDA_SDK_ROOT_DIR
# find_path(CUDA_CUT_INCLUDE_DIR
# cutil.h
# PATHS ${CUDA_SDK_SEARCH_PATH}
# PATH_SUFFIXES "common/inc"
# DOC "Location of cutil.h"
# NO_DEFAULT_PATH
# )
# # Now search system paths
# find_path(CUDA_CUT_INCLUDE_DIR cutil.h DOC "Location of cutil.h")
# mark_as_advanced(CUDA_CUT_INCLUDE_DIR)
# Example of how to find a library in the CUDA_SDK_ROOT_DIR
# # cutil library is called cutil64 for 64 bit builds on windows. We don't want
# # to get these confused, so we are setting the name based on the word size of
# # the build.
# if(CMAKE_SIZEOF_VOID_P EQUAL 8)
# set(cuda_cutil_name cutil64)
# else()
# set(cuda_cutil_name cutil32)
# endif()
# find_library(CUDA_CUT_LIBRARY
# NAMES cutil ${cuda_cutil_name}
# PATHS ${CUDA_SDK_SEARCH_PATH}
# # The new version of the sdk shows up in common/lib, but the old one is in lib
# PATH_SUFFIXES "common/lib" "lib"
# DOC "Location of cutil library"
# NO_DEFAULT_PATH
# )
# # Now search system paths
# find_library(CUDA_CUT_LIBRARY NAMES cutil ${cuda_cutil_name} DOC "Location of cutil library")
# mark_as_advanced(CUDA_CUT_LIBRARY)
# set(CUDA_CUT_LIBRARIES ${CUDA_CUT_LIBRARY})
#############################
# Check for required components
set(CUDA_FOUND TRUE)
set(CUDA_TOOLKIT_ROOT_DIR_INTERNAL "${CUDA_TOOLKIT_ROOT_DIR}" CACHE INTERNAL
"This is the value of the last time CUDA_TOOLKIT_ROOT_DIR was set successfully." FORCE)
set(CUDA_TOOLKIT_TARGET_DIR_INTERNAL "${CUDA_TOOLKIT_TARGET_DIR}" CACHE INTERNAL
"This is the value of the last time CUDA_TOOLKIT_TARGET_DIR was set successfully." FORCE)
set(CUDA_SDK_ROOT_DIR_INTERNAL "${CUDA_SDK_ROOT_DIR}" CACHE INTERNAL
"This is the value of the last time CUDA_SDK_ROOT_DIR was set successfully." FORCE)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(CUDA
REQUIRED_VARS
CUDA_TOOLKIT_ROOT_DIR
CUDA_NVCC_EXECUTABLE
CUDA_INCLUDE_DIRS
${CUDA_CUDART_LIBRARY_VAR}
VERSION_VAR
CUDA_VERSION
)
###############################################################################
###############################################################################
# Macros
###############################################################################
###############################################################################
###############################################################################
# Add include directories to pass to the nvcc command.
macro(CUDA_INCLUDE_DIRECTORIES)
foreach(dir ${ARGN})
list(APPEND CUDA_NVCC_INCLUDE_ARGS_USER -I${dir})
endforeach()
endmacro()
##############################################################################
cuda_find_helper_file(parse_cubin cmake)
cuda_find_helper_file(make2cmake cmake)
cuda_find_helper_file(run_nvcc cmake)
include("${CMAKE_CURRENT_LIST_DIR}/FindCUDA/select_compute_arch.cmake")
##############################################################################
# Separate the OPTIONS out from the sources
#
macro(CUDA_GET_SOURCES_AND_OPTIONS _sources _cmake_options _options)
set( ${_sources} )
set( ${_cmake_options} )
set( ${_options} )
set( _found_options FALSE )
foreach(arg ${ARGN})
if("x${arg}" STREQUAL "xOPTIONS")
set( _found_options TRUE )
elseif(
"x${arg}" STREQUAL "xWIN32" OR
"x${arg}" STREQUAL "xMACOSX_BUNDLE" OR
"x${arg}" STREQUAL "xEXCLUDE_FROM_ALL" OR
"x${arg}" STREQUAL "xSTATIC" OR
"x${arg}" STREQUAL "xSHARED" OR
"x${arg}" STREQUAL "xMODULE"
)
list(APPEND ${_cmake_options} ${arg})
else()
if ( _found_options )
list(APPEND ${_options} ${arg})
else()
# Assume this is a file
list(APPEND ${_sources} ${arg})
endif()
endif()
endforeach()
endmacro()
##############################################################################
# Parse the OPTIONS from ARGN and set the variables prefixed by _option_prefix
#
macro(CUDA_PARSE_NVCC_OPTIONS _option_prefix)
set( _found_config )
foreach(arg ${ARGN})
# Determine if we are dealing with a perconfiguration flag
foreach(config ${CUDA_configuration_types})
string(TOUPPER ${config} config_upper)
if (arg STREQUAL "${config_upper}")
set( _found_config _${arg})
# Set arg to nothing to keep it from being processed further
set( arg )
endif()
endforeach()
if ( arg )
list(APPEND ${_option_prefix}${_found_config} "${arg}")
endif()
endforeach()
endmacro()
##############################################################################
# Helper to add the include directory for CUDA only once
function(CUDA_ADD_CUDA_INCLUDE_ONCE)
get_directory_property(_include_directories INCLUDE_DIRECTORIES)
set(_add TRUE)
if(_include_directories)
foreach(dir ${_include_directories})
if("${dir}" STREQUAL "${CUDA_INCLUDE_DIRS}")
set(_add FALSE)
endif()
endforeach()
endif()
if(_add)
include_directories(${CUDA_INCLUDE_DIRS})
endif()
endfunction()
function(CUDA_BUILD_SHARED_LIBRARY shared_flag)
set(cmake_args ${ARGN})
# If SHARED, MODULE, or STATIC aren't already in the list of arguments, then
# add SHARED or STATIC based on the value of BUILD_SHARED_LIBS.
list(FIND cmake_args SHARED _cuda_found_SHARED)
list(FIND cmake_args MODULE _cuda_found_MODULE)
list(FIND cmake_args STATIC _cuda_found_STATIC)
if( _cuda_found_SHARED GREATER -1 OR
_cuda_found_MODULE GREATER -1 OR
_cuda_found_STATIC GREATER -1)
set(_cuda_build_shared_libs)
else()
if (BUILD_SHARED_LIBS)
set(_cuda_build_shared_libs SHARED)
else()
set(_cuda_build_shared_libs STATIC)
endif()
endif()
set(${shared_flag} ${_cuda_build_shared_libs} PARENT_SCOPE)
endfunction()
##############################################################################
# Helper to avoid clashes of files with the same basename but different paths.
# This doesn't attempt to do exactly what CMake internals do, which is to only
# add this path when there is a conflict, since by the time a second collision
# in names is detected it's already too late to fix the first one. For
# consistency sake the relative path will be added to all files.
function(CUDA_COMPUTE_BUILD_PATH path build_path)
#message("CUDA_COMPUTE_BUILD_PATH([${path}] ${build_path})")
# Only deal with CMake style paths from here on out
file(TO_CMAKE_PATH "${path}" bpath)
if (IS_ABSOLUTE "${bpath}")
# Absolute paths are generally unnessary, especially if something like
# file(GLOB_RECURSE) is used to pick up the files.
string(FIND "${bpath}" "${CMAKE_CURRENT_BINARY_DIR}" _binary_dir_pos)
if (_binary_dir_pos EQUAL 0)
file(RELATIVE_PATH bpath "${CMAKE_CURRENT_BINARY_DIR}" "${bpath}")
else()
file(RELATIVE_PATH bpath "${CMAKE_CURRENT_SOURCE_DIR}" "${bpath}")
endif()
endif()
# This recipe is from cmLocalGenerator::CreateSafeUniqueObjectFileName in the
# CMake source.
# Remove leading /
string(REGEX REPLACE "^[/]+" "" bpath "${bpath}")
# Avoid absolute paths by removing ':'
string(REPLACE ":" "_" bpath "${bpath}")
# Avoid relative paths that go up the tree
string(REPLACE "../" "__/" bpath "${bpath}")
# Avoid spaces
string(REPLACE " " "_" bpath "${bpath}")
# Strip off the filename. I wait until here to do it, since removin the
# basename can make a path that looked like path/../basename turn into
# path/.. (notice the trailing slash).
get_filename_component(bpath "${bpath}" PATH)
set(${build_path} "${bpath}" PARENT_SCOPE)
#message("${build_path} = ${bpath}")
endfunction()
##############################################################################
##############################################################################
# CUDA WRAP SRCS
#
# This helper macro populates the following variables and setups up custom
# commands and targets to invoke the nvcc compiler to generate C or PTX source
# dependent upon the format parameter. The compiler is invoked once with -M
# to generate a dependency file and a second time with -cuda or -ptx to generate
# a .cpp or .ptx file.
# INPUT:
# cuda_target - Target name
# format - PTX, CUBIN, FATBIN or OBJ
# FILE1 .. FILEN - The remaining arguments are the sources to be wrapped.
# OPTIONS - Extra options to NVCC
# OUTPUT:
# generated_files - List of generated files
##############################################################################
##############################################################################
macro(CUDA_WRAP_SRCS cuda_target format generated_files)
# If CMake doesn't support separable compilation, complain
if(CUDA_SEPARABLE_COMPILATION AND CMAKE_VERSION VERSION_LESS "2.8.10.1")
message(SEND_ERROR "CUDA_SEPARABLE_COMPILATION isn't supported for CMake versions less than 2.8.10.1")
endif()
# Set up all the command line flags here, so that they can be overridden on a per target basis.
set(nvcc_flags "")
# Emulation if the card isn't present.
if (CUDA_BUILD_EMULATION)
# Emulation.
set(nvcc_flags ${nvcc_flags} --device-emulation -D_DEVICEEMU -g)
else()
# Device mode. No flags necessary.
endif()
if(CUDA_HOST_COMPILATION_CPP)
set(CUDA_C_OR_CXX CXX)
else()
if(CUDA_VERSION VERSION_LESS "3.0")
set(nvcc_flags ${nvcc_flags} --host-compilation C)
else()
message(WARNING "--host-compilation flag is deprecated in CUDA version >= 3.0. Removing --host-compilation C flag" )
endif()
set(CUDA_C_OR_CXX C)
endif()
set(generated_extension ${CMAKE_${CUDA_C_OR_CXX}_OUTPUT_EXTENSION})
if(CUDA_64_BIT_DEVICE_CODE)
set(nvcc_flags ${nvcc_flags} -m64)
else()
set(nvcc_flags ${nvcc_flags} -m32)
endif()
if(CUDA_TARGET_CPU_ARCH)
set(nvcc_flags ${nvcc_flags} "--target-cpu-architecture=${CUDA_TARGET_CPU_ARCH}")
endif()
# This needs to be passed in at this stage, because VS needs to fill out the
# value of VCInstallDir from within VS. Note that CCBIN is only used if
# -ccbin or --compiler-bindir isn't used and CUDA_HOST_COMPILER matches
# $(VCInstallDir)/bin.
if(CMAKE_GENERATOR MATCHES "Visual Studio")
set(ccbin_flags -D "\"CCBIN:PATH=${CUDA_HOST_COMPILER}\"" )
else()
set(ccbin_flags)
endif()
# Figure out which configure we will use and pass that in as an argument to
# the script. We need to defer the decision until compilation time, because
# for VS projects we won't know if we are making a debug or release build
# until build time.
if(CMAKE_GENERATOR MATCHES "Visual Studio")
set( CUDA_build_configuration "$(ConfigurationName)" )
else()
set( CUDA_build_configuration "${CMAKE_BUILD_TYPE}")
endif()
# Initialize our list of includes with the user ones followed by the CUDA system ones.
set(CUDA_NVCC_INCLUDE_ARGS ${CUDA_NVCC_INCLUDE_ARGS_USER} "-I${CUDA_INCLUDE_DIRS}")
# Get the include directories for this directory and use them for our nvcc command.
get_directory_property(CUDA_NVCC_INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES)
if(CUDA_NVCC_INCLUDE_DIRECTORIES)
foreach(dir ${CUDA_NVCC_INCLUDE_DIRECTORIES})
list(APPEND CUDA_NVCC_INCLUDE_ARGS -I${dir})
endforeach()
endif()
# Reset these variables
set(CUDA_WRAP_OPTION_NVCC_FLAGS)
foreach(config ${CUDA_configuration_types})
string(TOUPPER ${config} config_upper)
set(CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper})
endforeach()
CUDA_GET_SOURCES_AND_OPTIONS(_cuda_wrap_sources _cuda_wrap_cmake_options _cuda_wrap_options ${ARGN})
CUDA_PARSE_NVCC_OPTIONS(CUDA_WRAP_OPTION_NVCC_FLAGS ${_cuda_wrap_options})
# Figure out if we are building a shared library. BUILD_SHARED_LIBS is
# respected in CUDA_ADD_LIBRARY.
set(_cuda_build_shared_libs FALSE)
# SHARED, MODULE
list(FIND _cuda_wrap_cmake_options SHARED _cuda_found_SHARED)
list(FIND _cuda_wrap_cmake_options MODULE _cuda_found_MODULE)
if(_cuda_found_SHARED GREATER -1 OR _cuda_found_MODULE GREATER -1)
set(_cuda_build_shared_libs TRUE)
endif()
# STATIC
list(FIND _cuda_wrap_cmake_options STATIC _cuda_found_STATIC)
if(_cuda_found_STATIC GREATER -1)
set(_cuda_build_shared_libs FALSE)
endif()
# CUDA_HOST_FLAGS
if(_cuda_build_shared_libs)
# If we are setting up code for a shared library, then we need to add extra flags for
# compiling objects for shared libraries.
set(CUDA_HOST_SHARED_FLAGS ${CMAKE_SHARED_LIBRARY_${CUDA_C_OR_CXX}_FLAGS})
else()
set(CUDA_HOST_SHARED_FLAGS)
endif()
# If we are using batch building and we are using VS 2013+ we could have problems with
# parallel accesses to the PDB files which comes from the parallel batch building. /FS
# serializes the builds which fixes this. There doesn't seem any harm to add this for
# PTX targets or for builds that don't do parallel building.
set( EXTRA_FS_ARG )
if( CUDA_BATCH_BUILD_LOG AND MSVC )
if(NOT MSVC_VERSION VERSION_LESS 1800)
set( EXTRA_FS_ARG "/FS" )
endif()
endif()
# Only add the CMAKE_{C,CXX}_FLAGS if we are propagating host flags. We
# always need to set the SHARED_FLAGS, though.
if(CUDA_PROPAGATE_HOST_FLAGS)
set(_cuda_host_flags "set(CMAKE_HOST_FLAGS ${CMAKE_${CUDA_C_OR_CXX}_FLAGS} ${CUDA_HOST_SHARED_FLAGS} ${EXTRA_FS_ARG})")
else()
set(_cuda_host_flags "set(CMAKE_HOST_FLAGS ${CUDA_HOST_SHARED_FLAGS} ${EXTRA_FS_ARG})")
endif()
set(_cuda_nvcc_flags_config "# Build specific configuration flags")
# Loop over all the configuration types to generate appropriate flags for run_nvcc.cmake
foreach(config ${CUDA_configuration_types})
string(TOUPPER ${config} config_upper)
# CMAKE_FLAGS are strings and not lists. By not putting quotes around CMAKE_FLAGS
# we convert the strings to lists (like we want).
if(CUDA_PROPAGATE_HOST_FLAGS)
# nvcc chokes on -g3 in versions previous to 3.0, so replace it with -g
set(_cuda_fix_g3 FALSE)
if(CMAKE_COMPILER_IS_GNUCC)
if (CUDA_VERSION VERSION_LESS "3.0" OR
CUDA_VERSION VERSION_EQUAL "4.1" OR
CUDA_VERSION VERSION_EQUAL "4.2"
)
set(_cuda_fix_g3 TRUE)
endif()
endif()
if(_cuda_fix_g3)
string(REPLACE "-g3" "-g" _cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
else()
set(_cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
endif()
# Using the optimized debug information flag causes problems.
if (MSVC)
string(REPLACE "/Zo" "" _cuda_C_FLAGS "${_cuda_C_FLAGS}")
endif()
set(_cuda_host_flags "${_cuda_host_flags}\nset(CMAKE_HOST_FLAGS_${config_upper} ${_cuda_C_FLAGS})")
endif()
# Note that if we ever want CUDA_NVCC_FLAGS_<CONFIG> to be string (instead of a list
# like it is currently), we can remove the quotes around the
# ${CUDA_NVCC_FLAGS_${config_upper}} variable like the CMAKE_HOST_FLAGS_<CONFIG> variable.
set(_cuda_nvcc_flags_config "${_cuda_nvcc_flags_config}\nset(CUDA_NVCC_FLAGS_${config_upper} ${CUDA_NVCC_FLAGS_${config_upper}} ;; ${CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper}})")
endforeach()
# NVCC can't handle this C++ argument, because it uses during certain phases where the C
# compiler is invoked and complains about it.
if( CMAKE_COMPILER_IS_GNUCXX )
string(REPLACE "-fvisibility-inlines-hidden" "" _cuda_host_flags "${_cuda_host_flags}")
endif()
# Process the C++11 flag. If the host sets the flag, we need to add it to nvcc and
# remove it from the host. This is because -Xcompile -std=c++ will choke nvcc (it uses
# the C preprocessor). In order to get this to work correctly, we need to use nvcc's
# specific c++11 flag.
if( "${_cuda_host_flags}" MATCHES "-std=c\\+\\+11" OR ( CMAKE_CXX_STANDARD EQUAL 11 AND NOT USING_WINDOWS_CL ) )
# Add the c++11 flag to nvcc if it isn't already present. Note that we only look at
# the main flag instead of the configuration specific flags.
if( NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std;c\\+\\+11" )
list(APPEND nvcc_flags --std c++11)
endif()
string(REGEX REPLACE "[-]+std=c\\+\\+11" "" _cuda_host_flags "${_cuda_host_flags}")
endif()
# Get the list of definitions from the directory property
get_directory_property(CUDA_NVCC_DEFINITIONS COMPILE_DEFINITIONS)
if(CUDA_NVCC_DEFINITIONS)
foreach(_definition ${CUDA_NVCC_DEFINITIONS})
list(APPEND nvcc_flags "-D${_definition}")
endforeach()
endif()
if(_cuda_build_shared_libs)
list(APPEND nvcc_flags "-D${cuda_target}_EXPORTS")
endif()
# Reset the output variable
set(_cuda_wrap_generated_files "")
# Iterate over the macro arguments and create custom
# commands for all the .cu files.
foreach(file ${ARGN})
# Ignore any file marked as a HEADER_FILE_ONLY
get_source_file_property(_is_header ${file} HEADER_FILE_ONLY)
# Allow per source file overrides of the format. Also allows compiling non-.cu files.
get_source_file_property(_cuda_source_format ${file} CUDA_SOURCE_PROPERTY_FORMAT)
if((${file} MATCHES "\\.cu$" OR _cuda_source_format) AND NOT _is_header)
if(NOT _cuda_source_format)
set(_cuda_source_format ${format})
endif()
# If file isn't a .cu file, we need to tell nvcc to treat it as such.
if(NOT ${file} MATCHES "\\.cu$")
set(cuda_language_flag -x=cu)
else()
set(cuda_language_flag)
endif()
if( ${_cuda_source_format} STREQUAL "OBJ")
set( cuda_compile_to_external_module OFF )
set( cuda_compile_to_external_module_multi_config_build ON )
else()
set( cuda_compile_to_external_module ON )
set( cuda_compile_to_external_module_multi_config_build OFF )
if( ${_cuda_source_format} STREQUAL "PTX" )
set( cuda_compile_to_external_module_flag "-ptx")
set( cuda_compile_to_external_module_type "ptx" )
elseif( ${_cuda_source_format} STREQUAL "CUBIN")
set( cuda_compile_to_external_module_flag "-cubin" )
set( cuda_compile_to_external_module_type "cubin" )
elseif( ${_cuda_source_format} STREQUAL "FATBIN")
set( cuda_compile_to_external_module_flag "-fatbin" )
set( cuda_compile_to_external_module_type "fatbin" )
elseif( ${_cuda_source_format} STREQUAL "OPTIXIR")
set( cuda_compile_to_external_module_flag "-optix-ir" )
set( cuda_compile_to_external_module_type "optixir" )
set( cuda_compile_to_external_module_multi_config_build ON )
else()
if(DEFINED CUDA_CUSTOM_SOURCE_FORMAT_FLAG_${_cuda_source_format} AND DEFINED CUDA_CUSTOM_SOURCE_FORMAT_TYPE_${_cuda_source_format})
set( cuda_compile_to_external_module_flag "${CUDA_CUSTOM_SOURCE_FORMAT_FLAG_${_cuda_source_format}}" )
set( cuda_compile_to_external_module_type "${CUDA_CUSTOM_SOURCE_FORMAT_TYPE_${_cuda_source_format}}" )
else()
message( FATAL_ERROR "Invalid format flag passed to CUDA_WRAP_SRCS or set with CUDA_SOURCE_PROPERTY_FORMAT file property for file '${file}': '${_cuda_source_format}'. Use OBJ, PTX, CUBIN or FATBIN.")
endif()
endif()
endif()
if(cuda_compile_to_external_module)
# Don't use any of the host compilation flags for PTX targets.
set(CUDA_HOST_FLAGS)
else()
set(CUDA_HOST_FLAGS ${_cuda_host_flags})
endif()
if(cuda_compile_to_external_module_multi_config_build)
set(CUDA_NVCC_FLAGS_CONFIG ${_cuda_nvcc_flags_config})
set( cuda_compile_cfg_intdir "${CMAKE_CFG_INTDIR}" )
else()
set(CUDA_NVCC_FLAGS_CONFIG)
set( cuda_compile_cfg_intdir "." )
endif()
# Determine output directory
cuda_compute_build_path("${file}" cuda_build_path)
set(cuda_compile_intermediate_directory "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${cuda_target}.dir/${cuda_build_path}")
if(CUDA_GENERATED_OUTPUT_DIR)
set(cuda_compile_output_dir "${CUDA_GENERATED_OUTPUT_DIR}")
else()
if ( cuda_compile_to_external_module )
set(cuda_compile_output_dir "${CMAKE_CURRENT_BINARY_DIR}")
else()
set(cuda_compile_output_dir "${cuda_compile_intermediate_directory}")
endif()
endif()
# Add a custom target to generate a c or ptx file. ######################
get_filename_component( basename ${file} NAME )
set(generated_file_path "${cuda_compile_output_dir}/${cuda_compile_cfg_intdir}")
if( cuda_compile_to_external_module )
set(generated_file_basename "${cuda_target}_generated_${basename}.${cuda_compile_to_external_module_type}")
set(format_flag "${cuda_compile_to_external_module_flag}")
file(MAKE_DIRECTORY "${cuda_compile_output_dir}")
else()
set(generated_file_basename "${cuda_target}_generated_${basename}${generated_extension}")
if(CUDA_SEPARABLE_COMPILATION)
set(format_flag "-dc")
else()
set(format_flag "-c")
endif()
endif()
# Set all of our file names. Make sure that whatever filenames that have
# generated_file_path in them get passed in through as a command line
# argument, so that the ${CMAKE_CFG_INTDIR} gets expanded at run time
# instead of configure time.
set(generated_file "${generated_file_path}/${generated_file_basename}")
set(cmake_dependency_file "${cuda_compile_intermediate_directory}/${generated_file_basename}.depend")
set(NVCC_generated_dependency_file "${cuda_compile_intermediate_directory}/${generated_file_basename}.NVCC-depend")
set(generated_cubin_file "${generated_file_path}/${generated_file_basename}.cubin.txt")
set(generated_fatbin_file "${generated_file_path}/${generated_file_basename}.fatbin.txt")
set(custom_target_script "${cuda_compile_intermediate_directory}/${generated_file_basename}.cmake")
# Setup properties for obj files:
if( NOT cuda_compile_to_external_module )
set_source_files_properties("${generated_file}"
PROPERTIES
EXTERNAL_OBJECT true # This is an object file not to be compiled, but only be linked.
)
endif()
# Don't add CMAKE_CURRENT_SOURCE_DIR if the path is already an absolute path.
get_filename_component(file_path "${file}" PATH)
if(IS_ABSOLUTE "${file_path}")
set(source_file "${file}")
else()
set(source_file "${CMAKE_CURRENT_SOURCE_DIR}/${file}")
endif()
if( NOT cuda_compile_to_external_module AND CUDA_SEPARABLE_COMPILATION)
list(APPEND ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS "${generated_file}")
endif()
# Convience string for output ###########################################
if(CUDA_BUILD_EMULATION)
set(cuda_build_type "Emulation")
else()
set(cuda_build_type "Device")
endif()
# Build the NVCC made dependency file ###################################
set(build_cubin OFF)
if ( NOT CUDA_BUILD_EMULATION AND CUDA_BUILD_CUBIN )
if ( NOT cuda_compile_to_external_module )
set ( build_cubin ON )
endif()
endif()
# Configure the build script
configure_file("${CUDA_run_nvcc}" "${custom_target_script}" @ONLY)
# So if a user specifies the same cuda file as input more than once, you
# can have bad things happen with dependencies. Here we check an option
# to see if this is the behavior they want.
if(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE)
set(main_dep MAIN_DEPENDENCY ${source_file})
else()
set(main_dep DEPENDS ${source_file})
endif()
if(CUDA_VERBOSE_BUILD)
set(verbose_output ON)
elseif(CMAKE_GENERATOR MATCHES "Makefiles")
set(verbose_output "$(VERBOSE)")
else()
set(verbose_output OFF)
endif()
# Create up the comment string
file(RELATIVE_PATH generated_file_relative_path "${CMAKE_BINARY_DIR}" "${generated_file}")
if(cuda_compile_to_external_module)
set(cuda_build_comment_string "Building NVCC ${cuda_compile_to_external_module_type} file ${generated_file_relative_path}")
else()
set(cuda_build_comment_string "Building NVCC (${cuda_build_type}) object ${generated_file_relative_path}")
endif()
# Bring in the dependencies. Creates a variable CUDA_NVCC_DEPEND #######
cuda_include_nvcc_dependencies(${cmake_dependency_file})
# Check to see if the build script is newer than the dependency file. If
# it is, regenerate it.
# message("CUDA_GENERATE_DEPENDENCIES_DURING_CONFIGURE = ${CUDA_GENERATE_DEPENDENCIES_DURING_CONFIGURE}")
# message("CUDA_NVCC_DEPEND_REGENERATE = ${CUDA_NVCC_DEPEND_REGENERATE}")
# execute_process(COMMAND ls -lTtr "${custom_target_script}" "${cmake_dependency_file}" "${NVCC_generated_dependency_file}")
set(_cuda_generate_dependencies FALSE)
# Note that NVCC_generated_dependency_file is always generated.
if(CUDA_GENERATE_DEPENDENCIES_DURING_CONFIGURE
AND "${custom_target_script}" IS_NEWER_THAN "${NVCC_generated_dependency_file}")
# If the two files were generated about the same time then reversing the
# comparison will also be true, so check the CUDA_NVCC_DEPEND_REGENERATE
# flag.
if ("${NVCC_generated_dependency_file}" IS_NEWER_THAN "${custom_target_script}")
# message("************************************************************************")
# message("Same modification time: ${custom_target_script} ${NVCC_generated_dependency_file}")
if (CUDA_NVCC_DEPEND_REGENERATE OR NOT EXISTS "${NVCC_generated_dependency_file}")
set(_cuda_generate_dependencies TRUE)
endif()
else()
# The timestamp check is valid
set(_cuda_generate_dependencies TRUE)
endif()
endif()
# message("_cuda_generate_dependencies = ${_cuda_generate_dependencies}")
# If we needed to regenerate the dependency file, do so now.
if (_cuda_generate_dependencies)
set(_cuda_dependency_ccbin)
# message("CUDA_HOST_COMPILER = ${CUDA_HOST_COMPILER}")
if(ccbin_flags MATCHES "\\$\\(VCInstallDir\\)")
set(_cuda_dependency_ccbin_dir)
if (CUDA_VS_DIR AND EXISTS "${CUDA_VS_DIR}/VC/bin")
set(_cuda_dependency_ccbin_dir "${CUDA_VS_DIR}/VC/bin")
elseif( EXISTS "${CMAKE_CXX_COMPILER}" )
get_filename_component(_cuda_dependency_ccbin_dir "${CMAKE_CXX_COMPILER}" DIRECTORY)
endif()
if( _cuda_dependency_ccbin_dir )
set(_cuda_dependency_ccbin -D "CCBIN:PATH=${_cuda_dependency_ccbin_dir}")
endif()
elseif(ccbin_flags)
# The CUDA_HOST_COMPILER is set to something interesting, so use the
# ccbin_flags as-is.
set(_cuda_dependency_ccbin ${ccbin_flags})
endif()
# message("_cuda_dependency_ccbin = ${_cuda_dependency_ccbin}")
if(_cuda_dependency_ccbin OR NOT ccbin_flags)
# Only do this if we have some kind of host compiler defined in
# _cuda_dependency_ccbin or ccbin_flags isn't set.
set( _execute_process_args
COMMAND ${CMAKE_COMMAND}
-D generate_dependency_only:BOOL=TRUE
-D verbose:BOOL=TRUE
${_cuda_dependency_ccbin}
-D "generated_file:STRING=${generated_file}"
-D "generated_cubin_file:STRING=${generated_cubin_file}"
-P "${custom_target_script}"
WORKING_DIRECTORY "${cuda_compile_intermediate_directory}"
RESULT_VARIABLE _cuda_dependency_error
OUTPUT_VARIABLE _cuda_dependency_output
ERROR_VARIABLE _cuda_dependency_output
)
if( CUDA_BATCH_DEPENDS_LOG )
file( APPEND ${CUDA_BATCH_DEPENDS_LOG} "COMMENT;Generating dependencies for ${file};${_execute_process_args}\n" )
else()
message(STATUS "Generating dependencies for ${file}")
execute_process(
${_execute_process_args}
)
endif()
if (_cuda_dependency_error)
message(WARNING "Error (${_cuda_dependency_error}) generating dependencies for ${file}:\n\n${_cuda_dependency_output}. This will be postponed until build time.")
else()
# Try and reload the dependies
cuda_include_nvcc_dependencies(${cmake_dependency_file})
endif()
endif()
endif()
# Build the generated file and dependency file ##########################
set( _custom_command_args
OUTPUT ${generated_file}
# These output files depend on the source_file and the contents of cmake_dependency_file
${main_dep}
DEPENDS ${CUDA_NVCC_DEPEND}
DEPENDS ${custom_target_script}
# Make sure the output directory exists before trying to write to it.
COMMAND ${CMAKE_COMMAND} -E make_directory "${generated_file_path}"
COMMAND ${CMAKE_COMMAND}
-D verbose:BOOL=${verbose_output}
-D check_dependencies:BOOL=${CUDA_CHECK_DEPENDENCIES_DURING_COMPILE}
${ccbin_flags}
-D build_configuration:STRING=${CUDA_build_configuration}
-D "generated_file:STRING=${generated_file}"
-D "generated_cubin_file:STRING=${generated_cubin_file}"
-D "generated_fatbin_file:STRING=${generated_fatbin_file}"
-P "${custom_target_script}"
WORKING_DIRECTORY "${cuda_compile_intermediate_directory}"
COMMENT "${cuda_build_comment_string}"
)
if( CUDA_BATCH_BUILD_LOG )
list(APPEND CUDA_BATCH_BUILD_OUTPUTS ${generated_file})
set_property( GLOBAL APPEND PROPERTY CUDA_BATCH_BUILD_DEPENDS ${source_file} ${CUDA_NVCC_DEPEND} ${custom_target_script})
file( APPEND ${CUDA_BATCH_BUILD_LOG} "${_custom_command_args}\n" )
endif()
add_custom_command( ${_custom_command_args} )
# Make sure the build system knows the file is generated.
set_source_files_properties(${generated_file} PROPERTIES GENERATED TRUE)
list(APPEND _cuda_wrap_generated_files ${generated_file})
# Add the other files that we want cmake to clean on a cleanup ##########
list(APPEND CUDA_ADDITIONAL_CLEAN_FILES "${cmake_dependency_file}")
list(REMOVE_DUPLICATES CUDA_ADDITIONAL_CLEAN_FILES)
set(CUDA_ADDITIONAL_CLEAN_FILES ${CUDA_ADDITIONAL_CLEAN_FILES} CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
endif()
endforeach()
# Set the return parameter
set(${generated_files} ${_cuda_wrap_generated_files})
endmacro()
function(_cuda_get_important_host_flags important_flags flag_string)
if(CMAKE_GENERATOR MATCHES "Visual Studio")
string(REGEX MATCHALL "/M[DT][d]?" flags "${flag_string}")
list(APPEND ${important_flags} ${flags})
else()
string(REGEX MATCHALL "-fPIC" flags "${flag_string}")
list(APPEND ${important_flags} ${flags})
endif()
set(${important_flags} ${${important_flags}} PARENT_SCOPE)
endfunction()
###############################################################################
###############################################################################
# Separable Compilation Link
###############################################################################
###############################################################################
# Compute the filename to be used by CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS
function(CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME output_file_var cuda_target object_files)
if (object_files)
set(generated_extension ${CMAKE_${CUDA_C_OR_CXX}_OUTPUT_EXTENSION})
set(output_file "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${cuda_target}.dir/${CMAKE_CFG_INTDIR}/${cuda_target}_intermediate_link${generated_extension}")
else()
set(output_file)
endif()
set(${output_file_var} "${output_file}" PARENT_SCOPE)
endfunction()
# Setup the build rule for the separable compilation intermediate link file.
function(CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS output_file cuda_target options object_files)
if (object_files)
set_source_files_properties("${output_file}"
PROPERTIES
EXTERNAL_OBJECT TRUE # This is an object file not to be compiled, but only
# be linked.
GENERATED TRUE # This file is generated during the build
)
# For now we are ignoring all the configuration specific flags.
set(nvcc_flags)
CUDA_PARSE_NVCC_OPTIONS(nvcc_flags ${options})
if(CUDA_64_BIT_DEVICE_CODE)
list(APPEND nvcc_flags -m64)
else()
list(APPEND nvcc_flags -m32)
endif()
# If -ccbin, --compiler-bindir has been specified, don't do anything. Otherwise add it here.
list( FIND nvcc_flags "-ccbin" ccbin_found0 )
list( FIND nvcc_flags "--compiler-bindir" ccbin_found1 )
if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 AND CUDA_HOST_COMPILER )
# Match VERBATIM check below.
if(CUDA_HOST_COMPILER MATCHES "\\$\\(VCInstallDir\\)")
list(APPEND nvcc_flags -ccbin "\"${CUDA_HOST_COMPILER}\"")
else()
list(APPEND nvcc_flags -ccbin "${CUDA_HOST_COMPILER}")
endif()
endif()
# Create a list of flags specified by CUDA_NVCC_FLAGS_${CONFIG} and CMAKE_${CUDA_C_OR_CXX}_FLAGS*
set(config_specific_flags)
set(flags)
foreach(config ${CUDA_configuration_types})
string(TOUPPER ${config} config_upper)
# Add config specific flags
foreach(f ${CUDA_NVCC_FLAGS_${config_upper}})
list(APPEND config_specific_flags $<$<CONFIG:${config}>:${f}>)
endforeach()
set(important_host_flags)
_cuda_get_important_host_flags(important_host_flags "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
foreach(f ${important_host_flags})
list(APPEND flags $<$<CONFIG:${config}>:-Xcompiler> $<$<CONFIG:${config}>:${f}>)
endforeach()
endforeach()
# Add CMAKE_${CUDA_C_OR_CXX}_FLAGS
set(important_host_flags)
_cuda_get_important_host_flags(important_host_flags "${CMAKE_${CUDA_C_OR_CXX}_FLAGS}")
foreach(f ${important_host_flags})
list(APPEND flags -Xcompiler ${f})
endforeach()
# Add our general CUDA_NVCC_FLAGS with the configuration specifig flags
set(nvcc_flags ${CUDA_NVCC_FLAGS} ${config_specific_flags} ${nvcc_flags})
file(RELATIVE_PATH output_file_relative_path "${CMAKE_BINARY_DIR}" "${output_file}")
# Some generators don't handle the multiple levels of custom command
# dependencies correctly (obj1 depends on file1, obj2 depends on obj1), so
# we work around that issue by compiling the intermediate link object as a
# pre-link custom command in that situation.
set(do_obj_build_rule TRUE)
if (MSVC_VERSION GREATER 1599 AND MSVC_VERSION LESS 1800)
# VS 2010 and 2012 have this problem.
set(do_obj_build_rule FALSE)
endif()
set(_verbatim VERBATIM)
if(nvcc_flags MATCHES "\\$\\(VCInstallDir\\)")
set(_verbatim "")
endif()
if (do_obj_build_rule)
add_custom_command(
OUTPUT ${output_file}
DEPENDS ${object_files}
COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} -dlink ${object_files} -o ${output_file}
${flags}
COMMENT "Building NVCC intermediate link file ${output_file_relative_path}"
${_verbatim}
)
else()
get_filename_component(output_file_dir "${output_file}" DIRECTORY)
add_custom_command(
TARGET ${cuda_target}
PRE_LINK
COMMAND ${CMAKE_COMMAND} -E echo "Building NVCC intermediate link file ${output_file_relative_path}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${output_file_dir}"
COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} ${flags} -dlink ${object_files} -o "${output_file}"
${_verbatim}
)
endif()
endif()
endfunction()
###############################################################################
###############################################################################
# ADD LIBRARY
###############################################################################
###############################################################################
macro(CUDA_ADD_LIBRARY cuda_target)
CUDA_ADD_CUDA_INCLUDE_ONCE()
# Separate the sources from the options
CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
CUDA_BUILD_SHARED_LIBRARY(_cuda_shared_flag ${ARGN})
# Create custom commands and targets for each file.
CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources}
${_cmake_options} ${_cuda_shared_flag}
OPTIONS ${_options} )
# Compute the file name of the intermedate link file used for separable
# compilation.
CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME(link_file ${cuda_target} "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
# Add the library.
add_library(${cuda_target} ${_cmake_options}
${_generated_files}
${_sources}
${link_file}
)
# Add a link phase for the separable compilation if it has been enabled. If
# it has been enabled then the ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS
# variable will have been defined.
CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS("${link_file}" ${cuda_target} "${_options}" "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
target_link_libraries(${cuda_target}
${CUDA_LIBRARIES}
)
if(CUDA_SEPARABLE_COMPILATION)
target_link_libraries(${cuda_target}
${CUDA_cudadevrt_LIBRARY}
)
endif()
# We need to set the linker language based on what the expected generated file
# would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
set_target_properties(${cuda_target}
PROPERTIES
LINKER_LANGUAGE ${CUDA_C_OR_CXX}
)
endmacro()
###############################################################################
###############################################################################
# ADD EXECUTABLE
###############################################################################
###############################################################################
macro(CUDA_ADD_EXECUTABLE cuda_target)
CUDA_ADD_CUDA_INCLUDE_ONCE()
# Separate the sources from the options
CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
# Create custom commands and targets for each file.
CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources} OPTIONS ${_options} )
# Compute the file name of the intermedate link file used for separable
# compilation.
CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME(link_file ${cuda_target} "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
# Add the library.
add_executable(${cuda_target} ${_cmake_options}
${_generated_files}
${_sources}
${link_file}
)
# Add a link phase for the separable compilation if it has been enabled. If
# it has been enabled then the ${cuda_target}_SEPARABLE_COMPILATION_OBJECTS
# variable will have been defined.
CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS("${link_file}" ${cuda_target} "${_options}" "${${cuda_target}_SEPARABLE_COMPILATION_OBJECTS}")
target_link_libraries(${cuda_target}
${CUDA_LIBRARIES}
)
# We need to set the linker language based on what the expected generated file
# would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
set_target_properties(${cuda_target}
PROPERTIES
LINKER_LANGUAGE ${CUDA_C_OR_CXX}
)
endmacro()
###############################################################################
###############################################################################
# (Internal) helper for manually added cuda source files with specific targets
###############################################################################
###############################################################################
macro(cuda_compile_base cuda_target format generated_files)
# Separate the sources from the options
CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
# Create custom commands and targets for each file.
CUDA_WRAP_SRCS( ${cuda_target} ${format} _generated_files ${_sources}
${_cmake_options} OPTIONS ${_options})
set( ${generated_files} ${_generated_files})
endmacro()
###############################################################################
###############################################################################
# CUDA COMPILE
###############################################################################
###############################################################################
macro(CUDA_COMPILE generated_files)
cuda_compile_base(cuda_compile OBJ ${generated_files} ${ARGN})
endmacro()
###############################################################################
###############################################################################
# CUDA COMPILE PTX
###############################################################################
###############################################################################
macro(CUDA_COMPILE_PTX generated_files)
cuda_compile_base(cuda_compile_ptx PTX ${generated_files} ${ARGN})
endmacro()
###############################################################################
###############################################################################
# CUDA COMPILE FATBIN
###############################################################################
###############################################################################
macro(CUDA_COMPILE_FATBIN generated_files)
cuda_compile_base(cuda_compile_fatbin FATBIN ${generated_files} ${ARGN})
endmacro()
###############################################################################
###############################################################################
# CUDA COMPILE CUBIN
###############################################################################
###############################################################################
macro(CUDA_COMPILE_CUBIN generated_files)
cuda_compile_base(cuda_compile_cubin CUBIN ${generated_files} ${ARGN})
endmacro()
###############################################################################
###############################################################################
# CUDA ADD CUFFT TO TARGET
###############################################################################
###############################################################################
macro(CUDA_ADD_CUFFT_TO_TARGET target)
if (CUDA_BUILD_EMULATION)
target_link_libraries(${target} ${CUDA_cufftemu_LIBRARY})
else()
target_link_libraries(${target} ${CUDA_cufft_LIBRARY})
endif()
endmacro()
###############################################################################
###############################################################################
# CUDA ADD CUBLAS TO TARGET
###############################################################################
###############################################################################
macro(CUDA_ADD_CUBLAS_TO_TARGET target)
if (CUDA_BUILD_EMULATION)
target_link_libraries(${target} ${CUDA_cublasemu_LIBRARY})
else()
target_link_libraries(${target} ${CUDA_cublas_LIBRARY} ${CUDA_cublas_device_LIBRARY})
endif()
endmacro()
###############################################################################
###############################################################################
# CUDA BUILD CLEAN TARGET
###############################################################################
###############################################################################
macro(CUDA_BUILD_CLEAN_TARGET)
# Call this after you add all your CUDA targets, and you will get a convience
# target. You should also make clean after running this target to get the
# build system to generate all the code again.
set(cuda_clean_target_name clean_cuda_depends)
if (CMAKE_GENERATOR MATCHES "Visual Studio")
string(TOUPPER ${cuda_clean_target_name} cuda_clean_target_name)
endif()
add_custom_target(${cuda_clean_target_name}
COMMAND ${CMAKE_COMMAND} -E remove ${CUDA_ADDITIONAL_CLEAN_FILES})
# Clear out the variable, so the next time we configure it will be empty.
# This is useful so that the files won't persist in the list after targets
# have been removed.
set(CUDA_ADDITIONAL_CLEAN_FILES "" CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
endmacro()
##############################################################################
###############################################################################
# CUDA BATCH BUILD BEGIN
###############################################################################
###############################################################################
function(CUDA_BATCH_BUILD_BEGIN target)
if(MSVC AND CUDA_ENABLE_BATCHING)
set( CUDA_BATCH_BUILD_LOG "${CMAKE_BINARY_DIR}/CMakeFiles/${target}.dir/cudaBatchBuild.log" )
file( REMOVE ${CUDA_BATCH_BUILD_LOG} )
set( CUDA_BATCH_BUILD_LOG "${CUDA_BATCH_BUILD_LOG}" PARENT_SCOPE ) # export variable
set_property( GLOBAL PROPERTY CUDA_BATCH_BUILD_DEPENDS "" )
endif()
endfunction()
###############################################################################
###############################################################################
# CUDA BATCH BUILD END
###############################################################################
###############################################################################
function(CUDA_BATCH_BUILD_END target)
set(BATCH_CMAKE_SCRIPT "${CMAKE_SOURCE_DIR}/CMake/cuda/FindCUDA/batchCMake.py")
find_package(PythonInterp)
if( CUDA_BATCH_BUILD_LOG )
set(cuda_batch_build_target "_${target}_cudaBatchBuild")
set(stamp_dir "${CMAKE_BINARY_DIR}/CMakeFiles/${target}.dir/${CMAKE_CFG_INTDIR}")
set(stamp_file ${stamp_dir}/cuda-batch-build.stamp)
get_property(cuda_depends GLOBAL PROPERTY CUDA_BATCH_BUILD_DEPENDS)
list(REMOVE_DUPLICATES cuda_depends)
add_custom_target( ${cuda_batch_build_target}
COMMENT "CUDA batch build ${cuda_batch_build_target}..."
COMMAND "${PYTHON_EXECUTABLE}" "${BATCH_CMAKE_SCRIPT}" -t ${cuda_batch_build_target} -c ${CUDA_BATCH_BUILD_LOG} -s "\"%24(VCInstallDir)=$(VCInstallDir)\\\"" -s "%24(ConfigurationName)=$(ConfigurationName)" -s "%24(Configuration)=$(Configuration)" -s "%24(VCToolsVersion)=$(VCToolsVersion)" -s "%24(Platform)=$(Platform)" -s "%24(PlatformTarget)=$(PlatformTarget)" # %24 is the '$' character - needed to escape '$' in VS rule
DEPENDS ${cuda_depends}
)
add_dependencies( ${target} ${cuda_batch_build_target} )
endif()
set( CUDA_BATCH_BUILD_LOG )
set_property( GLOBAL PROPERTY CUDA_BATCH_BUILD_DEPENDS "" )
endfunction()
##############################################################################
###############################################################################
# CUDA BATCH DEPENDS BEGIN
###############################################################################
###############################################################################
function(CUDA_BATCH_DEPENDS_BEGIN)
if(MSVC AND CUDA_ENABLE_BATCHING)
set( CUDA_BATCH_DEPENDS_LOG "${CMAKE_BINARY_DIR}/CMakeFiles/cudaBatchDepends.log" )
file( REMOVE ${CUDA_BATCH_DEPENDS_LOG} )
set( CUDA_BATCH_DEPENDS_LOG "${CUDA_BATCH_DEPENDS_LOG}" PARENT_SCOPE ) # export variable
set(BATCH_CMAKE_SCRIPT "${CMAKE_SOURCE_DIR}/CMake/cuda/FindCUDA/batchCMake.py")
# Create batch file to setup VS environment, since CUDA 8 broke running nvcc outside
# of VS environment. You could get around this with the following command with newer
# versions of cmake (3.5.2 worked for me, but 3.2.1 didn't like the && ):
# execute_process( COMMAND ${CUDA_VC_VARS_ALL_BAT} && ${PYTHON_EXECUTABLE} ... )
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(BUILD_BITS amd64)
else()
set(BUILD_BITS x86)
endif()
file(WRITE ${CUDA_BATCH_DEPENDS_LOG}.vsconfigure.bat
"@echo OFF\n"
"REM Created by FindCUDA.cmake\n"
"@call \"${CUDA_VC_VARS_ALL_BAT}\" ${BUILD_BITS}\n"
"\"${PYTHON_EXECUTABLE}\" \"${BATCH_CMAKE_SCRIPT}\" -e \"${CUDA_BATCH_DEPENDS_LOG}\" -t \"CUDA batch dependencies\""
)
endif()
endfunction()
###############################################################################
###############################################################################
# CUDA BATCH DEPENDS END
###############################################################################
###############################################################################
function(CUDA_BATCH_DEPENDS_END)
if( CUDA_BATCH_DEPENDS_LOG )
if( EXISTS ${CUDA_BATCH_DEPENDS_LOG} )
message(STATUS "CUDA batch dependencies ...")
execute_process(
COMMAND ${CUDA_BATCH_DEPENDS_LOG}.vsconfigure.bat
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE _cuda_batch_depends_output
ERROR_VARIABLE _cuda_batch_depends_output
RESULT_VARIABLE _cuda_batch_depends_result
)
message(STATUS ${_cuda_batch_depends_output})
if( ${_cuda_batch_depends_result} )
message(FATAL_ERROR "Failed")
else()
message(SEND_ERROR "Please reconfigure to ensure that dependencies are incorporated into the build files")
endif()
endif()
endif()
set( CUDA_BATCH_DEPENDS_LOG )
endfunction()
|
arhix52/Strelka/cmake/FindOptiX.cmake | #
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Locate the OptiX distribution. Search relative to the SDK first, then look in the system.
# Our initial guess will be within the SDK.
# set(OptiX_INSTALL_DIR "${CMAKE_SOURCE_DIR}/../" CACHE PATH "Path to OptiX installed location.")
# The distribution contains only 64 bit libraries. Error when we have been mis-configured.
if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
if(WIN32)
message(SEND_ERROR "Make sure when selecting the generator, you select one with Win64 or x64.")
endif()
message(FATAL_ERROR "OptiX only supports builds configured for 64 bits.")
endif()
# search path based on the bit-ness of the build. (i.e. 64: bin64, lib64; 32:
# bin, lib). Note that on Mac, the OptiX library is a universal binary, so we
# only need to look in lib and not lib64 for 64 bit builds.
if(NOT APPLE)
set(bit_dest "64")
else()
set(bit_dest "")
endif()
# Include
find_path(OptiX_INCLUDE
NAMES optix.h
PATHS "${OptiX_INSTALL_DIR}/include"
NO_DEFAULT_PATH
)
find_path(OptiX_INCLUDE
NAMES optix.h
)
# Check to make sure we found what we were looking for
function(OptiX_report_error error_message required component )
if(DEFINED OptiX_FIND_REQUIRED_${component} AND NOT OptiX_FIND_REQUIRED_${component})
set(required FALSE)
endif()
if(OptiX_FIND_REQUIRED AND required)
message(FATAL_ERROR "${error_message} Please locate before proceeding.")
else()
if(NOT OptiX_FIND_QUIETLY)
message(STATUS "${error_message}")
endif(NOT OptiX_FIND_QUIETLY)
endif()
endfunction()
if(NOT OptiX_INCLUDE)
OptiX_report_error("OptiX headers (optix.h and friends) not found." TRUE headers )
endif()
|
arhix52/Strelka/cmake/FindCUDA/select_compute_arch.cmake | # Synopsis:
# CUDA_SELECT_NVCC_ARCH_FLAGS(out_variable [target_CUDA_architectures])
# -- Selects GPU arch flags for nvcc based on target_CUDA_architectures
# target_CUDA_architectures : Auto | Common | All | LIST(ARCH_AND_PTX ...)
# - "Auto" detects local machine GPU compute arch at runtime.
# - "Common" and "All" cover common and entire subsets of architectures
# ARCH_AND_PTX : NAME | NUM.NUM | NUM.NUM(NUM.NUM) | NUM.NUM+PTX
# NAME: Fermi Kepler Maxwell Kepler+Tegra Kepler+Tesla Maxwell+Tegra Pascal
# NUM: Any number. Only those pairs are currently accepted by NVCC though:
# 2.0 2.1 3.0 3.2 3.5 3.7 5.0 5.2 5.3 6.0 6.2
# Returns LIST of flags to be added to CUDA_NVCC_FLAGS in ${out_variable}
# Additionally, sets ${out_variable}_readable to the resulting numeric list
# Example:
# CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS 3.0 3.5+PTX 5.2(5.0) Maxwell)
# LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})
#
# More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA
#
# This list will be used for CUDA_ARCH_NAME = All option
set(CUDA_KNOWN_GPU_ARCHITECTURES "Fermi" "Kepler" "Maxwell")
# This list will be used for CUDA_ARCH_NAME = Common option (enabled by default)
set(CUDA_COMMON_GPU_ARCHITECTURES "3.0" "3.5" "5.0")
if (CUDA_VERSION VERSION_GREATER "6.5")
list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Kepler+Tegra" "Kepler+Tesla" "Maxwell+Tegra")
list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2")
endif ()
if (CUDA_VERSION VERSION_GREATER "7.5")
list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Pascal")
list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.0" "6.1" "6.1+PTX")
else()
list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2+PTX")
endif ()
################################################################################################
# A function for automatic detection of GPUs installed (if autodetection is enabled)
# Usage:
# CUDA_DETECT_INSTALLED_GPUS(OUT_VARIABLE)
#
function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE)
if(NOT CUDA_GPU_DETECT_OUTPUT)
set(cufile ${PROJECT_BINARY_DIR}/detect_cuda_archs.cu)
file(WRITE ${cufile} ""
"#include <cstdio>\n"
"int main()\n"
"{\n"
" int count = 0;\n"
" if (cudaSuccess != cudaGetDeviceCount(&count)) return -1;\n"
" if (count == 0) return -1;\n"
" for (int device = 0; device < count; ++device)\n"
" {\n"
" cudaDeviceProp prop;\n"
" if (cudaSuccess == cudaGetDeviceProperties(&prop, device))\n"
" std::printf(\"%d.%d \", prop.major, prop.minor);\n"
" }\n"
" return 0;\n"
"}\n")
execute_process(COMMAND "${CUDA_NVCC_EXECUTABLE}" "--run" "${cufile}"
WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/CMakeFiles/"
RESULT_VARIABLE nvcc_res OUTPUT_VARIABLE nvcc_out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(nvcc_res EQUAL 0)
string(REPLACE "2.1" "2.1(2.0)" nvcc_out "${nvcc_out}")
set(CUDA_GPU_DETECT_OUTPUT ${nvcc_out} CACHE INTERNAL "Returned GPU architetures from detect_gpus tool" FORCE)
endif()
endif()
if(NOT CUDA_GPU_DETECT_OUTPUT)
message(STATUS "Automatic GPU detection failed. Building for common architectures.")
set(${OUT_VARIABLE} ${CUDA_COMMON_GPU_ARCHITECTURES} PARENT_SCOPE)
else()
set(${OUT_VARIABLE} ${CUDA_GPU_DETECT_OUTPUT} PARENT_SCOPE)
endif()
endfunction()
################################################################################################
# Function for selecting GPU arch flags for nvcc based on CUDA architectures from parameter list
# Usage:
# SELECT_NVCC_ARCH_FLAGS(out_variable [list of CUDA compute archs])
function(CUDA_SELECT_NVCC_ARCH_FLAGS out_variable)
set(CUDA_ARCH_LIST "${ARGN}")
if("X${CUDA_ARCH_LIST}" STREQUAL "X" )
set(CUDA_ARCH_LIST "Auto")
endif()
set(cuda_arch_bin)
set(cuda_arch_ptx)
if("${CUDA_ARCH_LIST}" STREQUAL "All")
set(CUDA_ARCH_LIST ${CUDA_KNOWN_GPU_ARCHITECTURES})
elseif("${CUDA_ARCH_LIST}" STREQUAL "Common")
set(CUDA_ARCH_LIST ${CUDA_COMMON_GPU_ARCHITECTURES})
elseif("${CUDA_ARCH_LIST}" STREQUAL "Auto")
CUDA_DETECT_INSTALLED_GPUS(CUDA_ARCH_LIST)
message(STATUS "Autodetected CUDA architecture(s): ${CUDA_ARCH_LIST}")
endif()
# Now process the list and look for names
string(REGEX REPLACE "[ \t]+" ";" CUDA_ARCH_LIST "${CUDA_ARCH_LIST}")
list(REMOVE_DUPLICATES CUDA_ARCH_LIST)
foreach(arch_name ${CUDA_ARCH_LIST})
set(arch_bin)
set(add_ptx FALSE)
# Check to see if we are compiling PTX
if(arch_name MATCHES "(.*)\\+PTX$")
set(add_ptx TRUE)
set(arch_name ${CMAKE_MATCH_1})
endif()
if(arch_name MATCHES "^([0-9]\\.[0-9](\\([0-9]\\.[0-9]\\))?)$")
set(arch_bin ${CMAKE_MATCH_1})
set(arch_ptx ${arch_bin})
else()
# Look for it in our list of known architectures
if(${arch_name} STREQUAL "Fermi")
set(arch_bin 2.0 "2.1(2.0)")
elseif(${arch_name} STREQUAL "Kepler+Tegra")
set(arch_bin 3.2)
elseif(${arch_name} STREQUAL "Kepler+Tesla")
set(arch_bin 3.7)
elseif(${arch_name} STREQUAL "Kepler")
set(arch_bin 3.0 3.5)
set(arch_ptx 3.5)
elseif(${arch_name} STREQUAL "Maxwell+Tegra")
set(arch_bin 5.3)
elseif(${arch_name} STREQUAL "Maxwell")
set(arch_bin 5.0 5.2)
set(arch_ptx 5.2)
elseif(${arch_name} STREQUAL "Pascal")
set(arch_bin 6.0 6.1)
set(arch_ptx 6.1)
else()
message(SEND_ERROR "Unknown CUDA Architecture Name ${arch_name} in CUDA_SELECT_NVCC_ARCH_FLAGS")
endif()
endif()
if(NOT arch_bin)
message(SEND_ERROR "arch_bin wasn't set for some reason")
endif()
list(APPEND cuda_arch_bin ${arch_bin})
if(add_ptx)
if (NOT arch_ptx)
set(arch_ptx ${arch_bin})
endif()
list(APPEND cuda_arch_ptx ${arch_ptx})
endif()
endforeach()
# remove dots and convert to lists
string(REGEX REPLACE "\\." "" cuda_arch_bin "${cuda_arch_bin}")
string(REGEX REPLACE "\\." "" cuda_arch_ptx "${cuda_arch_ptx}")
string(REGEX MATCHALL "[0-9()]+" cuda_arch_bin "${cuda_arch_bin}")
string(REGEX MATCHALL "[0-9]+" cuda_arch_ptx "${cuda_arch_ptx}")
if(cuda_arch_bin)
list(REMOVE_DUPLICATES cuda_arch_bin)
endif()
if(cuda_arch_ptx)
list(REMOVE_DUPLICATES cuda_arch_ptx)
endif()
set(nvcc_flags "")
set(nvcc_archs_readable "")
# Tell NVCC to add binaries for the specified GPUs
foreach(arch ${cuda_arch_bin})
if(arch MATCHES "([0-9]+)\\(([0-9]+)\\)")
# User explicitly specified ARCH for the concrete CODE
list(APPEND nvcc_flags -gencode arch=compute_${CMAKE_MATCH_2},code=sm_${CMAKE_MATCH_1})
list(APPEND nvcc_archs_readable sm_${CMAKE_MATCH_1})
else()
# User didn't explicitly specify ARCH for the concrete CODE, we assume ARCH=CODE
list(APPEND nvcc_flags -gencode arch=compute_${arch},code=sm_${arch})
list(APPEND nvcc_archs_readable sm_${arch})
endif()
endforeach()
# Tell NVCC to add PTX intermediate code for the specified architectures
foreach(arch ${cuda_arch_ptx})
list(APPEND nvcc_flags -gencode arch=compute_${arch},code=compute_${arch})
list(APPEND nvcc_archs_readable compute_${arch})
endforeach()
string(REPLACE ";" " " nvcc_archs_readable "${nvcc_archs_readable}")
set(${out_variable} ${nvcc_flags} PARENT_SCOPE)
set(${out_variable}_readable ${nvcc_archs_readable} PARENT_SCOPE)
endfunction()
|
arhix52/Strelka/cmake/FindCUDA/run_nvcc.cmake | # James Bigler, NVIDIA Corp (nvidia.com - jbigler)
#
# Copyright (c) 2008 - 2021 NVIDIA Corporation. All rights reserved.
#
# This code is licensed under the MIT License. See the FindCUDA.cmake script
# for the text of the license.
# The MIT License
#
# License for the specific language governing rights and limitations under
# 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.
##########################################################################
# This file runs the nvcc commands to produce the desired output file along with
# the dependency file needed by CMake to compute dependencies. In addition the
# file checks the output of each command and if the command fails it deletes the
# output files.
# Input variables
#
# verbose:BOOL=<> OFF: Be as quiet as possible (default)
# ON : Describe each step
#
# build_configuration:STRING=<> Typically one of Debug, MinSizeRel, Release, or
# RelWithDebInfo, but it should match one of the
# entries in CUDA_HOST_FLAGS. This is the build
# configuration used when compiling the code. If
# blank or unspecified Debug is assumed as this is
# what CMake does.
#
# generated_file:STRING=<> File to generate. This argument must be passed in.
#
# generated_cubin_file:STRING=<> File to generate. This argument must be passed
# in if build_cubin is true.
# generate_dependency_only:BOOL=<> Only generate the dependency file.
#
# check_dependencies:BOOL=<> Check the dependencies. If everything is up to
# date, simply touch the output file instead of
# generating it.
# Support IN_LIST
cmake_policy(SET CMP0057 NEW)
if(NOT generated_file)
message(FATAL_ERROR "You must specify generated_file on the command line")
endif()
# Set these up as variables to make reading the generated file easier
set(CMAKE_COMMAND "@CMAKE_COMMAND@") # path
set(source_file "@source_file@") # path
set(NVCC_generated_dependency_file "@NVCC_generated_dependency_file@") # path
set(cmake_dependency_file "@cmake_dependency_file@") # path
set(CUDA_make2cmake "@CUDA_make2cmake@") # path
set(CUDA_parse_cubin "@CUDA_parse_cubin@") # path
set(build_cubin @build_cubin@) # bool
set(CUDA_HOST_COMPILER "@CUDA_HOST_COMPILER@") # path
# We won't actually use these variables for now, but we need to set this, in
# order to force this file to be run again if it changes.
set(generated_file_path "@generated_file_path@") # path
set(generated_file_internal "@generated_file@") # path
set(generated_cubin_file_internal "@generated_cubin_file@") # path
set(CUDA_REMOVE_GLOBAL_MEMORY_SPACE_WARNING @CUDA_REMOVE_GLOBAL_MEMORY_SPACE_WARNING@)
set(CUDA_NVCC_EXECUTABLE "@CUDA_NVCC_EXECUTABLE@") # path
set(CUDA_NVCC_FLAGS @CUDA_NVCC_FLAGS@ ;; @CUDA_WRAP_OPTION_NVCC_FLAGS@) # list
@CUDA_NVCC_FLAGS_CONFIG@
set(nvcc_flags @nvcc_flags@) # list
set(CUDA_NVCC_INCLUDE_ARGS "@CUDA_NVCC_INCLUDE_ARGS@") # list (needs to be in quotes to handle spaces properly).
set(format_flag "@format_flag@") # string
set(cuda_language_flag @cuda_language_flag@) # list
if(build_cubin AND NOT generated_cubin_file)
message(FATAL_ERROR "You must specify generated_cubin_file on the command line")
endif()
# This is the list of host compilation flags. It C or CXX should already have
# been chosen by FindCUDA.cmake.
@CUDA_HOST_FLAGS@
# Take the compiler flags and package them up to be sent to the compiler via -Xcompiler
set(nvcc_host_compiler_flags "")
# If we weren't given a build_configuration, use Debug.
if(NOT build_configuration)
set(build_configuration Debug)
endif()
string(TOUPPER "${build_configuration}" build_configuration)
#message("CUDA_NVCC_HOST_COMPILER_FLAGS = ${CUDA_NVCC_HOST_COMPILER_FLAGS}")
foreach(flag ${CMAKE_HOST_FLAGS} ${CMAKE_HOST_FLAGS_${build_configuration}})
# Extra quotes are added around each flag to help nvcc parse out flags with spaces.
if ("${nvcc_host_compiler_flags}" STREQUAL "")
set(nvcc_host_compiler_flags "\"${flag}\"")
else()
set(nvcc_host_compiler_flags "${nvcc_host_compiler_flags},\"${flag}\"")
endif()
endforeach()
if (nvcc_host_compiler_flags)
set(nvcc_host_compiler_flags "-Xcompiler" ${nvcc_host_compiler_flags})
endif()
#message("nvcc_host_compiler_flags = \"${nvcc_host_compiler_flags}\"")
set(depends_nvcc_host_compiler_flags "")
foreach(flag ${CMAKE_HOST_FLAGS} )
# Extra quotes are added around each flag to help nvcc parse out flags with spaces.
if ("${depends_nvcc_host_compiler_flags}" STREQUAL "")
set(depends_nvcc_host_compiler_flags "\"${flag}\"")
else()
set(depends_nvcc_host_compiler_flags "${depends_nvcc_host_compiler_flags},\"${flag}\"")
endif()
endforeach()
if (depends_nvcc_host_compiler_flags)
set(depends_nvcc_host_compiler_flags "-Xcompiler" ${depends_nvcc_host_compiler_flags})
endif()
list(APPEND depends_CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS})
# Add the build specific configuration flags
list(APPEND CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS_${build_configuration}})
# Any -ccbin existing in CUDA_NVCC_FLAGS gets highest priority
list( FIND CUDA_NVCC_FLAGS "-ccbin" ccbin_found0 )
list( FIND CUDA_NVCC_FLAGS "--compiler-bindir" ccbin_found1 )
if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 AND CUDA_HOST_COMPILER )
if (CUDA_HOST_COMPILER STREQUAL "@_CUDA_MSVC_HOST_COMPILER@" AND DEFINED CCBIN)
set(CCBIN -ccbin "${CCBIN}")
else()
set(CCBIN -ccbin "${CUDA_HOST_COMPILER}")
endif()
endif()
# cuda_execute_process - Executes a command with optional command echo and status message.
#
# status - Status message to print if verbose is true
# command - COMMAND argument from the usual execute_process argument structure
# ARGN - Remaining arguments are the command with arguments
#
# CUDA_result - return value from running the command
#
# Make this a macro instead of a function, so that things like RESULT_VARIABLE
# and other return variables are present after executing the process.
function(cuda_execute_process status command)
set(_command ${command})
if(NOT "x${_command}" STREQUAL "xCOMMAND")
message(FATAL_ERROR "Malformed call to cuda_execute_process. Missing COMMAND as second argument. (command = ${command})")
endif()
# nvcc warns when specifying -G and --lineinfo, which is annoying.
if("-G" IN_LIST ARGN)
list(REMOVE_ITEM ARGN "-lineinfo")
list(REMOVE_ITEM ARGN "--lineinfo")
endif()
if(verbose)
execute_process(COMMAND "${CMAKE_COMMAND}" -E echo -- ${status})
# Now we need to build up our command string. We are accounting for quotes
# and spaces, anything else is left up to the user to fix if they want to
# copy and paste a runnable command line.
set(cuda_execute_process_string)
foreach(arg ${ARGN})
# If there are quotes, excape them, so they come through.
string(REPLACE "\"" "\\\"" arg ${arg})
# Args with spaces need quotes around them to get them to be parsed as a single argument.
if(arg MATCHES " ")
list(APPEND cuda_execute_process_string "\"${arg}\"")
else()
list(APPEND cuda_execute_process_string ${arg})
endif()
endforeach()
# Echo the command
execute_process(COMMAND ${CMAKE_COMMAND} -E echo ${cuda_execute_process_string})
endif()
# Run the command
execute_process(COMMAND ${ARGN} RESULT_VARIABLE CUDA_result )
endfunction()
# For CUDA 2.3 and below, -G -M doesn't work, so remove the -G flag
# for dependency generation and hope for the best.
set(CUDA_VERSION @CUDA_VERSION@)
if(CUDA_VERSION VERSION_LESS "3.0")
cmake_policy(PUSH)
# CMake policy 0007 NEW states that empty list elements are not
# ignored. I'm just setting it to avoid the warning that's printed.
cmake_policy(SET CMP0007 NEW)
# Note that this will remove all occurances of -G.
list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "-G")
cmake_policy(POP)
endif()
# If we need to create relocatible code, the dependency phase doesn't like this argument.
# We need to filter it out here.
list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "-dc")
list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "--device-c")
# nvcc doesn't define __CUDACC__ for some reason when generating dependency files. This
# can cause incorrect dependencies when #including files based on this macro which is
# defined in the generating passes of nvcc invokation. We will go ahead and manually
# define this for now until a future version fixes this bug.
set(CUDACC_DEFINE -D__CUDACC__)
if (check_dependencies)
set(rebuild FALSE)
include(${cmake_dependency_file})
if(NOT CUDA_NVCC_DEPEND)
# CUDA_NVCC_DEPEND should have something useful in it by now. If not we
# should force the rebuild.
if (verbose)
message(WARNING "CUDA_NVCC_DEPEND not found for ${generated_file}")
endif()
set(rebuild TRUE)
endif()
# Rebuilding is also dependent on this file changing.
list(APPEND CUDA_NVCC_DEPEND "${CMAKE_CURRENT_LIST_FILE}")
foreach(f ${CUDA_NVCC_DEPEND})
# True if file1 is newer than file2 or if one of the two files doesn't
# exist. Behavior is well-defined only for full paths. If the file time
# stamps are exactly the same, an IS_NEWER_THAN comparison returns true, so
# that any dependent build operations will occur in the event of a tie. This
# includes the case of passing the same file name for both file1 and file2.
if("${f}" IS_NEWER_THAN "${generated_file}")
#message("file ${f} is newer than ${generated_file}")
set(rebuild TRUE)
endif()
endforeach()
if (NOT rebuild)
#message("Not rebuilding ${generated_file}")
cuda_execute_process(
"Dependencies up to date. Not rebuilding ${generated_file}"
COMMAND "${CMAKE_COMMAND}" -E touch "${generated_file}"
)
return()
endif()
endif()
# Generate the dependency file
cuda_execute_process(
"Generating dependency file: ${NVCC_generated_dependency_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
-M
${CUDACC_DEFINE}
"${source_file}"
-o "${NVCC_generated_dependency_file}"
${CCBIN}
${nvcc_flags}
${depends_nvcc_host_compiler_flags}
${depends_CUDA_NVCC_FLAGS}
-DNVCC
${CUDA_NVCC_INCLUDE_ARGS}
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Generate the cmake readable dependency file to a temp file. Don't put the
# quotes just around the filenames for the input_file and output_file variables.
# CMake will pass the quotes through and not be able to find the file.
cuda_execute_process(
"Generating temporary cmake readable file: ${cmake_dependency_file}.tmp"
COMMAND "${CMAKE_COMMAND}"
-D "input_file:FILEPATH=${NVCC_generated_dependency_file}"
-D "output_file:FILEPATH=${cmake_dependency_file}.tmp"
-P "${CUDA_make2cmake}"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Copy the file if it is different
cuda_execute_process(
"Copy if different ${cmake_dependency_file}.tmp to ${cmake_dependency_file}"
COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${cmake_dependency_file}.tmp" "${cmake_dependency_file}"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Delete the temporary file
cuda_execute_process(
"Removing ${cmake_dependency_file}.tmp"
COMMAND "${CMAKE_COMMAND}" -E remove "${cmake_dependency_file}.tmp"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
if (generate_dependency_only)
return()
endif()
if(CUDA_REMOVE_GLOBAL_MEMORY_SPACE_WARNING)
set(get_error ERROR_VARIABLE stderr)
endif()
# Delete the target file
cuda_execute_process(
"Removing ${generated_file}"
COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}"
)
# Generate the code
cuda_execute_process(
"Generating ${generated_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
"${source_file}"
${cuda_language_flag}
${format_flag} -o "${generated_file}"
${CCBIN}
${nvcc_flags}
${nvcc_host_compiler_flags}
${CUDA_NVCC_FLAGS}
-DNVCC
${CUDA_NVCC_INCLUDE_ARGS}
${get_error}
)
if(get_error)
if(stderr)
# Filter out the annoying Advisory about pointer stuff.
# Advisory: Cannot tell what pointer points to, assuming global memory space
string(REGEX REPLACE "(^|\n)[^\n]*\(Advisory|Warning\): Cannot tell what pointer points to, assuming global memory space\n\n" "\\1" stderr "${stderr}")
# Filter out warning we do not care about
string(REGEX REPLACE "(^|\n)[^\n]*: Warning: Function [^\n]* has a large return size, so overriding noinline attribute. The function may be inlined when called.\n\n" "\\1" stderr "${stderr}")
# To be investigated (OP-1999)
string(REGEX REPLACE "(^|\n)[^\n]*: warning: function [^\n]*\n[^\n]*: here was declared deprecated \(.[^\n]* is not valid on compute_70 and above, and should be replaced with [^\n]*.To continue using [^\n]*, specify virtual architecture compute_60 when targeting sm_70 and above, for example, using the pair of compiler options.[^\n]*..\)\n( *detected during instantiation of [^\n]*\n[^\n]*: here\n)?( *detected during:\n( *instantiation of [^\n]*\n[^\n]*: here\n([^\n]*instantiation contexts not shown[^\n]*\n)?)+)?\n" "\\1" stderr "${stderr}")
string(REGEX REPLACE "(^|\n)[^\n]*: warning: function [^\n]*\n[^\n]*: here was declared deprecated \(.[^\n]* is deprecated in favor of [^\n]* and may be removed in a future release [^\n]*\)\n( *detected during instantiation of [^\n]*\n[^\n]*: here\n)?( *detected during:\n( *instantiation of [^\n]*\n[^\n]*: here\n([^\n]*instantiation contexts not shown[^\n]*\n)?)+)?\n" "\\1" stderr "${stderr}")
# If there is error output, there is usually a stray newline at the end. Eliminate it if it is the only content of ${stderr}.
string(REGEX REPLACE "^\n$" "" stderr "${stderr}")
if(stderr)
message("${stderr}")
endif()
endif()
endif()
if(CUDA_result)
# Since nvcc can sometimes leave half done files make sure that we delete the output file.
cuda_execute_process(
"Removing ${generated_file}"
COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}"
)
message(FATAL_ERROR "Error generating file ${generated_file}")
else()
if(verbose)
message("Generated ${generated_file} successfully.")
endif()
endif()
# Cubin resource report commands.
if( build_cubin )
# Run with -cubin to produce resource usage report.
cuda_execute_process(
"Generating ${generated_cubin_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
"${source_file}"
${CUDA_NVCC_FLAGS}
${nvcc_flags}
${CCBIN}
${nvcc_host_compiler_flags}
-DNVCC
-cubin
-o "${generated_cubin_file}"
${CUDA_NVCC_INCLUDE_ARGS}
)
# Execute the parser script.
cuda_execute_process(
"Executing the parser script"
COMMAND "${CMAKE_COMMAND}"
-D "input_file:STRING=${generated_cubin_file}"
-P "${CUDA_parse_cubin}"
)
endif()
|
arhix52/Strelka/cmake/FindCUDA/parse_cubin.cmake | # James Bigler, NVIDIA Corp (nvidia.com - jbigler)
# Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
#
# Copyright (c) 2008 - 2021 NVIDIA Corporation. All rights reserved.
#
# Copyright (c) 2007-2009
# Scientific Computing and Imaging Institute, University of Utah
#
# This code is licensed under the MIT License. See the FindCUDA.cmake script
# for the text of the license.
# The MIT License
#
# License for the specific language governing rights and limitations under
# 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.
#
#######################################################################
# Parses a .cubin file produced by nvcc and reports statistics about the file.
file(READ ${input_file} file_text)
if (NOT "${file_text}" STREQUAL "")
string(REPLACE ";" "\\;" file_text ${file_text})
string(REPLACE "\ncode" ";code" file_text ${file_text})
list(LENGTH file_text len)
foreach(line ${file_text})
# Only look at "code { }" blocks.
if(line MATCHES "^code")
# Break into individual lines.
string(REGEX REPLACE "\n" ";" line ${line})
foreach(entry ${line})
# Extract kernel names.
if (${entry} MATCHES "[^g]name = ([^ ]+)")
set(entry "${CMAKE_MATCH_1}")
# Check to see if the kernel name starts with "_"
set(skip FALSE)
# if (${entry} MATCHES "^_")
# Skip the rest of this block.
# message("Skipping ${entry}")
# set(skip TRUE)
# else ()
message("Kernel: ${entry}")
# endif ()
endif()
# Skip the rest of the block if necessary
if(NOT skip)
# Registers
if (${entry} MATCHES "reg([ ]+)=([ ]+)([^ ]+)")
set(entry "${CMAKE_MATCH_3}")
message("Registers: ${entry}")
endif()
# Local memory
if (${entry} MATCHES "lmem([ ]+)=([ ]+)([^ ]+)")
set(entry "${CMAKE_MATCH_3}")
message("Local: ${entry}")
endif()
# Shared memory
if (${entry} MATCHES "smem([ ]+)=([ ]+)([^ ]+)")
set(entry "${CMAKE_MATCH_3}")
message("Shared: ${entry}")
endif()
if (${entry} MATCHES "^}")
message("")
endif()
endif()
endforeach()
endif()
endforeach()
else()
# message("FOUND NO DEPENDS")
endif()
|
arhix52/Strelka/cmake/FindCUDA/make2cmake.cmake | # James Bigler, NVIDIA Corp (nvidia.com - jbigler)
# Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
#
# Copyright (c) 2008 - 2021 NVIDIA Corporation. All rights reserved.
#
# Copyright (c) 2007-2009
# Scientific Computing and Imaging Institute, University of Utah
#
# This code is licensed under the MIT License. See the FindCUDA.cmake script
# for the text of the license.
# The MIT License
#
# License for the specific language governing rights and limitations under
# 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.
#
#######################################################################
# This converts a file written in makefile syntax into one that can be included
# by CMake.
# Input variables
#
# verbose:BOOL=<> OFF: Be as quiet as possible (default)
# ON : Extra output
#
# input_file:FILEPATH=<> Path to dependecy file in makefile format
#
# output_file:FILEPATH=<> Path to file with dependencies in CMake readable variable
#
file(READ ${input_file} depend_text)
if (NOT "${depend_text}" STREQUAL "")
# message("FOUND DEPENDS")
string(REPLACE "\\ " " " depend_text ${depend_text})
# This works for the nvcc -M generated dependency files.
string(REGEX REPLACE "^.* : " "" depend_text ${depend_text})
string(REGEX REPLACE "[ \\\\]*\n" ";" depend_text ${depend_text})
set(dependency_list "")
foreach(file ${depend_text})
string(REGEX REPLACE "^ +" "" file ${file})
# OK, now if we had a UNC path, nvcc has a tendency to only output the first '/'
# instead of '//'. Here we will test to see if the file exists, if it doesn't then
# try to prepend another '/' to the path and test again. If it still fails remove the
# path.
if(NOT EXISTS "${file}")
if (EXISTS "/${file}")
set(file "/${file}")
else()
if(verbose)
message(WARNING " Removing non-existent dependency file: ${file}")
endif()
set(file "")
endif()
endif()
# Make sure we check to see if we have a file, before asking if it is not a directory.
# if(NOT IS_DIRECTORY "") will return TRUE.
if(file AND NOT IS_DIRECTORY "${file}")
# If softlinks start to matter, we should change this to REALPATH. For now we need
# to flatten paths, because nvcc can generate stuff like /bin/../include instead of
# just /include.
get_filename_component(file_absolute "${file}" ABSOLUTE)
list(APPEND dependency_list "${file_absolute}")
endif()
endforeach()
else()
# message("FOUND NO DEPENDS")
endif()
# Remove the duplicate entries and sort them.
list(REMOVE_DUPLICATES dependency_list)
list(SORT dependency_list)
foreach(file ${dependency_list})
set(cuda_nvcc_depend "${cuda_nvcc_depend} \"${file}\"\n")
endforeach()
file(WRITE ${output_file} "# Generated by: make2cmake.cmake\nSET(CUDA_NVCC_DEPEND\n ${cuda_nvcc_depend})\n\n")
|
arhix52/Strelka/include/HdStrelka/RendererPlugin.h | #pragma once
#include <pxr/imaging/hd/rendererPlugin.h>
#include <memory>
#include <log/logmanager.h>
#include "MaterialNetworkTranslator.h"
PXR_NAMESPACE_OPEN_SCOPE
class HdStrelkaRendererPlugin final : public HdRendererPlugin
{
public:
HdStrelkaRendererPlugin();
~HdStrelkaRendererPlugin() override;
public:
HdRenderDelegate* CreateRenderDelegate() override;
HdRenderDelegate* CreateRenderDelegate(const HdRenderSettingsMap& settingsMap) override;
void DeleteRenderDelegate(HdRenderDelegate* renderDelegate) override;
bool IsSupported(bool gpuEnabled = true) const override;
private:
oka::Logmanager mLoggerManager;
std::unique_ptr<MaterialNetworkTranslator> m_translator;
bool m_isSupported;
};
PXR_NAMESPACE_CLOSE_SCOPE
|
arhix52/Strelka/include/materialmanager/mdlLogger.h | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <mi/base/interface_implement.h>
#include <mi/base/ilogger.h>
#include <mi/neuraylib/imdl_execution_context.h>
namespace oka
{
class MdlLogger : public mi::base::Interface_implement<mi::base::ILogger>
{
public:
void message(mi::base::Message_severity level,
const char* moduleCategory,
const mi::base::Message_details& details,
const char* message) override;
void message(mi::base::Message_severity level,
const char* moduleCategory,
const char* message) override;
void message(mi::base::Message_severity level,
const char* message);
void flushContextMessages(mi::neuraylib::IMdl_execution_context* context);
};
}
|
arhix52/Strelka/include/materialmanager/materialmanager.h | #pragma once
#include <memory>
#include <stdint.h>
#include <string>
#include <vector>
namespace oka
{
class MaterialManager
{
class Context;
std::unique_ptr<Context> mContext;
public:
struct Module;
struct MaterialInstance;
struct CompiledMaterial;
struct TargetCode;
struct TextureDescription;
bool addMdlSearchPath(const char* paths[], uint32_t numPaths);
Module* createModule(const char* file);
Module* createMtlxModule(const char* file);
void destroyModule(Module* module);
MaterialInstance* createMaterialInstance(Module* module, const char* materialName);
void destroyMaterialInstance(MaterialInstance* material);
struct Param
{
enum class Type : uint32_t
{
eFloat = 0,
eInt,
eBool,
eFloat2,
eFloat3,
eFloat4,
eTexture
};
Type type;
std::string name;
std::vector<uint8_t> value;
};
void dumpParams(const TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material);
bool setParam(TargetCode* targetCode, uint32_t materialIdx, CompiledMaterial* material, const Param& param);
TextureDescription* createTextureDescription(const char* name, const char* gamma);
const char* getTextureDbName(TextureDescription* texDesc);
CompiledMaterial* compileMaterial(MaterialInstance* matInstance);
void destroyCompiledMaterial(CompiledMaterial* compMaterial);
const char* getName(CompiledMaterial* compMaterial);
TargetCode* generateTargetCode(CompiledMaterial** materials, const uint32_t numMaterials);
const char* getShaderCode(const TargetCode* targetCode, uint32_t materialId);
uint32_t getReadOnlyBlockSize(const TargetCode* targetCode);
const uint8_t* getReadOnlyBlockData(const TargetCode* targetCode);
uint32_t getArgBufferSize(const TargetCode* targetCode);
const uint8_t* getArgBufferData(const TargetCode* targetCode);
uint32_t getResourceInfoSize(const TargetCode* targetCode);
const uint8_t* getResourceInfoData(const TargetCode* targetCode);
int registerResource(TargetCode* targetCode, int index);
uint32_t getMdlMaterialSize(const TargetCode* targetCode);
const uint8_t* getMdlMaterialData(const TargetCode* targetCode);
uint32_t getArgBlockOffset(const TargetCode* targetCode, uint32_t materialId);
uint32_t getReadOnlyOffset(const TargetCode* targetCode, uint32_t materialId);
uint32_t getTextureCount(const TargetCode* targetCode, uint32_t materialId);
const char* getTextureName(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
const float* getTextureData(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
const char* getTextureType(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
uint32_t getTextureWidth(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
uint32_t getTextureHeight(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
uint32_t getTextureBytesPerTexel(const TargetCode* targetCode, uint32_t materialId, uint32_t index);
MaterialManager();
~MaterialManager();
};
} // namespace oka
|
arhix52/Strelka/include/materialmanager/mdlPtxCodeGen.h | #pragma once
#include "mdlLogger.h"
#include "mdlRuntime.h"
#include <MaterialXCore/Document.h>
#include <MaterialXFormat/File.h>
#include <MaterialXGenShader/ShaderGenerator.h>
#include <mi/mdl_sdk.h>
namespace oka
{
class MdlPtxCodeGen
{
public:
explicit MdlPtxCodeGen(){};
bool init(MdlRuntime& runtime);
struct InternalMaterialInfo
{
mi::Size argument_block_index;
};
bool setOptionBinary(const char* name, const char* data, size_t size);
mi::base::Handle<const mi::neuraylib::ITarget_code> translate(
const mi::neuraylib::ICompiled_material* material,
std::string& ptxSrc,
InternalMaterialInfo& internalsInfo);
mi::base::Handle<const mi::neuraylib::ITarget_code> translate(
const std::vector<const mi::neuraylib::ICompiled_material*>& materials,
std::string& ptxSrc,
std::vector<InternalMaterialInfo>& internalsInfo);
private:
bool appendMaterialToLinkUnit(uint32_t idx,
const mi::neuraylib::ICompiled_material* compiledMaterial,
mi::neuraylib::ILink_unit* linkUnit,
mi::Size& argBlockIndex);
std::unique_ptr<MdlNeurayLoader> mLoader;
mi::base::Handle<MdlLogger> mLogger;
mi::base::Handle<mi::neuraylib::IMdl_backend> mBackend;
mi::base::Handle<mi::neuraylib::IDatabase> mDatabase;
mi::base::Handle<mi::neuraylib::ITransaction> mTransaction;
mi::base::Handle<mi::neuraylib::IMdl_execution_context> mContext;
};
} // namespace oka
|
arhix52/Strelka/include/materialmanager/mdlNeurayLoader.h | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <mi/base/handle.h>
#include <mi/neuraylib/ineuray.h>
namespace oka
{
class MdlNeurayLoader
{
public:
MdlNeurayLoader();
~MdlNeurayLoader();
public:
bool init(const char* resourcePath, const char* imagePluginPath);
mi::base::Handle<mi::neuraylib::INeuray> getNeuray() const;
private:
bool loadDso(const char* resourcePath);
bool loadNeuray();
bool loadPlugin(const char* imagePluginPath);
void unloadDso();
private:
void* mDsoHandle;
mi::base::Handle<mi::neuraylib::INeuray> mNeuray;
};
}
|
arhix52/Strelka/include/materialmanager/mdlMaterialCompiler.h | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <string>
#include <mi/base/handle.h>
#include <mi/neuraylib/icompiled_material.h>
#include <mi/neuraylib/idatabase.h>
#include <mi/neuraylib/itransaction.h>
#include <mi/neuraylib/imaterial_instance.h>
#include <mi/neuraylib/imdl_impexp_api.h>
#include <mi/neuraylib/imdl_execution_context.h>
#include <mi/neuraylib/imdl_factory.h>
#include "mdlRuntime.h"
namespace oka
{
class MdlMaterialCompiler
{
public:
MdlMaterialCompiler(MdlRuntime& runtime);
public:
bool createModule(const std::string& identifier,
std::string& moduleName);
bool createMaterialInstace(const char* moduleName, const char* identifier,
mi::base::Handle<mi::neuraylib::IFunction_call>& matInstance);
bool compileMaterial(mi::base::Handle<mi::neuraylib::IFunction_call>& instance,
mi::base::Handle<mi::neuraylib::ICompiled_material>& compiledMaterial);
mi::base::Handle<mi::neuraylib::IMdl_factory>& getFactory();
mi::base::Handle<mi::neuraylib::ITransaction>& getTransaction();
private:
mi::base::Handle<MdlLogger> mLogger;
mi::base::Handle<mi::neuraylib::IDatabase> mDatabase;
mi::base::Handle<mi::neuraylib::ITransaction> mTransaction;
mi::base::Handle<mi::neuraylib::IMdl_factory> mFactory;
mi::base::Handle<mi::neuraylib::IMdl_impexp_api> mImpExpApi;
};
}
|
arhix52/Strelka/include/materialmanager/mdlRuntime.h | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include "mdlLogger.h"
#include "mdlNeurayLoader.h"
#include <mi/base/handle.h>
#include <mi/neuraylib/idatabase.h>
#include <mi/neuraylib/itransaction.h>
#include <mi/neuraylib/imdl_backend_api.h>
#include <mi/neuraylib/imdl_impexp_api.h>
#include <mi/neuraylib/imdl_factory.h>
#include <mi/mdl_sdk.h>
#include <memory>
#include <vector>
namespace oka
{
class MdlRuntime
{
public:
MdlRuntime();
~MdlRuntime();
public:
bool init(const char* paths[], uint32_t numPaths, const char* neurayPath, const char* imagePluginPath);
mi::base::Handle<MdlLogger> getLogger();
mi::base::Handle<mi::neuraylib::IDatabase> getDatabase();
mi::base::Handle<mi::neuraylib::ITransaction> getTransaction();
mi::base::Handle<mi::neuraylib::IMdl_factory> getFactory();
mi::base::Handle<mi::neuraylib::IMdl_impexp_api> getImpExpApi();
mi::base::Handle<mi::neuraylib::IMdl_backend_api> getBackendApi();
mi::base::Handle<mi::neuraylib::INeuray> getNeuray();
mi::base::Handle<mi::neuraylib::IMdl_configuration> getConfig();
std::unique_ptr<MdlNeurayLoader> mLoader;
private:
mi::base::Handle<MdlLogger> mLogger;
mi::base::Handle<mi::neuraylib::IDatabase> mDatabase;
mi::base::Handle<mi::neuraylib::ITransaction> mTransaction;
mi::base::Handle<mi::neuraylib::IMdl_factory> mFactory;
mi::base::Handle<mi::neuraylib::IMdl_backend_api> mBackendApi;
mi::base::Handle<mi::neuraylib::IMdl_impexp_api> mImpExpApi;
mi::base::Handle<mi::neuraylib::IMdl_configuration> mConfig;
};
} // namespace oka
|
arhix52/Strelka/include/materialmanager/mtlxMdlCodeGen.h | // Copyright (C) 2021 Pablo Delgado Krämer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <stdint.h>
#include <string>
#include <MaterialXCore/Document.h>
#include <MaterialXFormat/File.h>
#include <MaterialXGenShader/ShaderGenerator.h>
#include "mdlRuntime.h"
namespace oka
{
class MtlxMdlCodeGen
{
public:
explicit MtlxMdlCodeGen(const char* mtlxlibPath, MdlRuntime* mdlRuntime);
public:
bool translate(const char* mtlxSrc, std::string& mdlSrc, std::string& subIdentifier);
private:
const MaterialX::FileSearchPath mMtlxlibPath;
MaterialX::DocumentPtr mStdLib;
MaterialX::ShaderGeneratorPtr mShaderGen;
MdlRuntime* mMdlRuntime;
};
}
|
arhix52/Strelka/include/render/buffer.h | #pragma once
#include "common.h"
#include <stdint.h>
#include <vector>
namespace oka
{
enum class BufferFormat : char
{
UNSIGNED_BYTE4,
FLOAT4,
FLOAT3
};
struct BufferDesc
{
uint32_t width;
uint32_t height;
BufferFormat format;
};
class Buffer
{
public:
virtual ~Buffer() = default;
virtual void resize(uint32_t width, uint32_t height) = 0;
virtual void* map() = 0;
virtual void unmap() = 0;
uint32_t width() const
{
return mWidth;
}
uint32_t height() const
{
return mHeight;
}
// Get output buffer
virtual void* getHostPointer()
{
return mHostData.data();
}
virtual size_t getHostDataSize()
{
return mHostData.size();
}
static size_t getElementSize(BufferFormat format)
{
switch (format)
{
case BufferFormat::FLOAT4:
return 4 * sizeof(float);
break;
case BufferFormat::FLOAT3:
return 3 * sizeof(float);
break;
case BufferFormat::UNSIGNED_BYTE4:
return 4 * sizeof(char);
break;
default:
break;
}
assert(0);
return 0;
}
size_t getElementSize() const
{
return Buffer::getElementSize(mFormat);
}
BufferFormat getFormat() const
{
return mFormat;
}
protected:
uint32_t mWidth = 0u;
uint32_t mHeight = 0u;
BufferFormat mFormat;
std::vector<char> mHostData;
};
struct ImageBuffer
{
void* data = nullptr;
size_t dataSize = 0;
unsigned int width = 0;
unsigned int height = 0;
BufferFormat pixel_format;
};
} // namespace oka
|
arhix52/Strelka/include/render/Lights.h | #pragma once
#include <vector_types.h>
#include <sutil/vec_math.h>
struct UniformLight
{
float4 points[4];
float4 color;
float4 normal;
int type;
float halfAngle;
float pad0;
float pad1;
};
struct LightSampleData
{
float3 pointOnLight;
float pdf;
float3 normal;
float area;
float3 L;
float distToLight;
};
__forceinline__ __device__ float misWeightBalance(const float a, const float b)
{
return 1.0f / ( 1.0f + (b / a) );
}
static __inline__ __device__ float calcLightArea(const UniformLight& l)
{
float area = 0.0f;
if (l.type == 0) // rectangle area
{
float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]);
float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]);
area = length(cross(e1, e2));
}
else if (l.type == 1) // disc area
{
area = M_PIf * l.points[0].x * l.points[0].x; // pi * radius^2
}
else if (l.type == 2) // sphere area
{
area = 4.0f * M_PIf * l.points[0].x * l.points[0].x; // 4 * pi * radius^2
}
return area;
}
static __inline__ __device__ float3 calcLightNormal(const UniformLight& l, const float3 hitPoint)
{
float3 norm = make_float3(0.0f);
if (l.type == 0)
{
float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]);
float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]);
norm = -normalize(cross(e1, e2));
}
else if (l.type == 1)
{
norm = make_float3(l.normal);
}
else if (l.type == 2)
{
norm = normalize(hitPoint - make_float3(l.points[1]));
}
return norm;
}
static __inline__ __device__ void fillLightData(const UniformLight& l, const float3 hitPoint, LightSampleData& lightSampleData)
{
lightSampleData.area = calcLightArea(l);
lightSampleData.normal = calcLightNormal(l, hitPoint);
const float3 toLight = lightSampleData.pointOnLight - hitPoint;
const float lenToLight = length(toLight);
lightSampleData.L = toLight / lenToLight;
lightSampleData.distToLight = lenToLight;
}
struct SphQuad
{
float3 o, x, y, z;
float z0, z0sq;
float x0, y0, y0sq; // rectangle coords in ’R’
float x1, y1, y1sq;
float b0, b1, b0sq, k;
float S;
};
// Precomputation of constants for the spherical rectangle Q.
static __device__ SphQuad init(const UniformLight& l, const float3 o)
{
SphQuad squad;
float3 ex = make_float3(l.points[1]) - make_float3(l.points[0]);
float3 ey = make_float3(l.points[3]) - make_float3(l.points[0]);
float3 s = make_float3(l.points[0]);
float exl = length(ex);
float eyl = length(ey);
squad.o = o;
squad.x = ex / exl;
squad.y = ey / eyl;
squad.z = cross(squad.x, squad.y);
// compute rectangle coords in local reference system
float3 d = s - o;
squad.z0 = dot(d, squad.z);
// flip ’z’ to make it point against ’Q’
if (squad.z0 > 0)
{
squad.z *= -1;
squad.z0 *= -1;
}
squad.z0sq = squad.z0 * squad.z0;
squad.x0 = dot(d, squad.x);
squad.y0 = dot(d, squad.y);
squad.x1 = squad.x0 + exl;
squad.y1 = squad.y0 + eyl;
squad.y0sq = squad.y0 * squad.y0;
squad.y1sq = squad.y1 * squad.y1;
// create vectors to four vertices
float3 v00 = { squad.x0, squad.y0, squad.z0 };
float3 v01 = { squad.x0, squad.y1, squad.z0 };
float3 v10 = { squad.x1, squad.y0, squad.z0 };
float3 v11 = { squad.x1, squad.y1, squad.z0 };
// compute normals to edges
float3 n0 = normalize(cross(v00, v10));
float3 n1 = normalize(cross(v10, v11));
float3 n2 = normalize(cross(v11, v01));
float3 n3 = normalize(cross(v01, v00));
// compute internal angles (gamma_i)
float g0 = acos(-dot(n0, n1));
float g1 = acos(-dot(n1, n2));
float g2 = acos(-dot(n2, n3));
float g3 = acos(-dot(n3, n0));
// compute predefined constants
squad.b0 = n0.z;
squad.b1 = n2.z;
squad.b0sq = squad.b0 * squad.b0;
squad.k = 2.0f * M_PIf - g2 - g3;
// compute solid angle from internal angles
squad.S = g0 + g1 - squad.k;
return squad;
}
static __device__ float3 SphQuadSample(const SphQuad& squad, const float2 uv)
{
float u = uv.x;
float v = uv.y;
// 1. compute cu
float au = u * squad.S + squad.k;
float fu = (cosf(au) * squad.b0 - squad.b1) / sinf(au);
float cu = 1.0f / sqrtf(fu * fu + squad.b0sq) * (fu > 0.0f ? 1.0f : -1.0f);
cu = clamp(cu, -1.0f, 1.0f); // avoid NaNs
// 2. compute xu
float xu = -(cu * squad.z0) / sqrtf(1.0f - cu * cu);
xu = clamp(xu, squad.x0, squad.x1); // avoid Infs
// 3. compute yv
float d = sqrtf(xu * xu + squad.z0sq);
float h0 = squad.y0 / sqrtf(d * d + squad.y0sq);
float h1 = squad.y1 / sqrtf(d * d + squad.y1sq);
float hv = h0 + v * (h1 - h0);
float hv2 = hv * hv;
float eps = 1e-5f;
float yv = (hv < 1.0f - eps) ? (hv * d) / sqrtf(1 - hv2) : squad.y1;
// 4. transform (xu, yv, z0) to world coords
return (squad.o + xu * squad.x + yv * squad.y + squad.z0 * squad.z);
}
static __inline__ __device__ float getLightPdf(const UniformLight& l, const float3 hitPoint)
{
SphQuad quad = init(l, hitPoint);
if (quad.S <= 0.0f)
{
return 0.0f;
}
return 1.0f / quad.S;
}
static __inline__ __device__ float getRectLightPdf(const UniformLight& l, const float3 lightHitPoint, const float3 surfaceHitPoint)
{
LightSampleData lightSampleData {};
lightSampleData.pointOnLight = lightHitPoint;
fillLightData(l, surfaceHitPoint, lightSampleData);
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(dot(-lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData.pdf;
}
static __inline__ __device__ float getDirectLightPdf(float angle)
{
return 1.0f / (2.0f * M_PIf * (1.0f - cos(angle)));
}
static __inline__ __device__ float getSphereLightPdf()
{
return 1.0f / (4.0f * M_PIf);
}
static __inline__ __device__ float getLightPdf(const UniformLight& l,
const float3 lightHitPoint,
const float3 surfaceHitPoint)
{
switch (l.type)
{
case 0:
// Rect
return getRectLightPdf(l, lightHitPoint, surfaceHitPoint);
break;
case 2:
// sphere
return getSphereLightPdf();
break;
case 3:
// Distant
return getDirectLightPdf(l.halfAngle);
break;
default:
break;
}
return 0.0f;
}
static __inline__ __device__ LightSampleData SampleRectLight(const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]);
float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]);
// lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y;
// https://www.arnoldrenderer.com/research/egsr2013_spherical_rectangle.pdf
SphQuad quad = init(l, hitPoint);
if (quad.S <= 0.0f)
{
lightSampleData.pdf = 0.0f;
lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
return lightSampleData;
}
if (quad.S < 1e-3f)
{
// just use uniform, because rectangle too small
lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(-dot(lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData;
}
lightSampleData.pointOnLight = SphQuadSample(quad, u);
fillLightData(l, hitPoint, lightSampleData);
lightSampleData.pdf = 1.0f / quad.S;
return lightSampleData;
}
static __inline__ __device__ LightSampleData SampleRectLightUniform(const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
// // uniform sampling
float3 e1 = make_float3(l.points[1]) - make_float3(l.points[0]);
float3 e2 = make_float3(l.points[3]) - make_float3(l.points[0]);
lightSampleData.pointOnLight = make_float3(l.points[0]) + e1 * u.x + e2 * u.y;
fillLightData(l, hitPoint, lightSampleData);
// here is conversion from are to solid angle: dist2 / cos
lightSampleData.pdf = lightSampleData.distToLight * lightSampleData.distToLight /
(-dot(lightSampleData.L, lightSampleData.normal) * lightSampleData.area);
return lightSampleData;
}
static __device__ void createCoordinateSystem(const float3& N, float3& Nt, float3& Nb) {
if (fabs(N.x) > fabs(N.y)) {
float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z);
Nt = make_float3(-N.z * invLen, 0.0f, N.x * invLen);
} else {
float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z);
Nt = make_float3(0.0f, N.z * invLen, -N.y * invLen);
}
Nb = cross(N, Nt);
}
static __device__ float3 SampleCone(float2 uv, float angle, float3 direction, float& pdf) {
float phi = 2.0 * M_PIf * uv.x;
float cosTheta = 1.0 - uv.y * (1.0 - cos(angle));
// Convert spherical coordinates to 3D direction
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
float3 u, v;
createCoordinateSystem(direction, u, v);
float3 sampledDir = normalize(cos(phi) * sinTheta * u + sin(phi) * sinTheta * v + cosTheta * direction);
// Calculate the PDF for the sampled direction
pdf = 1.0 / (2.0 * M_PIf * (1.0 - cos(angle)));
return sampledDir;
}
static __inline__ __device__ LightSampleData SampleDistantLight(const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
float pdf = 0.0f;
float3 coneSample = SampleCone(u, l.halfAngle, -make_float3(l.normal), pdf);
lightSampleData.area = 0.0f;
lightSampleData.distToLight = 1e9;
lightSampleData.L = coneSample;
lightSampleData.normal = make_float3(l.normal);
lightSampleData.pdf = pdf;
lightSampleData.pointOnLight = coneSample;
return lightSampleData;
}
static __inline__ __device__ LightSampleData SampleSphereLight(const UniformLight& l, const float2 u, const float3 hitPoint)
{
LightSampleData lightSampleData;
// Generate a random direction on the sphere using solid angle sampling
float cosTheta = 1.0f - 2.0f * u.x; // cosTheta is uniformly distributed between [-1, 1]
float sinTheta = sqrt(1.0f - cosTheta * cosTheta);
float phi = 2.0f * M_PIf * u.y; // phi is uniformly distributed between [0, 2*pi]
const float radius = l.points[0].x;
// Convert spherical coordinates to Cartesian coordinates
float3 sphereDirection = make_float3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);
// Scale the direction by the radius of the sphere and move it to the light position
float3 lightPoint = make_float3(l.points[1]) + radius * sphereDirection;
// Calculate the direction from the hit point to the sampled point on the light
lightSampleData.L = normalize(lightPoint - hitPoint);
// Calculate the distance to the light
lightSampleData.distToLight = length(lightPoint - hitPoint);
lightSampleData.area = 0.0f;
lightSampleData.normal = sphereDirection;
lightSampleData.pdf = 1.0f / (4.0f * M_PIf);
lightSampleData.pointOnLight = lightPoint;
return lightSampleData;
}
|
arhix52/Strelka/include/render/Camera.h | #pragma once
#include <glm/glm.hpp>
#include <glm/gtx/compatibility.hpp>
class Camera
{
public:
Camera()
: m_eye(glm::float3(1.0f)),
m_lookat(glm::float3(0.0f)),
m_up(glm::float3(0.0f, 1.0f, 0.0f)),
m_fovY(35.0f),
m_aspectRatio(1.0f)
{
}
Camera(const glm::float3& eye, const glm::float3& lookat, const glm::float3& up, float fovY, float aspectRatio)
: m_eye(eye), m_lookat(lookat), m_up(up), m_fovY(fovY), m_aspectRatio(aspectRatio)
{
}
glm::float3 direction() const
{
return glm::normalize(m_lookat - m_eye);
}
void setDirection(const glm::float3& dir)
{
m_lookat = m_eye + glm::length(m_lookat - m_eye) * dir;
}
const glm::float3& eye() const
{
return m_eye;
}
void setEye(const glm::float3& val)
{
m_eye = val;
}
const glm::float3& lookat() const
{
return m_lookat;
}
void setLookat(const glm::float3& val)
{
m_lookat = val;
}
const glm::float3& up() const
{
return m_up;
}
void setUp(const glm::float3& val)
{
m_up = val;
}
const float& fovY() const
{
return m_fovY;
}
void setFovY(const float& val)
{
m_fovY = val;
}
const float& aspectRatio() const
{
return m_aspectRatio;
}
void setAspectRatio(const float& val)
{
m_aspectRatio = val;
}
// UVW forms an orthogonal, but not orthonormal basis!
void UVWFrame(glm::float3& U, glm::float3& V, glm::float3& W) const
{
W = m_lookat - m_eye; // Do not normalize W -- it implies focal length
float wlen = glm::length(W);
U = glm::normalize(glm::cross(W, m_up));
V = glm::normalize(glm::cross(U, W));
float vlen = wlen * tanf(0.5f * m_fovY * M_PI / 180.0f);
V *= vlen;
float ulen = vlen * m_aspectRatio;
U *= ulen;
}
private:
glm::float3 m_eye;
glm::float3 m_lookat;
glm::float3 m_up;
float m_fovY;
float m_aspectRatio;
};
|
arhix52/Strelka/include/render/render.h | #pragma once
#include "common.h"
#include "buffer.h"
#include <scene/scene.h>
namespace oka
{
enum class RenderType : int
{
eOptiX = 0,
eMetal,
eCompute,
};
/**
* Render interface
*/
class Render
{
public:
virtual ~Render() = default;
virtual void init() = 0;
virtual void render(Buffer* output) = 0;
virtual Buffer* createBuffer(const BufferDesc& desc) = 0;
virtual void* getNativeDevicePtr()
{
return nullptr;
}
void setSharedContext(SharedContext* ctx)
{
mSharedCtx = ctx;
}
SharedContext& getSharedContext()
{
return *mSharedCtx;
}
void setScene(Scene* scene)
{
mScene = scene;
}
Scene* getScene()
{
return mScene;
}
protected:
SharedContext* mSharedCtx = nullptr;
oka::Scene* mScene = nullptr;
};
class RenderFactory
{
public:
static Render* createRender(RenderType type);
};
} // namespace oka
|
arhix52/Strelka/include/render/common.h | #pragma once
#include <glm/glm.hpp>
#include <glm/gtx/compatibility.hpp>
#include <settings/settings.h>
namespace oka
{
static constexpr int MAX_FRAMES_IN_FLIGHT = 3;
#ifdef __APPLE__
struct float3;
struct float4;
#else
using Float3 = glm::float3;
using Float4 = glm::float4;
#endif
class Render;
struct SharedContext
{
size_t mFrameNumber = 0;
size_t mSubframeIndex = 0;
SettingsManager* mSettingsManager = nullptr;
Render* mRender = nullptr;
};
enum class Result : uint32_t
{
eOk,
eFail,
eOutOfMemory,
};
} // namespace oka
|
arhix52/Strelka/include/render/materials.h | #pragma once
#ifdef __cplusplus
# define GLM_FORCE_SILENT_WARNINGS
# define GLM_LANG_STL11_FORCED
# define GLM_ENABLE_EXPERIMENTAL
# define GLM_FORCE_CTOR_INIT
# define GLM_FORCE_RADIANS
# define GLM_FORCE_DEPTH_ZERO_TO_ONE
# include <glm/glm.hpp>
# include <glm/gtx/compatibility.hpp>
# define float4 glm::float4
# define float3 glm::float3
# define uint glm::uint
#endif
struct MdlMaterial
{
int arg_block_offset = 0; // in bytes
int ro_data_segment_offset = 0; // in bytes
int functionId = 0;
int pad1;
};
/// Information passed to GPU for mapping id requested in the runtime functions to buffer
/// views of the corresponding type.
struct Mdl_resource_info
{
// index into the tex2d, tex3d, ... buffers, depending on the type requested
uint gpu_resource_array_start;
uint pad0;
uint pad1;
uint pad2;
};
#ifdef __cplusplus
# undef float4
# undef float3
# undef uint
#endif
|
arhix52/Strelka/include/settings/settings.h | #pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <cassert>
namespace oka
{
class SettingsManager
{
private:
/* data */
std::unordered_map<std::string, std::string> mMap;
void isNameValid(const char* name)
{
if (mMap.find(name) == mMap.end())
{
std::cerr << "The setting " << name << " does not exist" << std::endl;
assert(0);
}
}
public:
SettingsManager(/* args */) = default;
~SettingsManager() = default;
template <typename T>
void setAs(const char* name, const T& value)
{
// mMap[name] = std::to_string(value);
mMap[name] = toString(value);
}
template <typename T>
T getAs(const char* name)
{
isNameValid(name);
return convertValue<T>(mMap[name]);
}
private:
template <typename T>
T convertValue(const std::string& value)
{
// Default implementation for non-specialized types
return T{};
}
static std::string toString(const std::string& value)
{
return value;
}
template <typename T>
std::string toString(const T& value)
{
// Default implementation for non-specialized types
return std::to_string(value);
}
};
template<>
inline void SettingsManager::setAs(const char* name, const std::string& value)
{
mMap[name] = value;
}
template <>
inline bool SettingsManager::convertValue(const std::string& value)
{
return static_cast<bool>(atoi(value.c_str()));
}
template <>
inline float SettingsManager::convertValue(const std::string& value)
{
return static_cast<float>(atof(value.c_str()));
}
template <>
inline uint32_t SettingsManager::convertValue(const std::string& value)
{
return static_cast<uint32_t>(atoi(value.c_str()));
}
template <>
inline std::string SettingsManager::convertValue(const std::string& value)
{
return value;
}
template <>
inline std::string SettingsManager::toString(const std::string& value)
{
return value;
}
} // namespace oka
|
arhix52/Strelka/include/scene/camera.h | #pragma once
#define GLM_FORCE_SILENT_WARNINGS
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/compatibility.hpp>
#include <string>
namespace oka
{
class Camera
{
public:
std::string name = "Default camera";
int node = -1;
enum class CameraType : uint32_t
{
lookat,
firstperson
};
CameraType type = CameraType::firstperson;
float fov = 45.0f;
float znear = 0.1f, zfar = 1000.0f;
// View dir -Z
glm::quat mOrientation = { 1.0f, 0.0f, 0.0f, 0.0f };
glm::float3 position = { 0.0f, 0.0f, 10.0f };
glm::float3 mWorldUp = {0.0, 1.0, 0.0};
glm::float3 mWorldForward = {0.0, 0.0, -1.0};
glm::quat getOrientation();
float rotationSpeed = 0.025f;
float movementSpeed = 5.0f;
bool updated = false;
bool isDirty = true;
struct MouseButtons
{
bool left = false;
bool right = false;
bool middle = false;
} mouseButtons;
glm::float2 mousePos;
struct Matrices
{
glm::float4x4 perspective;
glm::float4x4 invPerspective;
glm::float4x4 view;
};
Matrices matrices;
void updateViewMatrix();
struct
{
bool left = false;
bool right = false;
bool up = false;
bool down = false;
bool forward = false;
bool back = false;
} keys;
glm::float3 getFront() const;
glm::float3 getUp() const;
glm::float3 getRight() const;
bool moving() const;
float getNearClip() const;
float getFarClip() const;
void setFov(float fov);
void setPerspective(float fov, float aspect, float znear, float zfar);
void setWorldUp(const glm::float3 up);
glm::float3 getWorldUp();
void setWorldForward(const glm::float3 forward);
glm::float3 getWorldForward();
glm::float4x4& getPerspective();
glm::float4x4 getView();
void updateAspectRatio(float aspect);
void setPosition(glm::float3 position);
glm::float3 getPosition();
void setRotation(glm::quat rotation);
void rotate(float, float);
void setTranslation(glm::float3 translation);
void translate(glm::float3 delta);
void update(float deltaTime);
};
} // namespace oka
|
arhix52/Strelka/include/scene/scene.h | #pragma once
#include "camera.h"
#include "glm-wrapper.hpp"
// #include "materials.h"
// #undef float4
// #undef float3
#include <cstdint>
#include <mutex>
#include <set>
#include <stack>
#include <unordered_map>
#include <vector>
#include <mutex>
#include <materialmanager/materialmanager.h>
namespace oka
{
struct Mesh
{
uint32_t mIndex; // Index of 1st index in index buffer
uint32_t mCount; // amount of indices in mesh
uint32_t mVbOffset; // start in vb
uint32_t mVertexCount; // number of vertices in mesh
};
struct Curve
{
enum class Type : uint8_t
{
eLinear,
eCubic,
};
uint32_t mVertexCountsStart;
uint32_t mVertexCountsCount;
uint32_t mPointsStart;
uint32_t mPointsCount;
uint32_t mWidthsStart;
uint32_t mWidthsCount;
};
struct Instance
{
glm::mat4 transform;
enum class Type : uint8_t
{
eMesh,
eLight,
eCurve
} type;
union
{
uint32_t mMeshId;
uint32_t mCurveId;
};
uint32_t mMaterialId = 0;
uint32_t mLightId = (uint32_t)-1;
};
class Scene
{
public:
struct MaterialDescription
{
enum class Type
{
eMdl,
eMaterialX
} type;
std::string code;
std::string file;
std::string name;
bool hasColor = false;
glm::float3 color;
std::vector<MaterialManager::Param> params;
};
struct Vertex
{
glm::float3 pos;
uint32_t tangent;
uint32_t normal;
uint32_t uv;
float pad0;
float pad1;
};
struct Node
{
std::string name;
glm::float3 translation;
glm::float3 scale;
glm::quat rotation;
int parent = -1;
std::vector<int> children;
};
std::vector<Node> mNodes;
enum class AnimationState : uint32_t
{
eStop,
ePlay,
eScroll,
};
AnimationState mAnimState = AnimationState::eStop;
struct AnimationSampler
{
enum class InterpolationType
{
LINEAR,
STEP,
CUBICSPLINE
};
InterpolationType interpolation;
std::vector<float> inputs;
std::vector<glm::float4> outputsVec4;
};
struct AnimationChannel
{
enum class PathType
{
TRANSLATION,
ROTATION,
SCALE
};
PathType path;
int node;
uint32_t samplerIndex;
};
struct Animation
{
std::string name;
std::vector<AnimationSampler> samplers;
std::vector<AnimationChannel> channels;
float start = std::numeric_limits<float>::max();
float end = std::numeric_limits<float>::min();
};
std::vector<Animation> mAnimations;
// GPU side structure
struct Light
{
glm::float4 points[4];
glm::float4 color = glm::float4(1.0f);
glm::float4 normal;
int type;
float halfAngle;
float pad0;
float pad1;
};
// CPU side structure
struct UniformLightDesc
{
int32_t type;
glm::float4x4 xform{ 1.0 };
glm::float3 position; // world position
glm::float3 orientation; // euler angles in degrees
bool useXform;
// OX - axis of light or normal
glm::float3 color;
float intensity;
// rectangle light
float width; // OY
float height; // OZ
// disc/sphere light
float radius;
// distant light
float halfAngle;
};
std::vector<UniformLightDesc> mLightDesc;
enum class DebugView : uint32_t
{
eNone = 0,
eNormals = 1,
eShadows = 2,
eLTC = 3,
eMotion = 4,
eCustomDebug = 5,
ePTDebug = 11
};
DebugView mDebugViewSettings = DebugView::eNone;
bool transparentMode = true;
bool opaqueMode = true;
glm::float4 mLightPosition{ 10.0, 10.0, 10.0, 1.0 };
std::mutex mMeshMutex;
std::mutex mInstanceMutex;
std::vector<Vertex> mVertices;
std::vector<uint32_t> mIndices;
std::vector<glm::float3> mCurvePoints;
std::vector<float> mCurveWidths;
std::vector<uint32_t> mCurveVertexCounts;
std::string modelPath;
std::string getSceneFileName();
std::string getSceneDir();
std::vector<Mesh> mMeshes;
std::vector<Curve> mCurves;
std::vector<Instance> mInstances;
std::vector<Light> mLights;
std::vector<uint32_t> mTransparentInstances;
std::vector<uint32_t> mOpaqueInstances;
Scene() = default;
~Scene() = default;
std::unordered_map<uint32_t, uint32_t> mLightIdToInstanceId{};
std::unordered_map<int32_t, std::string> mTexIdToTexName{};
std::vector<Vertex>& getVertices()
{
return mVertices;
}
std::vector<uint32_t>& getIndices()
{
return mIndices;
}
std::vector<MaterialDescription>& getMaterials()
{
return mMaterialsDescs;
}
std::vector<Light>& getLights()
{
return mLights;
}
std::vector<UniformLightDesc>& getLightsDesc()
{
return mLightDesc;
}
uint32_t findCameraByName(const std::string& name)
{
std::scoped_lock lock(mCameraMutex);
if (mNameToCamera.find(name) != mNameToCamera.end())
{
return mNameToCamera[name];
}
return (uint32_t)-1;
}
uint32_t addCamera(Camera& camera)
{
std::scoped_lock lock(mCameraMutex);
mCameras.push_back(camera);
// store camera index
mNameToCamera[camera.name] = (uint32_t)mCameras.size() - 1;
return (uint32_t)mCameras.size() - 1;
}
void updateCamera(Camera& camera, uint32_t index)
{
assert(index < mCameras.size());
std::scoped_lock lock(mCameraMutex);
mCameras[index] = camera;
}
Camera& getCamera(uint32_t index)
{
assert(index < mCameras.size());
std::scoped_lock lock(mCameraMutex);
return mCameras[index];
}
const std::vector<Camera>& getCameras()
{
std::scoped_lock lock(mCameraMutex);
return mCameras;
}
size_t getCameraCount()
{
std::scoped_lock lock(mCameraMutex);
return mCameras.size();
}
const std::vector<Instance>& getInstances() const
{
return mInstances;
}
const std::vector<Mesh>& getMeshes() const
{
return mMeshes;
}
const std::vector<Curve>& getCurves() const
{
return mCurves;
}
const std::vector<glm::float3>& getCurvesPoint() const
{
return mCurvePoints;
}
const std::vector<float>& getCurvesWidths() const
{
return mCurveWidths;
}
const std::vector<uint32_t>& getCurvesVertexCounts() const
{
return mCurveVertexCounts;
}
void updateCamerasParams(int width, int height)
{
for (Camera& camera : mCameras)
{
camera.updateAspectRatio((float)width / height);
}
}
glm::float4x4 getTransform(const Scene::UniformLightDesc& desc)
{
const glm::float4x4 translationMatrix = glm::translate(glm::float4x4(1.0f), desc.position);
glm::quat rotation = glm::quat(glm::radians(desc.orientation)); // to quaternion
const glm::float4x4 rotationMatrix{ rotation };
glm::float3 scale = { desc.width, desc.height, 1.0f };
const glm::float4x4 scaleMatrix = glm::scale(glm::float4x4(1.0f), scale);
const glm::float4x4 localTransform = translationMatrix * rotationMatrix * scaleMatrix;
return localTransform;
}
glm::float4x4 getTransformFromRoot(int nodeIdx)
{
std::stack<glm::float4x4> xforms;
while (nodeIdx != -1)
{
const Node& n = mNodes[nodeIdx];
glm::float4x4 xform = glm::translate(glm::float4x4(1.0f), n.translation) * glm::float4x4(n.rotation) *
glm::scale(glm::float4x4(1.0f), n.scale);
xforms.push(xform);
nodeIdx = n.parent;
}
glm::float4x4 xform = glm::float4x4(1.0);
while (!xforms.empty())
{
xform = xform * xforms.top();
xforms.pop();
}
return xform;
}
glm::float4x4 getTransform(int nodeIdx)
{
glm::float4x4 xform = glm::float4x4(1.0);
while (nodeIdx != -1)
{
const Node& n = mNodes[nodeIdx];
xform = glm::translate(glm::float4x4(1.0f), n.translation) * glm::float4x4(n.rotation) *
glm::scale(glm::float4x4(1.0f), n.scale) * xform;
nodeIdx = n.parent;
}
return xform;
}
glm::float4x4 getCameraTransform(int nodeIdx)
{
int child = mNodes[nodeIdx].children[0];
return getTransform(child);
}
void updateAnimation(const float dt);
void updateLight(uint32_t lightId, const UniformLightDesc& desc);
/// <summary>
/// Create Mesh geometry
/// </summary>
/// <param name="vb">Vertices</param>
/// <param name="ib">Indices</param>
/// <returns>Mesh id in scene</returns>
uint32_t createMesh(const std::vector<Vertex>& vb, const std::vector<uint32_t>& ib);
/// <summary>
/// Creates Instance
/// </summary>
/// <param name="meshId">valid mesh id</param>
/// <param name="materialId">valid material id</param>
/// <param name="transform">transform</param>
/// <returns>Instance id in scene</returns>
uint32_t createInstance(const Instance::Type type,
const uint32_t geomId,
const uint32_t materialId,
const glm::mat4& transform,
const uint32_t lightId = (uint32_t)-1);
uint32_t addMaterial(const MaterialDescription& material);
uint32_t createCurve(const Curve::Type type,
const std::vector<uint32_t>& vertexCounts,
const std::vector<glm::float3>& points,
const std::vector<float>& widths);
uint32_t createLight(const UniformLightDesc& desc);
/// <summary>
/// Removes instance/mesh/material
/// </summary>
/// <param name="meshId">valid mesh id</param>
/// <param name="materialId">valid material id</param>
/// <param name="instId">valid instance id</param>
/// <returns>Nothing</returns>
void removeInstance(uint32_t instId);
void removeMesh(uint32_t meshId);
void removeMaterial(uint32_t materialId);
std::vector<uint32_t>& getOpaqueInstancesToRender(const glm::float3& camPos);
std::vector<uint32_t>& getTransparentInstancesToRender(const glm::float3& camPos);
/// <summary>
/// Get set of DirtyInstances
/// </summary>
/// <returns>Set of instances</returns>
std::set<uint32_t> getDirtyInstances();
/// <summary>
/// Get Frame mode (bool)
/// </summary>
/// <returns>Bool</returns>
bool getFrMod();
/// <summary>
/// Updates Instance matrix(transform)
/// </summary>
/// <param name="instId">valid instance id</param>
/// <param name="newTransform">new transformation matrix</param>
/// <returns>Nothing</returns>
void updateInstanceTransform(uint32_t instId, glm::float4x4 newTransform);
/// <summary>
/// Changes status of scene and cleans up mDirty* sets
/// </summary>
/// <returns>Nothing</returns>
void beginFrame();
/// <summary>
/// Changes status of scene
/// </summary>
/// <returns>Nothing</returns>
void endFrame();
private:
std::vector<Camera> mCameras;
std::unordered_map<std::string, uint32_t> mNameToCamera;
std::mutex mCameraMutex;
std::stack<uint32_t> mDelInstances;
std::stack<uint32_t> mDelMesh;
std::stack<uint32_t> mDelMaterial;
std::vector<MaterialDescription> mMaterialsDescs;
uint32_t createRectLightMesh();
uint32_t createDiscLightMesh();
uint32_t createSphereLightMesh();
bool FrMod{};
std::set<uint32_t> mDirtyInstances;
uint32_t mRectLightMeshId = (uint32_t)-1;
uint32_t mDiskLightMeshId = (uint32_t)-1;
uint32_t mSphereLightMeshId = (uint32_t)-1;
};
} // namespace oka
|
arhix52/Strelka/include/scene/glm-wrapper.hpp | #pragma once
#define GLM_FORCE_SILENT_WARNINGS
#define GLM_LANG_STL11_FORCED
#define GLM_ENABLE_EXPERIMENTAL
#define GLM_FORCE_CTOR_INIT
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtx/hash.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/compatibility.hpp>
|
arhix52/Strelka/include/log/logmanager.h | #pragma once
#include <spdlog/spdlog.h>
namespace oka
{
class Logmanager
{
public:
Logmanager(/* args */);
~Logmanager();
void initialize();
void shutdown();
};
} // namespace oka
|
arhix52/Strelka/include/log/log.h | #pragma once
#include <spdlog/spdlog.h>
#define STRELKA_DEFAULT_LOGGER_NAME "Strelka"
#ifndef RELEASE
#define STRELKA_TRACE(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->trace(__VA_ARGS__);}
#define STRELKA_DEBUG(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->debug(__VA_ARGS__);}
#define STRELKA_INFO(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->info(__VA_ARGS__);}
#define STRELKA_WARNING(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->warn(__VA_ARGS__);}
#define STRELKA_ERROR(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->error(__VA_ARGS__);}
#define STRELKA_FATAL(...) if (spdlog::get(STRELKA_DEFAULT_LOGGER_NAME) != nullptr) {spdlog::get(STRELKA_DEFAULT_LOGGER_NAME)->critical(__VA_ARGS__);}
#else
define STRELKA_TRACE(...) void(0);
define STRELKA_DEBUG(...) void(0);
define STRELKA_INFO(...) void(0);
define STRELKA_WARNING(...) void(0);
define STRELKA_ERROR(...) void(0);
define STRELKA_FATAL(...) void(0);
#endif
|
arhix52/Strelka/include/sceneloader/gltfloader.h | #pragma once
#include <scene/scene.h>
#include <string>
#include <vector>
namespace oka
{
class GltfLoader
{
private:
public:
explicit GltfLoader(){}
bool loadGltf(const std::string& modelPath, Scene& mScene);
void computeTangent(std::vector<Scene::Vertex>& _vertices,
const std::vector<uint32_t>& _indices) const;
};
} // namespace oka
|
arhix52/Strelka/include/display/Display.h | #pragma once
#include <render/common.h>
#include <render/buffer.h>
#include <GLFW/glfw3.h>
namespace oka
{
class InputHandler
{
public:
virtual void keyCallback(int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods) = 0;
virtual void mouseButtonCallback(int button, int action, [[maybe_unused]] int mods) = 0;
virtual void handleMouseMoveCallback([[maybe_unused]] double xpos, [[maybe_unused]] double ypos) = 0;
};
class ResizeHandler
{
public:
virtual void framebufferResize(int newWidth, int newHeight) = 0;
};
class Display
{
public:
Display()
{
}
virtual ~Display()
{
}
virtual void init(int width, int height, oka::SharedContext* ctx) = 0;
virtual void destroy() = 0;
void setWindowTitle(const char* title)
{
glfwSetWindowTitle(mWindow, title);
}
void setInputHandler(InputHandler* handler)
{
mInputHandler = handler;
}
InputHandler* getInputHandler()
{
return mInputHandler;
}
void setResizeHandler(ResizeHandler* handler)
{
mResizeHandler = handler;
}
ResizeHandler* getResizeHandler()
{
return mResizeHandler;
}
bool windowShouldClose()
{
return glfwWindowShouldClose(mWindow);
}
void pollEvents()
{
glfwPollEvents();
}
virtual void onBeginFrame() = 0;
virtual void onEndFrame() = 0;
virtual void drawFrame(ImageBuffer& result) = 0;
virtual void drawUI();
protected:
static void framebufferResizeCallback(GLFWwindow* window, int width, int height);
static void keyCallback(
GLFWwindow* window, int key, [[maybe_unused]] int scancode, int action, [[maybe_unused]] int mods);
static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
static void handleMouseMoveCallback(GLFWwindow* window, double xpos, double ypos);
static void scrollCallback(GLFWwindow* window, double xoffset, double yoffset);
int mWindowWidth = 800;
int mWindowHeight = 600;
InputHandler* mInputHandler = nullptr;
ResizeHandler* mResizeHandler = nullptr;
oka::SharedContext* mCtx = nullptr;
GLFWwindow* mWindow;
};
class DisplayFactory
{
public:
static Display* createDisplay();
};
} // namespace oka
|
arhix52/Strelka/cuda/random.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
template<unsigned int N>
static __host__ __device__ __inline__ unsigned int tea( unsigned int val0, unsigned int val1 )
{
unsigned int v0 = val0;
unsigned int v1 = val1;
unsigned int s0 = 0;
for( unsigned int n = 0; n < N; n++ )
{
s0 += 0x9e3779b9;
v0 += ((v1<<4)+0xa341316c)^(v1+s0)^((v1>>5)+0xc8013ea4);
v1 += ((v0<<4)+0xad90777d)^(v0+s0)^((v0>>5)+0x7e95761e);
}
return v0;
}
// Generate random unsigned int in [0, 2^24)
static __host__ __device__ __inline__ unsigned int lcg(unsigned int &prev)
{
const unsigned int LCG_A = 1664525u;
const unsigned int LCG_C = 1013904223u;
prev = (LCG_A * prev + LCG_C);
return prev & 0x00FFFFFF;
}
static __host__ __device__ __inline__ unsigned int lcg2(unsigned int &prev)
{
prev = (prev*8121 + 28411) % 134456;
return prev;
}
// Generate random float in [0, 1)
static __host__ __device__ __inline__ float rnd(unsigned int &prev)
{
return ((float) lcg(prev) / (float) 0x01000000);
}
static __host__ __device__ __inline__ unsigned int rot_seed( unsigned int seed, unsigned int frame )
{
return seed ^ frame;
}
|
arhix52/Strelka/cuda/curve.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include <optix.h>
#include <sutil/vec_math.h>
#include <vector_types.h>
//
// First order polynomial interpolator
//
struct LinearInterpolator
{
__device__ __forceinline__ LinearInterpolator() {}
__device__ __forceinline__ void initialize( const float4* q )
{
p[0] = q[0];
p[1] = q[1] - q[0];
}
__device__ __forceinline__ float4 position4( float u ) const
{
return p[0] + u * p[1]; // Horner scheme
}
__device__ __forceinline__ float3 position3( float u ) const
{
return make_float3( position4( u ) );
}
__device__ __forceinline__ float radius( const float& u ) const
{
return position4( u ).w;
}
__device__ __forceinline__ float4 velocity4( float u ) const
{
return p[1];
}
__device__ __forceinline__ float3 velocity3( float u ) const
{
return make_float3( velocity4( u ) );
}
__device__ __forceinline__ float derivative_of_radius( float u ) const
{
return velocity4( u ).w;
}
__device__ __forceinline__ float3 acceleration3( float u ) const { return make_float3( 0.f ); }
__device__ __forceinline__ float4 acceleration4( float u ) const { return make_float4( 0.f ); }
float4 p[2];
};
//
// Second order polynomial interpolator
//
struct QuadraticInterpolator
{
__device__ __forceinline__ QuadraticInterpolator() {}
__device__ __forceinline__ void initializeFromBSpline( const float4* q )
{
// Bspline-to-Poly = Matrix([[1/2, -1, 1/2],
// [-1, 1, 0],
// [1/2, 1/2, 0]])
p[0] = ( q[0] - 2.0f * q[1] + q[2] ) / 2.0f;
p[1] = ( -2.0f * q[0] + 2.0f * q[1] ) / 2.0f;
p[2] = ( q[0] + q[1] ) / 2.0f;
}
__device__ __forceinline__ void export2BSpline( float4 bs[3] ) const
{
// inverse of initializeFromBSpline
// Bspline-to-Poly = Matrix([[1/2, -1, 1/2],
// [-1, 1, 0],
// [1/2, 1/2, 0]])
// invert to get:
// Poly-to-Bspline = Matrix([[0, -1/2, 1],
// [0, 1/2, 1],
// [2, 3/2, 1]])
bs[0] = p[0] - p[1] / 2;
bs[1] = p[0] + p[1] / 2;
bs[2] = p[0] + 1.5f * p[1] + 2 * p[2];
}
__device__ __forceinline__ float4 position4( float u ) const
{
return ( p[0] * u + p[1] ) * u + p[2]; // Horner scheme
}
__device__ __forceinline__ float3 position3( float u ) const
{
return make_float3( position4( u ) );
}
__device__ __forceinline__ float radius( float u ) const
{
return position4( u ).w;
}
__device__ __forceinline__ float4 velocity4( float u ) const
{
return 2.0f * p[0] * u + p[1];
}
__device__ __forceinline__ float3 velocity3( float u ) const
{
return make_float3( velocity4( u ) );
}
__device__ __forceinline__ float derivative_of_radius( float u ) const
{
return velocity4( u ).w;
}
__device__ __forceinline__ float4 acceleration4( float u ) const
{
return 2.0f * p[0];
}
__device__ __forceinline__ float3 acceleration3( float u ) const
{
return make_float3( acceleration4( u ) );
}
float4 p[3];
};
//
// Third order polynomial interpolator
//
// Storing {p0, p1, p2, p3} for evaluation:
// P(u) = p0 * u^3 + p1 * u^2 + p2 * u + p3
//
struct CubicInterpolator
{
__device__ __forceinline__ CubicInterpolator() {}
// TODO: Initialize from polynomial weights. Check that sample doesn't rely on
// legacy behavior.
// __device__ __forceinline__ CubicBSplineSegment( const float4* q ) { initializeFromBSpline( q ); }
__device__ __forceinline__ void initializeFromBSpline( const float4* q )
{
// Bspline-to-Poly = Matrix([[-1/6, 1/2, -1/2, 1/6],
// [ 1/2, -1, 1/2, 0],
// [-1/2, 0, 1/2, 0],
// [ 1/6, 2/3, 1/6, 0]])
p[0] = ( q[0] * ( -1.0f ) + q[1] * ( 3.0f ) + q[2] * ( -3.0f ) + q[3] ) / 6.0f;
p[1] = ( q[0] * ( 3.0f ) + q[1] * ( -6.0f ) + q[2] * ( 3.0f ) ) / 6.0f;
p[2] = ( q[0] * ( -3.0f ) + q[2] * ( 3.0f ) ) / 6.0f;
p[3] = ( q[0] * ( 1.0f ) + q[1] * ( 4.0f ) + q[2] * ( 1.0f ) ) / 6.0f;
}
__device__ __forceinline__ void export2BSpline( float4 bs[4] ) const
{
// inverse of initializeFromBSpline
// Bspline-to-Poly = Matrix([[-1/6, 1/2, -1/2, 1/6],
// [ 1/2, -1, 1/2, 0],
// [-1/2, 0, 1/2, 0],
// [ 1/6, 2/3, 1/6, 0]])
// invert to get:
// Poly-to-Bspline = Matrix([[0, 2/3, -1, 1],
// [0, -1/3, 0, 1],
// [0, 2/3, 1, 1],
// [6, 11/3, 2, 1]])
bs[0] = ( p[1] * ( 2.0f ) + p[2] * ( -1.0f ) + p[3] ) / 3.0f;
bs[1] = ( p[1] * ( -1.0f ) + p[3] ) / 3.0f;
bs[2] = ( p[1] * ( 2.0f ) + p[2] * ( 1.0f ) + p[3] ) / 3.0f;
bs[3] = ( p[0] + p[1] * ( 11.0f ) + p[2] * ( 2.0f ) + p[3] ) / 3.0f;
}
__device__ __forceinline__ void initializeFromCatrom(const float4* q)
{
// Catrom-to-Poly = Matrix([[-1/2, 3/2, -3/2, 1/2],
// [1, -5/2, 2, -1/2],
// [-1/2, 0, 1/2, 0],
// [0, 1, 0, 0]])
p[0] = ( -1.0f * q[0] + ( 3.0f ) * q[1] + ( -3.0f ) * q[2] + ( 1.0f ) * q[3] ) / 2.0f;
p[1] = ( 2.0f * q[0] + ( -5.0f ) * q[1] + ( 4.0f ) * q[2] + ( -1.0f ) * q[3] ) / 2.0f;
p[2] = ( -1.0f * q[0] + ( 1.0f ) * q[2] ) / 2.0f;
p[3] = ( ( 2.0f ) * q[1] ) / 2.0f;
}
__device__ __forceinline__ void export2Catrom(float4 cr[4]) const
{
// Catrom-to-Poly = Matrix([[-1/2, 3/2, -3/2, 1/2],
// [1, -5/2, 2, -1/2],
// [-1/2, 0, 1/2, 0],
// [0, 1, 0, 0]])
// invert to get:
// Poly-to-Catrom = Matrix([[1, 1, -1, 1],
// [0, 0, 0, 1],
// [1, 1, 1, 1],
// [6, 4, 2, 1]])
cr[0] = ( p[0] * 6.f/6.f ) - ( p[1] * 5.f/6.f ) + ( p[2] * 2.f/6.f ) + ( p[3] * 1.f/6.f );
cr[1] = ( p[0] * 6.f/6.f ) ;
cr[2] = ( p[0] * 6.f/6.f ) + ( p[1] * 1.f/6.f ) + ( p[2] * 2.f/6.f ) + ( p[3] * 1.f/6.f );
cr[3] = ( p[0] * 6.f/6.f ) + ( p[3] * 6.f/6.f );
}
__device__ __forceinline__ float4 position4( float u ) const
{
return ( ( ( p[0] * u ) + p[1] ) * u + p[2] ) * u + p[3]; // Horner scheme
}
__device__ __forceinline__ float3 position3( float u ) const
{
// rely on compiler and inlining for dead code removal
return make_float3( position4( u ) );
}
__device__ __forceinline__ float radius( float u ) const
{
return position4( u ).w;
}
__device__ __forceinline__ float4 velocity4( float u ) const
{
// adjust u to avoid problems with tripple knots.
if( u == 0 )
u = 0.000001f;
if( u == 1 )
u = 0.999999f;
return ( ( 3.0f * p[0] * u ) + 2.0f * p[1] ) * u + p[2];
}
__device__ __forceinline__ float3 velocity3( float u ) const
{
return make_float3( velocity4( u ) );
}
__device__ __forceinline__ float derivative_of_radius( float u ) const
{
return velocity4( u ).w;
}
__device__ __forceinline__ float4 acceleration4( float u ) const
{
return 6.0f * p[0] * u + 2.0f * p[1]; // Horner scheme
}
__device__ __forceinline__ float3 acceleration3( float u ) const
{
return make_float3( acceleration4( u ) );
}
float4 p[4];
};
// Compute curve primitive surface normal in object space.
//
// Template parameters:
// CurveType - A B-Spline evaluator class.
// type - 0 ~ cylindrical approximation (correct if radius' == 0)
// 1 ~ conic approximation (correct if curve'' == 0)
// other ~ the bona fide surface normal
//
// Parameters:
// bc - A B-Spline evaluator object.
// u - segment parameter of hit-point.
// ps - hit-point on curve's surface in object space; usually
// computed like this.
// float3 ps = ray_orig + t_hit * ray_dir;
// the resulting point is slightly offset away from the
// surface. For this reason (Warning!) ps gets modified by this
// method, projecting it onto the surface
// in case it is not already on it. (See also inline
// comments.)
//
template <typename CurveType, int type = 2>
__device__ __forceinline__ float3 surfaceNormal( const CurveType& bc, float u, float3& ps )
{
float3 normal;
if( u == 0.0f )
{
normal = -bc.velocity3( 0 ); // special handling for flat endcaps
}
else if( u == 1.0f )
{
normal = bc.velocity3( 1 ); // special handling for flat endcaps
}
else
{
// ps is a point that is near the curve's offset surface,
// usually ray.origin + ray.direction * rayt.
// We will push it exactly to the surface by projecting it to the plane(p,d).
// The function derivation:
// we (implicitly) transform the curve into coordinate system
// {p, o1 = normalize(ps - p), o2 = normalize(curve'(t)), o3 = o1 x o2} in which
// curve'(t) = (0, length(d), 0); ps = (r, 0, 0);
float4 p4 = bc.position4( u );
float3 p = make_float3( p4 );
float r = p4.w; // == length(ps - p) if ps is already on the surface
float4 d4 = bc.velocity4( u );
float3 d = make_float3( d4 );
float dr = d4.w;
float dd = dot( d, d );
float3 o1 = ps - p; // dot(modified_o1, d) == 0 by design:
o1 -= ( dot( o1, d ) / dd ) * d; // first, project ps to the plane(p,d)
o1 *= r / length( o1 ); // and then drop it to the surface
ps = p + o1; // fine-tuning the hit point
if( type == 0 )
{
normal = o1; // cylindrical approximation
}
else
{
if( type != 1 )
{
dd -= dot( bc.acceleration3( u ), o1 );
}
normal = dd * o1 - ( dr * r ) * d;
}
}
return normalize( normal );
}
template <int type = 1>
__device__ __forceinline__ float3 surfaceNormal( const LinearInterpolator& bc, float u, float3& ps )
{
float3 normal;
if( u == 0.0f )
{
normal = ps - ( float3 & )( bc.p[0] ); // special handling for round endcaps
}
else if( u >= 1.0f )
{
// reconstruct second control point (Note: the interpolator pre-transforms
// the control-points to speed up repeated evaluation.
const float3 p1 = ( float3 & ) (bc.p[1] ) + ( float3 & )( bc.p[0] );
normal = ps - p1; // special handling for round endcaps
}
else
{
// ps is a point that is near the curve's offset surface,
// usually ray.origin + ray.direction * rayt.
// We will push it exactly to the surface by projecting it to the plane(p,d).
// The function derivation:
// we (implicitly) transform the curve into coordinate system
// {p, o1 = normalize(ps - p), o2 = normalize(curve'(t)), o3 = o1 x o2} in which
// curve'(t) = (0, length(d), 0); ps = (r, 0, 0);
float4 p4 = bc.position4( u );
float3 p = make_float3( p4 );
float r = p4.w; // == length(ps - p) if ps is already on the surface
float4 d4 = bc.velocity4( u );
float3 d = make_float3( d4 );
float dr = d4.w;
float dd = dot( d, d );
float3 o1 = ps - p; // dot(modified_o1, d) == 0 by design:
o1 -= ( dot( o1, d ) / dd ) * d; // first, project ps to the plane(p,d)
o1 *= r / length( o1 ); // and then drop it to the surface
ps = p + o1; // fine-tuning the hit point
if( type == 0 )
{
normal = o1; // cylindrical approximation
}
else
{
normal = dd * o1 - ( dr * r ) * d;
}
}
return normalize( normal );
}
// Compute curve primitive tangent in object space.
//
// Template parameters:
// CurveType - A B-Spline evaluator class.
//
// Parameters:
// bc - A B-Spline evaluator object.
// u - segment parameter of tangent location on curve.
//
template <typename CurveType>
__device__ __forceinline__ float3 curveTangent( const CurveType& bc, float u )
{
float3 tangent = bc.velocity3( u );
return normalize( tangent );
}
|
arhix52/Strelka/cuda/helpers.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include <vector_types.h>
#include <sutil/vec_math.h>
__forceinline__ __device__ float3 toSRGB( const float3& c )
{
float invGamma = 1.0f / 2.4f;
float3 powed = make_float3( powf( c.x, invGamma ), powf( c.y, invGamma ), powf( c.z, invGamma ) );
return make_float3(
c.x < 0.0031308f ? 12.92f * c.x : 1.055f * powed.x - 0.055f,
c.y < 0.0031308f ? 12.92f * c.y : 1.055f * powed.y - 0.055f,
c.z < 0.0031308f ? 12.92f * c.z : 1.055f * powed.z - 0.055f );
}
//__forceinline__ __device__ float dequantizeUnsigned8Bits( const unsigned char i )
//{
// enum { N = (1 << 8) - 1 };
// return min((float)i / (float)N), 1.f)
//}
__forceinline__ __device__ unsigned char quantizeUnsigned8Bits( float x )
{
x = clamp( x, 0.0f, 1.0f );
enum { N = (1 << 8) - 1, Np1 = (1 << 8) };
return (unsigned char)min((unsigned int)(x * (float)Np1), (unsigned int)N);
}
__forceinline__ __device__ uchar4 make_color( const float3& c )
{
// first apply gamma, then convert to unsigned char
float3 srgb = toSRGB( clamp( c, 0.0f, 1.0f ) );
return make_uchar4( quantizeUnsigned8Bits( srgb.x ), quantizeUnsigned8Bits( srgb.y ), quantizeUnsigned8Bits( srgb.z ), 255u );
}
__forceinline__ __device__ uchar4 make_color( const float4& c )
{
return make_color( make_float3( c.x, c.y, c.z ) );
}
|
arhix52/Strelka/cuda/util.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#ifndef __CUDACC_RTC__
#include <stdio.h>
#endif
#define if_pixel( x_, y_ ) \
const uint3 launch_idx__ = optixGetLaunchIndex(); \
if( launch_idx__.x == (x_) && launch_idx__.y == (y_) ) \
#define print_pixel( x_, y_, str, ... ) \
do \
{ \
const uint3 launch_idx = optixGetLaunchIndex(); \
if( launch_idx.x == (x_) && launch_idx.y == (y_) ) \
{ \
printf( str, __VA_ARGS__ ); \
} \
} while(0);
|
arhix52/Strelka/tests/tests_main.cpp | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>
// This is all that is needed to compile a test-runner executable.
// More tests can be added here, or in a new tests/*.cpp file.
|
arhix52/Strelka/tests/CMakeLists.txt | cmake_minimum_required(VERSION 3.20)
include(CTest)
find_package(doctest REQUIRED)
set(TESTFILES
tests_main.cpp
materialmanager/test_materialmanager.cpp
)
set(TEST_MAIN unit_tests)
set(TEST_RUNNER_PARAMS "")
find_package(USD REQUIRED HINTS ${USD_DIR} NAMES pxr)
message(STATUS "USD LIBRARY: ${USD_DIR}")
find_package(MaterialX REQUIRED)
add_executable(${TEST_MAIN} ${TESTFILES})
target_link_libraries(${TEST_MAIN}
PUBLIC
doctest::doctest
materialmanager
)
target_include_directories(${TEST_MAIN} PRIVATE ${ROOT_HOME}/include/)
set_target_properties(${TEST_MAIN} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
add_test(
NAME ${RENDERLIB_NAME}.${TEST_MAIN}
COMMAND ${TEST_MAIN} ${TEST_RUNNER_PARAMS})
|
arhix52/Strelka/tests/materialmanager/test_materialmanager.cpp | #include <materialmanager/materialmanager.h>
// #include <render/render.h>
#include <doctest/doctest.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <cassert>
using namespace oka;
namespace fs = std::filesystem;
TEST_CASE("mtlx to hlsl code gen test")
{
// static const char* DEFAULT_MTLX_DOC_1 =
// "<?xml version=\"1.0\"?>"
// "<materialx version=\"1.38\" colorspace=\"lin_rec709\">"
// " <UsdPreviewSurface name=\"SR_Invalid\" type=\"surfaceshader\">"
// " <input name=\"diffuseColor\" type=\"color3\" value=\"1.0, 0.0, 1.0\" />"
// " <input name=\"roughness\" type=\"float\" value=\"1.0\" />"
// " </UsdPreviewSurface>"
// " <surfacematerial name=\"invalid\" type=\"material\">"
// " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_Invalid\" />"
// " </surfacematerial>"
// "</materialx>";
static const char* DEFAULT_MTLX_DOC_1 =
"<?xml version=\"1.0\"?>"
"<materialx version=\"1.38\" colorspace=\"lin_rec709\">"
" <UsdPreviewSurface name=\"SR_default\" type=\"surfaceshader\">"
" <input name=\"diffuseColor\" type=\"color3\" value=\"0.18, 0.18, 0.18\" />"
" <input name=\"emissiveColor\" type=\"color3\" value=\"0, 0, 0\" />"
" <input name=\"useSpecularWorkflow\" type=\"integer\" value=\"0\" />"
" <input name=\"specularColor\" type=\"color3\" value=\"0, 0, 0\" />"
" <input name=\"metallic\" type=\"float\" value=\"0\" />"
" <input name=\"roughness\" type=\"float\" value=\"0.5\" />"
" <input name=\"clearcoat\" type=\"float\" value=\"0\" />"
" <input name=\"clearcoatRoughness\" type=\"float\" value=\"0.01\" />"
" <input name=\"opacity\" type=\"float\" value=\"1\" />"
" <input name=\"opacityThreshold\" type=\"float\" value=\"0\" />"
" <input name=\"ior\" type=\"float\" value=\"1.5\" />"
" <input name=\"normal\" type=\"vector3\" value=\"0, 0, 1\" />"
" <input name=\"displacement\" type=\"float\" value=\"0\" />"
" <input name=\"occlusion\" type=\"float\" value=\"1\" />"
" </UsdPreviewSurface>"
" <surfacematerial name=\"USD_Default\" type=\"material\">"
" <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_default\" />"
" </surfacematerial>"
"</materialx>";
static const char* DEFAULT_MTLX_DOC_2 =
"<?xml version=\"1.0\"?>"
"<materialx version=\"1.38\" colorspace=\"lin_rec709\">"
" <UsdPreviewSurface name=\"SR_Invalid\" type=\"surfaceshader\">"
" <input name=\"diffuseColor\" type=\"color3\" value=\"0.0, 0.0, 1.0\" />"
" <input name=\"roughness\" type=\"float\" value=\"1.0\" />"
" </UsdPreviewSurface>"
" <surfacematerial name=\"invalid\" type=\"material\">"
" <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"SR_Invalid\" />"
" </surfacematerial>"
"</materialx>";
using namespace std;
const fs::path cwd = fs::current_path();
cout << cwd.c_str() << endl;
std::string mdlFile = "material.mdl";
std::ofstream mdlMaterial(mdlFile.c_str());
MaterialManager* matMngr = new MaterialManager();
CHECK(matMngr);
const char* envUSDPath = std::getenv("USD_DIR");
if (!envUSDPath)
{
printf("Please, set USD_DIR variable\n");
assert(0);
}
const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\";
const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/" };
bool res = matMngr->addMdlSearchPath(paths, 2);
CHECK(res);
MaterialManager::Module* mdlModule = matMngr->createMtlxModule(DEFAULT_MTLX_DOC_1);
assert(mdlModule);
MaterialManager::MaterialInstance* materialInst = matMngr->createMaterialInstance(mdlModule, "");
assert(materialInst);
MaterialManager::CompiledMaterial* materialComp = matMngr->compileMaterial(materialInst);
assert(materialComp);
MaterialManager::Module* mdlModule2 = matMngr->createMtlxModule(DEFAULT_MTLX_DOC_2);
assert(mdlModule2);
MaterialManager::MaterialInstance* materialInst2 = matMngr->createMaterialInstance(mdlModule2, "");
assert(materialInst2);
MaterialManager::CompiledMaterial* materialComp2 = matMngr->compileMaterial(materialInst2);
assert(materialComp2);
MaterialManager::CompiledMaterial* materials[2] = { materialComp, materialComp2 };
// std::vector<MaterialManager::CompiledMaterial*> materials;
// materials.push_back(materialComp);
// materials.push_back(materialComp2);
const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials, 2);
CHECK(code);
const char* hlsl = matMngr->getShaderCode(code, 0);
std::string shaderFile = "test_material_output.hlsl";
std::ofstream out(shaderFile.c_str());
out << hlsl << std::endl;
out.close();
delete matMngr;
}
TEST_CASE("MDL OmniPBR")
{
using namespace std;
const fs::path cwd = fs::current_path();
cout << cwd.c_str() << endl;
std::string mdlFile = "C:\\work\\StrelkaOptix\\build\\data\\materials\\mtlx\\OmniPBR.mdl";
// std::ofstream mdlMaterial(mdlFile.c_str());
MaterialManager* matMngr = new MaterialManager();
CHECK(matMngr);
const char* envUSDPath = std::getenv("USD_DIR");
if (!envUSDPath)
{
printf("Please, set USD_DIR variable\n");
assert(0);
}
const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\";
const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/",
"C:\\work\\StrelkaOptix\\build\\data\\materials\\mtlx\\",
"C:\\work\\Strelka\\misc\\test_data\\mdl" };
bool res = matMngr->addMdlSearchPath(paths, 4);
CHECK(res);
MaterialManager::Module* currModule = matMngr->createModule(mdlFile.c_str());
CHECK(currModule);
MaterialManager::MaterialInstance* materialInst1 = matMngr->createMaterialInstance(currModule, "OmniPBR");
CHECK(materialInst1);
MaterialManager::CompiledMaterial* materialComp1 = matMngr->compileMaterial(materialInst1);
CHECK(materialComp1);
MaterialManager::CompiledMaterial* materials[1] = { materialComp1 };
const MaterialManager::TargetCode* targetCode = matMngr->generateTargetCode(materials, 1);
CHECK(targetCode);
const char* ptx = matMngr->getShaderCode(targetCode, 0);
string ptxFileName = cwd.string() + "/output.ptx";
ofstream outPtxFile(ptxFileName.c_str());
outPtxFile << ptx << endl;
outPtxFile.close();
delete matMngr;
}
// TEST_CASE("mdl to hlsl code gen test")
// {
// using namespace std;
// const fs::path cwd = fs::current_path();
// cout << cwd.c_str() << endl;
// std::string ptFile = cwd.string() + "/output.ptx";
// std::ofstream outHLSLShaderFile(ptFile.c_str());
// // Render r;
// // r.HEIGHT = 600;
// // r.WIDTH = 800;
// // r.initWindow();
// // r.initVulkan();
// MaterialManager* matMngr = new MaterialManager();
// CHECK(matMngr);
// const char* envUSDPath = std::getenv("USD_DIR");
// if (!envUSDPath)
// {
// printf("Please, set USD_DIR variable\n");
// assert(0);
// }
// const std::string usdMdlLibPath = std::string(envUSDPath) + "\\libraries\\mdl\\";
// const char* paths[] = { usdMdlLibPath.c_str(), "./data/materials/mtlx/" };
// bool res = matMngr->addMdlSearchPath(paths, 2);
// CHECK(res);
// MaterialManager::Module* defaultModule = matMngr->createModule("default.mdl");
// CHECK(defaultModule);
// MaterialManager::MaterialInstance* materialInst0 = matMngr->createMaterialInstance(defaultModule, "default_material");
// CHECK(materialInst0);
// MaterialManager::CompiledMaterial* materialComp0 = matMngr->compileMaterial(materialInst0);
// CHECK(materialComp0);
// MaterialManager::CompiledMaterial* materialComp00 = matMngr->compileMaterial(materialInst0);
// CHECK(materialComp00);
// MaterialManager::CompiledMaterial* materialComp000 = matMngr->compileMaterial(materialInst0);
// CHECK(materialComp000);
// MaterialManager::Module* currModule = matMngr->createModule("OmniGlass.mdl");
// CHECK(currModule);
// MaterialManager::MaterialInstance* materialInst1 = matMngr->createMaterialInstance(currModule, "OmniGlass");
// CHECK(materialInst1);
// MaterialManager::CompiledMaterial* materialComp1 = matMngr->compileMaterial(materialInst1);
// CHECK(materialComp1);
// MaterialManager::CompiledMaterial* materialsDefault[1] = { materialComp0 };
// // const MaterialManager::TargetCode* codeDefault = matMngr->generateTargetCode(materialsDefault, 1);
// // CHECK(codeDefault);
// MaterialManager::CompiledMaterial* materials[4] = { materialComp0, materialComp00, materialComp1, materialComp000 };
// const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials, 4);
// CHECK(code);
// const char* hlsl = matMngr->getShaderCode(code);
// // std::cout << hlsl << std::endl;
// uint32_t size = matMngr->getArgBufferSize(code);
// CHECK(size != 0);
// size = matMngr->getArgBufferSize(code);
// CHECK(size != 0);
// size = matMngr->getResourceInfoSize(code);
// CHECK(size != 0);
// matMngr->dumpParams(code, materialComp1);
// // nevk::TextureManager* mTexManager = new nevk::TextureManager(r.getDevice(), r.getPhysicalDevice(),
// // r.getResManager());
// uint32_t texSize = matMngr->getTextureCount(code);
// // CHECK(texSize == 8);
// // for (uint32_t i = 0; i < texSize; ++i)
// // {
// // const float* data = matMngr->getTextureData(code, i);
// // uint32_t width = matMngr->getTextureWidth(code, i);
// // uint32_t height = matMngr->getTextureHeight(code, i);
// // const char* type = matMngr->getTextureType(code, i);
// // std::string name = matMngr->getTextureName(code, i);
// // // mTexManager->loadTextureMdl(data, width, height, type, name);
// // }
// // CHECK(mTexManager->textures.size() == 7);
// // CHECK(mTexManager->textures[0].texWidth == 512);
// // CHECK(mTexManager->textures[0].texHeight == 512);
// delete matMngr;
// }
// TEST_CASE("mtlx to mdl code gen test")
// {
// using namespace std;
// const fs::path cwd = fs::current_path();
// cout << cwd.c_str() << endl;
// std::string mdlFile = "material.mdl";
// std::ofstream mdlMaterial(mdlFile.c_str());
// std::string ptFile = cwd.string() + "/shaders/newPT.hlsl";
// std::ofstream outHLSLShaderFile(ptFile.c_str());
// Render r;
// r.HEIGHT = 600;
// r.WIDTH = 800;
// r.initWindow();
// r.initVulkan();
// MaterialManager* matMngr = new MaterialManager();
// CHECK(matMngr);
// const char* path[2] = { "misc/test_data/mdl/", "misc/test_data/mtlx" }; // todo: configure paths
// bool res = matMngr->addMdlSearchPath(path, 2);
// CHECK(res);
// std::string file = "misc/test_data/mtlx/standard_surface_wood_tiled.mtlx";
// std::unique_ptr<MaterialManager::Module> currModule = matMngr->createMtlxModule(file.c_str());
// CHECK(currModule);
// std::unique_ptr<MaterialManager::MaterialInstance> materialInst1 =
// matMngr->createMaterialInstance(currModule.get(), ""); CHECK(materialInst1);
// std::unique_ptr<MaterialManager::CompiledMaterial> materialComp1 = matMngr->compileMaterial(materialInst1.get());
// CHECK(materialComp1);
// std::vector<std::unique_ptr<MaterialManager::CompiledMaterial>> materials;
// materials.push_back(std::move(materialComp1));
// const MaterialManager::TargetCode* code = matMngr->generateTargetCode(materials);
// CHECK(code);
// const char* hlsl = matMngr->getShaderCode(code);
// //std::cout << hlsl << std::endl;
// uint32_t size = matMngr->getArgBufferSize(code);
// CHECK(size != 0);
// size = matMngr->getArgBufferSize(code);
// CHECK(size != 0);
// size = matMngr->getResourceInfoSize(code);
// CHECK(size != 0);
// nevk::TextureManager* mTexManager = new nevk::TextureManager(r.getDevice(), r.getPhysicalDevice(),
// r.getResManager()); uint32_t texSize = matMngr->getTextureCount(code); for (uint32_t i = 1; i < texSize; ++i)
// {
// const float* data = matMngr->getTextureData(code, i);
// uint32_t width = matMngr->getTextureWidth(code, i);
// uint32_t height = matMngr->getTextureHeight(code, i);
// const char* type = matMngr->getTextureType(code, i);
// std::string name = matMngr->getTextureName(code, i);
// if (data != NULL) // todo: for bsdf_text data is NULL in COMPILATION_CLASS. in default class there is no
// bsdf_tex
// {
// mTexManager->loadTextureMdl(data, width, height, type, name);
// }
// }
// CHECK(mTexManager->textures.size() == 2);
// CHECK(mTexManager->textures[0].texWidth == 512);
// CHECK(mTexManager->textures[0].texHeight == 512);
// }
|
arhix52/Strelka/sutil/Quaternion.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include <sutil/Matrix.h>
//------------------------------------------------------------------------------
//
// Quaternion class
//
//------------------------------------------------------------------------------
namespace sutil
{
class Quaternion
{
public:
Quaternion()
{ q[0] = q[1] = q[2] = q[3] = 0.0; }
Quaternion( float w, float x, float y, float z )
{ q[0] = w; q[1] = x; q[2] = y; q[3] = z; }
Quaternion( const float3& from, const float3& to );
Quaternion( const Quaternion& a )
{ q[0] = a[0]; q[1] = a[1]; q[2] = a[2]; q[3] = a[3]; }
Quaternion ( float angle, const float3& axis );
// getters and setters
void setW(float _w) { q[0] = _w; }
void setX(float _x) { q[1] = _x; }
void setY(float _y) { q[2] = _y; }
void setZ(float _z) { q[3] = _z; }
float w() const { return q[0]; }
float x() const { return q[1]; }
float y() const { return q[2]; }
float z() const { return q[3]; }
Quaternion& operator-=(const Quaternion& r)
{ q[0] -= r[0]; q[1] -= r[1]; q[2] -= r[2]; q[3] -= r[3]; return *this; }
Quaternion& operator+=(const Quaternion& r)
{ q[0] += r[0]; q[1] += r[1]; q[2] += r[2]; q[3] += r[3]; return *this; }
Quaternion& operator*=(const Quaternion& r);
Quaternion& operator/=(const float a);
Quaternion conjugate()
{ return Quaternion( q[0], -q[1], -q[2], -q[3] ); }
void rotation( float& angle, float3& axis ) const;
void rotation( float& angle, float& x, float& y, float& z ) const;
Matrix4x4 rotationMatrix() const;
float& operator[](int i) { return q[i]; }
float operator[](int i)const { return q[i]; }
// l2 norm
float norm() const
{ return sqrtf(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]); }
float normalize();
private:
float q[4];
};
inline Quaternion::Quaternion( const float3& from, const float3& to )
{
const float3 c = cross( from, to );
q[0] = dot(from, to);
q[1] = c.x;
q[2] = c.y;
q[3] = c.z;
}
inline Quaternion::Quaternion( float angle, const float3& axis )
{
const float n = length( axis );
const float inverse = 1.0f/n;
const float3 naxis = axis*inverse;
const float s = sinf(angle/2.0f);
q[0] = naxis.x*s*inverse;
q[1] = naxis.y*s*inverse;
q[2] = naxis.z*s*inverse;
q[3] = cosf(angle/2.0f);
}
inline Quaternion& Quaternion::operator*=(const Quaternion& r)
{
float w = q[0]*r[0] - q[1]*r[1] - q[2]*r[2] - q[3]*r[3];
float x = q[0]*r[1] + q[1]*r[0] + q[2]*r[3] - q[3]*r[2];
float y = q[0]*r[2] + q[2]*r[0] + q[3]*r[1] - q[1]*r[3];
float z = q[0]*r[3] + q[3]*r[0] + q[1]*r[2] - q[2]*r[1];
q[0] = w;
q[1] = x;
q[2] = y;
q[3] = z;
return *this;
}
inline Quaternion& Quaternion::operator/=(const float a)
{
float inverse = 1.0f/a;
q[0] *= inverse;
q[1] *= inverse;
q[2] *= inverse;
q[3] *= inverse;
return *this;
}
inline void Quaternion::rotation( float& angle, float3& axis ) const
{
Quaternion n = *this;
n.normalize();
axis.x = n[1];
axis.y = n[2];
axis.z = n[3];
angle = 2.0f * acosf(n[0]);
}
inline void Quaternion::rotation(
float& angle,
float& x,
float& y,
float& z
) const
{
Quaternion n = *this;
n.normalize();
x = n[1];
y = n[2];
z = n[3];
angle = 2.0f * acosf(n[0]);
}
inline float Quaternion::normalize()
{
float n = norm();
float inverse = 1.0f/n;
q[0] *= inverse;
q[1] *= inverse;
q[2] *= inverse;
q[3] *= inverse;
return n;
}
inline Quaternion operator*(const float a, const Quaternion &r)
{ return Quaternion(a*r[0], a*r[1], a*r[2], a*r[3]); }
inline Quaternion operator*(const Quaternion &r, const float a)
{ return Quaternion(a*r[0], a*r[1], a*r[2], a*r[3]); }
inline Quaternion operator/(const Quaternion &r, const float a)
{
float inverse = 1.0f/a;
return Quaternion( r[0]*inverse, r[1]*inverse, r[2]*inverse, r[3]*inverse);
}
inline Quaternion operator/(const float a, const Quaternion &r)
{
float inverse = 1.0f/a;
return Quaternion( r[0]*inverse, r[1]*inverse, r[2]*inverse, r[3]*inverse);
}
inline Quaternion operator-(const Quaternion& l, const Quaternion& r)
{ return Quaternion(l[0]-r[0], l[1]-r[1], l[2]-r[2], l[3]-r[3]); }
inline bool operator==(const Quaternion& l, const Quaternion& r)
{ return ( l[0] == r[0] && l[1] == r[1] && l[2] == r[2] && l[3] == r[3] ); }
inline bool operator!=(const Quaternion& l, const Quaternion& r)
{ return !(l == r); }
inline Quaternion operator+(const Quaternion& l, const Quaternion& r)
{ return Quaternion(l[0]+r[0], l[1]+r[1], l[2]+r[2], l[3]+r[3]); }
inline Quaternion operator*(const Quaternion& l, const Quaternion& r)
{
float w = l[0]*r[0] - l[1]*r[1] - l[2]*r[2] - l[3]*r[3];
float x = l[0]*r[1] + l[1]*r[0] + l[2]*r[3] - l[3]*r[2];
float y = l[0]*r[2] + l[2]*r[0] + l[3]*r[1] - l[1]*r[3];
float z = l[0]*r[3] + l[3]*r[0] + l[1]*r[2] - l[2]*r[1];
return Quaternion( w, x, y, z );
}
inline float dot( const Quaternion& l, const Quaternion& r )
{
return l.w()*r.w() + l.x()*r.x() + l.y()*r.y() + l.z()*r.z();
}
inline Matrix4x4 Quaternion::rotationMatrix() const
{
Matrix4x4 m;
const float qw = q[0];
const float qx = q[1];
const float qy = q[2];
const float qz = q[3];
m[0*4+0] = 1.0f - 2.0f*qy*qy - 2.0f*qz*qz;
m[0*4+1] = 2.0f*qx*qy - 2.0f*qz*qw;
m[0*4+2] = 2.0f*qx*qz + 2.0f*qy*qw;
m[0*4+3] = 0.0f;
m[1*4+0] = 2.0f*qx*qy + 2.0f*qz*qw;
m[1*4+1] = 1.0f - 2.0f*qx*qx - 2.0f*qz*qz;
m[1*4+2] = 2.0f*qy*qz - 2.0f*qx*qw;
m[1*4+3] = 0.0f;
m[2*4+0] = 2.0f*qx*qz - 2.0f*qy*qw;
m[2*4+1] = 2.0f*qy*qz + 2.0f*qx*qw;
m[2*4+2] = 1.0f - 2.0f*qx*qx - 2.0f*qy*qy;
m[2*4+3] = 0.0f;
m[3*4+0] = 0.0f;
m[3*4+1] = 0.0f;
m[3*4+2] = 0.0f;
m[3*4+3] = 1.0f;
return m;
}
} // end namespace sutil
|
arhix52/Strelka/sutil/Matrix.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include <sutil/sutilapi.h>
#include <sutil/Preprocessor.h>
#include <sutil/vec_math.h>
#if !defined(__CUDACC_RTC__)
#include <cmath>
#include <initializer_list>
#endif
#define RT_MATRIX_ACCESS(m,i,j) m[i*N+j]
#define RT_MAT_DECL template <unsigned int M, unsigned int N>
namespace sutil
{
template <int DIM> struct VectorDim { };
template <> struct VectorDim<2> { typedef float2 VectorType; };
template <> struct VectorDim<3> { typedef float3 VectorType; };
template <> struct VectorDim<4> { typedef float4 VectorType; };
template <unsigned int M, unsigned int N> class Matrix;
template <unsigned int M> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,M>& operator*=(Matrix<M,M>& m1, const Matrix<M,M>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator-=(Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator+=(Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& operator*=(Matrix<M,N>& m1, float f);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>&operator/=(Matrix<M,N>& m1, float f);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator-(const Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator+(const Matrix<M,N>& m1, const Matrix<M,N>& m2);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator/(const Matrix<M,N>& m, float f);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator*(const Matrix<M,N>& m, float f);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N> operator*(float f, const Matrix<M,N>& m);
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM operator*(const Matrix<M,N>& m, const typename Matrix<M,N>::floatN& v );
RT_MAT_DECL SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN operator*(const typename Matrix<M,N>::floatM& v, const Matrix<M,N>& m);
template<unsigned int M, unsigned int N, unsigned int R> SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,R> operator*(const Matrix<M,N>& m1, const Matrix<N,R>& m2);
// Partial specializations to make matrix vector multiplication more efficient
template <unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const Matrix<2,N>& m, const typename Matrix<2,N>::floatN& vec );
template <unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,N>& m, const typename Matrix<3,N>::floatN& vec );
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,4>& m, const float4& vec );
template <unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,N>& m, const typename Matrix<4,N>::floatN& vec );
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,4>& m, const float4& vec );
/**
* @brief A matrix with M rows and N columns
*
* @ingroup CUDACTypes
*
* <B>Description</B>
*
* @ref Matrix provides a utility class for small-dimension floating-point
* matrices, such as transformation matrices. @ref Matrix may also be useful
* in other computation and can be used in both host and device code.
* Typedefs are provided for 2x2 through 4x4 matrices.
*
*/
template <unsigned int M, unsigned int N>
class Matrix
{
public:
typedef typename VectorDim<N>::VectorType floatN; /// A row of the matrix
typedef typename VectorDim<M>::VectorType floatM; /// A column of the matrix
/** Create an uninitialized matrix */
SUTIL_HOSTDEVICE Matrix();
/** Create a matrix from the specified float array */
SUTIL_HOSTDEVICE explicit Matrix( const float data[M*N] ) { for(unsigned int i = 0; i < M*N; ++i) m_data[i] = data[i]; }
/** Copy the matrix */
SUTIL_HOSTDEVICE Matrix( const Matrix& m );
SUTIL_HOSTDEVICE Matrix( const std::initializer_list<float>& list );
/** Assignment operator */
SUTIL_HOSTDEVICE Matrix& operator=( const Matrix& b );
/** Access the specified element 0..N*M-1 */
SUTIL_HOSTDEVICE float operator[]( unsigned int i )const { return m_data[i]; }
/** Access the specified element 0..N*M-1 */
SUTIL_HOSTDEVICE float& operator[]( unsigned int i ) { return m_data[i]; }
/** Access the specified row 0..M. Returns float, float2, float3 or float4 depending on the matrix size */
SUTIL_HOSTDEVICE floatN getRow( unsigned int m )const;
/** Access the specified column 0..N. Returns float, float2, float3 or float4 depending on the matrix size */
SUTIL_HOSTDEVICE floatM getCol( unsigned int n )const;
/** Returns a pointer to the internal data array. The data array is stored in row-major order. */
SUTIL_HOSTDEVICE float* getData();
/** Returns a const pointer to the internal data array. The data array is stored in row-major order. */
SUTIL_HOSTDEVICE const float* getData()const;
/** Assign the specified row 0..M. Takes a float, float2, float3 or float4 depending on the matrix size */
SUTIL_HOSTDEVICE void setRow( unsigned int m, const floatN &r );
/** Assign the specified column 0..N. Takes a float, float2, float3 or float4 depending on the matrix size */
SUTIL_HOSTDEVICE void setCol( unsigned int n, const floatM &c );
/** Returns the transpose of the matrix */
SUTIL_HOSTDEVICE Matrix<N,M> transpose() const;
/** Returns the inverse of the matrix */
SUTIL_HOSTDEVICE Matrix<4,4> inverse() const;
/** Returns the determinant of the matrix */
SUTIL_HOSTDEVICE float det() const;
/** Returns a rotation matrix */
SUTIL_HOSTDEVICE static Matrix<4,4> rotate(const float radians, const float3& axis);
/** Returns a translation matrix */
SUTIL_HOSTDEVICE static Matrix<4,4> translate(const float3& vec);
/** Returns a scale matrix */
SUTIL_HOSTDEVICE static Matrix<4,4> scale(const float3& vec);
/** Creates a matrix from an ONB and center point */
SUTIL_HOSTDEVICE static Matrix<4,4> fromBasis( const float3& u, const float3& v, const float3& w, const float3& c );
/** Returns the identity matrix */
SUTIL_HOSTDEVICE static Matrix<3,4> affineIdentity();
SUTIL_HOSTDEVICE static Matrix<N,N> identity();
/** Ordered comparison operator so that the matrix can be used in an STL container */
SUTIL_HOSTDEVICE bool operator<( const Matrix<M, N>& rhs ) const;
private:
/** The data array is stored in row-major order */
float m_data[M*N];
};
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix()
{
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix( const Matrix<M,N>& m )
{
for(unsigned int i = 0; i < M*N; ++i)
m_data[i] = m[i];
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>::Matrix( const std::initializer_list<float>& list )
{
int i = 0;
for( auto it = list.begin(); it != list.end(); ++it )
m_data[ i++ ] = *it;
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<M,N>& Matrix<M,N>::operator=( const Matrix& b )
{
for(unsigned int i = 0; i < M*N; ++i)
m_data[i] = b[i];
return *this;
}
/*
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<M,N>::operator[]( unsigned int i )const
{
return m_data[i];
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float& Matrix<M,N>::operator[]( unsigned int i )
{
return m_data[i];
}
*/
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN Matrix<M,N>::getRow( unsigned int m )const
{
typename Matrix<M,N>::floatN temp;
float* v = reinterpret_cast<float*>( &temp );
const float* row = &( m_data[m*N] );
for(unsigned int i = 0; i < N; ++i)
v[i] = row[i];
return temp;
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM Matrix<M,N>::getCol( unsigned int n )const
{
typename Matrix<M,N>::floatM temp;
float* v = reinterpret_cast<float*>( &temp );
for ( unsigned int i = 0; i < M; ++i )
v[i] = RT_MATRIX_ACCESS( m_data, i, n );
return temp;
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float* Matrix<M,N>::getData()
{
return m_data;
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE const float* Matrix<M,N>::getData() const
{
return m_data;
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE void Matrix<M,N>::setRow( unsigned int m, const typename Matrix<M,N>::floatN &r )
{
const float* v = reinterpret_cast<const float*>( &r );
float* row = &( m_data[m*N] );
for(unsigned int i = 0; i < N; ++i)
row[i] = v[i];
}
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE void Matrix<M,N>::setCol( unsigned int n, const typename Matrix<M,N>::floatM &c )
{
const float* v = reinterpret_cast<const float*>( &c );
for ( unsigned int i = 0; i < M; ++i )
RT_MATRIX_ACCESS( m_data, i, n ) = v[i];
}
// Compare two matrices using exact float comparison
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE bool operator==(const Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
for ( unsigned int i = 0; i < M*N; ++i )
if ( m1[i] != m2[i] ) return false;
return true;
}
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE bool operator!=(const Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
for ( unsigned int i = 0; i < M*N; ++i )
if ( m1[i] != m2[i] ) return true;
return false;
}
// Subtract two matrices of the same size.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N> operator-(const Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
Matrix<M,N> temp( m1 );
temp -= m2;
return temp;
}
// Subtract two matrices of the same size.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N>& operator-=(Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
for ( unsigned int i = 0; i < M*N; ++i )
m1[i] -= m2[i];
return m1;
}
// Add two matrices of the same size.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N> operator+(const Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
Matrix<M,N> temp( m1 );
temp += m2;
return temp;
}
// Add two matrices of the same size.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N>& operator+=(Matrix<M,N>& m1, const Matrix<M,N>& m2)
{
for ( unsigned int i = 0; i < M*N; ++i )
m1[i] += m2[i];
return m1;
}
// Multiply two compatible matrices.
template<unsigned int M, unsigned int N, unsigned int R>
SUTIL_HOSTDEVICE Matrix<M,R> operator*( const Matrix<M,N>& m1, const Matrix<N,R>& m2)
{
Matrix<M,R> temp;
for ( unsigned int i = 0; i < M; ++i ) {
for ( unsigned int j = 0; j < R; ++j ) {
float sum = 0.0f;
for ( unsigned int k = 0; k < N; ++k ) {
float ik = m1[ i*N+k ];
float kj = m2[ k*R+j ];
sum += ik * kj;
}
temp[i*R+j] = sum;
}
}
return temp;
}
// Multiply two compatible matrices.
template<unsigned int M>
SUTIL_HOSTDEVICE Matrix<M,M>& operator*=(Matrix<M,M>& m1, const Matrix<M,M>& m2)
{
m1 = m1*m2;
return m1;
}
// Multiply matrix by vector
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE typename Matrix<M,N>::floatM operator*(const Matrix<M,N>& m, const typename Matrix<M,N>::floatN& vec )
{
typename Matrix<M,N>::floatM temp;
float* t = reinterpret_cast<float*>( &temp );
const float* v = reinterpret_cast<const float*>( &vec );
for (unsigned int i = 0; i < M; ++i) {
float sum = 0.0f;
for (unsigned int j = 0; j < N; ++j) {
sum += RT_MATRIX_ACCESS( m, i, j ) * v[j];
}
t[i] = sum;
}
return temp;
}
// Multiply matrix2xN by floatN
template<unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const Matrix<2,N>& m, const typename Matrix<2,N>::floatN& vec )
{
float2 temp = { 0.0f, 0.0f };
const float* v = reinterpret_cast<const float*>( &vec );
int index = 0;
for (unsigned int j = 0; j < N; ++j)
temp.x += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.y += m[index++] * v[j];
return temp;
}
// Multiply matrix3xN by floatN
template<unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,N>& m, const typename Matrix<3,N>::floatN& vec )
{
float3 temp = { 0.0f, 0.0f, 0.0f };
const float* v = reinterpret_cast<const float*>( &vec );
int index = 0;
for (unsigned int j = 0; j < N; ++j)
temp.x += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.y += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.z += m[index++] * v[j];
return temp;
}
// Multiply matrix4xN by floatN
template<unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,N>& m, const typename Matrix<4,N>::floatN& vec )
{
float4 temp = { 0.0f, 0.0f, 0.0f, 0.0f };
const float* v = reinterpret_cast<const float*>( &vec );
int index = 0;
for (unsigned int j = 0; j < N; ++j)
temp.x += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.y += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.z += m[index++] * v[j];
for (unsigned int j = 0; j < N; ++j)
temp.w += m[index++] * v[j];
return temp;
}
// Multiply matrix4x4 by float4
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const Matrix<3,4>& m, const float4& vec )
{
float3 temp;
temp.x = m[ 0] * vec.x +
m[ 1] * vec.y +
m[ 2] * vec.z +
m[ 3] * vec.w;
temp.y = m[ 4] * vec.x +
m[ 5] * vec.y +
m[ 6] * vec.z +
m[ 7] * vec.w;
temp.z = m[ 8] * vec.x +
m[ 9] * vec.y +
m[10] * vec.z +
m[11] * vec.w;
return temp;
}
// Multiply matrix4x4 by float4
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const Matrix<4,4>& m, const float4& vec )
{
float4 temp;
temp.x = m[ 0] * vec.x +
m[ 1] * vec.y +
m[ 2] * vec.z +
m[ 3] * vec.w;
temp.y = m[ 4] * vec.x +
m[ 5] * vec.y +
m[ 6] * vec.z +
m[ 7] * vec.w;
temp.z = m[ 8] * vec.x +
m[ 9] * vec.y +
m[10] * vec.z +
m[11] * vec.w;
temp.w = m[12] * vec.x +
m[13] * vec.y +
m[14] * vec.z +
m[15] * vec.w;
return temp;
}
// Multiply vector by matrix
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE typename Matrix<M,N>::floatN operator*(const typename Matrix<M,N>::floatM& vec, const Matrix<M,N>& m)
{
typename Matrix<M,N>::floatN temp;
float* t = reinterpret_cast<float*>( &temp );
const float* v = reinterpret_cast<const float*>( &vec);
for (unsigned int i = 0; i < N; ++i) {
float sum = 0.0f;
for (unsigned int j = 0; j < M; ++j) {
sum += v[j] * RT_MATRIX_ACCESS( m, j, i ) ;
}
t[i] = sum;
}
return temp;
}
// Multply matrix by a scalar.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N> operator*(const Matrix<M,N>& m, float f)
{
Matrix<M,N> temp( m );
temp *= f;
return temp;
}
// Multply matrix by a scalar.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N>& operator*=(Matrix<M,N>& m, float f)
{
for ( unsigned int i = 0; i < M*N; ++i )
m[i] *= f;
return m;
}
// Multply matrix by a scalar.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N> operator*(float f, const Matrix<M,N>& m)
{
Matrix<M,N> temp;
for ( unsigned int i = 0; i < M*N; ++i )
temp[i] = m[i]*f;
return temp;
}
// Divide matrix by a scalar.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N> operator/(const Matrix<M,N>& m, float f)
{
Matrix<M,N> temp( m );
temp /= f;
return temp;
}
// Divide matrix by a scalar.
template<unsigned int M, unsigned int N>
SUTIL_HOSTDEVICE Matrix<M,N>& operator/=(Matrix<M,N>& m, float f)
{
float inv_f = 1.0f / f;
for ( unsigned int i = 0; i < M*N; ++i )
m[i] *= inv_f;
return m;
}
// Returns the transpose of the matrix.
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<N,M> Matrix<M,N>::transpose() const
{
Matrix<N,M> ret;
for( unsigned int row = 0; row < M; ++row )
for( unsigned int col = 0; col < N; ++col )
ret[col*M+row] = m_data[row*N+col];
return ret;
}
// Returns the determinant of the matrix.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<3,3>::det() const
{
const float* m = m_data;
float d = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
- m[0]*m[5]*m[7] - m[1]*m[3]*m[8] - m[2]*m[4]*m[6];
return d;
}
// Returns the determinant of the matrix.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE float Matrix<4,4>::det() const
{
const float* m = m_data;
float d =
m[0]*m[5]*m[10]*m[15]-
m[0]*m[5]*m[11]*m[14]+m[0]*m[9]*m[14]*m[7]-
m[0]*m[9]*m[6]*m[15]+m[0]*m[13]*m[6]*m[11]-
m[0]*m[13]*m[10]*m[7]-m[4]*m[1]*m[10]*m[15]+m[4]*m[1]*m[11]*m[14]-
m[4]*m[9]*m[14]*m[3]+m[4]*m[9]*m[2]*m[15]-
m[4]*m[13]*m[2]*m[11]+m[4]*m[13]*m[10]*m[3]+m[8]*m[1]*m[6]*m[15]-
m[8]*m[1]*m[14]*m[7]+m[8]*m[5]*m[14]*m[3]-
m[8]*m[5]*m[2]*m[15]+m[8]*m[13]*m[2]*m[7]-
m[8]*m[13]*m[6]*m[3]-
m[12]*m[1]*m[6]*m[11]+m[12]*m[1]*m[10]*m[7]-
m[12]*m[5]*m[10]*m[3]+m[12]*m[5]*m[2]*m[11]-
m[12]*m[9]*m[2]*m[7]+m[12]*m[9]*m[6]*m[3];
return d;
}
// Returns the inverse of the matrix.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::inverse() const
{
Matrix<4,4> dst;
const float* m = m_data;
const float d = 1.0f / det();
dst[0] = d * (m[5] * (m[10] * m[15] - m[14] * m[11]) + m[9] * (m[14] * m[7] - m[6] * m[15]) + m[13] * (m[6] * m[11] - m[10] * m[7]));
dst[4] = d * (m[6] * (m[8] * m[15] - m[12] * m[11]) + m[10] * (m[12] * m[7] - m[4] * m[15]) + m[14] * (m[4] * m[11] - m[8] * m[7]));
dst[8] = d * (m[7] * (m[8] * m[13] - m[12] * m[9]) + m[11] * (m[12] * m[5] - m[4] * m[13]) + m[15] * (m[4] * m[9] - m[8] * m[5]));
dst[12] = d * (m[4] * (m[13] * m[10] - m[9] * m[14]) + m[8] * (m[5] * m[14] - m[13] * m[6]) + m[12] * (m[9] * m[6] - m[5] * m[10]));
dst[1] = d * (m[9] * (m[2] * m[15] - m[14] * m[3]) + m[13] * (m[10] * m[3] - m[2] * m[11]) + m[1] * (m[14] * m[11] - m[10] * m[15]));
dst[5] = d * (m[10] * (m[0] * m[15] - m[12] * m[3]) + m[14] * (m[8] * m[3] - m[0] * m[11]) + m[2] * (m[12] * m[11] - m[8] * m[15]));
dst[9] = d * (m[11] * (m[0] * m[13] - m[12] * m[1]) + m[15] * (m[8] * m[1] - m[0] * m[9]) + m[3] * (m[12] * m[9] - m[8] * m[13]));
dst[13] = d * (m[8] * (m[13] * m[2] - m[1] * m[14]) + m[12] * (m[1] * m[10] - m[9] * m[2]) + m[0] * (m[9] * m[14] - m[13] * m[10]));
dst[2] = d * (m[13] * (m[2] * m[7] - m[6] * m[3]) + m[1] * (m[6] * m[15] - m[14] * m[7]) + m[5] * (m[14] * m[3] - m[2] * m[15]));
dst[6] = d * (m[14] * (m[0] * m[7] - m[4] * m[3]) + m[2] * (m[4] * m[15] - m[12] * m[7]) + m[6] * (m[12] * m[3] - m[0] * m[15]));
dst[10] = d * (m[15] * (m[0] * m[5] - m[4] * m[1]) + m[3] * (m[4] * m[13] - m[12] * m[5]) + m[7] * (m[12] * m[1] - m[0] * m[13]));
dst[14] = d * (m[12] * (m[5] * m[2] - m[1] * m[6]) + m[0] * (m[13] * m[6] - m[5] * m[14]) + m[4] * (m[1] * m[14] - m[13] * m[2]));
dst[3] = d * (m[1] * (m[10] * m[7] - m[6] * m[11]) + m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[6] * m[3] - m[2] * m[7]));
dst[7] = d * (m[2] * (m[8] * m[7] - m[4] * m[11]) + m[6] * (m[0] * m[11] - m[8] * m[3]) + m[10] * (m[4] * m[3] - m[0] * m[7]));
dst[11] = d * (m[3] * (m[8] * m[5] - m[4] * m[9]) + m[7] * (m[0] * m[9] - m[8] * m[1]) + m[11] * (m[4] * m[1] - m[0] * m[5]));
dst[15] = d * (m[0] * (m[5] * m[10] - m[9] * m[6]) + m[4] * (m[9] * m[2] - m[1] * m[10]) + m[8] * (m[1] * m[6] - m[5] * m[2]));
return dst;
}
// Returns a rotation matrix.
// This is a static member.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::rotate(const float radians, const float3& axis)
{
Matrix<4,4> Mat = Matrix<4,4>::identity();
float *m = Mat.getData();
// NOTE: Element 0,1 is wrong in Foley and Van Dam, Pg 227!
float sintheta=sinf(radians);
float costheta=cosf(radians);
float ux=axis.x;
float uy=axis.y;
float uz=axis.z;
m[0*4+0]=ux*ux+costheta*(1-ux*ux);
m[0*4+1]=ux*uy*(1-costheta)-uz*sintheta;
m[0*4+2]=uz*ux*(1-costheta)+uy*sintheta;
m[0*4+3]=0;
m[1*4+0]=ux*uy*(1-costheta)+uz*sintheta;
m[1*4+1]=uy*uy+costheta*(1-uy*uy);
m[1*4+2]=uy*uz*(1-costheta)-ux*sintheta;
m[1*4+3]=0;
m[2*4+0]=uz*ux*(1-costheta)-uy*sintheta;
m[2*4+1]=uy*uz*(1-costheta)+ux*sintheta;
m[2*4+2]=uz*uz+costheta*(1-uz*uz);
m[2*4+3]=0;
m[3*4+0]=0;
m[3*4+1]=0;
m[3*4+2]=0;
m[3*4+3]=1;
return Matrix<4,4>( m );
}
// Returns a translation matrix.
// This is a static member.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::translate(const float3& vec)
{
Matrix<4,4> Mat = Matrix<4,4>::identity();
float *m = Mat.getData();
m[3] = vec.x;
m[7] = vec.y;
m[11]= vec.z;
return Matrix<4,4>( m );
}
// Returns a scale matrix.
// This is a static member.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::scale(const float3& vec)
{
Matrix<4,4> Mat = Matrix<4,4>::identity();
float *m = Mat.getData();
m[0] = vec.x;
m[5] = vec.y;
m[10]= vec.z;
return Matrix<4,4>( m );
}
// This is a static member.
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<4,4> Matrix<4,4>::fromBasis( const float3& u, const float3& v, const float3& w, const float3& c )
{
float m[16];
m[ 0] = u.x;
m[ 1] = v.x;
m[ 2] = w.x;
m[ 3] = c.x;
m[ 4] = u.y;
m[ 5] = v.y;
m[ 6] = w.y;
m[ 7] = c.y;
m[ 8] = u.z;
m[ 9] = v.z;
m[10] = w.z;
m[11] = c.z;
m[12] = 0.0f;
m[13] = 0.0f;
m[14] = 0.0f;
m[15] = 1.0f;
return Matrix<4,4>( m );
}
template<>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<3,4> Matrix<3,4>::affineIdentity()
{
Matrix<3,4> m;
m.m_data[ 0] = 1.0f;
m.m_data[ 1] = 0.0f;
m.m_data[ 2] = 0.0f;
m.m_data[ 3] = 0.0f;
m.m_data[ 4] = 0.0f;
m.m_data[ 5] = 1.0f;
m.m_data[ 6] = 0.0f;
m.m_data[ 7] = 0.0f;
m.m_data[ 8] = 0.0f;
m.m_data[ 9] = 0.0f;
m.m_data[10] = 1.0f;
m.m_data[11] = 0.0f;
return m;
}
// Returns the identity matrix.
// This is a static member.
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<N,N> Matrix<M,N>::identity()
{
float temp[N*N];
for(unsigned int i = 0; i < N*N; ++i)
temp[i] = 0;
for( unsigned int i = 0; i < N; ++i )
RT_MATRIX_ACCESS( temp,i,i ) = 1.0f;
return Matrix<N,N>( temp );
}
// Ordered comparison operator so that the matrix can be used in an STL container.
template<unsigned int M, unsigned int N>
SUTIL_INLINE SUTIL_HOSTDEVICE bool Matrix<M,N>::operator<( const Matrix<M, N>& rhs ) const
{
for( unsigned int i = 0; i < N*M; ++i ) {
if( m_data[i] < rhs[i] )
return true;
else if( m_data[i] > rhs[i] )
return false;
}
return false;
}
typedef Matrix<2, 2> Matrix2x2;
typedef Matrix<2, 3> Matrix2x3;
typedef Matrix<2, 4> Matrix2x4;
typedef Matrix<3, 2> Matrix3x2;
typedef Matrix<3, 3> Matrix3x3;
typedef Matrix<3, 4> Matrix3x4;
typedef Matrix<4, 2> Matrix4x2;
typedef Matrix<4, 3> Matrix4x3;
typedef Matrix<4, 4> Matrix4x4;
SUTIL_INLINE SUTIL_HOSTDEVICE Matrix<3,3> make_matrix3x3(const Matrix<4,4> &matrix)
{
Matrix<3,3> Mat;
float *m = Mat.getData();
const float *m4x4 = matrix.getData();
m[0*3+0]=m4x4[0*4+0];
m[0*3+1]=m4x4[0*4+1];
m[0*3+2]=m4x4[0*4+2];
m[1*3+0]=m4x4[1*4+0];
m[1*3+1]=m4x4[1*4+1];
m[1*3+2]=m4x4[1*4+2];
m[2*3+0]=m4x4[2*4+0];
m[2*3+1]=m4x4[2*4+1];
m[2*3+2]=m4x4[2*4+2];
return Mat;
}
} // end namespace sutil
#undef RT_MATRIX_ACCESS
#undef RT_MAT_DECL
|
arhix52/Strelka/sutil/Preprocessor.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#if defined(__CUDACC__) || defined(__CUDABE__)
# define SUTIL_HOSTDEVICE __host__ __device__
# define SUTIL_INLINE __forceinline__
# define CONST_STATIC_INIT( ... )
#else
# define SUTIL_HOSTDEVICE
# define SUTIL_INLINE inline
# define CONST_STATIC_INIT( ... ) = __VA_ARGS__
#endif
|
arhix52/Strelka/sutil/sutilapi.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#ifndef SUTILAPI
# if sutil_7_sdk_EXPORTS /* Set by CMAKE */
# if defined( _WIN32 ) || defined( _WIN64 )
# define SUTILAPI __declspec(dllexport)
# define SUTILCLASSAPI
# elif defined( linux ) || defined( __linux__ ) || defined ( __CYGWIN__ )
# define SUTILAPI __attribute__ ((visibility ("default")))
# define SUTILCLASSAPI SUTILAPI
# elif defined( __APPLE__ ) && defined( __MACH__ )
# define SUTILAPI __attribute__ ((visibility ("default")))
# define SUTILCLASSAPI SUTILAPI
# else
# error "CODE FOR THIS OS HAS NOT YET BEEN DEFINED"
# endif
# else /* sutil_7_sdk_EXPORTS */
# if defined( _WIN32 ) || defined( _WIN64 )
# define SUTILAPI __declspec(dllimport)
# define SUTILCLASSAPI
# elif defined( linux ) || defined( __linux__ ) || defined ( __CYGWIN__ )
# define SUTILAPI __attribute__ ((visibility ("default")))
# define SUTILCLASSAPI SUTILAPI
# elif defined( __APPLE__ ) && defined( __MACH__ )
# define SUTILAPI __attribute__ ((visibility ("default")))
# define SUTILCLASSAPI SUTILAPI
# elif defined( __CUDACC_RTC__ )
# define SUTILAPI
# define SUTILCLASSAPI
# else
# error "CODE FOR THIS OS HAS NOT YET BEEN DEFINED"
# endif
# endif /* sutil_7_sdk_EXPORTS */
#endif
|
arhix52/Strelka/sutil/vec_math.h | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include <sutil/Preprocessor.h>
#include <vector_functions.h>
#include <vector_types.h>
#if !defined(__CUDACC_RTC__)
#include <cmath>
#include <cstdlib>
#endif
/* scalar functions used in vector functions */
#ifndef M_PIf
#define M_PIf 3.14159265358979323846f
#endif
#ifndef M_PI_2f
#define M_PI_2f 1.57079632679489661923f
#endif
#ifndef M_1_PIf
#define M_1_PIf 0.318309886183790671538f
#endif
#if !defined(__CUDACC__)
SUTIL_INLINE SUTIL_HOSTDEVICE int max(int a, int b)
{
return a > b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE int min(int a, int b)
{
return a < b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE long long max(long long a, long long b)
{
return a > b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE long long min(long long a, long long b)
{
return a < b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int max(unsigned int a, unsigned int b)
{
return a > b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int min(unsigned int a, unsigned int b)
{
return a < b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long max(unsigned long long a, unsigned long long b)
{
return a > b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long min(unsigned long long a, unsigned long long b)
{
return a < b ? a : b;
}
SUTIL_INLINE SUTIL_HOSTDEVICE float min(const float a, const float b)
{
return a < b ? a : b;
}
/** lerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float lerp(const float a, const float b, const float t)
{
return a + t*(b-a);
}
/** bilerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float bilerp(const float x00, const float x10, const float x01, const float x11,
const float u, const float v)
{
return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v );
}
template <typename IntegerType>
SUTIL_INLINE SUTIL_HOSTDEVICE IntegerType roundUp(IntegerType x, IntegerType y)
{
return ( ( x + y - 1 ) / y ) * y;
}
#endif
/** clamp */
SUTIL_INLINE SUTIL_HOSTDEVICE float clamp( const float f, const float a, const float b )
{
return fmaxf( a, fminf( f, b ) );
}
/* float2 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float s)
{
return make_float2(s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const int2& a)
{
return make_float2(float(a.x), float(a.y));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const uint2& a)
{
return make_float2(float(a.x), float(a.y));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a)
{
return make_float2(-a.x, -a.y);
}
/** min
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 fminf(const float2& a, const float2& b)
{
return make_float2(fminf(a.x,b.x), fminf(a.y,b.y));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float2& a)
{
return fminf(a.x, a.y);
}
/** @} */
/** max
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 fmaxf(const float2& a, const float2& b)
{
return make_float2(fmaxf(a.x,b.x), fmaxf(a.y,b.y));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float2& a)
{
return fmaxf(a.x, a.y);
}
/** @} */
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float2& a, const float2& b)
{
return make_float2(a.x + b.x, a.y + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float2& a, const float b)
{
return make_float2(a.x + b, a.y + b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator+(const float a, const float2& b)
{
return make_float2(a + b.x, a + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float2& a, const float2& b)
{
a.x += b.x; a.y += b.y;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a, const float2& b)
{
return make_float2(a.x - b.x, a.y - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float2& a, const float b)
{
return make_float2(a.x - b, a.y - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator-(const float a, const float2& b)
{
return make_float2(a - b.x, a - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float2& a, const float2& b)
{
a.x -= b.x; a.y -= b.y;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float2& a, const float2& b)
{
return make_float2(a.x * b.x, a.y * b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float2& a, const float s)
{
return make_float2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator*(const float s, const float2& a)
{
return make_float2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float2& a, const float2& s)
{
a.x *= s.x; a.y *= s.y;
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float2& a, const float s)
{
a.x *= s; a.y *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float2& a, const float2& b)
{
return make_float2(a.x / b.x, a.y / b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float2& a, const float s)
{
float inv = 1.0f / s;
return a * inv;
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 operator/(const float s, const float2& a)
{
return make_float2( s/a.x, s/a.y );
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float2& a, const float s)
{
float inv = 1.0f / s;
a *= inv;
}
/** @} */
/** lerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 lerp(const float2& a, const float2& b, const float t)
{
return a + t*(b-a);
}
/** bilerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 bilerp(const float2& x00, const float2& x10, const float2& x01, const float2& x11,
const float u, const float v)
{
return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v );
}
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float2 clamp(const float2& v, const float a, const float b)
{
return make_float2(clamp(v.x, a, b), clamp(v.y, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float2 clamp(const float2& v, const float2& a, const float2& b)
{
return make_float2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y));
}
/** @} */
/** dot product */
SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float2& a, const float2& b)
{
return a.x * b.x + a.y * b.y;
}
/** length */
SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float2& v)
{
return sqrtf(dot(v, v));
}
/** normalize */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 normalize(const float2& v)
{
float invLen = 1.0f / sqrtf(dot(v, v));
return v * invLen;
}
/** floor */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 floor(const float2& v)
{
return make_float2(::floorf(v.x), ::floorf(v.y));
}
/** reflect */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 reflect(const float2& i, const float2& n)
{
return i - 2.0f * n * dot(n,i);
}
/** Faceforward
* Returns N if dot(i, nref) > 0; else -N;
* Typical usage is N = faceforward(N, -ray.dir, N);
* Note that this is opposite of what faceforward does in Cg and GLSL */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 faceforward(const float2& n, const float2& i, const float2& nref)
{
return n * copysignf( 1.0f, dot(i, nref) );
}
/** exp */
SUTIL_INLINE SUTIL_HOSTDEVICE float2 expf(const float2& v)
{
return make_float2(::expf(v.x), ::expf(v.y));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float2& v, int i)
{
return ((float*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float2& v, int i, float x)
{
((float*)(&v))[i] = x;
}
/* float3 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float s)
{
return make_float3(s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float2& a)
{
return make_float3(a.x, a.y, 0.0f);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const int3& a)
{
return make_float3(float(a.x), float(a.y), float(a.z));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const uint3& a)
{
return make_float3(float(a.x), float(a.y), float(a.z));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a)
{
return make_float3(-a.x, -a.y, -a.z);
}
/** min
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 fminf(const float3& a, const float3& b)
{
return make_float3(fminf(a.x,b.x), fminf(a.y,b.y), fminf(a.z,b.z));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float3& a)
{
return fminf(fminf(a.x, a.y), a.z);
}
/** @} */
/** max
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 fmaxf(const float3& a, const float3& b)
{
return make_float3(fmaxf(a.x,b.x), fmaxf(a.y,b.y), fmaxf(a.z,b.z));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float3& a)
{
return fmaxf(fmaxf(a.x, a.y), a.z);
}
/** @} */
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float3& a, const float3& b)
{
return make_float3(a.x + b.x, a.y + b.y, a.z + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float3& a, const float b)
{
return make_float3(a.x + b, a.y + b, a.z + b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator+(const float a, const float3& b)
{
return make_float3(a + b.x, a + b.y, a + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float3& a, const float3& b)
{
a.x += b.x; a.y += b.y; a.z += b.z;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a, const float3& b)
{
return make_float3(a.x - b.x, a.y - b.y, a.z - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float3& a, const float b)
{
return make_float3(a.x - b, a.y - b, a.z - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator-(const float a, const float3& b)
{
return make_float3(a - b.x, a - b.y, a - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float3& a, const float3& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float3& a, const float3& b)
{
return make_float3(a.x * b.x, a.y * b.y, a.z * b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float3& a, const float s)
{
return make_float3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator*(const float s, const float3& a)
{
return make_float3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float3& a, const float3& s)
{
a.x *= s.x; a.y *= s.y; a.z *= s.z;
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float3& a, const float s)
{
a.x *= s; a.y *= s; a.z *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float3& a, const float3& b)
{
return make_float3(a.x / b.x, a.y / b.y, a.z / b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float3& a, const float s)
{
float inv = 1.0f / s;
return a * inv;
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 operator/(const float s, const float3& a)
{
return make_float3( s/a.x, s/a.y, s/a.z );
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float3& a, const float s)
{
float inv = 1.0f / s;
a *= inv;
}
/** @} */
/** lerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 lerp(const float3& a, const float3& b, const float t)
{
return a + t*(b-a);
}
/** bilerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 bilerp(const float3& x00, const float3& x10, const float3& x01, const float3& x11,
const float u, const float v)
{
return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v );
}
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float3 clamp(const float3& v, const float a, const float b)
{
return make_float3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 clamp(const float3& v, const float3& a, const float3& b)
{
return make_float3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z));
}
/** @} */
/** dot product */
SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float3& a, const float3& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
/** cross product */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 cross(const float3& a, const float3& b)
{
return make_float3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
}
/** length */
SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float3& v)
{
return sqrtf(dot(v, v));
}
/** normalize */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 normalize(const float3& v)
{
float invLen = 1.0f / sqrtf(dot(v, v));
return v * invLen;
}
/** floor */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 floor(const float3& v)
{
return make_float3(::floorf(v.x), ::floorf(v.y), ::floorf(v.z));
}
/** reflect */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 reflect(const float3& i, const float3& n)
{
return i - 2.0f * n * dot(n,i);
}
/** Faceforward
* Returns N if dot(i, nref) > 0; else -N;
* Typical usage is N = faceforward(N, -ray.dir, N);
* Note that this is opposite of what faceforward does in Cg and GLSL */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 faceforward(const float3& n, const float3& i, const float3& nref)
{
return n * copysignf( 1.0f, dot(i, nref) );
}
/** exp */
SUTIL_INLINE SUTIL_HOSTDEVICE float3 expf(const float3& v)
{
return make_float3(::expf(v.x), ::expf(v.y), ::expf(v.z));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float3& v, int i)
{
return ((float*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float3& v, int i, float x)
{
((float*)(&v))[i] = x;
}
/* float4 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float s)
{
return make_float4(s, s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& a)
{
return make_float4(a.x, a.y, a.z, 0.0f);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const int4& a)
{
return make_float4(float(a.x), float(a.y), float(a.z), float(a.w));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const uint4& a)
{
return make_float4(float(a.x), float(a.y), float(a.z), float(a.w));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a)
{
return make_float4(-a.x, -a.y, -a.z, -a.w);
}
/** min
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 fminf(const float4& a, const float4& b)
{
return make_float4(fminf(a.x,b.x), fminf(a.y,b.y), fminf(a.z,b.z), fminf(a.w,b.w));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fminf(const float4& a)
{
return fminf(fminf(a.x, a.y), fminf(a.z, a.w));
}
/** @} */
/** max
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 fmaxf(const float4& a, const float4& b)
{
return make_float4(fmaxf(a.x,b.x), fmaxf(a.y,b.y), fmaxf(a.z,b.z), fmaxf(a.w,b.w));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float fmaxf(const float4& a)
{
return fmaxf(fmaxf(a.x, a.y), fmaxf(a.z, a.w));
}
/** @} */
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float4& a, const float4& b)
{
return make_float4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float4& a, const float b)
{
return make_float4(a.x + b, a.y + b, a.z + b, a.w + b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator+(const float a, const float4& b)
{
return make_float4(a + b.x, a + b.y, a + b.z, a + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(float4& a, const float4& b)
{
a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a, const float4& b)
{
return make_float4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float4& a, const float b)
{
return make_float4(a.x - b, a.y - b, a.z - b, a.w - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator-(const float a, const float4& b)
{
return make_float4(a - b.x, a - b.y, a - b.z, a - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(float4& a, const float4& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float4& a, const float4& s)
{
return make_float4(a.x * s.x, a.y * s.y, a.z * s.z, a.w * s.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float4& a, const float s)
{
return make_float4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator*(const float s, const float4& a)
{
return make_float4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float4& a, const float4& s)
{
a.x *= s.x; a.y *= s.y; a.z *= s.z; a.w *= s.w;
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(float4& a, const float s)
{
a.x *= s; a.y *= s; a.z *= s; a.w *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float4& a, const float4& b)
{
return make_float4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float4& a, const float s)
{
float inv = 1.0f / s;
return a * inv;
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 operator/(const float s, const float4& a)
{
return make_float4( s/a.x, s/a.y, s/a.z, s/a.w );
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(float4& a, const float s)
{
float inv = 1.0f / s;
a *= inv;
}
/** @} */
/** lerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 lerp(const float4& a, const float4& b, const float t)
{
return a + t*(b-a);
}
/** bilerp */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 bilerp(const float4& x00, const float4& x10, const float4& x01, const float4& x11,
const float u, const float v)
{
return lerp( lerp( x00, x10, u ), lerp( x01, x11, u ), v );
}
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 clamp(const float4& v, const float a, const float b)
{
return make_float4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE float4 clamp(const float4& v, const float4& a, const float4& b)
{
return make_float4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w));
}
/** @} */
/** dot product */
SUTIL_INLINE SUTIL_HOSTDEVICE float dot(const float4& a, const float4& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
/** length */
SUTIL_INLINE SUTIL_HOSTDEVICE float length(const float4& r)
{
return sqrtf(dot(r, r));
}
/** normalize */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 normalize(const float4& v)
{
float invLen = 1.0f / sqrtf(dot(v, v));
return v * invLen;
}
/** floor */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 floor(const float4& v)
{
return make_float4(::floorf(v.x), ::floorf(v.y), ::floorf(v.z), ::floorf(v.w));
}
/** reflect */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 reflect(const float4& i, const float4& n)
{
return i - 2.0f * n * dot(n,i);
}
/**
* Faceforward
* Returns N if dot(i, nref) > 0; else -N;
* Typical usage is N = faceforward(N, -ray.dir, N);
* Note that this is opposite of what faceforward does in Cg and GLSL
*/
SUTIL_INLINE SUTIL_HOSTDEVICE float4 faceforward(const float4& n, const float4& i, const float4& nref)
{
return n * copysignf( 1.0f, dot(i, nref) );
}
/** exp */
SUTIL_INLINE SUTIL_HOSTDEVICE float4 expf(const float4& v)
{
return make_float4(::expf(v.x), ::expf(v.y), ::expf(v.z), ::expf(v.w));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE float getByIndex(const float4& v, int i)
{
return ((float*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(float4& v, int i, float x)
{
((float*)(&v))[i] = x;
}
/* int functions */
/******************************************************************************/
/** clamp */
SUTIL_INLINE SUTIL_HOSTDEVICE int clamp(const int f, const int a, const int b)
{
return max(a, min(f, b));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int1& v, int i)
{
return ((int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int1& v, int i, int x)
{
((int*)(&v))[i] = x;
}
/* int2 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int s)
{
return make_int2(s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const float2& a)
{
return make_int2(int(a.x), int(a.y));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a)
{
return make_int2(-a.x, -a.y);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE int2 min(const int2& a, const int2& b)
{
return make_int2(min(a.x,b.x), min(a.y,b.y));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE int2 max(const int2& a, const int2& b)
{
return make_int2(max(a.x,b.x), max(a.y,b.y));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator+(const int2& a, const int2& b)
{
return make_int2(a.x + b.x, a.y + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int2& a, const int2& b)
{
a.x += b.x; a.y += b.y;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a, const int2& b)
{
return make_int2(a.x - b.x, a.y - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator-(const int2& a, const int b)
{
return make_int2(a.x - b, a.y - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int2& a, const int2& b)
{
a.x -= b.x; a.y -= b.y;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int2& a, const int2& b)
{
return make_int2(a.x * b.x, a.y * b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int2& a, const int s)
{
return make_int2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int2 operator*(const int s, const int2& a)
{
return make_int2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int2& a, const int s)
{
a.x *= s; a.y *= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 clamp(const int2& v, const int a, const int b)
{
return make_int2(clamp(v.x, a, b), clamp(v.y, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE int2 clamp(const int2& v, const int2& a, const int2& b)
{
return make_int2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int2& a, const int2& b)
{
return a.x == b.x && a.y == b.y;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int2& a, const int2& b)
{
return a.x != b.x || a.y != b.y;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int2& v, int i)
{
return ((int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int2& v, int i, int x)
{
((int*)(&v))[i] = x;
}
/* int3 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int s)
{
return make_int3(s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const float3& a)
{
return make_int3(int(a.x), int(a.y), int(a.z));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator-(const int3& a)
{
return make_int3(-a.x, -a.y, -a.z);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE int3 min(const int3& a, const int3& b)
{
return make_int3(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE int3 max(const int3& a, const int3& b)
{
return make_int3(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator+(const int3& a, const int3& b)
{
return make_int3(a.x + b.x, a.y + b.y, a.z + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int3& a, const int3& b)
{
a.x += b.x; a.y += b.y; a.z += b.z;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator-(const int3& a, const int3& b)
{
return make_int3(a.x - b.x, a.y - b.y, a.z - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int3& a, const int3& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int3& a, const int3& b)
{
return make_int3(a.x * b.x, a.y * b.y, a.z * b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int3& a, const int s)
{
return make_int3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator*(const int s, const int3& a)
{
return make_int3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int3& a, const int s)
{
a.x *= s; a.y *= s; a.z *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int3& a, const int3& b)
{
return make_int3(a.x / b.x, a.y / b.y, a.z / b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int3& a, const int s)
{
return make_int3(a.x / s, a.y / s, a.z / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 operator/(const int s, const int3& a)
{
return make_int3(s /a.x, s / a.y, s / a.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(int3& a, const int s)
{
a.x /= s; a.y /= s; a.z /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 clamp(const int3& v, const int a, const int b)
{
return make_int3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE int3 clamp(const int3& v, const int3& a, const int3& b)
{
return make_int3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int3& a, const int3& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int3& a, const int3& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int3& v, int i)
{
return ((int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int3& v, int i, int x)
{
((int*)(&v))[i] = x;
}
/* int4 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int s)
{
return make_int4(s, s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const float4& a)
{
return make_int4((int)a.x, (int)a.y, (int)a.z, (int)a.w);
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator-(const int4& a)
{
return make_int4(-a.x, -a.y, -a.z, -a.w);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE int4 min(const int4& a, const int4& b)
{
return make_int4(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z), min(a.w,b.w));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE int4 max(const int4& a, const int4& b)
{
return make_int4(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z), max(a.w,b.w));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator+(const int4& a, const int4& b)
{
return make_int4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(int4& a, const int4& b)
{
a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator-(const int4& a, const int4& b)
{
return make_int4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(int4& a, const int4& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int4& a, const int4& b)
{
return make_int4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int4& a, const int s)
{
return make_int4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator*(const int s, const int4& a)
{
return make_int4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(int4& a, const int s)
{
a.x *= s; a.y *= s; a.z *= s; a.w *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int4& a, const int4& b)
{
return make_int4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int4& a, const int s)
{
return make_int4(a.x / s, a.y / s, a.z / s, a.w / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 operator/(const int s, const int4& a)
{
return make_int4(s / a.x, s / a.y, s / a.z, s / a.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(int4& a, const int s)
{
a.x /= s; a.y /= s; a.z /= s; a.w /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int4 clamp(const int4& v, const int a, const int b)
{
return make_int4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE int4 clamp(const int4& v, const int4& a, const int4& b)
{
return make_int4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const int4& a, const int4& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const int4& a, const int4& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE int getByIndex(const int4& v, int i)
{
return ((int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(int4& v, int i, int x)
{
((int*)(&v))[i] = x;
}
/* uint functions */
/******************************************************************************/
/** clamp */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int clamp(const unsigned int f, const unsigned int a, const unsigned int b)
{
return max(a, min(f, b));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint1& v, unsigned int i)
{
return ((unsigned int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint1& v, int i, unsigned int x)
{
((unsigned int*)(&v))[i] = x;
}
/* uint2 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const unsigned int s)
{
return make_uint2(s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const float2& a)
{
return make_uint2((unsigned int)a.x, (unsigned int)a.y);
}
/** @} */
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 min(const uint2& a, const uint2& b)
{
return make_uint2(min(a.x,b.x), min(a.y,b.y));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 max(const uint2& a, const uint2& b)
{
return make_uint2(max(a.x,b.x), max(a.y,b.y));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator+(const uint2& a, const uint2& b)
{
return make_uint2(a.x + b.x, a.y + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint2& a, const uint2& b)
{
a.x += b.x; a.y += b.y;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator-(const uint2& a, const uint2& b)
{
return make_uint2(a.x - b.x, a.y - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator-(const uint2& a, const unsigned int b)
{
return make_uint2(a.x - b, a.y - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint2& a, const uint2& b)
{
a.x -= b.x; a.y -= b.y;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const uint2& a, const uint2& b)
{
return make_uint2(a.x * b.x, a.y * b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const uint2& a, const unsigned int s)
{
return make_uint2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 operator*(const unsigned int s, const uint2& a)
{
return make_uint2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint2& a, const unsigned int s)
{
a.x *= s; a.y *= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 clamp(const uint2& v, const unsigned int a, const unsigned int b)
{
return make_uint2(clamp(v.x, a, b), clamp(v.y, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 clamp(const uint2& v, const uint2& a, const uint2& b)
{
return make_uint2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint2& a, const uint2& b)
{
return a.x == b.x && a.y == b.y;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint2& a, const uint2& b)
{
return a.x != b.x || a.y != b.y;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint2& v, unsigned int i)
{
return ((unsigned int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint2& v, int i, unsigned int x)
{
((unsigned int*)(&v))[i] = x;
}
/* uint3 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const unsigned int s)
{
return make_uint3(s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const float3& a)
{
return make_uint3((unsigned int)a.x, (unsigned int)a.y, (unsigned int)a.z);
}
/** @} */
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 min(const uint3& a, const uint3& b)
{
return make_uint3(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 max(const uint3& a, const uint3& b)
{
return make_uint3(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator+(const uint3& a, const uint3& b)
{
return make_uint3(a.x + b.x, a.y + b.y, a.z + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint3& a, const uint3& b)
{
a.x += b.x; a.y += b.y; a.z += b.z;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator-(const uint3& a, const uint3& b)
{
return make_uint3(a.x - b.x, a.y - b.y, a.z - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint3& a, const uint3& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const uint3& a, const uint3& b)
{
return make_uint3(a.x * b.x, a.y * b.y, a.z * b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const uint3& a, const unsigned int s)
{
return make_uint3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator*(const unsigned int s, const uint3& a)
{
return make_uint3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint3& a, const unsigned int s)
{
a.x *= s; a.y *= s; a.z *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const uint3& a, const uint3& b)
{
return make_uint3(a.x / b.x, a.y / b.y, a.z / b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const uint3& a, const unsigned int s)
{
return make_uint3(a.x / s, a.y / s, a.z / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 operator/(const unsigned int s, const uint3& a)
{
return make_uint3(s / a.x, s / a.y, s / a.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(uint3& a, const unsigned int s)
{
a.x /= s; a.y /= s; a.z /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 clamp(const uint3& v, const unsigned int a, const unsigned int b)
{
return make_uint3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 clamp(const uint3& v, const uint3& a, const uint3& b)
{
return make_uint3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint3& a, const uint3& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint3& a, const uint3& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint3& v, unsigned int i)
{
return ((unsigned int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint3& v, int i, unsigned int x)
{
((unsigned int*)(&v))[i] = x;
}
/* uint4 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int s)
{
return make_uint4(s, s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const float4& a)
{
return make_uint4((unsigned int)a.x, (unsigned int)a.y, (unsigned int)a.z, (unsigned int)a.w);
}
/** @} */
/** min
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 min(const uint4& a, const uint4& b)
{
return make_uint4(min(a.x,b.x), min(a.y,b.y), min(a.z,b.z), min(a.w,b.w));
}
/** @} */
/** max
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 max(const uint4& a, const uint4& b)
{
return make_uint4(max(a.x,b.x), max(a.y,b.y), max(a.z,b.z), max(a.w,b.w));
}
/** @} */
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator+(const uint4& a, const uint4& b)
{
return make_uint4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(uint4& a, const uint4& b)
{
a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator-(const uint4& a, const uint4& b)
{
return make_uint4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(uint4& a, const uint4& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const uint4& a, const uint4& b)
{
return make_uint4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const uint4& a, const unsigned int s)
{
return make_uint4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator*(const unsigned int s, const uint4& a)
{
return make_uint4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(uint4& a, const unsigned int s)
{
a.x *= s; a.y *= s; a.z *= s; a.w *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const uint4& a, const uint4& b)
{
return make_uint4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const uint4& a, const unsigned int s)
{
return make_uint4(a.x / s, a.y / s, a.z / s, a.w / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 operator/(const unsigned int s, const uint4& a)
{
return make_uint4(s / a.x, s / a.y, s / a.z, s / a.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(uint4& a, const unsigned int s)
{
a.x /= s; a.y /= s; a.z /= s; a.w /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 clamp(const uint4& v, const unsigned int a, const unsigned int b)
{
return make_uint4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 clamp(const uint4& v, const uint4& a, const uint4& b)
{
return make_uint4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const uint4& a, const uint4& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const uint4& a, const uint4& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned int getByIndex(const uint4& v, unsigned int i)
{
return ((unsigned int*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(uint4& v, int i, unsigned int x)
{
((unsigned int*)(&v))[i] = x;
}
/* long long functions */
/******************************************************************************/
/** clamp */
SUTIL_INLINE SUTIL_HOSTDEVICE long long clamp(const long long f, const long long a, const long long b)
{
return max(a, min(f, b));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong1& v, int i)
{
return ((long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong1& v, int i, long long x)
{
((long long*)(&v))[i] = x;
}
/* longlong2 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const long long s)
{
return make_longlong2(s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const float2& a)
{
return make_longlong2(int(a.x), int(a.y));
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a)
{
return make_longlong2(-a.x, -a.y);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 min(const longlong2& a, const longlong2& b)
{
return make_longlong2(min(a.x, b.x), min(a.y, b.y));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 max(const longlong2& a, const longlong2& b)
{
return make_longlong2(max(a.x, b.x), max(a.y, b.y));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator+(const longlong2& a, const longlong2& b)
{
return make_longlong2(a.x + b.x, a.y + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong2& a, const longlong2& b)
{
a.x += b.x; a.y += b.y;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a, const longlong2& b)
{
return make_longlong2(a.x - b.x, a.y - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator-(const longlong2& a, const long long b)
{
return make_longlong2(a.x - b, a.y - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong2& a, const longlong2& b)
{
a.x -= b.x; a.y -= b.y;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const longlong2& a, const longlong2& b)
{
return make_longlong2(a.x * b.x, a.y * b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const longlong2& a, const long long s)
{
return make_longlong2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 operator*(const long long s, const longlong2& a)
{
return make_longlong2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong2& a, const long long s)
{
a.x *= s; a.y *= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 clamp(const longlong2& v, const long long a, const long long b)
{
return make_longlong2(clamp(v.x, a, b), clamp(v.y, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 clamp(const longlong2& v, const longlong2& a, const longlong2& b)
{
return make_longlong2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong2& a, const longlong2& b)
{
return a.x == b.x && a.y == b.y;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong2& a, const longlong2& b)
{
return a.x != b.x || a.y != b.y;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong2& v, int i)
{
return ((long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong2& v, int i, long long x)
{
((long long*)(&v))[i] = x;
}
/* longlong3 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const long long s)
{
return make_longlong3(s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const float3& a)
{
return make_longlong3( (long long)a.x, (long long)a.y, (long long)a.z);
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator-(const longlong3& a)
{
return make_longlong3(-a.x, -a.y, -a.z);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 min(const longlong3& a, const longlong3& b)
{
return make_longlong3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 max(const longlong3& a, const longlong3& b)
{
return make_longlong3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator+(const longlong3& a, const longlong3& b)
{
return make_longlong3(a.x + b.x, a.y + b.y, a.z + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong3& a, const longlong3& b)
{
a.x += b.x; a.y += b.y; a.z += b.z;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator-(const longlong3& a, const longlong3& b)
{
return make_longlong3(a.x - b.x, a.y - b.y, a.z - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong3& a, const longlong3& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const longlong3& a, const longlong3& b)
{
return make_longlong3(a.x * b.x, a.y * b.y, a.z * b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const longlong3& a, const long long s)
{
return make_longlong3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator*(const long long s, const longlong3& a)
{
return make_longlong3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong3& a, const long long s)
{
a.x *= s; a.y *= s; a.z *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const longlong3& a, const longlong3& b)
{
return make_longlong3(a.x / b.x, a.y / b.y, a.z / b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const longlong3& a, const long long s)
{
return make_longlong3(a.x / s, a.y / s, a.z / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 operator/(const long long s, const longlong3& a)
{
return make_longlong3(s /a.x, s / a.y, s / a.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(longlong3& a, const long long s)
{
a.x /= s; a.y /= s; a.z /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 clamp(const longlong3& v, const long long a, const long long b)
{
return make_longlong3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 clamp(const longlong3& v, const longlong3& a, const longlong3& b)
{
return make_longlong3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong3& a, const longlong3& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong3& a, const longlong3& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong3& v, int i)
{
return ((long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong3& v, int i, int x)
{
((long long*)(&v))[i] = x;
}
/* longlong4 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long s)
{
return make_longlong4(s, s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const float4& a)
{
return make_longlong4((long long)a.x, (long long)a.y, (long long)a.z, (long long)a.w);
}
/** @} */
/** negate */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator-(const longlong4& a)
{
return make_longlong4(-a.x, -a.y, -a.z, -a.w);
}
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 min(const longlong4& a, const longlong4& b)
{
return make_longlong4(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z), min(a.w, b.w));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 max(const longlong4& a, const longlong4& b)
{
return make_longlong4(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z), max(a.w, b.w));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator+(const longlong4& a, const longlong4& b)
{
return make_longlong4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(longlong4& a, const longlong4& b)
{
a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator-(const longlong4& a, const longlong4& b)
{
return make_longlong4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(longlong4& a, const longlong4& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const longlong4& a, const longlong4& b)
{
return make_longlong4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const longlong4& a, const long long s)
{
return make_longlong4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator*(const long long s, const longlong4& a)
{
return make_longlong4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(longlong4& a, const long long s)
{
a.x *= s; a.y *= s; a.z *= s; a.w *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const longlong4& a, const longlong4& b)
{
return make_longlong4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const longlong4& a, const long long s)
{
return make_longlong4(a.x / s, a.y / s, a.z / s, a.w / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 operator/(const long long s, const longlong4& a)
{
return make_longlong4(s / a.x, s / a.y, s / a.z, s / a.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(longlong4& a, const long long s)
{
a.x /= s; a.y /= s; a.z /= s; a.w /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 clamp(const longlong4& v, const long long a, const long long b)
{
return make_longlong4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 clamp(const longlong4& v, const longlong4& a, const longlong4& b)
{
return make_longlong4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const longlong4& a, const longlong4& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const longlong4& a, const longlong4& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE long long getByIndex(const longlong4& v, int i)
{
return ((long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(longlong4& v, int i, long long x)
{
((long long*)(&v))[i] = x;
}
/* ulonglong functions */
/******************************************************************************/
/** clamp */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long clamp(const unsigned long long f, const unsigned long long a, const unsigned long long b)
{
return max(a, min(f, b));
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong1& v, unsigned int i)
{
return ((unsigned long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong1& v, int i, unsigned long long x)
{
((unsigned long long*)(&v))[i] = x;
}
/* ulonglong2 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const unsigned long long s)
{
return make_ulonglong2(s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const float2& a)
{
return make_ulonglong2((unsigned long long)a.x, (unsigned long long)a.y);
}
/** @} */
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 min(const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(min(a.x, b.x), min(a.y, b.y));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 max(const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(max(a.x, b.x), max(a.y, b.y));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator+(const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(a.x + b.x, a.y + b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong2& a, const ulonglong2& b)
{
a.x += b.x; a.y += b.y;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator-(const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(a.x - b.x, a.y - b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator-(const ulonglong2& a, const unsigned long long b)
{
return make_ulonglong2(a.x - b, a.y - b);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong2& a, const ulonglong2& b)
{
a.x -= b.x; a.y -= b.y;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(a.x * b.x, a.y * b.y);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const ulonglong2& a, const unsigned long long s)
{
return make_ulonglong2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 operator*(const unsigned long long s, const ulonglong2& a)
{
return make_ulonglong2(a.x * s, a.y * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong2& a, const unsigned long long s)
{
a.x *= s; a.y *= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 clamp(const ulonglong2& v, const unsigned long long a, const unsigned long long b)
{
return make_ulonglong2(clamp(v.x, a, b), clamp(v.y, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 clamp(const ulonglong2& v, const ulonglong2& a, const ulonglong2& b)
{
return make_ulonglong2(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong2& a, const ulonglong2& b)
{
return a.x == b.x && a.y == b.y;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong2& a, const ulonglong2& b)
{
return a.x != b.x || a.y != b.y;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong2& v, unsigned int i)
{
return ((unsigned long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory */
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong2& v, int i, unsigned long long x)
{
((unsigned long long*)(&v))[i] = x;
}
/* ulonglong3 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const unsigned long long s)
{
return make_ulonglong3(s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const float3& a)
{
return make_ulonglong3((unsigned long long)a.x, (unsigned long long)a.y, (unsigned long long)a.z);
}
/** @} */
/** min */
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 min(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
}
/** max */
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 max(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
}
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator+(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(a.x + b.x, a.y + b.y, a.z + b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong3& a, const ulonglong3& b)
{
a.x += b.x; a.y += b.y; a.z += b.z;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator-(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(a.x - b.x, a.y - b.y, a.z - b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong3& a, const ulonglong3& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(a.x * b.x, a.y * b.y, a.z * b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const ulonglong3& a, const unsigned long long s)
{
return make_ulonglong3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator*(const unsigned long long s, const ulonglong3& a)
{
return make_ulonglong3(a.x * s, a.y * s, a.z * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong3& a, const unsigned long long s)
{
a.x *= s; a.y *= s; a.z *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(a.x / b.x, a.y / b.y, a.z / b.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const ulonglong3& a, const unsigned long long s)
{
return make_ulonglong3(a.x / s, a.y / s, a.z / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 operator/(const unsigned long long s, const ulonglong3& a)
{
return make_ulonglong3(s / a.x, s / a.y, s / a.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(ulonglong3& a, const unsigned long long s)
{
a.x /= s; a.y /= s; a.z /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 clamp(const ulonglong3& v, const unsigned long long a, const unsigned long long b)
{
return make_ulonglong3(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 clamp(const ulonglong3& v, const ulonglong3& a, const ulonglong3& b)
{
return make_ulonglong3(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong3& a, const ulonglong3& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong3& a, const ulonglong3& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong3& v, unsigned int i)
{
return ((unsigned long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong3& v, int i, unsigned long long x)
{
((unsigned long long*)(&v))[i] = x;
}
/* ulonglong4 functions */
/******************************************************************************/
/** additional constructors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long s)
{
return make_ulonglong4(s, s, s, s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const float4& a)
{
return make_ulonglong4((unsigned long long)a.x, (unsigned long long)a.y, (unsigned long long)a.z, (unsigned long long)a.w);
}
/** @} */
/** min
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 min(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z), min(a.w, b.w));
}
/** @} */
/** max
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 max(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z), max(a.w, b.w));
}
/** @} */
/** add
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator+(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator+=(ulonglong4& a, const ulonglong4& b)
{
a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w;
}
/** @} */
/** subtract
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator-(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator-=(ulonglong4& a, const ulonglong4& b)
{
a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w;
}
/** @} */
/** multiply
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const ulonglong4& a, const unsigned long long s)
{
return make_ulonglong4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator*(const unsigned long long s, const ulonglong4& a)
{
return make_ulonglong4(a.x * s, a.y * s, a.z * s, a.w * s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator*=(ulonglong4& a, const unsigned long long s)
{
a.x *= s; a.y *= s; a.z *= s; a.w *= s;
}
/** @} */
/** divide
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const ulonglong4& a, const unsigned long long s)
{
return make_ulonglong4(a.x / s, a.y / s, a.z / s, a.w / s);
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 operator/(const unsigned long long s, const ulonglong4& a)
{
return make_ulonglong4(s / a.x, s / a.y, s / a.z, s / a.w);
}
SUTIL_INLINE SUTIL_HOSTDEVICE void operator/=(ulonglong4& a, const unsigned long long s)
{
a.x /= s; a.y /= s; a.z /= s; a.w /= s;
}
/** @} */
/** clamp
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 clamp(const ulonglong4& v, const unsigned long long a, const unsigned long long b)
{
return make_ulonglong4(clamp(v.x, a, b), clamp(v.y, a, b), clamp(v.z, a, b), clamp(v.w, a, b));
}
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 clamp(const ulonglong4& v, const ulonglong4& a, const ulonglong4& b)
{
return make_ulonglong4(clamp(v.x, a.x, b.x), clamp(v.y, a.y, b.y), clamp(v.z, a.z, b.z), clamp(v.w, a.w, b.w));
}
/** @} */
/** equality
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator==(const ulonglong4& a, const ulonglong4& b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool operator!=(const ulonglong4& a, const ulonglong4& b)
{
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w;
}
/** @} */
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE unsigned long long getByIndex(const ulonglong4& v, unsigned int i)
{
return ((unsigned long long*)(&v))[i];
}
/** If used on the device, this could place the the 'v' in local memory
*/
SUTIL_INLINE SUTIL_HOSTDEVICE void setByIndex(ulonglong4& v, int i, unsigned long long x)
{
((unsigned long long*)(&v))[i] = x;
}
/******************************************************************************/
/** Narrowing functions
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int3& v0) { return make_int2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int2 make_int2(const int4& v0) { return make_int2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int4& v0) { return make_int3( v0.x, v0.y, v0.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const uint3& v0) { return make_uint2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint2 make_uint2(const uint4& v0) { return make_uint2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const uint4& v0) { return make_uint3( v0.x, v0.y, v0.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const longlong3& v0) { return make_longlong2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong2 make_longlong2(const longlong4& v0) { return make_longlong2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const longlong4& v0) { return make_longlong3( v0.x, v0.y, v0.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const ulonglong3& v0) { return make_ulonglong2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong2 make_ulonglong2(const ulonglong4& v0) { return make_ulonglong2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const ulonglong4& v0) { return make_ulonglong3( v0.x, v0.y, v0.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float3& v0) { return make_float2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float2 make_float2(const float4& v0) { return make_float2( v0.x, v0.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float4& v0) { return make_float3( v0.x, v0.y, v0.z ); }
/** @} */
/** Assemble functions from smaller vectors
* @{
*/
SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int v0, const int2& v1) { return make_int3( v0, v1.x, v1.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int3 make_int3(const int2& v0, const int v1) { return make_int3( v0.x, v0.y, v1 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int v1, const int2& v2) { return make_int4( v0, v1, v2.x, v2.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int2& v1, const int v2) { return make_int4( v0, v1.x, v1.y, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int2& v0, const int v1, const int v2) { return make_int4( v0.x, v0.y, v1, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int v0, const int3& v1) { return make_int4( v0, v1.x, v1.y, v1.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int3& v0, const int v1) { return make_int4( v0.x, v0.y, v0.z, v1 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE int4 make_int4(const int2& v0, const int2& v1) { return make_int4( v0.x, v0.y, v1.x, v1.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const unsigned int v0, const uint2& v1) { return make_uint3( v0, v1.x, v1.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint3 make_uint3(const uint2& v0, const unsigned int v1) { return make_uint3( v0.x, v0.y, v1 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const unsigned int v1, const uint2& v2) { return make_uint4( v0, v1, v2.x, v2.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const uint2& v1, const unsigned int v2) { return make_uint4( v0, v1.x, v1.y, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint2& v0, const unsigned int v1, const unsigned int v2) { return make_uint4( v0.x, v0.y, v1, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const unsigned int v0, const uint3& v1) { return make_uint4( v0, v1.x, v1.y, v1.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint3& v0, const unsigned int v1) { return make_uint4( v0.x, v0.y, v0.z, v1 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE uint4 make_uint4(const uint2& v0, const uint2& v1) { return make_uint4( v0.x, v0.y, v1.x, v1.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const long long v0, const longlong2& v1) { return make_longlong3(v0, v1.x, v1.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong3 make_longlong3(const longlong2& v0, const long long v1) { return make_longlong3(v0.x, v0.y, v1); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const long long v1, const longlong2& v2) { return make_longlong4(v0, v1, v2.x, v2.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const longlong2& v1, const long long v2) { return make_longlong4(v0, v1.x, v1.y, v2); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong2& v0, const long long v1, const long long v2) { return make_longlong4(v0.x, v0.y, v1, v2); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const long long v0, const longlong3& v1) { return make_longlong4(v0, v1.x, v1.y, v1.z); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong3& v0, const long long v1) { return make_longlong4(v0.x, v0.y, v0.z, v1); }
SUTIL_INLINE SUTIL_HOSTDEVICE longlong4 make_longlong4(const longlong2& v0, const longlong2& v1) { return make_longlong4(v0.x, v0.y, v1.x, v1.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const unsigned long long v0, const ulonglong2& v1) { return make_ulonglong3(v0, v1.x, v1.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong3 make_ulonglong3(const ulonglong2& v0, const unsigned long long v1) { return make_ulonglong3(v0.x, v0.y, v1); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const unsigned long long v1, const ulonglong2& v2) { return make_ulonglong4(v0, v1, v2.x, v2.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const ulonglong2& v1, const unsigned long long v2) { return make_ulonglong4(v0, v1.x, v1.y, v2); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong2& v0, const unsigned long long v1, const unsigned long long v2) { return make_ulonglong4(v0.x, v0.y, v1, v2); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const unsigned long long v0, const ulonglong3& v1) { return make_ulonglong4(v0, v1.x, v1.y, v1.z); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong3& v0, const unsigned long long v1) { return make_ulonglong4(v0.x, v0.y, v0.z, v1); }
SUTIL_INLINE SUTIL_HOSTDEVICE ulonglong4 make_ulonglong4(const ulonglong2& v0, const ulonglong2& v1) { return make_ulonglong4(v0.x, v0.y, v1.x, v1.y); }
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float2& v0, const float v1) { return make_float3(v0.x, v0.y, v1); }
SUTIL_INLINE SUTIL_HOSTDEVICE float3 make_float3(const float v0, const float2& v1) { return make_float3( v0, v1.x, v1.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float v1, const float2& v2) { return make_float4( v0, v1, v2.x, v2.y ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float2& v1, const float v2) { return make_float4( v0, v1.x, v1.y, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float2& v0, const float v1, const float v2) { return make_float4( v0.x, v0.y, v1, v2 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float v0, const float3& v1) { return make_float4( v0, v1.x, v1.y, v1.z ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& v0, const float v1) { return make_float4( v0.x, v0.y, v0.z, v1 ); }
SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float2& v0, const float2& v1) { return make_float4( v0.x, v0.y, v1.x, v1.y ); }
/** @} */
|
arhix52/Strelka/sutil/vec_math_adv.h | #pragma once
#include "sutil/vec_math.h"
#include <sutil/Preprocessor.h>
#include <vector_functions.h>
#include <vector_types.h>
#if !defined(__CUDACC_RTC__)
#include <cmath>
#include <cstdlib>
#endif
// SUTIL_INLINE SUTIL_HOSTDEVICE float clamp( const float f, const float a, const float b )
// {
// return fmaxf( a, fminf( f, b ) );
// }
// SUTIL_INLINE SUTIL_HOSTDEVICE float4 make_float4(const float3& a, float w)
// {
// return make_float4(a.x, a.y, a.z, w);
// }
SUTIL_INLINE SUTIL_HOSTDEVICE float3 saturate(const float3 v)
{
float3 r = v;
r.x = clamp(r.x, 0.0f, 1.0f);
r.y = clamp(r.y, 0.0f, 1.0f);
r.z = clamp(r.z, 0.0f, 1.0f);
return r;
}
SUTIL_INLINE SUTIL_HOSTDEVICE float saturate(const float v)
{
return clamp(v, 0.0f, 1.0f);
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool all(const float3 v)
{
return v.x != 0.0f && v.y != 0.0f && v.z != 0.0f;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool any(const float3 v)
{
return v.x != 0.0f || v.y != 0.0f || v.z != 0.0f;
}
SUTIL_INLINE SUTIL_HOSTDEVICE bool isnan(const float3 v)
{
return isnan(v.x) || isnan(v.y) || isnan(v.z);
}
SUTIL_INLINE SUTIL_HOSTDEVICE float3 powf(const float3 v, const float p)
{
float3 r = v;
r.x = powf(r.x, p);
r.y = powf(r.y, p);
r.z = powf(r.z, p);
return r;
}
|
cadop/HumanGenerator/README.md | # Overview
ovmh (ov_makehuman) is a MakeHuman extension for Nvidia Omniverse. This project relies on the makehuman project from https://github.com/makehumancommunity/makehuman.

# Getting Started
The easiest way to get started is using Omniverse Create. Navigate to the Extensions window and click on "Community". Search for `makehuman` and you should see our extension show up.
The extension may take a few minutes to install as it will download makehuman and install it in the Omniverse's local Python instance.
For use, check out the walkthrough video
[](https://www.youtube.com/watch?v=8GD3ld1Ep7c)
## License
*Our license restrictions are due to the AGPL of MakeHuman. In line with the statements from MakeHuman, the targets and resulting characters are CC0, meaning you can use whatever you create for free, without restrictions. It is only the codebase that is AGPL.
|
cadop/HumanGenerator/exts/siborg.create.human/API_EXAMPLE.py | # Human Generator API Example
# Author: Joshua Grebler | SiBORG Lab | 2023
# Description: This is an example of how to use the Human Generator API to create human models in NVIDIA Omniverse.
# The siborg.create.human extension must be installed and enabled for this to work.
# The script generates 10 humans, placing them throughout the stage. Random modifiers and clothing are applied to each.
import siborg.create.human as hg
from siborg.create.human.shared import data_path
import omni.usd
import random
# Get the stage
context = omni.usd.get_context()
stage = context.get_stage()
# Make a single Human to start with
human = hg.Human()
human.add_to_scene()
# Apply a modifier by name (you can find the names of all the available modifiers
# by using the `get_modifier_names()` method)
height = human.get_modifier_by_name("macrodetails-height/Height")
human.set_modifier_value(height, 1)
# Update the human in the scene
human.update_in_scene(human.prim_path)
# Gather some default clothing items (additional clothing can be downloaded from the extension UI)
clothes = ["nvidia_Casual/nvidia_casual.mhclo", "omni_casual/omni_casual.mhclo", "siborg_casual/siborg_casual.mhclo"]
# Convert the clothing names to their full paths.
clothes = [data_path(f"clothes/{c}") for c in clothes]
# Create 20 humans, placing them randomly throughout the scene, and applying random modifier values
for _ in range(10):
h = hg.Human()
h.add_to_scene()
# Apply a random translation and Y rotation to the human prim
translateOp = h.prim.AddTranslateOp()
translateOp.Set((random.uniform(-50, 50), 0, random.uniform(-50, 50)))
rotateOp = h.prim.AddRotateXYZOp()
rotateOp.Set((0, random.uniform(0, 360), 0))
# Apply a random value to the last 9 modifiers in the list.
# These modifiers are macros that affect the overall shape of the human more than any individual modifier.
# Get the last 9 modifiers
modifiers = h.get_modifiers()[-9:]
# Apply a random value to each modifier. Use the modifier's min/max values to ensure the value is within range.
for m in modifiers:
h.set_modifier_value(m, random.uniform(m.getMin(), m.getMax()))
# Update the human in the scene
h.update_in_scene(h.prim_path)
# Add a random clothing item to the human
h.add_item(random.choice(clothes))
|
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/human.py | from typing import Tuple, List, Dict, Union
from .mhcaller import MHCaller
import numpy as np
import omni.kit
import omni.usd
from pxr import Sdf, Usd, UsdGeom, UsdSkel
from .shared import sanitize, data_path
from .skeleton import Skeleton
from module3d import Object3D
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, UsdSkel, Vt
import carb
from .materials import get_mesh_texture, create_material, bind_material
class Human:
"""Class representing a human in the scene. This class is used to add a human to the scene,
and to update the human in the scene. The class also contains functions to add and remove
proxies (clothing, etc.) and apply modifiers, as well as a skeleton.
Attributes
----------
name : str
Name of the human
prim : UsdSkel.Root
Reference to the usd prim for the skelroot representing the human in the stage. Can be changed using set_prim()
prim_path : str
Path to the human prim
scale : float
Scale factor for the human. Defaults to 10 (Omniverse provided humans are 10 times larger than makehuman)
skeleton : Makehuman.Skeleton
Skeleton object for the human
usd_skel : UsdSkel.Skeleton
Skeleton object for the human in the USD stage. Imported from the skeleton object.
objects : List[Object3D]
List of objects attached to the human. Fetched from the makehuman app
mh_meshes : List[Object3D]
List of meshes attached to the human. Fetched from the makehuman app
"""
def __init__(self, name='human', **kwargs):
"""Constructs an instance of Human.
Parameters
----------
name : str
Name of the human. Defaults to 'human'
"""
self.name = name
# Reference to the usd prim for the skelroot representing the human in the stage
self.prim = None
# Provide a scale factor (Omniverse provided humans are 10 times larger than makehuman)
self.scale = 10
# Create a skeleton object for the human
self.skeleton = Skeleton(self.scale)
# usd_skel is none until the human is added to the stage
self.usd_skel = None
# Set the human in makehuman to default values
MHCaller.reset_human()
def reset(self):
"""Resets the human in makehuman and adds a new skeleton to the human"""
# Reset the human in makehuman
MHCaller.reset_human()
# Re-add the skeleton to the human
self.skeleton = Skeleton(self.scale)
def delete_proxies(self):
"""Deletes the prims corresponding to proxies attached to the human"""
# Delete any child prims corresponding to proxies
if self.prim:
# Get the children of the human prim and delete them all at once
proxy_prims = [child.GetPath() for child in self.prim.GetChildren() if child.GetCustomDataByKey("Proxy_path:")]
omni.kit.commands.execute("DeletePrims", paths=proxy_prims)
@property
def prim_path(self):
"""Path to the human prim"""
if self.prim:
return self.prim.GetPath().pathString
else:
return None
@property
def objects(self):
"""List of objects attached to the human. Fetched from the makehuman app"""
return MHCaller.objects
@property
def mh_meshes(self):
"""List of meshes attached to the human. Fetched from the makehuman app"""
return MHCaller.meshes
def add_to_scene(self):
"""Adds the human to the scene. Creates a prim for the human with custom attributes
to hold modifiers and proxies. Also creates a prim for each proxy and attaches it to
the human prim.
Returns
-------
str
Path to the human prim"""
# Get the current stage
stage = omni.usd.get_context().get_stage()
root_path = "/"
# Get default prim.
default_prim = stage.GetDefaultPrim()
if default_prim.IsValid():
# Set the rootpath under the stage's default prim, if the default prim is valid
root_path = default_prim.GetPath().pathString
# Create a path for the next available prim
prim_path = omni.usd.get_stage_next_free_path(stage, root_path + "/" + self.name, False)
# Create a prim for the human
# Prim should be a SkelRoot so we can rig the human with a skeleton later
self.prim = UsdSkel.Root.Define(stage, prim_path)
# Write the properties of the human to the prim
self.write_properties(prim_path, stage)
# Get the objects of the human from mhcaller
objects = MHCaller.objects
# Get the human object from the list of objects
human = objects[0]
# Determine the offset for the human from the ground
offset = -1 * human.getJointPosition("ground")
# Import makehuman objects into the scene
mesh_paths = self.import_meshes(prim_path, stage, offset = offset)
# Add the skeleton to the scene
self.usd_skel= self.skeleton.add_to_stage(stage, prim_path, offset = offset)
# Create bindings between meshes and the skeleton. Returns a list of
# bindings the length of the number of meshes
bindings = self.setup_bindings(mesh_paths, stage, self.usd_skel)
# Setup weights for corresponding mh_meshes (which hold the data) and
# bindings (which link USD_meshes to the skeleton)
self.setup_weights(self.mh_meshes, bindings, self.skeleton.joint_names, self.skeleton.joint_paths)
self.setup_materials(self.mh_meshes, mesh_paths, root_path, stage)
# Explicitly setup material for human skin
texture_path = data_path("skins/textures/skin.png")
skin = create_material(texture_path, "Skin", root_path, stage)
# Bind the skin material to the first prim in the list (the human)
bind_material(mesh_paths[0], skin, stage)
Human._set_scale(self.prim.GetPrim(), self.scale)
return self.prim
def update_in_scene(self, prim_path: str):
"""Updates the human in the scene. Writes the properties of the human to the
human prim and imports the human and proxy meshes. This is called when the
human is updated
Parameters
----------
prim_path : str
Path to the human prim (prim type is SkelRoot)
"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path)
prim = stage.GetPrimAtPath(prim_path)
if prim and stage:
print(prim.GetPath().pathString)
prim_kind = prim.GetTypeName()
# Check if the prim is a SkelRoot and a human
if prim_kind == "SkelRoot" and prim.GetCustomDataByKey("human"):
# Get default prim.
default_prim = stage.GetDefaultPrim()
if default_prim.IsValid():
# Set the rootpath under the stage's default prim, if the default prim is valid
root_path = default_prim.GetPath().pathString
else:
root_path = "/"
# Write the properties of the human to the prim
self.write_properties(prim_path, stage)
# Get the objects of the human from mhcaller
objects = MHCaller.objects
# Get the human object from the list of objects
human = objects[0]
# Determine the offset for the human from the ground
offset = -1 * human.getJointPosition("ground")
# Import makehuman objects into the scene
mesh_paths = self.import_meshes(prim_path, stage, offset = offset)
# Update the skeleton values and insert it into the stage
self.usd_skel = self.skeleton.update_in_scene(stage, prim_path, offset = offset)
# Create bindings between meshes and the skeleton. Returns a list of
# bindings the length of the number of meshes
bindings = self.setup_bindings(mesh_paths, stage, self.usd_skel)
# Setup weights for corresponding mh_meshes (which hold the data) and
# bindings (which link USD_meshes to the skeleton)
self.setup_weights(self.mh_meshes, bindings, self.skeleton.joint_names, self.skeleton.joint_paths)
self.setup_materials(self.mh_meshes, mesh_paths, root_path, stage)
# Explicitly setup material for human skin
texture_path = data_path("skins/textures/skin.png")
skin = create_material(texture_path, "Skin", root_path, stage)
# Bind the skin material to the first prim in the list (the human)
bind_material(mesh_paths[0], skin, stage)
else:
carb.log_warn("The selected prim must be a human!")
else:
carb.log_warn("Can't update human. No prim selected!")
def import_meshes(self, prim_path: str, stage: Usd.Stage, offset: List[float] = [0, 0, 0]):
"""Imports the meshes of the human into the scene. This is called when the human is
added to the scene, and when the human is updated. This function creates mesh prims
for both the human and its proxies, and attaches them to the human prim. If a mesh already
exists in the scene, its values are updated instead of creating a new mesh.
Parameters
----------
prim_path : str
Path to the human prim
stage : Usd.Stage
Stage to write to
offset : List[float], optional
Offset to move the mesh relative to the prim origin, by default [0, 0, 0]
Returns
-------
paths : array of: Sdf.Path
Usd Sdf paths to geometry prims in the scene
"""
# Get the objects of the human from mhcaller
objects = MHCaller.objects
# Get the meshes of the human and its proxies
meshes = [o.mesh for o in objects]
usd_mesh_paths = []
for mesh in meshes:
# Number of vertices per face
nPerFace = mesh.vertsPerFaceForExport
# Lists to hold pruned lists of vertex and UV indices
newvertindices = []
newuvindices = []
# Array of coordinates organized [[x1,y1,z1],[x2,y2,z2]...]
# Adding the given offset moves the mesh relative to the prim origin
coords = mesh.getCoords() + offset
for fn, fv in enumerate(mesh.fvert):
if not mesh.face_mask[fn]:
continue
# only include <nPerFace> verts for each face, and order them
# consecutively
newvertindices += [(fv[n]) for n in range(nPerFace)]
fuv = mesh.fuvs[fn]
# build an array of (u,v)s for each face
newuvindices += [(fuv[n]) for n in range(nPerFace)]
# Type conversion
newvertindices = np.array(newvertindices)
# Create mesh prim at appropriate path. Does not yet hold any data
name = sanitize(mesh.name)
usd_mesh_path = prim_path + "/" + name
usd_mesh_paths.append(usd_mesh_path)
# Check to see if the mesh prim already exists
prim = stage.GetPrimAtPath(usd_mesh_path)
if prim.IsValid():
# omni.kit.commands.execute("DeletePrims", paths=[usd_mesh_path])
point_attr = prim.GetAttribute('points')
point_attr.Set(coords)
face_count = prim.GetAttribute('faceVertexCounts')
nface = [nPerFace] * int(len(newvertindices) / nPerFace)
face_count.Set(nface)
face_idx = prim.GetAttribute('faceVertexIndices')
face_idx.Set(newvertindices)
normals_attr = prim.GetAttribute('normals')
normals_attr.Set(mesh.getNormals())
meshGeom = UsdGeom.Mesh(prim)
# If it doesn't exist, make it. This will run the first time a human is created and
# whenever a new proxy is added
else:
# First determine if the mesh is a proxy
p = mesh.object.proxy
if p:
# Determine if the mesh is a clothes proxy or a proxymesh. If not, then
# an existing proxy of this type already exists, and we must overwrite it
type = p.type if p.type else "proxymeshes"
if not (type == "clothes" or type == "proxymeshes"):
for child in self.prim.GetChildren():
child_type = child.GetCustomDataByKey("Proxy_type:")
if child_type == type:
# If the child prim has the same type as the proxy, delete it
omni.kit.commands.execute("DeletePrims", paths=[child.GetPath()])
break
meshGeom = UsdGeom.Mesh.Define(stage, usd_mesh_path)
prim = meshGeom.GetPrim()
# Set vertices. This is a list of tuples for ALL vertices in an unassociated
# cloud. Faces are built based on indices of this list.
# Example: 3 explicitly defined vertices:
# meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10)]
meshGeom.CreatePointsAttr(coords)
# Set face vertex count. This is an array where each element is the number
# of consecutive vertex indices to include in each face definition, as
# indices are given as a single flat list. The length of this list is the
# same as the number of faces
# Example: 4 faces with 4 vertices each
# meshGeom.CreateFaceVertexCountsAttr([4, 4, 4, 4])
nface = [nPerFace] * int(len(newvertindices) / nPerFace)
meshGeom.CreateFaceVertexCountsAttr(nface)
# Set face vertex indices.
# Example: one face with 4 vertices defined by 4 indices.
# meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
meshGeom.CreateFaceVertexIndicesAttr(newvertindices)
# Set vertex normals. Normals are represented as a list of tuples each of
# which is a vector indicating the direction a point is facing. This is later
# Used to calculate face normals
# Example: Normals for 3 vertices
# meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1,
# 0)])
meshGeom.CreateNormalsAttr(mesh.getNormals())
meshGeom.SetNormalsInterpolation("vertex")
# If the mesh is a proxy, write the proxy path to the mesh prim
if mesh.object.proxy:
p = mesh.object.proxy
type = p.type if p.type else "proxymeshes"
prim.SetCustomDataByKey("Proxy_path:", p.file)
prim.SetCustomDataByKey("Proxy_type:", type)
prim.SetCustomDataByKey("Proxy_name:", p.name)
# Set vertex uvs. UVs are represented as a list of tuples, each of which is a 2D
# coordinate. UV's are used to map textures to the surface of 3D geometry
# Example: texture coordinates for 3 vertices
# texCoords.Set([(0, 1), (0, 0), (1, 0)])
texCoords = meshGeom.CreatePrimvar(
"st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying
)
texCoords.Set(mesh.getUVs(newuvindices))
# # Subdivision is set to none. The mesh is as imported and not further refined
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# ConvertPath strings to USD Sdf paths. TODO change to map() for performance
paths = [Sdf.Path(mesh_path) for mesh_path in usd_mesh_paths]
return paths
def get_written_modifiers(self) -> Union[Dict[str, float], None]:
"""List of modifier names and values written to the human prim.
MAY BE STALE IF THE HUMAN HAS BEEN UPDATED IN MAKEHUMAN AND THE CHANGES HAVE NOT BEEN WRITTEN TO THE PRIM.
Returns
-------
Dict[str, float]
Dictionary of modifier names and values. Keys are modifier names, values are modifier values"""
return self.prim.GetCustomDataByKey("Modifiers") if self.prim else None
def get_changed_modifiers(self):
"""List of modifiers which have been changed in makehuman. Fetched from the human in makehuman.
MAY NOT MATCH `get_written_modifiers()` IF CHANGES HAVE NOT BEEN WRITTEN TO THE PRIM."""
return MHCaller.modifiers
def get_modifiers(self):
"""Retrieve the list of all modifiers available to the human, whether or not their values have changed."""
return MHCaller.default_modifiers
def set_modifier_value(self, modifier, value: float):
"""Sets the value of a modifier in makehuman. Validates the value before setting it.
Returns true if the value was set, false otherwise.
Parameters
----------
modifier : makehuman.humanmodifier.Modifier
Modifier to change
value : float
Value to set the modifier to
"""
# Get the range of the modifier
val_min = modifier.getMin()
val_max = modifier.getMax()
# Check if the value is within the range of the modifier
if value >= val_min and value <= val_max:
# Set the value of the modifier
modifier.setValue(value)
return True
else:
carb.log_warn(f"Value must be between {str(val_min)} and {str(val_max)}")
return False
def get_modifier_by_name(self, name: str):
"""Gets a modifier from the list of modifiers attached to the human by name
Parameters
----------
name : str
Name of the modifier to get
Returns
-------
makehuman.modifiers.Modifier
Modifier with the given name
"""
return MHCaller.human.getModifier(name)
def get_modifier_names(self):
return MHCaller.human.getModifierNames()
def write_properties(self, prim_path: str, stage: Usd.Stage):
"""Writes the properties of the human to the human prim. This includes modifiers and
proxies. This is called when the human is added to the scene, and when the human is
updated
Parameters
----------
prim_path : str
Path to the human prim
stage : Usd.Stage
Stage to write to
"""
prim = stage.GetPrimAtPath(prim_path)
# Add custom data to the prim by key, designating the prim is a human
prim.SetCustomDataByKey("human", True)
# Get the modifiers of the human in mhcaller
modifiers = MHCaller.modifiers
for m in modifiers:
# Add the modifier to the prim as custom data by key. For modifiers,
# the format is "group/modifer:value"
prim.SetCustomDataByKey("Modifiers:" + m.fullName, m.getValue())
# NOTE We are not currently using proxies in the USD export. Proxy data is stored
# in their respective mesh prims, so that deleting proxy prims will also remove the
# proxies. The following code is left here for reference.
# Get the proxies of the human in mhcaller
# proxies = MHCaller.proxies
# for p in proxies:
# # Add the proxy to the prim as custom data by key under "Proxies".
# # Proxy type should be "proxymeshes" if type cannot be determined from the
# # proxy.type property.
# type = p.type if p.type else "proxymeshes"
# # Only "proxymeshes" and "clothes" should be subdictionaries of "Proxies"
# if type == "clothes" or type == "proxymeshes":
# prim.SetCustomDataByKey("Proxies:" + type + ":" + p.name, p.file)
# # Other proxy types should be added as a key to the prim with their
# # type as the key and the path as the value
# else:
# prim.SetCustomDataByKey("Proxies:" + type, p.file)
def set_prim(self, usd_prim : Usd.Prim):
"""Updates the human based on the given prim's attributes
Parameters
----------
usd_prim : Usd.Prim
Prim from which to update the human model."""
self.prim = usd_prim
# Get the data from the prim
humandata = self.prim.GetCustomData()
# Get the list of modifiers from the prim
modifiers = humandata.get("Modifiers")
for m, v in modifiers.items():
MHCaller.human.getModifier(m).setValue(v, skipDependencies=False)
# Gather proxies from the prim children
proxies = []
for child in self.prim.GetChildren():
if child.GetTypeName() == "Mesh" and child.GetCustomDataByKey("Proxy_path:"):
proxies.append(child)
# Clear the makehuman proxies
MHCaller.clear_proxies()
# # Make sure the proxy list is not empty
if proxies:
for p in proxies:
type = p.GetCustomDataByKey("Proxy_type:")
path = p.GetCustomDataByKey("Proxy_path:")
# name = p.GetCustomDataByKey("Proxy_name:")
MHCaller.add_proxy(path, type)
# Update the human in MHCaller
MHCaller.human.applyAllTargets()
def setup_weights(self, mh_meshes: List['Object3D'], bindings: List[UsdSkel.BindingAPI], joint_names: List[str], joint_paths: List[str]):
"""Apply weights to USD meshes using data from makehuman. USD meshes,
bindings and skeleton must already be in the active scene
Parameters
----------
mh_meshes : list of `Object3D`
Makehuman meshes which store weight data
bindings : list of `UsdSkel.BindingAPI`
USD bindings between meshes and skeleton
joint_names : list of str
Unique, plaintext names of all joints in the skeleton in USD
(breadth-first) order.
joint_paths : list of str
List of the full usd path to each joint corresponding to the skeleton to bind to
"""
# Generate bone weights for all meshes up front so they can be reused for all
rawWeights = MHCaller.human.getVertexWeights(
MHCaller.human.getSkeleton()
) # Basemesh weights
for mesh in self.mh_meshes:
if mesh.object.proxy:
# Transfer weights to proxy
parentWeights = mesh.object.proxy.getVertexWeights(
rawWeights, MHCaller.human.getSkeleton()
)
else:
parentWeights = rawWeights
# Transfer weights to face/vert masked and/or subdivided mesh
weights = mesh.getVertexWeights(parentWeights)
# Attach these vertexWeights to the mesh to pass them around the
# exporter easier, the cloned mesh is discarded afterwards, anyway
# if this is the same person, just skip updating weights
mesh.vertexWeights = weights
# Iterate through corresponding meshes and bindings
for mh_mesh, binding in zip(mh_meshes, bindings):
# Calculate vertex weights
indices, weights = self.calculate_influences(mh_mesh, joint_names)
# Type conversion to native ints and floats from numpy
indices = list(map(int, indices))
weights = list(map(float, weights))
# Type conversion to USD
indices = Vt.IntArray(indices)
weights = Vt.FloatArray(weights)
# The number of weights to apply to each vertex, taken directly from
# MakeHuman data
elementSize = int(mh_mesh.vertexWeights._nWeights)
# weight_data = list(mh_mesh.vertexWeights.data) TODO remove
# We might not need to normalize. Makehuman weights are automatically
# normalized when loaded, see:
# http://www.makehumancommunity.org/wiki/Technical_notes_on_MakeHuman
UsdSkel.NormalizeWeights(weights, elementSize)
UsdSkel.SortInfluences(indices, weights, elementSize)
# Assign indices to binding
indices_attribute = binding.CreateJointIndicesPrimvar(
constant=False, elementSize=elementSize
)
joint_attr = binding.GetPrim().GetAttribute('skel:joints')
joint_attr.Set(joint_paths)
indices_attribute.Set(indices)
# Assign weights to binding
weights_attribute = binding.CreateJointWeightsPrimvar(
constant=False, elementSize=elementSize
)
weights_attribute.Set(weights)
def calculate_influences(self, mh_mesh: Object3D, joint_names: List[str]):
"""Build arrays of joint indices and corresponding weights for each vertex.
Joints are in USD (breadth-first) order.
Parameters
----------
mh_mesh : Object3D
Makehuman-format mesh. Contains weight and vertex data.
joint_names : list of str
Unique, plaintext names of all joints in the skeleton in USD
(breadth-first) order.
Returns
-------
indices : list of int
Flat list of joint indices for each vertex
weights : list of float
Flat list of weights corresponding to joint indices
"""
# The maximum number of weights a vertex might have
max_influences = mh_mesh.vertexWeights._nWeights
# Named joints corresponding to vertices and weights ie.
# {"joint",([indices],[weights])}
influence_joints = mh_mesh.vertexWeights.data
num_verts = mh_mesh.getVertexCount(excludeMaskedVerts=False)
# all skeleton joints in USD order
binding_joints = joint_names
# Corresponding arrays of joint indices and weights of length num_verts.
# Allots the maximum number of weights for every vertex, and pads any
# remaining weights with 0's, per USD spec, see:
# https://graphics.pixar.com/usd/dev/api/_usd_skel__schemas.html#UsdSkel_BindingAPI
# "If a point has fewer influences than are needed for other points, the
# unused array elements of that point should be filled with 0, both for
# joint indices and for weights."
indices = np.zeros((num_verts, max_influences))
weights = np.zeros((num_verts, max_influences))
# Keep track of the number of joint influences on each vertex
influence_counts = np.zeros(num_verts, dtype=int)
for joint, joint_data in influence_joints.items():
# get the index of the joint in our USD-ordered list of all joints
joint_index = binding_joints.index(joint)
for vert_index, weight in zip(*joint_data):
# Use influence_count to keep from overwriting existing influences
influence_count = influence_counts[vert_index]
# Add the joint index to our vertex array
indices[vert_index][influence_count] = joint_index
# Add the weight to the same vertex
weights[vert_index][influence_count] = weight
# Add to the influence count for this vertex
influence_counts[vert_index] += 1
# Check for any unweighted verts (this is a test routine)
# for i, d in enumerate(indices): if np.all((d == 0)): print(i)
# Flatten arrays to one dimensional lists
indices = indices.flatten()
weights = weights.flatten()
return indices, weights
def setup_bindings(self, paths: List[Sdf.Path], stage: Usd.Stage, skeleton: UsdSkel.Skeleton):
"""Setup bindings between meshes in the USD scene and the skeleton
Parameters
----------
paths : List of Sdf.Path
USD Sdf paths to each mesh prim
stage : Usd.Stage
The USD stage where the prims can be found
skeleton : UsdSkel.Skeleton
The USD skeleton to apply bindings to
Returns
-------
array of: UsdSkel.BindingAPI
Array of bindings between each mesh and the skeleton, in "path" order
"""
bindings = []
# TODO rename "mesh" to "path"
for mesh in paths:
# Get the prim in the stage
prim = stage.GetPrimAtPath(mesh)
attrs = prim.GetAttribute('primvars:skel:jointWeights')
# Check if joint weights have already been applied
if attrs.IsValid():
prim_path = prim.GetPath()
sdf_path = Sdf.Path(prim_path)
binding = UsdSkel.BindingAPI.Get(stage, sdf_path)
# relationships = prim.GetRelationships()
# 'material:binding' , 'proxyPrim', 'skel:animationSource','skel:blendShapeTargets','skel:skeleton'
# get_binding.GetSkeletonRel()
else:
# Create a binding applied to the prim
binding = UsdSkel.BindingAPI.Apply(prim)
# Create a relationship between the binding and the skeleton
binding.CreateSkeletonRel().SetTargets([skeleton.GetPath()])
# Add the binding to the list to return
bindings.append(binding)
return bindings
def setup_materials(self, mh_meshes: List['Object3D'], meshes: List[Sdf.Path], root: str, stage: Usd.Stage):
"""Fetches materials from Makehuman meshes and applies them to their corresponding
Usd mesh prims in the stage.
Parameters
----------
mh_meshes : List['Object3D']
List of makehuman meshes
meshes : List[Sdf.Path]
Paths to Usd meshes in the stage
root : str
The root path under which to create new prims
stage : Usd.Stage
Usd stage in which to create materials, and which contains the meshes
to which to apply materials
"""
for mh_mesh, mesh in zip(self.mh_meshes, meshes):
# Get a texture path and name from the makehuman mesh
texture, name = get_mesh_texture(mh_mesh)
if texture:
# If we can get a texture from the makehuman mesh, create a material
# from it and bind it to the corresponding USD mesh in the stage
material = create_material(texture, name, root, stage)
bind_material(mesh, material, stage)
def add_item(self, path: str):
"""Add a new asset to the human. Propagates changes to the Makehuman app
and then upates the stage with the new asset. If the asset is a proxy,
targets will not be applied. If the asset is a skeleton, targets must
be applied.
Parameters
----------
path : str
Path to an asset on disk
"""
# Check if human has a prim
if self.prim:
# Add an item through the MakeHuman instance and update the widget view
MHCaller.add_item(path)
self.update_in_scene(self.prim.GetPath().pathString)
else:
carb.log_warn("Can't add asset. No human prim selected!")
@staticmethod
def _set_scale(prim : Usd.Prim, scale : float):
"""Set scale of a prim.
Parameters
----------
prim : Usd.Prim
The prim to scale.
scale : float
The scale to apply."""
if prim == None:
return
# Uniform scale.
sV = Gf.Vec3f(scale, scale, scale)
scale = prim.GetAttribute("xformOp:scale").Get()
if scale != None:
prim.GetAttribute("xformOp:scale").Set(Gf.Vec3f(sV))
else:
# xformOpOrder is also updated.
xformAPI = UsdGeom.XformCommonAPI(prim)
xformAPI.SetScale(Gf.Vec3f(sV)) |
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/styles.py | # Stylesheet for parameter panels
panel_style = {
"Rectangle::group_rect": {
"background_color": 0xFF313333,
"border_radius": 5,
"margin": 5,
},
"VStack::contents": {
"margin": 10,
},
}
# Stylesheet for sliderentry widgets
sliderentry_style = {
"Label::label_param": {
"margin_width": 10,
},
}
# stylesheet for collapseable frame widgets, used for each modifier category
frame_style = {
"CollapsableFrame": {
"background_color": 0xFF1F2123,
},
}
# stylesheet for main UI window
window_style = {
"Rectangle::splitter": {"background_color": 0xFF454545},
"Rectangle::splitter:hovered": {"background_color": 0xFFFFCA83},
}
# Stylesheet for buttons
button_style = {
"Button:disabled": {
"background_color": 0xFF424242,
},
"Button:disabled.Label": {
"color": 0xFF848484,
},
}
|
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/mhcaller.py | from typing import TypeVar, Union
import warnings
import io
import makehuman
from pathlib import Path
# Makehuman loads most modules by manipulating the system path, so we have to
# run this before we can run the rest of our makehuman imports
makehuman.set_sys_path()
import human
import animation
import bvh
import files3d
import mh
from core import G
from mhmain import MHApplication
from shared import wavefront
import humanmodifier, skeleton
import proxy, gui3d, events3d, targets
from getpath import findFile
import numpy as np
import carb
from .shared import data_path
class classproperty:
"""Class property decorator. Allows us to define a property on a class
method rather than an instance method."""
def __init__(cls, fget):
cls.fget = fget
def __get__(cls, obj, owner):
return cls.fget(owner)
class MHCaller:
"""A singleton wrapper around the Makehuman app. Lets us use Makehuman functions without
launching the whole application. Also holds all data about the state of our Human
and available modifiers/assets, and allows us to create new humans without creating a new
instance of MHApp.
Attributes
----------
G : Globals
Makehuman global object. Stores globals needed by Makehuman internally
human : Human
Makehuman Human object. Encapsulates all human data (parameters, available)
modifiers, skeletons, meshes, assets, etc) and functions.
"""
G = G
human = None
def __init__(cls):
"""Constructs an instance of MHCaller. This involves setting up the
needed components to use makehuman modules independent of the GUI.
This includes app globals (G) and the human object."""
cls._config_mhapp()
cls.init_human()
def __new__(cls):
"""Singleton pattern. Only one instance of MHCaller can exist at a time."""
if not hasattr(cls, 'instance'):
cls.instance = super(MHCaller, cls).__new__(cls)
return cls.instance
@classmethod
def _config_mhapp(cls):
"""Declare and initialize the makehuman app, and move along if we
encounter any errors (omniverse sometimes fails to purge the app
singleton on extension reload, which can throw an error. This just means
the app already exists)
"""
try:
cls.G.app = MHApplication()
except:
return
cls.human_mapper = {}
@classmethod
def reset_human(cls):
"""Resets the human object to its initial state. This involves setting the
human's name to its default, resetting all modifications, and resetting all
proxies. Does not reset the skeleton. Also flags the human as having been
reset so that the new name can be created when adding to the Usd stage.
"""
cls.human.resetMeshValues()
# Subdivide the human mesh. This also means that any proxies added to the human are subdivided
cls.human.setSubdivided(True)
# Restore eyes
# cls.add_proxy(data_path("eyes/high-poly/high-poly.mhpxy"), "eyes")
# Reset skeleton to the game skeleton
cls.human.setSkeleton(cls.game_skel)
# Reset the human to tpose
cls.set_tpose()
# HACK Set the age to itcls to force an update of targets, otherwise humans
# are created with the MH base mesh, see:
# http://static.makehumancommunity.org/makehuman/docs/professional_mesh_topology.html
cls.human.setAge(cls.human.getAge())
@classmethod
def init_human(cls):
"""Initialize the human and set some required files from disk. This
includes the skeleton and any proxies (hair, clothes, accessories etc.)
The weights from the base skeleton must be transfered to the chosen
skeleton or else there will be unweighted verts on the meshes.
"""
cls.human = human.Human(files3d.loadMesh(mh.getSysDataPath("3dobjs/base.obj"), maxFaces=5))
# set the makehuman instance human so that features (eg skeletons) can
# access it globally
cls.G.app.selectedHuman = cls.human
humanmodifier.loadModifiers(mh.getSysDataPath("modifiers/modeling_modifiers.json"), cls.human)
# Add eyes
# cls.add_proxy(data_path("eyes/high-poly/high-poly.mhpxy"), "eyes")
cls.base_skel = skeleton.load(
mh.getSysDataPath("rigs/default.mhskel"),
cls.human.meshData,
)
# Load the game developer skeleton
# The root of this skeleton is at the origin which is better for animation
# retargeting
cls.game_skel = skeleton.load(data_path("rigs/game_engine.mhskel"), cls.human.meshData)
# Build joint weights on our chosen skeleton, derived from the base
# skeleton
cls.game_skel.autoBuildWeightReferences(cls.base_skel)
# Set the base skeleton
cls.human.setBaseSkeleton(cls.base_skel)
# Set the game skeleton
cls.human.setSkeleton(cls.game_skel)
@classproperty
def objects(cls):
"""List of objects attached to the human.
Returns
-------
list of: guiCommon.Object
All 3D objects included in the human. This includes the human
itcls, as well as any proxies
"""
# Make sure proxies are up-to-date
cls.update()
return cls.human.getObjects()
@classproperty
def meshes(cls):
"""All of the meshes of all of the objects attached to a human. This
includes the mesh of the human itcls as well as the meshes of all proxies
(clothing, hair, musculature, eyes, etc.)"""
return [o.mesh for o in cls.objects]
@classproperty
def modifiers(cls):
"""List of modifers attached to the human. These are all macros as well as any
individual modifiers which have changed.
Returns
-------
list of: humanmodifier.Modifier
The macros and changed modifiers included in the human
"""
return [m for m in cls.human.modifiers if m.getValue() or m.isMacro()]
@classproperty
def default_modifiers(cls):
"""List of all the loaded modifiers, whether or not their default values have been changed.
-------
list of: humanmodifier.Modifier
The macros and changed modifiers included in the human
"""
return cls.human.modifiers
@classproperty
def proxies(cls):
"""List of proxies attached to the human.
Returns
-------
list of: proxy.Proxy
All proxies included in the human
"""
return cls.human.getProxies()
@classmethod
def update(cls):
"""Propagate changes to meshes and proxies"""
# For every mesh object except for the human (first object), update the
# mesh and corresponding proxy
# See https://github.com/makehumancommunity/makehuman/search?q=adaptproxytohuman
for obj in cls.human.getObjects()[1:]:
mesh = obj.getSeedMesh()
pxy = obj.getProxy()
# Update the proxy and fit to posed human
# args are (mesh, fit_to_posed = false) by default
pxy.update(mesh, True)
# Update the mesh
mesh.update()
@classmethod
def add_proxy(cls, proxypath : str, proxy_type : str = None):
"""Load a proxy (hair, nails, clothes, etc.) and apply it to the human
Parameters
----------
proxypath : str
Path to the proxy file on disk
proxy_type: str, optional
Proxy type, None by default
Can be automatically determined using path names, but otherwise
must be defined (this is a limitation of how makehuman handles
proxies)
"""
# Derived from work by @tomtom92 at the MH-Community forums
# See: http://www.makehumancommunity.org/forum/viewtopic.php?f=9&t=17182&sid=7c2e6843275d8c6c6e70288bc0a27ae9
# Get proxy type if none is given
if proxy_type is None:
proxy_type = cls.guess_proxy_type(proxypath)
# Load the proxy
pxy = proxy.loadProxy(cls.human, proxypath, type=proxy_type)
# Get the mesh and Object3D object from the proxy applied to the human
mesh, obj = pxy.loadMeshAndObject(cls.human)
# TODO is this next line needed?
mesh.setPickable(True)
# TODO Can this next line be deleted? The app isn't running
gui3d.app.addObject(obj)
# Fit the proxy mesh to the human
mesh2 = obj.getSeedMesh()
fit_to_posed = True
pxy.update(mesh2, fit_to_posed)
mesh2.update()
# Set the object to be subdivided if the human is subdivided
obj.setSubdivided(cls.human.isSubdivided())
# Set/add proxy based on type
if proxy_type == "eyes":
cls.human.setEyesProxy(pxy)
elif proxy_type == "clothes":
cls.human.addClothesProxy(pxy)
elif proxy_type == "eyebrows":
cls.human.setEyebrowsProxy(pxy)
elif proxy_type == "eyelashes":
cls.human.setEyelashesProxy(pxy)
elif proxy_type == "hair":
cls.human.setHairProxy(pxy)
else:
# Body proxies (musculature, etc)
cls.human.setProxy(pxy)
vertsMask = np.ones(cls.human.meshData.getVertexCount(), dtype=bool)
proxyVertMask = proxy.transferVertexMaskToProxy(vertsMask, pxy)
# Apply accumulated mask from previous layers on this proxy
obj.changeVertexMask(proxyVertMask)
# Delete masked vertices
# TODO add toggle for this feature in UI
# verts = np.argwhere(pxy.deleteVerts)[..., 0]
# vertsMask[verts] = False
# cls.human.changeVertexMask(vertsMask)
Proxy = TypeVar("Proxy")
@classmethod
def remove_proxy(cls, proxy: Proxy):
"""Removes a proxy from the human. Executes a particular method for removal
based on proxy type.
Parameters
----------
proxy : proxy.Proxy
The Makehuman proxy to remove from the human
"""
proxy_type = proxy.type.lower()
# Use MakeHuman internal methods to remove proxy based on type
if proxy_type == "eyes":
cls.human.setEyesProxy(None)
elif proxy_type == "clothes":
cls.human.removeClothesProxy(proxy.uuid)
elif proxy_type == "eyebrows":
cls.human.setEyebrowsProxy(None)
elif proxy_type == "eyelashes":
cls.human.setEyelashesProxy(None)
elif proxy_type == "hair":
cls.human.setHairProxy(None)
else:
# Body proxies (musculature, etc)
cls.human.setProxy(None)
@classmethod
def clear_proxies(cls):
"""Removes all proxies from the human"""
for pxy in cls.proxies:
cls.remove_proxy(pxy)
Skeleton = TypeVar("Skeleton")
@classmethod
def remove_item(cls, item : Union[Skeleton, Proxy]):
"""Removes a Makehuman asset from the human. Assets include Skeletons
as well as proxies. Determines removal method based on asset object type.
Parameters
----------
item : Union[Skeleton,Proxy]
Makehuman skeleton or proxy to remove from the human
"""
if isinstance(item, proxy.Proxy):
cls.remove_proxy(item)
else:
return
@classmethod
def add_item(cls, path : str):
"""Add a Makehuman asset (skeleton or proxy) to the human.
Parameters
----------
path : str
Path to the asset on disk
"""
if "mhpxy" in path or "mhclo" in path:
cls.add_proxy(path)
elif "mhskel" in path:
cls.set_skel(path)
@classmethod
def set_skel(cls, path : str):
"""Change the skeleton applied to the human. Loads a skeleton from disk.
The skeleton position can be used to drive the human position in the scene.
Parameters
----------
path : str
The path to the skeleton to load from disk
"""
# Load skeleton from path
skel = skeleton.load(path, cls.human.meshData)
# Build skeleton weights based on base skeleton
skel.autoBuildWeightReferences(cls.base_skel)
# Set the skeleton and update the human
cls.human.setSkeleton(skel)
cls.human.applyAllTargets()
# Return the skeleton object
return skel
@classmethod
def guess_proxy_type(cls, path : str):
"""Guesses a proxy's type based on the path from which it is loaded.
Parameters
----------
path : str
The path to the proxy on disk
Returns
-------
Union[str,None]
The proxy type, or none if the type could not be determined
"""
proxy_types = ("eyes", "clothes", "eyebrows", "eyelashes", "hair")
for type in proxy_types:
if type in path:
return type
return None
@classmethod
def set_tpose(cls):
"""Sets the human to the T-Pose"""
# Load the T-Pose BVH file
filepath = data_path('poses\\tpose.bvh')
bvh_file = bvh.load(filepath, convertFromZUp="auto")
# Create an animation track from the BVH file
anim = bvh_file.createAnimationTrack(cls.human.getBaseSkeleton())
# Add the animation to the human
cls.human.addAnimation(anim)
# Set the active animation to the T-Pose
cls.human.setActiveAnimation(anim.name)
# Refresh the human pose
cls.human.refreshPose()
return
# Create an instance of MHCaller when imported
MHCaller()
|
cadop/HumanGenerator/exts/siborg.create.human/siborg/create/human/extension.py | import omni.ext
import omni.ui as ui
import carb
import carb.events
import omni
from functools import partial
import asyncio
import omni.usd
from pxr import Usd
from typing import Union
from .window import MHWindow, WINDOW_TITLE, MENU_PATH
class MakeHumanExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
# subscribe to stage events
# see https://github.com/mtw75/kit_customdata_view
_usd_context = omni.usd.get_context()
self._selection = _usd_context.get_selection()
self._human_selection_event = carb.events.type_from_string("siborg.create.human.human_selected")
# subscribe to stage events
self._events = _usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_push(
self._on_stage_event,
name='human seletion changed',
)
# get message bus event stream so we can push events to the message bus
self._bus = omni.kit.app.get_app().get_message_bus_event_stream()
ui.Workspace.set_show_window_fn(WINDOW_TITLE, partial(self.show_window, None))
# create a menu item to open the window
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
MENU_PATH, self.show_window, toggle=True, value=True
)
# show the window
ui.Workspace.show_window(WINDOW_TITLE)
print("[siborg.create.human] HumanGeneratorExtension startup")
def on_shutdown(self):
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(WINDOW_TITLE, None)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def visibility_changed(self, visible):
# Called when window closed by user
editor_menu = omni.kit.ui.get_editor_menu()
# Update the menu item to reflect the window state
if editor_menu:
editor_menu.set_value(MENU_PATH, visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
"""Handles showing and hiding the window"""
if value:
self._window = MHWindow(WINDOW_TITLE)
# # Dock window wherever the "Content" tab is found (bottom panel by default)
self._window.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self._window.set_visibility_changed_fn(self.visibility_changed)
elif self._window:
self._window.visible = False
def _on_stage_event(self, event):
"""Handles stage events. This is where we get notified when the user selects/deselects a prim in the viewport."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
# Get the current selection
selection = self._selection.get_selected_prim_paths()
# Check if the selection is empty
if not selection:
# Push an event to the message bus with "None" as a payload
# This event will be picked up by the window and used to update the UI
carb.log_warn("Human deselected")
self._bus.push(self._human_selection_event, payload={"prim_path": None})
else:
# Get the stage
_usd_context = omni.usd.get_context()
stage = _usd_context.get_stage()
if selection and stage:
if len(selection) > 0:
path = selection[-1]
print(path)
prim = stage.GetPrimAtPath(path)
prim = self._get_typed_parent(prim, "SkelRoot")
# If the selection is a human, push an event to the event stream with the prim as a payload
# This event will be picked up by the window and used to update the UI
if prim and prim.GetCustomDataByKey("human"):
# carb.log_warn("Human selected")
path = prim.GetPath().pathString
self._bus.push(self._human_selection_event, payload={"prim_path": path})
else:
# carb.log_warn("Human deselected")
self._bus.push(self._human_selection_event, payload={"prim_path": None})
def _get_typed_parent(self, prim: Union[Usd.Prim, None], type_name: str, level: int = 5):
"""Returns the first parent of the given prim with the given type name. If no parent is found, returns None.
Parameters:
-----------
prim : Usd.Prim or None
The prim to search from. If None, returns None.
type_name : str
The parent type name to search for
level : int
The maximum number of levels to traverse. Defaults to 5.
Returns:
--------
Usd.Prim
The first parent of the given prim with the given type name. If no match is found, returns None.
"""
if (not prim) or level == 0:
return None
elif prim and prim.GetTypeName() == type_name:
return prim
else:
return self._get_typed_parent(prim.GetParent(), type_name, level - 1)
|
Subsets and Splits