summaryrefslogtreecommitdiff
path: root/Source/Core/VideoCommon/Assets/DirectFilesystemAssetLibrary.cpp
blob: cbb3046f4da1c795f393fba145de179ae9063884 (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
// Copyright 2023 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "VideoCommon/Assets/DirectFilesystemAssetLibrary.h"

#include <algorithm>

#include <fmt/std.h>

#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/StringUtil.h"
#include "VideoCommon/Assets/MaterialAsset.h"
#include "VideoCommon/Assets/ShaderAsset.h"

namespace VideoCommon
{
namespace
{
std::chrono::system_clock::time_point FileTimeToSysTime(std::filesystem::file_time_type file_time)
{
#ifdef _WIN32
  return std::chrono::clock_cast<std::chrono::system_clock>(file_time);
#else
  // Note: all compilers should switch to chrono::clock_cast
  // once it is available for use
  const auto system_time_now = std::chrono::system_clock::now();
  const auto file_time_now = decltype(file_time)::clock::now();
  return std::chrono::time_point_cast<std::chrono::system_clock::duration>(
      file_time - file_time_now + system_time_now);
#endif
}

std::size_t GetAssetSize(const CustomTextureData& data)
{
  std::size_t total = 0;
  for (const auto& slice : data.m_slices)
  {
    for (const auto& level : slice.m_levels)
    {
      total += level.data.size();
    }
  }
  return total;
}
}  // namespace
CustomAssetLibrary::TimeType
DirectFilesystemAssetLibrary::GetLastAssetWriteTime(const AssetID& asset_id) const
{
  std::lock_guard lk(m_lock);
  if (auto iter = m_assetid_to_asset_map_path.find(asset_id);
      iter != m_assetid_to_asset_map_path.end())
  {
    const auto& asset_map_path = iter->second;
    CustomAssetLibrary::TimeType max_entry;
    for (const auto& [key, value] : asset_map_path)
    {
      std::error_code ec;
      const auto tp = std::filesystem::last_write_time(value, ec);
      if (ec)
        continue;
      auto tp_sys = FileTimeToSysTime(tp);
      if (tp_sys > max_entry)
        max_entry = tp_sys;
    }
    return max_entry;
  }

  return {};
}

CustomAssetLibrary::LoadInfo DirectFilesystemAssetLibrary::LoadPixelShader(const AssetID& asset_id,
                                                                           PixelShaderData* data)
{
  const auto asset_map = GetAssetMapForID(asset_id);

  // Asset map for a pixel shader is the shader and some metadata
  if (asset_map.size() != 2)
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' expected to have two files mapped!", asset_id);
    return {};
  }

  const auto metadata = asset_map.find("metadata");
  const auto shader = asset_map.find("shader");
  if (metadata == asset_map.end())
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' expected to have a metadata entry mapped!", asset_id);
    return {};
  }

  if (shader == asset_map.end())
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' expected to have a shader entry mapped!", asset_id);
    return {};
  }

  std::size_t metadata_size;
  {
    std::error_code ec;
    metadata_size = std::filesystem::file_size(metadata->second, ec);
    if (ec)
    {
      ERROR_LOG_FMT(VIDEO,
                    "Asset '{}' error - failed to get shader metadata file size with error '{}'!",
                    asset_id, ec);
      return {};
    }
  }
  std::size_t shader_size;
  {
    std::error_code ec;
    shader_size = std::filesystem::file_size(shader->second, ec);
    if (ec)
    {
      ERROR_LOG_FMT(VIDEO,
                    "Asset '{}' error - failed to get shader source file size with error '{}'!",
                    asset_id, ec);
      return {};
    }
  }
  const auto approx_mem_size = metadata_size + shader_size;

  if (!File::ReadFileToString(PathToString(shader->second), data->m_shader_source))
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error -  failed to load the shader file '{}',", asset_id,
                  PathToString(shader->second));
    return {};
  }

  std::string json_data;
  if (!File::ReadFileToString(PathToString(metadata->second), json_data))
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error -  failed to load the json file '{}',", asset_id,
                  PathToString(metadata->second));
    return {};
  }

  picojson::value root;
  const auto error = picojson::parse(root, json_data);

  if (!error.empty())
  {
    ERROR_LOG_FMT(VIDEO,
                  "Asset '{}' error -  failed to load the json file '{}', due to parse error: {}",
                  asset_id, PathToString(metadata->second), error);
    return {};
  }
  if (!root.is<picojson::object>())
  {
    ERROR_LOG_FMT(
        VIDEO,
        "Asset '{}' error -  failed to load the json file '{}', due to root not being an object!",
        asset_id, PathToString(metadata->second));
    return {};
  }

  const auto& root_obj = root.get<picojson::object>();

  if (!PixelShaderData::FromJson(asset_id, root_obj, data))
    return {};

  return LoadInfo{approx_mem_size, GetLastAssetWriteTime(asset_id)};
}

