1
2/*
3 * Copyright 2016 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9#include "../GLWindowContext.h"
10#include "WindowContextFactory_mac.h"
11
12#include "SDL.h"
13
14#include <OpenGL/gl.h>
15
16using sk_app::DisplayParams;
17using sk_app::window_context_factory::MacWindowInfo;
18using sk_app::GLWindowContext;
19
20namespace {
21
22class GLWindowContext_mac : public GLWindowContext {
23public:
24    GLWindowContext_mac(const MacWindowInfo&, const DisplayParams&);
25
26    ~GLWindowContext_mac() override;
27
28    void onSwapBuffers() override;
29
30    void onInitializeContext() override;
31    void onDestroyContext() override;
32
33private:
34    SDL_Window*   fWindow;
35    SDL_GLContext fGLContext;
36
37    typedef GLWindowContext INHERITED;
38};
39
40GLWindowContext_mac::GLWindowContext_mac(const MacWindowInfo& info, const DisplayParams& params)
41    : INHERITED(params)
42    , fWindow(info.fWindow)
43    , fGLContext(nullptr) {
44
45    // any config code here (particularly for msaa)?
46
47    this->initializeContext();
48}
49
50GLWindowContext_mac::~GLWindowContext_mac() {
51    this->destroyContext();
52}
53
54void GLWindowContext_mac::onInitializeContext() {
55    SkASSERT(fWindow);
56
57    fGLContext = SDL_GL_CreateContext(fWindow);
58    if (!fGLContext) {
59        SkDebugf("%s\n", SDL_GetError());
60        return;
61    }
62
63    if (0 == SDL_GL_MakeCurrent(fWindow, fGLContext)) {
64        glClearStencil(0);
65        glClearColor(0, 0, 0, 0);
66        glStencilMask(0xffffffff);
67        glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
68
69        SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &fStencilBits);
70        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fSampleCount);
71
72        SDL_GetWindowSize(fWindow, &fWidth, &fHeight);
73        glViewport(0, 0, fWidth, fHeight);
74    } else {
75        SkDebugf("MakeCurrent failed: %s\n", SDL_GetError());
76    }
77}
78
79void GLWindowContext_mac::onDestroyContext() {
80    if (!fWindow || !fGLContext) {
81        return;
82    }
83    SDL_GL_DeleteContext(fGLContext);
84    fGLContext = nullptr;
85}
86
87
88void GLWindowContext_mac::onSwapBuffers() {
89    if (fWindow && fGLContext) {
90        SDL_GL_SwapWindow(fWindow);
91    }
92}
93
94}  // anonymous namespace
95
96namespace sk_app {
97namespace window_context_factory {
98
99WindowContext* NewGLForMac(const MacWindowInfo& info, const DisplayParams& params) {
100    WindowContext* ctx = new GLWindowContext_mac(info, params);
101    if (!ctx->isValid()) {
102        delete ctx;
103        return nullptr;
104    }
105    return ctx;
106}
107
108}  // namespace window_context_factory
109}  // namespace sk_app
110