egl.cpp revision 697526bc9e44ce61c88614f98387ae8bbf0a187e
1/*
2**
3** Copyright 2007 The Android Open Source Project
4**
5** Licensed under the Apache License Version 2.0(the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing software
12** distributed under the License is distributed on an "AS IS" BASIS
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include <assert.h>
19#include <errno.h>
20#include <stdlib.h>
21#include <stdio.h>
22#include <string.h>
23#include <unistd.h>
24#include <fcntl.h>
25#include <sys/ioctl.h>
26#include <sys/types.h>
27#include <sys/mman.h>
28
29#include <cutils/log.h>
30#include <cutils/atomic.h>
31
32#include <utils/threads.h>
33
34#include <EGL/egl.h>
35#include <EGL/eglext.h>
36#include <GLES/gl.h>
37#include <GLES/glext.h>
38
39#include <pixelflinger/format.h>
40#include <pixelflinger/pixelflinger.h>
41
42#include <private/ui/android_natives_priv.h>
43
44#include "context.h"
45#include "state.h"
46#include "texture.h"
47#include "matrix.h"
48
49#undef NELEM
50#define NELEM(x) (sizeof(x)/sizeof(*(x)))
51
52// ----------------------------------------------------------------------------
53namespace android {
54// ----------------------------------------------------------------------------
55
56const unsigned int NUM_DISPLAYS = 1;
57
58static pthread_mutex_t gInitMutex = PTHREAD_MUTEX_INITIALIZER;
59static pthread_mutex_t gErrorKeyMutex = PTHREAD_MUTEX_INITIALIZER;
60static pthread_key_t gEGLErrorKey = -1;
61#ifndef HAVE_ANDROID_OS
62namespace gl {
63pthread_key_t gGLKey = -1;
64}; // namespace gl
65#endif
66
67template<typename T>
68static T setError(GLint error, T returnValue) {
69    if (ggl_unlikely(gEGLErrorKey == -1)) {
70        pthread_mutex_lock(&gErrorKeyMutex);
71        if (gEGLErrorKey == -1)
72            pthread_key_create(&gEGLErrorKey, NULL);
73        pthread_mutex_unlock(&gErrorKeyMutex);
74    }
75    pthread_setspecific(gEGLErrorKey, (void*)error);
76    return returnValue;
77}
78
79static GLint getError() {
80    if (ggl_unlikely(gEGLErrorKey == -1))
81        return EGL_SUCCESS;
82    GLint error = (GLint)pthread_getspecific(gEGLErrorKey);
83    if (error == 0) {
84        // The TLS key has been created by another thread, but the value for
85        // this thread has not been initialized.
86        return EGL_SUCCESS;
87    }
88    pthread_setspecific(gEGLErrorKey, (void*)EGL_SUCCESS);
89    return error;
90}
91
92// ----------------------------------------------------------------------------
93
94struct egl_display_t
95{
96    egl_display_t() : type(0), initialized(0) { }
97
98    static egl_display_t& get_display(EGLDisplay dpy);
99
100    static EGLBoolean is_valid(EGLDisplay dpy) {
101        return ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS) ? EGL_FALSE : EGL_TRUE;
102    }
103
104    NativeDisplayType   type;
105    volatile int32_t    initialized;
106};
107
108static egl_display_t gDisplays[NUM_DISPLAYS];
109
110egl_display_t& egl_display_t::get_display(EGLDisplay dpy) {
111    return gDisplays[uintptr_t(dpy)-1U];
112}
113
114struct egl_context_t {
115    enum {
116        IS_CURRENT      =   0x00010000,
117        NEVER_CURRENT   =   0x00020000
118    };
119    uint32_t            flags;
120    EGLDisplay          dpy;
121    EGLConfig           config;
122    EGLSurface          read;
123    EGLSurface          draw;
124
125    static inline egl_context_t* context(EGLContext ctx) {
126        ogles_context_t* const gl = static_cast<ogles_context_t*>(ctx);
127        return static_cast<egl_context_t*>(gl->rasterizer.base);
128    }
129};
130
131// ----------------------------------------------------------------------------
132
133struct egl_surface_t
134{
135    enum {
136        PAGE_FLIP = 0x00000001,
137        MAGIC     = 0x31415265
138    };
139
140    uint32_t            magic;
141    EGLDisplay          dpy;
142    EGLConfig           config;
143    EGLContext          ctx;
144
145                egl_surface_t(EGLDisplay dpy, EGLConfig config, int32_t depthFormat);
146    virtual     ~egl_surface_t();
147                bool    isValid() const;
148    virtual     bool    initCheck() const = 0;
149
150    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl) = 0;
151    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl) = 0;
152    virtual     EGLBoolean  connect() { return EGL_TRUE; }
153    virtual     void        disconnect() {}
154    virtual     EGLint      getWidth() const = 0;
155    virtual     EGLint      getHeight() const = 0;
156
157    virtual     EGLint      getHorizontalResolution() const;
158    virtual     EGLint      getVerticalResolution() const;
159    virtual     EGLint      getRefreshRate() const;
160    virtual     EGLint      getSwapBehavior() const;
161    virtual     EGLBoolean  swapBuffers();
162    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
163protected:
164    GGLSurface              depth;
165};
166
167egl_surface_t::egl_surface_t(EGLDisplay dpy,
168        EGLConfig config,
169        int32_t depthFormat)
170    : magic(MAGIC), dpy(dpy), config(config), ctx(0)
171{
172    depth.version = sizeof(GGLSurface);
173    depth.data = 0;
174    depth.format = depthFormat;
175}
176egl_surface_t::~egl_surface_t()
177{
178    magic = 0;
179    free(depth.data);
180}
181bool egl_surface_t::isValid() const {
182    LOGE_IF(magic != MAGIC, "invalid EGLSurface (%p)", this);
183    return magic == MAGIC;
184}
185
186EGLBoolean egl_surface_t::swapBuffers() {
187    return EGL_FALSE;
188}
189EGLint egl_surface_t::getHorizontalResolution() const {
190    return (0 * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
191}
192EGLint egl_surface_t::getVerticalResolution() const {
193    return (0 * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
194}
195EGLint egl_surface_t::getRefreshRate() const {
196    return (60 * EGL_DISPLAY_SCALING);
197}
198EGLint egl_surface_t::getSwapBehavior() const {
199    return EGL_BUFFER_PRESERVED;
200}
201EGLBoolean egl_surface_t::setSwapRectangle(
202        EGLint l, EGLint t, EGLint w, EGLint h)
203{
204    return EGL_FALSE;
205}
206
207// ----------------------------------------------------------------------------
208
209struct egl_window_surface_v2_t : public egl_surface_t
210{
211    egl_window_surface_v2_t(
212            EGLDisplay dpy, EGLConfig config,
213            int32_t depthFormat,
214            ANativeWindow* window);
215
216    ~egl_window_surface_v2_t();
217
218    virtual     bool        initCheck() const { return true; } // TODO: report failure if ctor fails
219    virtual     EGLBoolean  swapBuffers();
220    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
221    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
222    virtual     EGLBoolean  connect();
223    virtual     void        disconnect();
224    virtual     EGLint      getWidth() const    { return width;  }
225    virtual     EGLint      getHeight() const   { return height; }
226    virtual     EGLint      getHorizontalResolution() const;
227    virtual     EGLint      getVerticalResolution() const;
228    virtual     EGLint      getRefreshRate() const;
229    virtual     EGLint      getSwapBehavior() const;
230    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
231
232private:
233    status_t lock(ANativeWindowBuffer* buf, int usage, void** vaddr);
234    status_t unlock(ANativeWindowBuffer* buf);
235    ANativeWindow*   nativeWindow;
236    ANativeWindowBuffer*   buffer;
237    ANativeWindowBuffer*   previousBuffer;
238    gralloc_module_t const*    module;
239    int width;
240    int height;
241    void* bits;
242    GGLFormat const* pixelFormatTable;
243
244    struct Rect {
245        inline Rect() { };
246        inline Rect(int32_t w, int32_t h)
247            : left(0), top(0), right(w), bottom(h) { }
248        inline Rect(int32_t l, int32_t t, int32_t r, int32_t b)
249            : left(l), top(t), right(r), bottom(b) { }
250        Rect& andSelf(const Rect& r) {
251            left   = max(left, r.left);
252            top    = max(top, r.top);
253            right  = min(right, r.right);
254            bottom = min(bottom, r.bottom);
255            return *this;
256        }
257        bool isEmpty() const {
258            return (left>=right || top>=bottom);
259        }
260        void dump(char const* what) {
261            LOGD("%s { %5d, %5d, w=%5d, h=%5d }",
262                    what, left, top, right-left, bottom-top);
263        }
264
265        int32_t left;
266        int32_t top;
267        int32_t right;
268        int32_t bottom;
269    };
270
271    struct Region {
272        inline Region() : count(0) { }
273        typedef Rect const* const_iterator;
274        const_iterator begin() const { return storage; }
275        const_iterator end() const { return storage+count; }
276        static Region subtract(const Rect& lhs, const Rect& rhs) {
277            Region reg;
278            Rect* storage = reg.storage;
279            if (!lhs.isEmpty()) {
280                if (lhs.top < rhs.top) { // top rect
281                    storage->left   = lhs.left;
282                    storage->top    = lhs.top;
283                    storage->right  = lhs.right;
284                    storage->bottom = rhs.top;
285                    storage++;
286                }
287                const int32_t top = max(lhs.top, rhs.top);
288                const int32_t bot = min(lhs.bottom, rhs.bottom);
289                if (top < bot) {
290                    if (lhs.left < rhs.left) { // left-side rect
291                        storage->left   = lhs.left;
292                        storage->top    = top;
293                        storage->right  = rhs.left;
294                        storage->bottom = bot;
295                        storage++;
296                    }
297                    if (lhs.right > rhs.right) { // right-side rect
298                        storage->left   = rhs.right;
299                        storage->top    = top;
300                        storage->right  = lhs.right;
301                        storage->bottom = bot;
302                        storage++;
303                    }
304                }
305                if (lhs.bottom > rhs.bottom) { // bottom rect
306                    storage->left   = lhs.left;
307                    storage->top    = rhs.bottom;
308                    storage->right  = lhs.right;
309                    storage->bottom = lhs.bottom;
310                    storage++;
311                }
312                reg.count = storage - reg.storage;
313            }
314            return reg;
315        }
316        bool isEmpty() const {
317            return count<=0;
318        }
319    private:
320        Rect storage[4];
321        ssize_t count;
322    };
323
324    void copyBlt(
325            ANativeWindowBuffer* dst, void* dst_vaddr,
326            ANativeWindowBuffer* src, void const* src_vaddr,
327            const Region& clip);
328
329    Rect dirtyRegion;
330    Rect oldDirtyRegion;
331};
332
333egl_window_surface_v2_t::egl_window_surface_v2_t(EGLDisplay dpy,
334        EGLConfig config,
335        int32_t depthFormat,
336        ANativeWindow* window)
337    : egl_surface_t(dpy, config, depthFormat),
338    nativeWindow(window), buffer(0), previousBuffer(0), module(0),
339    bits(NULL)
340{
341    pixelFormatTable = gglGetPixelFormatTable();
342
343    // keep a reference on the window
344    nativeWindow->common.incRef(&nativeWindow->common);
345    nativeWindow->query(nativeWindow, NATIVE_WINDOW_WIDTH, &width);
346    nativeWindow->query(nativeWindow, NATIVE_WINDOW_HEIGHT, &height);
347}
348
349egl_window_surface_v2_t::~egl_window_surface_v2_t() {
350    if (buffer) {
351        buffer->common.decRef(&buffer->common);
352    }
353    if (previousBuffer) {
354        previousBuffer->common.decRef(&previousBuffer->common);
355    }
356    nativeWindow->common.decRef(&nativeWindow->common);
357}
358
359EGLBoolean egl_window_surface_v2_t::connect()
360{
361    // we're intending to do software rendering
362    native_window_set_usage(nativeWindow,
363            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
364
365    // dequeue a buffer
366    if (nativeWindow->dequeueBuffer(nativeWindow, &buffer) != NO_ERROR) {
367        return setError(EGL_BAD_ALLOC, EGL_FALSE);
368    }
369
370    // allocate a corresponding depth-buffer
371    width = buffer->width;
372    height = buffer->height;
373    if (depth.format) {
374        depth.width   = width;
375        depth.height  = height;
376        depth.stride  = depth.width; // use the width here
377        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
378        if (depth.data == 0) {
379            return setError(EGL_BAD_ALLOC, EGL_FALSE);
380        }
381    }
382
383    // keep a reference on the buffer
384    buffer->common.incRef(&buffer->common);
385
386    // Lock the buffer
387    nativeWindow->lockBuffer(nativeWindow, buffer);
388    // pin the buffer down
389    if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN |
390            GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
391        LOGE("connect() failed to lock buffer %p (%ux%u)",
392                buffer, buffer->width, buffer->height);
393        return setError(EGL_BAD_ACCESS, EGL_FALSE);
394        // FIXME: we should make sure we're not accessing the buffer anymore
395    }
396    return EGL_TRUE;
397}
398
399void egl_window_surface_v2_t::disconnect()
400{
401    if (buffer && bits) {
402        bits = NULL;
403        unlock(buffer);
404    }
405    // enqueue the last frame
406    nativeWindow->queueBuffer(nativeWindow, buffer);
407    if (buffer) {
408        buffer->common.decRef(&buffer->common);
409        buffer = 0;
410    }
411    if (previousBuffer) {
412        previousBuffer->common.decRef(&previousBuffer->common);
413        previousBuffer = 0;
414    }
415}
416
417status_t egl_window_surface_v2_t::lock(
418        ANativeWindowBuffer* buf, int usage, void** vaddr)
419{
420    int err;
421
422    err = module->lock(module, buf->handle,
423            usage, 0, 0, buf->width, buf->height, vaddr);
424
425    return err;
426}
427
428status_t egl_window_surface_v2_t::unlock(ANativeWindowBuffer* buf)
429{
430    if (!buf) return BAD_VALUE;
431    int err = NO_ERROR;
432
433    err = module->unlock(module, buf->handle);
434
435    return err;
436}
437
438void egl_window_surface_v2_t::copyBlt(
439        ANativeWindowBuffer* dst, void* dst_vaddr,
440        ANativeWindowBuffer* src, void const* src_vaddr,
441        const Region& clip)
442{
443    // NOTE: dst and src must be the same format
444
445    Region::const_iterator cur = clip.begin();
446    Region::const_iterator end = clip.end();
447
448    const size_t bpp = pixelFormatTable[src->format].size;
449    const size_t dbpr = dst->stride * bpp;
450    const size_t sbpr = src->stride * bpp;
451
452    uint8_t const * const src_bits = (uint8_t const *)src_vaddr;
453    uint8_t       * const dst_bits = (uint8_t       *)dst_vaddr;
454
455    while (cur != end) {
456        const Rect& r(*cur++);
457        ssize_t w = r.right - r.left;
458        ssize_t h = r.bottom - r.top;
459        if (w <= 0 || h<=0) continue;
460        size_t size = w * bpp;
461        uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
462        uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
463        if (dbpr==sbpr && size==sbpr) {
464            size *= h;
465            h = 1;
466        }
467        do {
468            memcpy(d, s, size);
469            d += dbpr;
470            s += sbpr;
471        } while (--h > 0);
472    }
473}
474
475EGLBoolean egl_window_surface_v2_t::swapBuffers()
476{
477    if (!buffer) {
478        return setError(EGL_BAD_ACCESS, EGL_FALSE);
479    }
480
481    /*
482     * Handle eglSetSwapRectangleANDROID()
483     * We copyback from the front buffer
484     */
485    if (!dirtyRegion.isEmpty()) {
486        dirtyRegion.andSelf(Rect(buffer->width, buffer->height));
487        if (previousBuffer) {
488            // This was const Region copyBack, but that causes an
489            // internal compile error on simulator builds
490            /*const*/ Region copyBack(Region::subtract(oldDirtyRegion, dirtyRegion));
491            if (!copyBack.isEmpty()) {
492                void* prevBits;
493                if (lock(previousBuffer,
494                        GRALLOC_USAGE_SW_READ_OFTEN, &prevBits) == NO_ERROR) {
495                    // copy from previousBuffer to buffer
496                    copyBlt(buffer, bits, previousBuffer, prevBits, copyBack);
497                    unlock(previousBuffer);
498                }
499            }
500        }
501        oldDirtyRegion = dirtyRegion;
502    }
503
504    if (previousBuffer) {
505        previousBuffer->common.decRef(&previousBuffer->common);
506        previousBuffer = 0;
507    }
508
509    unlock(buffer);
510    previousBuffer = buffer;
511    nativeWindow->queueBuffer(nativeWindow, buffer);
512    buffer = 0;
513
514    // dequeue a new buffer
515    if (nativeWindow->dequeueBuffer(nativeWindow, &buffer) == NO_ERROR) {
516
517        // TODO: lockBuffer should rather be executed when the very first
518        // direct rendering occurs.
519        nativeWindow->lockBuffer(nativeWindow, buffer);
520
521        // reallocate the depth-buffer if needed
522        if ((width != buffer->width) || (height != buffer->height)) {
523            // TODO: we probably should reset the swap rect here
524            // if the window size has changed
525            width = buffer->width;
526            height = buffer->height;
527            if (depth.data) {
528                free(depth.data);
529                depth.width   = width;
530                depth.height  = height;
531                depth.stride  = buffer->stride;
532                depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
533                if (depth.data == 0) {
534                    setError(EGL_BAD_ALLOC, EGL_FALSE);
535                    return EGL_FALSE;
536                }
537            }
538        }
539
540        // keep a reference on the buffer
541        buffer->common.incRef(&buffer->common);
542
543        // finally pin the buffer down
544        if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN |
545                GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
546            LOGE("eglSwapBuffers() failed to lock buffer %p (%ux%u)",
547                    buffer, buffer->width, buffer->height);
548            return setError(EGL_BAD_ACCESS, EGL_FALSE);
549            // FIXME: we should make sure we're not accessing the buffer anymore
550        }
551    } else {
552        return setError(EGL_BAD_CURRENT_SURFACE, EGL_FALSE);
553    }
554
555    return EGL_TRUE;
556}
557
558EGLBoolean egl_window_surface_v2_t::setSwapRectangle(
559        EGLint l, EGLint t, EGLint w, EGLint h)
560{
561    dirtyRegion = Rect(l, t, l+w, t+h);
562    return EGL_TRUE;
563}
564
565EGLBoolean egl_window_surface_v2_t::bindDrawSurface(ogles_context_t* gl)
566{
567    GGLSurface buffer;
568    buffer.version = sizeof(GGLSurface);
569    buffer.width   = this->buffer->width;
570    buffer.height  = this->buffer->height;
571    buffer.stride  = this->buffer->stride;
572    buffer.data    = (GGLubyte*)bits;
573    buffer.format  = this->buffer->format;
574    gl->rasterizer.procs.colorBuffer(gl, &buffer);
575    if (depth.data != gl->rasterizer.state.buffers.depth.data)
576        gl->rasterizer.procs.depthBuffer(gl, &depth);
577
578    return EGL_TRUE;
579}
580EGLBoolean egl_window_surface_v2_t::bindReadSurface(ogles_context_t* gl)
581{
582    GGLSurface buffer;
583    buffer.version = sizeof(GGLSurface);
584    buffer.width   = this->buffer->width;
585    buffer.height  = this->buffer->height;
586    buffer.stride  = this->buffer->stride;
587    buffer.data    = (GGLubyte*)bits; // FIXME: hopefully is is LOCKED!!!
588    buffer.format  = this->buffer->format;
589    gl->rasterizer.procs.readBuffer(gl, &buffer);
590    return EGL_TRUE;
591}
592EGLint egl_window_surface_v2_t::getHorizontalResolution() const {
593    return (nativeWindow->xdpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
594}
595EGLint egl_window_surface_v2_t::getVerticalResolution() const {
596    return (nativeWindow->ydpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
597}
598EGLint egl_window_surface_v2_t::getRefreshRate() const {
599    return (60 * EGL_DISPLAY_SCALING); // FIXME
600}
601EGLint egl_window_surface_v2_t::getSwapBehavior() const
602{
603    /*
604     * EGL_BUFFER_PRESERVED means that eglSwapBuffers() completely preserves
605     * the content of the swapped buffer.
606     *
607     * EGL_BUFFER_DESTROYED means that the content of the buffer is lost.
608     *
609     * However when ANDROID_swap_retcangle is supported, EGL_BUFFER_DESTROYED
610     * only applies to the area specified by eglSetSwapRectangleANDROID(), that
611     * is, everything outside of this area is preserved.
612     *
613     * This implementation of EGL assumes the later case.
614     *
615     */
616
617    return EGL_BUFFER_DESTROYED;
618}
619
620// ----------------------------------------------------------------------------
621
622struct egl_pixmap_surface_t : public egl_surface_t
623{
624    egl_pixmap_surface_t(
625            EGLDisplay dpy, EGLConfig config,
626            int32_t depthFormat,
627            egl_native_pixmap_t const * pixmap);
628
629    virtual ~egl_pixmap_surface_t() { }
630
631    virtual     bool        initCheck() const { return !depth.format || depth.data!=0; }
632    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
633    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
634    virtual     EGLint      getWidth() const    { return nativePixmap.width;  }
635    virtual     EGLint      getHeight() const   { return nativePixmap.height; }
636private:
637    egl_native_pixmap_t     nativePixmap;
638};
639
640egl_pixmap_surface_t::egl_pixmap_surface_t(EGLDisplay dpy,
641        EGLConfig config,
642        int32_t depthFormat,
643        egl_native_pixmap_t const * pixmap)
644    : egl_surface_t(dpy, config, depthFormat), nativePixmap(*pixmap)
645{
646    if (depthFormat) {
647        depth.width   = pixmap->width;
648        depth.height  = pixmap->height;
649        depth.stride  = depth.width; // use the width here
650        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
651        if (depth.data == 0) {
652            setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
653        }
654    }
655}
656EGLBoolean egl_pixmap_surface_t::bindDrawSurface(ogles_context_t* gl)
657{
658    GGLSurface buffer;
659    buffer.version = sizeof(GGLSurface);
660    buffer.width   = nativePixmap.width;
661    buffer.height  = nativePixmap.height;
662    buffer.stride  = nativePixmap.stride;
663    buffer.data    = nativePixmap.data;
664    buffer.format  = nativePixmap.format;
665
666    gl->rasterizer.procs.colorBuffer(gl, &buffer);
667    if (depth.data != gl->rasterizer.state.buffers.depth.data)
668        gl->rasterizer.procs.depthBuffer(gl, &depth);
669    return EGL_TRUE;
670}
671EGLBoolean egl_pixmap_surface_t::bindReadSurface(ogles_context_t* gl)
672{
673    GGLSurface buffer;
674    buffer.version = sizeof(GGLSurface);
675    buffer.width   = nativePixmap.width;
676    buffer.height  = nativePixmap.height;
677    buffer.stride  = nativePixmap.stride;
678    buffer.data    = nativePixmap.data;
679    buffer.format  = nativePixmap.format;
680    gl->rasterizer.procs.readBuffer(gl, &buffer);
681    return EGL_TRUE;
682}
683
684// ----------------------------------------------------------------------------
685
686struct egl_pbuffer_surface_t : public egl_surface_t
687{
688    egl_pbuffer_surface_t(
689            EGLDisplay dpy, EGLConfig config, int32_t depthFormat,
690            int32_t w, int32_t h, int32_t f);
691
692    virtual ~egl_pbuffer_surface_t();
693
694    virtual     bool        initCheck() const   { return pbuffer.data != 0; }
695    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
696    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
697    virtual     EGLint      getWidth() const    { return pbuffer.width;  }
698    virtual     EGLint      getHeight() const   { return pbuffer.height; }
699private:
700    GGLSurface  pbuffer;
701};
702
703egl_pbuffer_surface_t::egl_pbuffer_surface_t(EGLDisplay dpy,
704        EGLConfig config, int32_t depthFormat,
705        int32_t w, int32_t h, int32_t f)
706    : egl_surface_t(dpy, config, depthFormat)
707{
708    size_t size = w*h;
709    switch (f) {
710        case GGL_PIXEL_FORMAT_A_8:          size *= 1; break;
711        case GGL_PIXEL_FORMAT_RGB_565:      size *= 2; break;
712        case GGL_PIXEL_FORMAT_RGBA_8888:    size *= 4; break;
713        case GGL_PIXEL_FORMAT_RGBX_8888:    size *= 4; break;
714        default:
715            LOGE("incompatible pixel format for pbuffer (format=%d)", f);
716            pbuffer.data = 0;
717            break;
718    }
719    pbuffer.version = sizeof(GGLSurface);
720    pbuffer.width   = w;
721    pbuffer.height  = h;
722    pbuffer.stride  = w;
723    pbuffer.data    = (GGLubyte*)malloc(size);
724    pbuffer.format  = f;
725
726    if (depthFormat) {
727        depth.width   = pbuffer.width;
728        depth.height  = pbuffer.height;
729        depth.stride  = depth.width; // use the width here
730        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
731        if (depth.data == 0) {
732            setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
733            return;
734        }
735    }
736}
737egl_pbuffer_surface_t::~egl_pbuffer_surface_t() {
738    free(pbuffer.data);
739}
740EGLBoolean egl_pbuffer_surface_t::bindDrawSurface(ogles_context_t* gl)
741{
742    gl->rasterizer.procs.colorBuffer(gl, &pbuffer);
743    if (depth.data != gl->rasterizer.state.buffers.depth.data)
744        gl->rasterizer.procs.depthBuffer(gl, &depth);
745    return EGL_TRUE;
746}
747EGLBoolean egl_pbuffer_surface_t::bindReadSurface(ogles_context_t* gl)
748{
749    gl->rasterizer.procs.readBuffer(gl, &pbuffer);
750    return EGL_TRUE;
751}
752
753// ----------------------------------------------------------------------------
754
755struct config_pair_t {
756    GLint key;
757    GLint value;
758};
759
760struct configs_t {
761    const config_pair_t* array;
762    int                  size;
763};
764
765struct config_management_t {
766    GLint key;
767    bool (*match)(GLint reqValue, GLint confValue);
768    static bool atLeast(GLint reqValue, GLint confValue) {
769        return (reqValue == EGL_DONT_CARE) || (confValue >= reqValue);
770    }
771    static bool exact(GLint reqValue, GLint confValue) {
772        return (reqValue == EGL_DONT_CARE) || (confValue == reqValue);
773    }
774    static bool mask(GLint reqValue, GLint confValue) {
775        return (confValue & reqValue) == reqValue;
776    }
777    static bool ignore(GLint reqValue, GLint confValue) {
778        return true;
779    }
780};
781
782// ----------------------------------------------------------------------------
783
784#define VERSION_MAJOR 1
785#define VERSION_MINOR 2
786static char const * const gVendorString     = "Google Inc.";
787static char const * const gVersionString    = "1.2 Android Driver 1.2.0";
788static char const * const gClientApiString  = "OpenGL ES";
789static char const * const gExtensionsString =
790        "EGL_KHR_image_base "
791        // "KHR_image_pixmap "
792        "EGL_ANDROID_image_native_buffer "
793        "EGL_ANDROID_swap_rectangle "
794        ;
795
796// ----------------------------------------------------------------------------
797
798struct extention_map_t {
799    const char * const name;
800    __eglMustCastToProperFunctionPointerType address;
801};
802
803static const extention_map_t gExtentionMap[] = {
804    { "glDrawTexsOES",
805            (__eglMustCastToProperFunctionPointerType)&glDrawTexsOES },
806    { "glDrawTexiOES",
807            (__eglMustCastToProperFunctionPointerType)&glDrawTexiOES },
808    { "glDrawTexfOES",
809            (__eglMustCastToProperFunctionPointerType)&glDrawTexfOES },
810    { "glDrawTexxOES",
811            (__eglMustCastToProperFunctionPointerType)&glDrawTexxOES },
812    { "glDrawTexsvOES",
813            (__eglMustCastToProperFunctionPointerType)&glDrawTexsvOES },
814    { "glDrawTexivOES",
815            (__eglMustCastToProperFunctionPointerType)&glDrawTexivOES },
816    { "glDrawTexfvOES",
817            (__eglMustCastToProperFunctionPointerType)&glDrawTexfvOES },
818    { "glDrawTexxvOES",
819            (__eglMustCastToProperFunctionPointerType)&glDrawTexxvOES },
820    { "glQueryMatrixxOES",
821            (__eglMustCastToProperFunctionPointerType)&glQueryMatrixxOES },
822    { "glEGLImageTargetTexture2DOES",
823            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetTexture2DOES },
824    { "glEGLImageTargetRenderbufferStorageOES",
825            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetRenderbufferStorageOES },
826    { "glClipPlanef",
827            (__eglMustCastToProperFunctionPointerType)&glClipPlanef },
828    { "glClipPlanex",
829            (__eglMustCastToProperFunctionPointerType)&glClipPlanex },
830    { "glBindBuffer",
831            (__eglMustCastToProperFunctionPointerType)&glBindBuffer },
832    { "glBufferData",
833            (__eglMustCastToProperFunctionPointerType)&glBufferData },
834    { "glBufferSubData",
835            (__eglMustCastToProperFunctionPointerType)&glBufferSubData },
836    { "glDeleteBuffers",
837            (__eglMustCastToProperFunctionPointerType)&glDeleteBuffers },
838    { "glGenBuffers",
839            (__eglMustCastToProperFunctionPointerType)&glGenBuffers },
840    { "eglCreateImageKHR",
841            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR },
842    { "eglDestroyImageKHR",
843            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR },
844    { "eglSetSwapRectangleANDROID",
845            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID },
846};
847
848/*
849 * In the lists below, attributes names MUST be sorted.
850 * Additionally, all configs must be sorted according to
851 * the EGL specification.
852 */
853
854static config_pair_t const config_base_attribute_list[] = {
855        { EGL_STENCIL_SIZE,               0                                 },
856        { EGL_CONFIG_CAVEAT,              EGL_SLOW_CONFIG                   },
857        { EGL_LEVEL,                      0                                 },
858        { EGL_MAX_PBUFFER_HEIGHT,         GGL_MAX_VIEWPORT_DIMS             },
859        { EGL_MAX_PBUFFER_PIXELS,
860                GGL_MAX_VIEWPORT_DIMS*GGL_MAX_VIEWPORT_DIMS                 },
861        { EGL_MAX_PBUFFER_WIDTH,          GGL_MAX_VIEWPORT_DIMS             },
862        { EGL_NATIVE_RENDERABLE,          EGL_TRUE                          },
863        { EGL_NATIVE_VISUAL_ID,           0                                 },
864        { EGL_NATIVE_VISUAL_TYPE,         GGL_PIXEL_FORMAT_RGB_565          },
865        { EGL_SAMPLES,                    0                                 },
866        { EGL_SAMPLE_BUFFERS,             0                                 },
867        { EGL_TRANSPARENT_TYPE,           EGL_NONE                          },
868        { EGL_TRANSPARENT_BLUE_VALUE,     0                                 },
869        { EGL_TRANSPARENT_GREEN_VALUE,    0                                 },
870        { EGL_TRANSPARENT_RED_VALUE,      0                                 },
871        { EGL_BIND_TO_TEXTURE_RGBA,       EGL_FALSE                         },
872        { EGL_BIND_TO_TEXTURE_RGB,        EGL_FALSE                         },
873        { EGL_MIN_SWAP_INTERVAL,          1                                 },
874        { EGL_MAX_SWAP_INTERVAL,          1                                 },
875        { EGL_LUMINANCE_SIZE,             0                                 },
876        { EGL_ALPHA_MASK_SIZE,            0                                 },
877        { EGL_COLOR_BUFFER_TYPE,          EGL_RGB_BUFFER                    },
878        { EGL_RENDERABLE_TYPE,            EGL_OPENGL_ES_BIT                 },
879        { EGL_CONFORMANT,                 0                                 }
880};
881
882// These configs can override the base attribute list
883// NOTE: when adding a config here, don't forget to update eglCreate*Surface()
884
885// 565 configs
886static config_pair_t const config_0_attribute_list[] = {
887        { EGL_BUFFER_SIZE,     16 },
888        { EGL_ALPHA_SIZE,       0 },
889        { EGL_BLUE_SIZE,        5 },
890        { EGL_GREEN_SIZE,       6 },
891        { EGL_RED_SIZE,         5 },
892        { EGL_DEPTH_SIZE,       0 },
893        { EGL_CONFIG_ID,        0 },
894        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGB_565 },
895        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
896};
897
898static config_pair_t const config_1_attribute_list[] = {
899        { EGL_BUFFER_SIZE,     16 },
900        { EGL_ALPHA_SIZE,       0 },
901        { EGL_BLUE_SIZE,        5 },
902        { EGL_GREEN_SIZE,       6 },
903        { EGL_RED_SIZE,         5 },
904        { EGL_DEPTH_SIZE,      16 },
905        { EGL_CONFIG_ID,        1 },
906        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGB_565 },
907        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
908};
909
910// RGB 888 configs
911static config_pair_t const config_2_attribute_list[] = {
912        { EGL_BUFFER_SIZE,     32 },
913        { EGL_ALPHA_SIZE,       0 },
914        { EGL_BLUE_SIZE,        8 },
915        { EGL_GREEN_SIZE,       8 },
916        { EGL_RED_SIZE,         8 },
917        { EGL_DEPTH_SIZE,       0 },
918        { EGL_CONFIG_ID,        6 },
919        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGBX_8888 },
920        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
921};
922
923static config_pair_t const config_3_attribute_list[] = {
924        { EGL_BUFFER_SIZE,     32 },
925        { EGL_ALPHA_SIZE,       0 },
926        { EGL_BLUE_SIZE,        8 },
927        { EGL_GREEN_SIZE,       8 },
928        { EGL_RED_SIZE,         8 },
929        { EGL_DEPTH_SIZE,      16 },
930        { EGL_CONFIG_ID,        7 },
931        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGBX_8888 },
932        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
933};
934
935// 8888 configs
936static config_pair_t const config_4_attribute_list[] = {
937        { EGL_BUFFER_SIZE,     32 },
938        { EGL_ALPHA_SIZE,       8 },
939        { EGL_BLUE_SIZE,        8 },
940        { EGL_GREEN_SIZE,       8 },
941        { EGL_RED_SIZE,         8 },
942        { EGL_DEPTH_SIZE,       0 },
943        { EGL_CONFIG_ID,        2 },
944        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGBA_8888 },
945        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
946};
947
948static config_pair_t const config_5_attribute_list[] = {
949        { EGL_BUFFER_SIZE,     32 },
950        { EGL_ALPHA_SIZE,       8 },
951        { EGL_BLUE_SIZE,        8 },
952        { EGL_GREEN_SIZE,       8 },
953        { EGL_RED_SIZE,         8 },
954        { EGL_DEPTH_SIZE,      16 },
955        { EGL_CONFIG_ID,        3 },
956        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_RGBA_8888 },
957        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
958};
959
960// A8 configs
961static config_pair_t const config_6_attribute_list[] = {
962        { EGL_BUFFER_SIZE,      8 },
963        { EGL_ALPHA_SIZE,       8 },
964        { EGL_BLUE_SIZE,        0 },
965        { EGL_GREEN_SIZE,       0 },
966        { EGL_RED_SIZE,         0 },
967        { EGL_DEPTH_SIZE,       0 },
968        { EGL_CONFIG_ID,        4 },
969        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_A_8 },
970        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
971};
972
973static config_pair_t const config_7_attribute_list[] = {
974        { EGL_BUFFER_SIZE,      8 },
975        { EGL_ALPHA_SIZE,       8 },
976        { EGL_BLUE_SIZE,        0 },
977        { EGL_GREEN_SIZE,       0 },
978        { EGL_RED_SIZE,         0 },
979        { EGL_DEPTH_SIZE,      16 },
980        { EGL_CONFIG_ID,        5 },
981        { EGL_NATIVE_VISUAL_ID, GGL_PIXEL_FORMAT_A_8 },
982        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
983};
984
985static configs_t const gConfigs[] = {
986        { config_0_attribute_list, NELEM(config_0_attribute_list) },
987        { config_1_attribute_list, NELEM(config_1_attribute_list) },
988        { config_2_attribute_list, NELEM(config_2_attribute_list) },
989        { config_3_attribute_list, NELEM(config_3_attribute_list) },
990        { config_4_attribute_list, NELEM(config_4_attribute_list) },
991        { config_5_attribute_list, NELEM(config_5_attribute_list) },
992        { config_6_attribute_list, NELEM(config_6_attribute_list) },
993        { config_7_attribute_list, NELEM(config_7_attribute_list) },
994};
995
996static config_management_t const gConfigManagement[] = {
997        { EGL_BUFFER_SIZE,                config_management_t::atLeast },
998        { EGL_ALPHA_SIZE,                 config_management_t::atLeast },
999        { EGL_BLUE_SIZE,                  config_management_t::atLeast },
1000        { EGL_GREEN_SIZE,                 config_management_t::atLeast },
1001        { EGL_RED_SIZE,                   config_management_t::atLeast },
1002        { EGL_DEPTH_SIZE,                 config_management_t::atLeast },
1003        { EGL_STENCIL_SIZE,               config_management_t::atLeast },
1004        { EGL_CONFIG_CAVEAT,              config_management_t::exact   },
1005        { EGL_CONFIG_ID,                  config_management_t::exact   },
1006        { EGL_LEVEL,                      config_management_t::exact   },
1007        { EGL_MAX_PBUFFER_HEIGHT,         config_management_t::ignore   },
1008        { EGL_MAX_PBUFFER_PIXELS,         config_management_t::ignore   },
1009        { EGL_MAX_PBUFFER_WIDTH,          config_management_t::ignore   },
1010        { EGL_NATIVE_RENDERABLE,          config_management_t::exact   },
1011        { EGL_NATIVE_VISUAL_ID,           config_management_t::ignore   },
1012        { EGL_NATIVE_VISUAL_TYPE,         config_management_t::exact   },
1013        { EGL_SAMPLES,                    config_management_t::exact   },
1014        { EGL_SAMPLE_BUFFERS,             config_management_t::exact   },
1015        { EGL_SURFACE_TYPE,               config_management_t::mask    },
1016        { EGL_TRANSPARENT_TYPE,           config_management_t::exact   },
1017        { EGL_TRANSPARENT_BLUE_VALUE,     config_management_t::exact   },
1018        { EGL_TRANSPARENT_GREEN_VALUE,    config_management_t::exact   },
1019        { EGL_TRANSPARENT_RED_VALUE,      config_management_t::exact   },
1020        { EGL_BIND_TO_TEXTURE_RGBA,       config_management_t::exact   },
1021        { EGL_BIND_TO_TEXTURE_RGB,        config_management_t::exact   },
1022        { EGL_MIN_SWAP_INTERVAL,          config_management_t::exact   },
1023        { EGL_MAX_SWAP_INTERVAL,          config_management_t::exact   },
1024        { EGL_LUMINANCE_SIZE,             config_management_t::atLeast },
1025        { EGL_ALPHA_MASK_SIZE,            config_management_t::atLeast },
1026        { EGL_COLOR_BUFFER_TYPE,          config_management_t::exact   },
1027        { EGL_RENDERABLE_TYPE,            config_management_t::mask    },
1028        { EGL_CONFORMANT,                 config_management_t::mask    }
1029};
1030
1031
1032static config_pair_t const config_defaults[] = {
1033    // attributes that are not specified are simply ignored, if a particular
1034    // one needs not be ignored, it must be specified here, eg:
1035    // { EGL_SURFACE_TYPE, EGL_WINDOW_BIT },
1036};
1037
1038// ----------------------------------------------------------------------------
1039
1040static status_t getConfigFormatInfo(EGLint configID,
1041        int32_t& pixelFormat, int32_t& depthFormat)
1042{
1043    switch(configID) {
1044    case 0:
1045        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1046        depthFormat = 0;
1047        break;
1048    case 1:
1049        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1050        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1051        break;
1052    case 2:
1053        pixelFormat = GGL_PIXEL_FORMAT_RGBX_8888;
1054        depthFormat = 0;
1055        break;
1056    case 3:
1057        pixelFormat = GGL_PIXEL_FORMAT_RGBX_8888;
1058        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1059        break;
1060    case 4:
1061        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1062        depthFormat = 0;
1063        break;
1064    case 5:
1065        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1066        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1067        break;
1068    case 6:
1069        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1070        depthFormat = 0;
1071        break;
1072    case 7:
1073        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1074        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1075        break;
1076    default:
1077        return NAME_NOT_FOUND;
1078    }
1079    return NO_ERROR;
1080}
1081
1082// ----------------------------------------------------------------------------
1083
1084template<typename T>
1085static int binarySearch(T const sortedArray[], int first, int last, EGLint key)
1086{
1087   while (first <= last) {
1088       int mid = (first + last) / 2;
1089       if (key > sortedArray[mid].key) {
1090           first = mid + 1;
1091       } else if (key < sortedArray[mid].key) {
1092           last = mid - 1;
1093       } else {
1094           return mid;
1095       }
1096   }
1097   return -1;
1098}
1099
1100static int isAttributeMatching(int i, EGLint attr, EGLint val)
1101{
1102    // look for the attribute in all of our configs
1103    config_pair_t const* configFound = gConfigs[i].array;
1104    int index = binarySearch<config_pair_t>(
1105            gConfigs[i].array,
1106            0, gConfigs[i].size-1,
1107            attr);
1108    if (index < 0) {
1109        configFound = config_base_attribute_list;
1110        index = binarySearch<config_pair_t>(
1111                config_base_attribute_list,
1112                0, NELEM(config_base_attribute_list)-1,
1113                attr);
1114    }
1115    if (index >= 0) {
1116        // attribute found, check if this config could match
1117        int cfgMgtIndex = binarySearch<config_management_t>(
1118                gConfigManagement,
1119                0, NELEM(gConfigManagement)-1,
1120                attr);
1121        if (cfgMgtIndex >= 0) {
1122            bool match = gConfigManagement[cfgMgtIndex].match(
1123                    val, configFound[index].value);
1124            if (match) {
1125                // this config matches
1126                return 1;
1127            }
1128        } else {
1129            // attribute not found. this should NEVER happen.
1130        }
1131    } else {
1132        // error, this attribute doesn't exist
1133    }
1134    return 0;
1135}
1136
1137static int makeCurrent(ogles_context_t* gl)
1138{
1139    ogles_context_t* current = (ogles_context_t*)getGlThreadSpecific();
1140    if (gl) {
1141        egl_context_t* c = egl_context_t::context(gl);
1142        if (c->flags & egl_context_t::IS_CURRENT) {
1143            if (current != gl) {
1144                // it is an error to set a context current, if it's already
1145                // current to another thread
1146                return -1;
1147            }
1148        } else {
1149            if (current) {
1150                // mark the current context as not current, and flush
1151                glFlush();
1152                egl_context_t::context(current)->flags &= ~egl_context_t::IS_CURRENT;
1153            }
1154        }
1155        if (!(c->flags & egl_context_t::IS_CURRENT)) {
1156            // The context is not current, make it current!
1157            setGlThreadSpecific(gl);
1158            c->flags |= egl_context_t::IS_CURRENT;
1159        }
1160    } else {
1161        if (current) {
1162            // mark the current context as not current, and flush
1163            glFlush();
1164            egl_context_t::context(current)->flags &= ~egl_context_t::IS_CURRENT;
1165        }
1166        // this thread has no context attached to it
1167        setGlThreadSpecific(0);
1168    }
1169    return 0;
1170}
1171
1172static EGLBoolean getConfigAttrib(EGLDisplay dpy, EGLConfig config,
1173        EGLint attribute, EGLint *value)
1174{
1175    size_t numConfigs =  NELEM(gConfigs);
1176    int index = (int)config;
1177    if (uint32_t(index) >= numConfigs)
1178        return setError(EGL_BAD_CONFIG, EGL_FALSE);
1179
1180    int attrIndex;
1181    attrIndex = binarySearch<config_pair_t>(
1182            gConfigs[index].array,
1183            0, gConfigs[index].size-1,
1184            attribute);
1185    if (attrIndex>=0) {
1186        *value = gConfigs[index].array[attrIndex].value;
1187        return EGL_TRUE;
1188    }
1189
1190    attrIndex = binarySearch<config_pair_t>(
1191            config_base_attribute_list,
1192            0, NELEM(config_base_attribute_list)-1,
1193            attribute);
1194    if (attrIndex>=0) {
1195        *value = config_base_attribute_list[attrIndex].value;
1196        return EGL_TRUE;
1197    }
1198    return setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1199}
1200
1201static EGLSurface createWindowSurface(EGLDisplay dpy, EGLConfig config,
1202        NativeWindowType window, const EGLint *attrib_list)
1203{
1204    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1205        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1206    if (window == 0)
1207        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1208
1209    EGLint surfaceType;
1210    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1211        return EGL_FALSE;
1212
1213    if (!(surfaceType & EGL_WINDOW_BIT))
1214        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1215
1216    if (static_cast<ANativeWindow*>(window)->common.magic !=
1217            ANDROID_NATIVE_WINDOW_MAGIC) {
1218        return setError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
1219    }
1220
1221    EGLint configID;
1222    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1223        return EGL_FALSE;
1224
1225    int32_t depthFormat;
1226    int32_t pixelFormat;
1227    if (getConfigFormatInfo(configID, pixelFormat, depthFormat) != NO_ERROR) {
1228        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1229    }
1230
1231    // FIXME: we don't have access to the pixelFormat here just yet.
1232    // (it's possible that the surface is not fully initialized)
1233    // maybe this should be done after the page-flip
1234    //if (EGLint(info.format) != pixelFormat)
1235    //    return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1236
1237    egl_surface_t* surface;
1238    surface = new egl_window_surface_v2_t(dpy, config, depthFormat,
1239            static_cast<ANativeWindow*>(window));
1240
1241    if (!surface->initCheck()) {
1242        // there was a problem in the ctor, the error
1243        // flag has been set.
1244        delete surface;
1245        surface = 0;
1246    }
1247    return surface;
1248}
1249
1250static EGLSurface createPixmapSurface(EGLDisplay dpy, EGLConfig config,
1251        NativePixmapType pixmap, const EGLint *attrib_list)
1252{
1253    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1254        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1255    if (pixmap == 0)
1256        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1257
1258    EGLint surfaceType;
1259    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1260        return EGL_FALSE;
1261
1262    if (!(surfaceType & EGL_PIXMAP_BIT))
1263        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1264
1265    if (static_cast<egl_native_pixmap_t*>(pixmap)->version !=
1266            sizeof(egl_native_pixmap_t)) {
1267        return setError(EGL_BAD_NATIVE_PIXMAP, EGL_NO_SURFACE);
1268    }
1269
1270    EGLint configID;
1271    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1272        return EGL_FALSE;
1273
1274    int32_t depthFormat;
1275    int32_t pixelFormat;
1276    if (getConfigFormatInfo(configID, pixelFormat, depthFormat) != NO_ERROR) {
1277        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1278    }
1279
1280    if (pixmap->format != pixelFormat)
1281        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1282
1283    egl_surface_t* surface =
1284        new egl_pixmap_surface_t(dpy, config, depthFormat,
1285                static_cast<egl_native_pixmap_t*>(pixmap));
1286
1287    if (!surface->initCheck()) {
1288        // there was a problem in the ctor, the error
1289        // flag has been set.
1290        delete surface;
1291        surface = 0;
1292    }
1293    return surface;
1294}
1295
1296static EGLSurface createPbufferSurface(EGLDisplay dpy, EGLConfig config,
1297        const EGLint *attrib_list)
1298{
1299    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1300        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1301
1302    EGLint surfaceType;
1303    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1304        return EGL_FALSE;
1305
1306    if (!(surfaceType & EGL_PBUFFER_BIT))
1307        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1308
1309    EGLint configID;
1310    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1311        return EGL_FALSE;
1312
1313    int32_t depthFormat;
1314    int32_t pixelFormat;
1315    if (getConfigFormatInfo(configID, pixelFormat, depthFormat) != NO_ERROR) {
1316        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1317    }
1318
1319    int32_t w = 0;
1320    int32_t h = 0;
1321    while (attrib_list[0]) {
1322        if (attrib_list[0] == EGL_WIDTH)  w = attrib_list[1];
1323        if (attrib_list[0] == EGL_HEIGHT) h = attrib_list[1];
1324        attrib_list+=2;
1325    }
1326
1327    egl_surface_t* surface =
1328        new egl_pbuffer_surface_t(dpy, config, depthFormat, w, h, pixelFormat);
1329
1330    if (!surface->initCheck()) {
1331        // there was a problem in the ctor, the error
1332        // flag has been set.
1333        delete surface;
1334        surface = 0;
1335    }
1336    return surface;
1337}
1338
1339// ----------------------------------------------------------------------------
1340}; // namespace android
1341// ----------------------------------------------------------------------------
1342
1343using namespace android;
1344
1345// ----------------------------------------------------------------------------
1346// Initialization
1347// ----------------------------------------------------------------------------
1348
1349EGLDisplay eglGetDisplay(NativeDisplayType display)
1350{
1351#ifndef HAVE_ANDROID_OS
1352    // this just needs to be done once
1353    if (gGLKey == -1) {
1354        pthread_mutex_lock(&gInitMutex);
1355        if (gGLKey == -1)
1356            pthread_key_create(&gGLKey, NULL);
1357        pthread_mutex_unlock(&gInitMutex);
1358    }
1359#endif
1360    if (display == EGL_DEFAULT_DISPLAY) {
1361        EGLDisplay dpy = (EGLDisplay)1;
1362        egl_display_t& d = egl_display_t::get_display(dpy);
1363        d.type = display;
1364        return dpy;
1365    }
1366    return EGL_NO_DISPLAY;
1367}
1368
1369EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
1370{
1371    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1372        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1373
1374    EGLBoolean res = EGL_TRUE;
1375    egl_display_t& d = egl_display_t::get_display(dpy);
1376
1377    if (android_atomic_inc(&d.initialized) == 0) {
1378        // initialize stuff here if needed
1379        //pthread_mutex_lock(&gInitMutex);
1380        //pthread_mutex_unlock(&gInitMutex);
1381    }
1382
1383    if (res == EGL_TRUE) {
1384        if (major != NULL) *major = VERSION_MAJOR;
1385        if (minor != NULL) *minor = VERSION_MINOR;
1386    }
1387    return res;
1388}
1389
1390EGLBoolean eglTerminate(EGLDisplay dpy)
1391{
1392    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1393        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1394
1395    EGLBoolean res = EGL_TRUE;
1396    egl_display_t& d = egl_display_t::get_display(dpy);
1397    if (android_atomic_dec(&d.initialized) == 1) {
1398        // TODO: destroy all resources (surfaces, contexts, etc...)
1399        //pthread_mutex_lock(&gInitMutex);
1400        //pthread_mutex_unlock(&gInitMutex);
1401    }
1402    return res;
1403}
1404
1405// ----------------------------------------------------------------------------
1406// configuration
1407// ----------------------------------------------------------------------------
1408
1409EGLBoolean eglGetConfigs(   EGLDisplay dpy,
1410                            EGLConfig *configs,
1411                            EGLint config_size, EGLint *num_config)
1412{
1413    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1414        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1415
1416    GLint numConfigs = NELEM(gConfigs);
1417    if (!configs) {
1418        *num_config = numConfigs;
1419        return EGL_TRUE;
1420    }
1421    GLint i;
1422    for (i=0 ; i<numConfigs && i<config_size ; i++) {
1423        *configs++ = (EGLConfig)i;
1424    }
1425    *num_config = i;
1426    return EGL_TRUE;
1427}
1428
1429EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list,
1430                            EGLConfig *configs, EGLint config_size,
1431                            EGLint *num_config)
1432{
1433    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1434        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1435
1436    if (ggl_unlikely(num_config==0)) {
1437        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1438    }
1439
1440    if (ggl_unlikely(attrib_list==0)) {
1441        /*
1442         * A NULL attrib_list should be treated as though it was an empty
1443         * one (terminated with EGL_NONE) as defined in
1444         * section 3.4.1 "Querying Configurations" in the EGL specification.
1445         */
1446        static const EGLint dummy = EGL_NONE;
1447        attrib_list = &dummy;
1448    }
1449
1450    int numAttributes = 0;
1451    int numConfigs =  NELEM(gConfigs);
1452    uint32_t possibleMatch = (1<<numConfigs)-1;
1453    while(possibleMatch && *attrib_list != EGL_NONE) {
1454        numAttributes++;
1455        EGLint attr = *attrib_list++;
1456        EGLint val  = *attrib_list++;
1457        for (int i=0 ; possibleMatch && i<numConfigs ; i++) {
1458            if (!(possibleMatch & (1<<i)))
1459                continue;
1460            if (isAttributeMatching(i, attr, val) == 0) {
1461                possibleMatch &= ~(1<<i);
1462            }
1463        }
1464    }
1465
1466    // now, handle the attributes which have a useful default value
1467    for (size_t j=0 ; possibleMatch && j<NELEM(config_defaults) ; j++) {
1468        // see if this attribute was specified, if not, apply its
1469        // default value
1470        if (binarySearch<config_pair_t>(
1471                (config_pair_t const*)attrib_list,
1472                0, numAttributes-1,
1473                config_defaults[j].key) < 0)
1474        {
1475            for (int i=0 ; possibleMatch && i<numConfigs ; i++) {
1476                if (!(possibleMatch & (1<<i)))
1477                    continue;
1478                if (isAttributeMatching(i,
1479                        config_defaults[j].key,
1480                        config_defaults[j].value) == 0)
1481                {
1482                    possibleMatch &= ~(1<<i);
1483                }
1484            }
1485        }
1486    }
1487
1488    // return the configurations found
1489    int n=0;
1490    if (possibleMatch) {
1491        if (configs) {
1492            for (int i=0 ; config_size && i<numConfigs ; i++) {
1493                if (possibleMatch & (1<<i)) {
1494                    *configs++ = (EGLConfig)i;
1495                    config_size--;
1496                    n++;
1497                }
1498            }
1499        } else {
1500            for (int i=0 ; i<numConfigs ; i++) {
1501                if (possibleMatch & (1<<i)) {
1502                    n++;
1503                }
1504            }
1505        }
1506    }
1507    *num_config = n;
1508     return EGL_TRUE;
1509}
1510
1511EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
1512        EGLint attribute, EGLint *value)
1513{
1514    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1515        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1516
1517    return getConfigAttrib(dpy, config, attribute, value);
1518}
1519
1520// ----------------------------------------------------------------------------
1521// surfaces
1522// ----------------------------------------------------------------------------
1523
1524EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
1525                                    NativeWindowType window,
1526                                    const EGLint *attrib_list)
1527{
1528    return createWindowSurface(dpy, config, window, attrib_list);
1529}
1530
1531EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
1532                                    NativePixmapType pixmap,
1533                                    const EGLint *attrib_list)
1534{
1535    return createPixmapSurface(dpy, config, pixmap, attrib_list);
1536}
1537
1538EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config,
1539                                    const EGLint *attrib_list)
1540{
1541    return createPbufferSurface(dpy, config, attrib_list);
1542}
1543
1544EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface eglSurface)
1545{
1546    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1547        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1548    if (eglSurface != EGL_NO_SURFACE) {
1549        egl_surface_t* surface( static_cast<egl_surface_t*>(eglSurface) );
1550        if (!surface->isValid())
1551            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1552        if (surface->dpy != dpy)
1553            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1554        if (surface->ctx) {
1555            // FIXME: this surface is current check what the spec says
1556            surface->disconnect();
1557            surface->ctx = 0;
1558        }
1559        delete surface;
1560    }
1561    return EGL_TRUE;
1562}
1563
1564EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface eglSurface,
1565                            EGLint attribute, EGLint *value)
1566{
1567    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1568        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1569    egl_surface_t* surface = static_cast<egl_surface_t*>(eglSurface);
1570    if (!surface->isValid())
1571        return setError(EGL_BAD_SURFACE, EGL_FALSE);
1572    if (surface->dpy != dpy)
1573        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1574
1575    EGLBoolean ret = EGL_TRUE;
1576    switch (attribute) {
1577        case EGL_CONFIG_ID:
1578            ret = getConfigAttrib(dpy, surface->config, EGL_CONFIG_ID, value);
1579            break;
1580        case EGL_WIDTH:
1581            *value = surface->getWidth();
1582            break;
1583        case EGL_HEIGHT:
1584            *value = surface->getHeight();
1585            break;
1586        case EGL_LARGEST_PBUFFER:
1587            // not modified for a window or pixmap surface
1588            break;
1589        case EGL_TEXTURE_FORMAT:
1590            *value = EGL_NO_TEXTURE;
1591            break;
1592        case EGL_TEXTURE_TARGET:
1593            *value = EGL_NO_TEXTURE;
1594            break;
1595        case EGL_MIPMAP_TEXTURE:
1596            *value = EGL_FALSE;
1597            break;
1598        case EGL_MIPMAP_LEVEL:
1599            *value = 0;
1600            break;
1601        case EGL_RENDER_BUFFER:
1602            // TODO: return the real RENDER_BUFFER here
1603            *value = EGL_BACK_BUFFER;
1604            break;
1605        case EGL_HORIZONTAL_RESOLUTION:
1606            // pixel/mm * EGL_DISPLAY_SCALING
1607            *value = surface->getHorizontalResolution();
1608            break;
1609        case EGL_VERTICAL_RESOLUTION:
1610            // pixel/mm * EGL_DISPLAY_SCALING
1611            *value = surface->getVerticalResolution();
1612            break;
1613        case EGL_PIXEL_ASPECT_RATIO: {
1614            // w/h * EGL_DISPLAY_SCALING
1615            int wr = surface->getHorizontalResolution();
1616            int hr = surface->getVerticalResolution();
1617            *value = (wr * EGL_DISPLAY_SCALING) / hr;
1618        } break;
1619        case EGL_SWAP_BEHAVIOR:
1620            *value = surface->getSwapBehavior();
1621            break;
1622        default:
1623            ret = setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1624    }
1625    return ret;
1626}
1627
1628EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config,
1629                            EGLContext share_list, const EGLint *attrib_list)
1630{
1631    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1632        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1633
1634    ogles_context_t* gl = ogles_init(sizeof(egl_context_t));
1635    if (!gl) return setError(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
1636
1637    egl_context_t* c = static_cast<egl_context_t*>(gl->rasterizer.base);
1638    c->flags = egl_context_t::NEVER_CURRENT;
1639    c->dpy = dpy;
1640    c->config = config;
1641    c->read = 0;
1642    c->draw = 0;
1643    return (EGLContext)gl;
1644}
1645
1646EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
1647{
1648    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1649        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1650    egl_context_t* c = egl_context_t::context(ctx);
1651    if (c->flags & egl_context_t::IS_CURRENT)
1652        setGlThreadSpecific(0);
1653    ogles_uninit((ogles_context_t*)ctx);
1654    return EGL_TRUE;
1655}
1656
1657EGLBoolean eglMakeCurrent(  EGLDisplay dpy, EGLSurface draw,
1658                            EGLSurface read, EGLContext ctx)
1659{
1660    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1661        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1662    if (draw) {
1663        egl_surface_t* s = (egl_surface_t*)draw;
1664        if (!s->isValid())
1665            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1666        if (s->dpy != dpy)
1667            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1668        // TODO: check that draw is compatible with the context
1669    }
1670    if (read && read!=draw) {
1671        egl_surface_t* s = (egl_surface_t*)read;
1672        if (!s->isValid())
1673            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1674        if (s->dpy != dpy)
1675            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1676        // TODO: check that read is compatible with the context
1677    }
1678
1679    EGLContext current_ctx = EGL_NO_CONTEXT;
1680
1681    if ((read == EGL_NO_SURFACE && draw == EGL_NO_SURFACE) && (ctx != EGL_NO_CONTEXT))
1682        return setError(EGL_BAD_MATCH, EGL_FALSE);
1683
1684    if ((read != EGL_NO_SURFACE || draw != EGL_NO_SURFACE) && (ctx == EGL_NO_CONTEXT))
1685        return setError(EGL_BAD_MATCH, EGL_FALSE);
1686
1687    if (ctx == EGL_NO_CONTEXT) {
1688        // if we're detaching, we need the current context
1689        current_ctx = (EGLContext)getGlThreadSpecific();
1690    } else {
1691        egl_context_t* c = egl_context_t::context(ctx);
1692        egl_surface_t* d = (egl_surface_t*)draw;
1693        egl_surface_t* r = (egl_surface_t*)read;
1694        if ((d && d->ctx && d->ctx != ctx) ||
1695            (r && r->ctx && r->ctx != ctx)) {
1696            // one of the surface is bound to a context in another thread
1697            return setError(EGL_BAD_ACCESS, EGL_FALSE);
1698        }
1699    }
1700
1701    ogles_context_t* gl = (ogles_context_t*)ctx;
1702    if (makeCurrent(gl) == 0) {
1703        if (ctx) {
1704            egl_context_t* c = egl_context_t::context(ctx);
1705            egl_surface_t* d = (egl_surface_t*)draw;
1706            egl_surface_t* r = (egl_surface_t*)read;
1707
1708            if (c->draw) {
1709                egl_surface_t* s = reinterpret_cast<egl_surface_t*>(c->draw);
1710                s->disconnect();
1711            }
1712            if (c->read) {
1713                // FIXME: unlock/disconnect the read surface too
1714            }
1715
1716            c->draw = draw;
1717            c->read = read;
1718
1719            if (c->flags & egl_context_t::NEVER_CURRENT) {
1720                c->flags &= ~egl_context_t::NEVER_CURRENT;
1721                GLint w = 0;
1722                GLint h = 0;
1723                if (draw) {
1724                    w = d->getWidth();
1725                    h = d->getHeight();
1726                }
1727                ogles_surfaceport(gl, 0, 0);
1728                ogles_viewport(gl, 0, 0, w, h);
1729                ogles_scissor(gl, 0, 0, w, h);
1730            }
1731            if (d) {
1732                if (d->connect() == EGL_FALSE) {
1733                    return EGL_FALSE;
1734                }
1735                d->ctx = ctx;
1736                d->bindDrawSurface(gl);
1737            }
1738            if (r) {
1739                // FIXME: lock/connect the read surface too
1740                r->ctx = ctx;
1741                r->bindReadSurface(gl);
1742            }
1743        } else {
1744            // if surfaces were bound to the context bound to this thread
1745            // mark then as unbound.
1746            if (current_ctx) {
1747                egl_context_t* c = egl_context_t::context(current_ctx);
1748                egl_surface_t* d = (egl_surface_t*)c->draw;
1749                egl_surface_t* r = (egl_surface_t*)c->read;
1750                if (d) {
1751                    c->draw = 0;
1752                    d->ctx = EGL_NO_CONTEXT;
1753                    d->disconnect();
1754                }
1755                if (r) {
1756                    c->read = 0;
1757                    r->ctx = EGL_NO_CONTEXT;
1758                    // FIXME: unlock/disconnect the read surface too
1759                }
1760            }
1761        }
1762        return EGL_TRUE;
1763    }
1764    return setError(EGL_BAD_ACCESS, EGL_FALSE);
1765}
1766
1767EGLContext eglGetCurrentContext(void)
1768{
1769    // eglGetCurrentContext returns the current EGL rendering context,
1770    // as specified by eglMakeCurrent. If no context is current,
1771    // EGL_NO_CONTEXT is returned.
1772    return (EGLContext)getGlThreadSpecific();
1773}
1774
1775EGLSurface eglGetCurrentSurface(EGLint readdraw)
1776{
1777    // eglGetCurrentSurface returns the read or draw surface attached
1778    // to the current EGL rendering context, as specified by eglMakeCurrent.
1779    // If no context is current, EGL_NO_SURFACE is returned.
1780    EGLContext ctx = (EGLContext)getGlThreadSpecific();
1781    if (ctx == EGL_NO_CONTEXT) return EGL_NO_SURFACE;
1782    egl_context_t* c = egl_context_t::context(ctx);
1783    if (readdraw == EGL_READ) {
1784        return c->read;
1785    } else if (readdraw == EGL_DRAW) {
1786        return c->draw;
1787    }
1788    return setError(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
1789}
1790
1791EGLDisplay eglGetCurrentDisplay(void)
1792{
1793    // eglGetCurrentDisplay returns the current EGL display connection
1794    // for the current EGL rendering context, as specified by eglMakeCurrent.
1795    // If no context is current, EGL_NO_DISPLAY is returned.
1796    EGLContext ctx = (EGLContext)getGlThreadSpecific();
1797    if (ctx == EGL_NO_CONTEXT) return EGL_NO_DISPLAY;
1798    egl_context_t* c = egl_context_t::context(ctx);
1799    return c->dpy;
1800}
1801
1802EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx,
1803                            EGLint attribute, EGLint *value)
1804{
1805    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1806        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1807    egl_context_t* c = egl_context_t::context(ctx);
1808    switch (attribute) {
1809        case EGL_CONFIG_ID:
1810            // Returns the ID of the EGL frame buffer configuration with
1811            // respect to which the context was created
1812            return getConfigAttrib(dpy, c->config, EGL_CONFIG_ID, value);
1813    }
1814    return setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1815}
1816
1817EGLBoolean eglWaitGL(void)
1818{
1819    return EGL_TRUE;
1820}
1821
1822EGLBoolean eglWaitNative(EGLint engine)
1823{
1824    return EGL_TRUE;
1825}
1826
1827EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw)
1828{
1829    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1830        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1831
1832    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
1833    if (!d->isValid())
1834        return setError(EGL_BAD_SURFACE, EGL_FALSE);
1835    if (d->dpy != dpy)
1836        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1837
1838    // post the surface
1839    d->swapBuffers();
1840
1841    // if it's bound to a context, update the buffer
1842    if (d->ctx != EGL_NO_CONTEXT) {
1843        d->bindDrawSurface((ogles_context_t*)d->ctx);
1844        // if this surface is also the read surface of the context
1845        // it is bound to, make sure to update the read buffer as well.
1846        // The EGL spec is a little unclear about this.
1847        egl_context_t* c = egl_context_t::context(d->ctx);
1848        if (c->read == draw) {
1849            d->bindReadSurface((ogles_context_t*)d->ctx);
1850        }
1851    }
1852
1853    return EGL_TRUE;
1854}
1855
1856EGLBoolean eglCopyBuffers(  EGLDisplay dpy, EGLSurface surface,
1857                            NativePixmapType target)
1858{
1859    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1860        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1861    // TODO: eglCopyBuffers()
1862    return EGL_FALSE;
1863}
1864
1865EGLint eglGetError(void)
1866{
1867    return getError();
1868}
1869
1870const char* eglQueryString(EGLDisplay dpy, EGLint name)
1871{
1872    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1873        return setError(EGL_BAD_DISPLAY, (const char*)0);
1874
1875    switch (name) {
1876        case EGL_VENDOR:
1877            return gVendorString;
1878        case EGL_VERSION:
1879            return gVersionString;
1880        case EGL_EXTENSIONS:
1881            return gExtensionsString;
1882        case EGL_CLIENT_APIS:
1883            return gClientApiString;
1884    }
1885    return setError(EGL_BAD_PARAMETER, (const char *)0);
1886}
1887
1888// ----------------------------------------------------------------------------
1889// EGL 1.1
1890// ----------------------------------------------------------------------------
1891
1892EGLBoolean eglSurfaceAttrib(
1893        EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
1894{
1895    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1896        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1897    // TODO: eglSurfaceAttrib()
1898    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1899}
1900
1901EGLBoolean eglBindTexImage(
1902        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1903{
1904    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1905        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1906    // TODO: eglBindTexImage()
1907    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1908}
1909
1910EGLBoolean eglReleaseTexImage(
1911        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1912{
1913    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1914        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1915    // TODO: eglReleaseTexImage()
1916    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1917}
1918
1919EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
1920{
1921    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1922        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1923    // TODO: eglSwapInterval()
1924    return EGL_TRUE;
1925}
1926
1927// ----------------------------------------------------------------------------
1928// EGL 1.2
1929// ----------------------------------------------------------------------------
1930
1931EGLBoolean eglBindAPI(EGLenum api)
1932{
1933    if (api != EGL_OPENGL_ES_API)
1934        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1935    return EGL_TRUE;
1936}
1937
1938EGLenum eglQueryAPI(void)
1939{
1940    return EGL_OPENGL_ES_API;
1941}
1942
1943EGLBoolean eglWaitClient(void)
1944{
1945    glFinish();
1946    return EGL_TRUE;
1947}
1948
1949EGLBoolean eglReleaseThread(void)
1950{
1951    // TODO: eglReleaseThread()
1952    return EGL_TRUE;
1953}
1954
1955EGLSurface eglCreatePbufferFromClientBuffer(
1956          EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
1957          EGLConfig config, const EGLint *attrib_list)
1958{
1959    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1960        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1961    // TODO: eglCreatePbufferFromClientBuffer()
1962    return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
1963}
1964
1965// ----------------------------------------------------------------------------
1966// EGL_EGLEXT_VERSION 3
1967// ----------------------------------------------------------------------------
1968
1969void (*eglGetProcAddress (const char *procname))()
1970{
1971    extention_map_t const * const map = gExtentionMap;
1972    for (uint32_t i=0 ; i<NELEM(gExtentionMap) ; i++) {
1973        if (!strcmp(procname, map[i].name)) {
1974            return map[i].address;
1975        }
1976    }
1977    return NULL;
1978}
1979
1980EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
1981        const EGLint *attrib_list)
1982{
1983    EGLBoolean result = EGL_FALSE;
1984    return result;
1985}
1986
1987EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
1988{
1989    EGLBoolean result = EGL_FALSE;
1990    return result;
1991}
1992
1993EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
1994        EGLClientBuffer buffer, const EGLint *attrib_list)
1995{
1996    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
1997        return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
1998    }
1999    if (ctx != EGL_NO_CONTEXT) {
2000        return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
2001    }
2002    if (target != EGL_NATIVE_BUFFER_ANDROID) {
2003        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2004    }
2005
2006    ANativeWindowBuffer* native_buffer = (ANativeWindowBuffer*)buffer;
2007
2008    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
2009        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2010
2011    if (native_buffer->common.version != sizeof(ANativeWindowBuffer))
2012        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2013
2014    switch (native_buffer->format) {
2015        case HAL_PIXEL_FORMAT_RGBA_8888:
2016        case HAL_PIXEL_FORMAT_RGBX_8888:
2017        case HAL_PIXEL_FORMAT_RGB_888:
2018        case HAL_PIXEL_FORMAT_RGB_565:
2019        case HAL_PIXEL_FORMAT_BGRA_8888:
2020        case HAL_PIXEL_FORMAT_RGBA_5551:
2021        case HAL_PIXEL_FORMAT_RGBA_4444:
2022            break;
2023        default:
2024            return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2025    }
2026
2027    native_buffer->common.incRef(&native_buffer->common);
2028    return (EGLImageKHR)native_buffer;
2029}
2030
2031EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
2032{
2033    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
2034        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2035    }
2036
2037    ANativeWindowBuffer* native_buffer = (ANativeWindowBuffer*)img;
2038
2039    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
2040        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2041
2042    if (native_buffer->common.version != sizeof(ANativeWindowBuffer))
2043        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2044
2045    native_buffer->common.decRef(&native_buffer->common);
2046
2047    return EGL_TRUE;
2048}
2049
2050// ----------------------------------------------------------------------------
2051// ANDROID extensions
2052// ----------------------------------------------------------------------------
2053
2054EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
2055        EGLint left, EGLint top, EGLint width, EGLint height)
2056{
2057    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
2058        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2059
2060    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
2061    if (!d->isValid())
2062        return setError(EGL_BAD_SURFACE, EGL_FALSE);
2063    if (d->dpy != dpy)
2064        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2065
2066    // post the surface
2067    d->setSwapRectangle(left, top, width, height);
2068
2069    return EGL_TRUE;
2070}
2071