1#include "RenderMaterial.h"
3#include "Rendering/IBuffers.h"
4#include "Rendering/ICapabilities.h"
5#include "Rendering/IContext.h"
6#include "Rendering/IEffects.h"
7#include "Rendering/ITextures.h"
11#include "Resources/MaterialManager.h"
12#include "Systems/Core/CameraSystem.h"
14#include "RenderStates.h"
15#include "RenderResources.h"
20#include "EffectBindings.h"
22#include "Foundation/HashSequence.h"
23#include "Foundation/Logging/Logger.h"
31 size_t calculateHash(
const size_t permutationIndex,
38 size_t instanceCode =
Cogs::hash(permutationIndex);
45 if (definition.isShared) {
46 instanceCode =
Cogs::hash(definition.value, instanceCode);
53 assert(streamsLayout);
55 LOG_ERROR(logger,
"Non-empty MeshStreamsLayout with zero hash");
58 instanceCode =
Cogs::hash(enginePermutation->getCode(), instanceCode);
60 instanceCode =
Cogs::hash(clipShape, instanceCode);
67 if (!binding.renderEffect) {
69 return ActivationResult::Postponed;
72 if (binding.renderEffect->hasFailed()) {
73 if (!renderMaterial->hasFailed()) {
75 auto * material = renderMaterial->getResource();
76 LOG_ERROR(logger,
"Could not initialize bindings for effect %s, failing activation.", material ? material->getName().to_string().c_str() :
"");
78 renderMaterial->setFailed();
81 return ActivationResult::Failure;
82 }
if (binding.renderEffect->isReleased()) {
83 LOG_ERROR(logger,
"Could not initialize bindings for released effect.");
85 renderMaterial->setFailed();
87 return ActivationResult::Failure;
88 }
else if (binding.renderEffect->
isDelayed()) {
89 renderMaterial->setDelayed();
91 return ActivationResult::Delayed;
92 }
else if (!binding.renderEffect->
isActive()) {
93 LOG_DEBUG(logger,
"Could not initialize render material due to uninitialized effect. Re-queuing.");
95 return ActivationResult::Postponed;
98 return ActivationResult::Success;
112 gpubuf.generation = materialBuffer.
generation;
121 if (b->renderEffect &&
HandleIsValid(b->renderEffect->effectHandle) && !b->textureBindings.size()) {
122 b->textureBindings.resize(material->textureProperties.size());
123 b->samplerBindings.resize(material->textureProperties.size());
127 for (
auto& tp : material->textureProperties) {
131 b->samplerBindings[tp.key] = device->
getEffects()->
getSamplerStateBinding(b->renderEffect->effectHandle, tp.name.substr(0, tp.name.find(
"[")) +
"Sampler", unit);
145 size_t N = material->textureProperties.size();
146 renderMaterial->texturePropertyStates.resize(N);
147 for (
size_t i = 0; i < N; i++) {
149 if (t.isPerInstance)
continue;
152 if (
size_t hash = t.texture.hash(); !
HandleIsValid(state.samplerState) || state.hash != hash) {
159 t.texture.filterMode,
160 Cogs::SamplerState::Never,
161 static_cast<unsigned int>(settings.anisotropicFiltering->getInt()),
164 state.samplerState = renderStates->getSamplerState(samplerStateDesc);
165 debug_assert(state.samplerState);
178 binding.renderEffect = renderEffect;
180 auto effectResult = checkEffect(renderMaterial, binding);
182 if (effectResult != ActivationResult::Success)
return effectResult;
190 binding.bufferBindings.resize(material->constantBuffers.
buffers.size());
191 binding.buffers.resize(material->constantBuffers.
buffers.size());
193 for (
auto& buffer : material->constantBuffers.
buffers) {
194 if (!buffer.
size)
continue;
196 binding.bufferBindings[buffer.
index] = effects->getConstantBufferBinding(binding.renderEffect->effectHandle, buffer.
name);
200 deviceBuffers->annotate(binding.buffers[buffer.
index].handle, material->definition.name +
"_mat_" + std::to_string(buffer.
index));
204 auto& effectHandle = binding.renderEffect->effectHandle;
206 binding.sceneBufferBinding = effects->getConstantBufferBinding(effectHandle,
"SceneBuffer");
207 binding.viewBufferBinding = effects->getConstantBufferBinding(effectHandle,
"ViewBuffer");
208 binding.lightBufferBinding = effects->getConstantBufferBinding(effectHandle,
"LightBuffer");
209 binding.shadowBufferBinding = effects->getConstantBufferBinding(effectHandle,
"ShadowBuffer");
210 binding.animationBufferBinding = effects->getConstantBufferBinding(effectHandle,
"AnimationBuffer");
212 binding.shadowArrayBinding = effects->getTextureBinding(effectHandle,
"cascadedShadowMap", 1);
213 binding.shadowArrayBinding_1 = effects->getTextureBinding(effectHandle,
"cascadedShadowMap_1", 1);
214 binding.shadowArraySamplerBinding = effects->getSamplerStateBinding(effectHandle,
"cascadedShadowMapSampler", 1);
215 binding.shadowSamplerBinding = effects->getSamplerStateBinding(effectHandle,
"cascadedShadowSampler", 1);
217 binding.shadowCubeArrayBinding = effects->getTextureBinding(effectHandle,
"cubeShadowMap", 2);
218 binding.shadowCubeArrayBinding_1 = effects->getTextureBinding(effectHandle,
"cubeShadowMap_1", 2);
219 binding.shadowCubeArraySamplerBinding = effects->getSamplerStateBinding(effectHandle,
"cubeShadowMapSampler", 2);
221 binding.skyBinding = effects->getTextureBinding(effectHandle,
"environmentSky", 0);
222 binding.radianceBinding = effects->getTextureBinding(effectHandle,
"environmentRadiance", 0);
223 binding.irradianceBinding = effects->getTextureBinding(effectHandle,
"environmentIrradiance", 0);
224 binding.ambientIrradianceBinding = effects->getTextureBinding(effectHandle,
"ambientIrradiance", 0);
225 binding.brdfLUTBinding = effects->getTextureBinding(effectHandle,
"brdfLUT", 0);
227 binding.skySamplerBinding = effects->getSamplerStateBinding(effectHandle,
"environmentSkySampler", 0);
228 binding.radianceSamplerBinding = effects->getSamplerStateBinding(effectHandle,
"environmentRadianceSampler", 0);
229 binding.irradianceSamplerBinding = effects->getSamplerStateBinding(effectHandle,
"environmentIrradianceSampler", 0);
230 binding.ambientIrradianceSamplerBinding = effects->getSamplerStateBinding(effectHandle,
"ambientIrradianceSampler", 0);
231 binding.brdfLUTSamplerBinding = effects->getSamplerStateBinding(effectHandle,
"brdfLUTSampler", 0);
233 binding.objectBufferBinding = effects->getConstantBufferBinding(effectHandle,
"ObjectBuffer");
235 binding.blueNoise = effects->getTextureBinding(effectHandle,
"blueNoise_LDR_RGBA", 0);
236 binding.blueNoiseStable = effects->getTextureBinding(effectHandle,
"blueNoiseStable_LDR_RGBA", 0);
239 updateTextureBinding(material, device, renderStates, binding);
241 binding.effectGeneration = renderEffect->getGeneration();
242 ++binding.generation;
244 return ActivationResult::Success;
251 auto context = resources->getContext();
252 this->renderer = context->renderer;
254 std::vector<EffectBindingInstance> stillPending;
256 uint32_t results = 0;
257 for (
auto & pending : pendingBindings) {
258 auto & effect = pending.effect;
259 auto binding = pending.binding;
261 auto renderEffect = resources->getRenderEffect(effect);
264 if (renderEffect && binding->effectGeneration != renderEffect->generation) {
265 result = setupBinding(device, renderStates,
this, material, effect.resolve(), renderEffect, *binding);
267 results |=
static_cast<uint32_t
>(result);
270 updateBufferContents(device, material, *binding);
271 bindings.emplace_back(pending);
276 stillPending.emplace_back(pending);
279 for (
auto & binding : bindings) {
280 if (!
HandleIsValid(binding.binding->renderEffect->effectHandle)) {
283 updateBufferContents(device, material, *binding.binding);
287 pendingBindings = std::move(stillPending);
298 }
else if (havePostponed && !haveActive) {
300 }
else if (haveDelayed && !haveActive) {
306 auto instances = context->materialInstanceManager->getAllocatedResources();
308 if (uint32_t gen = material->
getGeneration(); updatedGeneration != gen) {
309 updatedGeneration = gen;
310 updateTextureProperties(
this, resources, renderStates, material);
318 if (materialInstance->
material == material &&
320 materialInstance->setChanged();
329void Cogs::Core::RenderMaterial::release(
Renderer * renderer)
333 for (
auto & b : bindings) {
334 auto binding = b.binding;
336 if (!binding)
continue;
338 for (
auto & buffer : binding->buffers) {
344 binding->buffers.clear();
345 binding->bufferBindings.clear();
350 for (
auto & b : pendingBindings) {
355 pendingBindings.clear();
367 const size_t code = calculateHash(permutationIndex, materialInstance, streamsLayout, enginePermutation, passOptions, clipShape);
370 if (b.code == code)
return b.binding;
374 if (b.code == code)
return b.binding;
379 EffectHandle effect = material->
getEffect(code, materialInstance, streamsLayout, enginePermutation, passOptions, clipShape);
385 material->setChanged();
Contains render resources used by the renderer.
EffectBindings & getEffectBindings() override
Get the reference to the EffectBindings structure.
IGraphicsDevice * getDevice() override
Get the graphics device used by the renderer.
const RenderSettings & getSettings() const override
Get the settings of the renderer.
Represents a graphics device used to manage graphics resources and issue drawing commands.
virtual IEffects * getEffects()=0
Get a pointer to the effect management interface.
virtual IContext * getImmediateContext()=0
Get a pointer to the immediate context used to issue commands to the graphics device.
virtual IBuffers * getBuffers()=0
Get a pointer to the buffer management interface.
Log implementation class.
Contains the Engine, Renderer, resource managers and other systems needed to run Cogs....
ClipShapeType
Specifices what kind of shape a clip shape has.
ActivationResult
Defines results for resource activation.
@ Success
Resource activated successfully.
@ Delayed
Delayed activation.
@ Postponed
Resource activation postponed, retry later.
@ Failure
Resource activation failed.
bool HandleIsValid(const ResourceHandle_t< T > &handle)
Check if the given resource is valid, that is not equal to NoHandle or InvalidHandle.
constexpr Log getLogger(const char(&name)[LEN]) noexcept
constexpr size_t hash() noexcept
Simple getter function that returns the initial value for fnv1a hashing.
@ Write
The buffer can be mapped and written to by the CPU after creation.
@ ConstantBuffer
The buffer can be bound as input to effects as a constant buffer.
std::vector< MaterialPropertyBuffer > buffers
Constant buffer instances.
uint16_t buffersGeneration
If the constant buffer bindings need updates.
Effect resources contain data to control the shader stages of the GPU pipeline.
Material instances represent a specialized Material combined with state for all its buffers and prope...
std::vector< std::string > variantStrings
String storage for string variants.
Material * material
Material resource this MaterialInstance is created from.
ShaderVariantSelectors variantSelectors
Variant selectors.
Material property buffers contain properties for a material, such as color, reflectiveness or other v...
bool isPerInstance
If the buffer is updated per instance.
ConstantBufferKey index
Index of the buffer in the set of buffers owned by the same Material.
size_t size
Total size of the buffer in bytes.
PropertyName name
Name used to refer to the buffer in shaders.
std::vector< uint8_t > content
Default content for property buffer instances created from this buffer.
size_t generation
Generation counter.
Material resources define the how of geometry rendering (the what is defined by Mesh and Texture reso...
EffectHandle getEffect(size_t code, const MaterialInstance *materialInstance, const MeshStreamsLayout *streamsLayout, const EnginePermutation *enginePermutation, const RenderPassOptions &passOptions, const ClipShapeType clipShape)
EffectBinding * getBinding(const size_t permutationIndex, const MaterialInstance *materialInstance, const MeshStreamsLayout *streamsLayout, const EnginePermutation *enginePermutation, const RenderPassOptions &passOptions, const ClipShapeType clipShape)
Material * resource
Engine resource this render resource represents.
bool isDelayed() const
Get if the render resource is in a delayed state.
bool isActive() const
Get if the render resource is active and can be used for rendering.
Render settings variables.
uint32_t getGeneration() const
Get the generation count.
uint32_t referenceCount() const
Get the current reference count.
Property value for texture samplers.
Provides buffer management functionality.
virtual void releaseBuffer(BufferHandle bufferHandle)=0
Releases the buffer with the given bufferHandle.
Represents a graphics device context which can receive rendering commands.
virtual void updateBuffer(BufferHandle bufferHandle, const void *data, size_t size)=0
Replace contents of buffer with new data.
virtual SamplerStateBindingHandle getSamplerStateBinding(EffectHandle effectHandle, const StringView &name, const unsigned int slot)=0
Get a handle to a sampler state object binding, mapping how to bind the sampler state to the given ef...
virtual TextureBindingHandle getTextureBinding(EffectHandle effectHandle, const StringView &name, const unsigned int slot)=0
Get a handle to a texture object binding, mapping how to bind textures to the given effect.
Encapsulates state for texture sampling in a state object.
@ Dynamic
Buffer will be loaded and modified with some frequency.