1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "shader_state_loader.h"
17 
18 #include <cctype>
19 #include <locale>
20 
21 #include <base/containers/string.h>
22 #include <core/io/intf_file_manager.h>
23 #include <core/namespace.h>
24 
25 #include "json_util.h"
26 #include "shader_state_loader_util.h"
27 #include "util/log.h"
28 
29 using namespace BASE_NS;
30 using namespace CORE_NS;
31 
32 RENDER_BEGIN_NAMESPACE()
33 namespace {
LoadImpl(const string_view jsonString)34 ShaderStateLoaderUtil::ShaderStateResult LoadImpl(const string_view jsonString)
35 {
36     const auto json = json::parse(jsonString.data());
37     if (json) {
38         ShaderStateLoaderUtil::ShaderStateResult ssr = ShaderStateLoaderUtil::LoadStates(json);
39         return ssr;
40     } else {
41         return ShaderStateLoaderUtil::ShaderStateResult { ShaderStateLoader::LoadResult { "Invalid json file." }, {} };
42     }
43 }
44 } // namespace
45 
Load(IFileManager & fileManager,const string_view uri)46 ShaderStateLoader::LoadResult ShaderStateLoader::Load(IFileManager& fileManager, const string_view uri)
47 {
48     uri_ = uri;
49     IFile::Ptr file = fileManager.OpenFile(uri);
50     if (!file) {
51         PLUGIN_LOG_D("Error loading '%s'", uri_.c_str());
52         return LoadResult("Failed to open file.");
53     }
54 
55     const uint64_t byteLength = file->GetLength();
56 
57     string raw;
58     raw.resize(static_cast<size_t>(byteLength));
59 
60     if (file->Read(raw.data(), byteLength) != byteLength) {
61         PLUGIN_LOG_D("Error loading '%s'", uri_.c_str());
62         return LoadResult("Failed to read file.");
63     }
64 
65     ShaderStateLoaderUtil::ShaderStateResult ssr = RENDER_NS::LoadImpl(string_view(raw));
66     graphicsStates_ = move(ssr.states.states);
67     graphicsStateVariantData_ = move(ssr.states.variantData);
68 
69     return ssr.res;
70 }
71 
GetUri() const72 string_view ShaderStateLoader::GetUri() const
73 {
74     return uri_;
75 }
76 
GetGraphicsStateVariantData() const77 array_view<const ShaderStateLoaderVariantData> ShaderStateLoader::GetGraphicsStateVariantData() const
78 {
79     return graphicsStateVariantData_;
80 }
81 
GetGraphicsStates() const82 array_view<const GraphicsState> ShaderStateLoader::GetGraphicsStates() const
83 {
84     return graphicsStates_;
85 }
86 
87 RENDER_END_NAMESPACE()
88