2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/render/shaders/program.h>
26 #include <dali/graphics-api/graphics-controller.h>
27 #include <dali/graphics-api/graphics-program.h>
28 #include <dali/integration-api/debug.h>
29 #include <dali/integration-api/gl-defines.h>
30 #include <dali/internal/common/shader-data.h>
31 #include <dali/internal/render/common/performance-monitor.h>
32 #include <dali/internal/render/gl-resources/gl-call-debug.h>
33 #include <dali/internal/render/shaders/program-cache.h>
34 #include <dali/public-api/common/constants.h>
35 #include <dali/public-api/common/dali-common.h>
36 #include <dali/public-api/common/dali-vector.h>
45 const char* const gStdAttribs[Program::ATTRIB_TYPE_LAST] =
47 "aPosition", // ATTRIB_POSITION
48 "aTexCoord", // ATTRIB_TEXCOORD
51 const char* const gStdUniforms[Program::UNIFORM_TYPE_LAST] =
53 "uMvpMatrix", // UNIFORM_MVP_MATRIX
54 "uModelView", // UNIFORM_MODELVIEW_MATRIX
55 "uProjection", // UNIFORM_PROJECTION_MATRIX
56 "uModelMatrix", // UNIFORM_MODEL_MATRIX,
57 "uViewMatrix", // UNIFORM_VIEW_MATRIX,
58 "uNormalMatrix", // UNIFORM_NORMAL_MATRIX
59 "uColor", // UNIFORM_COLOR
60 "sTexture", // UNIFORM_SAMPLER
61 "sTextureRect", // UNIFORM_SAMPLER_RECT
62 "sEffect", // UNIFORM_EFFECT_SAMPLER
63 "uSize" // UNIFORM_SIZE
70 Program* Program::New(ProgramCache& cache, Internal::ShaderDataPtr shaderData, Graphics::Controller& gfxController, Graphics::UniquePtr<Graphics::Program>&& gfxProgram, bool modifiesGeometry)
72 uint32_t programId{0u};
74 // Get program id and use it as hash for the cache
75 // in order to maintain current functionality as long as needed
76 gfxController.GetProgramParameter(*gfxProgram, 1, &programId);
78 size_t shaderHash = programId;
79 Program* program = cache.GetProgram(shaderHash);
81 if(nullptr == program)
83 // program not found so create it
84 program = new Program(cache, shaderData, gfxController, std::move(gfxProgram), modifiesGeometry);
85 program->GetActiveSamplerUniforms();
86 cache.AddProgram(shaderHash, program);
93 LOG_GL("UseProgram(%d)\n", mProgramId);
94 CHECK_GL(mGlAbstraction, mGlAbstraction.UseProgram(mProgramId));
95 mCache.SetCurrentProgram(this);
98 bool Program::IsUsed()
100 return (this == mCache.GetCurrentProgram());
103 GLint Program::GetAttribLocation(AttribType type)
105 DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
107 return GetCustomAttributeLocation(type);
110 uint32_t Program::RegisterCustomAttribute(ConstString name)
113 // find the value from cache
114 for(; index < static_cast<uint32_t>(mAttributeLocations.size()); ++index)
116 if(mAttributeLocations[index].first == name)
118 // name found so return index
122 // if we get here, index is one past end so push back the new name
123 mAttributeLocations.push_back(std::make_pair(name, ATTRIB_UNKNOWN));
127 GLint Program::GetCustomAttributeLocation(uint32_t attributeIndex)
129 // debug check that index is within name cache
130 DALI_ASSERT_DEBUG(mAttributeLocations.size() > attributeIndex);
132 // check if we have already queried the location of the attribute
133 GLint location = mAttributeLocations[attributeIndex].second;
135 if(location == ATTRIB_UNKNOWN)
137 location = CHECK_GL(mGlAbstraction, mGlAbstraction.GetAttribLocation(mProgramId, mAttributeLocations[attributeIndex].first.GetCString()));
139 mAttributeLocations[attributeIndex].second = location;
140 LOG_GL("GetAttributeLocation(program=%d,%s) = %d\n", mProgramId, mAttributeLocations[attributeIndex].first.GetCString(), mAttributeLocations[attributeIndex].second);
146 uint32_t Program::RegisterUniform(ConstString name)
149 // find the value from cache
150 for(; index < static_cast<uint32_t>(mUniformLocations.size()); ++index)
152 if(mUniformLocations[index].first == name)
154 // name found so return index
158 // if we get here, index is one past end so push back the new name
159 mUniformLocations.push_back(std::make_pair(name, UNIFORM_NOT_QUERIED));
163 GLint Program::GetUniformLocation(uint32_t uniformIndex)
165 // debug check that index is within name cache
166 DALI_ASSERT_DEBUG(mUniformLocations.size() > uniformIndex);
168 // check if we have already queried the location of the uniform
169 GLint location = mUniformLocations[uniformIndex].second;
171 if(location == UNIFORM_NOT_QUERIED)
173 location = CHECK_GL(mGlAbstraction, mGlAbstraction.GetUniformLocation(mProgramId, mUniformLocations[uniformIndex].first.GetCString()));
175 mUniformLocations[uniformIndex].second = location;
176 LOG_GL("GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[uniformIndex].first.GetCString(), mUniformLocations[uniformIndex].second);
185 * This struct is used to record the position of a uniform declaration
186 * within the fragment shader source code.
188 struct LocationPosition
190 GLint uniformLocation; ///< The location of the uniform (used as an identifier)
191 int32_t position; ///< the position of the uniform declaration
192 LocationPosition(GLint uniformLocation, int32_t position)
193 : uniformLocation(uniformLocation),
199 bool sortByPosition(LocationPosition a, LocationPosition b)
201 return a.position < b.position;
204 const char* const DELIMITERS = " \t\n";
208 const char* const mString;
209 const uint32_t mLength;
211 template<uint32_t kLength>
212 constexpr StringSize(const char (&string)[kLength])
214 mLength(kLength - 1) // remove terminating null; N.B. there should be no other null.
218 operator const char*() const
224 bool operator==(const StringSize& lhs, const char* rhs)
226 return strncmp(lhs.mString, rhs, lhs.mLength) == 0;
229 constexpr StringSize UNIFORM{"uniform"};
230 constexpr StringSize SAMPLER_PREFIX{"sampler"};
231 constexpr StringSize SAMPLER_TYPES[] = {
236 constexpr auto END_SAMPLER_TYPES = SAMPLER_TYPES + std::extent<decltype(SAMPLER_TYPES)>::value;
240 void Program::GetActiveSamplerUniforms()
242 GLint numberOfActiveUniforms = -1;
243 GLint uniformMaxNameLength = -1;
245 mGlAbstraction.GetProgramiv(mProgramId, GL_ACTIVE_UNIFORMS, &numberOfActiveUniforms);
246 mGlAbstraction.GetProgramiv(mProgramId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformMaxNameLength);
248 std::vector<std::string> samplerNames;
249 std::vector<char> name(uniformMaxNameLength + 1); // Allow for null terminator
250 std::vector<LocationPosition> samplerUniformLocations;
255 GLenum type = GL_ZERO;
257 for(int i = 0; i < numberOfActiveUniforms; ++i)
259 mGlAbstraction.GetActiveUniform(mProgramId, static_cast<GLuint>(i), uniformMaxNameLength, &nameLength, &number, &type, name.data());
261 if(type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_EXTERNAL_OES)
263 GLuint location = mGlAbstraction.GetUniformLocation(mProgramId, name.data());
264 samplerNames.push_back(name.data());
265 samplerUniformLocations.push_back(LocationPosition(location, -1));
270 //Determine declaration order of each sampler
271 char* fragShader = strdup(mProgramData->GetFragmentShader());
272 char* uniform = strstr(fragShader, UNIFORM);
273 int samplerPosition = 0;
276 char* outerToken = strtok_r(uniform + UNIFORM.mLength, ";", &uniform);
278 char* nextPtr = nullptr;
279 char* token = strtok_r(outerToken, DELIMITERS, &nextPtr);
282 if(SAMPLER_PREFIX == token)
284 token += SAMPLER_PREFIX.mLength;
285 if(std::find(SAMPLER_TYPES, END_SAMPLER_TYPES, token) != END_SAMPLER_TYPES)
288 token = strtok_r(nullptr, DELIMITERS, &nextPtr);
289 for(uint32_t i = 0; i < static_cast<uint32_t>(samplerUniformLocations.size()); ++i)
291 if(samplerUniformLocations[i].position == -1 &&
292 strncmp(token, samplerNames[i].c_str(), samplerNames[i].size()) == 0)
294 samplerUniformLocations[i].position = samplerPosition++;
302 DALI_LOG_ERROR("Sampler uniform %s declared but not used in the shader\n", token);
308 token = strtok_r(nullptr, DELIMITERS, &nextPtr);
311 uniform = strstr(uniform, UNIFORM);
316 // Re-order according to declaration order in the fragment source.
317 uint32_t samplerUniformCount = static_cast<uint32_t>(samplerUniformLocations.size());
318 if(samplerUniformCount > 1)
320 std::sort(samplerUniformLocations.begin(), samplerUniformLocations.end(), sortByPosition);
323 mSamplerUniformLocations.resize(samplerUniformCount);
324 for(uint32_t i = 0; i < samplerUniformCount; ++i)
326 mSamplerUniformLocations[i] = samplerUniformLocations[i].uniformLocation;
330 bool Program::GetSamplerUniformLocation(uint32_t index, GLint& location)
333 if(index < mSamplerUniformLocations.size())
335 location = mSamplerUniformLocations[index];
341 uint32_t Program::GetActiveSamplerCount() const
343 return static_cast<uint32_t>(mSamplerUniformLocations.size());
346 void Program::SetUniform1i(GLint location, GLint value0)
348 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
350 if(UNIFORM_UNKNOWN == location)
352 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
353 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
354 // specified uniform variable will not be changed.following opengl silently do nothing
358 // check if uniform location fits the cache
359 if(location >= MAX_UNIFORM_CACHE_SIZE)
361 // not cached, make the gl call
362 LOG_GL("Uniform1i(%d,%d)\n", location, value0);
363 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1i(location, value0));
367 // check if the value is different from what's already been set
368 if(value0 != mUniformCacheInt[location])
371 LOG_GL("Uniform1i(%d,%d)\n", location, value0);
372 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1i(location, value0));
374 mUniformCacheInt[location] = value0;
379 void Program::SetUniform4i(GLint location, GLint value0, GLint value1, GLint value2, GLint value3)
381 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
383 if(UNIFORM_UNKNOWN == location)
385 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
386 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
387 // specified uniform variable will not be changed.following opengl silently do nothing
391 // Not caching these as based on current analysis this is not called that often by our shaders
392 LOG_GL("Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3);
393 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4i(location, value0, value1, value2, value3));
396 void Program::SetUniform1f(GLint location, GLfloat value0)
398 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
400 if(UNIFORM_UNKNOWN == location)
402 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
403 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
404 // specified uniform variable will not be changed.following opengl silently do nothing
408 // check if uniform location fits the cache
409 if(location >= MAX_UNIFORM_CACHE_SIZE)
411 // not cached, make the gl call
412 LOG_GL("Uniform1f(%d,%f)\n", location, value0);
413 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1f(location, value0));
417 // check if the same value has already been set, reset if it is different
418 if((fabsf(value0 - mUniformCacheFloat[location]) >= Math::MACHINE_EPSILON_1))
421 LOG_GL("Uniform1f(%d,%f)\n", location, value0);
422 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform1f(location, value0));
425 mUniformCacheFloat[location] = value0;
430 void Program::SetUniform2f(GLint location, GLfloat value0, GLfloat value1)
432 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
434 if(UNIFORM_UNKNOWN == location)
436 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
437 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
438 // specified uniform variable will not be changed.following opengl silently do nothing
442 // check if uniform location fits the cache
443 if(location >= MAX_UNIFORM_CACHE_SIZE)
445 // not cached, make the gl call
446 LOG_GL("Uniform2f(%d,%f,%f)\n", location, value0, value1);
447 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform2f(location, value0, value1));
451 // check if the same value has already been set, reset if it is different
452 if((fabsf(value0 - mUniformCacheFloat2[location][0]) >= Math::MACHINE_EPSILON_1) ||
453 (fabsf(value1 - mUniformCacheFloat2[location][1]) >= Math::MACHINE_EPSILON_1))
456 LOG_GL("Uniform2f(%d,%f,%f)\n", location, value0, value1);
457 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform2f(location, value0, value1));
460 mUniformCacheFloat2[location][0] = value0;
461 mUniformCacheFloat2[location][1] = value1;
466 void Program::SetSizeUniform3f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2)
468 if((fabsf(value0 - mSizeUniformCache.x) >= Math::MACHINE_EPSILON_1) ||
469 (fabsf(value1 - mSizeUniformCache.y) >= Math::MACHINE_EPSILON_1) ||
470 (fabsf(value2 - mSizeUniformCache.z) >= Math::MACHINE_EPSILON_1))
472 mSizeUniformCache.x = value0;
473 mSizeUniformCache.y = value1;
474 mSizeUniformCache.z = value2;
475 SetUniform3f(location, value0, value1, value2);
479 void Program::SetUniform3f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2)
481 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
483 if(UNIFORM_UNKNOWN == location)
485 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
486 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
487 // specified uniform variable will not be changed.following opengl silently do nothing
491 // Not caching these as based on current analysis this is not called that often by our shaders
492 LOG_GL("Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2);
493 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform3f(location, value0, value1, value2));
496 void Program::SetUniform4f(GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3)
498 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
500 if(UNIFORM_UNKNOWN == location)
502 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
503 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
504 // specified uniform variable will not be changed.following opengl silently do nothing
508 // check if uniform location fits the cache
509 if(location >= MAX_UNIFORM_CACHE_SIZE)
511 // not cached, make the gl call
512 LOG_GL("Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3);
513 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4f(location, value0, value1, value2, value3));
517 // check if the same value has already been set, reset if any component is different
518 // checking index 3 first because we're often animating alpha (rgba)
519 if((fabsf(value3 - mUniformCacheFloat4[location][3]) >= Math::MACHINE_EPSILON_1) ||
520 (fabsf(value0 - mUniformCacheFloat4[location][0]) >= Math::MACHINE_EPSILON_1) ||
521 (fabsf(value1 - mUniformCacheFloat4[location][1]) >= Math::MACHINE_EPSILON_1) ||
522 (fabsf(value2 - mUniformCacheFloat4[location][2]) >= Math::MACHINE_EPSILON_1))
525 LOG_GL("Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3);
526 CHECK_GL(mGlAbstraction, mGlAbstraction.Uniform4f(location, value0, value1, value2, value3));
528 mUniformCacheFloat4[location][0] = value0;
529 mUniformCacheFloat4[location][1] = value1;
530 mUniformCacheFloat4[location][2] = value2;
531 mUniformCacheFloat4[location][3] = value3;
536 void Program::SetUniformMatrix4fv(GLint location, GLsizei count, const GLfloat* value)
538 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
540 if(UNIFORM_UNKNOWN == location)
542 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
543 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
544 // specified uniform variable will not be changed.following opengl silently do nothing
548 // Not caching these calls. Based on current analysis this is called very often
549 // but with different values (we're using this for MVP matrices)
550 // NOTE! we never want driver or GPU to transpose
551 LOG_GL("UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value);
552 CHECK_GL(mGlAbstraction, mGlAbstraction.UniformMatrix4fv(location, count, GL_FALSE, value));
555 void Program::SetUniformMatrix3fv(GLint location, GLsizei count, const GLfloat* value)
557 DALI_ASSERT_DEBUG(IsUsed()); // should not call this if this program is not used
559 if(UNIFORM_UNKNOWN == location)
561 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
562 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
563 // specified uniform variable will not be changed.following opengl silently do nothing
567 // Not caching these calls. Based on current analysis this is called very often
568 // but with different values (we're using this for MVP matrices)
569 // NOTE! we never want driver or GPU to transpose
570 LOG_GL("UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value);
571 CHECK_GL(mGlAbstraction, mGlAbstraction.UniformMatrix3fv(location, count, GL_FALSE, value));
574 void Program::GlContextCreated()
578 void Program::GlContextDestroyed()
580 ResetAttribsUniformCache();
583 bool Program::ModifiesGeometry()
585 return mModifiesGeometry;
588 Program::Program(ProgramCache& cache, Internal::ShaderDataPtr shaderData, Graphics::Controller& controller, Graphics::UniquePtr<Graphics::Program>&& gfxProgram, bool modifiesGeometry)
590 mGlAbstraction(mCache.GetGlAbstraction()),
591 mProjectionMatrix(nullptr),
592 mViewMatrix(nullptr),
594 mGfxProgram(std::move(gfxProgram)),
595 mGfxController(controller),
596 mProgramData(shaderData),
597 mModifiesGeometry(modifiesGeometry)
599 // reserve space for standard attributes
600 mAttributeLocations.reserve(ATTRIB_TYPE_LAST);
601 for(uint32_t i = 0; i < ATTRIB_TYPE_LAST; ++i)
603 RegisterCustomAttribute(ConstString(gStdAttribs[i]));
606 // reserve space for standard uniforms
607 mUniformLocations.reserve(UNIFORM_TYPE_LAST);
608 // reset built in uniform names in cache
609 for(uint32_t i = 0; i < UNIFORM_TYPE_LAST; ++i)
611 RegisterUniform(ConstString(gStdUniforms[i]));
615 ResetAttribsUniformCache();
617 // Get program id and use it as hash for the cache
618 // in order to maintain current functionality as long as needed
619 mGfxController.GetProgramParameter(*mGfxProgram, 1, &mProgramId);
626 void Program::ResetAttribsUniformCache()
628 // reset attribute locations
629 for(uint32_t i = 0; i < mAttributeLocations.size(); ++i)
631 mAttributeLocations[i].second = ATTRIB_UNKNOWN;
634 // reset all gl uniform locations
635 for(uint32_t i = 0; i < mUniformLocations.size(); ++i)
637 // reset gl program locations and names
638 mUniformLocations[i].second = UNIFORM_NOT_QUERIED;
641 mSamplerUniformLocations.clear();
643 // reset uniform caches
644 mSizeUniformCache.x = mSizeUniformCache.y = mSizeUniformCache.z = 0.f;
646 for(uint32_t i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i)
648 // GL initializes uniforms to 0
649 mUniformCacheInt[i] = 0;
650 mUniformCacheFloat[i] = 0.0f;
651 mUniformCacheFloat2[i][0] = 0.0f;
652 mUniformCacheFloat2[i][1] = 0.0f;
653 mUniformCacheFloat4[i][0] = 0.0f;
654 mUniformCacheFloat4[i][1] = 0.0f;
655 mUniformCacheFloat4[i][2] = 0.0f;
656 mUniformCacheFloat4[i][3] = 0.0f;
660 } // namespace Internal