Hash :
d33a2222
        
        Author :
  
        
        Date :
2021-04-26T16:56:15
        
      
Upstream Apple's direct-to-Metal backend: compile libANGLE. This change is meant to merge the metal backend changes from Apple's direct-to-Metal backend. Taken from Kyle Piddington's CL: https://chromium-review.googlesource.com/c/angle/angle/+/2857366/ The goal of this CL is to merge the metal backend code in a state that compiles, but not to switch the Metal backend over to using the direct-to-metal backend yet. Bug: angleproject:5505 Bug: angleproject:6127 Change-Id: If6783e06e0086b3a1dd25c6f53caca5cfc96cb86 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2950067 Reviewed-by: Jonah Ryan-Davis <jonahr@google.com> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Jonah Ryan-Davis <jonahr@google.com>
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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayCGL.mm: CGL implementation of egl::Display
#include "common/platform.h"
#if defined(ANGLE_PLATFORM_MACOS) || defined(ANGLE_PLATFORM_MACCATALYST)
#    include "libANGLE/renderer/gl/cgl/DisplayCGL.h"
#    import <Cocoa/Cocoa.h>
#    include <EGL/eglext.h>
#    include <dlfcn.h>
#    include "common/debug.h"
#    include "common/gl/cgl/FunctionsCGL.h"
#    include "gpu_info_util/SystemInfo.h"
#    include "libANGLE/Display.h"
#    include "libANGLE/Error.h"
#    include "libANGLE/renderer/gl/cgl/ContextCGL.h"
#    include "libANGLE/renderer/gl/cgl/DeviceCGL.h"
#    include "libANGLE/renderer/gl/cgl/IOSurfaceSurfaceCGL.h"
#    include "libANGLE/renderer/gl/cgl/PbufferSurfaceCGL.h"
#    include "libANGLE/renderer/gl/cgl/RendererCGL.h"
#    include "libANGLE/renderer/gl/cgl/WindowSurfaceCGL.h"
#    include "platform/PlatformMethods.h"
namespace
{
const char *kDefaultOpenGLDylibName =
    "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib";
const char *kFallbackOpenGLDylibName = "GL";
}
namespace rx
{
namespace
{
// Global IOKit I/O registryID that can match a GPU across process boundaries.
using IORegistryGPUID = uint64_t;
// Code from WebKit to set an OpenGL context to use a particular GPU by ID.
// https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/cocoa/GraphicsContextGLOpenGLCocoa.mm
// Used with permission.
static void SetGPUByRegistryID(CGLContextObj contextObj,
                               CGLPixelFormatObj pixelFormatObj,
                               IORegistryGPUID preferredGPUID)
{
    if (@available(macOS 10.13, *))
    {
        // When a process does not have access to the WindowServer (as with Chromium's GPU process
        // and WebKit's WebProcess), there is no way for OpenGL to tell which GPU is connected to a
        // display. On 10.13+, find the virtual screen that corresponds to the preferred GPU by its
        // registryID. CGLSetVirtualScreen can then be used to tell OpenGL which GPU it should be
        // using.
        if (!contextObj || !preferredGPUID)
            return;
        GLint virtualScreenCount = 0;
        CGLError error = CGLDescribePixelFormat(pixelFormatObj, 0, kCGLPFAVirtualScreenCount,
                                                &virtualScreenCount);
        ASSERT(error == kCGLNoError);
        GLint firstAcceleratedScreen = -1;
        for (GLint virtualScreen = 0; virtualScreen < virtualScreenCount; ++virtualScreen)
        {
            GLint displayMask = 0;
            error = CGLDescribePixelFormat(pixelFormatObj, virtualScreen, kCGLPFADisplayMask,
                                           &displayMask);
            ASSERT(error == kCGLNoError);
            auto gpuID = angle::GetGpuIDFromOpenGLDisplayMask(displayMask);
            if (gpuID == preferredGPUID)
            {
                error = CGLSetVirtualScreen(contextObj, virtualScreen);
                ASSERT(error == kCGLNoError);
                fprintf(stderr, "Context (%p) set to GPU with ID: (%lld).", contextObj, gpuID);
                return;
            }
            if (firstAcceleratedScreen < 0)
            {
                GLint isAccelerated = 0;
                error = CGLDescribePixelFormat(pixelFormatObj, virtualScreen, kCGLPFAAccelerated,
                                               &isAccelerated);
                ASSERT(error == kCGLNoError);
                if (isAccelerated)
                    firstAcceleratedScreen = virtualScreen;
            }
        }
        // No registryID match found; set to first hardware-accelerated virtual screen.
        if (firstAcceleratedScreen >= 0)
        {
            error = CGLSetVirtualScreen(contextObj, firstAcceleratedScreen);
            ASSERT(error == kCGLNoError);
        }
    }
}
}  // anonymous namespace
EnsureCGLContextIsCurrent::EnsureCGLContextIsCurrent(CGLContextObj context)
    : mOldContext(CGLGetCurrentContext()), mResetContext(mOldContext != context)
{
    if (mResetContext)
    {
        CGLSetCurrentContext(context);
    }
}
EnsureCGLContextIsCurrent::~EnsureCGLContextIsCurrent()
{
    if (mResetContext)
    {
        CGLSetCurrentContext(mOldContext);
    }
}
class FunctionsGLCGL : public FunctionsGL
{
  public:
    FunctionsGLCGL(void *dylibHandle) : mDylibHandle(dylibHandle) {}
    ~FunctionsGLCGL() override { dlclose(mDylibHandle); }
  private:
    void *loadProcAddress(const std::string &function) const override
    {
        return dlsym(mDylibHandle, function.c_str());
    }
    void *mDylibHandle;
};
DisplayCGL::DisplayCGL(const egl::DisplayState &state)
    : DisplayGL(state),
      mEGLDisplay(nullptr),
      mContext(nullptr),
      mThreadsWithCurrentContext(),
      mPixelFormat(nullptr),
      mSupportsGPUSwitching(false),
      mCurrentGPUID(0),
      mDiscreteGPUPixelFormat(nullptr),
      mDiscreteGPURefs(0),
      mLastDiscreteGPUUnrefTime(0.0)
{}
DisplayCGL::~DisplayCGL() {}
egl::Error DisplayCGL::initialize(egl::Display *display)
{
    mEGLDisplay = display;
    angle::SystemInfo info;
    // It's legal for GetSystemInfo to return false and thereby
    // contain incomplete information.
    (void)angle::GetSystemInfo(&info);
    // This code implements the effect of the
    // disableGPUSwitchingSupport workaround in FeaturesGL.
    mSupportsGPUSwitching = info.isMacSwitchable && !info.hasNVIDIAGPU();
    {
        // TODO(cwallez) investigate which pixel format we want
        std::vector<CGLPixelFormatAttribute> attribs;
        attribs.push_back(kCGLPFAOpenGLProfile);
        attribs.push_back(static_cast<CGLPixelFormatAttribute>(kCGLOGLPVersion_3_2_Core));
        attribs.push_back(kCGLPFAAllowOfflineRenderers);
        attribs.push_back(static_cast<CGLPixelFormatAttribute>(0));
        GLint nVirtualScreens = 0;
        CGLChoosePixelFormat(attribs.data(), &mPixelFormat, &nVirtualScreens);
        if (mPixelFormat == nullptr)
        {
            return egl::EglNotInitialized() << "Could not create the context's pixel format.";
        }
    }
    CGLCreateContext(mPixelFormat, nullptr, &mContext);
    if (mContext == nullptr)
    {
        return egl::EglNotInitialized() << "Could not create the CGL context.";
    }
    if (mSupportsGPUSwitching)
    {
        // Determine the currently active GPU on the system.
        mCurrentGPUID = angle::GetGpuIDFromDisplayID(kCGDirectMainDisplay);
    }
    if (CGLSetCurrentContext(mContext) != kCGLNoError)
    {
        return egl::EglNotInitialized() << "Could not make the CGL context current.";
    }
    mThreadsWithCurrentContext.insert(std::this_thread::get_id());
    // There is no equivalent getProcAddress in CGL so we open the dylib directly
    void *handle = dlopen(kDefaultOpenGLDylibName, RTLD_NOW);
    if (!handle)
    {
        handle = dlopen(kFallbackOpenGLDylibName, RTLD_NOW);
    }
    if (!handle)
    {
        return egl::EglNotInitialized() << "Could not open the OpenGL Framework.";
    }
    std::unique_ptr<FunctionsGL> functionsGL(new FunctionsGLCGL(handle));
    functionsGL->initialize(display->getAttributeMap());
    mRenderer.reset(new RendererCGL(std::move(functionsGL), display->getAttributeMap(), this));
    const gl::Version &maxVersion = mRenderer->getMaxSupportedESVersion();
    if (maxVersion < gl::Version(2, 0))
    {
        return egl::EglNotInitialized() << "OpenGL ES 2.0 is not supportable.";
    }
    auto &attributes = display->getAttributeMap();
    mDeviceContextIsVolatile =
        attributes.get(EGL_PLATFORM_ANGLE_DEVICE_CONTEXT_VOLATILE_CGL_ANGLE, GL_FALSE);
    return DisplayGL::initialize(display);
}
void DisplayCGL::terminate()
{
    DisplayGL::terminate();
    mRenderer.reset();
    if (mPixelFormat != nullptr)
    {
        CGLDestroyPixelFormat(mPixelFormat);
        mPixelFormat = nullptr;
    }
    if (mContext != nullptr)
    {
        CGLSetCurrentContext(nullptr);
        CGLDestroyContext(mContext);
        mContext = nullptr;
        mThreadsWithCurrentContext.clear();
    }
    if (mDiscreteGPUPixelFormat != nullptr)
    {
        CGLDestroyPixelFormat(mDiscreteGPUPixelFormat);
        mDiscreteGPUPixelFormat   = nullptr;
        mLastDiscreteGPUUnrefTime = 0.0;
    }
}
egl::Error DisplayCGL::prepareForCall()
{
    if (!mContext)
    {
        return egl::EglNotInitialized() << "Context not allocated.";
    }
    auto threadId = std::this_thread::get_id();
    if (mDeviceContextIsVolatile ||
        mThreadsWithCurrentContext.find(threadId) == mThreadsWithCurrentContext.end())
    {
        if (CGLSetCurrentContext(mContext) != kCGLNoError)
        {
            return egl::EglBadAlloc() << "Could not make device CGL context current.";
        }
        mThreadsWithCurrentContext.insert(threadId);
    }
    return egl::NoError();
}
egl::Error DisplayCGL::releaseThread()
{
    ASSERT(mContext);
    auto threadId = std::this_thread::get_id();
    if (mThreadsWithCurrentContext.find(threadId) != mThreadsWithCurrentContext.end())
    {
        if (CGLSetCurrentContext(nullptr) != kCGLNoError)
        {
            return egl::EglBadAlloc() << "Could not release device CGL context.";
        }
        mThreadsWithCurrentContext.erase(threadId);
    }
    return egl::NoError();
}
egl::Error DisplayCGL::makeCurrent(egl::Display *display,
                                   egl::Surface *drawSurface,
                                   egl::Surface *readSurface,
                                   gl::Context *context)
{
    checkDiscreteGPUStatus();
    return DisplayGL::makeCurrent(display, drawSurface, readSurface, context);
}
SurfaceImpl *DisplayCGL::createWindowSurface(const egl::SurfaceState &state,
                                             EGLNativeWindowType window,
                                             const egl::AttributeMap &attribs)
{
    return new WindowSurfaceCGL(state, mRenderer.get(), window, mContext);
}
SurfaceImpl *DisplayCGL::createPbufferSurface(const egl::SurfaceState &state,
                                              const egl::AttributeMap &attribs)
{
    EGLint width  = static_cast<EGLint>(attribs.get(EGL_WIDTH, 0));
    EGLint height = static_cast<EGLint>(attribs.get(EGL_HEIGHT, 0));
    return new PbufferSurfaceCGL(state, mRenderer.get(), width, height);
}
SurfaceImpl *DisplayCGL::createPbufferFromClientBuffer(const egl::SurfaceState &state,
                                                       EGLenum buftype,
                                                       EGLClientBuffer clientBuffer,
                                                       const egl::AttributeMap &attribs)
{
    ASSERT(buftype == EGL_IOSURFACE_ANGLE);
    return new IOSurfaceSurfaceCGL(state, mContext, clientBuffer, attribs);
}
SurfaceImpl *DisplayCGL::createPixmapSurface(const egl::SurfaceState &state,
                                             NativePixmapType nativePixmap,
                                             const egl::AttributeMap &attribs)
{
    UNIMPLEMENTED();
    return nullptr;
}
ContextImpl *DisplayCGL::createContext(const gl::State &state,
                                       gl::ErrorSet *errorSet,
                                       const egl::Config *configuration,
                                       const gl::Context *shareContext,
                                       const egl::AttributeMap &attribs)
{
    bool usesDiscreteGPU = false;
    if (attribs.get(EGL_POWER_PREFERENCE_ANGLE, EGL_LOW_POWER_ANGLE) == EGL_HIGH_POWER_ANGLE)
    {
        // Should have been rejected by validation if not supported.
        ASSERT(mSupportsGPUSwitching);
        usesDiscreteGPU = true;
    }
    return new ContextCGL(this, state, errorSet, mRenderer, usesDiscreteGPU);
}
DeviceImpl *DisplayCGL::createDevice()
{
    return new DeviceCGL();
}
egl::ConfigSet DisplayCGL::generateConfigs()
{
    // TODO(cwallez): generate more config permutations
    egl::ConfigSet configs;
    const gl::Version &maxVersion = getMaxSupportedESVersion();
    ASSERT(maxVersion >= gl::Version(2, 0));
    bool supportsES3 = maxVersion >= gl::Version(3, 0);
    egl::Config config;
    // Native stuff
    config.nativeVisualID   = 0;
    config.nativeVisualType = 0;
    config.nativeRenderable = EGL_TRUE;
    // Buffer sizes
    config.redSize     = 8;
    config.greenSize   = 8;
    config.blueSize    = 8;
    config.alphaSize   = 8;
    config.depthSize   = 24;
    config.stencilSize = 8;
    config.colorBufferType = EGL_RGB_BUFFER;
    config.luminanceSize   = 0;
    config.alphaMaskSize   = 0;
    config.bufferSize = config.redSize + config.greenSize + config.blueSize + config.alphaSize;
    config.transparentType = EGL_NONE;
    // Pbuffer
    config.maxPBufferWidth  = 4096;
    config.maxPBufferHeight = 4096;
    config.maxPBufferPixels = 4096 * 4096;
    // Caveat
    config.configCaveat = EGL_NONE;
    // Misc
    config.sampleBuffers     = 0;
    config.samples           = 0;
    config.level             = 0;
    config.bindToTextureRGB  = EGL_FALSE;
    config.bindToTextureRGBA = EGL_FALSE;
    config.bindToTextureTarget = EGL_TEXTURE_RECTANGLE_ANGLE;
    config.surfaceType = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
    config.minSwapInterval = 1;
    config.maxSwapInterval = 1;
    config.renderTargetFormat = GL_RGBA8;
    config.depthStencilFormat = GL_DEPTH24_STENCIL8;
    config.conformant     = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
    config.renderableType = config.conformant;
    config.matchNativePixmap = EGL_NONE;
    config.colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
    configs.add(config);
    return configs;
}
bool DisplayCGL::testDeviceLost()
{
    // TODO(cwallez) investigate implementing this
    return false;
}
egl::Error DisplayCGL::restoreLostDevice(const egl::Display *display)
{
    UNIMPLEMENTED();
    return egl::EglBadDisplay();
}
bool DisplayCGL::isValidNativeWindow(EGLNativeWindowType window) const
{
    NSObject *layer = reinterpret_cast<NSObject *>(window);
    return [layer isKindOfClass:[CALayer class]];
}
egl::Error DisplayCGL::validateClientBuffer(const egl::Config *configuration,
                                            EGLenum buftype,
                                            EGLClientBuffer clientBuffer,
                                            const egl::AttributeMap &attribs) const
{
    ASSERT(buftype == EGL_IOSURFACE_ANGLE);
    if (!IOSurfaceSurfaceCGL::validateAttributes(clientBuffer, attribs))
    {
        return egl::EglBadAttribute();
    }
    return egl::NoError();
}
CGLContextObj DisplayCGL::getCGLContext() const
{
    return mContext;
}
CGLPixelFormatObj DisplayCGL::getCGLPixelFormat() const
{
    return mPixelFormat;
}
void DisplayCGL::generateExtensions(egl::DisplayExtensions *outExtensions) const
{
    outExtensions->iosurfaceClientBuffer = true;
    outExtensions->surfacelessContext    = true;
    // Contexts are virtualized so textures and semaphores can be shared globally
    outExtensions->displayTextureShareGroup   = true;
    outExtensions->displaySemaphoreShareGroup = true;
    if (mSupportsGPUSwitching)
    {
        outExtensions->powerPreference = true;
    }
    DisplayGL::generateExtensions(outExtensions);
}
void DisplayCGL::generateCaps(egl::Caps *outCaps) const
{
    outCaps->textureNPOT = true;
}
egl::Error DisplayCGL::waitClient(const gl::Context *context)
{
    // TODO(cwallez) UNIMPLEMENTED()
    return egl::NoError();
}
egl::Error DisplayCGL::waitNative(const gl::Context *context, EGLint engine)
{
    // TODO(cwallez) UNIMPLEMENTED()
    return egl::NoError();
}
gl::Version DisplayCGL::getMaxSupportedESVersion() const
{
    return mRenderer->getMaxSupportedESVersion();
}
egl::Error DisplayCGL::makeCurrentSurfaceless(gl::Context *context)
{
    // We have nothing to do as mContext is always current, and that CGL is surfaceless by
    // default.
    return egl::NoError();
}
class WorkerContextCGL final : public WorkerContext
{
  public:
    WorkerContextCGL(CGLContextObj context);
    ~WorkerContextCGL() override;
    bool makeCurrent() override;
    void unmakeCurrent() override;
  private:
    CGLContextObj mContext;
};
WorkerContextCGL::WorkerContextCGL(CGLContextObj context) : mContext(context) {}
WorkerContextCGL::~WorkerContextCGL()
{
    CGLSetCurrentContext(nullptr);
    CGLReleaseContext(mContext);
    mContext = nullptr;
}
bool WorkerContextCGL::makeCurrent()
{
    CGLError error = CGLSetCurrentContext(mContext);
    if (error != kCGLNoError)
    {
        ERR() << "Unable to make gl context current.\n";
        return false;
    }
    return true;
}
void WorkerContextCGL::unmakeCurrent()
{
    CGLSetCurrentContext(nullptr);
}
WorkerContext *DisplayCGL::createWorkerContext(std::string *infoLog)
{
    CGLContextObj context = nullptr;
    CGLCreateContext(mPixelFormat, mContext, &context);
    if (context == nullptr)
    {
        *infoLog += "Could not create the CGL context.";
        return nullptr;
    }
    return new WorkerContextCGL(context);
}
void DisplayCGL::initializeFrontendFeatures(angle::FrontendFeatures *features) const
{
    mRenderer->initializeFrontendFeatures(features);
}
void DisplayCGL::populateFeatureList(angle::FeatureList *features)
{
    mRenderer->getFeatures().populateFeatureList(features);
}
RendererGL *DisplayCGL::getRenderer() const
{
    return mRenderer.get();
}
egl::Error DisplayCGL::referenceDiscreteGPU()
{
    // Should have been rejected by validation if not supported.
    ASSERT(mSupportsGPUSwitching);
    // Create discrete pixel format if necessary.
    if (mDiscreteGPUPixelFormat)
    {
        // Clear this out if necessary.
        mLastDiscreteGPUUnrefTime = 0.0;
    }
    else
    {
        ASSERT(mLastDiscreteGPUUnrefTime == 0.0);
        CGLPixelFormatAttribute discreteAttribs[] = {static_cast<CGLPixelFormatAttribute>(0)};
        GLint numPixelFormats                     = 0;
        if (CGLChoosePixelFormat(discreteAttribs, &mDiscreteGPUPixelFormat, &numPixelFormats) !=
            kCGLNoError)
        {
            return egl::EglBadAlloc() << "Error choosing discrete pixel format.";
        }
    }
    ++mDiscreteGPURefs;
    return egl::NoError();
}
egl::Error DisplayCGL::unreferenceDiscreteGPU()
{
    // Should have been rejected by validation if not supported.
    ASSERT(mSupportsGPUSwitching);
    ASSERT(mDiscreteGPURefs > 0);
    if (--mDiscreteGPURefs == 0)
    {
        auto *platform            = ANGLEPlatformCurrent();
        mLastDiscreteGPUUnrefTime = platform->monotonicallyIncreasingTime(platform);
    }
    return egl::NoError();
}
void DisplayCGL::checkDiscreteGPUStatus()
{
    const double kDiscreteGPUTimeoutInSeconds = 10.0;
    if (mLastDiscreteGPUUnrefTime != 0.0)
    {
        ASSERT(mSupportsGPUSwitching);
        // A non-zero value implies that the timer is ticking on deleting the discrete GPU pixel
        // format.
        auto *platform = ANGLEPlatformCurrent();
        ASSERT(platform);
        double currentTime = platform->monotonicallyIncreasingTime(platform);
        if (currentTime > mLastDiscreteGPUUnrefTime + kDiscreteGPUTimeoutInSeconds)
        {
            CGLDestroyPixelFormat(mDiscreteGPUPixelFormat);
            mDiscreteGPUPixelFormat   = nullptr;
            mLastDiscreteGPUUnrefTime = 0.0;
        }
    }
}
egl::Error DisplayCGL::handleGPUSwitch()
{
    if (mSupportsGPUSwitching)
    {
        uint64_t gpuID = angle::GetGpuIDFromDisplayID(kCGDirectMainDisplay);
        if (gpuID != mCurrentGPUID)
        {
            SetGPUByRegistryID(mContext, mPixelFormat, gpuID);
            // Performing the above operation seems to need a call to CGLSetCurrentContext to make
            // the context work properly again. Failing to do this returns null strings for
            // GL_VENDOR and GL_RENDERER.
            CGLUpdateContext(mContext);
            CGLSetCurrentContext(mContext);
            onStateChange(angle::SubjectMessage::SubjectChanged);
            mCurrentGPUID = gpuID;
            mRenderer->handleGPUSwitch();
        }
    }
    return egl::NoError();
}
}  // namespace rx
#endif  // defined(ANGLE_PLATFORM_MACOS) || defined(ANGLE_PLATFORM_MACCATALYST)