blob: cb752b01a2fe67c8d6b174a6b15fea671a9c9342 [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
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//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include <cmath>
23
24#include <EGL/egl.h>
25#include <EGL/eglext.h>
26#include <GLES2/gl2.h>
27#include <sync/sync.h>
28#include <ui/GraphicBuffer.h>
29#include <utils/Trace.h>
30#include "../gl/GLExtensions.h"
31#include "SkiaGLRenderEngine.h"
32
33#include <GrContextOptions.h>
34#include <gl/GrGLInterface.h>
35
36#include <SkCanvas.h>
37#include <SkImage.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070038#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070039#include <SkSurface.h>
40
41extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
42
43bool checkGlError(const char* op, int lineNumber);
44
45namespace android {
46namespace renderengine {
47namespace skia {
48
49static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
50 EGLint wanted, EGLConfig* outConfig) {
51 EGLint numConfigs = -1, n = 0;
52 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
53 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
54 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
55 configs.resize(n);
56
57 if (!configs.empty()) {
58 if (attribute != EGL_NONE) {
59 for (EGLConfig config : configs) {
60 EGLint value = 0;
61 eglGetConfigAttrib(dpy, config, attribute, &value);
62 if (wanted == value) {
63 *outConfig = config;
64 return NO_ERROR;
65 }
66 }
67 } else {
68 // just pick the first one
69 *outConfig = configs[0];
70 return NO_ERROR;
71 }
72 }
73
74 return NAME_NOT_FOUND;
75}
76
77static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
78 EGLConfig* config) {
79 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
80 // it is to be used with WIFI displays
81 status_t err;
82 EGLint wantedAttribute;
83 EGLint wantedAttributeValue;
84
85 std::vector<EGLint> attribs;
86 if (renderableType) {
87 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
88 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
89
90 // Default to 8 bits per channel.
91 const EGLint tmpAttribs[] = {
92 EGL_RENDERABLE_TYPE,
93 renderableType,
94 EGL_RECORDABLE_ANDROID,
95 EGL_TRUE,
96 EGL_SURFACE_TYPE,
97 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
98 EGL_FRAMEBUFFER_TARGET_ANDROID,
99 EGL_TRUE,
100 EGL_RED_SIZE,
101 is1010102 ? 10 : 8,
102 EGL_GREEN_SIZE,
103 is1010102 ? 10 : 8,
104 EGL_BLUE_SIZE,
105 is1010102 ? 10 : 8,
106 EGL_ALPHA_SIZE,
107 is1010102 ? 2 : 8,
108 EGL_NONE,
109 };
110 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
111 std::back_inserter(attribs));
112 wantedAttribute = EGL_NONE;
113 wantedAttributeValue = EGL_NONE;
114 } else {
115 // if no renderable type specified, fallback to a simplified query
116 wantedAttribute = EGL_NATIVE_VISUAL_ID;
117 wantedAttributeValue = format;
118 }
119
120 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
121 config);
122 if (err == NO_ERROR) {
123 EGLint caveat;
124 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
125 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
126 }
127
128 return err;
129}
130
131std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
132 const RenderEngineCreationArgs& args) {
133 // initialize EGL for the default display
134 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
135 if (!eglInitialize(display, nullptr, nullptr)) {
136 LOG_ALWAYS_FATAL("failed to initialize EGL");
137 }
138
139 const auto eglVersion = eglQueryStringImplementationANDROID(display, EGL_VERSION);
140 if (!eglVersion) {
141 checkGlError(__FUNCTION__, __LINE__);
142 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_VERSION) failed");
143 }
144
145 const auto eglExtensions = eglQueryStringImplementationANDROID(display, EGL_EXTENSIONS);
146 if (!eglExtensions) {
147 checkGlError(__FUNCTION__, __LINE__);
148 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_EXTENSIONS) failed");
149 }
150
151 auto& extensions = gl::GLExtensions::getInstance();
152 extensions.initWithEGLStrings(eglVersion, eglExtensions);
153
154 // The code assumes that ES2 or later is available if this extension is
155 // supported.
156 EGLConfig config = EGL_NO_CONFIG_KHR;
157 if (!extensions.hasNoConfigContext()) {
158 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
159 }
160
161 bool useContextPriority =
162 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
163 EGLContext protectedContext = EGL_NO_CONTEXT;
164 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
165 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
166 Protection::PROTECTED);
167 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
168 }
169
170 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
171 Protection::UNPROTECTED);
172
173 // if can't create a GL context, we can only abort.
174 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
175
176 EGLSurface placeholder = EGL_NO_SURFACE;
177 if (!extensions.hasSurfacelessContext()) {
178 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
179 Protection::UNPROTECTED);
180 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
181 }
182 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
183 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
184 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
185 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
186
187 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
188 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
189 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
190 Protection::PROTECTED);
191 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
192 "can't create protected placeholder pbuffer");
193 }
194
195 // initialize the renderer while GL is current
196 std::unique_ptr<SkiaGLRenderEngine> engine =
Alec Mouri081be4c2020-09-16 10:24:47 -0700197 std::make_unique<SkiaGLRenderEngine>(display, config, ctxt, placeholder,
John Reck67b1e2b2020-08-26 13:17:24 -0700198 protectedContext, protectedPlaceholder);
199
200 ALOGI("OpenGL ES informations:");
201 ALOGI("vendor : %s", extensions.getVendor());
202 ALOGI("renderer : %s", extensions.getRenderer());
203 ALOGI("version : %s", extensions.getVersion());
204 ALOGI("extensions: %s", extensions.getExtensions());
205 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
206 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
207
208 return engine;
209}
210
211EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
212 status_t err;
213 EGLConfig config;
214
215 // First try to get an ES3 config
216 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
217 if (err != NO_ERROR) {
218 // If ES3 fails, try to get an ES2 config
219 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
220 if (err != NO_ERROR) {
221 // If ES2 still doesn't work, probably because we're on the emulator.
222 // try a simplified query
223 ALOGW("no suitable EGLConfig found, trying a simpler query");
224 err = selectEGLConfig(display, format, 0, &config);
225 if (err != NO_ERROR) {
226 // this EGL is too lame for android
227 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
228 }
229 }
230 }
231
232 if (logConfig) {
233 // print some debugging info
234 EGLint r, g, b, a;
235 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
236 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
237 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
238 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
239 ALOGI("EGL information:");
240 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
241 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
242 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
243 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
244 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
245 }
246
247 return config;
248}
249
Alec Mouri081be4c2020-09-16 10:24:47 -0700250SkiaGLRenderEngine::SkiaGLRenderEngine(EGLDisplay display, EGLConfig config, EGLContext ctxt,
251 EGLSurface placeholder, EGLContext protectedContext,
252 EGLSurface protectedPlaceholder)
253 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700254 mEGLConfig(config),
255 mEGLContext(ctxt),
256 mPlaceholderSurface(placeholder),
257 mProtectedEGLContext(protectedContext),
258 mProtectedPlaceholderSurface(protectedPlaceholder) {
259 // Suppress unused field warnings for things we definitely will need/use
260 // These EGL fields will all be needed for toggling between protected & unprotected contexts
261 // Or we need different RE instances for that
262 (void)mEGLDisplay;
263 (void)mEGLConfig;
264 (void)mEGLContext;
265 (void)mPlaceholderSurface;
266 (void)mProtectedEGLContext;
267 (void)mProtectedPlaceholderSurface;
268
269 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
270 LOG_ALWAYS_FATAL_IF(!glInterface.get());
271
272 GrContextOptions options;
273 options.fPreferExternalImagesOverES3 = true;
274 options.fDisableDistanceFieldPaths = true;
275 mGrContext = GrDirectContext::MakeGL(std::move(glInterface), options);
276}
277
278base::unique_fd SkiaGLRenderEngine::flush() {
279 ATRACE_CALL();
280 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
281 return base::unique_fd();
282 }
283
284 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
285 if (sync == EGL_NO_SYNC_KHR) {
286 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
287 return base::unique_fd();
288 }
289
290 // native fence fd will not be populated until flush() is done.
291 glFlush();
292
293 // get the fence fd
294 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
295 eglDestroySyncKHR(mEGLDisplay, sync);
296 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
297 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
298 }
299
300 return fenceFd;
301}
302
303bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
304 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
305 !gl::GLExtensions::getInstance().hasWaitSync()) {
306 return false;
307 }
308
309 // release the fd and transfer the ownership to EGLSync
310 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
311 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
312 if (sync == EGL_NO_SYNC_KHR) {
313 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
314 return false;
315 }
316
317 // XXX: The spec draft is inconsistent as to whether this should return an
318 // EGLint or void. Ignore the return value for now, as it's not strictly
319 // needed.
320 eglWaitSyncKHR(mEGLDisplay, sync, 0);
321 EGLint error = eglGetError();
322 eglDestroySyncKHR(mEGLDisplay, sync);
323 if (error != EGL_SUCCESS) {
324 ALOGE("failed to wait for EGL native fence sync: %#x", error);
325 return false;
326 }
327
328 return true;
329}
330
331static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
332 return !!(desc.usage & usage);
333}
334
335void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
336 std::lock_guard<std::mutex> lock(mRenderingMutex);
337 mImageCache.erase(bufferId);
338}
339
340status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
341 const std::vector<const LayerSettings*>& layers,
342 const sp<GraphicBuffer>& buffer,
343 const bool useFramebufferCache,
344 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
345 ATRACE_NAME("SkiaGL::drawLayers");
346 std::lock_guard<std::mutex> lock(mRenderingMutex);
347 if (layers.empty()) {
348 ALOGV("Drawing empty layer stack");
349 return NO_ERROR;
350 }
351
352 if (bufferFence.get() >= 0) {
353 // Duplicate the fence for passing to waitFence.
354 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
355 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
356 ATRACE_NAME("Waiting before draw");
357 sync_wait(bufferFence.get(), -1);
358 }
359 }
360 if (buffer == nullptr) {
361 ALOGE("No output buffer provided. Aborting GPU composition.");
362 return BAD_VALUE;
363 }
364
365 AHardwareBuffer_Desc bufferDesc;
366 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
367
368 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
369 "missing usage");
370
371 sk_sp<SkSurface> surface;
372 if (useFramebufferCache) {
373 auto iter = mSurfaceCache.find(buffer->getId());
374 if (iter != mSurfaceCache.end()) {
375 ALOGV("Cache hit!");
376 surface = iter->second;
377 }
378 }
379 if (!surface) {
380 surface = SkSurface::MakeFromAHardwareBuffer(mGrContext.get(), buffer->toAHardwareBuffer(),
381 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
382 SkColorSpace::MakeSRGB(), nullptr);
383 if (useFramebufferCache && surface) {
384 ALOGD("Adding to cache");
385 mSurfaceCache.insert({buffer->getId(), surface});
386 }
387 }
388 if (!surface) {
389 ALOGE("Failed to make surface");
390 return BAD_VALUE;
391 }
392 auto canvas = surface->getCanvas();
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700393 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700394
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700395 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
396 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
397 // displays might have different scaling when compared to the physical screen.
398 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
399 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
400 static_cast<SkScalar>(display.clip.width());
401 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
402 static_cast<SkScalar>(display.clip.height());
403 canvas->scale(scaleX, scaleY);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700404 canvas->clipRect(getSkRect(display.clip));
John Reck67b1e2b2020-08-26 13:17:24 -0700405 canvas->drawColor(0, SkBlendMode::kSrc);
406 for (const auto& layer : layers) {
Lucas Dupin21f348e2020-09-16 17:31:26 -0700407 SkPaint paint;
408 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700409 const auto dest = getSkRect(bounds);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700410
John Reck67b1e2b2020-08-26 13:17:24 -0700411 if (layer->source.buffer.buffer) {
412 ATRACE_NAME("DrawImage");
413 const auto& item = layer->source.buffer;
414 sk_sp<SkImage> image;
415 auto iter = mImageCache.find(item.buffer->getId());
416 if (iter != mImageCache.end()) {
417 image = iter->second;
418 } else {
419 image = SkImage::MakeFromAHardwareBuffer(item.buffer->toAHardwareBuffer(),
420 item.usePremultipliedAlpha
421 ? kPremul_SkAlphaType
422 : kUnpremul_SkAlphaType);
423 mImageCache.insert({item.buffer->getId(), image});
424 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700425
426 SkMatrix matrix;
427 if (layer->geometry.roundedCornersRadius > 0) {
428 const auto roundedRect = getRoundedRect(layer);
429 matrix.setTranslate(roundedRect.getBounds().left() - dest.left(),
430 roundedRect.getBounds().top() - dest.top());
431 } else {
432 matrix.setIdentity();
433 }
434 paint.setShader(image->makeShader(matrix));
John Reck67b1e2b2020-08-26 13:17:24 -0700435 } else {
436 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700437 const auto color = layer->source.solidColor;
438 paint.setColor(SkColor4f{.fR = color.r, .fG = color.g, .fB = color.b, layer->alpha});
439 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700440
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700441 // Layers have a local transform matrix that should be applied to them.
442 canvas->save();
443 canvas->concat(getSkM44(layer->geometry.positionTransform));
444
Lucas Dupin3f11e922020-09-22 17:31:04 -0700445 if (layer->shadow.length > 0) {
446 const auto rect = layer->geometry.roundedCornersRadius > 0
447 ? getSkRect(layer->geometry.roundedCornersCrop)
448 : dest;
449 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
450 }
451
Lucas Dupin21f348e2020-09-16 17:31:26 -0700452 if (layer->geometry.roundedCornersRadius > 0) {
453 canvas->drawRRect(getRoundedRect(layer), paint);
454 } else {
455 canvas->drawRect(dest, paint);
456 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700457 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700458 }
459 {
460 ATRACE_NAME("flush surface");
461 surface->flush();
462 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700463 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700464
465 if (drawFence != nullptr) {
466 *drawFence = flush();
467 }
468
469 // If flush failed or we don't support native fences, we need to force the
470 // gl command stream to be executed.
471 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
472 if (requireSync) {
473 ATRACE_BEGIN("Submit(sync=true)");
474 } else {
475 ATRACE_BEGIN("Submit(sync=false)");
476 }
477 bool success = mGrContext->submit(requireSync);
478 ATRACE_END();
479 if (!success) {
480 ALOGE("Failed to flush RenderEngine commands");
481 // Chances are, something illegal happened (either the caller passed
482 // us bad parameters, or we messed up our shader generation).
483 return INVALID_OPERATION;
484 }
485
486 // checkErrors();
487 return NO_ERROR;
488}
489
Lucas Dupin3f11e922020-09-22 17:31:04 -0700490inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
491 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
492}
493
494inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
495 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
496}
497
Lucas Dupin21f348e2020-09-16 17:31:26 -0700498inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Lucas Dupin3f11e922020-09-22 17:31:04 -0700499 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700500 const auto cornerRadius = layer->geometry.roundedCornersRadius;
501 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
502}
503
Lucas Dupin3f11e922020-09-22 17:31:04 -0700504inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
505 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
506}
507
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700508inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
509 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
510 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
511 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
512 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
513}
514
Lucas Dupin3f11e922020-09-22 17:31:04 -0700515inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
516 return SkPoint3::Make(vector.x, vector.y, vector.z);
517}
518
John Reck67b1e2b2020-08-26 13:17:24 -0700519size_t SkiaGLRenderEngine::getMaxTextureSize() const {
520 return mGrContext->maxTextureSize();
521}
522
523size_t SkiaGLRenderEngine::getMaxViewportDims() const {
524 return mGrContext->maxRenderTargetSize();
525}
526
Lucas Dupin3f11e922020-09-22 17:31:04 -0700527void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
528 const ShadowSettings& settings) {
529 ATRACE_CALL();
530 const float casterZ = settings.length / 2.0f;
531 const auto shadowShape = cornerRadius > 0
532 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
533 : SkPath::Rect(casterRect);
534 const auto flags =
535 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
536
537 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
538 getSkPoint3(settings.lightPos), settings.lightRadius,
539 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
540 flags);
541}
542
John Reck67b1e2b2020-08-26 13:17:24 -0700543EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
544 EGLContext shareContext, bool useContextPriority,
545 Protection protection) {
546 EGLint renderableType = 0;
547 if (config == EGL_NO_CONFIG_KHR) {
548 renderableType = EGL_OPENGL_ES3_BIT;
549 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
550 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
551 }
552 EGLint contextClientVersion = 0;
553 if (renderableType & EGL_OPENGL_ES3_BIT) {
554 contextClientVersion = 3;
555 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
556 contextClientVersion = 2;
557 } else if (renderableType & EGL_OPENGL_ES_BIT) {
558 contextClientVersion = 1;
559 } else {
560 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
561 }
562
563 std::vector<EGLint> contextAttributes;
564 contextAttributes.reserve(7);
565 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
566 contextAttributes.push_back(contextClientVersion);
567 if (useContextPriority) {
568 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
569 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
570 }
571 if (protection == Protection::PROTECTED) {
572 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
573 contextAttributes.push_back(EGL_TRUE);
574 }
575 contextAttributes.push_back(EGL_NONE);
576
577 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
578
579 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
580 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
581 // EGL_NO_CONTEXT so that we can abort.
582 if (config != EGL_NO_CONFIG_KHR) {
583 return context;
584 }
585 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
586 // should try to fall back to GLES 2.
587 contextAttributes[1] = 2;
588 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
589 }
590
591 return context;
592}
593
594EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
595 EGLConfig config, int hwcFormat,
596 Protection protection) {
597 EGLConfig placeholderConfig = config;
598 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
599 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
600 }
601 std::vector<EGLint> attributes;
602 attributes.reserve(7);
603 attributes.push_back(EGL_WIDTH);
604 attributes.push_back(1);
605 attributes.push_back(EGL_HEIGHT);
606 attributes.push_back(1);
607 if (protection == Protection::PROTECTED) {
608 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
609 attributes.push_back(EGL_TRUE);
610 }
611 attributes.push_back(EGL_NONE);
612
613 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
614}
615
616void SkiaGLRenderEngine::cleanFramebufferCache() {
617 mSurfaceCache.clear();
618}
619
620} // namespace skia
621} // namespace renderengine
622} // namespace android