Cogs.Core
RenderMaterialInstance.cpp
1#include "RenderMaterialInstance.h"
2
3#include "Rendering/IEffects.h"
4#include "Rendering/IBuffers.h"
5#include "Rendering/IContext.h"
6#include "Rendering/ITextures.h"
7#include "Rendering/ICapabilities.h"
8
9#include "Context.h"
10
11#include "RenderStates.h"
12#include "RenderResources.h"
13#include "Resources/MaterialManager.h"
14
15#include "Renderer.h"
16#include "Engine.h"
17
18#include "Foundation/HashSequence.h"
19#include "Foundation/Logging/Logger.h"
20
21namespace
22{
23 using namespace Cogs::Core;
24
25 Cogs::Logging::Log logger = Cogs::Logging::getLogger("RenderMaterialInstance");
26
27 void clearBuffers(RenderMaterialInstance* that, Cogs::IBuffers* deviceBuffers)
28 {
29 for (auto& buffer : that->ownedBuffers) {
30 if (HandleIsValid(buffer)) {
31 deviceBuffers->releaseBuffer(buffer);
32 }
33 }
34
35 for (auto& buffer : that->buffers) {
36 buffer.handle = Cogs::BufferHandle::NoHandle;
37 buffer.generation = 0;
38 }
39
40 that->ownedBuffers.clear();
41 }
42
43 size_t getBindingCode(const MeshStreamsLayout& streamsLayout,
44 const EnginePermutation* permutation,
45 const RenderPassOptions& passOptions,
46 ClipShapeType clipShape)
47 {
48 if (streamsLayout.numStreams && streamsLayout.hash == 0) {
49 LOG_ERROR(logger, "MeshStreamsLayout has streams but hash is zero.");
50 }
51 return Cogs::hashSequence(streamsLayout.hash, permutation->getCode(), passOptions.hash, clipShape);
52 }
53
54 void updateBindings(RenderMaterialInstance* that,
55 MaterialInstance* materialInstance,
56 const Material* material,
58 EffectBinding* /*effectBinding*/)
59 {
60 Cogs::IBuffers* deviceBuffers = device->getBuffers();
61 Cogs::IContext* immediateContext = device->getImmediateContext();
62
63 if (that->context->variables->get("renderer.disableMaterialUpdates", false)) {
64 return;
65 }
66
67 if (that->buffersGeneration != materialInstance->buffersGeneration) {
68 that->buffersGeneration = materialInstance->buffersGeneration;
69
70 // If a binding permutation has been encountered earlier with valid bindings for only a
71 // subset of buffers, we may have both owned buffers and missing buffers.
72 clearBuffers(that, deviceBuffers);
73
74 that->buffers.resize(material->constantBuffers.buffers.size());
75
76 for (auto& buffer : material->constantBuffers.buffers) {
77
78 if (buffer.isPerInstance && buffer.size) {
79 that->buffers[buffer.index].handle = deviceBuffers->loadBuffer(nullptr, buffer.size, Cogs::Usage::Dynamic, Cogs::AccessMode::Write, Cogs::BindFlags::ConstantBuffer);
80 deviceBuffers->annotate(that->buffers[buffer.index].handle, material->definition.name + "_matinst_" + std::to_string(buffer.index));
81
82 that->ownedBuffers.push_back(that->buffers[buffer.index].handle);
83 that->buffers[buffer.index].bound = true;
84 }
85 }
86 }
87
88 for (auto& buffer : material->constantBuffers.buffers) {
89 if (!buffer.isPerInstance) continue;
90
91 auto& instanceBuffer = materialInstance->buffers[buffer.index];
92 RenderMaterialInstance::UpdateBuffer& updateBuffer = that->buffers[buffer.index];
93
94 bool dirty = updateBuffer.generation != instanceBuffer.generation;
95
96 if (dirty && HandleIsValid(updateBuffer.handle)) {
97 immediateContext->updateBuffer(updateBuffer.handle, instanceBuffer.content.data(), buffer.size);
98 updateBuffer.generation = instanceBuffer.generation;
99 }
100 }
101 }
102
103
104 void updateTextureProperties(RenderMaterialInstance* that,
105 MaterialInstance* materialInstance,
106 Cogs::IGraphicsDevice* /*device*/,
107 RenderStates* renderStates)
108 {
109 auto& settings = that->context->renderer->getSettings();
110
111 // Allocate enough room to store a sampler state per texture.
112 that->samplerStates.resize(materialInstance->textureVariables.size());
113
114 for (auto& t : materialInstance->textureVariables) {
115 if (t.dirty || !HandleIsValid(that->samplerStates[t.key])) {
116 unsigned int anisotropy = 1;
117 if (t.texture.filterMode == Cogs::SamplerState::FilterMode::MinMagMipLinear) {
118 anisotropy = static_cast<unsigned int>(settings.anisotropicFiltering->getInt());
119 }
120 const Cogs::SamplerState state = {
121 t.texture.sMode,
122 t.texture.tMode,
123 t.texture.uMode,
124 t.texture.filterMode,
125 Cogs::SamplerState::Never,
126 anisotropy,
127 { 0, 0, 0, 1 }
128 };
129
130 that->samplerStates[t.key] = renderStates->getSamplerState(state);
131
132 debug_assert(HandleIsValid(that->samplerStates[t.key]));
133
134 t.dirty = false;
135 }
136 }
137 }
138
139 ActivationResult checkMaterial(RenderMaterialInstance* instance, RenderMaterial* renderMaterial)
140 {
141 if (!renderMaterial) {
142 return ActivationResult::Postponed;
143 }
144
145 if (renderMaterial->hasFailed()) {
146 instance->setFailed();
147 return ActivationResult::Failure;
148 }
149 else if (renderMaterial->isReleased()) {
150 LOG_ERROR(logger, "Could not initialize material instance for released material.");
151 instance->setFailed();
152 return ActivationResult::Failure;
153 }
154 else if (renderMaterial->isDelayed()) {
155 instance->setDelayed();
156 return ActivationResult::Delayed;
157 }
158 else if (!renderMaterial->isActive()) {
159 return ActivationResult::Postponed;
160 }
161
162 return ActivationResult::Success;
163 }
164
165
166 const EffectBinding* checkEffectBinding(Context* context,
167 EffectBinding* effectBinding,
168 RenderMaterial* renderMaterial,
169 MaterialInstance* materialInstance,
170 Material* material,
171 uint16_t buffersGeneration)
172 {
173 if (effectBinding->buffersGeneration == material->constantBuffers.buffersGeneration &&
174 buffersGeneration == materialInstance->buffersGeneration)
175 {
176 return effectBinding;
177 }
178
179 if (renderMaterial->isDelayed() || !renderMaterial->pendingBindings.empty()) {
180 material->setChanged();
181 }
182
183 if (materialInstance->hasFailedActivation()) {
184 materialInstance->setChanged();
185 material->setChanged();
186 }
187
188 context->engine->setDirty();
189 return nullptr;
190 }
191
192}
193
194Cogs::Core::ActivationResult Cogs::Core::RenderMaterialInstance::update(MaterialInstance* materialInstance,
195 IGraphicsDevice* device,
196 RenderResources* resources,
197 RenderStates* renderStates)
198{
199 context = resources->getContext();
200
201 Material* material = materialInstance->material;
202 assert(material);
203
204 renderMaterial = resources->getRenderMaterial(materialInstance->material);
205
206 auto checkResult = checkMaterial(this, renderMaterial);
207
208 if (checkResult != ActivationResult::Success) return checkResult;
209
210 updateTextureProperties(this, materialInstance, device, renderStates);
211
212 if ((permutationIndex != materialInstance->permutationIndex) ||
213 (materialVariantGeneration != material->variantGeneration) ||
214 (instanceVariantGeneration != materialInstance->variantGeneration))
215 {
216 loadedBindings.clear();
217 pendingBindings.clear();
218
219 permutationIndex = materialInstance->permutationIndex;
220 materialVariantGeneration = material->variantGeneration;
221 instanceVariantGeneration = materialInstance->variantGeneration;
222 }
223
224 std::vector<RenderEffectBinding> stillPending;
225
226 for (RenderEffectBinding& pending : pendingBindings) {
227
228 EffectBinding* binding = renderMaterial->getBinding(permutationIndex,
229 materialInstance,
230 &pending.streamsLayout,
231 pending.enginePermutation,
232 pending.passOptions,
233 pending.clipShape);
234
235 if (binding) {
236 pending.binding = binding;
237 loadedBindings.push_back(std::move(pending));
238 }
239 else {
240 stillPending.push_back(std::move(pending));
241 materialInstance->setChanged();
242 }
243 }
244
245 pendingBindings = std::move(stillPending);
246
247 for (auto & loaded : loadedBindings) {
248 updateBindings(this, materialInstance, materialInstance->material, device, loaded.binding);
249 }
250
251 setActive();
252
254}
255
256
257void Cogs::Core::RenderMaterialInstance::release(Renderer * renderer)
258{
259 assert(!isReleased());
260
261 clearBuffers(this, renderer->getDevice()->getBuffers());
262
263 setReleased();
264}
265
267 const EnginePermutation* permutation,
268 const RenderPassOptions& passOptions,
269 ClipShapeType clipShape,
270 const RenderTarget* renderTarget)
271{
272 MaterialInstance* materialInstance = getResource();
273 Material* material = materialInstance->material;
274
275 permutation = context->renderer->getEnginePermutations().get(permutation->getIndex());
276
277 size_t bindingCode = getBindingCode(streamsLayout, permutation, passOptions, clipShape);
278
279 for (RenderEffectBinding& binding : loadedBindings) {
280 if (binding.permutationCode == bindingCode) {
281 return checkEffectBinding(context, binding.binding, renderMaterial, materialInstance, material, buffersGeneration);
282 }
283 }
284
285 bool pending = false;
286 for (RenderEffectBinding& binding : pendingBindings) {
287 if (binding.permutationCode == bindingCode) {
288 pending = true;
289 break;
290 }
291 }
292
293
294 if (renderMaterial) {
295 EffectBinding* bindings = renderMaterial->getBinding(permutationIndex,
296 materialInstance,
297 &streamsLayout,
298 permutation,
299 passOptions,
300 clipShape);
301
302 if (bindings) {
303 auto device = context->renderer->getDevice();
304 updateBindings(this, materialInstance, material, device, bindings);
305 updateTextureProperties(this, materialInstance, device, &context->renderer->getRenderStates());
306
307 loadedBindings.push_back(RenderEffectBinding { bindingCode, streamsLayout, permutation, passOptions, clipShape, bindings });
308
309 if (pending) {
310 for (size_t i = 0; i < pendingBindings.size(); ++i) {
311 if (pendingBindings[i].permutationCode == bindingCode) {
312 pendingBindings.erase(pendingBindings.begin() + static_cast<ptrdiff_t>(i));
313 break;
314 }
315 }
316 }
317 return checkEffectBinding(context, bindings, renderMaterial, materialInstance, material, buffersGeneration);
318 }
319 }
320
321 if (!pending) {
322 pendingBindings.emplace_back(RenderEffectBinding{ bindingCode, streamsLayout, permutation, passOptions, clipShape, nullptr });
323 }
324
325 materialInstance->setChanged();
326 if (materialInstance->hasFailedActivation()) {
327 material->setChanged();
328 }
329
330 context->engine->setDirty();
331 return nullptr;
332}
A Context instance contains all the services, systems and runtime components needed to use Cogs.
Definition: Context.h:83
class IRenderer * renderer
Renderer.
Definition: Context.h:228
std::unique_ptr< class Variables > variables
Variables service instance.
Definition: Context.h:180
std::unique_ptr< class Engine > engine
Engine instance.
Definition: Context.h:222
virtual RenderStates & getRenderStates()=0
Get the reference to the RenderStates structure.
virtual IGraphicsDevice * getDevice()=0
Get the graphics device used by the renderer.
virtual EnginePermutations & getEnginePermutations()=0
Get the reference to the EnginePermutations structure.
virtual const RenderSettings & getSettings() const =0
Get the settings of the renderer.
Contains render resources used by the renderer.
Core renderer system.
Definition: Renderer.h:29
IGraphicsDevice * getDevice() override
Get the graphics device used by the renderer.
Definition: Renderer.h:46
Represents a graphics device used to manage graphics resources and issue drawing commands.
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.
Definition: LogManager.h:140
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.
Definition: ResourceBase.h:14
@ Success
Resource activated successfully.
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
Definition: LogManager.h:181
constexpr size_t hashSequence(const T &t, const U &u)
Hash the last two items in a sequence of objects.
Definition: HashSequence.h:8
@ Write
The buffer can be mapped and written to by the CPU after creation.
Definition: Flags.h:50
@ ConstantBuffer
The buffer can be bound as input to effects as a constant buffer.
Definition: Flags.h:72
std::vector< MaterialPropertyBuffer > buffers
Constant buffer instances.
uint16_t buffersGeneration
If the constant buffer bindings need updates.
Material instances represent a specialized Material combined with state for all its buffers and prope...
std::vector< TextureValue > textureVariables
Texture property values for this instance.
uint16_t buffersGeneration
If the material buffer bindings need updates.
std::vector< MaterialPropertyBufferInstance > buffers
Buffer instances matching the buffers and layout of the parent material.
size_t variantGeneration
If the variant or definitions need updates.
size_t permutationIndex
Index of material permutation to use.
Material * material
Material resource this MaterialInstance is created from.
Material resources define the how of geometry rendering (the what is defined by Mesh and Texture reso...
Definition: Material.h:82
const EffectBinding * checkReady(const MeshStreamsLayout &streamsLayout, const EnginePermutation *permutation, const RenderPassOptions &passOptions, ClipShapeType clipShape, const RenderTarget *renderTarget)
EffectBinding * getBinding(const size_t permutationIndex, const MaterialInstance *materialInstance, const MeshStreamsLayout *streamsLayout, const EnginePermutation *enginePermutation, const RenderPassOptions &passOptions, const ClipShapeType clipShape)
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.
static const Handle_t NoHandle
Represents a handle to nothing.
Definition: Common.h:78
Provides buffer management functionality.
Definition: IBuffers.h:13
virtual void annotate(BufferHandle handle, const StringView &name)
Associate a name with an object for use in graphics debugging.
Definition: IBuffers.h:17
virtual BufferHandle loadBuffer(const void *data, const size_t size, Usage::EUsage usage, uint32_t accessMode, uint32_t bindFlags, uint32_t stride=0)=0
Loads a new buffer using the given data to populate the buffer.
virtual void releaseBuffer(BufferHandle bufferHandle)=0
Releases the buffer with the given bufferHandle.
Represents a graphics device context which can receive rendering commands.
Definition: IContext.h:43
virtual void updateBuffer(BufferHandle bufferHandle, const void *data, size_t size)=0
Replace contents of buffer with new data.
Encapsulates state for texture sampling in a state object.
Definition: SamplerState.h:12
@ MinMagMipLinear
Linear sampling for both minification and magnification.
Definition: SamplerState.h:35
@ Dynamic
Buffer will be loaded and modified with some frequency.
Definition: Flags.h:30