Cleaned up unused code in Program
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / program.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/shaders/program.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring>
23 #include <map>
24
25 // INTERNAL INCLUDES
26 #include <dali/devel-api/common/hash.h>
27 #include <dali/graphics-api/graphics-controller.h>
28 #include <dali/graphics-api/graphics-program.h>
29 #include <dali/graphics-api/graphics-reflection.h>
30 #include <dali/integration-api/debug.h>
31 #include <dali/internal/common/shader-data.h>
32 #include <dali/internal/render/common/performance-monitor.h>
33 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
34 #include <dali/internal/render/shaders/program-cache.h>
35 #include <dali/public-api/common/constants.h>
36 #include <dali/public-api/common/dali-common.h>
37 #include <dali/public-api/common/dali-vector.h>
38
39 namespace Dali
40 {
41 namespace Internal
42 {
43 // LOCAL STUFF
44 namespace
45 {
46 const unsigned int NUMBER_OF_DEFAULT_UNIFORMS = static_cast<unsigned int>(Program::DefaultUniformIndex::COUNT);
47
48 /**
49  * List of all default uniforms used for quicker lookup
50  */
51 size_t DEFAULT_UNIFORM_HASHTABLE[NUMBER_OF_DEFAULT_UNIFORMS] =
52   {
53     CalculateHash(std::string("uModelMatrix")),
54     CalculateHash(std::string("uMvpMatrix")),
55     CalculateHash(std::string("uViewMatrix")),
56     CalculateHash(std::string("uModelView")),
57     CalculateHash(std::string("uNormalMatrix")),
58     CalculateHash(std::string("uProjection")),
59     CalculateHash(std::string("uSize")),
60     CalculateHash(std::string("uColor")),
61     CalculateHash(std::string("uActorColor"))};
62
63 /**
64  * Helper function to calculate the correct alignment of data for uniform buffers
65  * @param dataSize size of uniform buffer
66  * @return size of data aligned to given size
67  */
68 inline uint32_t AlignSize(uint32_t dataSize, uint32_t alignSize)
69 {
70   return ((dataSize / alignSize) + ((dataSize % alignSize) ? 1u : 0u)) * alignSize;
71 }
72
73 } // namespace
74
75 // IMPLEMENTATION
76
77 Program* Program::New(ProgramCache& cache, const Internal::ShaderDataPtr& shaderData, Graphics::Controller& gfxController)
78 {
79   size_t shaderHash = shaderData->GetHashValue();
80
81   Program* program = cache.GetProgram(shaderHash);
82
83   if(nullptr == program)
84   {
85     // program not found so create it
86     program = new Program(cache, shaderData, gfxController);
87
88     DALI_LOG_INFO(Debug::Filter::gShader, Debug::Verbose, "Program::New() created a unique program:\n  VertexShader:\n%s\n\n  FragShader:\n%s\n", shaderData->GetVertexShader(), shaderData->GetFragmentShader());
89     cache.AddProgram(shaderHash, program);
90   }
91
92   return program;
93 }
94
95 Program::Program(ProgramCache& cache, Internal::ShaderDataPtr shaderData, Graphics::Controller& controller)
96 : mCache(cache),
97   mGfxProgram(nullptr),
98   mGfxController(controller),
99   mProgramData(std::move(shaderData))
100 {
101 }
102
103 Program::~Program() = default;
104
105 void Program::BuildReflection(const Graphics::Reflection& graphicsReflection, Render::UniformBufferManager& uniformBufferManager)
106 {
107   mReflectionDefaultUniforms.clear();
108   mReflectionDefaultUniforms.resize(NUMBER_OF_DEFAULT_UNIFORMS);
109
110   auto uniformBlockCount = graphicsReflection.GetUniformBlockCount();
111
112   // add uniform block fields
113   for(auto i = 0u; i < uniformBlockCount; ++i)
114   {
115     Graphics::UniformBlockInfo uboInfo;
116     graphicsReflection.GetUniformBlock(i, uboInfo);
117
118     // for each member store data
119     for(const auto& item : uboInfo.members)
120     {
121       // Add a hash for the whole name.
122       //
123       // If the name represents an array of basic types, it won't contain an index
124       // operator "[",NN,"]".
125       //
126       // If the name represents an element in an array of structs, it will contain an
127       // index operator, but should be hashed in full.
128       auto hashValue = CalculateHash(item.name);
129       mReflection.emplace_back(ReflectionUniformInfo{hashValue, false, item});
130
131       // update buffer index
132       mReflection.back().uniformInfo.bufferIndex = i;
133
134       // Update default uniforms
135       for(auto j = 0u; j < NUMBER_OF_DEFAULT_UNIFORMS; ++j)
136       {
137         if(hashValue == DEFAULT_UNIFORM_HASHTABLE[j])
138         {
139           mReflectionDefaultUniforms[j] = mReflection.back();
140           break;
141         }
142       }
143     }
144   }
145
146   // add samplers
147   auto samplers = graphicsReflection.GetSamplers(); // Only holds first element of arrays without [].
148   for(const auto& sampler : samplers)
149   {
150     mReflection.emplace_back(ReflectionUniformInfo{CalculateHash(sampler.name), false, sampler});
151   }
152
153   // check for potential collisions
154   std::map<size_t, bool> hashTest;
155   bool                   hasCollisions(false);
156   for(auto&& item : mReflection)
157   {
158     if(hashTest.find(item.hashValue) == hashTest.end())
159     {
160       hashTest[item.hashValue] = false;
161     }
162     else
163     {
164       hashTest[item.hashValue] = true;
165       hasCollisions            = true;
166     }
167   }
168
169   // update collision flag for further use
170   if(hasCollisions)
171   {
172     for(auto&& item : mReflection)
173     {
174       item.hasCollision = hashTest[item.hashValue];
175     }
176   }
177
178   mUniformBlockMemoryRequirements.blockSize.resize(uniformBlockCount);
179   mUniformBlockMemoryRequirements.blockSizeAligned.resize(uniformBlockCount);
180   mUniformBlockMemoryRequirements.blockCount           = uniformBlockCount;
181   mUniformBlockMemoryRequirements.totalSizeRequired    = 0u;
182   mUniformBlockMemoryRequirements.totalCpuSizeRequired = 0u;
183   mUniformBlockMemoryRequirements.totalGpuSizeRequired = 0u;
184
185   for(auto i = 0u; i < uniformBlockCount; ++i)
186   {
187     Graphics::UniformBlockInfo uboInfo;
188     graphicsReflection.GetUniformBlock(i, uboInfo);
189     bool standaloneUniformBlock = (i == 0);
190
191     auto     blockSize        = graphicsReflection.GetUniformBlockSize(i);
192     uint32_t blockAlignment   = uniformBufferManager.GetUniformBlockAlignment(standaloneUniformBlock);
193     auto     alignedBlockSize = AlignSize(blockSize, blockAlignment);
194
195     mUniformBlockMemoryRequirements.blockSize[i]        = blockSize;
196     mUniformBlockMemoryRequirements.blockSizeAligned[i] = alignedBlockSize;
197
198     mUniformBlockMemoryRequirements.totalSizeRequired += alignedBlockSize;
199     mUniformBlockMemoryRequirements.totalCpuSizeRequired += (standaloneUniformBlock) ? alignedBlockSize : 0;
200     mUniformBlockMemoryRequirements.totalGpuSizeRequired += (standaloneUniformBlock) ? 0 : alignedBlockSize;
201   }
202 }
203
204 void Program::SetGraphicsProgram(Graphics::UniquePtr<Graphics::Program>&& program, Render::UniformBufferManager& uniformBufferManager)
205 {
206   mGfxProgram = std::move(program);
207   BuildReflection(mGfxController.GetProgramReflection(*mGfxProgram.get()), uniformBufferManager);
208 }
209
210 bool Program::GetUniform(const std::string_view& name, Hash hashedName, Hash hashedNameNoArray, Graphics::UniformInfo& out) const
211 {
212   if(mReflection.empty())
213   {
214     return false;
215   }
216   DALI_ASSERT_DEBUG(hashedName != 0 && "GetUniform() hash is not set");
217
218   // If name contains a "]", but has nothing after, it's an element in an array,
219   // The reflection doesn't contain such elements, it only contains the name without square brackets
220   // Use the hash without array subscript.
221
222   // If the name contains a "]" anywhere but the end, it's a structure element. The reflection
223   // does contain such elements, so use normal hash.
224   Hash             hash  = hashedName;
225   std::string_view match = name;
226
227   if(!name.empty() && name.back() == ']')
228   {
229     hash     = hashedNameNoArray;
230     auto pos = name.rfind("[");
231     match    = name.substr(0, pos - 1); // Remove subscript
232   }
233
234   for(const ReflectionUniformInfo& item : mReflection)
235   {
236     if(item.hashValue == hash)
237     {
238       if(!item.hasCollision || item.uniformInfo.name == match)
239       {
240         out = item.uniformInfo;
241         return true;
242       }
243       else
244       {
245         return false;
246       }
247     }
248   }
249   return false;
250 }
251
252 const Graphics::UniformInfo* Program::GetDefaultUniform(DefaultUniformIndex defaultUniformIndex) const
253 {
254   if(mReflectionDefaultUniforms.empty())
255   {
256     return nullptr;
257   }
258
259   const auto value = &mReflectionDefaultUniforms[static_cast<uint32_t>(defaultUniformIndex)];
260   return &value->uniformInfo;
261 }
262
263 } // namespace Internal
264
265 } // namespace Dali