summaryrefslogtreecommitdiff
path: root/Source/Core/VideoCommon/Resources/MaterialResource.cpp
blob: ea96cdf5f68bfb6a923a5e960ce4f05dd9f5ae5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2025 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "VideoCommon/Resources/MaterialResource.h"

#include <utility>

#include <xxh3.h>

#include "Common/VariantUtil.h"

#include "VideoCommon/AbstractGfx.h"
#include "VideoCommon/Assets/CustomAssetCache.h"
#include "VideoCommon/AsyncShaderCompiler.h"
#include "VideoCommon/FramebufferManager.h"
#include "VideoCommon/PipelineUtils.h"
#include "VideoCommon/Resources/CustomResourceManager.h"
#include "VideoCommon/VideoConfig.h"

namespace
{
// TODO: absorb this with TextureCacheBase
bool IsAnisotropicEnhancementSafe(const SamplerState::TM0& tm0)
{
  return !(tm0.min_filter == FilterMode::Near && tm0.mag_filter == FilterMode::Near);
}

// TODO: absorb this with TextureCacheBase
SamplerState CalculateSamplerAnisotropy(const SamplerState& initial_sampler)
{
  SamplerState state = initial_sampler;
  if (g_ActiveConfig.iMaxAnisotropy != AnisotropicFilteringMode::Default &&
      IsAnisotropicEnhancementSafe(state.tm0))
  {
    state.tm0.anisotropic_filtering = std::to_underlying(g_ActiveConfig.iMaxAnisotropy);
  }

  if (state.tm0.anisotropic_filtering != 0)
  {
    // https://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt
    // For predictable results on all hardware/drivers, only use one of:
    //	GL_LINEAR + GL_LINEAR (No Mipmaps [Bilinear])
    //	GL_LINEAR + GL_LINEAR_MIPMAP_LINEAR (w/ Mipmaps [Trilinear])
    // Letting the game set other combinations will have varying arbitrary results;
    // possibly being interpreted as equal to bilinear/trilinear, implicitly
    // disabling anisotropy, or changing the anisotropic algorithm employed.
    state.tm0.min_filter = FilterMode::Linear;
    state.tm0.mag_filter = FilterMode::Linear;
    state.tm0.mipmap_filter = FilterMode::Linear;
  }
  return state;
}
}  // namespace

