Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
out
third_party/cpplint
third_party/dxc
third_party/glslang
third_party/googletest
third_party/lodepng
Expand Down
32 changes: 26 additions & 6 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ option(AMBER_SKIP_SAMPLES
option(AMBER_USE_LOCAL_VULKAN "Build with vulkan in third_party" OFF)
option(AMBER_ENABLE_SWIFTSHADER
"Build using SwiftShader" ${AMBER_ENABLE_SWIFTSHADER})
option(AMBER_USE_LOCAL_VULKAN "Build with vulkan in third_party" OFF)
option(AMBER_USE_DXC "Enable DXC integration" ${AMBER_USE_DXC})

if(WIN32)
# On Windows, CMake by default compiles with the shared CRT.
# Default it to the static CRT.
Expand All @@ -53,7 +54,6 @@ if(WIN32)
${AMBER_ENABLE_SHARED_CRT})
endif(WIN32)


if (${AMBER_SKIP_SPIRV_TOOLS})
set(AMBER_ENABLE_SPIRV_TOOLS FALSE)
set(AMBER_ENABLE_SHADERC FALSE)
Expand All @@ -66,11 +66,13 @@ else()
set(AMBER_ENABLE_SHADERC TRUE)
endif()
endif()

if (${AMBER_SKIP_TESTS})
set(AMBER_ENABLE_TESTS FALSE)
else()
set(AMBER_ENABLE_TESTS TRUE)
endif()

if (${AMBER_SKIP_SAMPLES})
set(AMBER_ENABLE_SAMPLES FALSE)
else()
Expand All @@ -82,17 +84,21 @@ if (${AMBER_ENABLE_SWIFTSHADER})
set(AMBER_USE_LOCAL_VULKAN TRUE)
endif()

if (${AMBER_USE_LOCAL_VULKAN})
message(STATUS "Using python3")
# vulkan-loaders requires python 3
find_package(PythonInterp 3 REQUIRED)
if (${AMBER_USE_DXC})
set(AMBER_ENABLE_DXC TRUE)
else()
set(AMBER_ENABLE_DXC FALSE)
endif()

message(STATUS "Using python3")
find_package(PythonInterp 3 REQUIRED)

message(STATUS "Amber enable SPIRV-Tools: ${AMBER_ENABLE_SPIRV_TOOLS}")
message(STATUS "Amber enable Shaderc: ${AMBER_ENABLE_SHADERC}")
message(STATUS "Amber enable tests: ${AMBER_ENABLE_TESTS}")
message(STATUS "Amber enable samples: ${AMBER_ENABLE_SAMPLES}")
message(STATUS "Amber enable SwiftShader: ${AMBER_ENABLE_SWIFTSHADER}")
message(STATUS "Amber enable DXC: ${AMBER_ENABLE_DXC}")

include_directories("${PROJECT_SOURCE_DIR}/include")
include_directories("${PROJECT_SOURCE_DIR}")
Expand All @@ -112,6 +118,20 @@ add_definitions(-DAMBER_ENGINE_VULKAN=$<BOOL:${Vulkan_FOUND}>)
add_definitions(-DAMBER_ENGINE_DAWN=$<BOOL:${Dawn_FOUND}>)
add_definitions(-DAMBER_ENABLE_SPIRV_TOOLS=$<BOOL:${AMBER_ENABLE_SPIRV_TOOLS}>)
add_definitions(-DAMBER_ENABLE_SHADERC=$<BOOL:${AMBER_ENABLE_SHADERC}>)
add_definitions(-DAMBER_ENABLE_DXC=$<BOOL:${AMBER_ENABLE_DXC}>)

set(CMAKE_DEBUG_POSTFIX "")

# This has to be done very early so the link path will get set correctly for all
# the various libraries and binaries.
if (${AMBER_ENABLE_DXC})
link_directories("${CMAKE_BINARY_DIR}/third_party/dxc/lib")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For later: We can use <projectname>_BINARY_DIR to specify this dir, without assuming its source was under third_party.

It's kind of weird, but DXC sets the project name to "LLVM", so then it would still look weird!
See https://github.com/microsoft/DirectXShaderCompiler/blob/master/CMakeLists.txt#L28


if (MSVC)
# DXC turns this off all over the place so we have to do the same.
add_definitions(/D_ITERATOR_DEBUG_LEVEL=0)
endif()
endif()