CustomAssetLibrary::LoadInfo DirectFilesystemAssetLibrary::LoadMaterial(const AssetID& asset_id,
                                                                        MaterialData* data)
{
  const auto asset_map = GetAssetMapForID(asset_id);

  // Material is expected to have one asset mapped
  if (asset_map.empty() || asset_map.size() > 1)
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error - material expected to have one file mapped!", asset_id);
    return {};
  }
  const auto& asset_path = asset_map.begin()->second;

  std::string json_data;
  if (!File::ReadFileToString(PathToString(asset_path), json_data))
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error -  material failed to load the json file '{}',",
                  asset_id, PathToString(asset_path));
    return {};
  }

  picojson::value root;
  const auto error = picojson::parse(root, json_data);

  if (!error.empty())
  {
    ERROR_LOG_FMT(
        VIDEO,
        "Asset '{}' error -  material failed to load the json file '{}', due to parse error: {}",
        asset_id, PathToString(asset_path), error);
    return {};
  }
  if (!root.is<picojson::object>())
  {
    ERROR_LOG_FMT(VIDEO,
                  "Asset '{}' error - material failed to load the json file '{}', due to root not "
                  "being an object!",
                  asset_id, PathToString(asset_path));
    return {};
  }

  const auto& root_obj = root.get<picojson::object>();

  if (!MaterialData::FromJson(asset_id, root_obj, data))
  {
    ERROR_LOG_FMT(VIDEO,
                  "Asset '{}' error -  material failed to load the json file '{}', as material "
                  "json could not be parsed!",
                  asset_id, PathToString(asset_path));
    return {};
  }

  return LoadInfo{json_data.size(), GetLastAssetWriteTime(asset_id)};
}

CustomAssetLibrary::LoadInfo DirectFilesystemAssetLibrary::LoadTexture(const AssetID& asset_id,
                                                                       CustomTextureData* data)
{
  const auto asset_map = GetAssetMapForID(asset_id);

  // Raw texture is expected to have one asset mapped
  if (asset_map.empty() || asset_map.size() > 1)
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error - raw texture expected to have one file mapped!",
                  asset_id);
    return {};
  }
  const auto& asset_path = asset_map.begin()->second;

  std::error_code ec;
  const auto last_loaded_time = std::filesystem::last_write_time(asset_path, ec);
  if (ec)
  {
    ERROR_LOG_FMT(VIDEO, "Asset '{}' error - failed to get last write time with error '{}'!",
                  asset_id, ec);
    return {};
  }
  auto ext = PathToString(asset_path.extension());
  Common::ToLower(&ext);
  if (ext == ".dds")
  {
    if (!LoadDDSTexture(data, PathToString(asset_path)))
    {
      ERROR_LOG_FMT(VIDEO, "Asset '{}' error - could not load dds texture!", asset_id);
      return {};
    }

    if (data->m_slices.empty()) [[unlikely]]
      data->m_slices.push_back({});

    if (!LoadMips(asset_path, &data->m_slices[0]))
      return {};

    return LoadInfo{GetAssetSize(*data), FileTimeToSysTime(last_loaded_time)};
  }
  else if (ext == ".png")
  {
    // If we have no slices, create one
    if (data->m_slices.empty())
      data->m_slices.push_back({});

    auto& slice = data->m_slices[0];
    // If we have no levels, create one to pass into LoadPNGTexture
    if (slice.m_levels.empty())
      slice.m_levels.push_back({});

    if (!LoadPNGTexture(&slice.m_levels[0], PathToString(asset_path)))
    {
      ERROR_LOG_FMT(VIDEO, "Asset '{}' error - could not load png texture!", asset_id);
      return {};
    }

    if (!LoadMips(asset_path, &slice))
      return {};

    return LoadInfo{GetAssetSize(*data), FileTimeToSysTime(last_loaded_time)};
  }

  ERROR_LOG_FMT(VIDEO, "Asset '{}' error - extension '{}' unknown!", asset_id, ext);
  return {};
}

void DirectFilesystemAssetLibrary::SetAssetIDMapData(const AssetID& asset_id,
                                                     AssetMap asset_path_map)
{
  std::lock_guard lk(m_lock);
  m_assetid_to_asset_map_path[asset_id] = std::move(asset_path_map);
}

bool DirectFilesystemAssetLibrary::LoadMips(const std::filesystem::path& asset_path,
                                            CustomTextureData::ArraySlice* data)
{
  if (!data) [[unlikely]]
    return false;

  std::string path;
  std::string filename;
  std::string extension;
  SplitPath(PathToString(asset_path), &path, &filename, &extension);

  std::string extension_lower = extension;
  Common::ToLower(&extension_lower);

  // Load additional mip levels
  for (u32 mip_level = static_cast<u32>(data->m_levels.size());; mip_level++)
  {
    const auto mip_level_filename = filename + fmt::format("_mip{}", mip_level);

    const auto full_path = path + mip_level_filename + extension;
    if (!File::Exists(full_path))
      return true;

    VideoCommon::CustomTextureData::ArraySlice::Level level;
    if (extension_lower == ".dds")
    {
      if (!LoadDDSTexture(&level, full_path, mip_level))
      {
        ERROR_LOG_FMT(VIDEO, "Custom mipmap '{}' failed to load", mip_level_filename);
        return false;
      }
    }
    else if (extension_lower == ".png")
    {
      if (!LoadPNGTexture(&level, full_path))
      {
        ERROR_LOG_FMT(VIDEO, "Custom mipmap '{}' failed to load", mip_level_filename);
        return false;
      }
    }
    else
    {
      ERROR_LOG_FMT(VIDEO, "Custom mipmap '{}' has unsupported extension", mip_level_filename);
      return false;
    }

    data->m_levels.push_back(std::move(level));
  }

  return true;
}

DirectFilesystemAssetLibrary::AssetMap
DirectFilesystemAssetLibrary::GetAssetMapForID(const AssetID& asset_id) const
{
  std::lock_guard lk(m_lock);
  if (auto iter = m_assetid_to_asset_map_path.find(asset_id);
      iter != m_assetid_to_asset_map_path.end())
  {
    return iter->second;
  }
  return {};
}
}  // namespace VideoCommon