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