obs-studio/libobs-d3d11/d3d11-shader.cpp
jp9000 5780f3f177 (API Change) Improve graphics API consistency
Summary:
- Prefix all graphics subsystem names with gs_ or GS_
- Unsquish funciton names (for example _setfloat to _set_float)
- Changed create functions to be more consistent with the rest of the
  API elsewhere.  For exmaple, instead of
  gs_create_texture/gs_texture_destroy, it's now
  gs_texture_create/gs_texture_destroy
- Renamed gs_stencil_op enum to gs_stencil_op_type

From:                            To:
-----------------------------------------------------------
tvertarray                       gs_tvertarray
vb_data                          gs_vb_data
vbdata_create                    gs_vbdata_create
vbdata_destroy                   gs_vbdata_destroy
shader_param                     gs_shader_param
gs_effect                        gs_effect
effect_technique                 gs_effect_technique
effect_pass                      gs_effect_pass
effect_param                     gs_effect_param
texture_t                        gs_texture_t
stagesurf_t                      gs_stagesurf_t
zstencil_t                       gs_zstencil_t
vertbuffer_t                     gs_vertbuffer_t
indexbuffer_t                    gs_indexbuffer_t
samplerstate_t                   gs_samplerstate_t
swapchain_t                      gs_swapchain_t
texrender_t                      gs_texrender_t
shader_t                         gs_shader_t
sparam_t                         gs_sparam_t
effect_t                         gs_effect_t
technique_t                      gs_technique_t
eparam_t                         gs_eparam_t
device_t                         gs_device_t
graphics_t                       graphics_t
shader_param_type                gs_shader_param_type
SHADER_PARAM_UNKNOWN             GS_SHADER_PARAM_UNKNOWN
SHADER_PARAM_BOOL                GS_SHADER_PARAM_BOOL
SHADER_PARAM_FLOAT               GS_SHADER_PARAM_FLOAT
SHADER_PARAM_INT                 GS_SHADER_PARAM_INT
SHADER_PARAM_STRING              GS_SHADER_PARAM_STRING
SHADER_PARAM_VEC2                GS_SHADER_PARAM_VEC2
SHADER_PARAM_VEC3                GS_SHADER_PARAM_VEC3
SHADER_PARAM_VEC4                GS_SHADER_PARAM_VEC4
SHADER_PARAM_MATRIX4X4           GS_SHADER_PARAM_MATRIX4X4
SHADER_PARAM_TEXTURE             GS_SHADER_PARAM_TEXTURE
shader_param_info                gs_shader_param_info
shader_type                      gs_shader_type
SHADER_VERTEX                    GS_SHADER_VERTEX
SHADER_PIXEL                     GS_SHADER_PIXEL
shader_destroy                   gs_shader_destroy
shader_numparams                 gs_shader_get_num_params
shader_getparambyidx             gs_shader_get_param_by_idx
shader_getparambyname            gs_shader_get_param_by_name
shader_getviewprojmatrix         gs_shader_get_viewproj_matrix
shader_getworldmatrix            gs_shader_get_world_matrix
shader_getparaminfo              gs_shader_get_param_info
shader_setbool                   gs_shader_set_bool
shader_setfloat                  gs_shader_set_float
shader_setint                    gs_shader_set_int
shader_setmatrix3                gs_shader_setmatrix3
shader_setmatrix4                gs_shader_set_matrix4
shader_setvec2                   gs_shader_set_vec2
shader_setvec3                   gs_shader_set_vec3
shader_setvec4                   gs_shader_set_vec4
shader_settexture                gs_shader_set_texture
shader_setval                    gs_shader_set_val
shader_setdefault                gs_shader_set_default
effect_property_type             gs_effect_property_type
EFFECT_NONE                      GS_EFFECT_NONE
EFFECT_BOOL                      GS_EFFECT_BOOL
EFFECT_FLOAT                     GS_EFFECT_FLOAT
EFFECT_COLOR                     GS_EFFECT_COLOR
EFFECT_TEXTURE                   GS_EFFECT_TEXTURE
effect_param_info                gs_effect_param_info
effect_destroy                   gs_effect_destroy
effect_gettechnique              gs_effect_get_technique
technique_begin                  gs_technique_begin
technique_end                    gs_technique_end
technique_beginpass              gs_technique_begin_pass
technique_beginpassbyname        gs_technique_begin_pass_by_name
technique_endpass                gs_technique_end_pass
effect_numparams                 gs_effect_get_num_params
effect_getparambyidx             gs_effect_get_param_by_idx
effect_getparambyname            gs_effect_get_param_by_name
effect_updateparams              gs_effect_update_params
effect_getviewprojmatrix         gs_effect_get_viewproj_matrix
effect_getworldmatrix            gs_effect_get_world_matrix
effect_getparaminfo              gs_effect_get_param_info
effect_setbool                   gs_effect_set_bool
effect_setfloat                  gs_effect_set_float
effect_setint                    gs_effect_set_int
effect_setmatrix4                gs_effect_set_matrix4
effect_setvec2                   gs_effect_set_vec2
effect_setvec3                   gs_effect_set_vec3
effect_setvec4                   gs_effect_set_vec4
effect_settexture                gs_effect_set_texture
effect_setval                    gs_effect_set_val
effect_setdefault                gs_effect_set_default
texrender_create                 gs_texrender_create
texrender_destroy                gs_texrender_destroy
texrender_begin                  gs_texrender_begin
texrender_end                    gs_texrender_end
texrender_reset                  gs_texrender_reset
texrender_gettexture             gs_texrender_get_texture
GS_BUILDMIPMAPS                  GS_BUILD_MIPMAPS
GS_RENDERTARGET                  GS_RENDER_TARGET
gs_device_name                   gs_get_device_name
gs_device_type                   gs_get_device_type
gs_entercontext                  gs_enter_context
gs_leavecontext                  gs_leave_context
gs_getcontext                    gs_get_context
gs_renderstart                   gs_render_start
gs_renderstop                    gs_render_stop
gs_rendersave                    gs_render_save
gs_getinput                      gs_get_input
gs_geteffect                     gs_get_effect
gs_create_effect_from_file       gs_effect_create_from_file
gs_create_effect                 gs_effect_create
gs_create_vertexshader_from_file gs_vertexshader_create_from_file
gs_create_pixelshader_from_file  gs_pixelshader_create_from_file
gs_create_texture_from_file      gs_texture_create_from_file
gs_resetviewport                 gs_reset_viewport
gs_set2dmode                     gs_set_2d_mode
gs_set3dmode                     gs_set_3d_mode
gs_create_swapchain              gs_swapchain_create
gs_getsize                       gs_get_size
gs_getwidth                      gs_get_width
gs_getheight                     gs_get_height
gs_create_texture                gs_texture_create
gs_create_cubetexture            gs_cubetexture_create
gs_create_volumetexture          gs_voltexture_create
gs_create_zstencil               gs_zstencil_create
gs_create_stagesurface           gs_stagesurface_create
gs_create_samplerstate           gs_samplerstate_create
gs_create_vertexshader           gs_vertexshader_create
gs_create_pixelshader            gs_pixelshader_create
gs_create_vertexbuffer           gs_vertexbuffer_create
gs_create_indexbuffer            gs_indexbuffer_create
gs_gettexturetype                gs_get_texture_type
gs_load_defaultsamplerstate      gs_load_default_samplerstate
gs_getvertexshader               gs_get_vertex_shader
gs_getpixelshader                gs_get_pixel_shader
gs_getrendertarget               gs_get_render_target
gs_getzstenciltarget             gs_get_zstencil_target
gs_setrendertarget               gs_set_render_target
gs_setcuberendertarget           gs_set_cube_render_target
gs_beginscene                    gs_begin_scene
gs_draw                          gs_draw
gs_endscene                      gs_end_scene
gs_setcullmode                   gs_set_cull_mode
gs_getcullmode                   gs_get_cull_mode
gs_enable_depthtest              gs_enable_depth_test
gs_enable_stenciltest            gs_enable_stencil_test
gs_enable_stencilwrite           gs_enable_stencil_write
gs_blendfunction                 gs_blend_function
gs_depthfunction                 gs_depth_function
gs_stencilfunction               gs_stencil_function
gs_stencilop                     gs_stencil_op
gs_setviewport                   gs_set_viewport
gs_getviewport                   gs_get_viewport
gs_setscissorrect                gs_set_scissor_rect
gs_create_texture_from_iosurface gs_texture_create_from_iosurface
gs_create_gdi_texture            gs_texture_create_gdi
gs_is_compressed_format          gs_is_compressed_format
gs_num_total_levels              gs_get_total_levels
texture_setimage                 gs_texture_set_image
cubetexture_setimage             gs_cubetexture_set_image
swapchain_destroy                gs_swapchain_destroy
texture_destroy                  gs_texture_destroy
texture_getwidth                 gs_texture_get_width
texture_getheight                gs_texture_get_height
texture_getcolorformat           gs_texture_get_color_format
texture_map                      gs_texture_map
texture_unmap                    gs_texture_unmap
texture_isrect                   gs_texture_is_rect
texture_getobj                   gs_texture_get_obj
cubetexture_destroy              gs_cubetexture_destroy
cubetexture_getsize              gs_cubetexture_get_size
cubetexture_getcolorformat       gs_cubetexture_get_color_format
volumetexture_destroy            gs_voltexture_destroy
volumetexture_getwidth           gs_voltexture_get_width
volumetexture_getheight          gs_voltexture_get_height
volumetexture_getdepth           gs_voltexture_getdepth
volumetexture_getcolorformat     gs_voltexture_get_color_format
stagesurface_destroy             gs_stagesurface_destroy
stagesurface_getwidth            gs_stagesurface_get_width
stagesurface_getheight           gs_stagesurface_get_height
stagesurface_getcolorformat      gs_stagesurface_get_color_format
stagesurface_map                 gs_stagesurface_map
stagesurface_unmap               gs_stagesurface_unmap
zstencil_destroy                 gs_zstencil_destroy
samplerstate_destroy             gs_samplerstate_destroy
vertexbuffer_destroy             gs_vertexbuffer_destroy
vertexbuffer_flush               gs_vertexbuffer_flush
vertexbuffer_getdata             gs_vertexbuffer_get_data
indexbuffer_destroy              gs_indexbuffer_destroy
indexbuffer_flush                gs_indexbuffer_flush
indexbuffer_getdata              gs_indexbuffer_get_data
indexbuffer_numindices           gs_indexbuffer_get_num_indices
indexbuffer_gettype              gs_indexbuffer_get_type
texture_rebind_iosurface         gs_texture_rebind_iosurface
texture_get_dc                   gs_texture_get_dc
texture_release_dc               gs_texture_release_dc
2014-08-09 11:57:38 -07:00