if ("${CMAKE_BUILD_TYPE}" STREQUAL "")
message(STATUS "No build type selected, default to Debug")
Expand Down
5 changes: 5 additions & 0 deletions DEPS
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ vars = {
'khronos_git': 'https://github.com/KhronosGroup',
'lvandeve_git': 'https://github.com/lvandeve',
'swiftshader_git': 'https://swiftshader.googlesource.com',
'microsoft_git': 'https://github.com/Microsoft',

'cpplint_revision': '9f41862c0efa7681e2147910d39629c73a2b2702',
'dxc_revision': '7342a3b9be25bd4787fd24a4041795796e7ec49f',
'glslang_revision': 'f44b17ee135d5e153ce000e88b806b5377812b11',
'googletest_revision': 'd5932506d6eed73ac80b9bcc47ed723c8c74eb1e',
'lodepng_revision': 'ba9fc1f084f03b5fbf8c9a5df9448173f27544b1',
Expand All @@ -22,6 +24,9 @@ deps = {
'third_party/cpplint': vars['google_git'] + '/styleguide.git@' +
vars['cpplint_revision'],

'third_party/dxc': vars['microsoft_git'] + '/DirectXShaderCompiler.git@' +
vars['dxc_revision'],

'third_party/googletest': vars['google_git'] + '/googletest.git@' +
vars['googletest_revision'],

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ The available flags which can be defined are:
cmake -DAMBER_SKIP_TESTS=True -DAMBER_SKIP_SPIRV_TOOLS=True -GNinja ../..
```

#### DXC

DXC can be enabled in Amber by adding the `-DAMBER_USE_DXC=true` flag when
running cmake.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should say that this also enables HLSL shader support, and that DXC is used to compile those shaders.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although we would also need updates to the vk_script and amberscript docs. So I'll file an issue for that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have no plans on updating vkscript to support hlsl. This will be AmberScript only.

## Build Bots

There are a number of build bots to verify Amber continues to compile and run
Expand Down
1 change: 1 addition & 0 deletions include/amber/shader_info.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ enum ShaderFormat {
kShaderFormatDefault = 0,
kShaderFormatText,
kShaderFormatGlsl,
kShaderFormatHlsl,
kShaderFormatSpirvAsm,
kShaderFormatSpirvHex,
};
Expand Down
20 changes: 20 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,31 @@ if (${Dawn_FOUND})
list(APPEND AMBER_SOURCES dawn_engine_config.cc)
endif()

if (${AMBER_ENABLE_DXC})
list(APPEND AMBER_SOURCES dxc_helper.cc)
endif()

add_library(libamber ${AMBER_SOURCES})
amber_default_compile_options(libamber)
target_include_directories(libamber PRIVATE "${CMAKE_BINARY_DIR}")
set_target_properties(libamber PROPERTIES OUTPUT_NAME "amber")

if (${AMBER_ENABLE_DXC})
target_include_directories(libamber PRIVATE
"${PROJECT_SOURCE_DIR}/third_party/dxc/include"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly, this could be ${LLVM_SOURCE_DIR}/include and ${LLVM_BINARY_DIR}/include

"${CMAKE_BINARY_DIR}/third_party/dxc/include"
)

add_dependencies(libamber dxcompiler)
target_link_libraries(libamber
dxcompiler
LLVMDxcSupport
LLVMOption
LLVMHLSL
LLVMScalarOpts
)
endif()

if (${AMBER_ENABLE_SPIRV_TOOLS})
target_link_libraries(libamber SPIRV-Tools)
endif()
Expand Down
2 changes: 2 additions & 0 deletions src/amberscript/parser.cc
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ Result Parser::ToShaderFormat(const std::string& str, ShaderFormat* fmt) {

if (str == "GLSL")
*fmt = kShaderFormatGlsl;
else if (str == "HLSL")
*fmt = kShaderFormatHlsl;
else if (str == "SPIRV-ASM")
*fmt = kShaderFormatSpirvAsm;
else if (str == "SPIRV-HEX")
Expand Down
162 changes: 162 additions & 0 deletions src/dxc_helper.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// Copyright 2019 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/dxc_helper.h"

#include <algorithm>
#include <sstream>

#include "src/platform.h"

#if AMBER_PLATFORM_WINDOWS
#pragma warning(push)
#pragma warning(disable : 4267)
#pragma warning(disable : 4003)
#endif // AMBER_PLATFORM_WINDOWS

// clang-format off
// The order here matters, so don't reformat.
#include "third_party/dxc/include/dxc/Support/WinAdapter.h"
#include "third_party/dxc/include/dxc/Support/WinIncludes.h"
#include "third_party/dxc/include/dxc/Support/Global.h"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems over-descriptive. In future we should allow DXC's source to be in some configurable location. But that's for the future.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Include paths should be from the root src/ directory. Or are you thinking we should allow DXC to live outside amber?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean DXC should be able to live outside of Amber. Like, if I had one giant build tree that included many tools for the Vulkan shader stack.
So, I'd have

#include "dxc/Support/Global.h"

so that I can always find with a -I option on the compiler, where that is controlled from a CMake string expression.

#include "third_party/dxc/include/dxc/Support/HLSLOptions.h"
#include "third_party/dxc/include/dxc/Support/dxcapi.use.h"
#include "third_party/dxc/include/dxc/dxcapi.h"
// clang-format on

#if AMBER_PLATFORM_WINDOWS
#pragma warning(pop)
#endif // AMBER_PLATFORM_WINDOWS

namespace amber {
namespace dxchelper {
namespace {

const wchar_t* kDxcFlags[] = {
L"-spirv", // SPIR-V compilation
L"-Vd" // Disable validation.
};
const size_t kDxcFlagsCount = sizeof(kDxcFlags) / sizeof(const wchar_t*);

// Converts an IDxcBlob into a vector of 32-bit unsigned integers which
// is returned via the 'binaryWords' argument.
void ConvertIDxcBlobToUint32(IDxcBlob* blob,
std::vector<uint32_t>* binaryWords) {
size_t num32BitWords = (blob->GetBufferSize() + 3) / 4;
std::string binaryStr(static_cast<char*>(blob->GetBufferPointer()),
blob->GetBufferSize());
binaryStr.resize(num32BitWords * 4, 0);
binaryWords->resize(num32BitWords, 0);
memcpy(binaryWords->data(), binaryStr.data(), binaryStr.size());
}

} // namespace

Result Compile(const std::string& src,
const std::string& entry,
const std::string& profile,
std::vector<uint32_t>* generated_binary) {
DxcInitThreadMalloc();

if (hlsl::options::initHlslOptTable()) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: initHlslOptTable");
}

IDxcLibrary* dxc_lib;
if (DxcCreateInstance(CLSID_DxcLibrary, __uuidof(IDxcLibrary),
reinterpret_cast<void**>(&dxc_lib)) < 0) {
DxcCleanupThreadMalloc();
return Result("DXCCreateInstance for DXCLibrary failed");
}

IDxcBlobEncoding* source;
if (dxc_lib->CreateBlobWithEncodingOnHeapCopy(
src.data(), static_cast<uint32_t>(src.size()), CP_UTF8, &source) <
0) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: CreateBlobFromFile");
}

IDxcIncludeHandler* include_handler;
if (dxc_lib->CreateIncludeHandler(&include_handler) < 0) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: CreateIncludeHandler");
}

IDxcCompiler* compiler;
if (DxcCreateInstance(CLSID_DxcCompiler, __uuidof(IDxcCompiler),
reinterpret_cast<void**>(&compiler)) < 0) {
DxcCleanupThreadMalloc();
return Result("DXCCreateInstance for DXCCompiler failed");
}

IDxcOperationResult* result;
std::wstring src_filename =
L"amber." + std::wstring(profile.begin(), profile.end());
if (compiler->Compile(source, /* source text */
src_filename.c_str(), /* original file source */
std::wstring(entry.begin(), entry.end())
.c_str(), /* entry point name */
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to stop for a while, worrying about the lifetime of the temporary. But it dies at the end of the full expression, so that's late enough. Phew.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heh, I didn't think about that at the time.

std::wstring(profile.begin(), profile.end())
.c_str(), /* shader profile to compile */
kDxcFlags, /* arguments */
kDxcFlagsCount, /* argument count */
nullptr, /* defines */
0, /* define count */
include_handler, /* handler for #include */
&result /* output status */) < 0) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: Compile");
}

// Compilation is done. We can clean up the HlslOptTable.
hlsl::options::cleanupHlslOptTable();

// Get compilation results.
HRESULT result_status;
if (result->GetStatus(&result_status) < 0) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: GetStatus");
}

// Get diagnostics string.
IDxcBlobEncoding* error_buffer;
if (result->GetErrorBuffer(&error_buffer)) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: GetErrorBuffer");
}

const std::string diagnostics(
static_cast<char*>(error_buffer->GetBufferPointer()),
error_buffer->GetBufferSize());

bool success = true;
if (SUCCEEDED(result_status)) {
IDxcBlob* compiled_blob;
if (result->GetResult(&compiled_blob) < 0) {
DxcCleanupThreadMalloc();
return Result("DXC compile failure: GetResult");
}
ConvertIDxcBlobToUint32(compiled_blob, generated_binary);
} else {
success = false;
}

DxcCleanupThreadMalloc();
return success ? Result() : Result("DXC compile failure: " + diagnostics);
}

} // namespace dxchelper
} // namespace amber
36 changes: 36 additions & 0 deletions src/dxc_helper.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2019 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SRC_DXC_HELPER_H_
#define SRC_DXC_HELPER_H_

#include <string>
#include <vector>

#include "amber/result.h"

namespace amber {
namespace dxchelper {

// Passes the HLSL source code to the DXC compiler with SPIR-V CodeGen.
// Returns the generated SPIR-V binary via |generated_binary| argument.
Result Compile(const std::string& src_str,
const std::string& entry_str,
const std::string& profile_str,
std::vector<uint32_t>* generated_binary);

} // namespace dxchelper
} // namespace amber

#endif // SRC_DXC_HELPER_H_
Loading