diff options
author | Steve Block <steveblock@google.com> | 2011-05-06 11:45:16 +0100 |
---|---|---|
committer | Steve Block <steveblock@google.com> | 2011-05-12 13:44:10 +0100 |
commit | cad810f21b803229eb11403f9209855525a25d57 (patch) | |
tree | 29a6fd0279be608e0fe9ffe9841f722f0f4e4269 /Source/WebCore/platform/graphics/opengl | |
parent | 121b0cf4517156d0ac5111caf9830c51b69bae8f (diff) | |
download | external_webkit-cad810f21b803229eb11403f9209855525a25d57.zip external_webkit-cad810f21b803229eb11403f9209855525a25d57.tar.gz external_webkit-cad810f21b803229eb11403f9209855525a25d57.tar.bz2 |
Merge WebKit at r75315: Initial merge by git.
Change-Id: I570314b346ce101c935ed22a626b48c2af266b84
Diffstat (limited to 'Source/WebCore/platform/graphics/opengl')
5 files changed, 2399 insertions, 0 deletions
diff --git a/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.cpp b/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.cpp new file mode 100644 index 0000000..4215d12 --- /dev/null +++ b/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(3D_CANVAS) + +#include "Extensions3DOpenGL.h" + +#include "GraphicsContext3D.h" +#include <wtf/Vector.h> + +#if PLATFORM(MAC) +#include <OpenGL/gl.h> +#endif + +namespace WebCore { + +Extensions3DOpenGL::Extensions3DOpenGL() + : m_initializedAvailableExtensions(false) +{ +} + +Extensions3DOpenGL::~Extensions3DOpenGL() +{ +} + +bool Extensions3DOpenGL::supports(const String& name) +{ + // Note on support for BGRA: + // + // For OpenGL ES2.0, requires checking for + // GL_EXT_texture_format_BGRA8888 and GL_EXT_read_format_bgra. + // For desktop GL, BGRA has been supported since OpenGL 1.2. + // + // However, note that the GL ES2 extension requires the + // internalFormat to glTexImage2D() be GL_BGRA, while desktop GL + // will not accept GL_BGRA (must be GL_RGBA), so this must be + // checked on each platform. Desktop GL offers neither + // GL_EXT_texture_format_BGRA8888 or GL_EXT_read_format_bgra, so + // treat them as unsupported here. + if (!m_initializedAvailableExtensions) { + String extensionsString(reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS))); + Vector<String> availableExtensions; + extensionsString.split(" ", availableExtensions); + for (size_t i = 0; i < availableExtensions.size(); ++i) + m_availableExtensions.add(availableExtensions[i]); + m_initializedAvailableExtensions = true; + } + + // GL_ANGLE_framebuffer_blit and GL_ANGLE_framebuffer_multisample are "fake". They are implemented using other + // extensions. In particular GL_EXT_framebuffer_blit and GL_EXT_framebuffer_multisample + if (name == "GL_ANGLE_framebuffer_blit") + return m_availableExtensions.contains("GL_EXT_framebuffer_blit"); + if (name == "GL_ANGLE_framebuffer_multisample") + return m_availableExtensions.contains("GL_EXT_framebuffer_multisample"); + + // If GL_ARB_texture_float is available then we report GL_OES_texture_float and + // GL_OES_texture_half_float as available. + if (name == "GL_OES_texture_float" || name == "GL_OES_texture_half_float") + return m_availableExtensions.contains("GL_ARB_texture_float"); + + return m_availableExtensions.contains(name); +} + +void Extensions3DOpenGL::ensureEnabled(const String& name) +{ + ASSERT_UNUSED(name, supports(name)); +} + +int Extensions3DOpenGL::getGraphicsResetStatusARB() +{ + return GraphicsContext3D::NO_ERROR; +} + +void Extensions3DOpenGL::blitFramebuffer(long srcX0, long srcY0, long srcX1, long srcY1, long dstX0, long dstY0, long dstX1, long dstY1, unsigned long mask, unsigned long filter) +{ + ::glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +void Extensions3DOpenGL::renderbufferStorageMultisample(unsigned long target, unsigned long samples, unsigned long internalformat, unsigned long width, unsigned long height) +{ + ::glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); +} + +} // namespace WebCore + +#endif // ENABLE(3D_CANVAS) diff --git a/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.h b/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.h new file mode 100644 index 0000000..59f8180 --- /dev/null +++ b/Source/WebCore/platform/graphics/opengl/Extensions3DOpenGL.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef Extensions3DOpenGL_h +#define Extensions3DOpenGL_h + +#include "Extensions3D.h" + +#include "GraphicsContext3D.h" +#include <wtf/HashSet.h> +#include <wtf/text/StringHash.h> + +namespace WebCore { + +class Extensions3DOpenGL : public Extensions3D { +public: + virtual ~Extensions3DOpenGL(); + + // Extensions3D methods. + virtual bool supports(const String&); + virtual void ensureEnabled(const String&); + virtual int getGraphicsResetStatusARB(); + virtual void blitFramebuffer(long srcX0, long srcY0, long srcX1, long srcY1, long dstX0, long dstY0, long dstX1, long dstY1, unsigned long mask, unsigned long filter); + virtual void renderbufferStorageMultisample(unsigned long target, unsigned long samples, unsigned long internalformat, unsigned long width, unsigned long height); + +private: + // This class only needs to be instantiated by GraphicsContext3D implementations. + friend class GraphicsContext3D; + Extensions3DOpenGL(); + + bool m_initializedAvailableExtensions; + HashSet<String> m_availableExtensions; +}; + +} // namespace WebCore + +#endif // Extensions3DOpenGL_h diff --git a/Source/WebCore/platform/graphics/opengl/GraphicsContext3DOpenGL.cpp b/Source/WebCore/platform/graphics/opengl/GraphicsContext3DOpenGL.cpp new file mode 100644 index 0000000..221ee11 --- /dev/null +++ b/Source/WebCore/platform/graphics/opengl/GraphicsContext3DOpenGL.cpp @@ -0,0 +1,1476 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(3D_CANVAS) + +#include "GraphicsContext3D.h" + +#include "ArrayBuffer.h" +#include "ArrayBufferView.h" +#include "WebGLObject.h" +#include "CanvasRenderingContext.h" +#include "Extensions3DOpenGL.h" +#include "Float32Array.h" +#include "GraphicsContext.h" +#include "HTMLCanvasElement.h" +#include "ImageBuffer.h" +#include "Int32Array.h" +#include "NotImplemented.h" +#include "Uint8Array.h" + +#if PLATFORM(MAC) +#include <OpenGL/gl.h> +#endif + +#include <wtf/UnusedParam.h> +#include <wtf/text/CString.h> + +namespace WebCore { + +void GraphicsContext3D::validateAttributes() +{ + const char* extensions = reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS)); + if (m_attrs.stencil) { + if (std::strstr(extensions, "GL_EXT_packed_depth_stencil")) { + if (!m_attrs.depth) + m_attrs.depth = true; + } else + m_attrs.stencil = false; + } + if (m_attrs.antialias) { + bool isValidVendor = true; + // Currently in Mac we only turn on antialias if vendor is NVIDIA. + const char* vendor = reinterpret_cast<const char*>(::glGetString(GL_VENDOR)); + if (!std::strstr(vendor, "NVIDIA")) + isValidVendor = false; + if (!isValidVendor || !std::strstr(extensions, "GL_EXT_framebuffer_multisample")) + m_attrs.antialias = false; + } + // FIXME: instead of enforcing premultipliedAlpha = true, implement the + // correct behavior when premultipliedAlpha = false is requested. + m_attrs.premultipliedAlpha = true; +} + +void GraphicsContext3D::paintRenderingResultsToCanvas(CanvasRenderingContext* context) +{ + HTMLCanvasElement* canvas = context->canvas(); + ImageBuffer* imageBuffer = canvas->buffer(); + + int rowBytes = m_currentWidth * 4; + int totalBytes = rowBytes * m_currentHeight; + + OwnArrayPtr<unsigned char> pixels(new unsigned char[totalBytes]); + if (!pixels) + return; + + makeContextCurrent(); + + bool mustRestoreFBO = false; + if (m_attrs.antialias) { + ::glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); + ::glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); + ::glBlitFramebufferEXT(0, 0, m_currentWidth, m_currentHeight, 0, 0, m_currentWidth, m_currentHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + mustRestoreFBO = true; + } else { + if (m_boundFBO != m_fbo) { + mustRestoreFBO = true; + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + } + } + + GLint packAlignment = 4; + bool mustRestorePackAlignment = false; + ::glGetIntegerv(GL_PACK_ALIGNMENT, &packAlignment); + if (packAlignment > 4) { + ::glPixelStorei(GL_PACK_ALIGNMENT, 4); + mustRestorePackAlignment = true; + } + + ::glReadPixels(0, 0, m_currentWidth, m_currentHeight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pixels.get()); + + if (mustRestorePackAlignment) + ::glPixelStorei(GL_PACK_ALIGNMENT, packAlignment); + + if (mustRestoreFBO) + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); + + paintToCanvas(pixels.get(), m_currentWidth, m_currentHeight, + canvas->width(), canvas->height(), imageBuffer->context()->platformContext()); +} + +void GraphicsContext3D::reshape(int width, int height) +{ + if (!m_contextObj) + return; + + if (width == m_currentWidth && height == m_currentHeight) + return; + + m_currentWidth = width; + m_currentHeight = height; + + makeContextCurrent(); + + GLuint internalColorFormat, colorFormat, internalDepthStencilFormat = 0; + if (m_attrs.alpha) { + internalColorFormat = GL_RGBA8; + colorFormat = GL_RGBA; + } else { + internalColorFormat = GL_RGB8; + colorFormat = GL_RGB; + } + if (m_attrs.stencil || m_attrs.depth) { + // We don't allow the logic where stencil is required and depth is not. + // See GraphicsContext3D constructor. + if (m_attrs.stencil && m_attrs.depth) + internalDepthStencilFormat = GL_DEPTH24_STENCIL8_EXT; + else + internalDepthStencilFormat = GL_DEPTH_COMPONENT; + } + + bool mustRestoreFBO = false; + + // resize multisample FBO + if (m_attrs.antialias) { + GLint maxSampleCount; + ::glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSampleCount); + GLint sampleCount = std::min(8, maxSampleCount); + if (sampleCount > maxSampleCount) + sampleCount = maxSampleCount; + if (m_boundFBO != m_multisampleFBO) { + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); + mustRestoreFBO = true; + } + ::glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleColorBuffer); + ::glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalColorFormat, width, height); + ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, m_multisampleColorBuffer); + if (m_attrs.stencil || m_attrs.depth) { + ::glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); + ::glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalDepthStencilFormat, width, height); + if (m_attrs.stencil) + ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); + if (m_attrs.depth) + ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); + } + ::glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); + if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) { + // FIXME: cleanup. + notImplemented(); + } + } + + // resize regular FBO + if (m_boundFBO != m_fbo) { + mustRestoreFBO = true; + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + } + ::glBindTexture(GL_TEXTURE_2D, m_texture); + ::glTexImage2D(GL_TEXTURE_2D, 0, internalColorFormat, width, height, 0, colorFormat, GL_UNSIGNED_BYTE, 0); + ::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_texture, 0); + ::glBindTexture(GL_TEXTURE_2D, 0); + if (!m_attrs.antialias && (m_attrs.stencil || m_attrs.depth)) { + ::glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthStencilBuffer); + ::glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internalDepthStencilFormat, width, height); + if (m_attrs.stencil) + ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer); + if (m_attrs.depth) + ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer); + ::glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); + } + if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) { + // FIXME: cleanup + notImplemented(); + } + + if (m_attrs.antialias) { + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); + if (m_boundFBO == m_multisampleFBO) + mustRestoreFBO = false; + } + + // Initialize renderbuffers to 0. + GLfloat clearColor[] = {0, 0, 0, 0}, clearDepth = 0; + GLint clearStencil = 0; + GLboolean colorMask[] = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}, depthMask = GL_TRUE; + GLuint stencilMask = 0xffffffff; + GLboolean isScissorEnabled = GL_FALSE; + GLboolean isDitherEnabled = GL_FALSE; + GLbitfield clearMask = GL_COLOR_BUFFER_BIT; + ::glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor); + ::glClearColor(0, 0, 0, 0); + ::glGetBooleanv(GL_COLOR_WRITEMASK, colorMask); + ::glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + if (m_attrs.depth) { + ::glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth); + ::glClearDepth(1); + ::glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); + ::glDepthMask(GL_TRUE); + clearMask |= GL_DEPTH_BUFFER_BIT; + } + if (m_attrs.stencil) { + ::glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &clearStencil); + ::glClearStencil(0); + ::glGetIntegerv(GL_STENCIL_WRITEMASK, reinterpret_cast<GLint*>(&stencilMask)); + ::glStencilMaskSeparate(GL_FRONT, 0xffffffff); + clearMask |= GL_STENCIL_BUFFER_BIT; + } + isScissorEnabled = ::glIsEnabled(GL_SCISSOR_TEST); + ::glDisable(GL_SCISSOR_TEST); + isDitherEnabled = ::glIsEnabled(GL_DITHER); + ::glDisable(GL_DITHER); + + ::glClear(clearMask); + + ::glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); + ::glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); + if (m_attrs.depth) { + ::glClearDepth(clearDepth); + ::glDepthMask(depthMask); + } + if (m_attrs.stencil) { + ::glClearStencil(clearStencil); + ::glStencilMaskSeparate(GL_FRONT, stencilMask); + } + if (isScissorEnabled) + ::glEnable(GL_SCISSOR_TEST); + else + ::glDisable(GL_SCISSOR_TEST); + if (isDitherEnabled) + ::glEnable(GL_DITHER); + else + ::glDisable(GL_DITHER); + + if (mustRestoreFBO) + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); + + ::glFlush(); +} + +IntSize GraphicsContext3D::getInternalFramebufferSize() +{ + return IntSize(m_currentWidth, m_currentHeight); +} + +void GraphicsContext3D::prepareTexture() +{ + makeContextCurrent(); + if (m_attrs.antialias) { + ::glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); + ::glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); + ::glBlitFramebufferEXT(0, 0, m_currentWidth, m_currentHeight, 0, 0, m_currentWidth, m_currentHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); + } + ::glFinish(); +} + +void GraphicsContext3D::activeTexture(GC3Denum texture) +{ + makeContextCurrent(); + ::glActiveTexture(texture); +} + +void GraphicsContext3D::attachShader(Platform3DObject program, Platform3DObject shader) +{ + ASSERT(program); + ASSERT(shader); + makeContextCurrent(); + ::glAttachShader(program, shader); +} + +void GraphicsContext3D::bindAttribLocation(Platform3DObject program, GC3Duint index, const String& name) +{ + ASSERT(program); + makeContextCurrent(); + ::glBindAttribLocation(program, index, name.utf8().data()); +} + +void GraphicsContext3D::bindBuffer(GC3Denum target, Platform3DObject buffer) +{ + makeContextCurrent(); + ::glBindBuffer(target, buffer); +} + + +void GraphicsContext3D::bindFramebuffer(GC3Denum target, Platform3DObject buffer) +{ + makeContextCurrent(); + GLuint fbo; + if (buffer) + fbo = buffer; + else + fbo = (m_attrs.antialias ? m_multisampleFBO : m_fbo); + if (fbo != m_boundFBO) { + ::glBindFramebufferEXT(target, fbo); + m_boundFBO = fbo; + } +} + +void GraphicsContext3D::bindRenderbuffer(GC3Denum target, Platform3DObject renderbuffer) +{ + makeContextCurrent(); + ::glBindRenderbufferEXT(target, renderbuffer); +} + + +void GraphicsContext3D::bindTexture(GC3Denum target, Platform3DObject texture) +{ + makeContextCurrent(); + ::glBindTexture(target, texture); +} + +void GraphicsContext3D::blendColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha) +{ + makeContextCurrent(); + ::glBlendColor(red, green, blue, alpha); +} + +void GraphicsContext3D::blendEquation(GC3Denum mode) +{ + makeContextCurrent(); + ::glBlendEquation(mode); +} + +void GraphicsContext3D::blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha) +{ + makeContextCurrent(); + ::glBlendEquationSeparate(modeRGB, modeAlpha); +} + + +void GraphicsContext3D::blendFunc(GC3Denum sfactor, GC3Denum dfactor) +{ + makeContextCurrent(); + ::glBlendFunc(sfactor, dfactor); +} + +void GraphicsContext3D::blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha) +{ + makeContextCurrent(); + ::glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); +} + +void GraphicsContext3D::bufferData(GC3Denum target, GC3Dsizeiptr size, GC3Denum usage) +{ + makeContextCurrent(); + ::glBufferData(target, size, 0, usage); +} + +void GraphicsContext3D::bufferData(GC3Denum target, GC3Dsizeiptr size, const void* data, GC3Denum usage) +{ + makeContextCurrent(); + ::glBufferData(target, size, data, usage); +} + +void GraphicsContext3D::bufferSubData(GC3Denum target, GC3Dintptr offset, GC3Dsizeiptr size, const void* data) +{ + makeContextCurrent(); + ::glBufferSubData(target, offset, size, data); +} + +GC3Denum GraphicsContext3D::checkFramebufferStatus(GC3Denum target) +{ + makeContextCurrent(); + return ::glCheckFramebufferStatusEXT(target); +} + +void GraphicsContext3D::clearColor(GC3Dclampf r, GC3Dclampf g, GC3Dclampf b, GC3Dclampf a) +{ + makeContextCurrent(); + ::glClearColor(r, g, b, a); +} + +void GraphicsContext3D::clear(GC3Dbitfield mask) +{ + makeContextCurrent(); + ::glClear(mask); +} + +void GraphicsContext3D::clearDepth(GC3Dclampf depth) +{ + makeContextCurrent(); + ::glClearDepth(depth); +} + +void GraphicsContext3D::clearStencil(GC3Dint s) +{ + makeContextCurrent(); + ::glClearStencil(s); +} + +void GraphicsContext3D::colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha) +{ + makeContextCurrent(); + ::glColorMask(red, green, blue, alpha); +} + +void GraphicsContext3D::compileShader(Platform3DObject shader) +{ + ASSERT(shader); + makeContextCurrent(); + + int GLshaderType; + ANGLEShaderType shaderType; + + glGetShaderiv(shader, SHADER_TYPE, &GLshaderType); + + if (GLshaderType == VERTEX_SHADER) + shaderType = SHADER_TYPE_VERTEX; + else if (GLshaderType == FRAGMENT_SHADER) + shaderType = SHADER_TYPE_FRAGMENT; + else + return; // Invalid shader type. + + HashMap<Platform3DObject, ShaderSourceEntry>::iterator result = m_shaderSourceMap.find(shader); + + if (result == m_shaderSourceMap.end()) + return; + + ShaderSourceEntry& entry = result->second; + + String translatedShaderSource; + String shaderInfoLog; + + bool isValid = m_compiler.validateShaderSource(entry.source.utf8().data(), shaderType, translatedShaderSource, shaderInfoLog); + + entry.log = shaderInfoLog; + entry.isValid = isValid; + + if (!isValid) + return; // Shader didn't validate, don't move forward with compiling translated source + + int translatedShaderLength = translatedShaderSource.length(); + + const CString& translatedShaderCString = translatedShaderSource.utf8(); + const char* translatedShaderPtr = translatedShaderCString.data(); + + ::glShaderSource(shader, 1, &translatedShaderPtr, &translatedShaderLength); + + ::glCompileShader(shader); + + int GLCompileSuccess; + + ::glGetShaderiv(shader, COMPILE_STATUS, &GLCompileSuccess); + + // ASSERT that ANGLE generated GLSL will be accepted by OpenGL + ASSERT(GLCompileSuccess == GL_TRUE); +} + +void GraphicsContext3D::copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border) +{ + makeContextCurrent(); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) { + ::glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); + ::glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); + ::glBlitFramebufferEXT(x, y, x + width, y + height, x, y, x + width, y + height, GL_COLOR_BUFFER_BIT, GL_LINEAR); + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + } + ::glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); +} + +void GraphicsContext3D::copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) +{ + makeContextCurrent(); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) { + ::glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); + ::glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); + ::glBlitFramebufferEXT(x, y, x + width, y + height, x, y, x + width, y + height, GL_COLOR_BUFFER_BIT, GL_LINEAR); + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + } + ::glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); +} + +void GraphicsContext3D::cullFace(GC3Denum mode) +{ + makeContextCurrent(); + ::glCullFace(mode); +} + +void GraphicsContext3D::depthFunc(GC3Denum func) +{ + makeContextCurrent(); + ::glDepthFunc(func); +} + +void GraphicsContext3D::depthMask(GC3Dboolean flag) +{ + makeContextCurrent(); + ::glDepthMask(flag); +} + +void GraphicsContext3D::depthRange(GC3Dclampf zNear, GC3Dclampf zFar) +{ + makeContextCurrent(); + ::glDepthRange(zNear, zFar); +} + +void GraphicsContext3D::detachShader(Platform3DObject program, Platform3DObject shader) +{ + ASSERT(program); + ASSERT(shader); + makeContextCurrent(); + ::glDetachShader(program, shader); +} + +void GraphicsContext3D::disable(GC3Denum cap) +{ + makeContextCurrent(); + ::glDisable(cap); +} + +void GraphicsContext3D::disableVertexAttribArray(GC3Duint index) +{ + makeContextCurrent(); + ::glDisableVertexAttribArray(index); +} + +void GraphicsContext3D::drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count) +{ + makeContextCurrent(); + ::glDrawArrays(mode, first, count); +} + +void GraphicsContext3D::drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset) +{ + makeContextCurrent(); + ::glDrawElements(mode, count, type, reinterpret_cast<GLvoid*>(static_cast<intptr_t>(offset))); +} + +void GraphicsContext3D::enable(GC3Denum cap) +{ + makeContextCurrent(); + ::glEnable(cap); +} + +void GraphicsContext3D::enableVertexAttribArray(GC3Duint index) +{ + makeContextCurrent(); + ::glEnableVertexAttribArray(index); +} + +void GraphicsContext3D::finish() +{ + makeContextCurrent(); + ::glFinish(); +} + +void GraphicsContext3D::flush() +{ + makeContextCurrent(); + ::glFlush(); +} + +void GraphicsContext3D::framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, Platform3DObject buffer) +{ + makeContextCurrent(); + ::glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, buffer); +} + +void GraphicsContext3D::framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, Platform3DObject texture, GC3Dint level) +{ + makeContextCurrent(); + ::glFramebufferTexture2DEXT(target, attachment, textarget, texture, level); +} + +void GraphicsContext3D::frontFace(GC3Denum mode) +{ + makeContextCurrent(); + ::glFrontFace(mode); +} + +void GraphicsContext3D::generateMipmap(GC3Denum target) +{ + makeContextCurrent(); + ::glGenerateMipmapEXT(target); +} + +bool GraphicsContext3D::getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo& info) +{ + if (!program) { + synthesizeGLError(INVALID_VALUE); + return false; + } + makeContextCurrent(); + GLint maxAttributeSize = 0; + ::glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttributeSize); + GLchar name[maxAttributeSize]; // GL_ACTIVE_ATTRIBUTE_MAX_LENGTH includes null termination + GLsizei nameLength = 0; + GLint size = 0; + GLenum type = 0; + ::glGetActiveAttrib(program, index, maxAttributeSize, &nameLength, &size, &type, name); + if (!nameLength) + return false; + info.name = String(name, nameLength); + info.type = type; + info.size = size; + return true; +} + +bool GraphicsContext3D::getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo& info) +{ + if (!program) { + synthesizeGLError(INVALID_VALUE); + return false; + } + makeContextCurrent(); + GLint maxUniformSize = 0; + ::glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformSize); + GLchar name[maxUniformSize]; // GL_ACTIVE_UNIFORM_MAX_LENGTH includes null termination + GLsizei nameLength = 0; + GLint size = 0; + GLenum type = 0; + ::glGetActiveUniform(program, index, maxUniformSize, &nameLength, &size, &type, name); + if (!nameLength) + return false; + info.name = String(name, nameLength); + info.type = type; + info.size = size; + return true; +} + +void GraphicsContext3D::getAttachedShaders(Platform3DObject program, GC3Dsizei maxCount, GC3Dsizei* count, Platform3DObject* shaders) +{ + if (!program) { + synthesizeGLError(INVALID_VALUE); + return; + } + makeContextCurrent(); + ::glGetAttachedShaders(program, maxCount, count, shaders); +} + +int GraphicsContext3D::getAttribLocation(Platform3DObject program, const String& name) +{ + if (!program) + return -1; + + makeContextCurrent(); + return ::glGetAttribLocation(program, name.utf8().data()); +} + +GraphicsContext3D::Attributes GraphicsContext3D::getContextAttributes() +{ + return m_attrs; +} + +GC3Denum GraphicsContext3D::getError() +{ + if (m_syntheticErrors.size() > 0) { + ListHashSet<GC3Denum>::iterator iter = m_syntheticErrors.begin(); + GC3Denum err = *iter; + m_syntheticErrors.remove(iter); + return err; + } + + makeContextCurrent(); + return ::glGetError(); +} + +String GraphicsContext3D::getString(GC3Denum name) +{ + makeContextCurrent(); + return String((const char*) ::glGetString(name)); +} + +void GraphicsContext3D::hint(GC3Denum target, GC3Denum mode) +{ + makeContextCurrent(); + ::glHint(target, mode); +} + +GC3Dboolean GraphicsContext3D::isBuffer(Platform3DObject buffer) +{ + if (!buffer) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsBuffer(buffer); +} + +GC3Dboolean GraphicsContext3D::isEnabled(GC3Denum cap) +{ + makeContextCurrent(); + return ::glIsEnabled(cap); +} + +GC3Dboolean GraphicsContext3D::isFramebuffer(Platform3DObject framebuffer) +{ + if (!framebuffer) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsFramebufferEXT(framebuffer); +} + +GC3Dboolean GraphicsContext3D::isProgram(Platform3DObject program) +{ + if (!program) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsProgram(program); +} + +GC3Dboolean GraphicsContext3D::isRenderbuffer(Platform3DObject renderbuffer) +{ + if (!renderbuffer) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsRenderbufferEXT(renderbuffer); +} + +GC3Dboolean GraphicsContext3D::isShader(Platform3DObject shader) +{ + if (!shader) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsShader(shader); +} + +GC3Dboolean GraphicsContext3D::isTexture(Platform3DObject texture) +{ + if (!texture) + return GL_FALSE; + + makeContextCurrent(); + return ::glIsTexture(texture); +} + +void GraphicsContext3D::lineWidth(GC3Dfloat width) +{ + makeContextCurrent(); + ::glLineWidth(width); +} + +void GraphicsContext3D::linkProgram(Platform3DObject program) +{ + ASSERT(program); + makeContextCurrent(); + ::glLinkProgram(program); +} + +void GraphicsContext3D::pixelStorei(GC3Denum pname, GC3Dint param) +{ + makeContextCurrent(); + ::glPixelStorei(pname, param); +} + +void GraphicsContext3D::polygonOffset(GC3Dfloat factor, GC3Dfloat units) +{ + makeContextCurrent(); + ::glPolygonOffset(factor, units); +} + +void GraphicsContext3D::readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, void* data) +{ + // FIXME: remove the two glFlush calls when the driver bug is fixed, i.e., + // all previous rendering calls should be done before reading pixels. + makeContextCurrent(); + ::glFlush(); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) { + ::glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); + ::glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); + ::glBlitFramebufferEXT(x, y, x + width, y + height, x, y, x + width, y + height, GL_COLOR_BUFFER_BIT, GL_LINEAR); + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + ::glFlush(); + } + ::glReadPixels(x, y, width, height, format, type, data); + if (m_attrs.antialias && m_boundFBO == m_multisampleFBO) + ::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); +} + +void GraphicsContext3D::releaseShaderCompiler() +{ + // FIXME: This is not implemented on desktop OpenGL. We need to have ifdefs for the different GL variants + makeContextCurrent(); + //::glReleaseShaderCompiler(); +} + +void GraphicsContext3D::renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height) +{ + makeContextCurrent(); + switch (internalformat) { + case DEPTH_STENCIL: + internalformat = GL_DEPTH24_STENCIL8_EXT; + break; + case DEPTH_COMPONENT16: + internalformat = GL_DEPTH_COMPONENT; + break; + case RGBA4: + case RGB5_A1: + internalformat = GL_RGBA; + break; + case RGB565: + internalformat = GL_RGB; + break; + } + ::glRenderbufferStorageEXT(target, internalformat, width, height); +} + +void GraphicsContext3D::sampleCoverage(GC3Dclampf value, GC3Dboolean invert) +{ + makeContextCurrent(); + ::glSampleCoverage(value, invert); +} + +void GraphicsContext3D::scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) +{ + makeContextCurrent(); + ::glScissor(x, y, width, height); +} + +void GraphicsContext3D::shaderSource(Platform3DObject shader, const String& string) +{ + ASSERT(shader); + + makeContextCurrent(); + + ShaderSourceEntry entry; + + entry.source = string; + + m_shaderSourceMap.set(shader, entry); +} + +void GraphicsContext3D::stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask) +{ + makeContextCurrent(); + ::glStencilFunc(func, ref, mask); +} + +void GraphicsContext3D::stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask) +{ + makeContextCurrent(); + ::glStencilFuncSeparate(face, func, ref, mask); +} + +void GraphicsContext3D::stencilMask(GC3Duint mask) +{ + makeContextCurrent(); + ::glStencilMask(mask); +} + +void GraphicsContext3D::stencilMaskSeparate(GC3Denum face, GC3Duint mask) +{ + makeContextCurrent(); + ::glStencilMaskSeparate(face, mask); +} + +void GraphicsContext3D::stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass) +{ + makeContextCurrent(); + ::glStencilOp(fail, zfail, zpass); +} + +void GraphicsContext3D::stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass) +{ + makeContextCurrent(); + ::glStencilOpSeparate(face, fail, zfail, zpass); +} + +void GraphicsContext3D::texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat value) +{ + makeContextCurrent(); + ::glTexParameterf(target, pname, value); +} + +void GraphicsContext3D::texParameteri(GC3Denum target, GC3Denum pname, GC3Dint value) +{ + makeContextCurrent(); + ::glTexParameteri(target, pname, value); +} + +void GraphicsContext3D::uniform1f(GC3Dint location, GC3Dfloat v0) +{ + makeContextCurrent(); + ::glUniform1f(location, v0); +} + +void GraphicsContext3D::uniform1fv(GC3Dint location, GC3Dfloat* array, GC3Dsizei size) +{ + makeContextCurrent(); + ::glUniform1fv(location, size, array); +} + +void GraphicsContext3D::uniform2f(GC3Dint location, GC3Dfloat v0, GC3Dfloat v1) +{ + makeContextCurrent(); + ::glUniform2f(location, v0, v1); +} + +void GraphicsContext3D::uniform2fv(GC3Dint location, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 2 + makeContextCurrent(); + ::glUniform2fv(location, size, array); +} + +void GraphicsContext3D::uniform3f(GC3Dint location, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2) +{ + makeContextCurrent(); + ::glUniform3f(location, v0, v1, v2); +} + +void GraphicsContext3D::uniform3fv(GC3Dint location, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 3 + makeContextCurrent(); + ::glUniform3fv(location, size, array); +} + +void GraphicsContext3D::uniform4f(GC3Dint location, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2, GC3Dfloat v3) +{ + makeContextCurrent(); + ::glUniform4f(location, v0, v1, v2, v3); +} + +void GraphicsContext3D::uniform4fv(GC3Dint location, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 4 + makeContextCurrent(); + ::glUniform4fv(location, size, array); +} + +void GraphicsContext3D::uniform1i(GC3Dint location, GC3Dint v0) +{ + makeContextCurrent(); + ::glUniform1i(location, v0); +} + +void GraphicsContext3D::uniform1iv(GC3Dint location, GC3Dint* array, GC3Dsizei size) +{ + makeContextCurrent(); + ::glUniform1iv(location, size, array); +} + +void GraphicsContext3D::uniform2i(GC3Dint location, GC3Dint v0, GC3Dint v1) +{ + makeContextCurrent(); + ::glUniform2i(location, v0, v1); +} + +void GraphicsContext3D::uniform2iv(GC3Dint location, GC3Dint* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 2 + makeContextCurrent(); + ::glUniform2iv(location, size, array); +} + +void GraphicsContext3D::uniform3i(GC3Dint location, GC3Dint v0, GC3Dint v1, GC3Dint v2) +{ + makeContextCurrent(); + ::glUniform3i(location, v0, v1, v2); +} + +void GraphicsContext3D::uniform3iv(GC3Dint location, GC3Dint* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 3 + makeContextCurrent(); + ::glUniform3iv(location, size, array); +} + +void GraphicsContext3D::uniform4i(GC3Dint location, GC3Dint v0, GC3Dint v1, GC3Dint v2, GC3Dint v3) +{ + makeContextCurrent(); + ::glUniform4i(location, v0, v1, v2, v3); +} + +void GraphicsContext3D::uniform4iv(GC3Dint location, GC3Dint* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 4 + makeContextCurrent(); + ::glUniform4iv(location, size, array); +} + +void GraphicsContext3D::uniformMatrix2fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 4 + makeContextCurrent(); + ::glUniformMatrix2fv(location, size, transpose, array); +} + +void GraphicsContext3D::uniformMatrix3fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 9 + makeContextCurrent(); + ::glUniformMatrix3fv(location, size, transpose, array); +} + +void GraphicsContext3D::uniformMatrix4fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* array, GC3Dsizei size) +{ + // FIXME: length needs to be a multiple of 16 + makeContextCurrent(); + ::glUniformMatrix4fv(location, size, transpose, array); +} + +void GraphicsContext3D::useProgram(Platform3DObject program) +{ + makeContextCurrent(); + ::glUseProgram(program); +} + +void GraphicsContext3D::validateProgram(Platform3DObject program) +{ + ASSERT(program); + + makeContextCurrent(); + ::glValidateProgram(program); +} + +void GraphicsContext3D::vertexAttrib1f(GC3Duint index, GC3Dfloat v0) +{ + makeContextCurrent(); + ::glVertexAttrib1f(index, v0); +} + +void GraphicsContext3D::vertexAttrib1fv(GC3Duint index, GC3Dfloat* array) +{ + makeContextCurrent(); + ::glVertexAttrib1fv(index, array); +} + +void GraphicsContext3D::vertexAttrib2f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1) +{ + makeContextCurrent(); + ::glVertexAttrib2f(index, v0, v1); +} + +void GraphicsContext3D::vertexAttrib2fv(GC3Duint index, GC3Dfloat* array) +{ + makeContextCurrent(); + ::glVertexAttrib2fv(index, array); +} + +void GraphicsContext3D::vertexAttrib3f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2) +{ + makeContextCurrent(); + ::glVertexAttrib3f(index, v0, v1, v2); +} + +void GraphicsContext3D::vertexAttrib3fv(GC3Duint index, GC3Dfloat* array) +{ + makeContextCurrent(); + ::glVertexAttrib3fv(index, array); +} + +void GraphicsContext3D::vertexAttrib4f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2, GC3Dfloat v3) +{ + makeContextCurrent(); + ::glVertexAttrib4f(index, v0, v1, v2, v3); +} + +void GraphicsContext3D::vertexAttrib4fv(GC3Duint index, GC3Dfloat* array) +{ + makeContextCurrent(); + ::glVertexAttrib4fv(index, array); +} + +void GraphicsContext3D::vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized, GC3Dsizei stride, GC3Dintptr offset) +{ + makeContextCurrent(); + ::glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<GLvoid*>(static_cast<intptr_t>(offset))); +} + +void GraphicsContext3D::viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) +{ + makeContextCurrent(); + ::glViewport(x, y, width, height); +} + +void GraphicsContext3D::getBooleanv(GC3Denum pname, GC3Dboolean* value) +{ + makeContextCurrent(); + ::glGetBooleanv(pname, value); +} + +void GraphicsContext3D::getBufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetBufferParameteriv(target, pname, value); +} + +void GraphicsContext3D::getFloatv(GC3Denum pname, GC3Dfloat* value) +{ + makeContextCurrent(); + ::glGetFloatv(pname, value); +} + +void GraphicsContext3D::getFramebufferAttachmentParameteriv(GC3Denum target, GC3Denum attachment, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + if (attachment == DEPTH_STENCIL_ATTACHMENT) + attachment = DEPTH_ATTACHMENT; // Or STENCIL_ATTACHMENT, either works. + ::glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, value); +} + +void GraphicsContext3D::getIntegerv(GC3Denum pname, GC3Dint* value) +{ + // Need to emulate MAX_FRAGMENT/VERTEX_UNIFORM_VECTORS and MAX_VARYING_VECTORS + // because desktop GL's corresponding queries return the number of components + // whereas GLES2 return the number of vectors (each vector has 4 components). + // Therefore, the value returned by desktop GL needs to be divided by 4. + makeContextCurrent(); + switch (pname) { + case MAX_FRAGMENT_UNIFORM_VECTORS: + ::glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, value); + *value /= 4; + break; + case MAX_VERTEX_UNIFORM_VECTORS: + ::glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, value); + *value /= 4; + break; + case MAX_VARYING_VECTORS: + ::glGetIntegerv(GL_MAX_VARYING_FLOATS, value); + *value /= 4; + break; + default: + ::glGetIntegerv(pname, value); + } +} + +void GraphicsContext3D::getProgramiv(Platform3DObject program, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetProgramiv(program, pname, value); +} + +String GraphicsContext3D::getProgramInfoLog(Platform3DObject program) +{ + ASSERT(program); + + makeContextCurrent(); + GLint length; + ::glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); + if (!length) + return ""; + + GLsizei size; + GLchar* info = (GLchar*) fastMalloc(length); + + ::glGetProgramInfoLog(program, length, &size, info); + String s(info); + fastFree(info); + return s; +} + +void GraphicsContext3D::getRenderbufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetRenderbufferParameterivEXT(target, pname, value); +} + +void GraphicsContext3D::getShaderiv(Platform3DObject shader, GC3Denum pname, GC3Dint* value) +{ + ASSERT(shader); + + makeContextCurrent(); + + HashMap<Platform3DObject, ShaderSourceEntry>::iterator result = m_shaderSourceMap.find(shader); + + switch (pname) { + case DELETE_STATUS: + case SHADER_TYPE: + // Let OpenGL handle these. + + ::glGetShaderiv(shader, pname, value); + break; + + case COMPILE_STATUS: + if (result == m_shaderSourceMap.end()) { + (*value) = static_cast<int>(false); + return; + } + + (*value) = static_cast<int>(result->second.isValid); + break; + + case INFO_LOG_LENGTH: + if (result == m_shaderSourceMap.end()) { + (*value) = 0; + return; + } + + (*value) = getShaderInfoLog(shader).length(); + break; + + case SHADER_SOURCE_LENGTH: + (*value) = getShaderSource(shader).length(); + break; + + default: + synthesizeGLError(INVALID_ENUM); + } +} + +String GraphicsContext3D::getShaderInfoLog(Platform3DObject shader) +{ + ASSERT(shader); + + makeContextCurrent(); + + HashMap<Platform3DObject, ShaderSourceEntry>::iterator result = m_shaderSourceMap.find(shader); + + if (result == m_shaderSourceMap.end()) + return ""; + + ShaderSourceEntry entry = result->second; + + if (entry.isValid) { + GLint length; + ::glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); + if (!length) + return ""; + + GLsizei size; + GLchar* info = (GLchar*) fastMalloc(length); + + ::glGetShaderInfoLog(shader, length, &size, info); + + String s(info); + fastFree(info); + return s; + } else + return entry.log; +} + +String GraphicsContext3D::getShaderSource(Platform3DObject shader) +{ + ASSERT(shader); + + makeContextCurrent(); + + HashMap<Platform3DObject, ShaderSourceEntry>::iterator result = m_shaderSourceMap.find(shader); + + if (result == m_shaderSourceMap.end()) + return ""; + + return result->second.source; +} + + +void GraphicsContext3D::getTexParameterfv(GC3Denum target, GC3Denum pname, GC3Dfloat* value) +{ + makeContextCurrent(); + ::glGetTexParameterfv(target, pname, value); +} + +void GraphicsContext3D::getTexParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetTexParameteriv(target, pname, value); +} + +void GraphicsContext3D::getUniformfv(Platform3DObject program, GC3Dint location, GC3Dfloat* value) +{ + makeContextCurrent(); + ::glGetUniformfv(program, location, value); +} + +void GraphicsContext3D::getUniformiv(Platform3DObject program, GC3Dint location, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetUniformiv(program, location, value); +} + +GC3Dint GraphicsContext3D::getUniformLocation(Platform3DObject program, const String& name) +{ + ASSERT(program); + + makeContextCurrent(); + return ::glGetUniformLocation(program, name.utf8().data()); +} + +void GraphicsContext3D::getVertexAttribfv(GC3Duint index, GC3Denum pname, GC3Dfloat* value) +{ + makeContextCurrent(); + ::glGetVertexAttribfv(index, pname, value); +} + +void GraphicsContext3D::getVertexAttribiv(GC3Duint index, GC3Denum pname, GC3Dint* value) +{ + makeContextCurrent(); + ::glGetVertexAttribiv(index, pname, value); +} + +GC3Dsizeiptr GraphicsContext3D::getVertexAttribOffset(GC3Duint index, GC3Denum pname) +{ + makeContextCurrent(); + + GLvoid* pointer = 0; + ::glGetVertexAttribPointerv(index, pname, &pointer); + return static_cast<GC3Dsizeiptr>(reinterpret_cast<intptr_t>(pointer)); +} + +bool GraphicsContext3D::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels) +{ + if (width && height && !pixels) { + synthesizeGLError(INVALID_VALUE); + return false; + } + makeContextCurrent(); + GC3Denum openGLInternalFormat = internalformat; + if (type == GL_FLOAT) { + if (format == GL_RGBA) + openGLInternalFormat = GL_RGBA32F_ARB; + else if (format == GL_RGB) + openGLInternalFormat = GL_RGB32F_ARB; + } + + ::glTexImage2D(target, level, openGLInternalFormat, width, height, border, format, type, pixels); + return true; +} + +void GraphicsContext3D::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoff, GC3Dint yoff, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels) +{ + makeContextCurrent(); + + // FIXME: we will need to deal with PixelStore params when dealing with image buffers that differ from the subimage size + ::glTexSubImage2D(target, level, xoff, yoff, width, height, format, type, pixels); +} + +Platform3DObject GraphicsContext3D::createBuffer() +{ + makeContextCurrent(); + GLuint o = 0; + glGenBuffers(1, &o); + return o; +} + +Platform3DObject GraphicsContext3D::createFramebuffer() +{ + makeContextCurrent(); + GLuint o = 0; + glGenFramebuffersEXT(1, &o); + return o; +} + +Platform3DObject GraphicsContext3D::createProgram() +{ + makeContextCurrent(); + return glCreateProgram(); +} + +Platform3DObject GraphicsContext3D::createRenderbuffer() +{ + makeContextCurrent(); + GLuint o = 0; + glGenRenderbuffersEXT(1, &o); + return o; +} + +Platform3DObject GraphicsContext3D::createShader(GC3Denum type) +{ + makeContextCurrent(); + return glCreateShader((type == FRAGMENT_SHADER) ? GL_FRAGMENT_SHADER : GL_VERTEX_SHADER); +} + +Platform3DObject GraphicsContext3D::createTexture() +{ + makeContextCurrent(); + GLuint o = 0; + glGenTextures(1, &o); + return o; +} + +void GraphicsContext3D::deleteBuffer(Platform3DObject buffer) +{ + makeContextCurrent(); + glDeleteBuffers(1, &buffer); +} + +void GraphicsContext3D::deleteFramebuffer(Platform3DObject framebuffer) +{ + makeContextCurrent(); + glDeleteFramebuffersEXT(1, &framebuffer); +} + +void GraphicsContext3D::deleteProgram(Platform3DObject program) +{ + makeContextCurrent(); + glDeleteProgram(program); +} + +void GraphicsContext3D::deleteRenderbuffer(Platform3DObject renderbuffer) +{ + makeContextCurrent(); + glDeleteRenderbuffersEXT(1, &renderbuffer); +} + +void GraphicsContext3D::deleteShader(Platform3DObject shader) +{ + makeContextCurrent(); + glDeleteShader(shader); +} + +void GraphicsContext3D::deleteTexture(Platform3DObject texture) +{ + makeContextCurrent(); + glDeleteTextures(1, &texture); +} + +uint32_t GraphicsContext3D::sizeInBytes(GC3Denum type) +{ + switch (type) { + case GL_BYTE: + return sizeof(GLbyte); + case GL_UNSIGNED_BYTE: + return sizeof(GLubyte); + case GL_SHORT: + return sizeof(GLshort); + case GL_UNSIGNED_SHORT: + return sizeof(GLushort); + case GL_INT: + return sizeof(GLint); + case GL_UNSIGNED_INT: + return sizeof(GLuint); + case GL_FLOAT: + return sizeof(GLfloat); + default: + return 0; + } +} + +void GraphicsContext3D::synthesizeGLError(GC3Denum error) +{ + m_syntheticErrors.add(error); +} + +Extensions3D* GraphicsContext3D::getExtensions() +{ + if (!m_extensions) + m_extensions = adoptPtr(new Extensions3DOpenGL); + return m_extensions.get(); +} + +} + +#endif // ENABLE(3D_CANVAS) diff --git a/Source/WebCore/platform/graphics/opengl/TextureMapperGL.cpp b/Source/WebCore/platform/graphics/opengl/TextureMapperGL.cpp new file mode 100644 index 0000000..03f9b7c --- /dev/null +++ b/Source/WebCore/platform/graphics/opengl/TextureMapperGL.cpp @@ -0,0 +1,663 @@ +/* + Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "TextureMapperGL.h" + +#include "GraphicsContext.h" +#include "HashMap.h" +#include "Image.h" +#include "PassRefPtr.h" +#include "RefCounted.h" +#include "Timer.h" + +#if defined(TEXMAP_OPENGL_ES_2) +#include <GLES2/gl2.h> +#elif OS(MAC_OS_X) +#include <AGL/agl.h> +#include <gl.h> +#else +#if OS(UNIX) +#include <GL/glx.h> +#endif +#include <GL/gl.h> +#endif + +#ifndef TEXMAP_OPENGL_ES2 +extern "C" { + void glUniform1f(GLint, GLfloat); + void glUniform1i(GLint, GLint); + void glVertexAttribPointer(GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid*); + void glUniform4f(GLint, GLfloat, GLfloat, GLfloat, GLfloat); + void glShaderSource(GLuint, GLsizei, const char**, const GLint*); + GLuint glCreateShader(GLenum); + void glShaderSource(GLuint, GLsizei, const char**, const GLint*); + void glCompileShader(GLuint); + void glDeleteShader(GLuint); + void glUniformMatrix4fv(GLint, GLsizei, GLboolean, const GLfloat*); + GLuint glCreateProgram(); + void glAttachShader(GLuint, GLuint); + void glLinkProgram(GLuint); + void glUseProgram(GLuint); + void glDisableVertexAttribArray(GLuint); + void glEnableVertexAttribArray(GLuint); + void glBindFramebuffer(GLenum target, GLuint framebuffer); + void glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers); + void glGenFramebuffers(GLsizei n, GLuint* framebuffers); + void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); + void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params); + void glBindBuffer(GLenum, GLuint); + void glDeleteBuffers(GLsizei, const GLuint*); + void glGenBuffers(GLsizei, GLuint*); + void glBufferData(GLenum, GLsizeiptr, const GLvoid*, GLenum); + void glBufferSubData(GLenum, GLsizeiptr, GLsizeiptr, const GLvoid*); + void glGetProgramInfoLog(GLuint program, GLsizei, GLsizei*, GLchar*); + +#if !OS(MAC_OS_X) + GLint glGetUniformLocation(GLuint, const GLchar*); + GLint glBindAttribLocation(GLuint, GLuint, const GLchar*); +#endif +} +#endif + +namespace WebCore { + +inline static void debugGLCommand(const char* command, int line) +{ + const GLenum err = glGetError(); + if (!err) + return; + WTFReportError(__FILE__, line, WTF_PRETTY_FUNCTION, "[TextureMapper GL] Command failed: %s (%x)\n", command, err); +} + +#define DEBUG_GL_COMMANDS + +#ifdef DEBUG_GL_COMMANDS +#define GL_CMD(x) {x, debugGLCommand(#x, __LINE__); } +#else +#define GL_CMD(x) x +#endif + +static const GLuint gInVertexAttributeIndex = 0; + +struct TextureMapperGLData { + static struct ShaderInfo { + enum ShaderProgramIndex { + SimpleProgram, + OpacityAndMaskProgram, + TargetProgram, + + ProgramCount + }; + + enum ShaderVariableIndex { + InMatrixVariable, + InSourceMatrixVariable, + InMaskMatrixVariable, + OpacityVariable, + SourceTextureVariable, + MaskTextureVariable, + + VariableCount + }; + + struct ProgramInfo { + GLuint id; + GLint vars[VariableCount]; + }; + + GLint getUniformLocation(ShaderProgramIndex prog, ShaderVariableIndex var, const char* name) + { + return programs[prog].vars[var] = glGetUniformLocation(programs[prog].id, name); + } + + void createShaderProgram(const char* vertexShaderSource, const char* fragmentShaderSource, ShaderProgramIndex index) + { + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + GL_CMD(glShaderSource(vertexShader, 1, &vertexShaderSource, 0)) + GL_CMD(glShaderSource(fragmentShader, 1, &fragmentShaderSource, 0)) + GLuint programID = glCreateProgram(); + GL_CMD(glCompileShader(vertexShader)) + GL_CMD(glCompileShader(fragmentShader)) + GL_CMD(glAttachShader(programID, vertexShader)) + GL_CMD(glAttachShader(programID, fragmentShader)) + GL_CMD(glBindAttribLocation(programID, gInVertexAttributeIndex, "InVertex")) + GL_CMD(glLinkProgram(programID)) + programs[index].id = programID; +#ifdef PRINT_PROGRAM_INFO_LOG + char infoLog[1024]; + int len; + GL_CMD(glGetProgramInfoLog(programID, 1024, &len, infoLog)); + LOG(Graphics, "Compiled program for texture mapper. Log: %s\n", infoLog); +#endif + } + + ProgramInfo programs[ProgramCount]; + + } shaderInfo; + + struct DirectlyCompositedImageRepository { + struct Entry { + GLuint texture; + int refCount; + }; + HashMap<NativeImagePtr, Entry> imageToTexture; + + GLuint findOrCreate(NativeImagePtr image, bool& found) + { + HashMap<NativeImagePtr, Entry>::iterator it = imageToTexture.find(image); + found = false; + if (it != imageToTexture.end()) { + it->second.refCount++; + found = true; + return it->second.texture; + } + Entry entry; + GL_CMD(glGenTextures(1, &entry.texture)); + entry.refCount = 1; + imageToTexture.add(image, entry); + return entry.texture; + } + + bool deref(NativeImagePtr image) + { + HashMap<NativeImagePtr, Entry>::iterator it = imageToTexture.find(image); + if (it != imageToTexture.end()) { + if (it->second.refCount < 2) { + imageToTexture.remove(it); + return false; + } + } + return true; + } + + DirectlyCompositedImageRepository() + { + } + + ~DirectlyCompositedImageRepository() + { + for (HashMap<NativeImagePtr, Entry>::iterator it = imageToTexture.begin(); it != imageToTexture.end(); ++it) { + GLuint texture = it->second.texture; + if (texture) + GL_CMD(glDeleteTextures(1, &texture)); + } + + } + } directlyCompositedImages; + + TextureMapperGLData() + : currentProgram(TextureMapperGLData::ShaderInfo::TargetProgram) + { } + + TransformationMatrix projectionMatrix; + int currentProgram; + +#if OS(MAC_OS_X) + AGLContext aglContext; +#elif OS(UNIX) + Drawable glxDrawable; + GLXContext glxContext; +#endif +}; + +TextureMapperGLData::ShaderInfo TextureMapperGLData::shaderInfo; + +class BitmapTextureGL : public BitmapTexture { +public: + virtual void destroy(); + virtual IntSize size() const; + virtual bool isValid() const; + virtual void reset(const IntSize&, bool opaque); + virtual PlatformGraphicsContext* beginPaint(const IntRect& dirtyRect); + virtual void endPaint(); + virtual void setContentsToImage(Image*); + ~BitmapTextureGL() { destroy(); } + +private: + GLuint m_id; + NativeImagePtr m_image; + FloatSize m_relativeSize; + bool m_opaque; + IntSize m_textureSize; + RefPtr<RGBA32PremultimpliedBuffer> m_buffer; + IntRect m_dirtyRect; + GLuint m_fbo; + IntSize m_actualSize; + bool m_surfaceNeedsReset; + TextureMapperGL* m_textureMapper; + BitmapTextureGL() + : m_id(0) + , m_image(0) + , m_opaque(false) + , m_fbo(0) + , m_surfaceNeedsReset(true) + , m_textureMapper(0) + { + } + + friend class TextureMapperGL; +}; + +#define TEXMAP_GET_SHADER_VAR_LOCATION(prog, var) \ + if (TextureMapperGLData::shaderInfo.getUniformLocation(TextureMapperGLData::shaderInfo.prog##Program, TextureMapperGLData::shaderInfo.var##Variable, #var) < 0) \ + LOG_ERROR("Couldn't find variable "#var" in program "#prog"\n"); + +#define TEXMAP_BUILD_SHADER(program) \ + TextureMapperGLData::shaderInfo.createShaderProgram(vertexShaderSource##program, fragmentShaderSource##program, TextureMapperGLData::shaderInfo.program##Program); + +TextureMapperGL::TextureMapperGL() + : m_data(new TextureMapperGLData) +{ + static bool shadersCompiled = false; + obtainCurrentContext(); + if (shadersCompiled) + return; + shadersCompiled = true; +#ifndef TEXMAP_OPENGL_ES2 +#define OES2_PRECISION_DEFINITIONS \ + "#define lowp\n#define highp\n" +#else +#define OES2_PRECISION_DEFINITIONS +#endif + + const char* fragmentShaderSourceOpacityAndMask = + OES2_PRECISION_DEFINITIONS +" uniform sampler2D SourceTexture, MaskTexture; \n" +" uniform lowp float Opacity; \n" +" varying highp vec2 OutTexCoordSource, OutTexCoordMask; \n" +" void main(void) \n" +" { \n" +" lowp vec4 color = texture2D(SourceTexture, OutTexCoordSource); \n" +" lowp vec4 maskColor = texture2D(MaskTexture, OutTexCoordMask); \n" +" lowp float o = Opacity * maskColor.a; \n" +" gl_FragColor = vec4(color.rgb * o, color.a * o); \n" +" } \n"; + + const char* vertexShaderSourceOpacityAndMask = + OES2_PRECISION_DEFINITIONS +" uniform mat4 InMatrix, InSourceMatrix, InMaskMatrix; \n" +" attribute vec4 InVertex; \n" +" varying highp vec2 OutTexCoordSource, OutTexCoordMask; \n" +" void main(void) \n" +" { \n" +" OutTexCoordSource = vec2(InSourceMatrix * InVertex); \n" +" OutTexCoordMask = vec2(InMaskMatrix * InVertex); \n" +" gl_Position = InMatrix * InVertex; \n" +" } \n"; + + const char* fragmentShaderSourceSimple = + OES2_PRECISION_DEFINITIONS +" uniform sampler2D SourceTexture; \n" +" uniform lowp float Opacity; \n" +" varying highp vec2 OutTexCoordSource; \n" +" void main(void) \n" +" { \n" +" lowp vec4 color = texture2D(SourceTexture, OutTexCoordSource); \n" +" gl_FragColor = vec4(color.rgb * Opacity, color.a * Opacity); \n" +" } \n"; + + const char* vertexShaderSourceSimple = + OES2_PRECISION_DEFINITIONS +" uniform mat4 InMatrix, InSourceMatrix; \n" +" attribute vec4 InVertex; \n" +" varying highp vec2 OutTexCoordSource; \n" +" void main(void) \n" +" { \n" +" OutTexCoordSource = vec2(InSourceMatrix * InVertex); \n" +" gl_Position = InMatrix * InVertex; \n" +" } \n"; + + const char* fragmentShaderSourceTarget = + OES2_PRECISION_DEFINITIONS +" uniform sampler2D SourceTexture; \n" +" uniform lowp float Opacity; \n" +" varying highp vec2 OutTexCoordSource; \n" +" void main(void) \n" +" { \n" +" lowp vec4 color = texture2D(SourceTexture, OutTexCoordSource); \n" +" gl_FragColor = vec4(color.bgr * Opacity, color.a * Opacity); \n" +" } \n"; + + const char* vertexShaderSourceTarget = vertexShaderSourceSimple; + + TEXMAP_BUILD_SHADER(Simple) + TEXMAP_BUILD_SHADER(OpacityAndMask) + TEXMAP_BUILD_SHADER(Target) + + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, InMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, InSourceMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, InMaskMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, SourceTexture) + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, MaskTexture) + TEXMAP_GET_SHADER_VAR_LOCATION(OpacityAndMask, Opacity) + + TEXMAP_GET_SHADER_VAR_LOCATION(Simple, InSourceMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(Simple, InMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(Simple, SourceTexture) + TEXMAP_GET_SHADER_VAR_LOCATION(Simple, Opacity) + + TEXMAP_GET_SHADER_VAR_LOCATION(Target, InSourceMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(Target, InMatrix) + TEXMAP_GET_SHADER_VAR_LOCATION(Target, SourceTexture) + TEXMAP_GET_SHADER_VAR_LOCATION(Target, Opacity) +} + +void TextureMapperGL::drawTexture(const BitmapTexture& texture, const IntRect& targetRect, const TransformationMatrix& modelViewMatrix, float opacity, const BitmapTexture* maskTexture) +{ + if (!texture.isValid()) + return; + + const BitmapTextureGL& textureGL = static_cast<const BitmapTextureGL&>(texture); + + TextureMapperGLData::ShaderInfo::ShaderProgramIndex program; + if (maskTexture) + program = TextureMapperGLData::ShaderInfo::OpacityAndMaskProgram; + else + program = TextureMapperGLData::ShaderInfo::SimpleProgram; + + const TextureMapperGLData::ShaderInfo::ProgramInfo& programInfo = data().shaderInfo.programs[program]; + if (data().currentProgram != program) { + GL_CMD(glUseProgram(programInfo.id)) + GL_CMD(glDisableVertexAttribArray(gInVertexAttributeIndex)) + data().currentProgram = program; + GL_CMD(glEnableVertexAttribArray(gInVertexAttributeIndex)) + } + + GL_CMD(glDisable(GL_DEPTH_TEST)) + GL_CMD(glDisable(GL_STENCIL_TEST)) + + GL_CMD(glActiveTexture(GL_TEXTURE0)) + GL_CMD(glBindTexture(GL_TEXTURE_2D, textureGL.m_id)) + GL_CMD(glBindBuffer(GL_ARRAY_BUFFER, 0)) + const GLfloat unitRect[] = {0, 0, 1, 0, 1, 1, 0, 1}; + GL_CMD(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, unitRect)) + + TransformationMatrix matrix = TransformationMatrix(data().projectionMatrix).multLeft(modelViewMatrix).multLeft(TransformationMatrix( + targetRect.width(), 0, 0, 0, + 0, targetRect.height(), 0, 0, + 0, 0, 1, 0, + targetRect.x(), targetRect.y(), 0, 1)); + + const GLfloat m4[] = { + matrix.m11(), matrix.m12(), matrix.m13(), matrix.m14(), + matrix.m21(), matrix.m22(), matrix.m23(), matrix.m24(), + matrix.m31(), matrix.m32(), matrix.m33(), matrix.m34(), + matrix.m41(), matrix.m42(), matrix.m43(), matrix.m44() + }; + const GLfloat m4src[] = {textureGL.m_relativeSize.width(), 0, 0, 0, + 0, textureGL.m_relativeSize.height(), 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1}; + GL_CMD(glUniformMatrix4fv(programInfo.vars[TextureMapperGLData::ShaderInfo::InMatrixVariable], 1, GL_FALSE, m4)) + GL_CMD(glUniformMatrix4fv(programInfo.vars[TextureMapperGLData::ShaderInfo::InSourceMatrixVariable], 1, GL_FALSE, m4src)) + GL_CMD(glUniform1i(programInfo.vars[TextureMapperGLData::ShaderInfo::SourceTextureVariable], 0)) + GL_CMD(glUniform1f(programInfo.vars[TextureMapperGLData::ShaderInfo::OpacityVariable], opacity)) + + if (maskTexture && maskTexture->isValid()) { + const BitmapTextureGL* maskTextureGL = static_cast<const BitmapTextureGL*>(maskTexture); + GL_CMD(glActiveTexture(GL_TEXTURE1)) + GL_CMD(glBindTexture(GL_TEXTURE_2D, maskTextureGL->m_id)) + const GLfloat m4mask[] = {maskTextureGL->m_relativeSize.width(), 0, 0, 0, + 0, maskTextureGL->m_relativeSize.height(), 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1}; + GL_CMD(glUniformMatrix4fv(programInfo.vars[TextureMapperGLData::ShaderInfo::InMaskMatrixVariable], 1, GL_FALSE, m4mask)); + GL_CMD(glUniform1i(programInfo.vars[TextureMapperGLData::ShaderInfo::MaskTextureVariable], 1)) + GL_CMD(glActiveTexture(GL_TEXTURE0)) + } + + if (textureGL.m_opaque && opacity > 0.99 && !maskTexture) + GL_CMD(glDisable(GL_BLEND)) + else { + GL_CMD(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)) + GL_CMD(glEnable(GL_BLEND)) + } + + GL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, 4)) +} + +const char* TextureMapperGL::type() const +{ + return "OpenGL"; +} + +void BitmapTextureGL::reset(const IntSize& newSize, bool opaque) +{ + BitmapTexture::reset(newSize, opaque); + m_image = 0; + IntSize newTextureSize = nextPowerOfTwo(newSize); + bool justCreated = false; + if (!m_id) { + GL_CMD(glGenTextures(1, &m_id)) + justCreated = true; + } + + if (justCreated || newTextureSize.width() > m_textureSize.width() || newTextureSize.height() > m_textureSize.height()) { + m_textureSize = newTextureSize; + GL_CMD(glBindTexture(GL_TEXTURE_2D, m_id)) + GL_CMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)) + GL_CMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)) + GL_CMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)) + GL_CMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)) + GL_CMD(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_textureSize.width(), m_textureSize.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)) + } + m_actualSize = newSize; + m_relativeSize = FloatSize(float(newSize.width()) / m_textureSize.width(), float(newSize.height()) / m_textureSize.height()); + m_opaque = opaque; + m_surfaceNeedsReset = true; +} + +PlatformGraphicsContext* BitmapTextureGL::beginPaint(const IntRect& dirtyRect) +{ + m_buffer = RGBA32PremultimpliedBuffer::create(); + m_dirtyRect = dirtyRect; + return m_buffer->beginPaint(dirtyRect, m_opaque); +} + +void BitmapTextureGL::endPaint() +{ + if (!m_buffer) + return; + m_buffer->endPaint(); + GL_CMD(glBindTexture(GL_TEXTURE_2D, m_id)) + GL_CMD(glTexSubImage2D(GL_TEXTURE_2D, 0, m_dirtyRect.x(), m_dirtyRect.y(), m_dirtyRect.width(), m_dirtyRect.height(), GL_RGBA, GL_UNSIGNED_BYTE, m_buffer->data())) + m_buffer.clear(); +} + +void BitmapTextureGL::setContentsToImage(Image* image) +{ + NativeImagePtr nativeImage = image ? image->nativeImageForCurrentFrame() : 0; + if (!image || !nativeImage) { + if (m_image) + destroy(); + return; + } + + if (nativeImage == m_image) + return; + bool found = false; + GLuint newTextureID = m_textureMapper->data().directlyCompositedImages.findOrCreate(nativeImage, found); + if (newTextureID != m_id) { + destroy(); + m_id = newTextureID; + reset(image->size(), false); + m_image = nativeImage; + if (!found) { + GraphicsContext context(beginPaint(IntRect(0, 0, m_textureSize.width(), m_textureSize.height()))); + context.drawImage(image, ColorSpaceDeviceRGB, IntPoint(0, 0), CompositeCopy); + endPaint(); + } + } +} + +void BitmapTextureGL::destroy() +{ + if (m_id && (!m_image || !m_textureMapper->data().directlyCompositedImages.deref(m_image))) + GL_CMD(glDeleteTextures(1, &m_id)) + if (m_fbo) + GL_CMD(glDeleteFramebuffers(1, &m_fbo)) + + m_fbo = 0; + m_id = 0; + m_textureSize = IntSize(); + m_relativeSize = FloatSize(1, 1); +} + +bool BitmapTextureGL::isValid() const +{ + return m_id; +} + +IntSize BitmapTextureGL::size() const +{ + return m_textureSize; +} + +static inline TransformationMatrix createProjectionMatrix(const IntSize& size, bool flip) +{ + return TransformationMatrix(2.0 / float(size.width()), 0, 0, 0, + 0, (flip ? -2.0 : 2.0) / float(size.height()), 0, 0, + 0, 0, -0.000001, 0, + -1, flip ? 1 : -1, 0, 1); +} + +TextureMapperGL::~TextureMapperGL() +{ + makeContextCurrent(); + delete m_data; +} + +bool TextureMapperGL::makeContextCurrent() +{ +#if OS(MAC_OS_X) + return aglSetCurrentContext(data().aglContext); +#elif OS(UNIX) + Display* display = XOpenDisplay(0); + if (!display) + return false; + return glXMakeCurrent(display, data().glxDrawable, data().glxContext); +#endif +} + +void TextureMapperGL::obtainCurrentContext() +{ +#if OS(MAC_OS_X) + data().aglContext = aglGetCurrentContext(); +#elif OS(UNIX) + data().glxDrawable = glXGetCurrentDrawable(); + data().glxContext = glXGetCurrentContext(); +#endif +} + +void TextureMapperGL::bindSurface(BitmapTexture *surfacePointer) +{ + BitmapTextureGL* surface = static_cast<BitmapTextureGL*>(surfacePointer); + + if (!surface) + return; + + TransformationMatrix matrix = createProjectionMatrix(surface->size(), false); + matrix.translate(-surface->offset().x(), -surface->offset().y()); + + if (surface->m_surfaceNeedsReset || !surface->m_fbo) { + if (!surface->m_fbo) + GL_CMD(glGenFramebuffers(1, &surface->m_fbo)) + GL_CMD(glBindFramebuffer(GL_FRAMEBUFFER, surface->m_fbo)) + GL_CMD(glBindTexture(GL_TEXTURE_2D, 0)) + GL_CMD(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, surface->m_id, 0)) + GL_CMD(glClearColor(0, 0, 0, 0)) + GL_CMD(glClear(GL_COLOR_BUFFER_BIT)) + surface->m_surfaceNeedsReset = false; + } else { + GL_CMD(glBindFramebuffer(GL_FRAMEBUFFER, surface->m_fbo)) + } + + GL_CMD(glViewport(0, 0, surface->size().width(), surface->size().height())) + data().projectionMatrix = matrix; +} + +void TextureMapperGL::setClip(const IntRect& rect) +{ + GL_CMD(glScissor(rect.x(), rect.y(), rect.width(), rect.height())) + GL_CMD(glEnable(GL_SCISSOR_TEST)) +} + + +void TextureMapperGL::paintToTarget(const BitmapTexture& aSurface, const IntSize& surfaceSize, const TransformationMatrix& transform, float opacity, const IntRect& visibleRect) +{ + const BitmapTextureGL& surface = static_cast<const BitmapTextureGL&>(aSurface); + + // Create the model-view-projection matrix to display on screen. + TransformationMatrix matrix = createProjectionMatrix(surfaceSize, true).multLeft(transform).multLeft( + TransformationMatrix( + surface.m_actualSize.width(), 0, 0, 0, + 0, surface.m_actualSize.height(), 0, 0, + 0, 0, 1, 0, + surface.offset().x(), surface.offset().y(), 0, 1) + ); + + const GLfloat m4[] = { + matrix.m11(), matrix.m12(), matrix.m13(), matrix.m14(), + matrix.m21(), matrix.m22(), matrix.m23(), matrix.m24(), + matrix.m31(), matrix.m32(), matrix.m33(), matrix.m34(), + matrix.m41(), matrix.m42(), matrix.m43(), matrix.m44() + }; + + const GLfloat m4src[] = {surface.m_relativeSize.width(), 0, 0, 0, + 0, surface.m_relativeSize.height(), 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1}; + + // We already blended the alpha in; the result is premultiplied. + GL_CMD(glUseProgram(data().shaderInfo.programs[TextureMapperGLData::ShaderInfo::TargetProgram].id)) + GL_CMD(glBindFramebuffer(GL_FRAMEBUFFER, 0)) + GL_CMD(glViewport(0, 0, surfaceSize.width(), surfaceSize.height())) + GL_CMD(glDisable(GL_STENCIL_TEST)) + const TextureMapperGLData::ShaderInfo::ProgramInfo& programInfo = data().shaderInfo.programs[TextureMapperGLData::ShaderInfo::TargetProgram]; + GL_CMD(glUniform1f(programInfo.vars[TextureMapperGLData::ShaderInfo::OpacityVariable], opacity)) + GL_CMD(glActiveTexture(GL_TEXTURE0)) + GL_CMD(glBindTexture(GL_TEXTURE_2D, surface.m_id)) + GL_CMD(glUniform1i(programInfo.vars[TextureMapperGLData::ShaderInfo::SourceTextureVariable], 0)) + GL_CMD(glEnableVertexAttribArray(gInVertexAttributeIndex)) + GL_CMD(glUniformMatrix4fv(programInfo.vars[TextureMapperGLData::ShaderInfo::InMatrixVariable], 1, GL_FALSE, m4)) + GL_CMD(glUniformMatrix4fv(programInfo.vars[TextureMapperGLData::ShaderInfo::InSourceMatrixVariable], 1, GL_FALSE, m4src)) + GL_CMD(glBindBuffer(GL_ARRAY_BUFFER, 0)) + const GLfloat unitRect[] = {0, 0, 1, 0, 1, 1, 0, 1}; + GL_CMD(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, unitRect)) + GL_CMD(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)) + GL_CMD(glEnable(GL_BLEND)) + setClip(visibleRect); + + GL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, 4)) + GL_CMD(glDisableVertexAttribArray(0)) + GL_CMD(glUseProgram(0)) + GL_CMD(glBindBuffer(GL_ARRAY_BUFFER, 0)) + data().currentProgram = TextureMapperGLData::ShaderInfo::TargetProgram; +} + +PassRefPtr<BitmapTexture> TextureMapperGL::createTexture() +{ + BitmapTextureGL* texture = new BitmapTextureGL(); + texture->m_textureMapper = this; + return adoptRef(texture); +} + +}; diff --git a/Source/WebCore/platform/graphics/opengl/TextureMapperGL.h b/Source/WebCore/platform/graphics/opengl/TextureMapperGL.h new file mode 100644 index 0000000..8035abf --- /dev/null +++ b/Source/WebCore/platform/graphics/opengl/TextureMapperGL.h @@ -0,0 +1,91 @@ +/* + Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. + */ + +#ifndef TextureMapperGL_h +#define TextureMapperGL_h + +#if USE(ACCELERATED_COMPOSITING) + +#include "FloatQuad.h" +#include "IntSize.h" +#include "TransformationMatrix.h" +#include "texmap/TextureMapper.h" + +namespace WebCore { + +class TextureMapperGLData; + +// An OpenGL-ES2 implementation of TextureMapper. +class TextureMapperGL : public TextureMapper { +public: + TextureMapperGL(); + virtual ~TextureMapperGL(); + + // reimps from TextureMapper + virtual void drawTexture(const BitmapTexture& texture, const IntRect&, const TransformationMatrix& transform, float opacity, const BitmapTexture* maskTexture); + virtual void bindSurface(BitmapTexture* surface); + virtual void setClip(const IntRect&); + virtual void paintToTarget(const BitmapTexture&, const IntSize&, const TransformationMatrix&, float opacity, const IntRect& visibleRect); + virtual bool allowSurfaceForRoot() const { return true; } + virtual PassRefPtr<BitmapTexture> createTexture(); + virtual const char* type() const; + void obtainCurrentContext(); + bool makeContextCurrent(); + static PassOwnPtr<TextureMapperGL> create() + { + return new TextureMapperGL; + } + +private: + inline TextureMapperGLData& data() { return *m_data; } + TextureMapperGLData* m_data; + friend class BitmapTextureGL; +}; + +// An offscreen buffer to be rendered by software. +class RGBA32PremultimpliedBuffer : public RefCounted<RGBA32PremultimpliedBuffer> { +public: + virtual ~RGBA32PremultimpliedBuffer() {} + virtual PlatformGraphicsContext* beginPaint(const IntRect& dirtyRect, bool opaque) = 0; + virtual void endPaint() = 0; + virtual const void* data() const = 0; + static PassRefPtr<RGBA32PremultimpliedBuffer> create(); +}; + +static inline int nextPowerOfTwo(int num) +{ + for (int i = 0x10000000; i > 0; i >>= 1) { + if (num == i) + return num; + if (num & i) + return (i << 1); + } + return 1; +} + +static inline IntSize nextPowerOfTwo(const IntSize& size) +{ + return IntSize(nextPowerOfTwo(size.width()), nextPowerOfTwo(size.height())); +} + +}; + +#endif + +#endif |