380 lines
10 KiB
C++

/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
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 2 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 <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "d3d11-subsystem.hpp"
#include "d3d11-shaderprocessor.hpp"
#include <graphics/vec2.h>
#include <graphics/vec3.h>
#include <graphics/matrix3.h>
#include <graphics/matrix4.h>
void gs_vertex_shader::GetBuffersExpected(
const vector<D3D11_INPUT_ELEMENT_DESC> &inputs)
{
for (size_t i = 0; i < inputs.size(); i++) {
const D3D11_INPUT_ELEMENT_DESC &input = inputs[i];
if (strcmp(input.SemanticName, "NORMAL") == 0)
hasNormals = true;
else if (strcmp(input.SemanticName, "TANGENT") == 0)
hasTangents = true;
else if (strcmp(input.SemanticName, "COLOR") == 0)
hasColors = true;
else if (strcmp(input.SemanticName, "TEXCOORD") == 0)
nTexUnits++;
}
}
gs_vertex_shader::gs_vertex_shader(gs_device_t device, const char *file,
const char *shaderString)
: gs_shader (device, GS_SHADER_VERTEX),
hasNormals (false),
hasColors (false),
hasTangents (false),
nTexUnits (0)
{
vector<D3D11_INPUT_ELEMENT_DESC> inputs;
ShaderProcessor processor(device);
ComPtr<ID3D10Blob> shaderBlob;
string outputString;
HRESULT hr;
processor.Process(shaderString, file);
processor.BuildString(outputString);
processor.BuildParams(params);
processor.BuildInputLayout(inputs);
GetBuffersExpected(inputs);
BuildConstantBuffer();
Compile(outputString.c_str(), file, "vs_4_0", shaderBlob.Assign());
hr = device->device->CreateVertexShader(shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(), NULL, shader.Assign());
if (FAILED(hr))
throw HRError("Failed to create vertex shader", hr);
hr = device->device->CreateInputLayout(inputs.data(),
(UINT)inputs.size(), shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(), layout.Assign());
if (FAILED(hr))
throw HRError("Failed to create input layout", hr);
viewProj = gs_shader_get_param_by_name(this, "ViewProj");
world = gs_shader_get_param_by_name(this, "World");
}
gs_pixel_shader::gs_pixel_shader(gs_device_t device, const char *file,
const char *shaderString)
: gs_shader(device, GS_SHADER_PIXEL)
{
ShaderProcessor processor(device);
ComPtr<ID3D10Blob> shaderBlob;
string outputString;
HRESULT hr;
processor.Process(shaderString, file);
processor.BuildString(outputString);
processor.BuildParams(params);
processor.BuildSamplers(samplers);
BuildConstantBuffer();
Compile(outputString.c_str(), file, "ps_4_0", shaderBlob.Assign());
hr = device->device->CreatePixelShader(shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(), NULL, shader.Assign());
if (FAILED(hr))
throw HRError("Failed to create vertex shader", hr);
}
/*
* Shader compilers will pack constants in to single registers when possible.
* For example:
*
* uniform float3 test1;
* uniform float test2;
*
* will inhabit a single constant register (c0.xyz for 'test1', and c0.w for
* 'test2')
*
* However, if two constants cannot inhabit the same register, the second one
* must begin at a new register, for example:
*
* uniform float2 test1;
* uniform float3 test2;
*
* 'test1' will inhabit register constant c0.xy. However, because there's no
* room for 'test2, it must use a new register constant entirely (c1.xyz).
*
* So if we want to calculate the position of the constants in the constant
* buffer, we must take this in to account.
*/
void gs_shader::BuildConstantBuffer()
{
for (size_t i = 0; i < params.size(); i++) {
gs_shader_param &param = params[i];
size_t size = 0;
switch (param.type) {
case GS_SHADER_PARAM_BOOL:
case GS_SHADER_PARAM_INT:
case GS_SHADER_PARAM_FLOAT: size = sizeof(float); break;
case GS_SHADER_PARAM_VEC2: size = sizeof(vec2); break;
case GS_SHADER_PARAM_VEC3: size = sizeof(float)*3; break;
case GS_SHADER_PARAM_VEC4: size = sizeof(vec4); break;
case GS_SHADER_PARAM_MATRIX4X4: size = sizeof(float)*4*4;
}
/* checks to see if this constant needs to start at a new
* register */
if (size && (constantSize & 15) != 0) {
size_t alignMax = (constantSize + 15) & ~15;
if ((size + constantSize) > alignMax)
constantSize = alignMax;
}
param.pos = constantSize;
constantSize += size;
}
if (constantSize) {
D3D11_BUFFER_DESC bd;
HRESULT hr;
memset(&bd, 0, sizeof(bd));
bd.ByteWidth = (constantSize+15)&0xFFFFFFF0; /* align */
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = device->device->CreateBuffer(&bd, NULL,
constants.Assign());
if (FAILED(hr))
throw HRError("Failed to create constant buffer", hr);
}
for (size_t i = 0; i < params.size(); i++)
gs_shader_set_default(&params[i]);
}
void gs_shader::Compile(const char *shaderString, const char *file,
const char *target, ID3D10Blob **shader)
{
ComPtr<ID3D10Blob> errorsBlob;
HRESULT hr;
if (!shaderString)
throw "No shader string specified";
hr = D3DCompile(shaderString, strlen(shaderString), file, NULL, NULL,
"main", target,
D3D10_SHADER_OPTIMIZATION_LEVEL1, 0,
shader, errorsBlob.Assign());
if (FAILED(hr)) {
if (errorsBlob != NULL && errorsBlob->GetBufferSize())
throw ShaderError(errorsBlob, hr);
else
throw HRError("Failed to compile shader", hr);
}
}
inline void gs_shader::UpdateParam(vector<uint8_t> &constData,
gs_shader_param &param, bool &upload)
{
if (param.type != GS_SHADER_PARAM_TEXTURE) {
if (!param.curValue.size())
throw "Not all shader parameters were set";
/* padding in case the constant needs to start at a new
* register */
if (param.pos > constData.size()) {
uint8_t zero = 0;
constData.insert(constData.end(),
param.pos - constData.size(), zero);
}
constData.insert(constData.end(),
param.curValue.begin(),
param.curValue.end());
if (param.changed) {
upload = true;
param.changed = false;
}
} else if (param.curValue.size() == sizeof(gs_texture_t)) {
gs_texture_t tex;
memcpy(&tex, param.curValue.data(), sizeof(gs_texture_t));
device_load_texture(device, tex, param.textureID);
}
}
void gs_shader::UploadParams()
{
vector<uint8_t> constData;
bool upload = false;
constData.reserve(constantSize);
for (size_t i = 0; i < params.size(); i++)
UpdateParam(constData, params[i], upload);
if (constData.size() != constantSize)
throw "Invalid constant data size given to shader";
if (upload) {
D3D11_MAPPED_SUBRESOURCE map;
HRESULT hr;
hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD,
0, &map);
if (FAILED(hr))
throw HRError("Could not lock constant buffer", hr);
memcpy(map.pData, constData.data(), constData.size());
device->context->Unmap(constants, 0);
}
}
void gs_shader_destroy(gs_shader_t shader)
{
delete shader;
}
int gs_shader_get_num_params(gs_shader_t shader)
{
return (int)shader->params.size();
}
gs_sparam_t gs_shader_get_param_by_idx(gs_shader_t shader, uint32_t param)
{
return &shader->params[param];
}
gs_sparam_t gs_shader_get_param_by_name(gs_shader_t shader, const char *name)
{
for (size_t i = 0; i < shader->params.size(); i++) {
gs_shader_param &param = shader->params[i];
if (strcmp(param.name.c_str(), name) == 0)
return &param;
}
return NULL;
}
gs_sparam_t gs_shader_get_viewproj_matrix(gs_shader_t shader)
{
if (shader->type != GS_SHADER_VERTEX)
return NULL;
return static_cast<gs_vertex_shader*>(shader)->viewProj;
}
gs_sparam_t gs_shader_get_world_matrix(gs_shader_t shader)
{
if (shader->type != GS_SHADER_VERTEX)
return NULL;
return static_cast<gs_vertex_shader*>(shader)->world;
}
void gs_shader_get_param_info(gs_sparam_t param,
struct gs_shader_param_info *info)
{
if (!param)
return;
info->name = param->name.c_str();
info->type = param->type;
}
static inline void shader_setval_inline(gs_shader_param *param,
const void *data, size_t size)
{
assert(param);
if (!param)
return;
bool size_changed = param->curValue.size() != size;
if (size_changed)
param->curValue.resize(size);
if (size_changed || memcmp(param->curValue.data(), data, size) != 0) {
memcpy(param->curValue.data(), data, size);
param->changed = true;
}
}
void gs_shader_set_bool(gs_sparam_t param, bool val)
{
shader_setval_inline(param, &val, sizeof(bool));
}
void gs_shader_set_float(gs_sparam_t param, float val)
{
shader_setval_inline(param, &val, sizeof(float));
}
void gs_shader_set_int(gs_sparam_t param, int val)
{
shader_setval_inline(param, &val, sizeof(int));
}
void gs_shader_setmatrix3(gs_sparam_t param, const struct matrix3 *val)
{
struct matrix4 mat;
matrix4_from_matrix3(&mat, val);
shader_setval_inline(param, &mat, sizeof(matrix4));
}
void gs_shader_set_matrix4(gs_sparam_t param, const struct matrix4 *val)
{
shader_setval_inline(param, val, sizeof(matrix4));
}
void gs_shader_set_vec2(gs_sparam_t param, const struct vec2 *val)
{
shader_setval_inline(param, val, sizeof(vec2));
}
void gs_shader_set_vec3(gs_sparam_t param, const struct vec3 *val)
{
shader_setval_inline(param, val, sizeof(float) * 3);
}
void gs_shader_set_vec4(gs_sparam_t param, const struct vec4 *val)
{
shader_setval_inline(param, val, sizeof(vec4));
}
void gs_shader_set_texture(gs_sparam_t param, gs_texture_t val)
{
shader_setval_inline(param, &val, sizeof(gs_texture_t));
}
void gs_shader_set_val(gs_sparam_t param, const void *val, size_t size)
{
shader_setval_inline(param, val, size);
}
void gs_shader_set_default(gs_sparam_t param)
{
if (param->defaultValue.size())
shader_setval_inline(param, param->defaultValue.data(),
param->defaultValue.size());
}