namespace VideoCommon
{
MaterialResource::MaterialResource(Resource::ResourceContext resource_context)
    : Resource(std::move(resource_context))
{
  m_material_asset = m_resource_context.asset_cache->CreateAsset<MaterialAsset>(
      m_resource_context.primary_asset_id, m_resource_context.asset_library, this);
}

MaterialResource::MaterialResource(Resource::ResourceContext resource_context,
                                   GXPipelineUid pipeline_uid)
    : Resource(std::move(resource_context)), m_uid(std::move(pipeline_uid))
{
  m_material_asset = m_resource_context.asset_cache->CreateAsset<MaterialAsset>(
      m_resource_context.primary_asset_id, m_resource_context.asset_library, this);
  m_uid_vertex_format_copy =
      g_gfx->CreateNativeVertexFormat(m_uid->vertex_format->GetVertexDeclaration());
  m_uid->vertex_format = m_uid_vertex_format_copy.get();
}

void MaterialResource::ResetData()
{
  if (m_current_data)
  {
    m_current_data->m_shader_resource->RemoveReference(this);
    for (const auto& texture_like_resource : m_current_data->m_texture_like_resources)
    {
      if (texture_like_resource)
        texture_like_resource->RemoveReference(this);
    }
    if (m_current_data->m_next_material)
      m_current_data->m_next_material->RemoveReference(this);
  }
  m_load_data = std::make_shared<Data>();
  m_processing_load_data = false;
}

Resource::TaskComplete MaterialResource::CollectPrimaryData()
{
  const auto material_data = m_material_asset->GetData();
  if (!material_data) [[unlikely]]
  {
    return Resource::TaskComplete::No;
  }
  m_load_data->m_material_data = material_data;

  // A shader asset is required to function
  if (m_load_data->m_material_data->shader_asset == "")
  {
    return Resource::TaskComplete::Error;
  }

  CreateTextureData(m_load_data.get());
  SetShaderKey(m_load_data.get(), m_uid ? &*m_uid : nullptr);

  return Resource::TaskComplete::Yes;
}

Resource::TaskComplete MaterialResource::CollectDependencyData()
{
  bool loaded = true;
  {
    auto* const shader_resource = m_resource_context.resource_manager->GetShaderFromAsset(
        m_load_data->m_material_data->shader_asset, m_load_data->m_shader_key, m_uid,
        m_load_data->m_preprocessor_settings, m_resource_context.asset_library);
    shader_resource->AddReference(this);
    m_load_data->m_shader_resource = shader_resource;
    const auto data_processed = shader_resource->IsDataProcessed();
    if (data_processed == TaskComplete::Error)
      return TaskComplete::Error;

    loaded &= data_processed == TaskComplete::Yes;
  }

  for (std::size_t i = 0; i < m_load_data->m_material_data->textures.size(); i++)
  {
    const auto& texture_and_sampler = m_load_data->m_material_data->textures[i];
    if (texture_and_sampler.asset == "")
      continue;

    const auto texture = m_resource_context.resource_manager->GetTextureAndSamplerFromAsset(
        texture_and_sampler.asset, m_resource_context.asset_library);
    m_load_data->m_texture_like_resources[i] = texture;
    m_load_data->m_texture_like_data[i] = texture->GetData();
    texture->AddReference(this);

    const auto data_processed = texture->IsDataProcessed();
    if (data_processed == TaskComplete::Error)
      return TaskComplete::Error;

    loaded &= data_processed == TaskComplete::Yes;
  }

  if (m_load_data->m_material_data->next_material_asset != "")
  {
    if (m_uid)
    {
      m_load_data->m_next_material = m_resource_context.resource_manager->GetDrawMaterialFromAsset(
          m_load_data->m_material_data->next_material_asset, *m_uid,
          m_resource_context.asset_library);
    }
    else
    {
      m_load_data->m_next_material =
          m_resource_context.resource_manager->GetPostProcessingMaterialFromAsset(
              m_load_data->m_material_data->next_material_asset, m_resource_context.asset_library);
    }
    m_load_data->m_next_material->AddReference(this);
    const auto data_processed = m_load_data->m_next_material->IsDataProcessed();
    if (data_processed == TaskComplete::Error)
      return TaskComplete::Error;

    loaded &= data_processed == TaskComplete::Yes;
  }

  return loaded ? TaskComplete::Yes : TaskComplete::No;
}

Resource::TaskComplete MaterialResource::ProcessData()
{
  auto shader_data = m_load_data->m_shader_resource->GetData();

  if (!shader_data) [[unlikely]]
    return Resource::TaskComplete::Error;

  for (std::size_t i = 0; i < m_load_data->m_texture_like_data.size(); i++)
  {
    auto& texture_like_reference = m_load_data->m_texture_like_references[i];
    const auto& texture_and_sampler = m_load_data->m_material_data->textures[i];

    // If the texture doesn't exist, use one of the placeholders
    if (texture_and_sampler.asset == "")
    {
      const auto texture_type = shader_data->GetTextureType(i);
      if (texture_type == AbstractTextureType::Texture_2D)
        texture_like_reference.texture = m_resource_context.invalid_color_texture;
      else if (texture_type == AbstractTextureType::Texture_2DArray)
        texture_like_reference.texture = m_resource_context.invalid_array_texture;
      else if (texture_type == AbstractTextureType::Texture_CubeMap)
        texture_like_reference.texture = m_resource_context.invalid_cubemap_texture;

      if (texture_like_reference.texture == nullptr)
      {
        PanicAlertFmt("Invalid texture (texture_type={}) is not found during material "
                      "resource processing (asset_id={})",
                      texture_type, m_resource_context.primary_asset_id);
      }

      continue;
    }

    auto& texture_like_data = m_load_data->m_texture_like_data[i];

    std::visit(overloaded{[&](const std::shared_ptr<TextureAndSamplerResource::Data>& data) {
                 texture_like_reference.texture = data->GetTexture();
                 texture_like_reference.sampler = CalculateSamplerAnisotropy(data->GetSampler());
                 ;
               }},
               texture_like_data);
  }

  class WorkItem final : public VideoCommon::AsyncShaderCompiler::WorkItem
  {
  public:
    WorkItem(std::shared_ptr<MaterialResource::Data> material_resource_data,
             std::shared_ptr<ShaderResource::Data> shader_resource_data,
             VideoCommon::GXPipelineUid* uid, FramebufferState frame_buffer_state)
        : m_material_resource_data(std::move(material_resource_data)),
          m_shader_resource_data(std::move(shader_resource_data)), m_uid(uid),
          m_frame_buffer_state(std::move(frame_buffer_state))
    {
    }

    bool Compile() override
    {
      // Sanity check
      if (!m_shader_resource_data->IsCompiled())
      {
        m_material_resource_data->m_processing_finished = true;
        return false;
      }

      AbstractPipelineConfig config;
      config.vertex_shader = m_shader_resource_data->GetVertexShader();
      config.pixel_shader = m_shader_resource_data->GetPixelShader();
      config.geometry_shader = m_shader_resource_data->GetGeometryShader();

      if (m_uid)
      {
        // Draw based pipeline
        const auto actual_uid = ApplyDriverBugs(*m_uid);

        if (m_material_resource_data->m_material_data->blending_state)
          config.blending_state = *m_material_resource_data->m_material_data->blending_state;
        else
          config.blending_state = actual_uid.blending_state;

        if (m_material_resource_data->m_material_data->depth_state)
          config.depth_state = *m_material_resource_data->m_material_data->depth_state;
        else
          config.depth_state = actual_uid.depth_state;

        config.framebuffer_state = std::move(m_frame_buffer_state);
        config.framebuffer_state.additional_color_attachment_count = 0;

        config.rasterization_state = actual_uid.rasterization_state;
        if (m_material_resource_data->m_material_data->cull_mode)
        {
          config.rasterization_state.cull_mode =
              *m_material_resource_data->m_material_data->cull_mode;
        }

        config.vertex_format = actual_uid.vertex_format;
        config.usage = AbstractPipelineUsage::GX;
      }
      else
      {
        // Post processing based pipeline

        // Many of these properties don't make sense to replace but we expose them for draw
        // based materials, might as well allow them to be used if the user wants

        if (m_material_resource_data->m_material_data->blending_state)
          config.blending_state = *m_material_resource_data->m_material_data->blending_state;
        else
          config.blending_state = RenderState::GetNoBlendingBlendState();

        if (m_material_resource_data->m_material_data->depth_state)
          config.depth_state = *m_material_resource_data->m_material_data->depth_state;
        else
          config.depth_state = RenderState::GetNoDepthTestingDepthState();

        config.framebuffer_state = RenderState::GetRGBA8FramebufferState();

        config.rasterization_state =
            RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
        if (m_material_resource_data->m_material_data->cull_mode)
        {
          config.rasterization_state.cull_mode =
              *m_material_resource_data->m_material_data->cull_mode;
        }

        config.vertex_format = nullptr;
        config.usage = AbstractPipelineUsage::Utility;
      }

      m_material_resource_data->m_pipeline = g_gfx->CreatePipeline(config);
      if (m_material_resource_data->m_pipeline)
      {
        WriteUniforms(m_material_resource_data.get());
      }
      m_material_resource_data->m_processing_finished = true;
      return true;
    }
    void Retrieve() override {}

  private:
    std::shared_ptr<MaterialResource::Data> m_material_resource_data;
    std::shared_ptr<ShaderResource::Data> m_shader_resource_data;
    VideoCommon::GXPipelineUid* m_uid;
    FramebufferState m_frame_buffer_state;
  };

  if (!m_processing_load_data)
  {
    auto wi = m_resource_context.shader_compiler->CreateWorkItem<WorkItem>(
        m_load_data, std::move(shader_data), m_uid ? &*m_uid : nullptr,
        g_framebuffer_manager->GetEFBFramebufferState());

    // We don't need priority, that is already handled by the resource system
    m_resource_context.shader_compiler->QueueWorkItem(std::move(wi), 0);
    m_processing_load_data = true;
  }

  if (!m_load_data->m_processing_finished)
    return TaskComplete::No;

  if (!m_load_data->m_pipeline)
  {
    return TaskComplete::Error;
  }

  std::swap(m_current_data, m_load_data);
  return TaskComplete::Yes;
}

void MaterialResource::MarkAsActive()
{
  if (!m_current_data) [[unlikely]]
    return;

  m_resource_context.asset_cache->MarkAssetActive(m_material_asset);
  for (const auto& texture_like_resource : m_current_data->m_texture_like_resources)
  {
    if (texture_like_resource)
      texture_like_resource->MarkAsActive();
  }
  if (m_current_data->m_shader_resource)
    m_current_data->m_shader_resource->MarkAsActive();
  if (m_current_data->m_next_material)
    m_current_data->m_next_material->MarkAsActive();
}

void MaterialResource::MarkAsPending()
{
  m_resource_context.asset_cache->MarkAssetPending(m_material_asset);
}

void MaterialResource::CreateTextureData(Data* data)
{
  ShaderCode preprocessor_settings;

  const auto& material_data = *data->m_material_data;
  data->m_texture_like_data.clear();
  data->m_texture_like_resources.clear();
  data->m_texture_like_references.clear();
  const u32 custom_sampler_index_offset = 8;
  for (u32 i = 0; i < static_cast<u32>(material_data.textures.size()); i++)
  {
    const auto& texture_and_sampler = material_data.textures[i];
    data->m_texture_like_references.push_back(TextureLikeReference{});

    TextureAndSamplerResource* value = nullptr;
    data->m_texture_like_resources.push_back(value);
    data->m_texture_like_data.push_back(std::shared_ptr<TextureAndSamplerResource::Data>{});

    auto& texture_like_reference = data->m_texture_like_references[i];

    if (texture_and_sampler.asset == "")
    {
      preprocessor_settings.Write("#define HAS_SAMPLER_{} 0\n", i);

      // For an invalid asset, force the sampler to use the default sampler
      texture_like_reference.sampler_origin =
          VideoCommon::TextureSamplerValue::SamplerOrigin::Asset;
      texture_like_reference.texture_hash = "";
    }
    else
    {
      preprocessor_settings.Write("#define HAS_SAMPLER_{} 1\n", i);

      texture_like_reference.sampler_origin = texture_and_sampler.sampler_origin;
      texture_like_reference.texture_hash = texture_and_sampler.texture_hash;
    }

    texture_like_reference.sampler_index = i + custom_sampler_index_offset;
    texture_like_reference.texture = nullptr;
  }

  data->m_preprocessor_settings = preprocessor_settings.GetBuffer();
}

void MaterialResource::SetShaderKey(Data* data, GXPipelineUid* uid)
{
  XXH3_state_t shader_key_hash;
  XXH3_INITSTATE(&shader_key_hash);
  XXH3_64bits_reset_withSeed(&shader_key_hash, static_cast<XXH64_hash_t>(1));

  if (uid)
    UpdateHashWithPipeline(*uid, &shader_key_hash);
  XXH3_64bits_update(&shader_key_hash, data->m_preprocessor_settings.c_str(),
                     data->m_preprocessor_settings.size());

  data->m_shader_key = XXH3_64bits_digest(&shader_key_hash);
}

void MaterialResource::WriteUniforms(Data* data)
{
  // Calculate the size in memory of the buffer
  std::size_t max_uniformdata_size = 0;
  for (const auto& property : data->m_material_data->properties)
  {
    max_uniformdata_size += VideoCommon::MaterialProperty::GetMemorySize(property);
  }
  data->m_uniform_data = Common::UniqueBuffer<u8>(max_uniformdata_size);

  // Now write the memory
  u8* uniform_data = data->m_uniform_data.data();
  for (const auto& property : data->m_material_data->properties)
  {
    VideoCommon::MaterialProperty::WriteToMemory(uniform_data, property);
  }
}
}  // namespace VideoCommon