code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexDataManager.cpp: Defines the IndexDataManager, a class that
// runs the Buffer translation process for index buffers.
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
IndexDataManager::IndexDataManager(Renderer *renderer) : mRenderer(renderer)
{
mStreamingBufferShort = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferShort->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
{
delete mStreamingBufferShort;
mStreamingBufferShort = NULL;
}
mStreamingBufferInt = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferInt->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
}
if (!mStreamingBufferShort)
{
// Make sure both buffers are deleted.
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
ERR("Failed to allocate the streaming index buffer(s).");
}
mCountingBuffer = NULL;
}
IndexDataManager::~IndexDataManager()
{
delete mStreamingBufferShort;
delete mStreamingBufferInt;
delete mCountingBuffer;
}
static unsigned int indexTypeSize(GLenum type)
{
switch (type)
{
case GL_UNSIGNED_INT: return sizeof(GLuint);
case GL_UNSIGNED_SHORT: return sizeof(GLushort);
case GL_UNSIGNED_BYTE: return sizeof(GLubyte);
default: UNREACHABLE(); return sizeof(GLushort);
}
}
static void convertIndices(GLenum type, const void *input, GLsizei count, void *output)
{
if (type == GL_UNSIGNED_BYTE)
{
const GLubyte *in = static_cast<const GLubyte*>(input);
GLushort *out = static_cast<GLushort*>(output);
for (GLsizei i = 0; i < count; i++)
{
out[i] = in[i];
}
}
else if (type == GL_UNSIGNED_INT)
{
memcpy(output, input, count * sizeof(GLuint));
}
else if (type == GL_UNSIGNED_SHORT)
{
memcpy(output, input, count * sizeof(GLushort));
}
else UNREACHABLE();
}
template <class IndexType>
static void computeRange(const IndexType *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
*minIndex = indices[0];
*maxIndex = indices[0];
for (GLsizei i = 0; i < count; i++)
{
if (*minIndex > indices[i]) *minIndex = indices[i];
if (*maxIndex < indices[i]) *maxIndex = indices[i];
}
}
static void computeRange(GLenum type, const GLvoid *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
if (type == GL_UNSIGNED_BYTE)
{
computeRange(static_cast<const GLubyte*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_INT)
{
computeRange(static_cast<const GLuint*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_SHORT)
{
computeRange(static_cast<const GLushort*>(indices), count, minIndex, maxIndex);
}
else UNREACHABLE();
}
GLenum IndexDataManager::prepareIndexData(GLenum type, GLsizei count, gl::Buffer *buffer, const GLvoid *indices, TranslatedIndexData *translated)
{
if (!mStreamingBufferShort)
{
return GL_OUT_OF_MEMORY;
}
GLenum destinationIndexType = (type == GL_UNSIGNED_INT) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
intptr_t offset = reinterpret_cast<intptr_t>(indices);
bool alignedOffset = false;
BufferStorage *storage = NULL;
if (buffer != NULL)
{
storage = buffer->getStorage();
switch (type)
{
case GL_UNSIGNED_BYTE: alignedOffset = (offset % sizeof(GLubyte) == 0); break;
case GL_UNSIGNED_SHORT: alignedOffset = (offset % sizeof(GLushort) == 0); break;
case GL_UNSIGNED_INT: alignedOffset = (offset % sizeof(GLuint) == 0); break;
default: UNREACHABLE(); alignedOffset = false;
}
if (indexTypeSize(type) * count + offset > storage->getSize())
{
return GL_INVALID_OPERATION;
}
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
StreamingIndexBufferInterface *streamingBuffer = (type == GL_UNSIGNED_INT) ? mStreamingBufferInt : mStreamingBufferShort;
StaticIndexBufferInterface *staticBuffer = buffer ? buffer->getStaticIndexBuffer() : NULL;
IndexBufferInterface *indexBuffer = streamingBuffer;
bool directStorage = alignedOffset && storage && storage->supportsDirectBinding() &&
destinationIndexType == type;
UINT streamOffset = 0;
if (directStorage)
{
indexBuffer = streamingBuffer;
streamOffset = offset;
storage->markBufferUsage();
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
}
else if (staticBuffer && staticBuffer->getBufferSize() != 0 && staticBuffer->getIndexType() == type && alignedOffset)
{
indexBuffer = staticBuffer;
streamOffset = staticBuffer->lookupRange(offset, count, &translated->minIndex, &translated->maxIndex);
if (streamOffset == -1)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
else
{
int convertCount = count;
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0 && alignedOffset)
{
indexBuffer = staticBuffer;
convertCount = storage->getSize() / indexTypeSize(type);
}
else
{
buffer->invalidateStaticData();
staticBuffer = NULL;
}
}
if (!indexBuffer)
{
ERR("No valid index buffer.");
return GL_INVALID_OPERATION;
}
unsigned int bufferSizeRequired = convertCount * indexTypeSize(destinationIndexType);
indexBuffer->reserveBufferSpace(bufferSizeRequired, type);
void* output = NULL;
streamOffset = indexBuffer->mapBuffer(bufferSizeRequired, &output);
if (streamOffset == -1 || output == NULL)
{
ERR("Failed to map index buffer.");
return GL_OUT_OF_MEMORY;
}
convertIndices(type, staticBuffer ? storage->getData() : indices, convertCount, output);
if (!indexBuffer->unmapBuffer())
{
ERR("Failed to unmap index buffer.");
return GL_OUT_OF_MEMORY;
}
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
if (staticBuffer)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
translated->storage = directStorage ? storage : NULL;
translated->indexBuffer = indexBuffer->getIndexBuffer();
translated->serial = directStorage ? storage->getSerial() : indexBuffer->getSerial();
translated->startIndex = streamOffset / indexTypeSize(destinationIndexType);
translated->startOffset = streamOffset;
if (buffer)
{
buffer->promoteStaticUsage(count * indexTypeSize(type));
}
return GL_NO_ERROR;
}
StaticIndexBufferInterface *IndexDataManager::getCountingIndices(GLsizei count)
{
if (count <= 65536) // 16-bit indices
{
const unsigned int spaceNeeded = count * sizeof(unsigned short);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else if (mStreamingBufferInt) // 32-bit indices supported
{
const unsigned int spaceNeeded = count * sizeof(unsigned int);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else
{
return NULL;
}
return mCountingBuffer;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/IndexDataManager.cpp | C++ | bsd | 10,038 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
sampler2D tex : s0;
uniform float4 mode : c0;
// Passthrough Pixel Shader
// Outputs texture 0 sampled at texcoord 0.
float4 passthroughps(float4 texcoord : TEXCOORD0) : COLOR
{
return tex2D(tex, texcoord.xy);
};
// Luminance Conversion Pixel Shader
// Outputs sample(tex0, tc0).rrra.
// For LA output (pass A) set C0.X = 1, C0.Y = 0.
// For L output (A = 1) set C0.X = 0, C0.Y = 1.
float4 luminanceps(float4 texcoord : TEXCOORD0) : COLOR
{
float4 tmp = tex2D(tex, texcoord.xy);
tmp.w = tmp.w * mode.x + mode.y;
return tmp.xxxw;
};
// RGB/A Component Mask Pixel Shader
// Outputs sample(tex0, tc0) with options to force RGB = 0 and/or A = 1.
// To force RGB = 0, set C0.X = 0, otherwise C0.X = 1.
// To force A = 1, set C0.Z = 0, C0.W = 1, otherwise C0.Z = 1, C0.W = 0.
float4 componentmaskps(float4 texcoord : TEXCOORD0) : COLOR
{
float4 tmp = tex2D(tex, texcoord.xy);
tmp.xyz = tmp.xyz * mode.x;
tmp.w = tmp.w * mode.z + mode.w;
return tmp;
};
| 010smithzhang-ddd | src/libGLESv2/renderer/shaders/Blit.ps | PostScript | bsd | 1,139 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
struct VS_OUTPUT
{
float4 position : POSITION;
float4 texcoord : TEXCOORD0;
};
uniform float4 halfPixelSize : c0;
// Standard Vertex Shader
// Input 0 is the homogenous position.
// Outputs the homogenous position as-is.
// Outputs a tex coord with (0,0) in the upper-left corner of the screen and (1,1) in the bottom right.
// C0.X must be negative half-pixel width, C0.Y must be half-pixel height. C0.ZW must be 0.
VS_OUTPUT standardvs(in float4 position : POSITION)
{
VS_OUTPUT Out;
Out.position = position + halfPixelSize;
Out.texcoord = position * float4(0.5, -0.5, 1.0, 1.0) + float4(0.5, 0.5, 0, 0);
return Out;
};
// Flip Y Vertex Shader
// Input 0 is the homogenous position.
// Outputs the homogenous position as-is.
// Outputs a tex coord with (0,1) in the upper-left corner of the screen and (1,0) in the bottom right.
// C0.XY must be the half-pixel width and height. C0.ZW must be 0.
VS_OUTPUT flipyvs(in float4 position : POSITION)
{
VS_OUTPUT Out;
Out.position = position + halfPixelSize;
Out.texcoord = position * float4(0.5, 0.5, 1.0, 1.0) + float4(0.5, 0.5, 0, 0);
return Out;
};
| 010smithzhang-ddd | src/libGLESv2/renderer/shaders/Blit.vs | GLSL | bsd | 1,327 |
void VS_Clear( in float3 inPosition : POSITION, in float4 inColor : COLOR,
out float4 outPosition : SV_POSITION, out float4 outColor : COLOR)
{
outPosition = float4(inPosition, 1.0f);
outColor = inColor;
}
// Assume we are in SM4+, which has 8 color outputs
struct PS_OutputMultiple
{
float4 color0 : SV_TARGET0;
float4 color1 : SV_TARGET1;
float4 color2 : SV_TARGET2;
float4 color3 : SV_TARGET3;
float4 color4 : SV_TARGET4;
float4 color5 : SV_TARGET5;
float4 color6 : SV_TARGET6;
float4 color7 : SV_TARGET7;
};
PS_OutputMultiple PS_ClearMultiple(in float4 inPosition : SV_POSITION, in float4 inColor : COLOR)
{
PS_OutputMultiple outColor;
outColor.color0 = inColor;
outColor.color1 = inColor;
outColor.color2 = inColor;
outColor.color3 = inColor;
outColor.color4 = inColor;
outColor.color5 = inColor;
outColor.color6 = inColor;
outColor.color7 = inColor;
return outColor;
}
float4 PS_ClearSingle(in float4 inPosition : SV_Position, in float4 inColor : COLOR) : SV_Target0
{
return inColor;
}
| 010smithzhang-ddd | src/libGLESv2/renderer/shaders/Clear11.hlsl | HLSL | bsd | 1,043 |
Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);
void VS_Passthrough( in float2 inPosition : POSITION, in float2 inTexCoord : TEXCOORD0,
out float4 outPosition : SV_POSITION, out float2 outTexCoord : TEXCOORD0)
{
outPosition = float4(inPosition, 0.0f, 1.0f);
outTexCoord = inTexCoord;
}
float4 PS_PassthroughRGBA(in float4 inPosition : SV_POSITION, in float2 inTexCoord : TEXCOORD0) : SV_TARGET0
{
return Texture.Sample(Sampler, inTexCoord).rgba;
}
float4 PS_PassthroughRGB(in float4 inPosition : SV_POSITION, in float2 inTexCoord : TEXCOORD0) : SV_TARGET0
{
return float4(Texture.Sample(Sampler, inTexCoord).rgb, 1.0f);
}
float4 PS_PassthroughLum(in float4 inPosition : SV_POSITION, in float2 inTexCoord : TEXCOORD0) : SV_TARGET0
{
return float4(Texture.Sample(Sampler, inTexCoord).rrr, 1.0f);
}
float4 PS_PassthroughLumAlpha(in float4 inPosition : SV_POSITION, in float2 inTexCoord : TEXCOORD0) : SV_TARGET0
{
return Texture.Sample(Sampler, inTexCoord).rrra;
}
| 010smithzhang-ddd | src/libGLESv2/renderer/shaders/Passthrough11.hlsl | HLSL | bsd | 1,040 |
@ECHO OFF
REM
REM Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
REM Use of this source code is governed by a BSD-style license that can be
REM found in the LICENSE file.
REM
PATH %PATH%;%DXSDK_DIR%\Utilities\bin\x86
fxc /E standardvs /T vs_2_0 /Fh compiled/standardvs.h Blit.vs
fxc /E flipyvs /T vs_2_0 /Fh compiled/flipyvs.h Blit.vs
fxc /E passthroughps /T ps_2_0 /Fh compiled/passthroughps.h Blit.ps
fxc /E luminanceps /T ps_2_0 /Fh compiled/luminanceps.h Blit.ps
fxc /E componentmaskps /T ps_2_0 /Fh compiled/componentmaskps.h Blit.ps
fxc /E VS_Passthrough /T vs_4_0 /Fh compiled/passthrough11vs.h Passthrough11.hlsl
fxc /E PS_PassthroughRGBA /T ps_4_0 /Fh compiled/passthroughrgba11ps.h Passthrough11.hlsl
fxc /E PS_PassthroughRGB /T ps_4_0 /Fh compiled/passthroughrgb11ps.h Passthrough11.hlsl
fxc /E PS_PassthroughLum /T ps_4_0 /Fh compiled/passthroughlum11ps.h Passthrough11.hlsl
fxc /E PS_PassthroughLumAlpha /T ps_4_0 /Fh compiled/passthroughlumalpha11ps.h Passthrough11.hlsl
fxc /E VS_Clear /T vs_4_0 /Fh compiled/clear11vs.h Clear11.hlsl
fxc /E PS_ClearSingle /T ps_4_0 /Fh compiled/clearsingle11ps.h Clear11.hlsl
fxc /E PS_ClearMultiple /T ps_4_0 /Fh compiled/clearmultiple11ps.h Clear11.hlsl
| 010smithzhang-ddd | src/libGLESv2/renderer/shaders/generate_shaders.bat | Batchfile | bsd | 1,253 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexBuffer.cpp: Defines the abstract IndexBuffer class and IndexBufferInterface
// class with derivations, classes that perform graphics API agnostic index buffer operations.
#include "libGLESv2/renderer/IndexBuffer.h"
#include "libGLESv2/renderer/Renderer.h"
namespace rx
{
unsigned int IndexBuffer::mNextSerial = 1;
IndexBuffer::IndexBuffer()
{
updateSerial();
}
IndexBuffer::~IndexBuffer()
{
}
unsigned int IndexBuffer::getSerial() const
{
return mSerial;
}
void IndexBuffer::updateSerial()
{
mSerial = mNextSerial++;
}
IndexBufferInterface::IndexBufferInterface(Renderer *renderer, bool dynamic) : mRenderer(renderer)
{
mIndexBuffer = renderer->createIndexBuffer();
mDynamic = dynamic;
mWritePosition = 0;
}
IndexBufferInterface::~IndexBufferInterface()
{
if (mIndexBuffer)
{
delete mIndexBuffer;
}
}
GLenum IndexBufferInterface::getIndexType() const
{
return mIndexBuffer->getIndexType();
}
unsigned int IndexBufferInterface::getBufferSize() const
{
return mIndexBuffer->getBufferSize();
}
unsigned int IndexBufferInterface::getSerial() const
{
return mIndexBuffer->getSerial();
}
int IndexBufferInterface::mapBuffer(unsigned int size, void** outMappedMemory)
{
if (!mIndexBuffer->mapBuffer(mWritePosition, size, outMappedMemory))
{
*outMappedMemory = NULL;
return -1;
}
int oldWritePos = static_cast<int>(mWritePosition);
mWritePosition += size;
return oldWritePos;
}
bool IndexBufferInterface::unmapBuffer()
{
return mIndexBuffer->unmapBuffer();
}
IndexBuffer * IndexBufferInterface::getIndexBuffer() const
{
return mIndexBuffer;
}
unsigned int IndexBufferInterface::getWritePosition() const
{
return mWritePosition;
}
void IndexBufferInterface::setWritePosition(unsigned int writePosition)
{
mWritePosition = writePosition;
}
bool IndexBufferInterface::discard()
{
return mIndexBuffer->discard();
}
bool IndexBufferInterface::setBufferSize(unsigned int bufferSize, GLenum indexType)
{
if (mIndexBuffer->getBufferSize() == 0)
{
return mIndexBuffer->initialize(bufferSize, indexType, mDynamic);
}
else
{
return mIndexBuffer->setSize(bufferSize, indexType);
}
}
StreamingIndexBufferInterface::StreamingIndexBufferInterface(Renderer *renderer) : IndexBufferInterface(renderer, true)
{
}
StreamingIndexBufferInterface::~StreamingIndexBufferInterface()
{
}
bool StreamingIndexBufferInterface::reserveBufferSpace(unsigned int size, GLenum indexType)
{
bool result = true;
unsigned int curBufferSize = getBufferSize();
if (size > curBufferSize)
{
result = setBufferSize(std::max(size, 2 * curBufferSize), indexType);
setWritePosition(0);
}
else if (getWritePosition() + size > curBufferSize)
{
if (!discard())
{
return false;
}
setWritePosition(0);
}
return result;
}
StaticIndexBufferInterface::StaticIndexBufferInterface(Renderer *renderer) : IndexBufferInterface(renderer, false)
{
}
StaticIndexBufferInterface::~StaticIndexBufferInterface()
{
}
bool StaticIndexBufferInterface::reserveBufferSpace(unsigned int size, GLenum indexType)
{
unsigned int curSize = getBufferSize();
if (curSize == 0)
{
return setBufferSize(size, indexType);
}
else if (curSize >= size && indexType == getIndexType())
{
return true;
}
else
{
ERR("Static index buffers can't be resized");
UNREACHABLE();
return false;
}
}
unsigned int StaticIndexBufferInterface::lookupRange(intptr_t offset, GLsizei count, unsigned int *minIndex, unsigned int *maxIndex)
{
IndexRange range = {offset, count};
std::map<IndexRange, IndexResult>::iterator res = mCache.find(range);
if (res == mCache.end())
{
return -1;
}
*minIndex = res->second.minIndex;
*maxIndex = res->second.maxIndex;
return res->second.streamOffset;
}
void StaticIndexBufferInterface::addRange(intptr_t offset, GLsizei count, unsigned int minIndex, unsigned int maxIndex, unsigned int streamOffset)
{
IndexRange indexRange = {offset, count};
IndexResult indexResult = {minIndex, maxIndex, streamOffset};
mCache[indexRange] = indexResult;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer.cpp | C++ | bsd | 4,512 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image.h: Defines the rx::Image class, an abstract base class for the
// renderer-specific classes which will define the interface to the underlying
// surfaces or resources.
#ifndef LIBGLESV2_RENDERER_IMAGE_H_
#define LIBGLESV2_RENDERER_IMAGE_H_
#include "common/debug.h"
namespace gl
{
class Framebuffer;
}
namespace rx
{
class Renderer;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class Image
{
public:
Image();
virtual ~Image() {};
GLsizei getWidth() const { return mWidth; }
GLsizei getHeight() const { return mHeight; }
GLenum getInternalFormat() const { return mInternalFormat; }
GLenum getActualFormat() const { return mActualFormat; }
void markDirty() {mDirty = true;}
void markClean() {mDirty = false;}
virtual bool isDirty() const = 0;
virtual void setManagedSurface(TextureStorageInterface2D *storage, int level) {};
virtual void setManagedSurface(TextureStorageInterfaceCube *storage, int face, int level) {};
virtual bool updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height) = 0;
virtual bool updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height) = 0;
virtual bool redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease) = 0;
virtual bool isRenderableFormat() const = 0;
virtual void loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input) = 0;
virtual void loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input) = 0;
virtual void copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source) = 0;
static void loadAlphaDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadAlphaDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadAlphaDataToBGRASSE2(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadLuminanceDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native);
static void loadLuminanceFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadLuminanceFloatDataToRGB(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadLuminanceHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadLuminanceAlphaDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native);
static void loadLuminanceAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadLuminanceAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBUByteDataToBGRX(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBUByteDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGB565DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGB565DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBFloatDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBAUByteDataToBGRASSE2(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBAUByteDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBAUByteDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBA4444DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBA4444DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBA5551DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBA5551DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBAFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadRGBAHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
static void loadBGRADataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output);
protected:
GLsizei mWidth;
GLsizei mHeight;
GLint mInternalFormat;
GLenum mActualFormat;
bool mDirty;
private:
DISALLOW_COPY_AND_ASSIGN(Image);
};
}
#endif // LIBGLESV2_RENDERER_IMAGE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Image.h | C++ | bsd | 7,708 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderStateCache.cpp: Defines rx::RenderStateCache, a cache of Direct3D render
// state objects.
#include "libGLESv2/renderer/RenderStateCache.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "common/debug.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
// MSDN's documentation of ID3D11Device::CreateBlendState, ID3D11Device::CreateRasterizerState,
// ID3D11Device::CreateDepthStencilState and ID3D11Device::CreateSamplerState claims the maximum
// number of unique states of each type an application can create is 4096
const unsigned int RenderStateCache::kMaxBlendStates = 4096;
const unsigned int RenderStateCache::kMaxRasterizerStates = 4096;
const unsigned int RenderStateCache::kMaxDepthStencilStates = 4096;
const unsigned int RenderStateCache::kMaxSamplerStates = 4096;
RenderStateCache::RenderStateCache() : mDevice(NULL), mCounter(0),
mBlendStateCache(kMaxBlendStates, hashBlendState, compareBlendStates),
mRasterizerStateCache(kMaxRasterizerStates, hashRasterizerState, compareRasterizerStates),
mDepthStencilStateCache(kMaxDepthStencilStates, hashDepthStencilState, compareDepthStencilStates),
mSamplerStateCache(kMaxSamplerStates, hashSamplerState, compareSamplerStates)
{
}
RenderStateCache::~RenderStateCache()
{
clear();
}
void RenderStateCache::initialize(ID3D11Device *device)
{
clear();
mDevice = device;
}
void RenderStateCache::clear()
{
for (BlendStateMap::iterator i = mBlendStateCache.begin(); i != mBlendStateCache.end(); i++)
{
i->second.first->Release();
}
mBlendStateCache.clear();
for (RasterizerStateMap::iterator i = mRasterizerStateCache.begin(); i != mRasterizerStateCache.end(); i++)
{
i->second.first->Release();
}
mRasterizerStateCache.clear();
for (DepthStencilStateMap::iterator i = mDepthStencilStateCache.begin(); i != mDepthStencilStateCache.end(); i++)
{
i->second.first->Release();
}
mDepthStencilStateCache.clear();
for (SamplerStateMap::iterator i = mSamplerStateCache.begin(); i != mSamplerStateCache.end(); i++)
{
i->second.first->Release();
}
mSamplerStateCache.clear();
}
std::size_t RenderStateCache::hashBlendState(const gl::BlendState &blendState)
{
static const unsigned int seed = 0xABCDEF98;
std::size_t hash = 0;
MurmurHash3_x86_32(&blendState, sizeof(gl::BlendState), seed, &hash);
return hash;
}
bool RenderStateCache::compareBlendStates(const gl::BlendState &a, const gl::BlendState &b)
{
return memcmp(&a, &b, sizeof(gl::BlendState)) == 0;
}
ID3D11BlendState *RenderStateCache::getBlendState(const gl::BlendState &blendState)
{
if (!mDevice)
{
ERR("RenderStateCache is not initialized.");
return NULL;
}
BlendStateMap::iterator i = mBlendStateCache.find(blendState);
if (i != mBlendStateCache.end())
{
BlendStateCounterPair &state = i->second;
state.second = mCounter++;
return state.first;
}
else
{
if (mBlendStateCache.size() >= kMaxBlendStates)
{
TRACE("Overflowed the limit of %u blend states, removing the least recently used "
"to make room.", kMaxBlendStates);
BlendStateMap::iterator leastRecentlyUsed = mBlendStateCache.begin();
for (BlendStateMap::iterator i = mBlendStateCache.begin(); i != mBlendStateCache.end(); i++)
{
if (i->second.second < leastRecentlyUsed->second.second)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.first->Release();
mBlendStateCache.erase(leastRecentlyUsed);
}
// Create a new blend state and insert it into the cache
D3D11_BLEND_DESC blendDesc = { 0 };
blendDesc.AlphaToCoverageEnable = blendState.sampleAlphaToCoverage;
blendDesc.IndependentBlendEnable = FALSE;
for (unsigned int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++)
{
D3D11_RENDER_TARGET_BLEND_DESC &rtBlend = blendDesc.RenderTarget[i];
rtBlend.BlendEnable = blendState.blend;
if (blendState.blend)
{
rtBlend.SrcBlend = gl_d3d11::ConvertBlendFunc(blendState.sourceBlendRGB, false);
rtBlend.DestBlend = gl_d3d11::ConvertBlendFunc(blendState.destBlendRGB, false);
rtBlend.BlendOp = gl_d3d11::ConvertBlendOp(blendState.blendEquationRGB);
rtBlend.SrcBlendAlpha = gl_d3d11::ConvertBlendFunc(blendState.sourceBlendAlpha, true);
rtBlend.DestBlendAlpha = gl_d3d11::ConvertBlendFunc(blendState.destBlendAlpha, true);
rtBlend.BlendOpAlpha = gl_d3d11::ConvertBlendOp(blendState.blendEquationAlpha);
}
rtBlend.RenderTargetWriteMask = gl_d3d11::ConvertColorMask(blendState.colorMaskRed,
blendState.colorMaskGreen,
blendState.colorMaskBlue,
blendState.colorMaskAlpha);
}
ID3D11BlendState *dx11BlendState = NULL;
HRESULT result = mDevice->CreateBlendState(&blendDesc, &dx11BlendState);
if (FAILED(result) || !dx11BlendState)
{
ERR("Unable to create a ID3D11BlendState, HRESULT: 0x%X.", result);
return NULL;
}
mBlendStateCache.insert(std::make_pair(blendState, std::make_pair(dx11BlendState, mCounter++)));
return dx11BlendState;
}
}
std::size_t RenderStateCache::hashRasterizerState(const RasterizerStateKey &rasterState)
{
static const unsigned int seed = 0xABCDEF98;
std::size_t hash = 0;
MurmurHash3_x86_32(&rasterState, sizeof(RasterizerStateKey), seed, &hash);
return hash;
}
bool RenderStateCache::compareRasterizerStates(const RasterizerStateKey &a, const RasterizerStateKey &b)
{
return memcmp(&a, &b, sizeof(RasterizerStateKey)) == 0;
}
ID3D11RasterizerState *RenderStateCache::getRasterizerState(const gl::RasterizerState &rasterState,
bool scissorEnabled, unsigned int depthSize)
{
if (!mDevice)
{
ERR("RenderStateCache is not initialized.");
return NULL;
}
RasterizerStateKey key;
key.rasterizerState = rasterState;
key.scissorEnabled = scissorEnabled;
key.depthSize = depthSize;
RasterizerStateMap::iterator i = mRasterizerStateCache.find(key);
if (i != mRasterizerStateCache.end())
{
RasterizerStateCounterPair &state = i->second;
state.second = mCounter++;
return state.first;
}
else
{
if (mRasterizerStateCache.size() >= kMaxRasterizerStates)
{
TRACE("Overflowed the limit of %u rasterizer states, removing the least recently used "
"to make room.", kMaxRasterizerStates);
RasterizerStateMap::iterator leastRecentlyUsed = mRasterizerStateCache.begin();
for (RasterizerStateMap::iterator i = mRasterizerStateCache.begin(); i != mRasterizerStateCache.end(); i++)
{
if (i->second.second < leastRecentlyUsed->second.second)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.first->Release();
mRasterizerStateCache.erase(leastRecentlyUsed);
}
D3D11_CULL_MODE cullMode = gl_d3d11::ConvertCullMode(rasterState.cullFace, rasterState.cullMode);
// Disable culling if drawing points
if (rasterState.pointDrawMode)
{
cullMode = D3D11_CULL_NONE;
}
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.CullMode = cullMode;
rasterDesc.FrontCounterClockwise = (rasterState.frontFace == GL_CCW) ? FALSE: TRUE;
rasterDesc.DepthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
rasterDesc.DepthBiasClamp = 0.0f; // MSDN documentation of DepthBiasClamp implies a value of zero will preform no clamping, must be tested though.
rasterDesc.SlopeScaledDepthBias = rasterState.polygonOffsetFactor;
rasterDesc.DepthClipEnable = TRUE;
rasterDesc.ScissorEnable = scissorEnabled ? TRUE : FALSE;
rasterDesc.MultisampleEnable = rasterState.multiSample;
rasterDesc.AntialiasedLineEnable = FALSE;
ID3D11RasterizerState *dx11RasterizerState = NULL;
HRESULT result = mDevice->CreateRasterizerState(&rasterDesc, &dx11RasterizerState);
if (FAILED(result) || !dx11RasterizerState)
{
ERR("Unable to create a ID3D11RasterizerState, HRESULT: 0x%X.", result);
return NULL;
}
mRasterizerStateCache.insert(std::make_pair(key, std::make_pair(dx11RasterizerState, mCounter++)));
return dx11RasterizerState;
}
}
std::size_t RenderStateCache::hashDepthStencilState(const gl::DepthStencilState &dsState)
{
static const unsigned int seed = 0xABCDEF98;
std::size_t hash = 0;
MurmurHash3_x86_32(&dsState, sizeof(gl::DepthStencilState), seed, &hash);
return hash;
}
bool RenderStateCache::compareDepthStencilStates(const gl::DepthStencilState &a, const gl::DepthStencilState &b)
{
return memcmp(&a, &b, sizeof(gl::DepthStencilState)) == 0;
}
ID3D11DepthStencilState *RenderStateCache::getDepthStencilState(const gl::DepthStencilState &dsState)
{
if (!mDevice)
{
ERR("RenderStateCache is not initialized.");
return NULL;
}
DepthStencilStateMap::iterator i = mDepthStencilStateCache.find(dsState);
if (i != mDepthStencilStateCache.end())
{
DepthStencilStateCounterPair &state = i->second;
state.second = mCounter++;
return state.first;
}
else
{
if (mDepthStencilStateCache.size() >= kMaxDepthStencilStates)
{
TRACE("Overflowed the limit of %u depth stencil states, removing the least recently used "
"to make room.", kMaxDepthStencilStates);
DepthStencilStateMap::iterator leastRecentlyUsed = mDepthStencilStateCache.begin();
for (DepthStencilStateMap::iterator i = mDepthStencilStateCache.begin(); i != mDepthStencilStateCache.end(); i++)
{
if (i->second.second < leastRecentlyUsed->second.second)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.first->Release();
mDepthStencilStateCache.erase(leastRecentlyUsed);
}
D3D11_DEPTH_STENCIL_DESC dsDesc = { 0 };
dsDesc.DepthEnable = dsState.depthTest ? TRUE : FALSE;
dsDesc.DepthWriteMask = gl_d3d11::ConvertDepthMask(dsState.depthMask);
dsDesc.DepthFunc = gl_d3d11::ConvertComparison(dsState.depthFunc);
dsDesc.StencilEnable = dsState.stencilTest ? TRUE : FALSE;
dsDesc.StencilReadMask = gl_d3d11::ConvertStencilMask(dsState.stencilMask);
dsDesc.StencilWriteMask = gl_d3d11::ConvertStencilMask(dsState.stencilWritemask);
dsDesc.FrontFace.StencilFailOp = gl_d3d11::ConvertStencilOp(dsState.stencilFail);
dsDesc.FrontFace.StencilDepthFailOp = gl_d3d11::ConvertStencilOp(dsState.stencilPassDepthFail);
dsDesc.FrontFace.StencilPassOp = gl_d3d11::ConvertStencilOp(dsState.stencilPassDepthPass);
dsDesc.FrontFace.StencilFunc = gl_d3d11::ConvertComparison(dsState.stencilFunc);
dsDesc.BackFace.StencilFailOp = gl_d3d11::ConvertStencilOp(dsState.stencilBackFail);
dsDesc.BackFace.StencilDepthFailOp = gl_d3d11::ConvertStencilOp(dsState.stencilBackPassDepthFail);
dsDesc.BackFace.StencilPassOp = gl_d3d11::ConvertStencilOp(dsState.stencilBackPassDepthPass);
dsDesc.BackFace.StencilFunc = gl_d3d11::ConvertComparison(dsState.stencilBackFunc);
ID3D11DepthStencilState *dx11DepthStencilState = NULL;
HRESULT result = mDevice->CreateDepthStencilState(&dsDesc, &dx11DepthStencilState);
if (FAILED(result) || !dx11DepthStencilState)
{
ERR("Unable to create a ID3D11DepthStencilState, HRESULT: 0x%X.", result);
return NULL;
}
mDepthStencilStateCache.insert(std::make_pair(dsState, std::make_pair(dx11DepthStencilState, mCounter++)));
return dx11DepthStencilState;
}
}
std::size_t RenderStateCache::hashSamplerState(const gl::SamplerState &samplerState)
{
static const unsigned int seed = 0xABCDEF98;
std::size_t hash = 0;
MurmurHash3_x86_32(&samplerState, sizeof(gl::SamplerState), seed, &hash);
return hash;
}
bool RenderStateCache::compareSamplerStates(const gl::SamplerState &a, const gl::SamplerState &b)
{
return memcmp(&a, &b, sizeof(gl::SamplerState)) == 0;
}
ID3D11SamplerState *RenderStateCache::getSamplerState(const gl::SamplerState &samplerState)
{
if (!mDevice)
{
ERR("RenderStateCache is not initialized.");
return NULL;
}
SamplerStateMap::iterator i = mSamplerStateCache.find(samplerState);
if (i != mSamplerStateCache.end())
{
SamplerStateCounterPair &state = i->second;
state.second = mCounter++;
return state.first;
}
else
{
if (mSamplerStateCache.size() >= kMaxSamplerStates)
{
TRACE("Overflowed the limit of %u sampler states, removing the least recently used "
"to make room.", kMaxSamplerStates);
SamplerStateMap::iterator leastRecentlyUsed = mSamplerStateCache.begin();
for (SamplerStateMap::iterator i = mSamplerStateCache.begin(); i != mSamplerStateCache.end(); i++)
{
if (i->second.second < leastRecentlyUsed->second.second)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.first->Release();
mSamplerStateCache.erase(leastRecentlyUsed);
}
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = gl_d3d11::ConvertFilter(samplerState.minFilter, samplerState.magFilter, samplerState.maxAnisotropy);
samplerDesc.AddressU = gl_d3d11::ConvertTextureWrap(samplerState.wrapS);
samplerDesc.AddressV = gl_d3d11::ConvertTextureWrap(samplerState.wrapT);
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = static_cast<float>(samplerState.lodOffset);
samplerDesc.MaxAnisotropy = samplerState.maxAnisotropy;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = gl_d3d11::ConvertMinLOD(samplerState.minFilter, samplerState.lodOffset);
samplerDesc.MaxLOD = gl_d3d11::ConvertMaxLOD(samplerState.minFilter, samplerState.lodOffset);
ID3D11SamplerState *dx11SamplerState = NULL;
HRESULT result = mDevice->CreateSamplerState(&samplerDesc, &dx11SamplerState);
if (FAILED(result) || !dx11SamplerState)
{
ERR("Unable to create a ID3D11DepthStencilState, HRESULT: 0x%X.", result);
return NULL;
}
mSamplerStateCache.insert(std::make_pair(samplerState, std::make_pair(dx11SamplerState, mCounter++)));
return dx11SamplerState;
}
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/RenderStateCache.cpp | C++ | bsd | 15,996 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer11.h: Defines the D3D11 VertexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_VERTEXBUFFER11_H_
#define LIBGLESV2_RENDERER_VERTEXBUFFER11_H_
#include "libGLESv2/renderer/VertexBuffer.h"
namespace rx
{
class Renderer11;
class VertexBuffer11 : public VertexBuffer
{
public:
explicit VertexBuffer11(rx::Renderer11 *const renderer);
virtual ~VertexBuffer11();
virtual bool initialize(unsigned int size, bool dynamicUsage);
static VertexBuffer11 *makeVertexBuffer11(VertexBuffer *vetexBuffer);
virtual bool storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances,
unsigned int offset);
virtual bool storeRawData(const void* data, unsigned int size, unsigned int offset);
virtual unsigned int getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count, GLsizei instances) const;
virtual bool requiresConversion(const gl::VertexAttribute &attrib) const;
virtual unsigned int getBufferSize() const;
virtual bool setBufferSize(unsigned int size);
virtual bool discard();
unsigned int getVertexSize(const gl::VertexAttribute &attrib) const;
DXGI_FORMAT getDXGIFormat(const gl::VertexAttribute &attrib) const;
ID3D11Buffer *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(VertexBuffer11);
rx::Renderer11 *const mRenderer;
ID3D11Buffer *mBuffer;
unsigned int mBufferSize;
bool mDynamicUsage;
typedef void (*VertexConversionFunction)(const void *, unsigned int, unsigned int, void *);
struct VertexConverter
{
VertexConversionFunction conversionFunc;
bool identity;
DXGI_FORMAT dxgiFormat;
unsigned int outputElementSize;
};
enum { NUM_GL_VERTEX_ATTRIB_TYPES = 6 };
// This table is used to generate mAttributeTypes.
static const VertexConverter mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4]; // [GL types as enumerated by typeIndex()][normalized][size - 1]
static const VertexConverter &getVertexConversion(const gl::VertexAttribute &attribute);
};
}
#endif // LIBGLESV2_RENDERER_VERTEXBUFFER11_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer11.h | C++ | bsd | 2,350 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDataManager.h: Defines the VertexDataManager, a class that
// runs the Buffer translation process.
#include "libGLESv2/renderer/VertexDataManager.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/VertexBuffer.h"
namespace
{
enum { INITIAL_STREAM_BUFFER_SIZE = 1024*1024 };
// This has to be at least 4k or else it fails on ATI cards.
enum { CONSTANT_VERTEX_BUFFER_SIZE = 4096 };
}
namespace rx
{
static int elementsInBuffer(const gl::VertexAttribute &attribute, int size)
{
int stride = attribute.stride();
return (size - attribute.mOffset % stride + (stride - attribute.typeSize())) / stride;
}
VertexDataManager::VertexDataManager(Renderer *renderer) : mRenderer(renderer)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentValue[i][0] = std::numeric_limits<float>::quiet_NaN();
mCurrentValue[i][1] = std::numeric_limits<float>::quiet_NaN();
mCurrentValue[i][2] = std::numeric_limits<float>::quiet_NaN();
mCurrentValue[i][3] = std::numeric_limits<float>::quiet_NaN();
mCurrentValueBuffer[i] = NULL;
mCurrentValueOffsets[i] = 0;
}
mStreamingBuffer = new StreamingVertexBufferInterface(renderer, INITIAL_STREAM_BUFFER_SIZE);
if (!mStreamingBuffer)
{
ERR("Failed to allocate the streaming vertex buffer.");
}
}
VertexDataManager::~VertexDataManager()
{
delete mStreamingBuffer;
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
delete mCurrentValueBuffer[i];
}
}
static bool directStoragePossible(VertexBufferInterface* vb, const gl::VertexAttribute& attrib)
{
gl::Buffer *buffer = attrib.mBoundBuffer.get();
BufferStorage *storage = buffer ? buffer->getStorage() : NULL;
const bool isAligned = (attrib.stride() % 4 == 0) && (attrib.mOffset % 4 == 0);
return storage && storage->supportsDirectBinding() && !vb->getVertexBuffer()->requiresConversion(attrib) && isAligned;
}
GLenum VertexDataManager::prepareVertexData(const gl::VertexAttribute attribs[], gl::ProgramBinary *programBinary, GLint start, GLsizei count, TranslatedAttribute *translated, GLsizei instances)
{
if (!mStreamingBuffer)
{
return GL_OUT_OF_MEMORY;
}
for (int attributeIndex = 0; attributeIndex < gl::MAX_VERTEX_ATTRIBS; attributeIndex++)
{
translated[attributeIndex].active = (programBinary->getSemanticIndex(attributeIndex) != -1);
}
// Invalidate static buffers that don't contain matching attributes
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (translated[i].active && attribs[i].mArrayEnabled)
{
gl::Buffer *buffer = attribs[i].mBoundBuffer.get();
StaticVertexBufferInterface *staticBuffer = buffer ? buffer->getStaticVertexBuffer() : NULL;
if (staticBuffer && staticBuffer->getBufferSize() > 0 && staticBuffer->lookupAttribute(attribs[i]) == -1 &&
!directStoragePossible(staticBuffer, attribs[i]))
{
buffer->invalidateStaticData();
}
}
}
// Reserve the required space in the buffers
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (translated[i].active && attribs[i].mArrayEnabled)
{
gl::Buffer *buffer = attribs[i].mBoundBuffer.get();
StaticVertexBufferInterface *staticBuffer = buffer ? buffer->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
if (!directStoragePossible(vertexBuffer, attribs[i]))
{
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0)
{
int totalCount = elementsInBuffer(attribs[i], buffer->size());
staticBuffer->reserveVertexSpace(attribs[i], totalCount, 0);
}
}
else
{
mStreamingBuffer->reserveVertexSpace(attribs[i], count, instances);
}
}
}
}
// Perform the vertex data translations
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (translated[i].active)
{
if (attribs[i].mArrayEnabled)
{
gl::Buffer *buffer = attribs[i].mBoundBuffer.get();
if (!buffer && attribs[i].mPointer == NULL)
{
// This is an application error that would normally result in a crash, but we catch it and return an error
ERR("An enabled vertex array has no buffer and no pointer.");
return GL_INVALID_OPERATION;
}
StaticVertexBufferInterface *staticBuffer = buffer ? buffer->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
BufferStorage *storage = buffer ? buffer->getStorage() : NULL;
bool directStorage = directStoragePossible(vertexBuffer, attribs[i]);
std::size_t streamOffset = -1;
unsigned int outputElementSize = 0;
if (directStorage)
{
outputElementSize = attribs[i].stride();
streamOffset = attribs[i].mOffset + outputElementSize * start;
storage->markBufferUsage();
}
else if (staticBuffer)
{
streamOffset = staticBuffer->lookupAttribute(attribs[i]);
outputElementSize = staticBuffer->getVertexBuffer()->getSpaceRequired(attribs[i], 1, 0);
if (streamOffset == -1)
{
// Convert the entire buffer
int totalCount = elementsInBuffer(attribs[i], storage->getSize());
int startIndex = attribs[i].mOffset / attribs[i].stride();
streamOffset = staticBuffer->storeVertexAttributes(attribs[i], -startIndex, totalCount, 0);
}
if (streamOffset != -1)
{
streamOffset += (attribs[i].mOffset / attribs[i].stride()) * outputElementSize;
if (instances == 0 || attribs[i].mDivisor == 0)
{
streamOffset += start * outputElementSize;
}
}
}
else
{
outputElementSize = mStreamingBuffer->getVertexBuffer()->getSpaceRequired(attribs[i], 1, 0);
streamOffset = mStreamingBuffer->storeVertexAttributes(attribs[i], start, count, instances);
}
if (streamOffset == -1)
{
return GL_OUT_OF_MEMORY;
}
translated[i].storage = directStorage ? storage : NULL;
translated[i].vertexBuffer = vertexBuffer->getVertexBuffer();
translated[i].serial = directStorage ? storage->getSerial() : vertexBuffer->getSerial();
translated[i].divisor = attribs[i].mDivisor;
translated[i].attribute = &attribs[i];
translated[i].stride = outputElementSize;
translated[i].offset = streamOffset;
}
else
{
if (!mCurrentValueBuffer[i])
{
mCurrentValueBuffer[i] = new StreamingVertexBufferInterface(mRenderer, CONSTANT_VERTEX_BUFFER_SIZE);
}
StreamingVertexBufferInterface *buffer = mCurrentValueBuffer[i];
if (mCurrentValue[i][0] != attribs[i].mCurrentValue[0] ||
mCurrentValue[i][1] != attribs[i].mCurrentValue[1] ||
mCurrentValue[i][2] != attribs[i].mCurrentValue[2] ||
mCurrentValue[i][3] != attribs[i].mCurrentValue[3])
{
unsigned int requiredSpace = sizeof(float) * 4;
buffer->reserveRawDataSpace(requiredSpace);
int streamOffset = buffer->storeRawData(attribs[i].mCurrentValue, requiredSpace);
if (streamOffset == -1)
{
return GL_OUT_OF_MEMORY;
}
mCurrentValueOffsets[i] = streamOffset;
}
translated[i].storage = NULL;
translated[i].vertexBuffer = mCurrentValueBuffer[i]->getVertexBuffer();
translated[i].serial = mCurrentValueBuffer[i]->getSerial();
translated[i].divisor = 0;
translated[i].attribute = &attribs[i];
translated[i].stride = 0;
translated[i].offset = mCurrentValueOffsets[i];
}
}
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (translated[i].active && attribs[i].mArrayEnabled)
{
gl::Buffer *buffer = attribs[i].mBoundBuffer.get();
if (buffer)
{
buffer->promoteStaticUsage(count * attribs[i].typeSize());
}
}
}
return GL_NO_ERROR;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexDataManager.cpp | C++ | bsd | 9,788 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence11.cpp: Defines the rx::Fence11 class which implements rx::FenceImpl.
#include "libGLESv2/renderer/Fence11.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/Renderer11.h"
namespace rx
{
Fence11::Fence11(rx::Renderer11 *renderer)
{
mRenderer = renderer;
mQuery = NULL;
}
Fence11::~Fence11()
{
if (mQuery)
{
mQuery->Release();
mQuery = NULL;
}
}
GLboolean Fence11::isFence()
{
// GL_NV_fence spec:
// A name returned by GenFencesNV, but not yet set via SetFenceNV, is not the name of an existing fence.
return mQuery != NULL;
}
void Fence11::setFence(GLenum condition)
{
if (!mQuery)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_EVENT;
queryDesc.MiscFlags = 0;
if (FAILED(mRenderer->getDevice()->CreateQuery(&queryDesc, &mQuery)))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
mRenderer->getDeviceContext()->End(mQuery);
setCondition(condition);
setStatus(GL_FALSE);
}
GLboolean Fence11::testFence()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION, GL_TRUE);
}
HRESULT result = mRenderer->getDeviceContext()->GetData(mQuery, NULL, 0, 0);
if (mRenderer->isDeviceLost())
{
return gl::error(GL_OUT_OF_MEMORY, GL_TRUE);
}
ASSERT(result == S_OK || result == S_FALSE);
setStatus(result == S_OK);
return getStatus();
}
void Fence11::finishFence()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
while (!testFence())
{
Sleep(0);
}
}
void Fence11::getFenceiv(GLenum pname, GLint *params)
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (pname)
{
case GL_FENCE_STATUS_NV:
{
// GL_NV_fence spec:
// Once the status of a fence has been finished (via FinishFenceNV) or tested and the returned status is TRUE (via either TestFenceNV
// or GetFenceivNV querying the FENCE_STATUS_NV), the status remains TRUE until the next SetFenceNV of the fence.
if (getStatus())
{
params[0] = GL_TRUE;
return;
}
HRESULT result = mRenderer->getDeviceContext()->GetData(mQuery, NULL, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH);
if (mRenderer->isDeviceLost())
{
params[0] = GL_TRUE;
return gl::error(GL_OUT_OF_MEMORY);
}
ASSERT(result == S_OK || result == S_FALSE);
setStatus(result == S_OK);
params[0] = getStatus();
break;
}
case GL_FENCE_CONDITION_NV:
params[0] = getCondition();
break;
default:
return gl::error(GL_INVALID_ENUM);
break;
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Fence11.cpp | C++ | bsd | 3,076 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexDataManager.h: Defines the IndexDataManager, a class that
// runs the Buffer translation process for index buffers.
#ifndef LIBGLESV2_INDEXDATAMANAGER_H_
#define LIBGLESV2_INDEXDATAMANAGER_H_
#include "common/angleutils.h"
namespace
{
enum { INITIAL_INDEX_BUFFER_SIZE = 4096 * sizeof(GLuint) };
}
namespace gl
{
class Buffer;
}
namespace rx
{
class StaticIndexBufferInterface;
class StreamingIndexBufferInterface;
class IndexBuffer;
class BufferStorage;
class Renderer;
struct TranslatedIndexData
{
unsigned int minIndex;
unsigned int maxIndex;
unsigned int startIndex;
unsigned int startOffset; // In bytes
IndexBuffer *indexBuffer;
BufferStorage *storage;
unsigned int serial;
};
class IndexDataManager
{
public:
explicit IndexDataManager(Renderer *renderer);
virtual ~IndexDataManager();
GLenum prepareIndexData(GLenum type, GLsizei count, gl::Buffer *arrayElementBuffer, const GLvoid *indices, TranslatedIndexData *translated);
StaticIndexBufferInterface *getCountingIndices(GLsizei count);
private:
DISALLOW_COPY_AND_ASSIGN(IndexDataManager);
Renderer *const mRenderer;
StreamingIndexBufferInterface *mStreamingBufferShort;
StreamingIndexBufferInterface *mStreamingBufferInt;
StaticIndexBufferInterface *mCountingBuffer;
};
}
#endif // LIBGLESV2_INDEXDATAMANAGER_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/IndexDataManager.h | C++ | bsd | 1,555 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage.h Defines the abstract BufferStorage class.
#ifndef LIBGLESV2_RENDERER_BUFFERSTORAGE_H_
#define LIBGLESV2_RENDERER_BUFFERSTORAGE_H_
#include "common/angleutils.h"
namespace rx
{
class BufferStorage
{
public:
BufferStorage();
virtual ~BufferStorage();
// The data returned is only guaranteed valid until next non-const method.
virtual void *getData() = 0;
virtual void setData(const void* data, unsigned int size, unsigned int offset) = 0;
virtual void clear() = 0;
virtual unsigned int getSize() const = 0;
virtual bool supportsDirectBinding() const = 0;
virtual void markBufferUsage();
unsigned int getSerial() const;
protected:
void updateSerial();
private:
DISALLOW_COPY_AND_ASSIGN(BufferStorage);
unsigned int mSerial;
static unsigned int mNextSerial;
};
}
#endif // LIBGLESV2_RENDERER_BUFFERSTORAGE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage.h | C++ | bsd | 1,077 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexBuffer11.h: Defines the D3D11 IndexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_INDEXBUFFER11_H_
#define LIBGLESV2_RENDERER_INDEXBUFFER11_H_
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
class Renderer11;
class IndexBuffer11 : public IndexBuffer
{
public:
explicit IndexBuffer11(Renderer11 *const renderer);
virtual ~IndexBuffer11();
virtual bool initialize(unsigned int bufferSize, GLenum indexType, bool dynamic);
static IndexBuffer11 *makeIndexBuffer11(IndexBuffer *indexBuffer);
virtual bool mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory);
virtual bool unmapBuffer();
virtual GLenum getIndexType() const;
virtual unsigned int getBufferSize() const;
virtual bool setSize(unsigned int bufferSize, GLenum indexType);
virtual bool discard();
DXGI_FORMAT getIndexFormat() const;
ID3D11Buffer *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(IndexBuffer11);
rx::Renderer11 *const mRenderer;
ID3D11Buffer *mBuffer;
unsigned int mBufferSize;
GLenum mIndexType;
bool mDynamicUsage;
};
}
#endif // LIBGLESV2_RENDERER_INDEXBUFFER11_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer11.h | C++ | bsd | 1,357 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderTarget11.h: Defines a DX11-specific wrapper for ID3D11View pointers
// retained by Renderbuffers.
#ifndef LIBGLESV2_RENDERER_RENDERTARGET11_H_
#define LIBGLESV2_RENDERER_RENDERTARGET11_H_
#include "libGLESv2/renderer/RenderTarget.h"
namespace rx
{
class Renderer;
class Renderer11;
class RenderTarget11 : public RenderTarget
{
public:
RenderTarget11(Renderer *renderer, ID3D11RenderTargetView *rtv, ID3D11Texture2D *tex, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height);
RenderTarget11(Renderer *renderer, ID3D11DepthStencilView *dsv, ID3D11Texture2D *tex, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height);
RenderTarget11(Renderer *renderer, GLsizei width, GLsizei height, GLenum format, GLsizei samples, bool depth);
virtual ~RenderTarget11();
static RenderTarget11 *makeRenderTarget11(RenderTarget *renderTarget);
// Adds reference, caller must call Release
ID3D11Texture2D *getTexture() const;
// Adds reference, caller must call Release
ID3D11RenderTargetView *getRenderTargetView() const;
// Adds reference, caller must call Release
ID3D11DepthStencilView *getDepthStencilView() const;
// Adds reference, caller must call Release
ID3D11ShaderResourceView *getShaderResourceView() const;
unsigned int getSubresourceIndex() const;
private:
DISALLOW_COPY_AND_ASSIGN(RenderTarget11);
unsigned int mSubresourceIndex;
ID3D11Texture2D *mTexture;
ID3D11RenderTargetView *mRenderTarget;
ID3D11DepthStencilView *mDepthStencil;
ID3D11ShaderResourceView *mShaderResource;
Renderer11 *mRenderer;
};
}
#endif LIBGLESV2_RENDERER_RENDERTARGET11_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/RenderTarget11.h | C++ | bsd | 1,855 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence11.h: Defines the rx::Fence11 class which implements rx::FenceImpl.
#ifndef LIBGLESV2_RENDERER_Fence11_H_
#define LIBGLESV2_RENDERER_Fence11_H_
#include "libGLESv2/renderer/FenceImpl.h"
namespace rx
{
class Renderer11;
class Fence11 : public FenceImpl
{
public:
explicit Fence11(rx::Renderer11 *renderer);
virtual ~Fence11();
GLboolean isFence();
void setFence(GLenum condition);
GLboolean testFence();
void finishFence();
void getFenceiv(GLenum pname, GLint *params);
private:
DISALLOW_COPY_AND_ASSIGN(Fence11);
rx::Renderer11 *mRenderer;
ID3D11Query *mQuery;
};
}
#endif // LIBGLESV2_RENDERER_FENCE11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Fence11.h | C++ | bsd | 848 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query11.cpp: Defines the rx::Query11 class which implements rx::QueryImpl.
#include "libGLESv2/renderer/Query11.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/main.h"
namespace rx
{
Query11::Query11(rx::Renderer11 *renderer, GLenum type) : QueryImpl(type)
{
mRenderer = renderer;
mQuery = NULL;
}
Query11::~Query11()
{
if (mQuery)
{
mQuery->Release();
mQuery = NULL;
}
}
void Query11::begin()
{
if (mQuery == NULL)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
if (FAILED(mRenderer->getDevice()->CreateQuery(&queryDesc, &mQuery)))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
mRenderer->getDeviceContext()->Begin(mQuery);
}
void Query11::end()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
mRenderer->getDeviceContext()->End(mQuery);
mStatus = GL_FALSE;
mResult = GL_FALSE;
}
GLuint Query11::getResult()
{
if (mQuery != NULL)
{
while (!testQuery())
{
Sleep(0);
// explicitly check for device loss, some drivers seem to return S_FALSE
// if the device is lost
if (mRenderer->testDeviceLost(true))
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
}
}
return mResult;
}
GLboolean Query11::isResultAvailable()
{
if (mQuery != NULL)
{
testQuery();
}
return mStatus;
}
GLboolean Query11::testQuery()
{
if (mQuery != NULL && mStatus != GL_TRUE)
{
UINT64 numPixels = 0;
HRESULT result = mRenderer->getDeviceContext()->GetData(mQuery, &numPixels, sizeof(UINT64), 0);
if (result == S_OK)
{
mStatus = GL_TRUE;
switch (getType())
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
mResult = (numPixels > 0) ? GL_TRUE : GL_FALSE;
break;
default:
UNREACHABLE();
}
}
else if (mRenderer->testDeviceLost(true))
{
return gl::error(GL_OUT_OF_MEMORY, GL_TRUE);
}
return mStatus;
}
return GL_TRUE; // prevent blocking when query is null
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Query11.cpp | C++ | bsd | 2,590 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderExecutable9.h: Defines a D3D9-specific class to contain shader
// executable implementation details.
#ifndef LIBGLESV2_RENDERER_SHADEREXECUTABLE9_H_
#define LIBGLESV2_RENDERER_SHADEREXECUTABLE9_H_
#include "libGLESv2/renderer/ShaderExecutable.h"
namespace rx
{
class ShaderExecutable9 : public ShaderExecutable
{
public:
ShaderExecutable9(const void *function, size_t length, IDirect3DPixelShader9 *executable);
ShaderExecutable9(const void *function, size_t length, IDirect3DVertexShader9 *executable);
virtual ~ShaderExecutable9();
static ShaderExecutable9 *makeShaderExecutable9(ShaderExecutable *executable);
IDirect3DPixelShader9 *getPixelShader() const;
IDirect3DVertexShader9 *getVertexShader() const;
private:
DISALLOW_COPY_AND_ASSIGN(ShaderExecutable9);
IDirect3DPixelShader9 *mPixelExecutable;
IDirect3DVertexShader9 *mVertexExecutable;
};
}
#endif // LIBGLESV2_RENDERER_SHADEREXECUTABLE9_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/ShaderExecutable9.h | C++ | bsd | 1,146 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/VertexBuffer9.h"
#include "libGLESv2/renderer/VertexDeclarationCache.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].vertexDeclaration)
{
mVertexDeclCache[i].vertexDeclaration->Release();
}
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
element->Stream = stream;
element->Offset = 0;
element->Type = attributes[i].attribute->mArrayEnabled ? vertexBuffer->getDeclType(*attributes[i].attribute) : D3DDECLTYPE_FLOAT4;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
lastCache->vertexDeclaration->Release();
lastCache->vertexDeclaration = NULL;
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexDeclarationCache.cpp | C++ | bsd | 7,095 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image9.cpp: Implements the rx::Image9 class, which acts as the interface to
// the actual underlying surfaces of a Texture.
#include "libGLESv2/renderer/Image9.h"
#include "libGLESv2/main.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/renderer/RenderTarget9.h"
#include "libGLESv2/renderer/TextureStorage9.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/generatemip.h"
namespace rx
{
Image9::Image9()
{
mSurface = NULL;
mRenderer = NULL;
mD3DPool = D3DPOOL_SYSTEMMEM;
mD3DFormat = D3DFMT_UNKNOWN;
}
Image9::~Image9()
{
if (mSurface)
{
mSurface->Release();
}
}
void Image9::generateMip(IDirect3DSurface9 *destSurface, IDirect3DSurface9 *sourceSurface)
{
D3DSURFACE_DESC destDesc;
HRESULT result = destSurface->GetDesc(&destDesc);
ASSERT(SUCCEEDED(result));
D3DSURFACE_DESC sourceDesc;
result = sourceSurface->GetDesc(&sourceDesc);
ASSERT(SUCCEEDED(result));
ASSERT(sourceDesc.Format == destDesc.Format);
ASSERT(sourceDesc.Width == 1 || sourceDesc.Width / 2 == destDesc.Width);
ASSERT(sourceDesc.Height == 1 || sourceDesc.Height / 2 == destDesc.Height);
D3DLOCKED_RECT sourceLocked = {0};
result = sourceSurface->LockRect(&sourceLocked, NULL, D3DLOCK_READONLY);
ASSERT(SUCCEEDED(result));
D3DLOCKED_RECT destLocked = {0};
result = destSurface->LockRect(&destLocked, NULL, 0);
ASSERT(SUCCEEDED(result));
const unsigned char *sourceData = reinterpret_cast<const unsigned char*>(sourceLocked.pBits);
unsigned char *destData = reinterpret_cast<unsigned char*>(destLocked.pBits);
if (sourceData && destData)
{
switch (sourceDesc.Format)
{
case D3DFMT_L8:
GenerateMip<L8>(sourceDesc.Width, sourceDesc.Height, sourceData, sourceLocked.Pitch, destData, destLocked.Pitch);
break;
case D3DFMT_A8L8:
GenerateMip<A8L8>(sourceDesc.Width, sourceDesc.Height, sourceData, sourceLocked.Pitch, destData, destLocked.Pitch);
break;
case D3DFMT_A8R8G8B8:
case D3DFMT_X8R8G8B8:
GenerateMip<A8R8G8B8>(sourceDesc.Width, sourceDesc.Height, sourceData, sourceLocked.Pitch, destData, destLocked.Pitch);
break;
case D3DFMT_A16B16G16R16F:
GenerateMip<A16B16G16R16F>(sourceDesc.Width, sourceDesc.Height, sourceData, sourceLocked.Pitch, destData, destLocked.Pitch);
break;
case D3DFMT_A32B32G32R32F:
GenerateMip<A32B32G32R32F>(sourceDesc.Width, sourceDesc.Height, sourceData, sourceLocked.Pitch, destData, destLocked.Pitch);
break;
default:
UNREACHABLE();
break;
}
destSurface->UnlockRect();
sourceSurface->UnlockRect();
}
}
Image9 *Image9::makeImage9(Image *img)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Image9*, img));
return static_cast<rx::Image9*>(img);
}
void Image9::generateMipmap(Image9 *dest, Image9 *source)
{
IDirect3DSurface9 *sourceSurface = source->getSurface();
if (sourceSurface == NULL)
return gl::error(GL_OUT_OF_MEMORY);
IDirect3DSurface9 *destSurface = dest->getSurface();
generateMip(destSurface, sourceSurface);
dest->markDirty();
}
void Image9::copyLockableSurfaces(IDirect3DSurface9 *dest, IDirect3DSurface9 *source)
{
D3DLOCKED_RECT sourceLock = {0};
D3DLOCKED_RECT destLock = {0};
source->LockRect(&sourceLock, NULL, 0);
dest->LockRect(&destLock, NULL, 0);
if (sourceLock.pBits && destLock.pBits)
{
D3DSURFACE_DESC desc;
source->GetDesc(&desc);
int rows = d3d9::IsCompressedFormat(desc.Format) ? desc.Height / 4 : desc.Height;
int bytes = d3d9::ComputeRowSize(desc.Format, desc.Width);
ASSERT(bytes <= sourceLock.Pitch && bytes <= destLock.Pitch);
for(int i = 0; i < rows; i++)
{
memcpy((char*)destLock.pBits + destLock.Pitch * i, (char*)sourceLock.pBits + sourceLock.Pitch * i, bytes);
}
source->UnlockRect();
dest->UnlockRect();
}
else UNREACHABLE();
}
bool Image9::redefine(rx::Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease)
{
if (mWidth != width ||
mHeight != height ||
mInternalFormat != internalformat ||
forceRelease)
{
mRenderer = Renderer9::makeRenderer9(renderer);
mWidth = width;
mHeight = height;
mInternalFormat = internalformat;
// compute the d3d format that will be used
mD3DFormat = mRenderer->ConvertTextureInternalFormat(internalformat);
mActualFormat = d3d9_gl::GetEquivalentFormat(mD3DFormat);
if (mSurface)
{
mSurface->Release();
mSurface = NULL;
}
return true;
}
return false;
}
void Image9::createSurface()
{
if(mSurface)
{
return;
}
IDirect3DTexture9 *newTexture = NULL;
IDirect3DSurface9 *newSurface = NULL;
const D3DPOOL poolToUse = D3DPOOL_SYSTEMMEM;
const D3DFORMAT d3dFormat = getD3DFormat();
ASSERT(d3dFormat != D3DFMT_INTZ); // We should never get here for depth textures
if (mWidth != 0 && mHeight != 0)
{
int levelToFetch = 0;
GLsizei requestWidth = mWidth;
GLsizei requestHeight = mHeight;
gl::MakeValidSize(true, gl::IsCompressed(mInternalFormat), &requestWidth, &requestHeight, &levelToFetch);
IDirect3DDevice9 *device = mRenderer->getDevice();
HRESULT result = device->CreateTexture(requestWidth, requestHeight, levelToFetch + 1, 0, d3dFormat,
poolToUse, &newTexture, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
ERR("Creating image surface failed.");
return gl::error(GL_OUT_OF_MEMORY);
}
newTexture->GetSurfaceLevel(levelToFetch, &newSurface);
newTexture->Release();
}
mSurface = newSurface;
mDirty = false;
mD3DPool = poolToUse;
}
HRESULT Image9::lock(D3DLOCKED_RECT *lockedRect, const RECT *rect)
{
createSurface();
HRESULT result = D3DERR_INVALIDCALL;
if (mSurface)
{
result = mSurface->LockRect(lockedRect, rect, 0);
ASSERT(SUCCEEDED(result));
mDirty = true;
}
return result;
}
void Image9::unlock()
{
if (mSurface)
{
HRESULT result = mSurface->UnlockRect();
ASSERT(SUCCEEDED(result));
}
}
bool Image9::isRenderableFormat() const
{
return TextureStorage9::IsTextureFormatRenderable(getD3DFormat());
}
D3DFORMAT Image9::getD3DFormat() const
{
// this should only happen if the image hasn't been redefined first
// which would be a bug by the caller
ASSERT(mD3DFormat != D3DFMT_UNKNOWN);
return mD3DFormat;
}
IDirect3DSurface9 *Image9::getSurface()
{
createSurface();
return mSurface;
}
void Image9::setManagedSurface(TextureStorageInterface2D *storage, int level)
{
TextureStorage9_2D *storage9 = TextureStorage9_2D::makeTextureStorage9_2D(storage->getStorageInstance());
setManagedSurface(storage9->getSurfaceLevel(level, false));
}
void Image9::setManagedSurface(TextureStorageInterfaceCube *storage, int face, int level)
{
TextureStorage9_Cube *storage9 = TextureStorage9_Cube::makeTextureStorage9_Cube(storage->getStorageInstance());
setManagedSurface(storage9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, false));
}
void Image9::setManagedSurface(IDirect3DSurface9 *surface)
{
D3DSURFACE_DESC desc;
surface->GetDesc(&desc);
ASSERT(desc.Pool == D3DPOOL_MANAGED);
if ((GLsizei)desc.Width == mWidth && (GLsizei)desc.Height == mHeight)
{
if (mSurface)
{
copyLockableSurfaces(surface, mSurface);
mSurface->Release();
}
mSurface = surface;
mD3DPool = desc.Pool;
}
}
bool Image9::updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
ASSERT(getSurface() != NULL);
TextureStorage9_2D *storage9 = TextureStorage9_2D::makeTextureStorage9_2D(storage->getStorageInstance());
return updateSurface(storage9->getSurfaceLevel(level, true), xoffset, yoffset, width, height);
}
bool Image9::updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
ASSERT(getSurface() != NULL);
TextureStorage9_Cube *storage9 = TextureStorage9_Cube::makeTextureStorage9_Cube(storage->getStorageInstance());
return updateSurface(storage9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, true), xoffset, yoffset, width, height);
}
bool Image9::updateSurface(IDirect3DSurface9 *destSurface, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
if (!destSurface)
return false;
IDirect3DSurface9 *sourceSurface = getSurface();
if (sourceSurface && sourceSurface != destSurface)
{
RECT rect;
rect.left = xoffset;
rect.top = yoffset;
rect.right = xoffset + width;
rect.bottom = yoffset + height;
POINT point = {rect.left, rect.top};
IDirect3DDevice9 *device = mRenderer->getDevice();
if (mD3DPool == D3DPOOL_MANAGED)
{
D3DSURFACE_DESC desc;
sourceSurface->GetDesc(&desc);
IDirect3DSurface9 *surf = 0;
HRESULT result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
if (SUCCEEDED(result))
{
copyLockableSurfaces(surf, sourceSurface);
result = device->UpdateSurface(surf, &rect, destSurface, &point);
ASSERT(SUCCEEDED(result));
surf->Release();
}
}
else
{
// UpdateSurface: source must be SYSTEMMEM, dest must be DEFAULT pools
HRESULT result = device->UpdateSurface(sourceSurface, &rect, destSurface, &point);
ASSERT(SUCCEEDED(result));
}
}
destSurface->Release();
return true;
}
// Store the pixel rectangle designated by xoffset,yoffset,width,height with pixels stored as format/type at input
// into the target pixel rectangle.
void Image9::loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input)
{
RECT lockRect =
{
xoffset, yoffset,
xoffset + width, yoffset + height
};
D3DLOCKED_RECT locked;
HRESULT result = lock(&locked, &lockRect);
if (FAILED(result))
{
return;
}
GLsizei inputPitch = gl::ComputePitch(width, mInternalFormat, unpackAlignment);
switch (mInternalFormat)
{
case GL_ALPHA8_EXT:
if (gl::supportsSSE2())
{
loadAlphaDataToBGRASSE2(width, height, inputPitch, input, locked.Pitch, locked.pBits);
}
else
{
loadAlphaDataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
}
break;
case GL_LUMINANCE8_EXT:
loadLuminanceDataToNativeOrBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits, getD3DFormat() == D3DFMT_L8);
break;
case GL_ALPHA32F_EXT:
loadAlphaFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_LUMINANCE32F_EXT:
loadLuminanceFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_ALPHA16F_EXT:
loadAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_LUMINANCE16F_EXT:
loadLuminanceHalfFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_LUMINANCE8_ALPHA8_EXT:
loadLuminanceAlphaDataToNativeOrBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits, getD3DFormat() == D3DFMT_A8L8);
break;
case GL_LUMINANCE_ALPHA32F_EXT:
loadLuminanceAlphaFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_LUMINANCE_ALPHA16F_EXT:
loadLuminanceAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGB8_OES:
loadRGBUByteDataToBGRX(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGB565:
loadRGB565DataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGBA8_OES:
if (gl::supportsSSE2())
{
loadRGBAUByteDataToBGRASSE2(width, height, inputPitch, input, locked.Pitch, locked.pBits);
}
else
{
loadRGBAUByteDataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
}
break;
case GL_RGBA4:
loadRGBA4444DataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGB5_A1:
loadRGBA5551DataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_BGRA8_EXT:
loadBGRADataToBGRA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
// float textures are converted to RGBA, not BGRA, as they're stored that way in D3D
case GL_RGB32F_EXT:
loadRGBFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGB16F_EXT:
loadRGBHalfFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGBA32F_EXT:
loadRGBAFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
case GL_RGBA16F_EXT:
loadRGBAHalfFloatDataToRGBA(width, height, inputPitch, input, locked.Pitch, locked.pBits);
break;
default: UNREACHABLE();
}
unlock();
}
void Image9::loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input)
{
ASSERT(xoffset % 4 == 0);
ASSERT(yoffset % 4 == 0);
RECT lockRect = {
xoffset, yoffset,
xoffset + width, yoffset + height
};
D3DLOCKED_RECT locked;
HRESULT result = lock(&locked, &lockRect);
if (FAILED(result))
{
return;
}
GLsizei inputSize = gl::ComputeCompressedSize(width, height, mInternalFormat);
GLsizei inputPitch = gl::ComputeCompressedPitch(width, mInternalFormat);
int rows = inputSize / inputPitch;
for (int i = 0; i < rows; ++i)
{
memcpy((void*)((BYTE*)locked.pBits + i * locked.Pitch), (void*)((BYTE*)input + i * inputPitch), inputPitch);
}
unlock();
}
// This implements glCopyTex[Sub]Image2D for non-renderable internal texture formats and incomplete textures
void Image9::copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source)
{
RenderTarget9 *renderTarget = NULL;
IDirect3DSurface9 *surface = NULL;
gl::Renderbuffer *colorbuffer = source->getColorbuffer(0);
if (colorbuffer)
{
renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
}
if (renderTarget)
{
surface = renderTarget->getSurface();
}
if (!surface)
{
ERR("Failed to retrieve the render target.");
return gl::error(GL_OUT_OF_MEMORY);
}
IDirect3DDevice9 *device = mRenderer->getDevice();
IDirect3DSurface9 *renderTargetData = NULL;
D3DSURFACE_DESC description;
surface->GetDesc(&description);
HRESULT result = device->CreateOffscreenPlainSurface(description.Width, description.Height, description.Format, D3DPOOL_SYSTEMMEM, &renderTargetData, NULL);
if (FAILED(result))
{
ERR("Could not create matching destination surface.");
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
result = device->GetRenderTargetData(surface, renderTargetData);
if (FAILED(result))
{
ERR("GetRenderTargetData unexpectedly failed.");
renderTargetData->Release();
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
RECT sourceRect = {x, y, x + width, y + height};
RECT destRect = {xoffset, yoffset, xoffset + width, yoffset + height};
D3DLOCKED_RECT sourceLock = {0};
result = renderTargetData->LockRect(&sourceLock, &sourceRect, 0);
if (FAILED(result))
{
ERR("Failed to lock the source surface (rectangle might be invalid).");
renderTargetData->Release();
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
D3DLOCKED_RECT destLock = {0};
result = lock(&destLock, &destRect);
if (FAILED(result))
{
ERR("Failed to lock the destination surface (rectangle might be invalid).");
renderTargetData->UnlockRect();
renderTargetData->Release();
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
if (destLock.pBits && sourceLock.pBits)
{
unsigned char *source = (unsigned char*)sourceLock.pBits;
unsigned char *dest = (unsigned char*)destLock.pBits;
switch (description.Format)
{
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
switch(getD3DFormat())
{
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
for(int y = 0; y < height; y++)
{
memcpy(dest, source, 4 * width);
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_L8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
dest[x] = source[x * 4 + 2];
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_A8L8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
dest[x * 2 + 0] = source[x * 4 + 2];
dest[x * 2 + 1] = source[x * 4 + 3];
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
default:
UNREACHABLE();
}
break;
case D3DFMT_R5G6B5:
switch(getD3DFormat())
{
case D3DFMT_X8R8G8B8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned short rgb = ((unsigned short*)source)[x];
unsigned char red = (rgb & 0xF800) >> 8;
unsigned char green = (rgb & 0x07E0) >> 3;
unsigned char blue = (rgb & 0x001F) << 3;
dest[x + 0] = blue | (blue >> 5);
dest[x + 1] = green | (green >> 6);
dest[x + 2] = red | (red >> 5);
dest[x + 3] = 0xFF;
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_L8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned char red = source[x * 2 + 1] & 0xF8;
dest[x] = red | (red >> 5);
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
default:
UNREACHABLE();
}
break;
case D3DFMT_A1R5G5B5:
switch(getD3DFormat())
{
case D3DFMT_X8R8G8B8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned short argb = ((unsigned short*)source)[x];
unsigned char red = (argb & 0x7C00) >> 7;
unsigned char green = (argb & 0x03E0) >> 2;
unsigned char blue = (argb & 0x001F) << 3;
dest[x + 0] = blue | (blue >> 5);
dest[x + 1] = green | (green >> 5);
dest[x + 2] = red | (red >> 5);
dest[x + 3] = 0xFF;
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_A8R8G8B8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned short argb = ((unsigned short*)source)[x];
unsigned char red = (argb & 0x7C00) >> 7;
unsigned char green = (argb & 0x03E0) >> 2;
unsigned char blue = (argb & 0x001F) << 3;
unsigned char alpha = (signed short)argb >> 15;
dest[x + 0] = blue | (blue >> 5);
dest[x + 1] = green | (green >> 5);
dest[x + 2] = red | (red >> 5);
dest[x + 3] = alpha;
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_L8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned char red = source[x * 2 + 1] & 0x7C;
dest[x] = (red << 1) | (red >> 4);
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
case D3DFMT_A8L8:
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
unsigned char red = source[x * 2 + 1] & 0x7C;
dest[x * 2 + 0] = (red << 1) | (red >> 4);
dest[x * 2 + 1] = (signed char)source[x * 2 + 1] >> 7;
}
source += sourceLock.Pitch;
dest += destLock.Pitch;
}
break;
default:
UNREACHABLE();
}
break;
default:
UNREACHABLE();
}
}
unlock();
renderTargetData->UnlockRect();
renderTargetData->Release();
surface->Release();
mDirty = true;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/Image9.cpp | C++ | bsd | 23,753 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage9.cpp Defines the BufferStorage9 class.
#include "libGLESv2/renderer/BufferStorage9.h"
#include "common/debug.h"
namespace rx
{
BufferStorage9::BufferStorage9()
{
mMemory = NULL;
mAllocatedSize = 0;
mSize = 0;
}
BufferStorage9::~BufferStorage9()
{
delete[] mMemory;
}
BufferStorage9 *BufferStorage9::makeBufferStorage9(BufferStorage *bufferStorage)
{
ASSERT(HAS_DYNAMIC_TYPE(BufferStorage9*, bufferStorage));
return static_cast<BufferStorage9*>(bufferStorage);
}
void *BufferStorage9::getData()
{
return mMemory;
}
void BufferStorage9::setData(const void* data, unsigned int size, unsigned int offset)
{
if (!mMemory || offset + size > mAllocatedSize)
{
unsigned int newAllocatedSize = offset + size;
void *newMemory = new char[newAllocatedSize];
if (offset > 0 && mMemory && mAllocatedSize > 0)
{
memcpy(newMemory, mMemory, std::min(offset, mAllocatedSize));
}
delete[] mMemory;
mMemory = newMemory;
mAllocatedSize = newAllocatedSize;
}
mSize = std::max(mSize, offset + size);
memcpy(reinterpret_cast<char*>(mMemory) + offset, data, size);
}
void BufferStorage9::clear()
{
mSize = 0;
}
unsigned int BufferStorage9::getSize() const
{
return mSize;
}
bool BufferStorage9::supportsDirectBinding() const
{
return false;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage9.cpp | C++ | bsd | 1,593 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderTarget9.h: Defines a D3D9-specific wrapper for IDirect3DSurface9 pointers
// retained by Renderbuffers.
#ifndef LIBGLESV2_RENDERER_RENDERTARGET9_H_
#define LIBGLESV2_RENDERER_RENDERTARGET9_H_
#include "libGLESv2/renderer/RenderTarget.h"
namespace rx
{
class Renderer;
class Renderer9;
class RenderTarget9 : public RenderTarget
{
public:
RenderTarget9(Renderer *renderer, IDirect3DSurface9 *surface);
RenderTarget9(Renderer *renderer, GLsizei width, GLsizei height, GLenum format, GLsizei samples);
virtual ~RenderTarget9();
static RenderTarget9 *makeRenderTarget9(RenderTarget *renderTarget);
IDirect3DSurface9 *getSurface();
private:
DISALLOW_COPY_AND_ASSIGN(RenderTarget9);
IDirect3DSurface9 *mRenderTarget;
Renderer9 *mRenderer;
};
}
#endif // LIBGLESV2_RENDERER_RENDERTARGET9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/RenderTarget9.h | C++ | bsd | 1,019 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexBuffer11.cpp: Defines the D3D11 IndexBuffer implementation.
#include "libGLESv2/renderer/IndexBuffer11.h"
#include "libGLESv2/renderer/Renderer11.h"
namespace rx
{
IndexBuffer11::IndexBuffer11(Renderer11 *const renderer) : mRenderer(renderer)
{
mBuffer = NULL;
mBufferSize = 0;
mDynamicUsage = false;
}
IndexBuffer11::~IndexBuffer11()
{
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
}
}
bool IndexBuffer11::initialize(unsigned int bufferSize, GLenum indexType, bool dynamic)
{
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
}
updateSerial();
if (bufferSize > 0)
{
ID3D11Device* dxDevice = mRenderer->getDevice();
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = bufferSize;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
HRESULT result = dxDevice->CreateBuffer(&bufferDesc, NULL, &mBuffer);
if (FAILED(result))
{
return false;
}
}
mBufferSize = bufferSize;
mIndexType = indexType;
mDynamicUsage = dynamic;
return true;
}
IndexBuffer11 *IndexBuffer11::makeIndexBuffer11(IndexBuffer *indexBuffer)
{
ASSERT(HAS_DYNAMIC_TYPE(IndexBuffer11*, indexBuffer));
return static_cast<IndexBuffer11*>(indexBuffer);
}
bool IndexBuffer11::mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory)
{
if (mBuffer)
{
if (offset + size > mBufferSize)
{
ERR("Index buffer map range is not inside the buffer.");
return false;
}
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
if (FAILED(result))
{
ERR("Index buffer map failed with error 0x%08x", result);
return false;
}
*outMappedMemory = reinterpret_cast<char*>(mappedResource.pData) + offset;
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
bool IndexBuffer11::unmapBuffer()
{
if (mBuffer)
{
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
dxContext->Unmap(mBuffer, 0);
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
GLenum IndexBuffer11::getIndexType() const
{
return mIndexType;
}
unsigned int IndexBuffer11::getBufferSize() const
{
return mBufferSize;
}
bool IndexBuffer11::setSize(unsigned int bufferSize, GLenum indexType)
{
if (bufferSize > mBufferSize || indexType != mIndexType)
{
return initialize(bufferSize, indexType, mDynamicUsage);
}
else
{
return true;
}
}
bool IndexBuffer11::discard()
{
if (mBuffer)
{
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Index buffer map failed with error 0x%08x", result);
return false;
}
dxContext->Unmap(mBuffer, 0);
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
DXGI_FORMAT IndexBuffer11::getIndexFormat() const
{
switch (mIndexType)
{
case GL_UNSIGNED_BYTE: return DXGI_FORMAT_R16_UINT;
case GL_UNSIGNED_SHORT: return DXGI_FORMAT_R16_UINT;
case GL_UNSIGNED_INT: return DXGI_FORMAT_R32_UINT;
default: UNREACHABLE(); return DXGI_FORMAT_UNKNOWN;
}
}
ID3D11Buffer *IndexBuffer11::getBuffer() const
{
return mBuffer;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer11.cpp | C++ | bsd | 4,241 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.h: Defines a helper class to construct and cache vertex declarations.
#ifndef LIBGLESV2_RENDERER_VERTEXDECLARATIONCACHE_H_
#define LIBGLESV2_RENDERER_VERTEXDECLARATIONCACHE_H_
#include "libGLESv2/renderer/VertexDataManager.h"
namespace gl
{
class VertexDataManager;
}
namespace rx
{
class VertexDeclarationCache
{
public:
VertexDeclarationCache();
~VertexDeclarationCache();
GLenum applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw);
void markStateDirty();
private:
UINT mMaxLru;
enum { NUM_VERTEX_DECL_CACHE_ENTRIES = 32 };
struct VBData
{
unsigned int serial;
unsigned int stride;
unsigned int offset;
};
VBData mAppliedVBs[gl::MAX_VERTEX_ATTRIBS];
IDirect3DVertexDeclaration9 *mLastSetVDecl;
bool mInstancingEnabled;
struct VertexDeclCacheEntry
{
D3DVERTEXELEMENT9 cachedElements[gl::MAX_VERTEX_ATTRIBS + 1];
UINT lruCount;
IDirect3DVertexDeclaration9 *vertexDeclaration;
} mVertexDeclCache[NUM_VERTEX_DECL_CACHE_ENTRIES];
};
}
#endif // LIBGLESV2_RENDERER_VERTEXDECLARATIONCACHE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexDeclarationCache.h | C++ | bsd | 1,419 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain9.cpp: Implements a back-end specific class for the D3D9 swap chain.
#include "libGLESv2/renderer/SwapChain9.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/Renderer9.h"
namespace rx
{
SwapChain9::SwapChain9(Renderer9 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat)
: mRenderer(renderer), SwapChain(window, shareHandle, backBufferFormat, depthBufferFormat)
{
mSwapChain = NULL;
mBackBuffer = NULL;
mDepthStencil = NULL;
mRenderTarget = NULL;
mOffscreenTexture = NULL;
mWidth = -1;
mHeight = -1;
mSwapInterval = -1;
}
SwapChain9::~SwapChain9()
{
release();
}
void SwapChain9::release()
{
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
if (mRenderTarget)
{
mRenderTarget->Release();
mRenderTarget = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mWindow)
mShareHandle = NULL;
}
static DWORD convertInterval(EGLint interval)
{
switch(interval)
{
case 0: return D3DPRESENT_INTERVAL_IMMEDIATE;
case 1: return D3DPRESENT_INTERVAL_ONE;
case 2: return D3DPRESENT_INTERVAL_TWO;
case 3: return D3DPRESENT_INTERVAL_THREE;
case 4: return D3DPRESENT_INTERVAL_FOUR;
default: UNREACHABLE();
}
return D3DPRESENT_INTERVAL_DEFAULT;
}
EGLint SwapChain9::resize(int backbufferWidth, int backbufferHeight)
{
// D3D9 does not support resizing swap chains without recreating them
return reset(backbufferWidth, backbufferHeight, mSwapInterval);
}
EGLint SwapChain9::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return EGL_BAD_ACCESS;
}
// Evict all non-render target textures to system memory and release all resources
// before reallocating them to free up as much video memory as possible.
device->EvictManagedResources();
HRESULT result;
// Release specific resources to free up memory for the new render target, while the
// old render target still exists for the purpose of preserving its contents.
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
HANDLE *pShareHandle = NULL;
if (!mWindow && mRenderer->getShareHandleSupport())
{
pShareHandle = &mShareHandle;
}
result = device->CreateTexture(backbufferWidth, backbufferHeight, 1, D3DUSAGE_RENDERTARGET,
gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat), D3DPOOL_DEFAULT,
&mOffscreenTexture, pShareHandle);
if (FAILED(result))
{
ERR("Could not create offscreen texture: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
IDirect3DSurface9 *oldRenderTarget = mRenderTarget;
result = mOffscreenTexture->GetSurfaceLevel(0, &mRenderTarget);
ASSERT(SUCCEEDED(result));
if (oldRenderTarget)
{
RECT rect =
{
0, 0,
mWidth, mHeight
};
if (rect.right > static_cast<LONG>(backbufferWidth))
{
rect.right = backbufferWidth;
}
if (rect.bottom > static_cast<LONG>(backbufferHeight))
{
rect.bottom = backbufferHeight;
}
mRenderer->endScene();
result = device->StretchRect(oldRenderTarget, &rect, mRenderTarget, &rect, D3DTEXF_NONE);
ASSERT(SUCCEEDED(result));
oldRenderTarget->Release();
}
if (mWindow)
{
D3DPRESENT_PARAMETERS presentParameters = {0};
presentParameters.AutoDepthStencilFormat = gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat);
presentParameters.BackBufferCount = 1;
presentParameters.BackBufferFormat = gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat);
presentParameters.EnableAutoDepthStencil = FALSE;
presentParameters.Flags = 0;
presentParameters.hDeviceWindow = mWindow;
presentParameters.MultiSampleQuality = 0; // FIXME: Unimplemented
presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE; // FIXME: Unimplemented
presentParameters.PresentationInterval = convertInterval(swapInterval);
presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
presentParameters.Windowed = TRUE;
presentParameters.BackBufferWidth = backbufferWidth;
presentParameters.BackBufferHeight = backbufferHeight;
// http://crbug.com/140239
// http://crbug.com/143434
//
// Some AMD/Intel switchable systems / drivers appear to round swap chain surfaces to a multiple of 64 pixels in width
// when using the integrated Intel. This rounds the width up rather than down.
//
// Some non-switchable AMD GPUs / drivers do not respect the source rectangle to Present. Therefore, when the vendor ID
// is not Intel, the back buffer width must be exactly the same width as the window or horizontal scaling will occur.
if (mRenderer->getAdapterVendor() == VENDOR_ID_INTEL)
{
presentParameters.BackBufferWidth = (presentParameters.BackBufferWidth + 63) / 64 * 64;
}
result = device->CreateAdditionalSwapChain(&presentParameters, &mSwapChain);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL || result == D3DERR_DEVICELOST);
ERR("Could not create additional swap chains or offscreen surfaces: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
InvalidateRect(mWindow, NULL, FALSE);
}
if (mDepthBufferFormat != GL_NONE)
{
result = device->CreateDepthStencilSurface(backbufferWidth, backbufferHeight,
gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat),
D3DMULTISAMPLE_NONE, 0, FALSE, &mDepthStencil, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL);
ERR("Could not create depthstencil surface for new swap chain: 0x%08X", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapInterval = swapInterval;
return EGL_SUCCESS;
}
// parameters should be validated/clamped by caller
EGLint SwapChain9::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return EGL_SUCCESS;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
// Disable all pipeline operations
device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
device->SetPixelShader(NULL);
device->SetVertexShader(NULL);
device->SetRenderTarget(0, mBackBuffer);
device->SetDepthStencilSurface(NULL);
device->SetTexture(0, mOffscreenTexture);
device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
device->SetViewport(&viewport);
float x1 = x - 0.5f;
float y1 = (mHeight - y - height) - 0.5f;
float x2 = (x + width) - 0.5f;
float y2 = (mHeight - y) - 0.5f;
float u1 = x / float(mWidth);
float v1 = y / float(mHeight);
float u2 = (x + width) / float(mWidth);
float v2 = (y + height) / float(mHeight);
float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
{x2, y1, 0.0f, 1.0f, u2, v2},
{x2, y2, 0.0f, 1.0f, u2, v1},
{x1, y2, 0.0f, 1.0f, u1, v1}}; // x, y, z, rhw, u, v
mRenderer->startScene();
device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
mRenderer->endScene();
device->SetTexture(0, NULL);
RECT rect =
{
x, mHeight - y - height,
x + width, mHeight - y
};
HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);
mRenderer->markAllStateDirty();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
{
return EGL_BAD_ALLOC;
}
ASSERT(SUCCEEDED(result));
return EGL_SUCCESS;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getRenderTarget()
{
if (mRenderTarget)
{
mRenderTarget->AddRef();
}
return mRenderTarget;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getDepthStencil()
{
if (mDepthStencil)
{
mDepthStencil->AddRef();
}
return mDepthStencil;
}
// Increments refcount on texture.
// caller must Release() the returned texture
IDirect3DTexture9 *SwapChain9::getOffscreenTexture()
{
if (mOffscreenTexture)
{
mOffscreenTexture->AddRef();
}
return mOffscreenTexture;
}
SwapChain9 *SwapChain9::makeSwapChain9(SwapChain *swapChain)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::SwapChain9*, swapChain));
return static_cast<rx::SwapChain9*>(swapChain);
}
void SwapChain9::recreate()
{
if (!mSwapChain)
{
return;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return;
}
D3DPRESENT_PARAMETERS presentParameters;
HRESULT result = mSwapChain->GetPresentParameters(&presentParameters);
ASSERT(SUCCEEDED(result));
IDirect3DSwapChain9* newSwapChain = NULL;
result = device->CreateAdditionalSwapChain(&presentParameters, &newSwapChain);
if (FAILED(result))
{
return;
}
mSwapChain->Release();
mSwapChain = newSwapChain;
mBackBuffer->Release();
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/SwapChain9.cpp | C++ | bsd | 12,634 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer11.h: Defines a back-end specific class for the D3D11 renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER11_H_
#define LIBGLESV2_RENDERER_RENDERER11_H_
#include "common/angleutils.h"
#include "libGLESv2/angletypes.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/RenderStateCache.h"
#include "libGLESv2/renderer/InputLayoutCache.h"
#include "libGLESv2/renderer/RenderTarget.h"
namespace gl
{
class Renderbuffer;
}
namespace rx
{
class VertexDataManager;
class IndexDataManager;
class StreamingIndexBufferInterface;
enum
{
MAX_VERTEX_UNIFORM_VECTORS_D3D11 = 1024,
MAX_FRAGMENT_UNIFORM_VECTORS_D3D11 = 1024
};
class Renderer11 : public Renderer
{
public:
Renderer11(egl::Display *display, HDC hDc);
virtual ~Renderer11();
static Renderer11 *makeRenderer11(Renderer *renderer);
virtual EGLint initialize();
virtual bool resetDevice();
virtual int generateConfigs(ConfigDesc **configDescList);
virtual void deleteConfigs(ConfigDesc *configDescList);
virtual void sync(bool block);
virtual SwapChain *createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat);
virtual void setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &sampler);
virtual void setTexture(gl::SamplerType type, int index, gl::Texture *texture);
virtual void setRasterizerState(const gl::RasterizerState &rasterState);
virtual void setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask);
virtual void setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW);
virtual void setScissorRectangle(const gl::Rectangle &scissor, bool enabled);
virtual bool setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport);
virtual bool applyPrimitiveType(GLenum mode, GLsizei count);
virtual bool applyRenderTarget(gl::Framebuffer *frameBuffer);
virtual void applyShaders(gl::ProgramBinary *programBinary);
virtual void applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray);
virtual GLenum applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances);
virtual GLenum applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo);
virtual void drawArrays(GLenum mode, GLsizei count, GLsizei instances);
virtual void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances);
virtual void clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer);
virtual void markAllStateDirty();
// lost device
void notifyDeviceLost();
virtual bool isDeviceLost();
virtual bool testDeviceLost(bool notify);
virtual bool testDeviceResettable();
// Renderer capabilities
virtual DWORD getAdapterVendor() const;
virtual std::string getRendererDescription() const;
virtual GUID getAdapterIdentifier() const;
virtual bool getBGRATextureSupport() const;
virtual bool getDXT1TextureSupport();
virtual bool getDXT3TextureSupport();
virtual bool getDXT5TextureSupport();
virtual bool getEventQuerySupport();
virtual bool getFloat32TextureSupport(bool *filtering, bool *renderable);
virtual bool getFloat16TextureSupport(bool *filtering, bool *renderable);
virtual bool getLuminanceTextureSupport();
virtual bool getLuminanceAlphaTextureSupport();
virtual unsigned int getMaxVertexTextureImageUnits() const;
virtual unsigned int getMaxCombinedTextureImageUnits() const;
virtual unsigned int getReservedVertexUniformVectors() const;
virtual unsigned int getReservedFragmentUniformVectors() const;
virtual unsigned int getMaxVertexUniformVectors() const;
virtual unsigned int getMaxFragmentUniformVectors() const;
virtual unsigned int getMaxVaryingVectors() const;
virtual bool getNonPower2TextureSupport() const;
virtual bool getDepthTextureSupport() const;
virtual bool getOcclusionQuerySupport() const;
virtual bool getInstancingSupport() const;
virtual bool getTextureFilterAnisotropySupport() const;
virtual float getTextureMaxAnisotropy() const;
virtual bool getShareHandleSupport() const;
virtual bool getDerivativeInstructionSupport() const;
virtual bool getPostSubBufferSupport() const;
virtual int getMajorShaderModel() const;
virtual float getMaxPointSize() const;
virtual int getMaxViewportDimension() const;
virtual int getMaxTextureWidth() const;
virtual int getMaxTextureHeight() const;
virtual bool get32BitIndexSupport() const;
virtual int getMinSwapInterval() const;
virtual int getMaxSwapInterval() const;
virtual GLsizei getMaxSupportedSamples() const;
int getNearestSupportedSamples(DXGI_FORMAT format, unsigned int requested) const;
virtual unsigned int getMaxRenderTargets() const;
// Pixel operations
virtual bool copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source);
virtual bool copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source);
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level);
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level);
bool copyTexture(ID3D11ShaderResourceView *source, const gl::Rectangle &sourceArea, unsigned int sourceWidth, unsigned int sourceHeight,
ID3D11RenderTargetView *dest, const gl::Rectangle &destArea, unsigned int destWidth, unsigned int destHeight, GLenum destFormat);
virtual bool blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil);
virtual void readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels);
// RenderTarget creation
virtual RenderTarget *createRenderTarget(SwapChain *swapChain, bool depth);
virtual RenderTarget *createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth);
// Shader operations
virtual ShaderExecutable *loadExecutable(const void *function, size_t length, rx::ShaderType type);
virtual ShaderExecutable *compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type);
// Image operations
virtual Image *createImage();
virtual void generateMipmap(Image *dest, Image *source);
virtual TextureStorage *createTextureStorage2D(SwapChain *swapChain);
virtual TextureStorage *createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual TextureStorage *createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
// Buffer creation
virtual VertexBuffer *createVertexBuffer();
virtual IndexBuffer *createIndexBuffer();
virtual BufferStorage *createBufferStorage();
// Query and Fence creation
virtual QueryImpl *createQuery(GLenum type);
virtual FenceImpl *createFence();
// D3D11-renderer specific methods
ID3D11Device *getDevice() { return mDevice; }
ID3D11DeviceContext *getDeviceContext() { return mDeviceContext; };
IDXGIFactory *getDxgiFactory() { return mDxgiFactory; };
bool getRenderTargetResource(gl::Renderbuffer *colorbuffer, unsigned int *subresourceIndex, ID3D11Texture2D **resource);
void unapplyRenderTargets();
void setOneTimeRenderTarget(ID3D11RenderTargetView *renderTargetView);
virtual bool getLUID(LUID *adapterLuid) const;
private:
DISALLOW_COPY_AND_ASSIGN(Renderer11);
void drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer);
void drawTriangleFan(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer, int instances);
void readTextureData(ID3D11Texture2D *texture, unsigned int subResource, const gl::Rectangle &area,
GLenum format, GLenum type, GLsizei outputPitch, bool packReverseRowOrder,
GLint packAlignment, void *pixels);
void maskedClear(const gl::ClearParameters &clearParams, bool usingExtendedDrawBuffers);
rx::Range getViewportBounds() const;
bool blitRenderbufferRect(const gl::Rectangle &readRect, const gl::Rectangle &drawRect, RenderTarget *readRenderTarget,
RenderTarget *drawRenderTarget, bool wholeBufferCopy);
ID3D11Texture2D *resolveMultisampledTexture(ID3D11Texture2D *source, unsigned int subresource);
HMODULE mD3d11Module;
HMODULE mDxgiModule;
HDC mDc;
bool mDeviceLost;
void initializeDevice();
void releaseDeviceResources();
int getMinorShaderModel() const;
void release();
RenderStateCache mStateCache;
// Support flags
bool mFloat16TextureSupport;
bool mFloat16FilterSupport;
bool mFloat16RenderSupport;
bool mFloat32TextureSupport;
bool mFloat32FilterSupport;
bool mFloat32RenderSupport;
bool mDXT1TextureSupport;
bool mDXT3TextureSupport;
bool mDXT5TextureSupport;
bool mDepthTextureSupport;
// Multisample format support
struct MultisampleSupportInfo
{
unsigned int qualityLevels[D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT];
};
typedef std::unordered_map<DXGI_FORMAT, MultisampleSupportInfo> MultisampleSupportMap;
MultisampleSupportMap mMultisampleSupportMap;
unsigned int mMaxSupportedSamples;
// current render target states
unsigned int mAppliedRenderTargetSerials[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS];
unsigned int mAppliedDepthbufferSerial;
unsigned int mAppliedStencilbufferSerial;
bool mDepthStencilInitialized;
bool mRenderTargetDescInitialized;
rx::RenderTarget::Desc mRenderTargetDesc;
unsigned int mCurDepthSize;
unsigned int mCurStencilSize;
// Currently applied sampler states
bool mForceSetVertexSamplerStates[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
gl::SamplerState mCurVertexSamplerStates[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
bool mForceSetPixelSamplerStates[gl::MAX_TEXTURE_IMAGE_UNITS];
gl::SamplerState mCurPixelSamplerStates[gl::MAX_TEXTURE_IMAGE_UNITS];
// Currently applied textures
unsigned int mCurVertexTextureSerials[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
unsigned int mCurPixelTextureSerials[gl::MAX_TEXTURE_IMAGE_UNITS];
// Currently applied blend state
bool mForceSetBlendState;
gl::BlendState mCurBlendState;
gl::Color mCurBlendColor;
unsigned int mCurSampleMask;
// Currently applied rasterizer state
bool mForceSetRasterState;
gl::RasterizerState mCurRasterState;
// Currently applied depth stencil state
bool mForceSetDepthStencilState;
gl::DepthStencilState mCurDepthStencilState;
int mCurStencilRef;
int mCurStencilBackRef;
// Currently applied scissor rectangle
bool mForceSetScissor;
bool mScissorEnabled;
gl::Rectangle mCurScissor;
// Currently applied viewport
bool mForceSetViewport;
gl::Rectangle mCurViewport;
float mCurNear;
float mCurFar;
unsigned int mAppliedIBSerial;
unsigned int mAppliedStorageIBSerial;
unsigned int mAppliedIBOffset;
unsigned int mAppliedProgramBinarySerial;
bool mIsGeometryShaderActive;
dx_VertexConstants mVertexConstants;
dx_VertexConstants mAppliedVertexConstants;
ID3D11Buffer *mDriverConstantBufferVS;
dx_PixelConstants mPixelConstants;
dx_PixelConstants mAppliedPixelConstants;
ID3D11Buffer *mDriverConstantBufferPS;
// Vertex, index and input layouts
VertexDataManager *mVertexDataManager;
IndexDataManager *mIndexDataManager;
InputLayoutCache mInputLayoutCache;
StreamingIndexBufferInterface *mLineLoopIB;
StreamingIndexBufferInterface *mTriangleFanIB;
// Texture copy resources
bool mCopyResourcesInitialized;
ID3D11Buffer *mCopyVB;
ID3D11SamplerState *mCopySampler;
ID3D11InputLayout *mCopyIL;
ID3D11VertexShader *mCopyVS;
ID3D11PixelShader *mCopyRGBAPS;
ID3D11PixelShader *mCopyRGBPS;
ID3D11PixelShader *mCopyLumPS;
ID3D11PixelShader *mCopyLumAlphaPS;
// Masked clear resources
bool mClearResourcesInitialized;
ID3D11Buffer *mClearVB;
ID3D11InputLayout *mClearIL;
ID3D11VertexShader *mClearVS;
ID3D11PixelShader *mClearSinglePS;
ID3D11PixelShader *mClearMultiplePS;
ID3D11RasterizerState *mClearScissorRS;
ID3D11RasterizerState *mClearNoScissorRS;
// Sync query
ID3D11Query *mSyncQuery;
ID3D11Device *mDevice;
D3D_FEATURE_LEVEL mFeatureLevel;
ID3D11DeviceContext *mDeviceContext;
IDXGIAdapter *mDxgiAdapter;
DXGI_ADAPTER_DESC mAdapterDescription;
char mDescription[128];
IDXGIFactory *mDxgiFactory;
// Cached device caps
bool mBGRATextureSupport;
};
}
#endif // LIBGLESV2_RENDERER_RENDERER11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Renderer11.h | C++ | bsd | 14,177 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Blit.cpp: Surface copy utility class.
#ifndef LIBGLESV2_BLIT_H_
#define LIBGLESV2_BLIT_H_
#include "common/angleutils.h"
namespace gl
{
class Framebuffer;
}
namespace rx
{
class Renderer9;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class Blit
{
public:
explicit Blit(Renderer9 *renderer);
~Blit();
// Copy from source surface to dest surface.
// sourceRect, xoffset, yoffset are in D3D coordinates (0,0 in upper-left)
bool copy(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level);
bool copy(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level);
// Copy from source surface to dest surface.
// sourceRect, xoffset, yoffset are in D3D coordinates (0,0 in upper-left)
// source is interpreted as RGBA and destFormat specifies the desired result format. For example, if destFormat = GL_RGB, the alpha channel will be forced to 0.
bool formatConvert(IDirect3DSurface9 *source, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, IDirect3DSurface9 *dest);
// 2x2 box filter sample from source to dest.
// Requires that source is RGB(A) and dest has the same format as source.
bool boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest);
private:
rx::Renderer9 *mRenderer;
IDirect3DVertexBuffer9 *mQuadVertexBuffer;
IDirect3DVertexDeclaration9 *mQuadVertexDeclaration;
void initGeometry();
bool setFormatConvertShaders(GLenum destFormat);
bool copy(IDirect3DSurface9 *source, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, IDirect3DSurface9 *dest);
IDirect3DTexture9 *copySurfaceToTexture(IDirect3DSurface9 *surface, const RECT &sourceRect);
void setViewport(const RECT &sourceRect, GLint xoffset, GLint yoffset);
void setCommonBlitState();
RECT getSurfaceRect(IDirect3DSurface9 *surface) const;
// This enum is used to index mCompiledShaders and mShaderSource.
enum ShaderId
{
SHADER_VS_STANDARD,
SHADER_VS_FLIPY,
SHADER_PS_PASSTHROUGH,
SHADER_PS_LUMINANCE,
SHADER_PS_COMPONENTMASK,
SHADER_COUNT
};
// This actually contains IDirect3DVertexShader9 or IDirect3DPixelShader9 casted to IUnknown.
IUnknown *mCompiledShaders[SHADER_COUNT];
template <class D3DShaderType>
bool setShader(ShaderId source, const char *profile,
D3DShaderType *(Renderer9::*createShader)(const DWORD *, size_t length),
HRESULT (WINAPI IDirect3DDevice9::*setShader)(D3DShaderType*));
bool setVertexShader(ShaderId shader);
bool setPixelShader(ShaderId shader);
void render();
void saveState();
void restoreState();
IDirect3DStateBlock9 *mSavedStateBlock;
IDirect3DSurface9 *mSavedRenderTarget;
IDirect3DSurface9 *mSavedDepthStencil;
DISALLOW_COPY_AND_ASSIGN(Blit);
};
}
#endif // LIBGLESV2_BLIT_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Blit.h | C++ | bsd | 3,320 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderExecutable9.cpp: Implements a D3D9-specific class to contain shader
// executable implementation details.
#include "libGLESv2/renderer/ShaderExecutable9.h"
#include "common/debug.h"
namespace rx
{
ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DPixelShader9 *executable)
: ShaderExecutable(function, length)
{
mPixelExecutable = executable;
mVertexExecutable = NULL;
}
ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DVertexShader9 *executable)
: ShaderExecutable(function, length)
{
mVertexExecutable = executable;
mPixelExecutable = NULL;
}
ShaderExecutable9::~ShaderExecutable9()
{
if (mVertexExecutable)
{
mVertexExecutable->Release();
}
if (mPixelExecutable)
{
mPixelExecutable->Release();
}
}
ShaderExecutable9 *ShaderExecutable9::makeShaderExecutable9(ShaderExecutable *executable)
{
ASSERT(HAS_DYNAMIC_TYPE(ShaderExecutable9*, executable));
return static_cast<ShaderExecutable9*>(executable);
}
IDirect3DVertexShader9 *ShaderExecutable9::getVertexShader() const
{
return mVertexExecutable;
}
IDirect3DPixelShader9 *ShaderExecutable9::getPixelShader() const
{
return mPixelExecutable;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/ShaderExecutable9.cpp | C++ | bsd | 1,474 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence9.h: Defines the rx::Fence9 class which implements rx::FenceImpl.
#ifndef LIBGLESV2_RENDERER_FENCE9_H_
#define LIBGLESV2_RENDERER_FENCE9_H_
#include "libGLESv2/renderer/FenceImpl.h"
namespace rx
{
class Renderer9;
class Fence9 : public FenceImpl
{
public:
explicit Fence9(rx::Renderer9 *renderer);
virtual ~Fence9();
GLboolean isFence();
void setFence(GLenum condition);
GLboolean testFence();
void finishFence();
void getFenceiv(GLenum pname, GLint *params);
private:
DISALLOW_COPY_AND_ASSIGN(Fence9);
rx::Renderer9 *mRenderer;
IDirect3DQuery9 *mQuery;
};
}
#endif // LIBGLESV2_RENDERER_FENCE9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Fence9.h | C++ | bsd | 840 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// InputLayoutCache.h: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#ifndef LIBGLESV2_RENDERER_INPUTLAYOUTCACHE_H_
#define LIBGLESV2_RENDERER_INPUTLAYOUTCACHE_H_
#include "libGLESv2/Constants.h"
#include "common/angleutils.h"
namespace gl
{
class ProgramBinary;
}
namespace rx
{
struct TranslatedAttribute;
class InputLayoutCache
{
public:
InputLayoutCache();
virtual ~InputLayoutCache();
void initialize(ID3D11Device *device, ID3D11DeviceContext *context);
void clear();
GLenum applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary);
private:
DISALLOW_COPY_AND_ASSIGN(InputLayoutCache);
struct InputLayoutKey
{
unsigned int elementCount;
D3D11_INPUT_ELEMENT_DESC elements[gl::MAX_VERTEX_ATTRIBS];
GLenum glslElementType[gl::MAX_VERTEX_ATTRIBS];
};
struct InputLayoutCounterPair
{
ID3D11InputLayout *inputLayout;
unsigned long long lastUsedTime;
};
static std::size_t hashInputLayout(const InputLayoutKey &inputLayout);
static bool compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b);
typedef std::size_t (*InputLayoutHashFunction)(const InputLayoutKey &);
typedef bool (*InputLayoutEqualityFunction)(const InputLayoutKey &, const InputLayoutKey &);
typedef std::unordered_map<InputLayoutKey,
InputLayoutCounterPair,
InputLayoutHashFunction,
InputLayoutEqualityFunction> InputLayoutMap;
InputLayoutMap mInputLayoutMap;
static const unsigned int kMaxInputLayouts;
unsigned long long mCounter;
ID3D11Device *mDevice;
ID3D11DeviceContext *mDeviceContext;
};
}
#endif // LIBGLESV2_RENDERER_INPUTLAYOUTCACHE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/InputLayoutCache.h | C++ | bsd | 2,067 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderTarget.h: Defines an abstract wrapper class to manage IDirect3DSurface9
// and ID3D11View objects belonging to renderbuffers.
#ifndef LIBGLESV2_RENDERER_RENDERTARGET_H_
#define LIBGLESV2_RENDERER_RENDERTARGET_H_
#include "common/angleutils.h"
namespace rx
{
class RenderTarget
{
public:
RenderTarget()
{
mWidth = 0;
mHeight = 0;
mInternalFormat = GL_NONE;
mActualFormat = GL_NONE;
mSamples = 0;
}
virtual ~RenderTarget() {};
GLsizei getWidth() { return mWidth; }
GLsizei getHeight() { return mHeight; }
GLenum getInternalFormat() { return mInternalFormat; }
GLenum getActualFormat() { return mActualFormat; }
GLsizei getSamples() { return mSamples; }
struct Desc {
GLsizei width;
GLsizei height;
GLenum format;
};
protected:
GLsizei mWidth;
GLsizei mHeight;
GLenum mInternalFormat;
GLenum mActualFormat;
GLsizei mSamples;
private:
DISALLOW_COPY_AND_ASSIGN(RenderTarget);
};
}
#endif // LIBGLESV2_RENDERTARGET_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/RenderTarget.h | C++ | bsd | 1,255 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// vertexconversion.h: A library of vertex conversion classes that can be used to build
// the FormatConverter objects used by the buffer conversion system.
#ifndef LIBGLESV2_VERTEXCONVERSION_H_
#define LIBGLESV2_VERTEXCONVERSION_H_
namespace rx
{
// Conversion types:
// static const bool identity: true if this is an identity transform, false otherwise
// static U convert(T): convert a single element from the input type to the output type
// typedef ... OutputType: the type produced by this conversion
template <class T>
struct Identity
{
static const bool identity = true;
typedef T OutputType;
static T convert(T x)
{
return x;
}
};
template <class FromT, class ToT>
struct Cast
{
static const bool identity = false;
typedef ToT OutputType;
static ToT convert(FromT x)
{
return static_cast<ToT>(x);
}
};
template <class T>
struct Cast<T, T>
{
static const bool identity = true;
typedef T OutputType;
static T convert(T x)
{
return static_cast<T>(x);
}
};
template <class T>
struct Normalize
{
static const bool identity = false;
typedef float OutputType;
static float convert(T x)
{
typedef std::numeric_limits<T> NL;
float f = static_cast<float>(x);
if (NL::is_signed)
{
// const float => VC2008 computes it at compile time
// static const float => VC2008 computes it the first time we get here, stores it to memory with static guard and all that.
const float divisor = 1.0f/(2*static_cast<float>(NL::max())+1);
return (2*f+1)*divisor;
}
else
{
return f/NL::max();
}
}
};
template <class FromType, std::size_t ScaleBits>
struct FixedToFloat
{
static const bool identity = false;
typedef float OutputType;
static float convert(FromType x)
{
const float divisor = 1.0f / static_cast<float>(static_cast<FromType>(1) << ScaleBits);
return static_cast<float>(x) * divisor;
}
};
// Widen types:
// static const unsigned int initialWidth: number of components before conversion
// static const unsigned int finalWidth: number of components after conversion
// Float is supported at any size.
template <std::size_t N>
struct NoWiden
{
static const std::size_t initialWidth = N;
static const std::size_t finalWidth = N;
};
// SHORT, norm-SHORT, norm-UNSIGNED_SHORT are supported but only with 2 or 4 components
template <std::size_t N>
struct WidenToEven
{
static const std::size_t initialWidth = N;
static const std::size_t finalWidth = N+(N&1);
};
template <std::size_t N>
struct WidenToFour
{
static const std::size_t initialWidth = N;
static const std::size_t finalWidth = 4;
};
// Most types have 0 and 1 that are just that.
template <class T>
struct SimpleDefaultValues
{
static T zero() { return static_cast<T>(0); }
static T one() { return static_cast<T>(1); }
};
// But normalised types only store [0,1] or [-1,1] so 1.0 is represented by the max value.
template <class T>
struct NormalizedDefaultValues
{
static T zero() { return static_cast<T>(0); }
static T one() { return std::numeric_limits<T>::max(); }
};
// Converter:
// static const bool identity: true if this is an identity transform (with no widening)
// static const std::size_t finalSize: number of bytes per output vertex
// static void convertArray(const void *in, std::size_t stride, std::size_t n, void *out): convert an array of vertices. Input may be strided, but output will be unstrided.
template <class InT, class WidenRule, class Converter, class DefaultValueRule = SimpleDefaultValues<InT> >
struct VertexDataConverter
{
typedef typename Converter::OutputType OutputType;
typedef InT InputType;
static const bool identity = (WidenRule::initialWidth == WidenRule::finalWidth) && Converter::identity;
static const std::size_t finalSize = WidenRule::finalWidth * sizeof(OutputType);
static void convertArray(const InputType *in, std::size_t stride, std::size_t n, OutputType *out)
{
for (std::size_t i = 0; i < n; i++)
{
const InputType *ein = pointerAddBytes(in, i * stride);
copyComponent(out, ein, 0, static_cast<OutputType>(DefaultValueRule::zero()));
copyComponent(out, ein, 1, static_cast<OutputType>(DefaultValueRule::zero()));
copyComponent(out, ein, 2, static_cast<OutputType>(DefaultValueRule::zero()));
copyComponent(out, ein, 3, static_cast<OutputType>(DefaultValueRule::one()));
out += WidenRule::finalWidth;
}
}
static void convertArray(const void *in, std::size_t stride, std::size_t n, void *out)
{
return convertArray(static_cast<const InputType*>(in), stride, n, static_cast<OutputType*>(out));
}
private:
// Advance the given pointer by a number of bytes (not pointed-to elements).
template <class T>
static T *pointerAddBytes(T *basePtr, std::size_t numBytes)
{
return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(basePtr) + numBytes);
}
static void copyComponent(OutputType *out, const InputType *in, std::size_t elementindex, OutputType defaultvalue)
{
if (WidenRule::finalWidth > elementindex)
{
if (WidenRule::initialWidth > elementindex)
{
out[elementindex] = Converter::convert(in[elementindex]);
}
else
{
out[elementindex] = defaultvalue;
}
}
}
};
}
#endif // LIBGLESV2_VERTEXCONVERSION_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/vertexconversion.h | C++ | bsd | 5,844 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer.h: Defines the abstract VertexBuffer class and VertexBufferInterface
// class with derivations, classes that perform graphics API agnostic vertex buffer operations.
#ifndef LIBGLESV2_RENDERER_VERTEXBUFFER_H_
#define LIBGLESV2_RENDERER_VERTEXBUFFER_H_
#include "common/angleutils.h"
namespace gl
{
class VertexAttribute;
}
namespace rx
{
class Renderer;
class VertexBuffer
{
public:
VertexBuffer();
virtual ~VertexBuffer();
virtual bool initialize(unsigned int size, bool dynamicUsage) = 0;
virtual bool storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count,
GLsizei instances, unsigned int offset) = 0;
virtual bool storeRawData(const void* data, unsigned int size, unsigned int offset) = 0;
virtual unsigned int getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count,
GLsizei instances) const = 0;
virtual bool requiresConversion(const gl::VertexAttribute &attrib) const = 0;
virtual unsigned int getBufferSize() const = 0;
virtual bool setBufferSize(unsigned int size) = 0;
virtual bool discard() = 0;
unsigned int getSerial() const;
protected:
void updateSerial();
private:
DISALLOW_COPY_AND_ASSIGN(VertexBuffer);
unsigned int mSerial;
static unsigned int mNextSerial;
};
class VertexBufferInterface
{
public:
VertexBufferInterface(rx::Renderer *renderer, bool dynamic);
virtual ~VertexBufferInterface();
void reserveVertexSpace(const gl::VertexAttribute &attribute, GLsizei count, GLsizei instances);
void reserveRawDataSpace(unsigned int size);
unsigned int getBufferSize() const;
unsigned int getSerial() const;
virtual int storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances);
virtual int storeRawData(const void* data, unsigned int size);
VertexBuffer* getVertexBuffer() const;
protected:
virtual bool reserveSpace(unsigned int size) = 0;
unsigned int getWritePosition() const;
void setWritePosition(unsigned int writePosition);
bool discard();
bool setBufferSize(unsigned int size);
private:
DISALLOW_COPY_AND_ASSIGN(VertexBufferInterface);
rx::Renderer *const mRenderer;
VertexBuffer* mVertexBuffer;
unsigned int mWritePosition;
unsigned int mReservedSpace;
bool mDynamic;
};
class StreamingVertexBufferInterface : public VertexBufferInterface
{
public:
StreamingVertexBufferInterface(rx::Renderer *renderer, std::size_t initialSize);
~StreamingVertexBufferInterface();
protected:
bool reserveSpace(unsigned int size);
};
class StaticVertexBufferInterface : public VertexBufferInterface
{
public:
explicit StaticVertexBufferInterface(rx::Renderer *renderer);
~StaticVertexBufferInterface();
int storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances);
// Returns the offset into the vertex buffer, or -1 if not found
int lookupAttribute(const gl::VertexAttribute &attribute);
protected:
bool reserveSpace(unsigned int size);
private:
struct VertexElement
{
GLenum type;
GLint size;
GLsizei stride;
bool normalized;
int attributeOffset;
unsigned int streamOffset;
};
std::vector<VertexElement> mCache;
};
}
#endif // LIBGLESV2_RENDERER_VERTEXBUFFER_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer.h | C++ | bsd | 3,684 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexBuffer.h: Defines the abstract IndexBuffer class and IndexBufferInterface
// class with derivations, classes that perform graphics API agnostic index buffer operations.
#ifndef LIBGLESV2_RENDERER_INDEXBUFFER_H_
#define LIBGLESV2_RENDERER_INDEXBUFFER_H_
#include "common/angleutils.h"
namespace rx
{
class Renderer;
class IndexBuffer
{
public:
IndexBuffer();
virtual ~IndexBuffer();
virtual bool initialize(unsigned int bufferSize, GLenum indexType, bool dynamic) = 0;
virtual bool mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory) = 0;
virtual bool unmapBuffer() = 0;
virtual bool discard() = 0;
virtual GLenum getIndexType() const = 0;
virtual unsigned int getBufferSize() const = 0;
virtual bool setSize(unsigned int bufferSize, GLenum indexType) = 0;
unsigned int getSerial() const;
protected:
void updateSerial();
private:
DISALLOW_COPY_AND_ASSIGN(IndexBuffer);
unsigned int mSerial;
static unsigned int mNextSerial;
};
class IndexBufferInterface
{
public:
IndexBufferInterface(Renderer *renderer, bool dynamic);
virtual ~IndexBufferInterface();
virtual bool reserveBufferSpace(unsigned int size, GLenum indexType) = 0;
GLenum getIndexType() const;
unsigned int getBufferSize() const;
unsigned int getSerial() const;
int mapBuffer(unsigned int size, void** outMappedMemory);
bool unmapBuffer();
IndexBuffer *getIndexBuffer() const;
protected:
unsigned int getWritePosition() const;
void setWritePosition(unsigned int writePosition);
bool discard();
bool setBufferSize(unsigned int bufferSize, GLenum indexType);
private:
DISALLOW_COPY_AND_ASSIGN(IndexBufferInterface);
rx::Renderer *const mRenderer;
IndexBuffer* mIndexBuffer;
unsigned int mWritePosition;
bool mDynamic;
};
class StreamingIndexBufferInterface : public IndexBufferInterface
{
public:
StreamingIndexBufferInterface(Renderer *renderer);
~StreamingIndexBufferInterface();
virtual bool reserveBufferSpace(unsigned int size, GLenum indexType);
};
class StaticIndexBufferInterface : public IndexBufferInterface
{
public:
explicit StaticIndexBufferInterface(Renderer *renderer);
~StaticIndexBufferInterface();
virtual bool reserveBufferSpace(unsigned int size, GLenum indexType);
unsigned int lookupRange(intptr_t offset, GLsizei count, unsigned int *minIndex, unsigned int *maxIndex); // Returns the offset into the index buffer, or -1 if not found
void addRange(intptr_t offset, GLsizei count, unsigned int minIndex, unsigned int maxIndex, unsigned int streamOffset);
private:
struct IndexRange
{
intptr_t offset;
GLsizei count;
bool operator<(const IndexRange& rhs) const
{
if (offset != rhs.offset)
{
return offset < rhs.offset;
}
if (count != rhs.count)
{
return count < rhs.count;
}
return false;
}
};
struct IndexResult
{
unsigned int minIndex;
unsigned int maxIndex;
unsigned int streamOffset;
};
std::map<IndexRange, IndexResult> mCache;
};
}
#endif // LIBGLESV2_RENDERER_INDEXBUFFER_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer.h | C++ | bsd | 3,500 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// FenceImpl.h: Defines the rx::FenceImpl class.
#ifndef LIBGLESV2_RENDERER_FENCEIMPL_H_
#define LIBGLESV2_RENDERER_FENCEIMPL_H_
#include "common/angleutils.h"
namespace rx
{
class FenceImpl
{
public:
FenceImpl() : mStatus(GL_FALSE), mCondition(GL_NONE) { };
virtual ~FenceImpl() { };
virtual GLboolean isFence() = 0;
virtual void setFence(GLenum condition) = 0;
virtual GLboolean testFence() = 0;
virtual void finishFence() = 0;
virtual void getFenceiv(GLenum pname, GLint *params) = 0;
protected:
void setStatus(GLboolean status) { mStatus = status; }
GLboolean getStatus() const { return mStatus; }
void setCondition(GLuint condition) { mCondition = condition; }
GLuint getCondition() const { return mCondition; }
private:
DISALLOW_COPY_AND_ASSIGN(FenceImpl);
GLboolean mStatus;
GLenum mCondition;
};
}
#endif // LIBGLESV2_RENDERER_FENCEIMPL_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/FenceImpl.h | C++ | bsd | 1,102 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer.cpp: Implements EGL dependencies for creating and destroying Renderer instances.
#include <EGL/eglext.h>
#include "libGLESv2/main.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/utilities.h"
#if !defined(ANGLE_ENABLE_D3D11)
// Enables use of the Direct3D 11 API for a default display, when available
#define ANGLE_ENABLE_D3D11 0
#endif
namespace rx
{
Renderer::Renderer(egl::Display *display) : mDisplay(display)
{
mD3dCompilerModule = NULL;
mD3DCompileFunc = NULL;
}
Renderer::~Renderer()
{
if (mD3dCompilerModule)
{
FreeLibrary(mD3dCompilerModule);
mD3dCompilerModule = NULL;
}
}
bool Renderer::initializeCompiler()
{
#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
// Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
for (size_t i = 0; i < ArraySize(d3dCompilerNames); ++i)
{
if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
{
break;
}
}
#else
// Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
if (!mD3dCompilerModule)
{
ERR("No D3D compiler module found - aborting!\n");
return false;
}
mD3DCompileFunc = reinterpret_cast<pCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
ASSERT(mD3DCompileFunc);
return mD3DCompileFunc != NULL;
}
// Compiles HLSL code into executable binaries
ShaderBlob *Renderer::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, UINT optimizationFlags, bool alternateFlags)
{
if (!hlsl)
{
return NULL;
}
HRESULT result = S_OK;
UINT flags = 0;
std::string sourceText;
if (gl::perfActive())
{
flags |= D3DCOMPILE_DEBUG;
#ifdef NDEBUG
flags |= optimizationFlags;
#else
flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
std::string sourcePath = getTempPath();
sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
}
else
{
flags |= optimizationFlags;
sourceText = hlsl;
}
// Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
// Try the default flags first and if compilation fails, try some alternatives.
const static UINT extraFlags[] =
{
0,
D3DCOMPILE_AVOID_FLOW_CONTROL,
D3DCOMPILE_PREFER_FLOW_CONTROL
};
const static char * const extraFlagNames[] =
{
"default",
"avoid flow control",
"prefer flow control"
};
int attempts = alternateFlags ? ArraySize(extraFlags) : 1;
pD3DCompile compileFunc = reinterpret_cast<pD3DCompile>(mD3DCompileFunc);
for (int i = 0; i < attempts; ++i)
{
ID3DBlob *errorMessage = NULL;
ID3DBlob *binary = NULL;
result = compileFunc(hlsl, strlen(hlsl), gl::g_fakepath, NULL, NULL,
"main", profile, flags | extraFlags[i], 0, &binary, &errorMessage);
if (errorMessage)
{
const char *message = (const char*)errorMessage->GetBufferPointer();
infoLog.appendSanitized(message);
TRACE("\n%s", hlsl);
TRACE("\n%s", message);
errorMessage->Release();
errorMessage = NULL;
}
if (SUCCEEDED(result))
{
return (ShaderBlob*)binary;
}
else
{
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
{
return gl::error(GL_OUT_OF_MEMORY, (ShaderBlob*) NULL);
}
infoLog.append("Warning: D3D shader compilation failed with ");
infoLog.append(extraFlagNames[i]);
infoLog.append(" flags.");
if (i + 1 < attempts)
{
infoLog.append(" Retrying with ");
infoLog.append(extraFlagNames[i + 1]);
infoLog.append(".\n");
}
}
}
return NULL;
}
}
extern "C"
{
rx::Renderer *glCreateRenderer(egl::Display *display, HDC hDc, EGLNativeDisplayType displayId)
{
rx::Renderer *renderer = NULL;
EGLint status = EGL_BAD_ALLOC;
if (ANGLE_ENABLE_D3D11 ||
displayId == EGL_D3D11_ELSE_D3D9_DISPLAY_ANGLE ||
displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
{
renderer = new rx::Renderer11(display, hDc);
if (renderer)
{
status = renderer->initialize();
}
if (status == EGL_SUCCESS)
{
return renderer;
}
else if (displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
{
return NULL;
}
// Failed to create a D3D11 renderer, try creating a D3D9 renderer
delete renderer;
}
bool softwareDevice = (displayId == EGL_SOFTWARE_DISPLAY_ANGLE);
renderer = new rx::Renderer9(display, hDc, softwareDevice);
if (renderer)
{
status = renderer->initialize();
}
if (status == EGL_SUCCESS)
{
return renderer;
}
return NULL;
}
void glDestroyRenderer(rx::Renderer *renderer)
{
delete renderer;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/Renderer.cpp | C++ | bsd | 5,892 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain11.cpp: Implements a back-end specific class for the D3D11 swap chain.
#include "libGLESv2/renderer/SwapChain11.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/shaders/compiled/passthrough11vs.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughrgba11ps.h"
namespace rx
{
SwapChain11::SwapChain11(Renderer11 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat)
: mRenderer(renderer), SwapChain(window, shareHandle, backBufferFormat, depthBufferFormat)
{
mSwapChain = NULL;
mBackBufferTexture = NULL;
mBackBufferRTView = NULL;
mOffscreenTexture = NULL;
mOffscreenRTView = NULL;
mOffscreenSRView = NULL;
mDepthStencilTexture = NULL;
mDepthStencilDSView = NULL;
mQuadVB = NULL;
mPassThroughSampler = NULL;
mPassThroughIL = NULL;
mPassThroughVS = NULL;
mPassThroughPS = NULL;
mWidth = -1;
mHeight = -1;
mSwapInterval = 0;
mAppCreatedShareHandle = mShareHandle != NULL;
mPassThroughResourcesInit = false;
}
SwapChain11::~SwapChain11()
{
release();
}
void SwapChain11::release()
{
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBufferTexture)
{
mBackBufferTexture->Release();
mBackBufferTexture = NULL;
}
if (mBackBufferRTView)
{
mBackBufferRTView->Release();
mBackBufferRTView = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mOffscreenRTView)
{
mOffscreenRTView->Release();
mOffscreenRTView = NULL;
}
if (mOffscreenSRView)
{
mOffscreenSRView->Release();
mOffscreenSRView = NULL;
}
if (mDepthStencilTexture)
{
mDepthStencilTexture->Release();
mDepthStencilTexture = NULL;
}
if (mDepthStencilDSView)
{
mDepthStencilDSView->Release();
mDepthStencilDSView = NULL;
}
if (mQuadVB)
{
mQuadVB->Release();
mQuadVB = NULL;
}
if (mPassThroughSampler)
{
mPassThroughSampler->Release();
mPassThroughSampler = NULL;
}
if (mPassThroughIL)
{
mPassThroughIL->Release();
mPassThroughIL = NULL;
}
if (mPassThroughVS)
{
mPassThroughVS->Release();
mPassThroughVS = NULL;
}
if (mPassThroughPS)
{
mPassThroughPS->Release();
mPassThroughPS = NULL;
}
if (!mAppCreatedShareHandle)
{
mShareHandle = NULL;
}
}
void SwapChain11::releaseOffscreenTexture()
{
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mOffscreenRTView)
{
mOffscreenRTView->Release();
mOffscreenRTView = NULL;
}
if (mOffscreenSRView)
{
mOffscreenSRView->Release();
mOffscreenSRView = NULL;
}
if (mDepthStencilTexture)
{
mDepthStencilTexture->Release();
mDepthStencilTexture = NULL;
}
if (mDepthStencilDSView)
{
mDepthStencilDSView->Release();
mDepthStencilDSView = NULL;
}
}
EGLint SwapChain11::resetOffscreenTexture(int backbufferWidth, int backbufferHeight)
{
ID3D11Device *device = mRenderer->getDevice();
ASSERT(device != NULL);
// D3D11 does not allow zero size textures
ASSERT(backbufferWidth >= 1);
ASSERT(backbufferHeight >= 1);
// Preserve the render target content
ID3D11Texture2D *previousOffscreenTexture = mOffscreenTexture;
if (previousOffscreenTexture)
{
previousOffscreenTexture->AddRef();
}
const int previousWidth = mWidth;
const int previousHeight = mHeight;
releaseOffscreenTexture();
// If the app passed in a share handle, open the resource
// See EGL_ANGLE_d3d_share_handle_client_buffer
if (mAppCreatedShareHandle)
{
ID3D11Resource *tempResource11;
HRESULT result = device->OpenSharedResource(mShareHandle, __uuidof(ID3D11Resource), (void**)&tempResource11);
if (FAILED(result))
{
ERR("Failed to open the swap chain pbuffer share handle: %08lX", result);
release();
return EGL_BAD_PARAMETER;
}
result = tempResource11->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&mOffscreenTexture);
tempResource11->Release();
if (FAILED(result))
{
ERR("Failed to query texture2d interface in pbuffer share handle: %08lX", result);
release();
return EGL_BAD_PARAMETER;
}
// Validate offscreen texture parameters
D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
mOffscreenTexture->GetDesc(&offscreenTextureDesc);
if (offscreenTextureDesc.Width != (UINT)backbufferWidth
|| offscreenTextureDesc.Height != (UINT)backbufferHeight
|| offscreenTextureDesc.Format != gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat)
|| offscreenTextureDesc.MipLevels != 1
|| offscreenTextureDesc.ArraySize != 1)
{
ERR("Invalid texture parameters in the shared offscreen texture pbuffer");
release();
return EGL_BAD_PARAMETER;
}
}
else
{
const bool useSharedResource = !mWindow && mRenderer->getShareHandleSupport();
D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
offscreenTextureDesc.Width = backbufferWidth;
offscreenTextureDesc.Height = backbufferHeight;
offscreenTextureDesc.Format = gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat);
offscreenTextureDesc.MipLevels = 1;
offscreenTextureDesc.ArraySize = 1;
offscreenTextureDesc.SampleDesc.Count = 1;
offscreenTextureDesc.SampleDesc.Quality = 0;
offscreenTextureDesc.Usage = D3D11_USAGE_DEFAULT;
offscreenTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
offscreenTextureDesc.CPUAccessFlags = 0;
offscreenTextureDesc.MiscFlags = useSharedResource ? D3D11_RESOURCE_MISC_SHARED : 0;
HRESULT result = device->CreateTexture2D(&offscreenTextureDesc, NULL, &mOffscreenTexture);
if (FAILED(result))
{
ERR("Could not create offscreen texture: %08lX", result);
release();
if (d3d11::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
d3d11::SetDebugName(mOffscreenTexture, "Offscreen texture");
// EGL_ANGLE_surface_d3d_texture_2d_share_handle requires that we store a share handle for the client
if (useSharedResource)
{
IDXGIResource *offscreenTextureResource = NULL;
result = mOffscreenTexture->QueryInterface(__uuidof(IDXGIResource), (void**)&offscreenTextureResource);
// Fall back to no share handle on failure
if (FAILED(result))
{
ERR("Could not query offscreen texture resource: %08lX", result);
}
else
{
result = offscreenTextureResource->GetSharedHandle(&mShareHandle);
if (FAILED(result))
{
mShareHandle = NULL;
ERR("Could not get offscreen texture shared handle: %08lX", result);
}
}
}
}
HRESULT result = device->CreateRenderTargetView(mOffscreenTexture, NULL, &mOffscreenRTView);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mOffscreenRTView, "Offscreen render target");
result = device->CreateShaderResourceView(mOffscreenTexture, NULL, &mOffscreenSRView);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mOffscreenSRView, "Offscreen shader resource");
if (mDepthBufferFormat != GL_NONE)
{
D3D11_TEXTURE2D_DESC depthStencilDesc = {0};
depthStencilDesc.Width = backbufferWidth;
depthStencilDesc.Height = backbufferHeight;
depthStencilDesc.Format = gl_d3d11::ConvertRenderbufferFormat(mDepthBufferFormat);
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
result = device->CreateTexture2D(&depthStencilDesc, NULL, &mDepthStencilTexture);
if (FAILED(result))
{
ERR("Could not create depthstencil surface for new swap chain: 0x%08X", result);
release();
if (d3d11::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
d3d11::SetDebugName(mDepthStencilTexture, "Depth stencil texture");
result = device->CreateDepthStencilView(mDepthStencilTexture, NULL, &mDepthStencilDSView);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mDepthStencilDSView, "Depth stencil view");
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
if (previousOffscreenTexture != NULL)
{
D3D11_BOX sourceBox = {0};
sourceBox.left = 0;
sourceBox.right = std::min(previousWidth, mWidth);
sourceBox.top = std::max(previousHeight - mHeight, 0);
sourceBox.bottom = previousHeight;
sourceBox.front = 0;
sourceBox.back = 1;
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
const int yoffset = std::max(mHeight - previousHeight, 0);
deviceContext->CopySubresourceRegion(mOffscreenTexture, 0, 0, yoffset, 0, previousOffscreenTexture, 0, &sourceBox);
previousOffscreenTexture->Release();
if (mSwapChain)
{
swapRect(0, 0, mWidth, mHeight);
}
}
return EGL_SUCCESS;
}
EGLint SwapChain11::resize(EGLint backbufferWidth, EGLint backbufferHeight)
{
ID3D11Device *device = mRenderer->getDevice();
if (device == NULL)
{
return EGL_BAD_ACCESS;
}
// Can only call resize if we have already created our swap buffer and resources
ASSERT(mSwapChain && mBackBufferTexture && mBackBufferRTView);
if (mBackBufferTexture)
{
mBackBufferTexture->Release();
mBackBufferTexture = NULL;
}
if (mBackBufferRTView)
{
mBackBufferRTView->Release();
mBackBufferRTView = NULL;
}
// Resize swap chain
DXGI_FORMAT backbufferDXGIFormat = gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat);
HRESULT result = mSwapChain->ResizeBuffers(2, backbufferWidth, backbufferHeight, backbufferDXGIFormat, 0);
if (FAILED(result))
{
ERR("Error resizing swap chain buffers: 0x%08X", result);
release();
if (d3d11::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackBufferTexture);
ASSERT(SUCCEEDED(result));
if (SUCCEEDED(result))
{
d3d11::SetDebugName(mBackBufferTexture, "Back buffer texture");
}
result = device->CreateRenderTargetView(mBackBufferTexture, NULL, &mBackBufferRTView);
ASSERT(SUCCEEDED(result));
if (SUCCEEDED(result))
{
d3d11::SetDebugName(mBackBufferRTView, "Back buffer render target");
}
return resetOffscreenTexture(backbufferWidth, backbufferHeight);
}
EGLint SwapChain11::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
{
ID3D11Device *device = mRenderer->getDevice();
if (device == NULL)
{
return EGL_BAD_ACCESS;
}
// Release specific resources to free up memory for the new render target, while the
// old render target still exists for the purpose of preserving its contents.
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBufferTexture)
{
mBackBufferTexture->Release();
mBackBufferTexture = NULL;
}
if (mBackBufferRTView)
{
mBackBufferRTView->Release();
mBackBufferRTView = NULL;
}
mSwapInterval = static_cast<unsigned int>(swapInterval);
if (mSwapInterval > 4)
{
// IDXGISwapChain::Present documentation states that valid sync intervals are in the [0,4] range
return EGL_BAD_PARAMETER;
}
// EGL allows creating a surface with 0x0 dimension, however, DXGI does not like 0x0 swapchains
if (backbufferWidth < 1 || backbufferHeight < 1)
{
releaseOffscreenTexture();
return EGL_SUCCESS;
}
if (mWindow)
{
// We cannot create a swap chain for an HWND that is owned by a different process
DWORD currentProcessId = GetCurrentProcessId();
DWORD wndProcessId;
GetWindowThreadProcessId(mWindow, &wndProcessId);
if (currentProcessId != wndProcessId)
{
ERR("Could not create swap chain, window owned by different process");
release();
return EGL_BAD_NATIVE_WINDOW;
}
IDXGIFactory *factory = mRenderer->getDxgiFactory();
DXGI_SWAP_CHAIN_DESC swapChainDesc = {0};
swapChainDesc.BufferCount = 2;
swapChainDesc.BufferDesc.Format = gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat);
swapChainDesc.BufferDesc.Width = backbufferWidth;
swapChainDesc.BufferDesc.Height = backbufferHeight;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.Flags = 0;
swapChainDesc.OutputWindow = mWindow;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Windowed = TRUE;
HRESULT result = factory->CreateSwapChain(device, &swapChainDesc, &mSwapChain);
if (FAILED(result))
{
ERR("Could not create additional swap chains or offscreen surfaces: %08lX", result);
release();
if (d3d11::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackBufferTexture);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mBackBufferTexture, "Back buffer texture");
result = device->CreateRenderTargetView(mBackBufferTexture, NULL, &mBackBufferRTView);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mBackBufferRTView, "Back buffer render target");
}
// If we are resizing the swap chain, we don't wish to recreate all the static resources
if (!mPassThroughResourcesInit)
{
mPassThroughResourcesInit = true;
initPassThroughResources();
}
return resetOffscreenTexture(backbufferWidth, backbufferHeight);
}
void SwapChain11::initPassThroughResources()
{
ID3D11Device *device = mRenderer->getDevice();
ASSERT(device != NULL);
// Make sure our resources are all not allocated, when we create
ASSERT(mQuadVB == NULL && mPassThroughSampler == NULL);
ASSERT(mPassThroughIL == NULL && mPassThroughVS == NULL && mPassThroughPS == NULL);
D3D11_BUFFER_DESC vbDesc;
vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
vbDesc.Usage = D3D11_USAGE_DYNAMIC;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
HRESULT result = device->CreateBuffer(&vbDesc, NULL, &mQuadVB);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mQuadVB, "Swap chain quad vertex buffer");
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
result = device->CreateSamplerState(&samplerDesc, &mPassThroughSampler);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mPassThroughSampler, "Swap chain pass through sampler");
D3D11_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
result = device->CreateInputLayout(quadLayout, 2, g_VS_Passthrough, sizeof(g_VS_Passthrough), &mPassThroughIL);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mPassThroughIL, "Swap chain pass through layout");
result = device->CreateVertexShader(g_VS_Passthrough, sizeof(g_VS_Passthrough), NULL, &mPassThroughVS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mPassThroughVS, "Swap chain pass through vertex shader");
result = device->CreatePixelShader(g_PS_PassthroughRGBA, sizeof(g_PS_PassthroughRGBA), NULL, &mPassThroughPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mPassThroughPS, "Swap chain pass through pixel shader");
}
// parameters should be validated/clamped by caller
EGLint SwapChain11::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return EGL_SUCCESS;
}
ID3D11Device *device = mRenderer->getDevice();
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
// Set vertices
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = deviceContext->Map(mQuadVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return EGL_BAD_ACCESS;
}
d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
// Create a quad in homogeneous coordinates
float x1 = (x / float(mWidth)) * 2.0f - 1.0f;
float y1 = (y / float(mHeight)) * 2.0f - 1.0f;
float x2 = ((x + width) / float(mWidth)) * 2.0f - 1.0f;
float y2 = ((y + height) / float(mHeight)) * 2.0f - 1.0f;
float u1 = x / float(mWidth);
float v1 = y / float(mHeight);
float u2 = (x + width) / float(mWidth);
float v2 = (y + height) / float(mHeight);
d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, u1, v1);
d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v2);
d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v1);
d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v2);
deviceContext->Unmap(mQuadVB, 0);
static UINT stride = sizeof(d3d11::PositionTexCoordVertex);
static UINT startIdx = 0;
deviceContext->IASetVertexBuffers(0, 1, &mQuadVB, &stride, &startIdx);
// Apply state
deviceContext->OMSetDepthStencilState(NULL, 0xFFFFFFFF);
static const float blendFactor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
deviceContext->OMSetBlendState(NULL, blendFactor, 0xFFFFFFF);
deviceContext->RSSetState(NULL);
// Apply shaders
deviceContext->IASetInputLayout(mPassThroughIL);
deviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
deviceContext->VSSetShader(mPassThroughVS, NULL, 0);
deviceContext->PSSetShader(mPassThroughPS, NULL, 0);
deviceContext->GSSetShader(NULL, NULL, 0);
// Apply render targets
mRenderer->setOneTimeRenderTarget(mBackBufferRTView);
// Set the viewport
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = mWidth;
viewport.Height = mHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
deviceContext->RSSetViewports(1, &viewport);
// Apply textures
deviceContext->PSSetShaderResources(0, 1, &mOffscreenSRView);
deviceContext->PSSetSamplers(0, 1, &mPassThroughSampler);
// Draw
deviceContext->Draw(4, 0);
result = mSwapChain->Present(mSwapInterval, 0);
if (result == DXGI_ERROR_DEVICE_REMOVED)
{
HRESULT removedReason = device->GetDeviceRemovedReason();
ERR("Present failed: the D3D11 device was removed: 0x%08X", removedReason);
return EGL_CONTEXT_LOST;
}
else if (result == DXGI_ERROR_DEVICE_RESET)
{
ERR("Present failed: the D3D11 device was reset from a bad command.");
return EGL_CONTEXT_LOST;
}
else if (FAILED(result))
{
ERR("Present failed with error code 0x%08X", result);
}
// Unbind
static ID3D11ShaderResourceView *const nullSRV = NULL;
deviceContext->PSSetShaderResources(0, 1, &nullSRV);
mRenderer->unapplyRenderTargets();
mRenderer->markAllStateDirty();
return EGL_SUCCESS;
}
// Increments refcount on texture.
// caller must Release() the returned texture
ID3D11Texture2D *SwapChain11::getOffscreenTexture()
{
if (mOffscreenTexture)
{
mOffscreenTexture->AddRef();
}
return mOffscreenTexture;
}
// Increments refcount on view.
// caller must Release() the returned view
ID3D11RenderTargetView *SwapChain11::getRenderTarget()
{
if (mOffscreenRTView)
{
mOffscreenRTView->AddRef();
}
return mOffscreenRTView;
}
// Increments refcount on view.
// caller must Release() the returned view
ID3D11ShaderResourceView *SwapChain11::getRenderTargetShaderResource()
{
if (mOffscreenSRView)
{
mOffscreenSRView->AddRef();
}
return mOffscreenSRView;
}
// Increments refcount on view.
// caller must Release() the returned view
ID3D11DepthStencilView *SwapChain11::getDepthStencil()
{
if (mDepthStencilDSView)
{
mDepthStencilDSView->AddRef();
}
return mDepthStencilDSView;
}
ID3D11Texture2D *SwapChain11::getDepthStencilTexture()
{
if (mDepthStencilTexture)
{
mDepthStencilTexture->AddRef();
}
return mDepthStencilTexture;
}
SwapChain11 *SwapChain11::makeSwapChain11(SwapChain *swapChain)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::SwapChain11*, swapChain));
return static_cast<rx::SwapChain11*>(swapChain);
}
void SwapChain11::recreate()
{
// possibly should use this method instead of reset
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/SwapChain11.cpp | C++ | bsd | 23,424 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage11.h: Defines the abstract rx::TextureStorage11 class and its concrete derived
// classes TextureStorage11_2D and TextureStorage11_Cube, which act as the interface to the D3D11 texture.
#ifndef LIBGLESV2_RENDERER_TEXTURESTORAGE11_H_
#define LIBGLESV2_RENDERER_TEXTURESTORAGE11_H_
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/TextureStorage.h"
namespace rx
{
class RenderTarget;
class RenderTarget11;
class Renderer;
class Renderer11;
class SwapChain11;
class TextureStorage11 : public TextureStorage
{
public:
TextureStorage11(Renderer *renderer, UINT bindFlags);
virtual ~TextureStorage11();
static TextureStorage11 *makeTextureStorage11(TextureStorage *storage);
static DWORD GetTextureBindFlags(DXGI_FORMAT d3dfmt, GLenum glusage, bool forceRenderable);
static bool IsTextureFormatRenderable(DXGI_FORMAT format);
UINT getBindFlags() const;
virtual ID3D11Texture2D *getBaseTexture() const;
virtual ID3D11ShaderResourceView *getSRV() = 0;
virtual RenderTarget *getRenderTarget() { return getRenderTarget(0); }
virtual RenderTarget *getRenderTarget(int level) { return NULL; }
virtual RenderTarget *getRenderTarget(GLenum faceTarget) { return getRenderTarget(faceTarget, 0); }
virtual RenderTarget *getRenderTarget(GLenum faceTarget, int level) { return NULL; }
virtual void generateMipmap(int level) {};
virtual void generateMipmap(int face, int level) {};
virtual int getLodOffset() const;
virtual bool isRenderTarget() const;
virtual bool isManaged() const;
virtual int levelCount();
UINT getSubresourceIndex(int level, int faceTarget);
bool updateSubresourceLevel(ID3D11Texture2D *texture, unsigned int sourceSubresource, int level,
int faceTarget, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
protected:
void generateMipmapLayer(RenderTarget11 *source, RenderTarget11 *dest);
Renderer11 *mRenderer;
int mLodOffset;
unsigned int mMipLevels;
ID3D11Texture2D *mTexture;
DXGI_FORMAT mTextureFormat;
DXGI_FORMAT mShaderResourceFormat;
DXGI_FORMAT mRenderTargetFormat;
DXGI_FORMAT mDepthStencilFormat;
unsigned int mTextureWidth;
unsigned int mTextureHeight;
ID3D11ShaderResourceView *mSRV;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage11);
const UINT mBindFlags;
};
class TextureStorage11_2D : public TextureStorage11
{
public:
TextureStorage11_2D(Renderer *renderer, SwapChain11 *swapchain);
TextureStorage11_2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual ~TextureStorage11_2D();
static TextureStorage11_2D *makeTextureStorage11_2D(TextureStorage *storage);
virtual ID3D11ShaderResourceView *getSRV();
virtual RenderTarget *getRenderTarget(int level);
virtual void generateMipmap(int level);
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage11_2D);
RenderTarget11 *mRenderTarget[gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS];
};
class TextureStorage11_Cube : public TextureStorage11
{
public:
TextureStorage11_Cube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
virtual ~TextureStorage11_Cube();
static TextureStorage11_Cube *makeTextureStorage11_Cube(TextureStorage *storage);
virtual ID3D11ShaderResourceView *getSRV();
virtual RenderTarget *getRenderTarget(GLenum faceTarget, int level);
virtual void generateMipmap(int face, int level);
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage11_Cube);
RenderTarget11 *mRenderTarget[6][gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS];
};
}
#endif // LIBGLESV2_RENDERER_TEXTURESTORAGE11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage11.h | C++ | bsd | 3,975 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
#include "libGLESv2/main.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/ShaderExecutable9.h"
#include "libGLESv2/renderer/SwapChain9.h"
#include "libGLESv2/renderer/TextureStorage9.h"
#include "libGLESv2/renderer/Image9.h"
#include "libGLESv2/renderer/Blit.h"
#include "libGLESv2/renderer/RenderTarget9.h"
#include "libGLESv2/renderer/VertexBuffer9.h"
#include "libGLESv2/renderer/IndexBuffer9.h"
#include "libGLESv2/renderer/BufferStorage9.h"
#include "libGLESv2/renderer/Query9.h"
#include "libGLESv2/renderer/Fence9.h"
#include "libEGL/Display.h"
// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
#define REF_RAST 0
// The "Debug This Pixel..." feature in PIX often fails when using the
// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
#if !defined(ANGLE_ENABLE_D3D9EX)
// Enables use of the IDirect3D9Ex interface, when available
#define ANGLE_ENABLE_D3D9EX 1
#endif // !defined(ANGLE_ENABLE_D3D9EX)
namespace rx
{
static const D3DFORMAT RenderTargetFormats[] =
{
D3DFMT_A1R5G5B5,
// D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
D3DFMT_A8R8G8B8,
D3DFMT_R5G6B5,
// D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
D3DFMT_X8R8G8B8
};
static const D3DFORMAT DepthStencilFormats[] =
{
D3DFMT_UNKNOWN,
// D3DFMT_D16_LOCKABLE,
D3DFMT_D32,
// D3DFMT_D15S1,
D3DFMT_D24S8,
D3DFMT_D24X8,
// D3DFMT_D24X4S4,
D3DFMT_D16,
// D3DFMT_D32F_LOCKABLE,
// D3DFMT_D24FS8
};
enum
{
MAX_VERTEX_CONSTANT_VECTORS_D3D9 = 256,
MAX_PIXEL_CONSTANT_VECTORS_SM2 = 32,
MAX_PIXEL_CONSTANT_VECTORS_SM3 = 224,
MAX_VARYING_VECTORS_SM2 = 8,
MAX_VARYING_VECTORS_SM3 = 10,
MAX_TEXTURE_IMAGE_UNITS_VTF_SM3 = 4
};
Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
{
mD3d9Module = NULL;
mD3d9 = NULL;
mD3d9Ex = NULL;
mDevice = NULL;
mDeviceEx = NULL;
mDeviceWindow = NULL;
mBlit = NULL;
mAdapter = D3DADAPTER_DEFAULT;
#if REF_RAST == 1 || defined(FORCE_REF_RAST)
mDeviceType = D3DDEVTYPE_REF;
#else
mDeviceType = D3DDEVTYPE_HAL;
#endif
mDeviceLost = false;
mMaxSupportedSamples = 0;
mMaskedClearSavedState = NULL;
mVertexDataManager = NULL;
mIndexDataManager = NULL;
mLineLoopIB = NULL;
mMaxNullColorbufferLRU = 0;
for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
{
mNullColorbufferCache[i].lruCount = 0;
mNullColorbufferCache[i].width = 0;
mNullColorbufferCache[i].height = 0;
mNullColorbufferCache[i].buffer = NULL;
}
}
Renderer9::~Renderer9()
{
releaseDeviceResources();
if (mDevice)
{
// If the device is lost, reset it first to prevent leaving the driver in an unstable state
if (testDeviceLost(false))
{
resetDevice();
}
mDevice->Release();
mDevice = NULL;
}
if (mDeviceEx)
{
mDeviceEx->Release();
mDeviceEx = NULL;
}
if (mD3d9)
{
mD3d9->Release();
mD3d9 = NULL;
}
if (mDeviceWindow)
{
DestroyWindow(mDeviceWindow);
mDeviceWindow = NULL;
}
if (mD3d9Ex)
{
mD3d9Ex->Release();
mD3d9Ex = NULL;
}
if (mD3d9Module)
{
mD3d9Module = NULL;
}
while (!mMultiSampleSupport.empty())
{
delete [] mMultiSampleSupport.begin()->second;
mMultiSampleSupport.erase(mMultiSampleSupport.begin());
}
}
Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Renderer9*, renderer));
return static_cast<rx::Renderer9*>(renderer);
}
EGLint Renderer9::initialize()
{
if (!initializeCompiler())
{
return EGL_NOT_INITIALIZED;
}
if (mSoftwareDevice)
{
mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
}
else
{
mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
}
if (mD3d9Module == NULL)
{
ERR("No D3D9 module found - aborting!\n");
return EGL_NOT_INITIALIZED;
}
typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
// Use Direct3D9Ex if available. Among other things, this version is less
// inclined to report a lost context, for example when the user switches
// desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
{
ASSERT(mD3d9Ex);
mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
ASSERT(mD3d9);
}
else
{
mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
}
if (!mD3d9)
{
ERR("Could not create D3D9 device - aborting!\n");
return EGL_NOT_INITIALIZED;
}
if (mDc != NULL)
{
// UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
}
HRESULT result;
// Give up on getting device caps after about one second.
for (int i = 0; i < 10; ++i)
{
result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
if (SUCCEEDED(result))
{
break;
}
else if (result == D3DERR_NOTAVAILABLE)
{
Sleep(100); // Give the driver some time to initialize/recover
}
else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
{
ERR("failed to get device caps (0x%x)\n", result);
return EGL_NOT_INITIALIZED;
}
}
if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
{
ERR("Renderer does not support PS 2.0. aborting!\n");
return EGL_NOT_INITIALIZED;
}
// When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
// This is required by Texture2D::convertToRenderTarget.
if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
{
ERR("Renderer does not support stretctrect from textures!\n");
return EGL_NOT_INITIALIZED;
}
mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
// ATI cards on XP have problems with non-power-of-two textures.
mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
!(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
!(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
!(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
// Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
mMinSwapInterval = 4;
mMaxSwapInterval = 0;
if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
{
mMinSwapInterval = std::min(mMinSwapInterval, 0);
mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
}
if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
{
mMinSwapInterval = std::min(mMinSwapInterval, 1);
mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
}
if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
{
mMinSwapInterval = std::min(mMinSwapInterval, 2);
mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
}
if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
{
mMinSwapInterval = std::min(mMinSwapInterval, 3);
mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
}
if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
{
mMinSwapInterval = std::min(mMinSwapInterval, 4);
mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
}
int max = 0;
for (unsigned int i = 0; i < ArraySize(RenderTargetFormats); ++i)
{
bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
{
if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
{
max = j;
}
}
}
for (unsigned int i = 0; i < ArraySize(DepthStencilFormats); ++i)
{
if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
continue;
bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
{
if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
{
max = j;
}
}
}
mMaxSupportedSamples = max;
static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
static const TCHAR className[] = TEXT("STATIC");
mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
{
return EGL_BAD_ALLOC;
}
if (FAILED(result))
{
result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
return EGL_BAD_ALLOC;
}
}
if (mD3d9Ex)
{
result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
ASSERT(SUCCEEDED(result));
}
mVertexShaderCache.initialize(mDevice);
mPixelShaderCache.initialize(mDevice);
// Check occlusion query support
IDirect3DQuery9 *occlusionQuery = NULL;
if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &occlusionQuery)) && occlusionQuery)
{
occlusionQuery->Release();
mOcclusionQuerySupport = true;
}
else
{
mOcclusionQuerySupport = false;
}
// Check event query support
IDirect3DQuery9 *eventQuery = NULL;
if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &eventQuery)) && eventQuery)
{
eventQuery->Release();
mEventQuerySupport = true;
}
else
{
mEventQuerySupport = false;
}
D3DDISPLAYMODE currentDisplayMode;
mD3d9->GetAdapterDisplayMode(mAdapter, ¤tDisplayMode);
// Check vertex texture support
// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
// We test this using D3D9 by checking support for the R16F format.
mVertexTextureSupport = mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F));
// Check depth texture support
// we use INTZ for depth textures in Direct3D9
// we also want NULL texture support to ensure the we can make depth-only FBOs
// see http://aras-p.info/texts/D3D9GPUHacks.html
mDepthTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
// Check 32 bit floating point texture support
mFloat32FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
mFloat32RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
if (!mFloat32FilterSupport && !mFloat32RenderSupport)
{
mFloat32TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
}
else
{
mFloat32TextureSupport = true;
}
// Check 16 bit floating point texture support
mFloat16FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
mFloat16RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
if (!mFloat16FilterSupport && !mFloat16RenderSupport)
{
mFloat16TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
}
else
{
mFloat16TextureSupport = true;
}
// Check DXT texture support
mDXT1TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
mDXT3TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
mDXT5TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
// Check luminance[alpha] texture support
mLuminanceTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
mLuminanceAlphaTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
initializeDevice();
return EGL_SUCCESS;
}
// do any one-time device initialization
// NOTE: this is also needed after a device lost/reset
// to reset the scene status and ensure the default states are reset.
void Renderer9::initializeDevice()
{
// Permanent non-default states
mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
{
mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
}
else
{
mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
}
markAllStateDirty();
mSceneStarted = false;
ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
mBlit = new Blit(this);
mVertexDataManager = new rx::VertexDataManager(this);
mIndexDataManager = new rx::IndexDataManager(this);
}
D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
{
D3DPRESENT_PARAMETERS presentParameters = {0};
// The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
presentParameters.BackBufferCount = 1;
presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
presentParameters.BackBufferWidth = 1;
presentParameters.BackBufferHeight = 1;
presentParameters.EnableAutoDepthStencil = FALSE;
presentParameters.Flags = 0;
presentParameters.hDeviceWindow = mDeviceWindow;
presentParameters.MultiSampleQuality = 0;
presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
presentParameters.Windowed = TRUE;
return presentParameters;
}
int Renderer9::generateConfigs(ConfigDesc **configDescList)
{
D3DDISPLAYMODE currentDisplayMode;
mD3d9->GetAdapterDisplayMode(mAdapter, ¤tDisplayMode);
unsigned int numRenderFormats = ArraySize(RenderTargetFormats);
unsigned int numDepthFormats = ArraySize(DepthStencilFormats);
(*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
int numConfigs = 0;
for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
{
D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
if (SUCCEEDED(result))
{
for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
{
D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
HRESULT result = D3D_OK;
if(depthStencilFormat != D3DFMT_UNKNOWN)
{
result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
}
if (SUCCEEDED(result))
{
if(depthStencilFormat != D3DFMT_UNKNOWN)
{
result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
}
if (SUCCEEDED(result))
{
ConfigDesc newConfig;
newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
(*configDescList)[numConfigs++] = newConfig;
}
}
}
}
}
return numConfigs;
}
void Renderer9::deleteConfigs(ConfigDesc *configDescList)
{
delete [] (configDescList);
}
void Renderer9::startScene()
{
if (!mSceneStarted)
{
long result = mDevice->BeginScene();
if (SUCCEEDED(result)) {
// This is defensive checking against the device being
// lost at unexpected times.
mSceneStarted = true;
}
}
}
void Renderer9::endScene()
{
if (mSceneStarted)
{
// EndScene can fail if the device was lost, for example due
// to a TDR during a draw call.
mDevice->EndScene();
mSceneStarted = false;
}
}
void Renderer9::sync(bool block)
{
HRESULT result;
IDirect3DQuery9* query = allocateEventQuery();
if (!query)
{
return;
}
result = query->Issue(D3DISSUE_END);
ASSERT(SUCCEEDED(result));
do
{
result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
if(block && result == S_FALSE)
{
// Keep polling, but allow other threads to do something useful first
Sleep(0);
// explicitly check for device loss
// some drivers seem to return S_FALSE even if the device is lost
// instead of D3DERR_DEVICELOST like they should
if (testDeviceLost(false))
{
result = D3DERR_DEVICELOST;
}
}
}
while(block && result == S_FALSE);
freeEventQuery(query);
if (d3d9::isDeviceLostError(result))
{
notifyDeviceLost();
}
}
SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
{
return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
}
IDirect3DQuery9* Renderer9::allocateEventQuery()
{
IDirect3DQuery9 *query = NULL;
if (mEventQueryPool.empty())
{
HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
ASSERT(SUCCEEDED(result));
}
else
{
query = mEventQueryPool.back();
mEventQueryPool.pop_back();
}
return query;
}
void Renderer9::freeEventQuery(IDirect3DQuery9* query)
{
if (mEventQueryPool.size() > 1000)
{
query->Release();
}
else
{
mEventQueryPool.push_back(query);
}
}
IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
{
return mVertexShaderCache.create(function, length);
}
IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
{
return mPixelShaderCache.create(function, length);
}
HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
{
D3DPOOL Pool = getBufferPool(Usage);
return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
}
VertexBuffer *Renderer9::createVertexBuffer()
{
return new VertexBuffer9(this);
}
HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
{
D3DPOOL Pool = getBufferPool(Usage);
return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
}
IndexBuffer *Renderer9::createIndexBuffer()
{
return new IndexBuffer9(this);
}
BufferStorage *Renderer9::createBufferStorage()
{
return new BufferStorage9();
}
QueryImpl *Renderer9::createQuery(GLenum type)
{
return new Query9(this, type);
}
FenceImpl *Renderer9::createFence()
{
return new Fence9(this);
}
void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
{
bool *forceSetSamplers = (type == gl::SAMPLER_PIXEL) ? mForceSetPixelSamplerStates : mForceSetVertexSamplerStates;
gl::SamplerState *appliedSamplers = (type == gl::SAMPLER_PIXEL) ? mCurPixelSamplerStates: mCurVertexSamplerStates;
if (forceSetSamplers[index] || memcmp(&samplerState, &appliedSamplers[index], sizeof(gl::SamplerState)) != 0)
{
int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
int d3dSampler = index + d3dSamplerOffset;
mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
if (mSupportsTextureFilterAnisotropy)
{
mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
}
}
forceSetSamplers[index] = false;
appliedSamplers[index] = samplerState;
}
void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
{
int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
int d3dSampler = index + d3dSamplerOffset;
IDirect3DBaseTexture9 *d3dTexture = NULL;
unsigned int serial = 0;
bool forceSetTexture = false;
unsigned int *appliedSerials = (type == gl::SAMPLER_PIXEL) ? mCurPixelTextureSerials : mCurVertexTextureSerials;
if (texture)
{
TextureStorageInterface *texStorage = texture->getNativeTexture();
if (texStorage)
{
TextureStorage9 *storage9 = TextureStorage9::makeTextureStorage9(texStorage->getStorageInstance());
d3dTexture = storage9->getBaseTexture();
}
// If we get NULL back from getBaseTexture here, something went wrong
// in the texture class and we're unexpectedly missing the d3d texture
ASSERT(d3dTexture != NULL);
serial = texture->getTextureSerial();
forceSetTexture = texture->hasDirtyImages();
}
if (forceSetTexture || appliedSerials[index] != serial)
{
mDevice->SetTexture(d3dSampler, d3dTexture);
}
appliedSerials[index] = serial;
}
void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
{
bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
if (rasterStateChanged)
{
// Set the cull mode
if (rasterState.cullFace)
{
mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
}
else
{
mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
}
if (rasterState.polygonOffsetFill)
{
if (mCurDepthSize > 0)
{
mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
}
}
else
{
mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
}
mCurRasterState = rasterState;
}
mForceSetRasterState = false;
}
void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
{
bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
if (blendStateChanged || blendColorChanged)
{
if (blendState.blend)
{
mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
{
mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
}
else
{
mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
gl::unorm<8>(blendColor.alpha),
gl::unorm<8>(blendColor.alpha),
gl::unorm<8>(blendColor.alpha)));
}
mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
blendState.destBlendRGB != blendState.destBlendAlpha ||
blendState.blendEquationRGB != blendState.blendEquationAlpha)
{
mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
}
else
{
mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
}
}
else
{
mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
if (blendState.sampleAlphaToCoverage)
{
FIXME("Sample alpha to coverage is unimplemented.");
}
// Set the color mask
bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
// Apparently some ATI cards have a bug where a draw with a zero color
// write mask can cause later draws to have incorrect results. Instead,
// set a nonzero color write mask but modify the blend state so that no
// drawing is done.
// http://code.google.com/p/angleproject/issues/detail?id=169
DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
blendState.colorMaskBlue, blendState.colorMaskAlpha);
if (colorMask == 0 && !zeroColorMaskAllowed)
{
// Enable green channel, but set blending so nothing will be drawn.
mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
}
else
{
mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
}
mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
mCurBlendState = blendState;
mCurBlendColor = blendColor;
}
if (sampleMaskChanged)
{
// Set the multisample mask
mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
mCurSampleMask = sampleMask;
}
mForceSetBlendState = false;
}
void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW)
{
bool depthStencilStateChanged = mForceSetDepthStencilState ||
memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
stencilBackRef != mCurStencilBackRef;
bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
if (depthStencilStateChanged)
{
if (depthStencilState.depthTest)
{
mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
}
else
{
mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
}
mCurDepthStencilState = depthStencilState;
}
if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
{
if (depthStencilState.stencilTest && mCurStencilSize > 0)
{
mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
// FIXME: Unsupported by D3D9
const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
stencilRef != stencilBackRef ||
depthStencilState.stencilMask != depthStencilState.stencilBackMask)
{
ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
return gl::error(GL_INVALID_OPERATION);
}
// get the maximum size of the stencil ref
unsigned int maxStencil = (1 << mCurStencilSize) - 1;
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
depthStencilState.stencilWritemask);
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
(stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
depthStencilState.stencilMask);
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
depthStencilState.stencilBackWritemask);
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
(stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
depthStencilState.stencilBackMask);
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
}
else
{
mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
}
mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
mCurStencilRef = stencilRef;
mCurStencilBackRef = stencilBackRef;
mCurFrontFaceCCW = frontFaceCCW;
}
mForceSetDepthStencilState = false;
}
void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
{
bool scissorChanged = mForceSetScissor ||
memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
enabled != mScissorEnabled;
if (scissorChanged)
{
if (enabled)
{
RECT rect;
rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
mDevice->SetScissorRect(&rect);
}
mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
mScissorEnabled = enabled;
mCurScissor = scissor;
}
mForceSetScissor = false;
}
bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport)
{
gl::Rectangle actualViewport = viewport;
float actualZNear = gl::clamp01(zNear);
float actualZFar = gl::clamp01(zFar);
if (ignoreViewport)
{
actualViewport.x = 0;
actualViewport.y = 0;
actualViewport.width = mRenderTargetDesc.width;
actualViewport.height = mRenderTargetDesc.height;
actualZNear = 0.0f;
actualZFar = 1.0f;
}
D3DVIEWPORT9 dxViewport;
dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
dxViewport.MinZ = actualZNear;
dxViewport.MaxZ = actualZFar;
if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
{
return false; // Nothing to render
}
bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
actualZNear != mCurNear || actualZFar != mCurFar;
if (viewportChanged)
{
mDevice->SetViewport(&dxViewport);
mCurViewport = actualViewport;
mCurNear = actualZNear;
mCurFar = actualZFar;
dx_VertexConstants vc = {0};
dx_PixelConstants pc = {0};
vc.viewAdjust[0] = (float)((actualViewport.width - (int)dxViewport.Width) + 2 * (actualViewport.x - (int)dxViewport.X) - 1) / dxViewport.Width;
vc.viewAdjust[1] = (float)((actualViewport.height - (int)dxViewport.Height) + 2 * (actualViewport.y - (int)dxViewport.Y) - 1) / dxViewport.Height;
vc.viewAdjust[2] = (float)actualViewport.width / dxViewport.Width;
vc.viewAdjust[3] = (float)actualViewport.height / dxViewport.Height;
pc.viewCoords[0] = actualViewport.width * 0.5f;
pc.viewCoords[1] = actualViewport.height * 0.5f;
pc.viewCoords[2] = actualViewport.x + (actualViewport.width * 0.5f);
pc.viewCoords[3] = actualViewport.y + (actualViewport.height * 0.5f);
pc.depthFront[0] = (actualZFar - actualZNear) * 0.5f;
pc.depthFront[1] = (actualZNear + actualZFar) * 0.5f;
pc.depthFront[2] = !gl::IsTriangleMode(drawMode) ? 0.0f : (frontFace == GL_CCW ? 1.0f : -1.0f);;
vc.depthRange[0] = actualZNear;
vc.depthRange[1] = actualZFar;
vc.depthRange[2] = actualZFar - actualZNear;
pc.depthRange[0] = actualZNear;
pc.depthRange[1] = actualZFar;
pc.depthRange[2] = actualZFar - actualZNear;
if (memcmp(&vc, &mVertexConstants, sizeof(dx_VertexConstants)) != 0)
{
mVertexConstants = vc;
mDxUniformsDirty = true;
}
if (memcmp(&pc, &mPixelConstants, sizeof(dx_PixelConstants)) != 0)
{
mPixelConstants = pc;
mDxUniformsDirty = true;
}
}
mForceSetViewport = false;
return true;
}
bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
{
switch (mode)
{
case GL_POINTS:
mPrimitiveType = D3DPT_POINTLIST;
mPrimitiveCount = count;
break;
case GL_LINES:
mPrimitiveType = D3DPT_LINELIST;
mPrimitiveCount = count / 2;
break;
case GL_LINE_LOOP:
mPrimitiveType = D3DPT_LINESTRIP;
mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
break;
case GL_LINE_STRIP:
mPrimitiveType = D3DPT_LINESTRIP;
mPrimitiveCount = count - 1;
break;
case GL_TRIANGLES:
mPrimitiveType = D3DPT_TRIANGLELIST;
mPrimitiveCount = count / 3;
break;
case GL_TRIANGLE_STRIP:
mPrimitiveType = D3DPT_TRIANGLESTRIP;
mPrimitiveCount = count - 2;
break;
case GL_TRIANGLE_FAN:
mPrimitiveType = D3DPT_TRIANGLEFAN;
mPrimitiveCount = count - 2;
break;
default:
return gl::error(GL_INVALID_ENUM, false);
}
return mPrimitiveCount > 0;
}
gl::Renderbuffer *Renderer9::getNullColorbuffer(gl::Renderbuffer *depthbuffer)
{
if (!depthbuffer)
{
ERR("Unexpected null depthbuffer for depth-only FBO.");
return NULL;
}
GLsizei width = depthbuffer->getWidth();
GLsizei height = depthbuffer->getHeight();
// search cached nullcolorbuffers
for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
{
if (mNullColorbufferCache[i].buffer != NULL &&
mNullColorbufferCache[i].width == width &&
mNullColorbufferCache[i].height == height)
{
mNullColorbufferCache[i].lruCount = ++mMaxNullColorbufferLRU;
return mNullColorbufferCache[i].buffer;
}
}
gl::Renderbuffer *nullbuffer = new gl::Renderbuffer(this, 0, new gl::Colorbuffer(this, width, height, GL_NONE, 0));
// add nullbuffer to the cache
NullColorbufferCacheEntry *oldest = &mNullColorbufferCache[0];
for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
{
if (mNullColorbufferCache[i].lruCount < oldest->lruCount)
{
oldest = &mNullColorbufferCache[i];
}
}
delete oldest->buffer;
oldest->buffer = nullbuffer;
oldest->lruCount = ++mMaxNullColorbufferLRU;
oldest->width = width;
oldest->height = height;
return nullbuffer;
}
bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
{
// if there is no color attachment we must synthesize a NULL colorattachment
// to keep the D3D runtime happy. This should only be possible if depth texturing.
gl::Renderbuffer *renderbufferObject = NULL;
if (framebuffer->getColorbufferType(0) != GL_NONE)
{
renderbufferObject = framebuffer->getColorbuffer(0);
}
else
{
renderbufferObject = getNullColorbuffer(framebuffer->getDepthbuffer());
}
if (!renderbufferObject)
{
ERR("unable to locate renderbuffer for FBO.");
return false;
}
bool renderTargetChanged = false;
unsigned int renderTargetSerial = renderbufferObject->getSerial();
if (renderTargetSerial != mAppliedRenderTargetSerial)
{
// Apply the render target on the device
IDirect3DSurface9 *renderTargetSurface = NULL;
RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
if (renderTarget)
{
renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
}
if (!renderTargetSurface)
{
ERR("render target pointer unexpectedly null.");
return false; // Context must be lost
}
mDevice->SetRenderTarget(0, renderTargetSurface);
renderTargetSurface->Release();
mAppliedRenderTargetSerial = renderTargetSerial;
renderTargetChanged = true;
}
gl::Renderbuffer *depthStencil = NULL;
unsigned int depthbufferSerial = 0;
unsigned int stencilbufferSerial = 0;
if (framebuffer->getDepthbufferType() != GL_NONE)
{
depthStencil = framebuffer->getDepthbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
return false;
}
depthbufferSerial = depthStencil->getSerial();
}
else if (framebuffer->getStencilbufferType() != GL_NONE)
{
depthStencil = framebuffer->getStencilbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
return false;
}
stencilbufferSerial = depthStencil->getSerial();
}
if (depthbufferSerial != mAppliedDepthbufferSerial ||
stencilbufferSerial != mAppliedStencilbufferSerial ||
!mDepthStencilInitialized)
{
unsigned int depthSize = 0;
unsigned int stencilSize = 0;
// Apply the depth stencil on the device
if (depthStencil)
{
IDirect3DSurface9 *depthStencilSurface = NULL;
RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
if (depthStencilRenderTarget)
{
depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
}
if (!depthStencilSurface)
{
ERR("depth stencil pointer unexpectedly null.");
return false; // Context must be lost
}
mDevice->SetDepthStencilSurface(depthStencilSurface);
depthStencilSurface->Release();
depthSize = depthStencil->getDepthSize();
stencilSize = depthStencil->getStencilSize();
}
else
{
mDevice->SetDepthStencilSurface(NULL);
}
if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
{
mCurDepthSize = depthSize;
mForceSetRasterState = true;
}
if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
{
mCurStencilSize = stencilSize;
mForceSetDepthStencilState = true;
}
mAppliedDepthbufferSerial = depthbufferSerial;
mAppliedStencilbufferSerial = stencilbufferSerial;
mDepthStencilInitialized = true;
}
if (renderTargetChanged || !mRenderTargetDescInitialized)
{
mForceSetScissor = true;
mForceSetViewport = true;
mRenderTargetDesc.width = renderbufferObject->getWidth();
mRenderTargetDesc.height = renderbufferObject->getHeight();
mRenderTargetDesc.format = renderbufferObject->getActualFormat();
mRenderTargetDescInitialized = true;
}
return true;
}
GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
{
TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
if (err != GL_NO_ERROR)
{
return err;
}
return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
}
// Applies the indices and element array bindings to the Direct3D 9 device
GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
{
GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
if (err == GL_NO_ERROR)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(indexInfo->storage == NULL);
if (indexInfo->serial != mAppliedIBSerial)
{
IndexBuffer9* indexBuffer = IndexBuffer9::makeIndexBuffer9(indexInfo->indexBuffer);
mDevice->SetIndices(indexBuffer->getBuffer());
mAppliedIBSerial = indexInfo->serial;
}
}
return err;
}
void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
{
startScene();
if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, GL_NONE, NULL, 0, NULL);
}
else if (instances > 0)
{
StaticIndexBufferInterface *countingIB = mIndexDataManager->getCountingIndices(count);
if (countingIB)
{
if (mAppliedIBSerial != countingIB->getSerial())
{
IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(countingIB->getIndexBuffer());
mDevice->SetIndices(indexBuffer->getBuffer());
mAppliedIBSerial = countingIB->getSerial();
}
for (int i = 0; i < mRepeatDraw; i++)
{
mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
}
}
else
{
ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
else // Regular case
{
mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
}
}
void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei /*instances*/)
{
startScene();
if (mode == GL_POINTS)
{
drawIndexedPoints(count, type, indices, elementArrayBuffer);
}
else if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
}
else
{
for (int i = 0; i < mRepeatDraw; i++)
{
GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
}
}
}
void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
{
// Get the raw indices for an indexed draw
if (type != GL_NONE && elementArrayBuffer)
{
gl::Buffer *indexBuffer = elementArrayBuffer;
BufferStorage *storage = indexBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
UINT startIndex = 0;
if (get32BitIndexSupport())
{
if (!mLineLoopIB)
{
mLineLoopIB = new StreamingIndexBufferInterface(this);
if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mLineLoopIB;
mLineLoopIB = NULL;
ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
const int spaceNeeded = (count + 1) * sizeof(unsigned int);
if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
{
ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
if (offset == -1 || mappedMemory == NULL)
{
ERR("Could not map index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
startIndex = static_cast<UINT>(offset) / 4;
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
switch (type)
{
case GL_NONE: // Non-indexed draw
for (int i = 0; i < count; i++)
{
data[i] = i;
}
data[count] = 0;
break;
case GL_UNSIGNED_BYTE:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLubyte*>(indices)[i];
}
data[count] = static_cast<const GLubyte*>(indices)[0];
break;
case GL_UNSIGNED_SHORT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLushort*>(indices)[i];
}
data[count] = static_cast<const GLushort*>(indices)[0];
break;
case GL_UNSIGNED_INT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLuint*>(indices)[i];
}
data[count] = static_cast<const GLuint*>(indices)[0];
break;
default: UNREACHABLE();
}
if (!mLineLoopIB->unmapBuffer())
{
ERR("Could not unmap index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
else
{
if (!mLineLoopIB)
{
mLineLoopIB = new StreamingIndexBufferInterface(this);
if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
{
delete mLineLoopIB;
mLineLoopIB = NULL;
ERR("Could not create a 16-bit looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
const int spaceNeeded = (count + 1) * sizeof(unsigned short);
if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT))
{
ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
if (offset == -1 || mappedMemory == NULL)
{
ERR("Could not map index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
startIndex = static_cast<UINT>(offset) / 2;
unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
switch (type)
{
case GL_NONE: // Non-indexed draw
for (int i = 0; i < count; i++)
{
data[i] = i;
}
data[count] = 0;
break;
case GL_UNSIGNED_BYTE:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLubyte*>(indices)[i];
}
data[count] = static_cast<const GLubyte*>(indices)[0];
break;
case GL_UNSIGNED_SHORT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLushort*>(indices)[i];
}
data[count] = static_cast<const GLushort*>(indices)[0];
break;
case GL_UNSIGNED_INT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLuint*>(indices)[i];
}
data[count] = static_cast<const GLuint*>(indices)[0];
break;
default: UNREACHABLE();
}
if (!mLineLoopIB->unmapBuffer())
{
ERR("Could not unmap index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
if (mAppliedIBSerial != mLineLoopIB->getSerial())
{
IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(mLineLoopIB->getIndexBuffer());
mDevice->SetIndices(indexBuffer->getBuffer());
mAppliedIBSerial = mLineLoopIB->getSerial();
}
mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
}
template <typename T>
static void drawPoints(IDirect3DDevice9* device, GLsizei count, const GLvoid *indices)
{
for (int i = 0; i < count; i++)
{
unsigned int indexValue = static_cast<unsigned int>(static_cast<const T*>(indices)[i]);
device->DrawPrimitive(D3DPT_POINTLIST, indexValue, 1);
}
}
void Renderer9::drawIndexedPoints(GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer)
{
// Drawing index point lists is unsupported in d3d9, fall back to a regular DrawPrimitive call
// for each individual point. This call is not expected to happen often.
if (elementArrayBuffer)
{
BufferStorage *storage = elementArrayBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
switch (type)
{
case GL_UNSIGNED_BYTE: drawPoints<GLubyte>(mDevice, count, indices); break;
case GL_UNSIGNED_SHORT: drawPoints<GLushort>(mDevice, count, indices); break;
case GL_UNSIGNED_INT: drawPoints<GLuint>(mDevice, count, indices); break;
default: UNREACHABLE();
}
}
void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
{
unsigned int programBinarySerial = programBinary->getSerial();
if (programBinarySerial != mAppliedProgramBinarySerial)
{
ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
IDirect3DVertexShader9 *vertexShader = NULL;
if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
IDirect3DPixelShader9 *pixelShader = NULL;
if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
mDevice->SetPixelShader(pixelShader);
mDevice->SetVertexShader(vertexShader);
programBinary->dirtyAllUniforms();
mDxUniformsDirty = true;
mAppliedProgramBinarySerial = programBinarySerial;
}
}
void Renderer9::applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray)
{
for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
{
gl::Uniform *targetUniform = *ub;
if (targetUniform->dirty)
{
GLfloat *f = (GLfloat*)targetUniform->data;
GLint *i = (GLint*)targetUniform->data;
switch (targetUniform->type)
{
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
break;
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
applyUniformnbv(targetUniform, i);
break;
case GL_FLOAT:
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
applyUniformnfv(targetUniform, f);
break;
case GL_INT:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
applyUniformniv(targetUniform, i);
break;
default:
UNREACHABLE();
}
targetUniform->dirty = false;
}
}
// Driver uniforms
if (mDxUniformsDirty)
{
mDevice->SetVertexShaderConstantF(0, (float*)&mVertexConstants, sizeof(dx_VertexConstants) / sizeof(float[4]));
mDevice->SetPixelShaderConstantF(0, (float*)&mPixelConstants, sizeof(dx_PixelConstants) / sizeof(float[4]));
mDxUniformsDirty = false;
}
}
void Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
{
if (targetUniform->psRegisterIndex >= 0)
{
mDevice->SetPixelShaderConstantF(targetUniform->psRegisterIndex, v, targetUniform->registerCount);
}
if (targetUniform->vsRegisterIndex >= 0)
{
mDevice->SetVertexShaderConstantF(targetUniform->vsRegisterIndex, v, targetUniform->registerCount);
}
}
void Renderer9::applyUniformniv(gl::Uniform *targetUniform, const GLint *v)
{
ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
for (unsigned int i = 0; i < targetUniform->registerCount; i++)
{
vector[i][0] = (GLfloat)v[4 * i + 0];
vector[i][1] = (GLfloat)v[4 * i + 1];
vector[i][2] = (GLfloat)v[4 * i + 2];
vector[i][3] = (GLfloat)v[4 * i + 3];
}
applyUniformnfv(targetUniform, (GLfloat*)vector);
}
void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, const GLint *v)
{
ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
for (unsigned int i = 0; i < targetUniform->registerCount; i++)
{
vector[i][0] = (v[4 * i + 0] == GL_FALSE) ? 0.0f : 1.0f;
vector[i][1] = (v[4 * i + 1] == GL_FALSE) ? 0.0f : 1.0f;
vector[i][2] = (v[4 * i + 2] == GL_FALSE) ? 0.0f : 1.0f;
vector[i][3] = (v[4 * i + 3] == GL_FALSE) ? 0.0f : 1.0f;
}
applyUniformnfv(targetUniform, (GLfloat*)vector);
}
void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
{
D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
gl::unorm<8>(clearParams.colorClearValue.red),
gl::unorm<8>(clearParams.colorClearValue.green),
gl::unorm<8>(clearParams.colorClearValue.blue));
float depth = gl::clamp01(clearParams.depthClearValue);
int stencil = clearParams.stencilClearValue & 0x000000FF;
unsigned int stencilUnmasked = 0x0;
if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
{
unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
stencilUnmasked = (0x1 << stencilSize) - 1;
}
bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
(clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
!(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
clearParams.colorMaskBlue && alphaUnmasked);
if (needMaskedColorClear || needMaskedStencilClear)
{
// State which is altered in all paths from this point to the clear call is saved.
// State which is altered in only some paths will be flagged dirty in the case that
// that path is taken.
HRESULT hr;
if (mMaskedClearSavedState == NULL)
{
hr = mDevice->BeginStateBlock();
ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
mDevice->SetPixelShader(NULL);
mDevice->SetVertexShader(NULL);
mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
mDevice->SetStreamSource(0, NULL, 0, 0);
mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mDevice->SetStreamSourceFreq(i, 1);
}
hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
}
ASSERT(mMaskedClearSavedState != NULL);
if (mMaskedClearSavedState != NULL)
{
hr = mMaskedClearSavedState->Capture();
ASSERT(SUCCEEDED(hr));
}
mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
if (clearParams.mask & GL_COLOR_BUFFER_BIT)
{
mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
clearParams.colorMaskGreen,
clearParams.colorMaskBlue,
clearParams.colorMaskAlpha));
}
else
{
mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
}
if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
{
mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
}
else
{
mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
}
mDevice->SetPixelShader(NULL);
mDevice->SetVertexShader(NULL);
mDevice->SetFVF(D3DFVF_XYZRHW);
mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mDevice->SetStreamSourceFreq(i, 1);
}
float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
quad[0][0] = -0.5f;
quad[0][1] = mRenderTargetDesc.height - 0.5f;
quad[0][2] = 0.0f;
quad[0][3] = 1.0f;
quad[1][0] = mRenderTargetDesc.width - 0.5f;
quad[1][1] = mRenderTargetDesc.height - 0.5f;
quad[1][2] = 0.0f;
quad[1][3] = 1.0f;
quad[2][0] = -0.5f;
quad[2][1] = -0.5f;
quad[2][2] = 0.0f;
quad[2][3] = 1.0f;
quad[3][0] = mRenderTargetDesc.width - 0.5f;
quad[3][1] = -0.5f;
quad[3][2] = 0.0f;
quad[3][3] = 1.0f;
startScene();
mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
{
mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
}
if (mMaskedClearSavedState != NULL)
{
mMaskedClearSavedState->Apply();
}
}
else if (clearParams.mask)
{
DWORD dxClearFlags = 0;
if (clearParams.mask & GL_COLOR_BUFFER_BIT)
{
dxClearFlags |= D3DCLEAR_TARGET;
}
if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
{
dxClearFlags |= D3DCLEAR_ZBUFFER;
}
if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
{
dxClearFlags |= D3DCLEAR_STENCIL;
}
mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
}
}
void Renderer9::markAllStateDirty()
{
mAppliedRenderTargetSerial = 0;
mAppliedDepthbufferSerial = 0;
mAppliedStencilbufferSerial = 0;
mDepthStencilInitialized = false;
mRenderTargetDescInitialized = false;
mForceSetDepthStencilState = true;
mForceSetRasterState = true;
mForceSetScissor = true;
mForceSetViewport = true;
mForceSetBlendState = true;
for (unsigned int i = 0; i < gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetVertexSamplerStates[i] = true;
mCurVertexTextureSerials[i] = 0;
}
for (unsigned int i = 0; i < gl::MAX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetPixelSamplerStates[i] = true;
mCurPixelTextureSerials[i] = 0;
}
mAppliedIBSerial = 0;
mAppliedProgramBinarySerial = 0;
mDxUniformsDirty = true;
mVertexDeclarationCache.markStateDirty();
}
void Renderer9::releaseDeviceResources()
{
while (!mEventQueryPool.empty())
{
mEventQueryPool.back()->Release();
mEventQueryPool.pop_back();
}
if (mMaskedClearSavedState)
{
mMaskedClearSavedState->Release();
mMaskedClearSavedState = NULL;
}
mVertexShaderCache.clear();
mPixelShaderCache.clear();
delete mBlit;
mBlit = NULL;
delete mVertexDataManager;
mVertexDataManager = NULL;
delete mIndexDataManager;
mIndexDataManager = NULL;
delete mLineLoopIB;
mLineLoopIB = NULL;
for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
{
delete mNullColorbufferCache[i].buffer;
mNullColorbufferCache[i].buffer = NULL;
}
}
void Renderer9::notifyDeviceLost()
{
mDeviceLost = true;
mDisplay->notifyDeviceLost();
}
bool Renderer9::isDeviceLost()
{
return mDeviceLost;
}
// set notify to true to broadcast a message to all contexts of the device loss
bool Renderer9::testDeviceLost(bool notify)
{
HRESULT status = S_OK;
if (mDeviceEx)
{
status = mDeviceEx->CheckDeviceState(NULL);
}
else if (mDevice)
{
status = mDevice->TestCooperativeLevel();
}
else
{
// No device yet, so no reset required
}
bool isLost = FAILED(status) || d3d9::isDeviceLostError(status);
if (isLost)
{
// ensure we note the device loss --
// we'll probably get this done again by notifyDeviceLost
// but best to remember it!
// Note that we don't want to clear the device loss status here
// -- this needs to be done by resetDevice
mDeviceLost = true;
if (notify)
{
notifyDeviceLost();
}
}
return isLost;
}
bool Renderer9::testDeviceResettable()
{
HRESULT status = D3D_OK;
if (mDeviceEx)
{
status = mDeviceEx->CheckDeviceState(NULL);
}
else if (mDevice)
{
status = mDevice->TestCooperativeLevel();
}
// On D3D9Ex, DEVICELOST represents a hung device that needs to be restarted
// DEVICEREMOVED indicates the device has been stopped and must be recreated
switch (status)
{
case D3DERR_DEVICENOTRESET:
case D3DERR_DEVICEHUNG:
return true;
case D3DERR_DEVICELOST:
return (mDeviceEx != NULL);
case D3DERR_DEVICEREMOVED:
UNIMPLEMENTED();
return false;
default:
return false;
}
}
bool Renderer9::resetDevice()
{
releaseDeviceResources();
D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
HRESULT result = D3D_OK;
bool lost = testDeviceLost(false);
int attempts = 3;
while (lost && attempts > 0)
{
if (mDeviceEx)
{
Sleep(500); // Give the graphics driver some CPU time
result = mDeviceEx->ResetEx(&presentParameters, NULL);
}
else
{
result = mDevice->TestCooperativeLevel();
while (result == D3DERR_DEVICELOST)
{
Sleep(100); // Give the graphics driver some CPU time
result = mDevice->TestCooperativeLevel();
}
if (result == D3DERR_DEVICENOTRESET)
{
result = mDevice->Reset(&presentParameters);
}
}
lost = testDeviceLost(false);
attempts --;
}
if (FAILED(result))
{
ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
return false;
}
// reset device defaults
initializeDevice();
mDeviceLost = false;
return true;
}
DWORD Renderer9::getAdapterVendor() const
{
return mAdapterIdentifier.VendorId;
}
std::string Renderer9::getRendererDescription() const
{
std::ostringstream rendererString;
rendererString << mAdapterIdentifier.Description;
if (getShareHandleSupport())
{
rendererString << " Direct3D9Ex";
}
else
{
rendererString << " Direct3D9";
}
rendererString << " vs_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.VertexShaderVersion) << "_" << D3DSHADER_VERSION_MINOR(mDeviceCaps.VertexShaderVersion);
rendererString << " ps_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion) << "_" << D3DSHADER_VERSION_MINOR(mDeviceCaps.PixelShaderVersion);
return rendererString.str();
}
GUID Renderer9::getAdapterIdentifier() const
{
return mAdapterIdentifier.DeviceIdentifier;
}
void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
{
for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
{
HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
}
}
bool Renderer9::getBGRATextureSupport() const
{
// DirectX 9 always supports BGRA
return true;
}
bool Renderer9::getDXT1TextureSupport()
{
return mDXT1TextureSupport;
}
bool Renderer9::getDXT3TextureSupport()
{
return mDXT3TextureSupport;
}
bool Renderer9::getDXT5TextureSupport()
{
return mDXT5TextureSupport;
}
bool Renderer9::getDepthTextureSupport() const
{
return mDepthTextureSupport;
}
bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
{
*filtering = mFloat32FilterSupport;
*renderable = mFloat32RenderSupport;
return mFloat32TextureSupport;
}
bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
{
*filtering = mFloat16FilterSupport;
*renderable = mFloat16RenderSupport;
return mFloat16TextureSupport;
}
bool Renderer9::getLuminanceTextureSupport()
{
return mLuminanceTextureSupport;
}
bool Renderer9::getLuminanceAlphaTextureSupport()
{
return mLuminanceAlphaTextureSupport;
}
bool Renderer9::getTextureFilterAnisotropySupport() const
{
return mSupportsTextureFilterAnisotropy;
}
float Renderer9::getTextureMaxAnisotropy() const
{
if (mSupportsTextureFilterAnisotropy)
{
return static_cast<float>(mDeviceCaps.MaxAnisotropy);
}
return 1.0f;
}
bool Renderer9::getEventQuerySupport()
{
return mEventQuerySupport;
}
unsigned int Renderer9::getMaxVertexTextureImageUnits() const
{
META_ASSERT(MAX_TEXTURE_IMAGE_UNITS_VTF_SM3 <= gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
return mVertexTextureSupport ? MAX_TEXTURE_IMAGE_UNITS_VTF_SM3 : 0;
}
unsigned int Renderer9::getMaxCombinedTextureImageUnits() const
{
return gl::MAX_TEXTURE_IMAGE_UNITS + getMaxVertexTextureImageUnits();
}
unsigned int Renderer9::getReservedVertexUniformVectors() const
{
return 2; // dx_ViewAdjust and dx_DepthRange.
}
unsigned int Renderer9::getReservedFragmentUniformVectors() const
{
return 3; // dx_ViewCoords, dx_DepthFront and dx_DepthRange.
}
unsigned int Renderer9::getMaxVertexUniformVectors() const
{
return MAX_VERTEX_CONSTANT_VECTORS_D3D9 - getReservedVertexUniformVectors();
}
unsigned int Renderer9::getMaxFragmentUniformVectors() const
{
const int maxPixelConstantVectors = (getMajorShaderModel() >= 3) ? MAX_PIXEL_CONSTANT_VECTORS_SM3 : MAX_PIXEL_CONSTANT_VECTORS_SM2;
return maxPixelConstantVectors - getReservedFragmentUniformVectors();
}
unsigned int Renderer9::getMaxVaryingVectors() const
{
return (getMajorShaderModel() >= 3) ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
}
bool Renderer9::getNonPower2TextureSupport() const
{
return mSupportsNonPower2Textures;
}
bool Renderer9::getOcclusionQuerySupport() const
{
return mOcclusionQuerySupport;
}
bool Renderer9::getInstancingSupport() const
{
return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
}
bool Renderer9::getShareHandleSupport() const
{
// PIX doesn't seem to support using share handles, so disable them.
return (mD3d9Ex != NULL) && !gl::perfActive();
}
bool Renderer9::getDerivativeInstructionSupport() const
{
return (mDeviceCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) != 0;
}
bool Renderer9::getPostSubBufferSupport() const
{
return true;
}
int Renderer9::getMajorShaderModel() const
{
return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
}
float Renderer9::getMaxPointSize() const
{
// Point size clamped at 1.0f for SM2
return getMajorShaderModel() == 3 ? mDeviceCaps.MaxPointSize : 1.0f;
}
int Renderer9::getMaxViewportDimension() const
{
int maxTextureDimension = std::min(std::min(getMaxTextureWidth(), getMaxTextureHeight()),
(int)gl::IMPLEMENTATION_MAX_TEXTURE_SIZE);
return maxTextureDimension;
}
int Renderer9::getMaxTextureWidth() const
{
return (int)mDeviceCaps.MaxTextureWidth;
}
int Renderer9::getMaxTextureHeight() const
{
return (int)mDeviceCaps.MaxTextureHeight;
}
bool Renderer9::get32BitIndexSupport() const
{
return mDeviceCaps.MaxVertexIndex >= (1 << 16);
}
DWORD Renderer9::getCapsDeclTypes() const
{
return mDeviceCaps.DeclTypes;
}
int Renderer9::getMinSwapInterval() const
{
return mMinSwapInterval;
}
int Renderer9::getMaxSwapInterval() const
{
return mMaxSwapInterval;
}
int Renderer9::getMaxSupportedSamples() const
{
return mMaxSupportedSamples;
}
int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
{
if (requested == 0)
{
return requested;
}
std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
if (itr == mMultiSampleSupport.end())
{
if (format == D3DFMT_UNKNOWN)
return 0;
return -1;
}
for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
{
if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
{
return i;
}
}
return -1;
}
unsigned int Renderer9::getMaxRenderTargets() const
{
// we do not support MRT in d3d9
return 1;
}
D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
{
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH24_STENCIL8_OES:
return D3DFMT_INTZ;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return D3DFMT_DXT1;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
return D3DFMT_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return D3DFMT_DXT5;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
return D3DFMT_A32B32G32R32F;
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
return D3DFMT_A16B16G16R16F;
case GL_LUMINANCE8_EXT:
if (getLuminanceTextureSupport())
{
return D3DFMT_L8;
}
break;
case GL_LUMINANCE8_ALPHA8_EXT:
if (getLuminanceAlphaTextureSupport())
{
return D3DFMT_A8L8;
}
break;
case GL_RGB8_OES:
case GL_RGB565:
return D3DFMT_X8R8G8B8;
}
return D3DFMT_A8R8G8B8;
}
bool Renderer9::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
{
bool result = false;
if (source && dest)
{
TextureStorage9_2D *source9 = TextureStorage9_2D::makeTextureStorage9_2D(source->getStorageInstance());
TextureStorage9_2D *dest9 = TextureStorage9_2D::makeTextureStorage9_2D(dest->getStorageInstance());
int levels = source9->levelCount();
for (int i = 0; i < levels; ++i)
{
IDirect3DSurface9 *srcSurf = source9->getSurfaceLevel(i, false);
IDirect3DSurface9 *dstSurf = dest9->getSurfaceLevel(i, false);
result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
if (srcSurf) srcSurf->Release();
if (dstSurf) dstSurf->Release();
if (!result)
return false;
}
}
return result;
}
bool Renderer9::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
{
bool result = false;
if (source && dest)
{
TextureStorage9_Cube *source9 = TextureStorage9_Cube::makeTextureStorage9_Cube(source->getStorageInstance());
TextureStorage9_Cube *dest9 = TextureStorage9_Cube::makeTextureStorage9_Cube(dest->getStorageInstance());
int levels = source9->levelCount();
for (int f = 0; f < 6; f++)
{
for (int i = 0; i < levels; i++)
{
IDirect3DSurface9 *srcSurf = source9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
IDirect3DSurface9 *dstSurf = dest9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
if (srcSurf) srcSurf->Release();
if (dstSurf) dstSurf->Release();
if (!result)
return false;
}
}
}
return result;
}
D3DPOOL Renderer9::getBufferPool(DWORD usage) const
{
if (mD3d9Ex != NULL)
{
return D3DPOOL_DEFAULT;
}
else
{
if (!(usage & D3DUSAGE_DYNAMIC))
{
return D3DPOOL_MANAGED;
}
}
return D3DPOOL_DEFAULT;
}
bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
{
RECT rect;
rect.left = sourceRect.x;
rect.top = sourceRect.y;
rect.right = sourceRect.x + sourceRect.width;
rect.bottom = sourceRect.y + sourceRect.height;
return mBlit->copy(framebuffer, rect, destFormat, xoffset, yoffset, storage, level);
}
bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
{
RECT rect;
rect.left = sourceRect.x;
rect.top = sourceRect.y;
rect.right = sourceRect.x + sourceRect.width;
rect.bottom = sourceRect.y + sourceRect.height;
return mBlit->copy(framebuffer, rect, destFormat, xoffset, yoffset, storage, target, level);
}
bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, const gl::Rectangle &readRect, gl::Framebuffer *drawFramebuffer, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil)
{
endScene();
if (blitRenderTarget)
{
gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer(0);
gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer(0);
RenderTarget9 *readRenderTarget = NULL;
RenderTarget9 *drawRenderTarget = NULL;
IDirect3DSurface9* readSurface = NULL;
IDirect3DSurface9* drawSurface = NULL;
if (readBuffer)
{
readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
}
if (drawBuffer)
{
drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
}
if (readRenderTarget)
{
readSurface = readRenderTarget->getSurface();
}
if (drawRenderTarget)
{
drawSurface = drawRenderTarget->getSurface();
}
if (!readSurface || !drawSurface)
{
ERR("Failed to retrieve the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RECT srcRect;
srcRect.left = readRect.x;
srcRect.right = readRect.x + readRect.width;
srcRect.top = readRect.y;
srcRect.bottom = readRect.y + readRect.height;
RECT dstRect;
dstRect.left = drawRect.x;
dstRect.right = drawRect.x + drawRect.width;
dstRect.top = drawRect.y;
dstRect.bottom = drawRect.y + drawRect.height;
HRESULT result = mDevice->StretchRect(readSurface, &srcRect, drawSurface, &dstRect, D3DTEXF_NONE);
readSurface->Release();
drawSurface->Release();
if (FAILED(result))
{
ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
return false;
}
}
if (blitDepthStencil)
{
gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
RenderTarget9 *readDepthStencil = NULL;
RenderTarget9 *drawDepthStencil = NULL;
IDirect3DSurface9* readSurface = NULL;
IDirect3DSurface9* drawSurface = NULL;
if (readBuffer)
{
readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
}
if (drawBuffer)
{
drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
}
if (readDepthStencil)
{
readSurface = readDepthStencil->getSurface();
}
if (drawDepthStencil)
{
drawSurface = drawDepthStencil->getSurface();
}
if (!readSurface || !drawSurface)
{
ERR("Failed to retrieve the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
readSurface->Release();
drawSurface->Release();
if (FAILED(result))
{
ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
return false;
}
}
return true;
}
void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
{
RenderTarget9 *renderTarget = NULL;
IDirect3DSurface9 *surface = NULL;
gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer(0);
if (colorbuffer)
{
renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
}
if (renderTarget)
{
surface = renderTarget->getSurface();
}
if (!surface)
{
// context must be lost
return;
}
D3DSURFACE_DESC desc;
surface->GetDesc(&desc);
if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
{
UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
HRESULT result;
IDirect3DSurface9 *systemSurface = NULL;
bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
if (directToPixels)
{
// Use the pixels ptr as a shared handle to write directly into client's memory
result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
if (FAILED(result))
{
// Try again without the shared handle
directToPixels = false;
}
}
if (!directToPixels)
{
result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
surface->Release();
return gl::error(GL_OUT_OF_MEMORY);
}
}
result = mDevice->GetRenderTargetData(surface, systemSurface);
surface->Release();
surface = NULL;
if (FAILED(result))
{
systemSurface->Release();
// It turns out that D3D will sometimes produce more error
// codes than those documented.
if (d3d9::isDeviceLostError(result))
{
notifyDeviceLost();
return gl::error(GL_OUT_OF_MEMORY);
}
else
{
UNREACHABLE();
return;
}
}
if (directToPixels)
{
systemSurface->Release();
return;
}
RECT rect;
rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
D3DLOCKED_RECT lock;
result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
if (FAILED(result))
{
UNREACHABLE();
systemSurface->Release();
return; // No sensible error to generate
}
unsigned char *dest = (unsigned char*)pixels;
unsigned short *dest16 = (unsigned short*)pixels;
unsigned char *source;
int inputPitch;
if (packReverseRowOrder)
{
source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
inputPitch = -lock.Pitch;
}
else
{
source = (unsigned char*)lock.pBits;
inputPitch = lock.Pitch;
}
unsigned int fastPixelSize = 0;
if (desc.Format == D3DFMT_A8R8G8B8 &&
format == GL_BGRA_EXT &&
type == GL_UNSIGNED_BYTE)
{
fastPixelSize = 4;
}
else if ((desc.Format == D3DFMT_A4R4G4B4 &&
format == GL_BGRA_EXT &&
type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
(desc.Format == D3DFMT_A1R5G5B5 &&
format == GL_BGRA_EXT &&
type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
{
fastPixelSize = 2;
}
else if (desc.Format == D3DFMT_A16B16G16R16F &&
format == GL_RGBA &&
type == GL_HALF_FLOAT_OES)
{
fastPixelSize = 8;
}
else if (desc.Format == D3DFMT_A32B32G32R32F &&
format == GL_RGBA &&
type == GL_FLOAT)
{
fastPixelSize = 16;
}
for (int j = 0; j < rect.bottom - rect.top; j++)
{
if (fastPixelSize != 0)
{
// Fast path for formats which require no translation:
// D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
// D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
// D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
// D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
// D3DFMT_A32B32G32R32F to RGBA/FLOAT
//
// Note that buffers with no alpha go through the slow path below.
memcpy(dest + j * outputPitch,
source + j * inputPitch,
(rect.right - rect.left) * fastPixelSize);
continue;
}
else if (desc.Format == D3DFMT_A8R8G8B8 &&
format == GL_RGBA &&
type == GL_UNSIGNED_BYTE)
{
// Fast path for swapping red with blue
for (int i = 0; i < rect.right - rect.left; i++)
{
unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
*(unsigned int*)(dest + 4 * i + j * outputPitch) =
(argb & 0xFF00FF00) | // Keep alpha and green
(argb & 0x00FF0000) >> 16 | // Move red to blue
(argb & 0x000000FF) << 16; // Move blue to red
}
continue;
}
for (int i = 0; i < rect.right - rect.left; i++)
{
float r;
float g;
float b;
float a;
switch (desc.Format)
{
case D3DFMT_R5G6B5:
{
unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
a = 1.0f;
b = (rgb & 0x001F) * (1.0f / 0x001F);
g = (rgb & 0x07E0) * (1.0f / 0x07E0);
r = (rgb & 0xF800) * (1.0f / 0xF800);
}
break;
case D3DFMT_A1R5G5B5:
{
unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
a = (argb & 0x8000) ? 1.0f : 0.0f;
b = (argb & 0x001F) * (1.0f / 0x001F);
g = (argb & 0x03E0) * (1.0f / 0x03E0);
r = (argb & 0x7C00) * (1.0f / 0x7C00);
}
break;
case D3DFMT_A8R8G8B8:
{
unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
}
break;
case D3DFMT_X8R8G8B8:
{
unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
a = 1.0f;
b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
}
break;
case D3DFMT_A2R10G10B10:
{
unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
}
break;
case D3DFMT_A32B32G32R32F:
{
// float formats in D3D are stored rgba, rather than the other way round
r = *((float*)(source + 16 * i + j * inputPitch) + 0);
g = *((float*)(source + 16 * i + j * inputPitch) + 1);
b = *((float*)(source + 16 * i + j * inputPitch) + 2);
a = *((float*)(source + 16 * i + j * inputPitch) + 3);
}
break;
case D3DFMT_A16B16G16R16F:
{
// float formats in D3D are stored rgba, rather than the other way round
r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
}
break;
default:
UNIMPLEMENTED(); // FIXME
UNREACHABLE();
return;
}
switch (format)
{
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
break;
default: UNREACHABLE();
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
break;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
dest16[i + j * outputPitch / sizeof(unsigned short)] =
((unsigned short)(15 * a + 0.5f) << 12)|
((unsigned short)(15 * r + 0.5f) << 8) |
((unsigned short)(15 * g + 0.5f) << 4) |
((unsigned short)(15 * b + 0.5f) << 0);
break;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
dest16[i + j * outputPitch / sizeof(unsigned short)] =
((unsigned short)( a + 0.5f) << 15) |
((unsigned short)(31 * r + 0.5f) << 10) |
((unsigned short)(31 * g + 0.5f) << 5) |
((unsigned short)(31 * b + 0.5f) << 0);
break;
default: UNREACHABLE();
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_SHORT_5_6_5:
dest16[i + j * outputPitch / sizeof(unsigned short)] =
((unsigned short)(31 * b + 0.5f) << 0) |
((unsigned short)(63 * g + 0.5f) << 5) |
((unsigned short)(31 * r + 0.5f) << 11);
break;
case GL_UNSIGNED_BYTE:
dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
break;
default: UNREACHABLE();
}
break;
default: UNREACHABLE();
}
}
}
systemSurface->UnlockRect();
systemSurface->Release();
}
RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
{
SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
IDirect3DSurface9 *surface = NULL;
if (depth)
{
surface = swapChain9->getDepthStencil();
}
else
{
surface = swapChain9->getRenderTarget();
}
RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
return renderTarget;
}
RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
{
RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
return renderTarget;
}
ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, rx::ShaderType type)
{
ShaderExecutable9 *executable = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
{
IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
if (vshader)
{
executable = new ShaderExecutable9(function, length, vshader);
}
}
break;
case rx::SHADER_PIXEL:
{
IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
if (pshader)
{
executable = new ShaderExecutable9(function, length, pshader);
}
}
break;
default:
UNREACHABLE();
break;
}
return executable;
}
ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type)
{
const char *profile = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
break;
case rx::SHADER_PIXEL:
profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
break;
default:
UNREACHABLE();
return NULL;
}
ID3DBlob *binary = (ID3DBlob*)compileToBinary(infoLog, shaderHLSL, profile, ANGLE_COMPILE_OPTIMIZATION_LEVEL, true);
if (!binary)
return NULL;
ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type);
binary->Release();
return executable;
}
bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
{
return mBlit->boxFilter(source, dest);
}
D3DPOOL Renderer9::getTexturePool(DWORD usage) const
{
if (mD3d9Ex != NULL)
{
return D3DPOOL_DEFAULT;
}
else
{
if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
{
return D3DPOOL_MANAGED;
}
}
return D3DPOOL_DEFAULT;
}
bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
{
if (source && dest)
{
HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
if (fromManaged)
{
D3DSURFACE_DESC desc;
source->GetDesc(&desc);
IDirect3DSurface9 *surf = 0;
result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
if (SUCCEEDED(result))
{
Image9::copyLockableSurfaces(surf, source);
result = mDevice->UpdateSurface(surf, NULL, dest, NULL);
surf->Release();
}
}
else
{
endScene();
result = mDevice->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
}
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return false;
}
}
return true;
}
Image *Renderer9::createImage()
{
return new Image9();
}
void Renderer9::generateMipmap(Image *dest, Image *src)
{
Image9 *src9 = Image9::makeImage9(src);
Image9 *dst9 = Image9::makeImage9(dest);
Image9::generateMipmap(dst9, src9);
}
TextureStorage *Renderer9::createTextureStorage2D(SwapChain *swapChain)
{
SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
return new TextureStorage9_2D(this, swapChain9);
}
TextureStorage *Renderer9::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
{
return new TextureStorage9_2D(this, levels, internalformat, usage, forceRenderable, width, height);
}
TextureStorage *Renderer9::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
{
return new TextureStorage9_Cube(this, levels, internalformat, usage, forceRenderable, size);
}
bool Renderer9::getLUID(LUID *adapterLuid) const
{
adapterLuid->HighPart = 0;
adapterLuid->LowPart = 0;
if (mD3d9Ex)
{
mD3d9Ex->GetAdapterLUID(mAdapter, adapterLuid);
return true;
}
return false;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Renderer9.cpp | C++ | bsd | 110,789 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage11.cpp Defines the BufferStorage11 class.
#include "libGLESv2/renderer/BufferStorage11.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/Renderer11.h"
namespace rx
{
BufferStorage11::BufferStorage11(Renderer11 *renderer)
{
mRenderer = renderer;
mStagingBuffer = NULL;
mStagingBufferSize = 0;
mBuffer = NULL;
mBufferSize = 0;
mSize = 0;
mResolvedData = NULL;
mResolvedDataSize = 0;
mResolvedDataValid = false;
mReadUsageCount = 0;
mWriteUsageCount = 0;
}
BufferStorage11::~BufferStorage11()
{
if (mStagingBuffer)
{
mStagingBuffer->Release();
mStagingBuffer = NULL;
}
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
}
if (mResolvedData)
{
free(mResolvedData);
mResolvedData = NULL;
}
}
BufferStorage11 *BufferStorage11::makeBufferStorage11(BufferStorage *bufferStorage)
{
ASSERT(HAS_DYNAMIC_TYPE(BufferStorage11*, bufferStorage));
return static_cast<BufferStorage11*>(bufferStorage);
}
void *BufferStorage11::getData()
{
if (!mResolvedDataValid)
{
ID3D11Device *device = mRenderer->getDevice();
ID3D11DeviceContext *context = mRenderer->getDeviceContext();
HRESULT result;
if (!mStagingBuffer || mStagingBufferSize < mBufferSize)
{
if (mStagingBuffer)
{
mStagingBuffer->Release();
mStagingBuffer = NULL;
mStagingBufferSize = 0;
}
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = mSize;
bufferDesc.Usage = D3D11_USAGE_STAGING;
bufferDesc.BindFlags = 0;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
result = device->CreateBuffer(&bufferDesc, NULL, &mStagingBuffer);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY, (void*)NULL);
}
mStagingBufferSize = bufferDesc.ByteWidth;
}
if (!mResolvedData || mResolvedDataSize < mBufferSize)
{
free(mResolvedData);
mResolvedData = malloc(mSize);
mResolvedDataSize = mSize;
}
D3D11_BOX srcBox;
srcBox.left = 0;
srcBox.right = mSize;
srcBox.top = 0;
srcBox.bottom = 1;
srcBox.front = 0;
srcBox.back = 1;
context->CopySubresourceRegion(mStagingBuffer, 0, 0, 0, 0, mBuffer, 0, &srcBox);
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = context->Map(mStagingBuffer, 0, D3D11_MAP_READ, 0, &mappedResource);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY, (void*)NULL);
}
memcpy(mResolvedData, mappedResource.pData, mSize);
context->Unmap(mStagingBuffer, 0);
mResolvedDataValid = true;
}
mReadUsageCount = 0;
return mResolvedData;
}
void BufferStorage11::setData(const void* data, unsigned int size, unsigned int offset)
{
ID3D11Device *device = mRenderer->getDevice();
ID3D11DeviceContext *context = mRenderer->getDeviceContext();
HRESULT result;
unsigned int requiredBufferSize = size + offset;
unsigned int requiredStagingSize = size;
bool directInitialization = offset == 0 && (!mBuffer || mBufferSize < size + offset);
if (!directInitialization)
{
if (!mStagingBuffer || mStagingBufferSize < requiredStagingSize)
{
if (mStagingBuffer)
{
mStagingBuffer->Release();
mStagingBuffer = NULL;
mStagingBufferSize = 0;
}
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = size;
bufferDesc.Usage = D3D11_USAGE_STAGING;
bufferDesc.BindFlags = 0;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA initialData;
initialData.pSysMem = data;
initialData.SysMemPitch = size;
initialData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&bufferDesc, &initialData, &mStagingBuffer);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY);
}
mStagingBufferSize = size;
}
else
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = context->Map(mStagingBuffer, 0, D3D11_MAP_WRITE, 0, &mappedResource);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY);
}
memcpy(mappedResource.pData, data, size);
context->Unmap(mStagingBuffer, 0);
}
}
if (!mBuffer || mBufferSize < size + offset)
{
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = requiredBufferSize;
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_INDEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
if (directInitialization)
{
// Since the data will fill the entire buffer (being larger than the initial size and having
// no offset), the buffer can be initialized with the data so no staging buffer is required
// No longer need the old buffer
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
mBufferSize = 0;
}
D3D11_SUBRESOURCE_DATA initialData;
initialData.pSysMem = data;
initialData.SysMemPitch = size;
initialData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&bufferDesc, &initialData, &mBuffer);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
else if (mBuffer && offset > 0)
{
// If offset is greater than zero and the buffer is non-null, need to preserve the data from
// the old buffer up to offset
ID3D11Buffer *newBuffer = NULL;
result = device->CreateBuffer(&bufferDesc, NULL, &newBuffer);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY);
}
D3D11_BOX srcBox;
srcBox.left = 0;
srcBox.right = std::min(offset, mBufferSize);
srcBox.top = 0;
srcBox.bottom = 1;
srcBox.front = 0;
srcBox.back = 1;
context->CopySubresourceRegion(newBuffer, 0, 0, 0, 0, mBuffer, 0, &srcBox);
mBuffer->Release();
mBuffer = newBuffer;
}
else
{
// Simple case, nothing needs to be copied from the old buffer to the new one, just create
// a new buffer
// No longer need the old buffer
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
mBufferSize = 0;
}
// Create a new buffer for data storage
result = device->CreateBuffer(&bufferDesc, NULL, &mBuffer);
if (FAILED(result))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
updateSerial();
mBufferSize = bufferDesc.ByteWidth;
}
if (!directInitialization)
{
ASSERT(mStagingBuffer && mStagingBufferSize >= requiredStagingSize);
// Data is already put into the staging buffer, copy it over to the data buffer
D3D11_BOX srcBox;
srcBox.left = 0;
srcBox.right = size;
srcBox.top = 0;
srcBox.bottom = 1;
srcBox.front = 0;
srcBox.back = 1;
context->CopySubresourceRegion(mBuffer, 0, offset, 0, 0, mStagingBuffer, 0, &srcBox);
}
mSize = std::max(mSize, offset + size);
mWriteUsageCount = 0;
mResolvedDataValid = false;
}
void BufferStorage11::clear()
{
mResolvedDataValid = false;
mSize = 0;
}
unsigned int BufferStorage11::getSize() const
{
return mSize;
}
bool BufferStorage11::supportsDirectBinding() const
{
return true;
}
void BufferStorage11::markBufferUsage()
{
mReadUsageCount++;
mWriteUsageCount++;
static const unsigned int usageLimit = 5;
if (mReadUsageCount > usageLimit && mResolvedData)
{
free(mResolvedData);
mResolvedData = NULL;
mResolvedDataSize = 0;
mResolvedDataValid = false;
}
if (mReadUsageCount > usageLimit && mWriteUsageCount > usageLimit && mStagingBuffer)
{
mStagingBuffer->Release();
mStagingBuffer = NULL;
mStagingBufferSize = 0;
}
}
ID3D11Buffer *BufferStorage11::getBuffer() const
{
return mBuffer;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage11.cpp | C++ | bsd | 9,344 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage9.h Defines the BufferStorage9 class.
#ifndef LIBGLESV2_RENDERER_BUFFERSTORAGE9_H_
#define LIBGLESV2_RENDERER_BUFFERSTORAGE9_H_
#include "libGLESv2/renderer/BufferStorage.h"
namespace rx
{
class BufferStorage9 : public BufferStorage
{
public:
BufferStorage9();
virtual ~BufferStorage9();
static BufferStorage9 *makeBufferStorage9(BufferStorage *bufferStorage);
virtual void *getData();
virtual void setData(const void* data, unsigned int size, unsigned int offset);
virtual void clear();
virtual unsigned int getSize() const;
virtual bool supportsDirectBinding() const;
private:
DISALLOW_COPY_AND_ASSIGN(BufferStorage9);
void *mMemory;
unsigned int mAllocatedSize;
unsigned int mSize;
};
}
#endif // LIBGLESV2_RENDERER_BUFFERSTORAGE9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage9.h | C++ | bsd | 997 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer9.cpp: Defines the D3D9 VertexBuffer implementation.
#include "libGLESv2/renderer/VertexBuffer9.h"
#include "libGLESv2/renderer/vertexconversion.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/Buffer.h"
namespace rx
{
bool VertexBuffer9::mTranslationsInitialized = false;
VertexBuffer9::FormatConverter VertexBuffer9::mFormatConverters[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
VertexBuffer9::VertexBuffer9(rx::Renderer9 *const renderer) : mRenderer(renderer)
{
mVertexBuffer = NULL;
mBufferSize = 0;
mDynamicUsage = false;
if (!mTranslationsInitialized)
{
initializeTranslations(renderer->getCapsDeclTypes());
mTranslationsInitialized = true;
}
}
VertexBuffer9::~VertexBuffer9()
{
if (mVertexBuffer)
{
mVertexBuffer->Release();
mVertexBuffer = NULL;
}
}
bool VertexBuffer9::initialize(unsigned int size, bool dynamicUsage)
{
if (mVertexBuffer)
{
mVertexBuffer->Release();
mVertexBuffer = NULL;
}
updateSerial();
if (size > 0)
{
DWORD flags = D3DUSAGE_WRITEONLY;
if (dynamicUsage)
{
flags |= D3DUSAGE_DYNAMIC;
}
HRESULT result = mRenderer->createVertexBuffer(size, flags, &mVertexBuffer);
if (FAILED(result))
{
ERR("Out of memory allocating a vertex buffer of size %lu.", size);
return false;
}
}
mBufferSize = size;
mDynamicUsage = dynamicUsage;
return true;
}
VertexBuffer9 *VertexBuffer9::makeVertexBuffer9(VertexBuffer *vertexBuffer)
{
ASSERT(HAS_DYNAMIC_TYPE(VertexBuffer9*, vertexBuffer));
return static_cast<VertexBuffer9*>(vertexBuffer);
}
bool VertexBuffer9::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count,
GLsizei instances, unsigned int offset)
{
if (mVertexBuffer)
{
gl::Buffer *buffer = attrib.mBoundBuffer.get();
int inputStride = attrib.stride();
int elementSize = attrib.typeSize();
const FormatConverter &converter = formatConverter(attrib);
DWORD lockFlags = mDynamicUsage ? D3DLOCK_NOOVERWRITE : 0;
void *mapPtr = NULL;
HRESULT result = mVertexBuffer->Lock(offset, spaceRequired(attrib, count, instances), &mapPtr, lockFlags);
if (FAILED(result))
{
ERR("Lock failed with error 0x%08x", result);
return false;
}
const char *input = NULL;
if (buffer)
{
BufferStorage *storage = buffer->getStorage();
input = static_cast<const char*>(storage->getData()) + static_cast<int>(attrib.mOffset);
}
else
{
input = static_cast<const char*>(attrib.mPointer);
}
if (instances == 0 || attrib.mDivisor == 0)
{
input += inputStride * start;
}
if (converter.identity && inputStride == elementSize)
{
memcpy(mapPtr, input, count * inputStride);
}
else
{
converter.convertArray(input, inputStride, count, mapPtr);
}
mVertexBuffer->Unlock();
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
bool VertexBuffer9::storeRawData(const void* data, unsigned int size, unsigned int offset)
{
if (mVertexBuffer)
{
DWORD lockFlags = mDynamicUsage ? D3DLOCK_NOOVERWRITE : 0;
void *mapPtr = NULL;
HRESULT result = mVertexBuffer->Lock(offset, size, &mapPtr, lockFlags);
if (FAILED(result))
{
ERR("Lock failed with error 0x%08x", result);
return false;
}
memcpy(mapPtr, data, size);
mVertexBuffer->Unlock();
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
unsigned int VertexBuffer9::getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count, GLsizei instances) const
{
return spaceRequired(attrib, count, instances);
}
bool VertexBuffer9::requiresConversion(const gl::VertexAttribute &attrib) const
{
return formatConverter(attrib).identity;
}
unsigned int VertexBuffer9::getVertexSize(const gl::VertexAttribute &attrib) const
{
return spaceRequired(attrib, 1, 0);
}
D3DDECLTYPE VertexBuffer9::getDeclType(const gl::VertexAttribute &attrib) const
{
return formatConverter(attrib).d3dDeclType;
}
unsigned int VertexBuffer9::getBufferSize() const
{
return mBufferSize;
}
bool VertexBuffer9::setBufferSize(unsigned int size)
{
if (size > mBufferSize)
{
return initialize(size, mDynamicUsage);
}
else
{
return true;
}
}
bool VertexBuffer9::discard()
{
if (mVertexBuffer)
{
void *dummy;
HRESULT result;
result = mVertexBuffer->Lock(0, 1, &dummy, D3DLOCK_DISCARD);
if (FAILED(result))
{
ERR("Discard lock failed with error 0x%08x", result);
return false;
}
result = mVertexBuffer->Unlock();
if (FAILED(result))
{
ERR("Discard unlock failed with error 0x%08x", result);
return false;
}
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
IDirect3DVertexBuffer9 * VertexBuffer9::getBuffer() const
{
return mVertexBuffer;
}
// Mapping from OpenGL-ES vertex attrib type to D3D decl type:
//
// BYTE SHORT (Cast)
// BYTE-norm FLOAT (Normalize) (can't be exactly represented as SHORT-norm)
// UNSIGNED_BYTE UBYTE4 (Identity) or SHORT (Cast)
// UNSIGNED_BYTE-norm UBYTE4N (Identity) or FLOAT (Normalize)
// SHORT SHORT (Identity)
// SHORT-norm SHORT-norm (Identity) or FLOAT (Normalize)
// UNSIGNED_SHORT FLOAT (Cast)
// UNSIGNED_SHORT-norm USHORT-norm (Identity) or FLOAT (Normalize)
// FIXED (not in WebGL) FLOAT (FixedToFloat)
// FLOAT FLOAT (Identity)
// GLToCType maps from GL type (as GLenum) to the C typedef.
template <GLenum GLType> struct GLToCType { };
template <> struct GLToCType<GL_BYTE> { typedef GLbyte type; };
template <> struct GLToCType<GL_UNSIGNED_BYTE> { typedef GLubyte type; };
template <> struct GLToCType<GL_SHORT> { typedef GLshort type; };
template <> struct GLToCType<GL_UNSIGNED_SHORT> { typedef GLushort type; };
template <> struct GLToCType<GL_FIXED> { typedef GLuint type; };
template <> struct GLToCType<GL_FLOAT> { typedef GLfloat type; };
// This differs from D3DDECLTYPE in that it is unsized. (Size expansion is applied last.)
enum D3DVertexType
{
D3DVT_FLOAT,
D3DVT_SHORT,
D3DVT_SHORT_NORM,
D3DVT_UBYTE,
D3DVT_UBYTE_NORM,
D3DVT_USHORT_NORM
};
// D3DToCType maps from D3D vertex type (as enum D3DVertexType) to the corresponding C type.
template <unsigned int D3DType> struct D3DToCType { };
template <> struct D3DToCType<D3DVT_FLOAT> { typedef float type; };
template <> struct D3DToCType<D3DVT_SHORT> { typedef short type; };
template <> struct D3DToCType<D3DVT_SHORT_NORM> { typedef short type; };
template <> struct D3DToCType<D3DVT_UBYTE> { typedef unsigned char type; };
template <> struct D3DToCType<D3DVT_UBYTE_NORM> { typedef unsigned char type; };
template <> struct D3DToCType<D3DVT_USHORT_NORM> { typedef unsigned short type; };
// Encode the type/size combinations that D3D permits. For each type/size it expands to a widener that will provide the appropriate final size.
template <unsigned int type, int size> struct WidenRule { };
template <int size> struct WidenRule<D3DVT_FLOAT, size> : NoWiden<size> { };
template <int size> struct WidenRule<D3DVT_SHORT, size> : WidenToEven<size> { };
template <int size> struct WidenRule<D3DVT_SHORT_NORM, size> : WidenToEven<size> { };
template <int size> struct WidenRule<D3DVT_UBYTE, size> : WidenToFour<size> { };
template <int size> struct WidenRule<D3DVT_UBYTE_NORM, size> : WidenToFour<size> { };
template <int size> struct WidenRule<D3DVT_USHORT_NORM, size> : WidenToEven<size> { };
// VertexTypeFlags encodes the D3DCAPS9::DeclType flag and vertex declaration flag for each D3D vertex type & size combination.
template <unsigned int d3dtype, int size> struct VertexTypeFlags { };
template <unsigned int _capflag, unsigned int _declflag>
struct VertexTypeFlagsHelper
{
enum { capflag = _capflag };
enum { declflag = _declflag };
};
template <> struct VertexTypeFlags<D3DVT_FLOAT, 1> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT1> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 2> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT2> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 3> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT3> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 4> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT4> { };
template <> struct VertexTypeFlags<D3DVT_SHORT, 2> : VertexTypeFlagsHelper<0, D3DDECLTYPE_SHORT2> { };
template <> struct VertexTypeFlags<D3DVT_SHORT, 4> : VertexTypeFlagsHelper<0, D3DDECLTYPE_SHORT4> { };
template <> struct VertexTypeFlags<D3DVT_SHORT_NORM, 2> : VertexTypeFlagsHelper<D3DDTCAPS_SHORT2N, D3DDECLTYPE_SHORT2N> { };
template <> struct VertexTypeFlags<D3DVT_SHORT_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_SHORT4N, D3DDECLTYPE_SHORT4N> { };
template <> struct VertexTypeFlags<D3DVT_UBYTE, 4> : VertexTypeFlagsHelper<D3DDTCAPS_UBYTE4, D3DDECLTYPE_UBYTE4> { };
template <> struct VertexTypeFlags<D3DVT_UBYTE_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_UBYTE4N, D3DDECLTYPE_UBYTE4N> { };
template <> struct VertexTypeFlags<D3DVT_USHORT_NORM, 2> : VertexTypeFlagsHelper<D3DDTCAPS_USHORT2N, D3DDECLTYPE_USHORT2N> { };
template <> struct VertexTypeFlags<D3DVT_USHORT_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_USHORT4N, D3DDECLTYPE_USHORT4N> { };
// VertexTypeMapping maps GL type & normalized flag to preferred and fallback D3D vertex types (as D3DVertexType enums).
template <GLenum GLtype, bool normalized> struct VertexTypeMapping { };
template <D3DVertexType Preferred, D3DVertexType Fallback = Preferred>
struct VertexTypeMappingBase
{
enum { preferred = Preferred };
enum { fallback = Fallback };
};
template <> struct VertexTypeMapping<GL_BYTE, false> : VertexTypeMappingBase<D3DVT_SHORT> { }; // Cast
template <> struct VertexTypeMapping<GL_BYTE, true> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Normalize
template <> struct VertexTypeMapping<GL_UNSIGNED_BYTE, false> : VertexTypeMappingBase<D3DVT_UBYTE, D3DVT_FLOAT> { }; // Identity, Cast
template <> struct VertexTypeMapping<GL_UNSIGNED_BYTE, true> : VertexTypeMappingBase<D3DVT_UBYTE_NORM, D3DVT_FLOAT> { }; // Identity, Normalize
template <> struct VertexTypeMapping<GL_SHORT, false> : VertexTypeMappingBase<D3DVT_SHORT> { }; // Identity
template <> struct VertexTypeMapping<GL_SHORT, true> : VertexTypeMappingBase<D3DVT_SHORT_NORM, D3DVT_FLOAT> { }; // Cast, Normalize
template <> struct VertexTypeMapping<GL_UNSIGNED_SHORT, false> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Cast
template <> struct VertexTypeMapping<GL_UNSIGNED_SHORT, true> : VertexTypeMappingBase<D3DVT_USHORT_NORM, D3DVT_FLOAT> { }; // Cast, Normalize
template <bool normalized> struct VertexTypeMapping<GL_FIXED, normalized> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // FixedToFloat
template <bool normalized> struct VertexTypeMapping<GL_FLOAT, normalized> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Identity
// Given a GL type & norm flag and a D3D type, ConversionRule provides the type conversion rule (Cast, Normalize, Identity, FixedToFloat).
// The conversion rules themselves are defined in vertexconversion.h.
// Almost all cases are covered by Cast (including those that are actually Identity since Cast<T,T> knows it's an identity mapping).
template <GLenum fromType, bool normalized, unsigned int toType>
struct ConversionRule : Cast<typename GLToCType<fromType>::type, typename D3DToCType<toType>::type> { };
// All conversions from normalized types to float use the Normalize operator.
template <GLenum fromType> struct ConversionRule<fromType, true, D3DVT_FLOAT> : Normalize<typename GLToCType<fromType>::type> { };
// Use a full specialization for this so that it preferentially matches ahead of the generic normalize-to-float rules.
template <> struct ConversionRule<GL_FIXED, true, D3DVT_FLOAT> : FixedToFloat<GLint, 16> { };
template <> struct ConversionRule<GL_FIXED, false, D3DVT_FLOAT> : FixedToFloat<GLint, 16> { };
// A 2-stage construction is used for DefaultVertexValues because float must use SimpleDefaultValues (i.e. 0/1)
// whether it is normalized or not.
template <class T, bool normalized> struct DefaultVertexValuesStage2 { };
template <class T> struct DefaultVertexValuesStage2<T, true> : NormalizedDefaultValues<T> { };
template <class T> struct DefaultVertexValuesStage2<T, false> : SimpleDefaultValues<T> { };
// Work out the default value rule for a D3D type (expressed as the C type) and
template <class T, bool normalized> struct DefaultVertexValues : DefaultVertexValuesStage2<T, normalized> { };
template <bool normalized> struct DefaultVertexValues<float, normalized> : SimpleDefaultValues<float> { };
// Policy rules for use with Converter, to choose whether to use the preferred or fallback conversion.
// The fallback conversion produces an output that all D3D9 devices must support.
template <class T> struct UsePreferred { enum { type = T::preferred }; };
template <class T> struct UseFallback { enum { type = T::fallback }; };
// Converter ties it all together. Given an OpenGL type/norm/size and choice of preferred/fallback conversion,
// it provides all the members of the appropriate VertexDataConverter, the D3DCAPS9::DeclTypes flag in cap flag
// and the D3DDECLTYPE member needed for the vertex declaration in declflag.
template <GLenum fromType, bool normalized, int size, template <class T> class PreferenceRule>
struct Converter
: VertexDataConverter<typename GLToCType<fromType>::type,
WidenRule<PreferenceRule< VertexTypeMapping<fromType, normalized> >::type, size>,
ConversionRule<fromType,
normalized,
PreferenceRule< VertexTypeMapping<fromType, normalized> >::type>,
DefaultVertexValues<typename D3DToCType<PreferenceRule< VertexTypeMapping<fromType, normalized> >::type>::type, normalized > >
{
private:
enum { d3dtype = PreferenceRule< VertexTypeMapping<fromType, normalized> >::type };
enum { d3dsize = WidenRule<d3dtype, size>::finalWidth };
public:
enum { capflag = VertexTypeFlags<d3dtype, d3dsize>::capflag };
enum { declflag = VertexTypeFlags<d3dtype, d3dsize>::declflag };
};
// Initialize a TranslationInfo
#define TRANSLATION(type, norm, size, preferred) \
{ \
Converter<type, norm, size, preferred>::identity, \
Converter<type, norm, size, preferred>::finalSize, \
Converter<type, norm, size, preferred>::convertArray, \
static_cast<D3DDECLTYPE>(Converter<type, norm, size, preferred>::declflag) \
}
#define TRANSLATION_FOR_TYPE_NORM_SIZE(type, norm, size) \
{ \
Converter<type, norm, size, UsePreferred>::capflag, \
TRANSLATION(type, norm, size, UsePreferred), \
TRANSLATION(type, norm, size, UseFallback) \
}
#define TRANSLATIONS_FOR_TYPE(type) \
{ \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 4) }, \
}
#define TRANSLATIONS_FOR_TYPE_NO_NORM(type) \
{ \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
}
const VertexBuffer9::TranslationDescription VertexBuffer9::mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4] = // [GL types as enumerated by typeIndex()][normalized][size-1]
{
TRANSLATIONS_FOR_TYPE(GL_BYTE),
TRANSLATIONS_FOR_TYPE(GL_UNSIGNED_BYTE),
TRANSLATIONS_FOR_TYPE(GL_SHORT),
TRANSLATIONS_FOR_TYPE(GL_UNSIGNED_SHORT),
TRANSLATIONS_FOR_TYPE_NO_NORM(GL_FIXED),
TRANSLATIONS_FOR_TYPE_NO_NORM(GL_FLOAT)
};
void VertexBuffer9::initializeTranslations(DWORD declTypes)
{
for (unsigned int i = 0; i < NUM_GL_VERTEX_ATTRIB_TYPES; i++)
{
for (unsigned int j = 0; j < 2; j++)
{
for (unsigned int k = 0; k < 4; k++)
{
if (mPossibleTranslations[i][j][k].capsFlag == 0 || (declTypes & mPossibleTranslations[i][j][k].capsFlag) != 0)
{
mFormatConverters[i][j][k] = mPossibleTranslations[i][j][k].preferredConversion;
}
else
{
mFormatConverters[i][j][k] = mPossibleTranslations[i][j][k].fallbackConversion;
}
}
}
}
}
unsigned int VertexBuffer9::typeIndex(GLenum type)
{
switch (type)
{
case GL_BYTE: return 0;
case GL_UNSIGNED_BYTE: return 1;
case GL_SHORT: return 2;
case GL_UNSIGNED_SHORT: return 3;
case GL_FIXED: return 4;
case GL_FLOAT: return 5;
default: UNREACHABLE(); return 5;
}
}
const VertexBuffer9::FormatConverter &VertexBuffer9::formatConverter(const gl::VertexAttribute &attribute)
{
return mFormatConverters[typeIndex(attribute.mType)][attribute.mNormalized][attribute.mSize - 1];
}
unsigned int VertexBuffer9::spaceRequired(const gl::VertexAttribute &attrib, std::size_t count, GLsizei instances)
{
unsigned int elementSize = formatConverter(attrib).outputElementSize;
if (instances == 0 || attrib.mDivisor == 0)
{
return elementSize * count;
}
else
{
return elementSize * ((instances + attrib.mDivisor - 1) / attrib.mDivisor);
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer9.cpp | C++ | bsd | 20,173 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain11.h: Defines a back-end specific class for the D3D11 swap chain.
#ifndef LIBGLESV2_RENDERER_SWAPCHAIN11_H_
#define LIBGLESV2_RENDERER_SWAPCHAIN11_H_
#include "common/angleutils.h"
#include "libGLESv2/renderer/SwapChain.h"
namespace rx
{
class Renderer11;
class SwapChain11 : public SwapChain
{
public:
SwapChain11(Renderer11 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat);
virtual ~SwapChain11();
EGLint resize(EGLint backbufferWidth, EGLint backbufferHeight);
virtual EGLint reset(EGLint backbufferWidth, EGLint backbufferHeight, EGLint swapInterval);
virtual EGLint swapRect(EGLint x, EGLint y, EGLint width, EGLint height);
virtual void recreate();
virtual ID3D11Texture2D *getOffscreenTexture();
virtual ID3D11RenderTargetView *getRenderTarget();
virtual ID3D11ShaderResourceView *getRenderTargetShaderResource();
virtual ID3D11Texture2D *getDepthStencilTexture();
virtual ID3D11DepthStencilView *getDepthStencil();
EGLint getWidth() const { return mWidth; }
EGLint getHeight() const { return mHeight; }
static SwapChain11 *makeSwapChain11(SwapChain *swapChain);
private:
DISALLOW_COPY_AND_ASSIGN(SwapChain11);
void release();
void initPassThroughResources();
void releaseOffscreenTexture();
EGLint resetOffscreenTexture(int backbufferWidth, int backbufferHeight);
Renderer11 *mRenderer;
EGLint mHeight;
EGLint mWidth;
bool mAppCreatedShareHandle;
unsigned int mSwapInterval;
bool mPassThroughResourcesInit;
IDXGISwapChain *mSwapChain;
ID3D11Texture2D *mBackBufferTexture;
ID3D11RenderTargetView *mBackBufferRTView;
ID3D11Texture2D *mOffscreenTexture;
ID3D11RenderTargetView *mOffscreenRTView;
ID3D11ShaderResourceView *mOffscreenSRView;
ID3D11Texture2D *mDepthStencilTexture;
ID3D11DepthStencilView *mDepthStencilDSView;
ID3D11Buffer *mQuadVB;
ID3D11SamplerState *mPassThroughSampler;
ID3D11InputLayout *mPassThroughIL;
ID3D11VertexShader *mPassThroughVS;
ID3D11PixelShader *mPassThroughPS;
};
}
#endif // LIBGLESV2_RENDERER_SWAPCHAIN11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/SwapChain11.h | C++ | bsd | 2,377 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderExecutable.h: Defines a renderer-agnostic class to contain shader
// executable implementation details.
#ifndef LIBGLESV2_RENDERER_SHADEREXECUTABLE_H_
#define LIBGLESV2_RENDERER_SHADEREXECUTABLE_H_
#include "common/angleutils.h"
namespace rx
{
class ShaderExecutable
{
public:
ShaderExecutable(const void *function, size_t length) : mLength(length)
{
mFunction = new char[length];
memcpy(mFunction, function, length);
}
virtual ~ShaderExecutable()
{
delete mFunction;
}
void *getFunction() const
{
return mFunction;
}
size_t getLength() const
{
return mLength;
}
private:
DISALLOW_COPY_AND_ASSIGN(ShaderExecutable);
void *mFunction;
const size_t mLength;
};
}
#endif // LIBGLESV2_RENDERER_SHADEREXECUTABLE9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/ShaderExecutable.h | C++ | bsd | 1,019 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence.h: Defines the gl::Fence class, which supports the GL_NV_fence extension.
#ifndef LIBGLESV2_FENCE_H_
#define LIBGLESV2_FENCE_H_
#include "common/angleutils.h"
namespace rx
{
class Renderer;
class FenceImpl;
}
namespace gl
{
class Fence
{
public:
explicit Fence(rx::Renderer *renderer);
virtual ~Fence();
GLboolean isFence();
void setFence(GLenum condition);
GLboolean testFence();
void finishFence();
void getFenceiv(GLenum pname, GLint *params);
private:
DISALLOW_COPY_AND_ASSIGN(Fence);
rx::FenceImpl *mFence;
};
}
#endif // LIBGLESV2_FENCE_H_
| 010smithzhang-ddd | src/libGLESv2/Fence.h | C++ | bsd | 793 |
//
// Copyright (c) 2010-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef LIBGLESV2_UNIFORM_H_
#define LIBGLESV2_UNIFORM_H_
#include <string>
#include <vector>
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/debug.h"
namespace gl
{
// Helper struct representing a single shader uniform
struct Uniform
{
Uniform(GLenum type, GLenum precision, const std::string &name, unsigned int arraySize);
~Uniform();
bool isArray() const;
unsigned int elementCount() const;
const GLenum type;
const GLenum precision;
const std::string name;
const unsigned int arraySize;
unsigned char *data;
bool dirty;
int psRegisterIndex;
int vsRegisterIndex;
unsigned int registerCount;
};
typedef std::vector<Uniform*> UniformArray;
}
#endif // LIBGLESV2_UNIFORM_H_
| 010smithzhang-ddd | src/libGLESv2/Uniform.h | C++ | bsd | 987 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence.cpp: Implements the gl::Fence class, which supports the GL_NV_fence extension.
#include "libGLESv2/Fence.h"
#include "libGLESv2/renderer/FenceImpl.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Fence::Fence(rx::Renderer *renderer)
{
mFence = renderer->createFence();
}
Fence::~Fence()
{
delete mFence;
}
GLboolean Fence::isFence()
{
return mFence->isFence();
}
void Fence::setFence(GLenum condition)
{
mFence->setFence(condition);
}
GLboolean Fence::testFence()
{
return mFence->testFence();
}
void Fence::finishFence()
{
mFence->finishFence();
}
void Fence::getFenceiv(GLenum pname, GLint *params)
{
mFence->getFenceiv(pname, params);
}
}
| 010smithzhang-ddd | src/libGLESv2/Fence.cpp | C++ | bsd | 910 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderbuffer.h: Defines the wrapper class gl::Renderbuffer, as well as the
// class hierarchy used to store its contents: RenderbufferStorage, Colorbuffer,
// DepthStencilbuffer, Depthbuffer and Stencilbuffer. Implements GL renderbuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4.3 page 108.
#ifndef LIBGLESV2_RENDERBUFFER_H_
#define LIBGLESV2_RENDERBUFFER_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/angleutils.h"
#include "common/RefCountObject.h"
namespace rx
{
class Renderer;
class SwapChain;
class RenderTarget;
}
namespace gl
{
class Texture2D;
class TextureCubeMap;
class Renderbuffer;
class Colorbuffer;
class DepthStencilbuffer;
class RenderbufferInterface
{
public:
RenderbufferInterface();
virtual ~RenderbufferInterface() {};
virtual void addProxyRef(const Renderbuffer *proxy);
virtual void releaseProxy(const Renderbuffer *proxy);
virtual rx::RenderTarget *getRenderTarget() = 0;
virtual rx::RenderTarget *getDepthStencil() = 0;
virtual GLsizei getWidth() const = 0;
virtual GLsizei getHeight() const = 0;
virtual GLenum getInternalFormat() const = 0;
virtual GLenum getActualFormat() const = 0;
virtual GLsizei getSamples() const = 0;
GLuint getRedSize() const;
GLuint getGreenSize() const;
GLuint getBlueSize() const;
GLuint getAlphaSize() const;
GLuint getDepthSize() const;
GLuint getStencilSize() const;
virtual unsigned int getSerial() const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(RenderbufferInterface);
};
class RenderbufferTexture2D : public RenderbufferInterface
{
public:
RenderbufferTexture2D(Texture2D *texture, GLenum target);
virtual ~RenderbufferTexture2D();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
rx::RenderTarget *getRenderTarget();
rx::RenderTarget *getDepthStencil();
virtual GLsizei getWidth() const;
virtual GLsizei getHeight() const;
virtual GLenum getInternalFormat() const;
virtual GLenum getActualFormat() const;
virtual GLsizei getSamples() const;
virtual unsigned int getSerial() const;
private:
DISALLOW_COPY_AND_ASSIGN(RenderbufferTexture2D);
BindingPointer <Texture2D> mTexture2D;
GLenum mTarget;
};
class RenderbufferTextureCubeMap : public RenderbufferInterface
{
public:
RenderbufferTextureCubeMap(TextureCubeMap *texture, GLenum target);
virtual ~RenderbufferTextureCubeMap();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
rx::RenderTarget *getRenderTarget();
rx::RenderTarget *getDepthStencil();
virtual GLsizei getWidth() const;
virtual GLsizei getHeight() const;
virtual GLenum getInternalFormat() const;
virtual GLenum getActualFormat() const;
virtual GLsizei getSamples() const;
virtual unsigned int getSerial() const;
private:
DISALLOW_COPY_AND_ASSIGN(RenderbufferTextureCubeMap);
BindingPointer <TextureCubeMap> mTextureCubeMap;
GLenum mTarget;
};
// A class derived from RenderbufferStorage is created whenever glRenderbufferStorage
// is called. The specific concrete type depends on whether the internal format is
// colour depth, stencil or packed depth/stencil.
class RenderbufferStorage : public RenderbufferInterface
{
public:
RenderbufferStorage();
virtual ~RenderbufferStorage() = 0;
virtual rx::RenderTarget *getRenderTarget();
virtual rx::RenderTarget *getDepthStencil();
virtual GLsizei getWidth() const;
virtual GLsizei getHeight() const;
virtual GLenum getInternalFormat() const;
virtual GLenum getActualFormat() const;
virtual GLsizei getSamples() const;
virtual unsigned int getSerial() const;
static unsigned int issueSerial();
static unsigned int issueCubeSerials();
protected:
GLsizei mWidth;
GLsizei mHeight;
GLenum mInternalFormat;
GLenum mActualFormat;
GLsizei mSamples;
private:
DISALLOW_COPY_AND_ASSIGN(RenderbufferStorage);
const unsigned int mSerial;
static unsigned int mCurrentSerial;
};
// Renderbuffer implements the GL renderbuffer object.
// It's only a proxy for a RenderbufferInterface instance; the internal object
// can change whenever glRenderbufferStorage is called.
class Renderbuffer : public RefCountObject
{
public:
Renderbuffer(rx::Renderer *renderer, GLuint id, RenderbufferInterface *storage);
virtual ~Renderbuffer();
// These functions from RefCountObject are overloaded here because
// Textures need to maintain their own count of references to them via
// Renderbuffers/RenderbufferTextures. These functions invoke those
// reference counting functions on the RenderbufferInterface.
void addRef() const;
void release() const;
rx::RenderTarget *getRenderTarget();
rx::RenderTarget *getDepthStencil();
GLsizei getWidth() const;
GLsizei getHeight() const;
GLenum getInternalFormat() const;
GLenum getActualFormat() const;
GLuint getRedSize() const;
GLuint getGreenSize() const;
GLuint getBlueSize() const;
GLuint getAlphaSize() const;
GLuint getDepthSize() const;
GLuint getStencilSize() const;
GLsizei getSamples() const;
unsigned int getSerial() const;
void setStorage(RenderbufferStorage *newStorage);
private:
DISALLOW_COPY_AND_ASSIGN(Renderbuffer);
RenderbufferInterface *mInstance;
};
class Colorbuffer : public RenderbufferStorage
{
public:
Colorbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain);
Colorbuffer(rx::Renderer *renderer, GLsizei width, GLsizei height, GLenum format, GLsizei samples);
virtual ~Colorbuffer();
virtual rx::RenderTarget *getRenderTarget();
private:
DISALLOW_COPY_AND_ASSIGN(Colorbuffer);
rx::RenderTarget *mRenderTarget;
};
class DepthStencilbuffer : public RenderbufferStorage
{
public:
DepthStencilbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain);
DepthStencilbuffer(rx::Renderer *renderer, GLsizei width, GLsizei height, GLsizei samples);
~DepthStencilbuffer();
virtual rx::RenderTarget *getDepthStencil();
protected:
rx::RenderTarget *mDepthStencil;
private:
DISALLOW_COPY_AND_ASSIGN(DepthStencilbuffer);
};
class Depthbuffer : public DepthStencilbuffer
{
public:
Depthbuffer(rx::Renderer *renderer, GLsizei width, GLsizei height, GLsizei samples);
virtual ~Depthbuffer();
private:
DISALLOW_COPY_AND_ASSIGN(Depthbuffer);
};
class Stencilbuffer : public DepthStencilbuffer
{
public:
Stencilbuffer(rx::Renderer *renderer, GLsizei width, GLsizei height, GLsizei samples);
virtual ~Stencilbuffer();
private:
DISALLOW_COPY_AND_ASSIGN(Stencilbuffer);
};
}
#endif // LIBGLESV2_RENDERBUFFER_H_
| 010smithzhang-ddd | src/libGLESv2/Renderbuffer.h | C++ | bsd | 7,028 |
#include "precompiled.h"
//
// Copyright (c) 2010-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "libGLESv2/Uniform.h"
#include "libGLESv2/utilities.h"
namespace gl
{
Uniform::Uniform(GLenum type, GLenum precision, const std::string &name, unsigned int arraySize)
: type(type), precision(precision), name(name), arraySize(arraySize)
{
int bytes = gl::UniformInternalSize(type) * elementCount();
data = new unsigned char[bytes];
memset(data, 0, bytes);
dirty = true;
psRegisterIndex = -1;
vsRegisterIndex = -1;
registerCount = VariableRowCount(type) * elementCount();
}
Uniform::~Uniform()
{
delete[] data;
}
bool Uniform::isArray() const
{
return arraySize > 0;
}
unsigned int Uniform::elementCount() const
{
return arraySize > 0 ? arraySize : 1;
}
}
| 010smithzhang-ddd | src/libGLESv2/Uniform.cpp | C++ | bsd | 968 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// mathutil.h: Math and bit manipulation functions.
#ifndef LIBGLESV2_MATHUTIL_H_
#define LIBGLESV2_MATHUTIL_H_
#include <intrin.h>
#include "common/system.h"
#include "common/debug.h"
namespace gl
{
struct Vector4
{
Vector4() {}
Vector4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
float x;
float y;
float z;
float w;
};
inline bool isPow2(int x)
{
return (x & (x - 1)) == 0 && (x != 0);
}
inline int log2(int x)
{
int r = 0;
while ((x >> r) > 1) r++;
return r;
}
inline unsigned int ceilPow2(unsigned int x)
{
if (x != 0) x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
template<typename T, typename MIN, typename MAX>
inline T clamp(T x, MIN min, MAX max)
{
// Since NaNs fail all comparison tests, a NaN value will default to min
return x > min ? (x > max ? max : x) : min;
}
inline float clamp01(float x)
{
return clamp(x, 0.0f, 1.0f);
}
template<const int n>
inline unsigned int unorm(float x)
{
const unsigned int max = 0xFFFFFFFF >> (32 - n);
if (x > 1)
{
return max;
}
else if (x < 0)
{
return 0;
}
else
{
return (unsigned int)(max * x + 0.5f);
}
}
inline bool supportsSSE2()
{
static bool checked = false;
static bool supports = false;
if (checked)
{
return supports;
}
int info[4];
__cpuid(info, 0);
if (info[0] >= 1)
{
__cpuid(info, 1);
supports = (info[3] >> 26) & 1;
}
checked = true;
return supports;
}
inline unsigned short float32ToFloat16(float fp32)
{
unsigned int fp32i = (unsigned int&)fp32;
unsigned int sign = (fp32i & 0x80000000) >> 16;
unsigned int abs = fp32i & 0x7FFFFFFF;
if(abs > 0x47FFEFFF) // Infinity
{
return sign | 0x7FFF;
}
else if(abs < 0x38800000) // Denormal
{
unsigned int mantissa = (abs & 0x007FFFFF) | 0x00800000;
int e = 113 - (abs >> 23);
if(e < 24)
{
abs = mantissa >> e;
}
else
{
abs = 0;
}
return sign | (abs + 0x00000FFF + ((abs >> 13) & 1)) >> 13;
}
else
{
return sign | (abs + 0xC8000000 + 0x00000FFF + ((abs >> 13) & 1)) >> 13;
}
}
float float16ToFloat32(unsigned short h);
}
namespace rx
{
struct Range
{
Range() {}
Range(int lo, int hi) : start(lo), end(hi) { ASSERT(lo <= hi); }
int start;
int end;
};
}
#endif // LIBGLESV2_MATHUTIL_H_
| 010smithzhang-ddd | src/libGLESv2/mathutil.h | C++ | bsd | 2,775 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Program.h: Defines the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#ifndef LIBGLESV2_PROGRAM_BINARY_H_
#define LIBGLESV2_PROGRAM_BINARY_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <string>
#include <vector>
#include "common/RefCountObject.h"
#include "angletypes.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/Uniform.h"
#include "libGLESv2/Shader.h"
#include "libGLESv2/Constants.h"
namespace rx
{
class ShaderExecutable;
class Renderer;
struct TranslatedAttribute;
}
namespace gl
{
class FragmentShader;
class VertexShader;
class InfoLog;
class AttributeBindings;
struct Varying;
// Struct used for correlating uniforms/elements of uniform arrays to handles
struct UniformLocation
{
UniformLocation()
{
}
UniformLocation(const std::string &name, unsigned int element, unsigned int index);
std::string name;
unsigned int element;
unsigned int index;
};
// This is the result of linking a program. It is the state that would be passed to ProgramBinary.
class ProgramBinary : public RefCountObject
{
public:
explicit ProgramBinary(rx::Renderer *renderer);
~ProgramBinary();
rx::ShaderExecutable *getPixelExecutable();
rx::ShaderExecutable *getVertexExecutable();
rx::ShaderExecutable *getGeometryExecutable();
GLuint getAttributeLocation(const char *name);
int getSemanticIndex(int attributeIndex);
GLint getSamplerMapping(SamplerType type, unsigned int samplerIndex);
TextureType getSamplerTextureType(SamplerType type, unsigned int samplerIndex);
GLint getUsedSamplerRange(SamplerType type);
bool usesPointSize() const;
bool usesPointSpriteEmulation() const;
bool usesGeometryShader() const;
GLint getUniformLocation(std::string name);
bool setUniform1fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform2fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform3fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform4fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniform1iv(GLint location, GLsizei count, const GLint *v);
bool setUniform2iv(GLint location, GLsizei count, const GLint *v);
bool setUniform3iv(GLint location, GLsizei count, const GLint *v);
bool setUniform4iv(GLint location, GLsizei count, const GLint *v);
bool getUniformfv(GLint location, GLsizei *bufSize, GLfloat *params);
bool getUniformiv(GLint location, GLsizei *bufSize, GLint *params);
void dirtyAllUniforms();
void applyUniforms();
bool load(InfoLog &infoLog, const void *binary, GLsizei length);
bool save(void* binary, GLsizei bufSize, GLsizei *length);
GLint getLength();
bool link(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader);
void getAttachedShaders(GLsizei maxCount, GLsizei *count, GLuint *shaders);
void getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const;
GLint getActiveAttributeCount() const;
GLint getActiveAttributeMaxLength() const;
void getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const;
GLint getActiveUniformCount() const;
GLint getActiveUniformMaxLength() const;
void validate(InfoLog &infoLog);
bool validateSamplers(InfoLog *infoLog);
bool isValidated() const;
unsigned int getSerial() const;
void sortAttributesByLayout(rx::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS], int sortedSemanticIndices[MAX_VERTEX_ATTRIBS]) const;
static std::string decorateAttribute(const std::string &name); // Prepend an underscore
private:
DISALLOW_COPY_AND_ASSIGN(ProgramBinary);
int packVaryings(InfoLog &infoLog, const Varying *packing[][4], FragmentShader *fragmentShader);
bool linkVaryings(InfoLog &infoLog, int registers, const Varying *packing[][4],
std::string& pixelHLSL, std::string& vertexHLSL,
FragmentShader *fragmentShader, VertexShader *vertexShader);
bool linkAttributes(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader);
bool linkUniforms(InfoLog &infoLog, const sh::ActiveUniforms &vertexUniforms, const sh::ActiveUniforms &fragmentUniforms);
bool defineUniform(GLenum shader, const sh::Uniform &constant, InfoLog &infoLog);
std::string generateGeometryShaderHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const;
std::string generatePointSpriteHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const;
rx::Renderer *const mRenderer;
rx::ShaderExecutable *mPixelExecutable;
rx::ShaderExecutable *mVertexExecutable;
rx::ShaderExecutable *mGeometryExecutable;
Attribute mLinkedAttribute[MAX_VERTEX_ATTRIBS];
int mSemanticIndex[MAX_VERTEX_ATTRIBS];
struct Sampler
{
Sampler();
bool active;
GLint logicalTextureUnit;
TextureType textureType;
};
Sampler mSamplersPS[MAX_TEXTURE_IMAGE_UNITS];
Sampler mSamplersVS[IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
GLuint mUsedVertexSamplerRange;
GLuint mUsedPixelSamplerRange;
bool mUsesPointSize;
UniformArray mUniforms;
typedef std::vector<UniformLocation> UniformIndex;
UniformIndex mUniformIndex;
bool mValidated;
const unsigned int mSerial;
static unsigned int issueSerial();
static unsigned int mCurrentSerial;
};
}
#endif // LIBGLESV2_PROGRAM_BINARY_H_
| 010smithzhang-ddd | src/libGLESv2/ProgramBinary.h | C++ | bsd | 6,263 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Buffer.h: Defines the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.
#ifndef LIBGLESV2_BUFFER_H_
#define LIBGLESV2_BUFFER_H_
#include "common/angleutils.h"
#include "common/RefCountObject.h"
namespace rx
{
class Renderer;
class BufferStorage;
class StaticIndexBufferInterface;
class StaticVertexBufferInterface;
};
namespace gl
{
class Buffer : public RefCountObject
{
public:
Buffer(rx::Renderer *renderer, GLuint id);
virtual ~Buffer();
void bufferData(const void *data, GLsizeiptr size, GLenum usage);
void bufferSubData(const void *data, GLsizeiptr size, GLintptr offset);
GLenum usage() const;
rx::BufferStorage *getStorage() const;
unsigned int size();
rx::StaticVertexBufferInterface *getStaticVertexBuffer();
rx::StaticIndexBufferInterface *getStaticIndexBuffer();
void invalidateStaticData();
void promoteStaticUsage(int dataSize);
private:
DISALLOW_COPY_AND_ASSIGN(Buffer);
rx::Renderer *mRenderer;
GLenum mUsage;
rx::BufferStorage *mBufferStorage;
rx::StaticVertexBufferInterface *mStaticVertexBuffer;
rx::StaticIndexBufferInterface *mStaticIndexBuffer;
unsigned int mUnmodifiedDataUse;
};
}
#endif // LIBGLESV2_BUFFER_H_
| 010smithzhang-ddd | src/libGLESv2/Buffer.h | C++ | bsd | 1,539 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Program.h: Defines the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#ifndef LIBGLESV2_PROGRAM_H_
#define LIBGLESV2_PROGRAM_H_
#include <string>
#include <set>
#include "common/angleutils.h"
#include "common/RefCountObject.h"
#include "libGLESv2/Constants.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class ResourceManager;
class FragmentShader;
class VertexShader;
class ProgramBinary;
class Shader;
extern const char * const g_fakepath;
class AttributeBindings
{
public:
AttributeBindings();
~AttributeBindings();
void bindAttributeLocation(GLuint index, const char *name);
int getAttributeBinding(const std::string &name) const;
private:
std::set<std::string> mAttributeBinding[MAX_VERTEX_ATTRIBS];
};
class InfoLog
{
public:
InfoLog();
~InfoLog();
int getLength() const;
void getLog(GLsizei bufSize, GLsizei *length, char *infoLog);
void appendSanitized(const char *message);
void append(const char *info, ...);
void reset();
private:
DISALLOW_COPY_AND_ASSIGN(InfoLog);
char *mInfoLog;
};
class Program
{
public:
Program(rx::Renderer *renderer, ResourceManager *manager, GLuint handle);
~Program();
bool attachShader(Shader *shader);
bool detachShader(Shader *shader);
int getAttachedShadersCount() const;
void bindAttributeLocation(GLuint index, const char *name);
bool link();
bool isLinked();
bool setProgramBinary(const void *binary, GLsizei length);
ProgramBinary *getProgramBinary();
int getInfoLogLength() const;
void getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog);
void getAttachedShaders(GLsizei maxCount, GLsizei *count, GLuint *shaders);
void getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
GLint getActiveAttributeCount();
GLint getActiveAttributeMaxLength();
void getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
GLint getActiveUniformCount();
GLint getActiveUniformMaxLength();
void addRef();
void release();
unsigned int getRefCount() const;
void flagForDeletion();
bool isFlaggedForDeletion() const;
void validate();
bool isValidated() const;
GLint getProgramBinaryLength() const;
private:
DISALLOW_COPY_AND_ASSIGN(Program);
void unlink(bool destroy = false);
FragmentShader *mFragmentShader;
VertexShader *mVertexShader;
AttributeBindings mAttributeBindings;
BindingPointer<ProgramBinary> mProgramBinary;
bool mLinked;
bool mDeleteStatus; // Flag to indicate that the program can be deleted when no longer in use
unsigned int mRefCount;
ResourceManager *mResourceManager;
rx::Renderer *mRenderer;
const GLuint mHandle;
InfoLog mInfoLog;
};
}
#endif // LIBGLESV2_PROGRAM_H_
| 010smithzhang-ddd | src/libGLESv2/Program.h | C++ | bsd | 3,161 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Texture.cpp: Implements the gl::Texture class and its derived classes
// Texture2D and TextureCubeMap. Implements GL texture objects and related
// functionality. [OpenGL ES 2.0.24] section 3.7 page 63.
#include "libGLESv2/Texture.h"
#include "libGLESv2/main.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/renderer/Blit.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/renderer/Image.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/TextureStorage.h"
#include "libEGL/Surface.h"
namespace gl
{
Texture::Texture(rx::Renderer *renderer, GLuint id) : RefCountObject(id)
{
mRenderer = renderer;
mSamplerState.minFilter = GL_NEAREST_MIPMAP_LINEAR;
mSamplerState.magFilter = GL_LINEAR;
mSamplerState.wrapS = GL_REPEAT;
mSamplerState.wrapT = GL_REPEAT;
mSamplerState.maxAnisotropy = 1.0f;
mSamplerState.lodOffset = 0;
mUsage = GL_NONE;
mDirtyImages = true;
mImmutable = false;
}
Texture::~Texture()
{
}
// Returns true on successful filter state update (valid enum parameter)
bool Texture::setMinFilter(GLenum filter)
{
switch (filter)
{
case GL_NEAREST:
case GL_LINEAR:
case GL_NEAREST_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_NEAREST:
case GL_NEAREST_MIPMAP_LINEAR:
case GL_LINEAR_MIPMAP_LINEAR:
mSamplerState.minFilter = filter;
return true;
default:
return false;
}
}
// Returns true on successful filter state update (valid enum parameter)
bool Texture::setMagFilter(GLenum filter)
{
switch (filter)
{
case GL_NEAREST:
case GL_LINEAR:
mSamplerState.magFilter = filter;
return true;
default:
return false;
}
}
// Returns true on successful wrap state update (valid enum parameter)
bool Texture::setWrapS(GLenum wrap)
{
switch (wrap)
{
case GL_REPEAT:
case GL_CLAMP_TO_EDGE:
case GL_MIRRORED_REPEAT:
mSamplerState.wrapS = wrap;
return true;
default:
return false;
}
}
// Returns true on successful wrap state update (valid enum parameter)
bool Texture::setWrapT(GLenum wrap)
{
switch (wrap)
{
case GL_REPEAT:
case GL_CLAMP_TO_EDGE:
case GL_MIRRORED_REPEAT:
mSamplerState.wrapT = wrap;
return true;
default:
return false;
}
}
// Returns true on successful max anisotropy update (valid anisotropy value)
bool Texture::setMaxAnisotropy(float textureMaxAnisotropy, float contextMaxAnisotropy)
{
textureMaxAnisotropy = std::min(textureMaxAnisotropy, contextMaxAnisotropy);
if (textureMaxAnisotropy < 1.0f)
{
return false;
}
mSamplerState.maxAnisotropy = textureMaxAnisotropy;
return true;
}
// Returns true on successful usage state update (valid enum parameter)
bool Texture::setUsage(GLenum usage)
{
switch (usage)
{
case GL_NONE:
case GL_FRAMEBUFFER_ATTACHMENT_ANGLE:
mUsage = usage;
return true;
default:
return false;
}
}
GLenum Texture::getMinFilter() const
{
return mSamplerState.minFilter;
}
GLenum Texture::getMagFilter() const
{
return mSamplerState.magFilter;
}
GLenum Texture::getWrapS() const
{
return mSamplerState.wrapS;
}
GLenum Texture::getWrapT() const
{
return mSamplerState.wrapT;
}
float Texture::getMaxAnisotropy() const
{
return mSamplerState.maxAnisotropy;
}
int Texture::getLodOffset()
{
rx::TextureStorageInterface *texture = getStorage(false);
return texture ? texture->getLodOffset() : 0;
}
void Texture::getSamplerState(SamplerState *sampler)
{
*sampler = mSamplerState;
sampler->lodOffset = getLodOffset();
}
GLenum Texture::getUsage() const
{
return mUsage;
}
bool Texture::isMipmapFiltered() const
{
switch (mSamplerState.minFilter)
{
case GL_NEAREST:
case GL_LINEAR:
return false;
case GL_NEAREST_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_NEAREST:
case GL_NEAREST_MIPMAP_LINEAR:
case GL_LINEAR_MIPMAP_LINEAR:
return true;
default: UNREACHABLE();
return false;
}
}
void Texture::setImage(GLint unpackAlignment, const void *pixels, rx::Image *image)
{
if (pixels != NULL)
{
image->loadData(0, 0, image->getWidth(), image->getHeight(), unpackAlignment, pixels);
mDirtyImages = true;
}
}
void Texture::setCompressedImage(GLsizei imageSize, const void *pixels, rx::Image *image)
{
if (pixels != NULL)
{
image->loadCompressedData(0, 0, image->getWidth(), image->getHeight(), pixels);
mDirtyImages = true;
}
}
bool Texture::subImage(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels, rx::Image *image)
{
if (pixels != NULL)
{
image->loadData(xoffset, yoffset, width, height, unpackAlignment, pixels);
mDirtyImages = true;
}
return true;
}
bool Texture::subImageCompressed(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels, rx::Image *image)
{
if (pixels != NULL)
{
image->loadCompressedData(xoffset, yoffset, width, height, pixels);
mDirtyImages = true;
}
return true;
}
rx::TextureStorageInterface *Texture::getNativeTexture()
{
// ensure the underlying texture is created
rx::TextureStorageInterface *storage = getStorage(false);
if (storage)
{
updateTexture();
}
return storage;
}
bool Texture::hasDirtyImages() const
{
return mDirtyImages;
}
void Texture::resetDirty()
{
mDirtyImages = false;
}
unsigned int Texture::getTextureSerial()
{
rx::TextureStorageInterface *texture = getStorage(false);
return texture ? texture->getTextureSerial() : 0;
}
unsigned int Texture::getRenderTargetSerial(GLenum target)
{
rx::TextureStorageInterface *texture = getStorage(true);
return texture ? texture->getRenderTargetSerial(target) : 0;
}
bool Texture::isImmutable() const
{
return mImmutable;
}
GLint Texture::creationLevels(GLsizei width, GLsizei height) const
{
if ((isPow2(width) && isPow2(height)) || mRenderer->getNonPower2TextureSupport())
{
return 0; // Maximum number of levels
}
else
{
// OpenGL ES 2.0 without GL_OES_texture_npot does not permit NPOT mipmaps.
return 1;
}
}
GLint Texture::creationLevels(GLsizei size) const
{
return creationLevels(size, size);
}
Texture2D::Texture2D(rx::Renderer *renderer, GLuint id) : Texture(renderer, id)
{
mTexStorage = NULL;
mSurface = NULL;
mColorbufferProxy = NULL;
mProxyRefs = 0;
for (int i = 0; i < IMPLEMENTATION_MAX_TEXTURE_LEVELS; ++i)
{
mImageArray[i] = renderer->createImage();
}
}
Texture2D::~Texture2D()
{
mColorbufferProxy = NULL;
delete mTexStorage;
mTexStorage = NULL;
if (mSurface)
{
mSurface->setBoundTexture(NULL);
mSurface = NULL;
}
for (int i = 0; i < IMPLEMENTATION_MAX_TEXTURE_LEVELS; ++i)
{
delete mImageArray[i];
}
}
// We need to maintain a count of references to renderbuffers acting as
// proxies for this texture, so that we do not attempt to use a pointer
// to a renderbuffer proxy which has been deleted.
void Texture2D::addProxyRef(const Renderbuffer *proxy)
{
mProxyRefs++;
}
void Texture2D::releaseProxy(const Renderbuffer *proxy)
{
if (mProxyRefs > 0)
mProxyRefs--;
if (mProxyRefs == 0)
mColorbufferProxy = NULL;
}
GLenum Texture2D::getTarget() const
{
return GL_TEXTURE_2D;
}
GLsizei Texture2D::getWidth(GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[level]->getWidth();
else
return 0;
}
GLsizei Texture2D::getHeight(GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[level]->getHeight();
else
return 0;
}
GLenum Texture2D::getInternalFormat(GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[level]->getInternalFormat();
else
return GL_NONE;
}
GLenum Texture2D::getActualFormat(GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[level]->getActualFormat();
else
return D3DFMT_UNKNOWN;
}
void Texture2D::redefineImage(GLint level, GLint internalformat, GLsizei width, GLsizei height)
{
releaseTexImage();
// If there currently is a corresponding storage texture image, it has these parameters
const int storageWidth = std::max(1, mImageArray[0]->getWidth() >> level);
const int storageHeight = std::max(1, mImageArray[0]->getHeight() >> level);
const int storageFormat = mImageArray[0]->getInternalFormat();
mImageArray[level]->redefine(mRenderer, internalformat, width, height, false);
if (mTexStorage)
{
const int storageLevels = mTexStorage->levelCount();
if ((level >= storageLevels && storageLevels != 0) ||
width != storageWidth ||
height != storageHeight ||
internalformat != storageFormat) // Discard mismatched storage
{
for (int i = 0; i < IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
mImageArray[i]->markDirty();
}
delete mTexStorage;
mTexStorage = NULL;
mDirtyImages = true;
}
}
}
void Texture2D::setImage(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
GLint internalformat = ConvertSizedInternalFormat(format, type);
redefineImage(level, internalformat, width, height);
Texture::setImage(unpackAlignment, pixels, mImageArray[level]);
}
void Texture2D::bindTexImage(egl::Surface *surface)
{
releaseTexImage();
GLint internalformat = surface->getFormat();
mImageArray[0]->redefine(mRenderer, internalformat, surface->getWidth(), surface->getHeight(), true);
delete mTexStorage;
mTexStorage = new rx::TextureStorageInterface2D(mRenderer, surface->getSwapChain());
mDirtyImages = true;
mSurface = surface;
mSurface->setBoundTexture(this);
}
void Texture2D::releaseTexImage()
{
if (mSurface)
{
mSurface->setBoundTexture(NULL);
mSurface = NULL;
if (mTexStorage)
{
delete mTexStorage;
mTexStorage = NULL;
}
for (int i = 0; i < IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
mImageArray[i]->redefine(mRenderer, GL_NONE, 0, 0, true);
}
}
}
void Texture2D::setCompressedImage(GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels)
{
// compressed formats don't have separate sized internal formats-- we can just use the compressed format directly
redefineImage(level, format, width, height);
Texture::setCompressedImage(imageSize, pixels, mImageArray[level]);
}
void Texture2D::commitRect(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
if (level < levelCount())
{
rx::Image *image = mImageArray[level];
if (image->updateSurface(mTexStorage, level, xoffset, yoffset, width, height))
{
image->markClean();
}
}
}
void Texture2D::subImage(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
if (Texture::subImage(xoffset, yoffset, width, height, format, type, unpackAlignment, pixels, mImageArray[level]))
{
commitRect(level, xoffset, yoffset, width, height);
}
}
void Texture2D::subImageCompressed(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels)
{
if (Texture::subImageCompressed(xoffset, yoffset, width, height, format, imageSize, pixels, mImageArray[level]))
{
commitRect(level, xoffset, yoffset, width, height);
}
}
void Texture2D::copyImage(GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source)
{
GLint internalformat = ConvertSizedInternalFormat(format, GL_UNSIGNED_BYTE);
redefineImage(level, internalformat, width, height);
if (!mImageArray[level]->isRenderableFormat())
{
mImageArray[level]->copy(0, 0, x, y, width, height, source);
mDirtyImages = true;
}
else
{
if (!mTexStorage || !mTexStorage->isRenderTarget())
{
convertToRenderTarget();
}
mImageArray[level]->markClean();
if (width != 0 && height != 0 && level < levelCount())
{
gl::Rectangle sourceRect;
sourceRect.x = x;
sourceRect.width = width;
sourceRect.y = y;
sourceRect.height = height;
mRenderer->copyImage(source, sourceRect, format, 0, 0, mTexStorage, level);
}
}
}
void Texture2D::copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source)
{
if (xoffset + width > mImageArray[level]->getWidth() || yoffset + height > mImageArray[level]->getHeight())
{
return gl::error(GL_INVALID_VALUE);
}
if (!mImageArray[level]->isRenderableFormat() || (!mTexStorage && !isSamplerComplete()))
{
mImageArray[level]->copy(xoffset, yoffset, x, y, width, height, source);
mDirtyImages = true;
}
else
{
if (!mTexStorage || !mTexStorage->isRenderTarget())
{
convertToRenderTarget();
}
updateTexture();
if (level < levelCount())
{
gl::Rectangle sourceRect;
sourceRect.x = x;
sourceRect.width = width;
sourceRect.y = y;
sourceRect.height = height;
mRenderer->copyImage(source, sourceRect,
gl::ExtractFormat(mImageArray[0]->getInternalFormat()),
xoffset, yoffset, mTexStorage, level);
}
}
}
void Texture2D::storage(GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
delete mTexStorage;
mTexStorage = new rx::TextureStorageInterface2D(mRenderer, levels, internalformat, mUsage, false, width, height);
mImmutable = true;
for (int level = 0; level < levels; level++)
{
mImageArray[level]->redefine(mRenderer, internalformat, width, height, true);
width = std::max(1, width >> 1);
height = std::max(1, height >> 1);
}
for (int level = levels; level < IMPLEMENTATION_MAX_TEXTURE_LEVELS; level++)
{
mImageArray[level]->redefine(mRenderer, GL_NONE, 0, 0, true);
}
if (mTexStorage->isManaged())
{
int levels = levelCount();
for (int level = 0; level < levels; level++)
{
mImageArray[level]->setManagedSurface(mTexStorage, level);
}
}
}
// Tests for 2D texture sampling completeness. [OpenGL ES 2.0.24] section 3.8.2 page 85.
bool Texture2D::isSamplerComplete() const
{
GLsizei width = mImageArray[0]->getWidth();
GLsizei height = mImageArray[0]->getHeight();
if (width <= 0 || height <= 0)
{
return false;
}
bool mipmapping = isMipmapFiltered();
bool filtering, renderable;
if ((IsFloat32Format(getInternalFormat(0)) && !mRenderer->getFloat32TextureSupport(&filtering, &renderable)) ||
(IsFloat16Format(getInternalFormat(0)) && !mRenderer->getFloat16TextureSupport(&filtering, &renderable)))
{
if (mSamplerState.magFilter != GL_NEAREST ||
(mSamplerState.minFilter != GL_NEAREST && mSamplerState.minFilter != GL_NEAREST_MIPMAP_NEAREST))
{
return false;
}
}
bool npotSupport = mRenderer->getNonPower2TextureSupport();
if (!npotSupport)
{
if ((mSamplerState.wrapS != GL_CLAMP_TO_EDGE && !isPow2(width)) ||
(mSamplerState.wrapT != GL_CLAMP_TO_EDGE && !isPow2(height)))
{
return false;
}
}
if (mipmapping)
{
if (!npotSupport)
{
if (!isPow2(width) || !isPow2(height))
{
return false;
}
}
if (!isMipmapComplete())
{
return false;
}
}
return true;
}
// Tests for 2D texture (mipmap) completeness. [OpenGL ES 2.0.24] section 3.7.10 page 81.
bool Texture2D::isMipmapComplete() const
{
if (isImmutable())
{
return true;
}
GLsizei width = mImageArray[0]->getWidth();
GLsizei height = mImageArray[0]->getHeight();
if (width <= 0 || height <= 0)
{
return false;
}
int q = log2(std::max(width, height));
for (int level = 1; level <= q; level++)
{
if (mImageArray[level]->getInternalFormat() != mImageArray[0]->getInternalFormat())
{
return false;
}
if (mImageArray[level]->getWidth() != std::max(1, width >> level))
{
return false;
}
if (mImageArray[level]->getHeight() != std::max(1, height >> level))
{
return false;
}
}
return true;
}
bool Texture2D::isCompressed(GLint level) const
{
return IsCompressed(getInternalFormat(level));
}
bool Texture2D::isDepth(GLint level) const
{
return IsDepthTexture(getInternalFormat(level));
}
// Constructs a native texture resource from the texture images
void Texture2D::createTexture()
{
GLsizei width = mImageArray[0]->getWidth();
GLsizei height = mImageArray[0]->getHeight();
if (!(width > 0 && height > 0))
return; // do not attempt to create native textures for nonexistant data
GLint levels = creationLevels(width, height);
GLenum internalformat = mImageArray[0]->getInternalFormat();
delete mTexStorage;
mTexStorage = new rx::TextureStorageInterface2D(mRenderer, levels, internalformat, mUsage, false, width, height);
if (mTexStorage->isManaged())
{
int levels = levelCount();
for (int level = 0; level < levels; level++)
{
mImageArray[level]->setManagedSurface(mTexStorage, level);
}
}
mDirtyImages = true;
}
void Texture2D::updateTexture()
{
bool mipmapping = (isMipmapFiltered() && isMipmapComplete());
int levels = (mipmapping ? levelCount() : 1);
for (int level = 0; level < levels; level++)
{
rx::Image *image = mImageArray[level];
if (image->isDirty())
{
commitRect(level, 0, 0, mImageArray[level]->getWidth(), mImageArray[level]->getHeight());
}
}
}
void Texture2D::convertToRenderTarget()
{
rx::TextureStorageInterface2D *newTexStorage = NULL;
if (mImageArray[0]->getWidth() != 0 && mImageArray[0]->getHeight() != 0)
{
GLsizei width = mImageArray[0]->getWidth();
GLsizei height = mImageArray[0]->getHeight();
GLint levels = mTexStorage != NULL ? mTexStorage->levelCount() : creationLevels(width, height);
GLenum internalformat = mImageArray[0]->getInternalFormat();
newTexStorage = new rx::TextureStorageInterface2D(mRenderer, levels, internalformat, GL_FRAMEBUFFER_ATTACHMENT_ANGLE, true, width, height);
if (mTexStorage != NULL)
{
if (!mRenderer->copyToRenderTarget(newTexStorage, mTexStorage))
{
delete newTexStorage;
return gl::error(GL_OUT_OF_MEMORY);
}
}
}
delete mTexStorage;
mTexStorage = newTexStorage;
mDirtyImages = true;
}
void Texture2D::generateMipmaps()
{
if (!mRenderer->getNonPower2TextureSupport())
{
if (!isPow2(mImageArray[0]->getWidth()) || !isPow2(mImageArray[0]->getHeight()))
{
return gl::error(GL_INVALID_OPERATION);
}
}
// Purge array levels 1 through q and reset them to represent the generated mipmap levels.
unsigned int q = log2(std::max(mImageArray[0]->getWidth(), mImageArray[0]->getHeight()));
for (unsigned int i = 1; i <= q; i++)
{
redefineImage(i, mImageArray[0]->getInternalFormat(),
std::max(mImageArray[0]->getWidth() >> i, 1),
std::max(mImageArray[0]->getHeight() >> i, 1));
}
if (mTexStorage && mTexStorage->isRenderTarget())
{
for (unsigned int i = 1; i <= q; i++)
{
mTexStorage->generateMipmap(i);
mImageArray[i]->markClean();
}
}
else
{
for (unsigned int i = 1; i <= q; i++)
{
mRenderer->generateMipmap(mImageArray[i], mImageArray[i - 1]);
}
}
}
Renderbuffer *Texture2D::getRenderbuffer(GLenum target)
{
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION, (Renderbuffer *)NULL);
}
if (mColorbufferProxy == NULL)
{
mColorbufferProxy = new Renderbuffer(mRenderer, id(), new RenderbufferTexture2D(this, target));
}
return mColorbufferProxy;
}
rx::RenderTarget *Texture2D::getRenderTarget(GLenum target)
{
ASSERT(target == GL_TEXTURE_2D);
// ensure the underlying texture is created
if (getStorage(true) == NULL)
{
return NULL;
}
updateTexture();
// ensure this is NOT a depth texture
if (isDepth(0))
{
return NULL;
}
return mTexStorage->getRenderTarget();
}
rx::RenderTarget *Texture2D::getDepthStencil(GLenum target)
{
ASSERT(target == GL_TEXTURE_2D);
// ensure the underlying texture is created
if (getStorage(true) == NULL)
{
return NULL;
}
updateTexture();
// ensure this is actually a depth texture
if (!isDepth(0))
{
return NULL;
}
return mTexStorage->getRenderTarget();
}
int Texture2D::levelCount()
{
return mTexStorage ? mTexStorage->levelCount() : 0;
}
rx::TextureStorageInterface *Texture2D::getStorage(bool renderTarget)
{
if (!mTexStorage || (renderTarget && !mTexStorage->isRenderTarget()))
{
if (renderTarget)
{
convertToRenderTarget();
}
else
{
createTexture();
}
}
return mTexStorage;
}
TextureCubeMap::TextureCubeMap(rx::Renderer *renderer, GLuint id) : Texture(renderer, id)
{
mTexStorage = NULL;
for (int i = 0; i < 6; i++)
{
mFaceProxies[i] = NULL;
mFaceProxyRefs[i] = 0;
for (int j = 0; j < IMPLEMENTATION_MAX_TEXTURE_LEVELS; ++j)
{
mImageArray[i][j] = renderer->createImage();
}
}
}
TextureCubeMap::~TextureCubeMap()
{
for (int i = 0; i < 6; i++)
{
mFaceProxies[i] = NULL;
for (int j = 0; j < IMPLEMENTATION_MAX_TEXTURE_LEVELS; ++j)
{
delete mImageArray[i][j];
}
}
delete mTexStorage;
mTexStorage = NULL;
}
// We need to maintain a count of references to renderbuffers acting as
// proxies for this texture, so that the texture is not deleted while
// proxy references still exist. If the reference count drops to zero,
// we set our proxy pointer NULL, so that a new attempt at referencing
// will cause recreation.
void TextureCubeMap::addProxyRef(const Renderbuffer *proxy)
{
for (int i = 0; i < 6; i++)
{
if (mFaceProxies[i] == proxy)
mFaceProxyRefs[i]++;
}
}
void TextureCubeMap::releaseProxy(const Renderbuffer *proxy)
{
for (int i = 0; i < 6; i++)
{
if (mFaceProxies[i] == proxy)
{
if (mFaceProxyRefs[i] > 0)
mFaceProxyRefs[i]--;
if (mFaceProxyRefs[i] == 0)
mFaceProxies[i] = NULL;
}
}
}
GLenum TextureCubeMap::getTarget() const
{
return GL_TEXTURE_CUBE_MAP;
}
GLsizei TextureCubeMap::getWidth(GLenum target, GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[faceIndex(target)][level]->getWidth();
else
return 0;
}
GLsizei TextureCubeMap::getHeight(GLenum target, GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[faceIndex(target)][level]->getHeight();
else
return 0;
}
GLenum TextureCubeMap::getInternalFormat(GLenum target, GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[faceIndex(target)][level]->getInternalFormat();
else
return GL_NONE;
}
GLenum TextureCubeMap::getActualFormat(GLenum target, GLint level) const
{
if (level < IMPLEMENTATION_MAX_TEXTURE_LEVELS)
return mImageArray[faceIndex(target)][level]->getActualFormat();
else
return D3DFMT_UNKNOWN;
}
void TextureCubeMap::setImagePosX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(0, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setImageNegX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(1, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setImagePosY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(2, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setImageNegY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(3, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setImagePosZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(4, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setImageNegZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
setImage(5, level, width, height, format, type, unpackAlignment, pixels);
}
void TextureCubeMap::setCompressedImage(GLenum face, GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels)
{
// compressed formats don't have separate sized internal formats-- we can just use the compressed format directly
redefineImage(faceIndex(face), level, format, width, height);
Texture::setCompressedImage(imageSize, pixels, mImageArray[faceIndex(face)][level]);
}
void TextureCubeMap::commitRect(int face, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
if (level < levelCount())
{
rx::Image *image = mImageArray[face][level];
if (image->updateSurface(mTexStorage, face, level, xoffset, yoffset, width, height))
image->markClean();
}
}
void TextureCubeMap::subImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
if (Texture::subImage(xoffset, yoffset, width, height, format, type, unpackAlignment, pixels, mImageArray[faceIndex(target)][level]))
{
commitRect(faceIndex(target), level, xoffset, yoffset, width, height);
}
}
void TextureCubeMap::subImageCompressed(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels)
{
if (Texture::subImageCompressed(xoffset, yoffset, width, height, format, imageSize, pixels, mImageArray[faceIndex(target)][level]))
{
commitRect(faceIndex(target), level, xoffset, yoffset, width, height);
}
}
// Tests for cube map sampling completeness. [OpenGL ES 2.0.24] section 3.8.2 page 86.
bool TextureCubeMap::isSamplerComplete() const
{
int size = mImageArray[0][0]->getWidth();
bool mipmapping = isMipmapFiltered();
bool filtering, renderable;
if ((gl::ExtractType(getInternalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0)) == GL_FLOAT && !mRenderer->getFloat32TextureSupport(&filtering, &renderable)) ||
(gl::ExtractType(getInternalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0) == GL_HALF_FLOAT_OES) && !mRenderer->getFloat16TextureSupport(&filtering, &renderable)))
{
if (mSamplerState.magFilter != GL_NEAREST ||
(mSamplerState.minFilter != GL_NEAREST && mSamplerState.minFilter != GL_NEAREST_MIPMAP_NEAREST))
{
return false;
}
}
if (!isPow2(size) && !mRenderer->getNonPower2TextureSupport())
{
if (mSamplerState.wrapS != GL_CLAMP_TO_EDGE || mSamplerState.wrapT != GL_CLAMP_TO_EDGE || mipmapping)
{
return false;
}
}
if (!mipmapping)
{
if (!isCubeComplete())
{
return false;
}
}
else
{
if (!isMipmapCubeComplete()) // Also tests for isCubeComplete()
{
return false;
}
}
return true;
}
// Tests for cube texture completeness. [OpenGL ES 2.0.24] section 3.7.10 page 81.
bool TextureCubeMap::isCubeComplete() const
{
if (mImageArray[0][0]->getWidth() <= 0 || mImageArray[0][0]->getHeight() != mImageArray[0][0]->getWidth())
{
return false;
}
for (unsigned int face = 1; face < 6; face++)
{
if (mImageArray[face][0]->getWidth() != mImageArray[0][0]->getWidth() ||
mImageArray[face][0]->getWidth() != mImageArray[0][0]->getHeight() ||
mImageArray[face][0]->getInternalFormat() != mImageArray[0][0]->getInternalFormat())
{
return false;
}
}
return true;
}
bool TextureCubeMap::isMipmapCubeComplete() const
{
if (isImmutable())
{
return true;
}
if (!isCubeComplete())
{
return false;
}
GLsizei size = mImageArray[0][0]->getWidth();
int q = log2(size);
for (int face = 0; face < 6; face++)
{
for (int level = 1; level <= q; level++)
{
if (mImageArray[face][level]->getInternalFormat() != mImageArray[0][0]->getInternalFormat())
{
return false;
}
if (mImageArray[face][level]->getWidth() != std::max(1, size >> level))
{
return false;
}
}
}
return true;
}
bool TextureCubeMap::isCompressed(GLenum target, GLint level) const
{
return IsCompressed(getInternalFormat(target, level));
}
// Constructs a native texture resource from the texture images, or returns an existing one
void TextureCubeMap::createTexture()
{
GLsizei size = mImageArray[0][0]->getWidth();
if (!(size > 0))
return; // do not attempt to create native textures for nonexistant data
GLint levels = creationLevels(size);
GLenum internalformat = mImageArray[0][0]->getInternalFormat();
delete mTexStorage;
mTexStorage = new rx::TextureStorageInterfaceCube(mRenderer, levels, internalformat, mUsage, false, size);
if (mTexStorage->isManaged())
{
int levels = levelCount();
for (int face = 0; face < 6; face++)
{
for (int level = 0; level < levels; level++)
{
mImageArray[face][level]->setManagedSurface(mTexStorage, face, level);
}
}
}
mDirtyImages = true;
}
void TextureCubeMap::updateTexture()
{
bool mipmapping = isMipmapFiltered() && isMipmapCubeComplete();
for (int face = 0; face < 6; face++)
{
int levels = (mipmapping ? levelCount() : 1);
for (int level = 0; level < levels; level++)
{
rx::Image *image = mImageArray[face][level];
if (image->isDirty())
{
commitRect(face, level, 0, 0, image->getWidth(), image->getHeight());
}
}
}
}
void TextureCubeMap::convertToRenderTarget()
{
rx::TextureStorageInterfaceCube *newTexStorage = NULL;
if (mImageArray[0][0]->getWidth() != 0)
{
GLsizei size = mImageArray[0][0]->getWidth();
GLint levels = mTexStorage != NULL ? mTexStorage->levelCount() : creationLevels(size);
GLenum internalformat = mImageArray[0][0]->getInternalFormat();
newTexStorage = new rx::TextureStorageInterfaceCube(mRenderer, levels, internalformat, GL_FRAMEBUFFER_ATTACHMENT_ANGLE, true, size);
if (mTexStorage != NULL)
{
if (!mRenderer->copyToRenderTarget(newTexStorage, mTexStorage))
{
delete newTexStorage;
return gl::error(GL_OUT_OF_MEMORY);
}
}
}
delete mTexStorage;
mTexStorage = newTexStorage;
mDirtyImages = true;
}
void TextureCubeMap::setImage(int faceIndex, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels)
{
GLint internalformat = ConvertSizedInternalFormat(format, type);
redefineImage(faceIndex, level, internalformat, width, height);
Texture::setImage(unpackAlignment, pixels, mImageArray[faceIndex][level]);
}
unsigned int TextureCubeMap::faceIndex(GLenum face)
{
META_ASSERT(GL_TEXTURE_CUBE_MAP_NEGATIVE_X - GL_TEXTURE_CUBE_MAP_POSITIVE_X == 1);
META_ASSERT(GL_TEXTURE_CUBE_MAP_POSITIVE_Y - GL_TEXTURE_CUBE_MAP_POSITIVE_X == 2);
META_ASSERT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y - GL_TEXTURE_CUBE_MAP_POSITIVE_X == 3);
META_ASSERT(GL_TEXTURE_CUBE_MAP_POSITIVE_Z - GL_TEXTURE_CUBE_MAP_POSITIVE_X == 4);
META_ASSERT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z - GL_TEXTURE_CUBE_MAP_POSITIVE_X == 5);
return face - GL_TEXTURE_CUBE_MAP_POSITIVE_X;
}
void TextureCubeMap::redefineImage(int face, GLint level, GLint internalformat, GLsizei width, GLsizei height)
{
// If there currently is a corresponding storage texture image, it has these parameters
const int storageWidth = std::max(1, mImageArray[0][0]->getWidth() >> level);
const int storageHeight = std::max(1, mImageArray[0][0]->getHeight() >> level);
const int storageFormat = mImageArray[0][0]->getInternalFormat();
mImageArray[face][level]->redefine(mRenderer, internalformat, width, height, false);
if (mTexStorage)
{
const int storageLevels = mTexStorage->levelCount();
if ((level >= storageLevels && storageLevels != 0) ||
width != storageWidth ||
height != storageHeight ||
internalformat != storageFormat) // Discard mismatched storage
{
for (int i = 0; i < IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
for (int f = 0; f < 6; f++)
{
mImageArray[f][i]->markDirty();
}
}
delete mTexStorage;
mTexStorage = NULL;
mDirtyImages = true;
}
}
}
void TextureCubeMap::copyImage(GLenum target, GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source)
{
unsigned int faceindex = faceIndex(target);
GLint internalformat = gl::ConvertSizedInternalFormat(format, GL_UNSIGNED_BYTE);
redefineImage(faceindex, level, internalformat, width, height);
if (!mImageArray[faceindex][level]->isRenderableFormat())
{
mImageArray[faceindex][level]->copy(0, 0, x, y, width, height, source);
mDirtyImages = true;
}
else
{
if (!mTexStorage || !mTexStorage->isRenderTarget())
{
convertToRenderTarget();
}
mImageArray[faceindex][level]->markClean();
ASSERT(width == height);
if (width > 0 && level < levelCount())
{
gl::Rectangle sourceRect;
sourceRect.x = x;
sourceRect.width = width;
sourceRect.y = y;
sourceRect.height = height;
mRenderer->copyImage(source, sourceRect, format, 0, 0, mTexStorage, target, level);
}
}
}
void TextureCubeMap::copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source)
{
GLsizei size = mImageArray[faceIndex(target)][level]->getWidth();
if (xoffset + width > size || yoffset + height > size)
{
return gl::error(GL_INVALID_VALUE);
}
unsigned int faceindex = faceIndex(target);
if (!mImageArray[faceindex][level]->isRenderableFormat() || (!mTexStorage && !isSamplerComplete()))
{
mImageArray[faceindex][level]->copy(0, 0, x, y, width, height, source);
mDirtyImages = true;
}
else
{
if (!mTexStorage || !mTexStorage->isRenderTarget())
{
convertToRenderTarget();
}
updateTexture();
if (level < levelCount())
{
gl::Rectangle sourceRect;
sourceRect.x = x;
sourceRect.width = width;
sourceRect.y = y;
sourceRect.height = height;
mRenderer->copyImage(source, sourceRect, gl::ExtractFormat(mImageArray[0][0]->getInternalFormat()),
xoffset, yoffset, mTexStorage, target, level);
}
}
}
void TextureCubeMap::storage(GLsizei levels, GLenum internalformat, GLsizei size)
{
delete mTexStorage;
mTexStorage = new rx::TextureStorageInterfaceCube(mRenderer, levels, internalformat, mUsage, false, size);
mImmutable = true;
for (int level = 0; level < levels; level++)
{
for (int face = 0; face < 6; face++)
{
mImageArray[face][level]->redefine(mRenderer, internalformat, size, size, true);
size = std::max(1, size >> 1);
}
}
for (int level = levels; level < IMPLEMENTATION_MAX_TEXTURE_LEVELS; level++)
{
for (int face = 0; face < 6; face++)
{
mImageArray[face][level]->redefine(mRenderer, GL_NONE, 0, 0, true);
}
}
if (mTexStorage->isManaged())
{
int levels = levelCount();
for (int face = 0; face < 6; face++)
{
for (int level = 0; level < levels; level++)
{
mImageArray[face][level]->setManagedSurface(mTexStorage, face, level);
}
}
}
}
void TextureCubeMap::generateMipmaps()
{
if (!isCubeComplete())
{
return gl::error(GL_INVALID_OPERATION);
}
if (!mRenderer->getNonPower2TextureSupport())
{
if (!isPow2(mImageArray[0][0]->getWidth()))
{
return gl::error(GL_INVALID_OPERATION);
}
}
// Purge array levels 1 through q and reset them to represent the generated mipmap levels.
unsigned int q = log2(mImageArray[0][0]->getWidth());
for (unsigned int f = 0; f < 6; f++)
{
for (unsigned int i = 1; i <= q; i++)
{
redefineImage(f, i, mImageArray[f][0]->getInternalFormat(),
std::max(mImageArray[f][0]->getWidth() >> i, 1),
std::max(mImageArray[f][0]->getWidth() >> i, 1));
}
}
if (mTexStorage && mTexStorage->isRenderTarget())
{
for (unsigned int f = 0; f < 6; f++)
{
for (unsigned int i = 1; i <= q; i++)
{
mTexStorage->generateMipmap(f, i);
mImageArray[f][i]->markClean();
}
}
}
else
{
for (unsigned int f = 0; f < 6; f++)
{
for (unsigned int i = 1; i <= q; i++)
{
mRenderer->generateMipmap(mImageArray[f][i], mImageArray[f][i - 1]);
}
}
}
}
Renderbuffer *TextureCubeMap::getRenderbuffer(GLenum target)
{
if (!IsCubemapTextureTarget(target))
{
return gl::error(GL_INVALID_OPERATION, (Renderbuffer *)NULL);
}
unsigned int face = faceIndex(target);
if (mFaceProxies[face] == NULL)
{
mFaceProxies[face] = new Renderbuffer(mRenderer, id(), new RenderbufferTextureCubeMap(this, target));
}
return mFaceProxies[face];
}
rx::RenderTarget *TextureCubeMap::getRenderTarget(GLenum target)
{
ASSERT(IsCubemapTextureTarget(target));
// ensure the underlying texture is created
if (getStorage(true) == NULL)
{
return NULL;
}
updateTexture();
return mTexStorage->getRenderTarget(target);
}
int TextureCubeMap::levelCount()
{
return mTexStorage ? mTexStorage->levelCount() - getLodOffset() : 0;
}
rx::TextureStorageInterface *TextureCubeMap::getStorage(bool renderTarget)
{
if (!mTexStorage || (renderTarget && !mTexStorage->isRenderTarget()))
{
if (renderTarget)
{
convertToRenderTarget();
}
else
{
createTexture();
}
}
return mTexStorage;
}
}
| 010smithzhang-ddd | src/libGLESv2/Texture.cpp | C++ | bsd | 41,345 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// precompiled.h: Precompiled header file for libGLESv2.
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#define EGLAPI
#include <EGL/egl.h>
#include <assert.h>
#include <cstddef>
#include <float.h>
#include <intrin.h>
#include <math.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <algorithm> // for std::min and std::max
#include <limits>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include <d3d9.h>
#include <D3D11.h>
#include <dxgi.h>
#include <D3Dcompiler.h>
#ifdef _MSC_VER
#include <hash_map>
#endif
| 010smithzhang-ddd | src/libGLESv2/precompiled.h | C++ | bsd | 824 |
deps = {
"trunk/third_party/gyp":
"http://gyp.googlecode.com/svn/trunk@1564",
"trunk/third_party/googletest":
"http://googletest.googlecode.com/svn/trunk@573", #release 1.6.0
"trunk/third_party/googlemock":
"http://googlemock.googlecode.com/svn/trunk@387", #release 1.6.0
}
hooks = [
{
# A change to a .gyp, .gypi, or to GYP itself should run the generator.
"pattern": ".",
"action": ["python", "trunk/build/gyp_angle"],
},
]
| 010smithzhang-ddd | DEPS | Python | bsd | 469 |
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2009 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* $Revision: 9356 $ on $Date: 2009-10-21 02:52:25 -0700 (Wed, 21 Oct 2009) $
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by sending them to the public Khronos Bugzilla
* (http://khronos.org/bugzilla) by filing a bug against product
* "Khronos (general)" component "Registry".
*
* A predefined template which fills in some of the bug fields can be
* reached using http://tinyurl.com/khrplatform-h-bugreport, but you
* must create a Bugzilla login first.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */
| 010smithzhang-ddd | include/KHR/khrplatform.h | C | bsd | 9,599 |
/* -*- mode: c; tab-width: 8; -*- */
/* vi: set sw=4 ts=8: */
/* Reference version of egl.h for EGL 1.4.
* $Revision: 9356 $ on $Date: 2009-10-21 02:52:25 -0700 (Wed, 21 Oct 2009) $
*/
/*
** Copyright (c) 2007-2009 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
#ifndef __egl_h_
#define __egl_h_
/* All platform-dependent types and macro boilerplate (such as EGLAPI
* and EGLAPIENTRY) should go in eglplatform.h.
*/
#include <EGL/eglplatform.h>
#ifdef __cplusplus
extern "C" {
#endif
/* EGL Types */
/* EGLint is defined in eglplatform.h */
typedef unsigned int EGLBoolean;
typedef unsigned int EGLenum;
typedef void *EGLConfig;
typedef void *EGLContext;
typedef void *EGLDisplay;
typedef void *EGLSurface;
typedef void *EGLClientBuffer;
/* EGL Versioning */
#define EGL_VERSION_1_0 1
#define EGL_VERSION_1_1 1
#define EGL_VERSION_1_2 1
#define EGL_VERSION_1_3 1
#define EGL_VERSION_1_4 1
/* EGL Enumerants. Bitmasks and other exceptional cases aside, most
* enums are assigned unique values starting at 0x3000.
*/
/* EGL aliases */
#define EGL_FALSE 0
#define EGL_TRUE 1
/* Out-of-band handle values */
#define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0)
#define EGL_NO_CONTEXT ((EGLContext)0)
#define EGL_NO_DISPLAY ((EGLDisplay)0)
#define EGL_NO_SURFACE ((EGLSurface)0)
/* Out-of-band attribute value */
#define EGL_DONT_CARE ((EGLint)-1)
/* Errors / GetError return values */
#define EGL_SUCCESS 0x3000
#define EGL_NOT_INITIALIZED 0x3001
#define EGL_BAD_ACCESS 0x3002
#define EGL_BAD_ALLOC 0x3003
#define EGL_BAD_ATTRIBUTE 0x3004
#define EGL_BAD_CONFIG 0x3005
#define EGL_BAD_CONTEXT 0x3006
#define EGL_BAD_CURRENT_SURFACE 0x3007
#define EGL_BAD_DISPLAY 0x3008
#define EGL_BAD_MATCH 0x3009
#define EGL_BAD_NATIVE_PIXMAP 0x300A
#define EGL_BAD_NATIVE_WINDOW 0x300B
#define EGL_BAD_PARAMETER 0x300C
#define EGL_BAD_SURFACE 0x300D
#define EGL_CONTEXT_LOST 0x300E /* EGL 1.1 - IMG_power_management */
/* Reserved 0x300F-0x301F for additional errors */
/* Config attributes */
#define EGL_BUFFER_SIZE 0x3020
#define EGL_ALPHA_SIZE 0x3021
#define EGL_BLUE_SIZE 0x3022
#define EGL_GREEN_SIZE 0x3023
#define EGL_RED_SIZE 0x3024
#define EGL_DEPTH_SIZE 0x3025
#define EGL_STENCIL_SIZE 0x3026
#define EGL_CONFIG_CAVEAT 0x3027
#define EGL_CONFIG_ID 0x3028
#define EGL_LEVEL 0x3029
#define EGL_MAX_PBUFFER_HEIGHT 0x302A
#define EGL_MAX_PBUFFER_PIXELS 0x302B
#define EGL_MAX_PBUFFER_WIDTH 0x302C
#define EGL_NATIVE_RENDERABLE 0x302D
#define EGL_NATIVE_VISUAL_ID 0x302E
#define EGL_NATIVE_VISUAL_TYPE 0x302F
#define EGL_SAMPLES 0x3031
#define EGL_SAMPLE_BUFFERS 0x3032
#define EGL_SURFACE_TYPE 0x3033
#define EGL_TRANSPARENT_TYPE 0x3034
#define EGL_TRANSPARENT_BLUE_VALUE 0x3035
#define EGL_TRANSPARENT_GREEN_VALUE 0x3036
#define EGL_TRANSPARENT_RED_VALUE 0x3037
#define EGL_NONE 0x3038 /* Attrib list terminator */
#define EGL_BIND_TO_TEXTURE_RGB 0x3039
#define EGL_BIND_TO_TEXTURE_RGBA 0x303A
#define EGL_MIN_SWAP_INTERVAL 0x303B
#define EGL_MAX_SWAP_INTERVAL 0x303C
#define EGL_LUMINANCE_SIZE 0x303D
#define EGL_ALPHA_MASK_SIZE 0x303E
#define EGL_COLOR_BUFFER_TYPE 0x303F
#define EGL_RENDERABLE_TYPE 0x3040
#define EGL_MATCH_NATIVE_PIXMAP 0x3041 /* Pseudo-attribute (not queryable) */
#define EGL_CONFORMANT 0x3042
/* Reserved 0x3041-0x304F for additional config attributes */
/* Config attribute values */
#define EGL_SLOW_CONFIG 0x3050 /* EGL_CONFIG_CAVEAT value */
#define EGL_NON_CONFORMANT_CONFIG 0x3051 /* EGL_CONFIG_CAVEAT value */
#define EGL_TRANSPARENT_RGB 0x3052 /* EGL_TRANSPARENT_TYPE value */
#define EGL_RGB_BUFFER 0x308E /* EGL_COLOR_BUFFER_TYPE value */
#define EGL_LUMINANCE_BUFFER 0x308F /* EGL_COLOR_BUFFER_TYPE value */
/* More config attribute values, for EGL_TEXTURE_FORMAT */
#define EGL_NO_TEXTURE 0x305C
#define EGL_TEXTURE_RGB 0x305D
#define EGL_TEXTURE_RGBA 0x305E
#define EGL_TEXTURE_2D 0x305F
/* Config attribute mask bits */
#define EGL_PBUFFER_BIT 0x0001 /* EGL_SURFACE_TYPE mask bits */
#define EGL_PIXMAP_BIT 0x0002 /* EGL_SURFACE_TYPE mask bits */
#define EGL_WINDOW_BIT 0x0004 /* EGL_SURFACE_TYPE mask bits */
#define EGL_VG_COLORSPACE_LINEAR_BIT 0x0020 /* EGL_SURFACE_TYPE mask bits */
#define EGL_VG_ALPHA_FORMAT_PRE_BIT 0x0040 /* EGL_SURFACE_TYPE mask bits */
#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200 /* EGL_SURFACE_TYPE mask bits */
#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400 /* EGL_SURFACE_TYPE mask bits */
#define EGL_OPENGL_ES_BIT 0x0001 /* EGL_RENDERABLE_TYPE mask bits */
#define EGL_OPENVG_BIT 0x0002 /* EGL_RENDERABLE_TYPE mask bits */
#define EGL_OPENGL_ES2_BIT 0x0004 /* EGL_RENDERABLE_TYPE mask bits */
#define EGL_OPENGL_BIT 0x0008 /* EGL_RENDERABLE_TYPE mask bits */
/* QueryString targets */
#define EGL_VENDOR 0x3053
#define EGL_VERSION 0x3054
#define EGL_EXTENSIONS 0x3055
#define EGL_CLIENT_APIS 0x308D
/* QuerySurface / SurfaceAttrib / CreatePbufferSurface targets */
#define EGL_HEIGHT 0x3056
#define EGL_WIDTH 0x3057
#define EGL_LARGEST_PBUFFER 0x3058
#define EGL_TEXTURE_FORMAT 0x3080
#define EGL_TEXTURE_TARGET 0x3081
#define EGL_MIPMAP_TEXTURE 0x3082
#define EGL_MIPMAP_LEVEL 0x3083
#define EGL_RENDER_BUFFER 0x3086
#define EGL_VG_COLORSPACE 0x3087
#define EGL_VG_ALPHA_FORMAT 0x3088
#define EGL_HORIZONTAL_RESOLUTION 0x3090
#define EGL_VERTICAL_RESOLUTION 0x3091
#define EGL_PIXEL_ASPECT_RATIO 0x3092
#define EGL_SWAP_BEHAVIOR 0x3093
#define EGL_MULTISAMPLE_RESOLVE 0x3099
/* EGL_RENDER_BUFFER values / BindTexImage / ReleaseTexImage buffer targets */
#define EGL_BACK_BUFFER 0x3084
#define EGL_SINGLE_BUFFER 0x3085
/* OpenVG color spaces */
#define EGL_VG_COLORSPACE_sRGB 0x3089 /* EGL_VG_COLORSPACE value */
#define EGL_VG_COLORSPACE_LINEAR 0x308A /* EGL_VG_COLORSPACE value */
/* OpenVG alpha formats */
#define EGL_VG_ALPHA_FORMAT_NONPRE 0x308B /* EGL_ALPHA_FORMAT value */
#define EGL_VG_ALPHA_FORMAT_PRE 0x308C /* EGL_ALPHA_FORMAT value */
/* Constant scale factor by which fractional display resolutions &
* aspect ratio are scaled when queried as integer values.
*/
#define EGL_DISPLAY_SCALING 10000
/* Unknown display resolution/aspect ratio */
#define EGL_UNKNOWN ((EGLint)-1)
/* Back buffer swap behaviors */
#define EGL_BUFFER_PRESERVED 0x3094 /* EGL_SWAP_BEHAVIOR value */
#define EGL_BUFFER_DESTROYED 0x3095 /* EGL_SWAP_BEHAVIOR value */
/* CreatePbufferFromClientBuffer buffer types */
#define EGL_OPENVG_IMAGE 0x3096
/* QueryContext targets */
#define EGL_CONTEXT_CLIENT_TYPE 0x3097
/* CreateContext attributes */
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
/* Multisample resolution behaviors */
#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A /* EGL_MULTISAMPLE_RESOLVE value */
#define EGL_MULTISAMPLE_RESOLVE_BOX 0x309B /* EGL_MULTISAMPLE_RESOLVE value */
/* BindAPI/QueryAPI targets */
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_OPENVG_API 0x30A1
#define EGL_OPENGL_API 0x30A2
/* GetCurrentSurface targets */
#define EGL_DRAW 0x3059
#define EGL_READ 0x305A
/* WaitNative engines */
#define EGL_CORE_NATIVE_ENGINE 0x305B
/* EGL 1.2 tokens renamed for consistency in EGL 1.3 */
#define EGL_COLORSPACE EGL_VG_COLORSPACE
#define EGL_ALPHA_FORMAT EGL_VG_ALPHA_FORMAT
#define EGL_COLORSPACE_sRGB EGL_VG_COLORSPACE_sRGB
#define EGL_COLORSPACE_LINEAR EGL_VG_COLORSPACE_LINEAR
#define EGL_ALPHA_FORMAT_NONPRE EGL_VG_ALPHA_FORMAT_NONPRE
#define EGL_ALPHA_FORMAT_PRE EGL_VG_ALPHA_FORMAT_PRE
/* EGL extensions must request enum blocks from the Khronos
* API Registrar, who maintains the enumerant registry. Submit
* a bug in Khronos Bugzilla against task "Registry".
*/
/* EGL Functions */
EGLAPI EGLint EGLAPIENTRY eglGetError(void);
EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id);
EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor);
EGLAPI EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy);
EGLAPI const char * EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs,
EGLint config_size, EGLint *num_config);
EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list,
EGLConfig *configs, EGLint config_size,
EGLint *num_config);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
EGLint attribute, EGLint *value);
EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config,
EGLNativeWindowType win,
const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config,
const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config,
EGLNativePixmapType pixmap,
const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface,
EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api);
EGLAPI EGLenum EGLAPIENTRY eglQueryAPI(void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient(void);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread(void);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(
EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
EGLConfig config, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface,
EGLint attribute, EGLint value);
EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval);
EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config,
EGLContext share_context,
const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx);
EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw,
EGLSurface read, EGLContext ctx);
EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void);
EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw);
EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx,
EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL(void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface,
EGLNativePixmapType target);
/* This is a generic function pointer type, whose name indicates it must
* be cast to the proper type *and calling convention* before use.
*/
typedef void (*__eglMustCastToProperFunctionPointerType)(void);
/* Now, define eglGetProcAddress using the generic function ptr. type */
EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY
eglGetProcAddress(const char *procname);
#ifdef __cplusplus
}
#endif
#endif /* __egl_h_ */
| 010smithzhang-ddd | include/EGL/egl.h | C | bsd | 12,353 |
#ifndef __eglext_h_
#define __eglext_h_
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright (c) 2007-2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
#include <EGL/eglplatform.h>
/*************************************************************/
/* Header file version number */
/* Current version at http://www.khronos.org/registry/egl/ */
/* $Revision: 16473 $ on $Date: 2012-01-04 02:20:48 -0800 (Wed, 04 Jan 2012) $ */
#define EGL_EGLEXT_VERSION 11
#ifndef EGL_KHR_config_attribs
#define EGL_KHR_config_attribs 1
#define EGL_CONFORMANT_KHR 0x3042 /* EGLConfig attribute */
#define EGL_VG_COLORSPACE_LINEAR_BIT_KHR 0x0020 /* EGL_SURFACE_TYPE bitfield */
#define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR 0x0040 /* EGL_SURFACE_TYPE bitfield */
#endif
#ifndef EGL_KHR_lock_surface
#define EGL_KHR_lock_surface 1
#define EGL_READ_SURFACE_BIT_KHR 0x0001 /* EGL_LOCK_USAGE_HINT_KHR bitfield */
#define EGL_WRITE_SURFACE_BIT_KHR 0x0002 /* EGL_LOCK_USAGE_HINT_KHR bitfield */
#define EGL_LOCK_SURFACE_BIT_KHR 0x0080 /* EGL_SURFACE_TYPE bitfield */
#define EGL_OPTIMAL_FORMAT_BIT_KHR 0x0100 /* EGL_SURFACE_TYPE bitfield */
#define EGL_MATCH_FORMAT_KHR 0x3043 /* EGLConfig attribute */
#define EGL_FORMAT_RGB_565_EXACT_KHR 0x30C0 /* EGL_MATCH_FORMAT_KHR value */
#define EGL_FORMAT_RGB_565_KHR 0x30C1 /* EGL_MATCH_FORMAT_KHR value */
#define EGL_FORMAT_RGBA_8888_EXACT_KHR 0x30C2 /* EGL_MATCH_FORMAT_KHR value */
#define EGL_FORMAT_RGBA_8888_KHR 0x30C3 /* EGL_MATCH_FORMAT_KHR value */
#define EGL_MAP_PRESERVE_PIXELS_KHR 0x30C4 /* eglLockSurfaceKHR attribute */
#define EGL_LOCK_USAGE_HINT_KHR 0x30C5 /* eglLockSurfaceKHR attribute */
#define EGL_BITMAP_POINTER_KHR 0x30C6 /* eglQuerySurface attribute */
#define EGL_BITMAP_PITCH_KHR 0x30C7 /* eglQuerySurface attribute */
#define EGL_BITMAP_ORIGIN_KHR 0x30C8 /* eglQuerySurface attribute */
#define EGL_BITMAP_PIXEL_RED_OFFSET_KHR 0x30C9 /* eglQuerySurface attribute */
#define EGL_BITMAP_PIXEL_GREEN_OFFSET_KHR 0x30CA /* eglQuerySurface attribute */
#define EGL_BITMAP_PIXEL_BLUE_OFFSET_KHR 0x30CB /* eglQuerySurface attribute */
#define EGL_BITMAP_PIXEL_ALPHA_OFFSET_KHR 0x30CC /* eglQuerySurface attribute */
#define EGL_BITMAP_PIXEL_LUMINANCE_OFFSET_KHR 0x30CD /* eglQuerySurface attribute */
#define EGL_LOWER_LEFT_KHR 0x30CE /* EGL_BITMAP_ORIGIN_KHR value */
#define EGL_UPPER_LEFT_KHR 0x30CF /* EGL_BITMAP_ORIGIN_KHR value */
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay display, EGLSurface surface);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLBoolean (EGLAPIENTRYP PFNEGLLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface);
#endif
#ifndef EGL_KHR_image
#define EGL_KHR_image 1
#define EGL_NATIVE_PIXMAP_KHR 0x30B0 /* eglCreateImageKHR target */
typedef void *EGLImageKHR;
#define EGL_NO_IMAGE_KHR ((EGLImageKHR)0)
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#endif
#ifndef EGL_KHR_vg_parent_image
#define EGL_KHR_vg_parent_image 1
#define EGL_VG_PARENT_IMAGE_KHR 0x30BA /* eglCreateImageKHR target */
#endif
#ifndef EGL_KHR_gl_texture_2D_image
#define EGL_KHR_gl_texture_2D_image 1
#define EGL_GL_TEXTURE_2D_KHR 0x30B1 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_LEVEL_KHR 0x30BC /* eglCreateImageKHR attribute */
#endif
#ifndef EGL_KHR_gl_texture_cubemap_image
#define EGL_KHR_gl_texture_cubemap_image 1
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR 0x30B3 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR 0x30B4 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR 0x30B5 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR 0x30B6 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR 0x30B7 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR 0x30B8 /* eglCreateImageKHR target */
#endif
#ifndef EGL_KHR_gl_texture_3D_image
#define EGL_KHR_gl_texture_3D_image 1
#define EGL_GL_TEXTURE_3D_KHR 0x30B2 /* eglCreateImageKHR target */
#define EGL_GL_TEXTURE_ZOFFSET_KHR 0x30BD /* eglCreateImageKHR attribute */
#endif
#ifndef EGL_KHR_gl_renderbuffer_image
#define EGL_KHR_gl_renderbuffer_image 1
#define EGL_GL_RENDERBUFFER_KHR 0x30B9 /* eglCreateImageKHR target */
#endif
#if KHRONOS_SUPPORT_INT64 /* EGLTimeKHR requires 64-bit uint support */
#ifndef EGL_KHR_reusable_sync
#define EGL_KHR_reusable_sync 1
typedef void* EGLSyncKHR;
typedef khronos_utime_nanoseconds_t EGLTimeKHR;
#define EGL_SYNC_STATUS_KHR 0x30F1
#define EGL_SIGNALED_KHR 0x30F2
#define EGL_UNSIGNALED_KHR 0x30F3
#define EGL_TIMEOUT_EXPIRED_KHR 0x30F5
#define EGL_CONDITION_SATISFIED_KHR 0x30F6
#define EGL_SYNC_TYPE_KHR 0x30F7
#define EGL_SYNC_REUSABLE_KHR 0x30FA
#define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR 0x0001 /* eglClientWaitSyncKHR <flags> bitfield */
#define EGL_FOREVER_KHR 0xFFFFFFFFFFFFFFFFull
#define EGL_NO_SYNC_KHR ((EGLSyncKHR)0)
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNCKHRPROC) (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync);
typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
#endif
#endif
#ifndef EGL_KHR_image_base
#define EGL_KHR_image_base 1
/* Most interfaces defined by EGL_KHR_image_pixmap above */
#define EGL_IMAGE_PRESERVED_KHR 0x30D2 /* eglCreateImageKHR attribute */
#endif
#ifndef EGL_KHR_image_pixmap
#define EGL_KHR_image_pixmap 1
/* Interfaces defined by EGL_KHR_image above */
#endif
#ifndef EGL_IMG_context_priority
#define EGL_IMG_context_priority 1
#define EGL_CONTEXT_PRIORITY_LEVEL_IMG 0x3100
#define EGL_CONTEXT_PRIORITY_HIGH_IMG 0x3101
#define EGL_CONTEXT_PRIORITY_MEDIUM_IMG 0x3102
#define EGL_CONTEXT_PRIORITY_LOW_IMG 0x3103
#endif
#ifndef EGL_KHR_lock_surface2
#define EGL_KHR_lock_surface2 1
#define EGL_BITMAP_PIXEL_SIZE_KHR 0x3110
#endif
#ifndef EGL_NV_coverage_sample
#define EGL_NV_coverage_sample 1
#define EGL_COVERAGE_BUFFERS_NV 0x30E0
#define EGL_COVERAGE_SAMPLES_NV 0x30E1
#endif
#ifndef EGL_NV_depth_nonlinear
#define EGL_NV_depth_nonlinear 1
#define EGL_DEPTH_ENCODING_NV 0x30E2
#define EGL_DEPTH_ENCODING_NONE_NV 0
#define EGL_DEPTH_ENCODING_NONLINEAR_NV 0x30E3
#endif
#if KHRONOS_SUPPORT_INT64 /* EGLTimeNV requires 64-bit uint support */
#ifndef EGL_NV_sync
#define EGL_NV_sync 1
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_NV 0x30E6
#define EGL_SYNC_STATUS_NV 0x30E7
#define EGL_SIGNALED_NV 0x30E8
#define EGL_UNSIGNALED_NV 0x30E9
#define EGL_SYNC_FLUSH_COMMANDS_BIT_NV 0x0001
#define EGL_FOREVER_NV 0xFFFFFFFFFFFFFFFFull
#define EGL_ALREADY_SIGNALED_NV 0x30EA
#define EGL_TIMEOUT_EXPIRED_NV 0x30EB
#define EGL_CONDITION_SATISFIED_NV 0x30EC
#define EGL_SYNC_TYPE_NV 0x30ED
#define EGL_SYNC_CONDITION_NV 0x30EE
#define EGL_SYNC_FENCE_NV 0x30EF
#define EGL_NO_SYNC_NV ((EGLSyncNV)0)
typedef void* EGLSyncNV;
typedef khronos_utime_nanoseconds_t EGLTimeNV;
#ifdef EGL_EGLEXT_PROTOTYPES
EGLSyncNV eglCreateFenceSyncNV (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
EGLBoolean eglDestroySyncNV (EGLSyncNV sync);
EGLBoolean eglFenceNV (EGLSyncNV sync);
EGLint eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
EGLBoolean eglSignalSyncNV (EGLSyncNV sync, EGLenum mode);
EGLBoolean eglGetSyncAttribNV (EGLSyncNV sync, EGLint attribute, EGLint *value);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLSyncNV (EGLAPIENTRYP PFNEGLCREATEFENCESYNCNVPROC) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCNVPROC) (EGLSyncNV sync);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync);
typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCNVPROC) (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCNVPROC) (EGLSyncNV sync, EGLenum mode);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBNVPROC) (EGLSyncNV sync, EGLint attribute, EGLint *value);
#endif
#endif
#if KHRONOS_SUPPORT_INT64 /* Dependent on EGL_KHR_reusable_sync which requires 64-bit uint support */
#ifndef EGL_KHR_fence_sync
#define EGL_KHR_fence_sync 1
/* Reuses most tokens and entry points from EGL_KHR_reusable_sync */
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR 0x30F0
#define EGL_SYNC_CONDITION_KHR 0x30F8
#define EGL_SYNC_FENCE_KHR 0x30F9
#endif
#endif
#ifndef EGL_HI_clientpixmap
#define EGL_HI_clientpixmap 1
/* Surface Attribute */
#define EGL_CLIENT_PIXMAP_POINTER_HI 0x8F74
/*
* Structure representing a client pixmap
* (pixmap's data is in client-space memory).
*/
struct EGLClientPixmapHI
{
void* pData;
EGLint iWidth;
EGLint iHeight;
EGLint iStride;
};
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI(EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEHIPROC) (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap);
#endif /* EGL_HI_clientpixmap */
#ifndef EGL_HI_colorformats
#define EGL_HI_colorformats 1
/* Config Attribute */
#define EGL_COLOR_FORMAT_HI 0x8F70
/* Color Formats */
#define EGL_COLOR_RGB_HI 0x8F71
#define EGL_COLOR_RGBA_HI 0x8F72
#define EGL_COLOR_ARGB_HI 0x8F73
#endif /* EGL_HI_colorformats */
#ifndef EGL_MESA_drm_image
#define EGL_MESA_drm_image 1
#define EGL_DRM_BUFFER_FORMAT_MESA 0x31D0 /* CreateDRMImageMESA attribute */
#define EGL_DRM_BUFFER_USE_MESA 0x31D1 /* CreateDRMImageMESA attribute */
#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA 0x31D2 /* EGL_IMAGE_FORMAT_MESA attribute value */
#define EGL_DRM_BUFFER_MESA 0x31D3 /* eglCreateImageKHR target */
#define EGL_DRM_BUFFER_STRIDE_MESA 0x31D4
#define EGL_DRM_BUFFER_USE_SCANOUT_MESA 0x00000001 /* EGL_DRM_BUFFER_USE_MESA bits */
#define EGL_DRM_BUFFER_USE_SHARE_MESA 0x00000002 /* EGL_DRM_BUFFER_USE_MESA bits */
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA (EGLDisplay dpy, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
#endif
#ifndef EGL_NV_post_sub_buffer
#define EGL_NV_post_sub_buffer 1
#define EGL_POST_SUB_BUFFER_SUPPORTED_NV 0x30BE
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLBoolean (EGLAPIENTRYP PFNEGLPOSTSUBBUFFERNVPROC) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
#endif
#ifndef EGL_ANGLE_query_surface_pointer
#define EGL_ANGLE_query_surface_pointer 1
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLBoolean eglQuerySurfacePointerANGLE(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
#endif
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPOINTERANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
#endif
#ifndef EGL_ANGLE_software_display
#define EGL_ANGLE_software_display 1
#define EGL_SOFTWARE_DISPLAY_ANGLE ((EGLNativeDisplayType)-1)
#endif
#ifndef EGL_ANGLE_direct3d_display
#define EGL_ANGLE_direct3d_display 1
#define EGL_D3D11_ELSE_D3D9_DISPLAY_ANGLE ((EGLNativeDisplayType)-2)
#define EGL_D3D11_ONLY_DISPLAY_ANGLE ((EGLNativeDisplayType)-3)
#endif
#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle
#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1
#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE 0x3200
#endif
#ifndef EGL_NV_coverage_sample_resolve
#define EGL_NV_coverage_sample_resolve 1
#define EGL_COVERAGE_SAMPLE_RESOLVE_NV 0x3131
#define EGL_COVERAGE_SAMPLE_RESOLVE_DEFAULT_NV 0x3132
#define EGL_COVERAGE_SAMPLE_RESOLVE_NONE_NV 0x3133
#endif
#if KHRONOS_SUPPORT_INT64 /* EGLTimeKHR requires 64-bit uint support */
#ifndef EGL_NV_system_time
#define EGL_NV_system_time 1
typedef khronos_utime_nanoseconds_t EGLuint64NV;
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeFrequencyNV(void);
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV(void);
#endif /* EGL_EGLEXT_PROTOTYPES */
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) (void);
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC) (void);
#endif
#endif
#ifndef EGL_EXT_create_context_robustness
#define EGL_EXT_create_context_robustness 1
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT 0x30BF
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT 0x3138
#define EGL_NO_RESET_NOTIFICATION_EXT 0x31BE
#define EGL_LOSE_CONTEXT_ON_RESET_EXT 0x31BF
#endif
#ifdef __cplusplus
}
#endif
#endif
| 010smithzhang-ddd | include/EGL/eglext.h | C | bsd | 15,715 |
#ifndef __eglplatform_h_
#define __eglplatform_h_
/*
** Copyright (c) 2007-2009 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Platform-specific types and definitions for egl.h
* $Revision: 12306 $ on $Date: 2010-08-25 09:51:28 -0700 (Wed, 25 Aug 2010) $
*
* Adopters may modify khrplatform.h and this file to suit their platform.
* You are encouraged to submit all modifications to the Khronos group so that
* they can be included in future versions of this file. Please submit changes
* by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
* by filing a bug against product "EGL" component "Registry".
*/
#include <KHR/khrplatform.h>
/* Macros used in EGL function prototype declarations.
*
* EGL functions should be prototyped as:
*
* EGLAPI return-type EGLAPIENTRY eglFunction(arguments);
* typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments);
*
* KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h
*/
#ifndef EGLAPI
#define EGLAPI KHRONOS_APICALL
#endif
#ifndef EGLAPIENTRY
#define EGLAPIENTRY KHRONOS_APIENTRY
#endif
#define EGLAPIENTRYP EGLAPIENTRY*
/* The types NativeDisplayType, NativeWindowType, and NativePixmapType
* are aliases of window-system-dependent types, such as X Display * or
* Windows Device Context. They must be defined in platform-specific
* code below. The EGL-prefixed versions of Native*Type are the same
* types, renamed in EGL 1.3 so all types in the API start with "EGL".
*
* Khronos STRONGLY RECOMMENDS that you use the default definitions
* provided below, since these changes affect both binary and source
* portability of applications using EGL running on different EGL
* implementations.
*/
#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
typedef HDC EGLNativeDisplayType;
typedef HBITMAP EGLNativePixmapType;
typedef HWND EGLNativeWindowType;
#elif defined(__WINSCW__) || defined(__SYMBIAN32__) /* Symbian */
typedef int EGLNativeDisplayType;
typedef void *EGLNativeWindowType;
typedef void *EGLNativePixmapType;
#elif defined(WL_EGL_PLATFORM)
typedef struct wl_display *EGLNativeDisplayType;
typedef struct wl_egl_pixmap *EGLNativePixmapType;
typedef struct wl_egl_window *EGLNativeWindowType;
#elif defined(__unix__) && !defined(ANDROID)
/* X11 (tentative) */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
typedef Display *EGLNativeDisplayType;
typedef Pixmap EGLNativePixmapType;
typedef Window EGLNativeWindowType;
#elif defined(ANDROID)
struct egl_native_pixmap_t;
typedef struct ANativeWindow* EGLNativeWindowType;
typedef struct egl_native_pixmap_t* EGLNativePixmapType;
typedef void* EGLNativeDisplayType;
#else
#error "Platform not recognized"
#endif
/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
typedef EGLNativeDisplayType NativeDisplayType;
typedef EGLNativePixmapType NativePixmapType;
typedef EGLNativeWindowType NativeWindowType;
/* Define EGLint. This must be a signed integral type large enough to contain
* all legal attribute names and values passed into and out of EGL, whether
* their type is boolean, bitmask, enumerant (symbolic constant), integer,
* handle, or other. While in general a 32-bit integer will suffice, if
* handles are 64 bit types, then EGLint should be defined as a signed 64-bit
* integer type.
*/
typedef khronos_int32_t EGLint;
#endif /* __eglplatform_h */
| 010smithzhang-ddd | include/EGL/eglplatform.h | C | bsd | 4,656 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef _COMPILER_INTERFACE_INCLUDED_
#define _COMPILER_INTERFACE_INCLUDED_
#if defined(COMPONENT_BUILD)
#if defined(_WIN32) || defined(_WIN64)
#if defined(COMPILER_IMPLEMENTATION)
#define COMPILER_EXPORT __declspec(dllexport)
#else
#define COMPILER_EXPORT __declspec(dllimport)
#endif // defined(COMPILER_IMPLEMENTATION)
#else // defined(WIN32)
#define COMPILER_EXPORT __attribute__((visibility("default")))
#endif
#else // defined(COMPONENT_BUILD)
#define COMPILER_EXPORT
#endif
#include "KHR/khrplatform.h"
#include <stddef.h>
//
// This is the platform independent interface between an OGL driver
// and the shading language compiler.
//
#ifdef __cplusplus
extern "C" {
#endif
// Version number for shader translation API.
// It is incremented everytime the API changes.
#define ANGLE_SH_VERSION 110
//
// The names of the following enums have been derived by replacing GL prefix
// with SH. For example, SH_INFO_LOG_LENGTH is equivalent to GL_INFO_LOG_LENGTH.
// The enum values are also equal to the values of their GL counterpart. This
// is done to make it easier for applications to use the shader library.
//
typedef enum {
SH_FRAGMENT_SHADER = 0x8B30,
SH_VERTEX_SHADER = 0x8B31
} ShShaderType;
typedef enum {
SH_GLES2_SPEC = 0x8B40,
SH_WEBGL_SPEC = 0x8B41,
// The CSS Shaders spec is a subset of the WebGL spec.
//
// In both CSS vertex and fragment shaders, ANGLE:
// (1) Reserves the "css_" prefix.
// (2) Renames the main function to css_main.
// (3) Disables the gl_MaxDrawBuffers built-in.
//
// In CSS fragment shaders, ANGLE:
// (1) Disables the gl_FragColor built-in.
// (2) Disables the gl_FragData built-in.
// (3) Enables the css_MixColor built-in.
// (4) Enables the css_ColorMatrix built-in.
//
// After passing a CSS shader through ANGLE, the browser is expected to append
// a new main function to it.
// This new main function will call the css_main function.
// It may also perform additional operations like varying assignment, texture
// access, and gl_FragColor assignment in order to implement the CSS Shaders
// blend modes.
//
SH_CSS_SHADERS_SPEC = 0x8B42
} ShShaderSpec;
typedef enum {
SH_ESSL_OUTPUT = 0x8B45,
SH_GLSL_OUTPUT = 0x8B46,
SH_HLSL_OUTPUT = 0x8B47,
SH_HLSL9_OUTPUT = 0x8B47,
SH_HLSL11_OUTPUT = 0x8B48
} ShShaderOutput;
typedef enum {
SH_NONE = 0,
SH_INT = 0x1404,
SH_FLOAT = 0x1406,
SH_FLOAT_VEC2 = 0x8B50,
SH_FLOAT_VEC3 = 0x8B51,
SH_FLOAT_VEC4 = 0x8B52,
SH_INT_VEC2 = 0x8B53,
SH_INT_VEC3 = 0x8B54,
SH_INT_VEC4 = 0x8B55,
SH_BOOL = 0x8B56,
SH_BOOL_VEC2 = 0x8B57,
SH_BOOL_VEC3 = 0x8B58,
SH_BOOL_VEC4 = 0x8B59,
SH_FLOAT_MAT2 = 0x8B5A,
SH_FLOAT_MAT3 = 0x8B5B,
SH_FLOAT_MAT4 = 0x8B5C,
SH_SAMPLER_2D = 0x8B5E,
SH_SAMPLER_CUBE = 0x8B60,
SH_SAMPLER_2D_RECT_ARB = 0x8B63,
SH_SAMPLER_EXTERNAL_OES = 0x8D66
} ShDataType;
typedef enum {
SH_INFO_LOG_LENGTH = 0x8B84,
SH_OBJECT_CODE_LENGTH = 0x8B88, // GL_SHADER_SOURCE_LENGTH
SH_ACTIVE_UNIFORMS = 0x8B86,
SH_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
SH_ACTIVE_ATTRIBUTES = 0x8B89,
SH_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
SH_MAPPED_NAME_MAX_LENGTH = 0x6000,
SH_NAME_MAX_LENGTH = 0x6001,
SH_HASHED_NAME_MAX_LENGTH = 0x6002,
SH_HASHED_NAMES_COUNT = 0x6003,
SH_ACTIVE_UNIFORMS_ARRAY = 0x6004
} ShShaderInfo;
// Compile options.
typedef enum {
SH_VALIDATE = 0,
SH_VALIDATE_LOOP_INDEXING = 0x0001,
SH_INTERMEDIATE_TREE = 0x0002,
SH_OBJECT_CODE = 0x0004,
SH_ATTRIBUTES_UNIFORMS = 0x0008,
SH_LINE_DIRECTIVES = 0x0010,
SH_SOURCE_PATH = 0x0020,
SH_MAP_LONG_VARIABLE_NAMES = 0x0040,
SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX = 0x0080,
// This is needed only as a workaround for certain OpenGL driver bugs.
SH_EMULATE_BUILT_IN_FUNCTIONS = 0x0100,
// This is an experimental flag to enforce restrictions that aim to prevent
// timing attacks.
// It generates compilation errors for shaders that could expose sensitive
// texture information via the timing channel.
// To use this flag, you must compile the shader under the WebGL spec
// (using the SH_WEBGL_SPEC flag).
SH_TIMING_RESTRICTIONS = 0x0200,
// This flag prints the dependency graph that is used to enforce timing
// restrictions on fragment shaders.
// This flag only has an effect if all of the following are true:
// - The shader spec is SH_WEBGL_SPEC.
// - The compile options contain the SH_TIMING_RESTRICTIONS flag.
// - The shader type is SH_FRAGMENT_SHADER.
SH_DEPENDENCY_GRAPH = 0x0400,
// Enforce the GLSL 1.017 Appendix A section 7 packing restrictions.
SH_ENFORCE_PACKING_RESTRICTIONS = 0x0800,
// This flag ensures all indirect (expression-based) array indexing
// is clamped to the bounds of the array. This ensures, for example,
// that you cannot read off the end of a uniform, whether an array
// vec234, or mat234 type. The ShArrayIndexClampingStrategy enum,
// specified in the ShBuiltInResources when constructing the
// compiler, selects the strategy for the clamping implementation.
SH_CLAMP_INDIRECT_ARRAY_BOUNDS = 0x1000,
// This flag limits the complexity of an expression.
SH_LIMIT_EXPRESSION_COMPLEXITY = 0x2000,
// This flag limits the depth of the call stack.
SH_LIMIT_CALL_STACK_DEPTH = 0x4000,
} ShCompileOptions;
// Defines alternate strategies for implementing array index clamping.
typedef enum {
// Use the clamp intrinsic for array index clamping.
SH_CLAMP_WITH_CLAMP_INTRINSIC = 1,
// Use a user-defined function for array index clamping.
SH_CLAMP_WITH_USER_DEFINED_INT_CLAMP_FUNCTION
} ShArrayIndexClampingStrategy;
//
// Driver must call this first, once, before doing any other
// compiler operations.
// If the function succeeds, the return value is nonzero, else zero.
//
COMPILER_EXPORT int ShInitialize();
//
// Driver should call this at shutdown.
// If the function succeeds, the return value is nonzero, else zero.
//
COMPILER_EXPORT int ShFinalize();
// The 64 bits hash function. The first parameter is the input string; the
// second parameter is the string length.
typedef khronos_uint64_t (*ShHashFunction64)(const char*, size_t);
//
// Implementation dependent built-in resources (constants and extensions).
// The names for these resources has been obtained by stripping gl_/GL_.
//
typedef struct
{
// Constants.
int MaxVertexAttribs;
int MaxVertexUniformVectors;
int MaxVaryingVectors;
int MaxVertexTextureImageUnits;
int MaxCombinedTextureImageUnits;
int MaxTextureImageUnits;
int MaxFragmentUniformVectors;
int MaxDrawBuffers;
// Extensions.
// Set to 1 to enable the extension, else 0.
int OES_standard_derivatives;
int OES_EGL_image_external;
int ARB_texture_rectangle;
int EXT_draw_buffers;
int EXT_frag_depth;
// Set to 1 if highp precision is supported in the fragment language.
// Default is 0.
int FragmentPrecisionHigh;
// Name Hashing.
// Set a 64 bit hash function to enable user-defined name hashing.
// Default is NULL.
ShHashFunction64 HashFunction;
// Selects a strategy to use when implementing array index clamping.
// Default is SH_CLAMP_WITH_CLAMP_INTRINSIC.
ShArrayIndexClampingStrategy ArrayIndexClampingStrategy;
// The maximum complexity an expression can be.
int MaxExpressionComplexity;
// The maximum depth a call stack can be.
int MaxCallStackDepth;
} ShBuiltInResources;
//
// Initialize built-in resources with minimum expected values.
//
COMPILER_EXPORT void ShInitBuiltInResources(ShBuiltInResources* resources);
//
// ShHandle held by but opaque to the driver. It is allocated,
// managed, and de-allocated by the compiler. It's contents
// are defined by and used by the compiler.
//
// If handle creation fails, 0 will be returned.
//
typedef void* ShHandle;
//
// Driver calls these to create and destroy compiler objects.
//
// Returns the handle of constructed compiler, null if the requested compiler is
// not supported.
// Parameters:
// type: Specifies the type of shader - SH_FRAGMENT_SHADER or SH_VERTEX_SHADER.
// spec: Specifies the language spec the compiler must conform to -
// SH_GLES2_SPEC or SH_WEBGL_SPEC.
// output: Specifies the output code type - SH_ESSL_OUTPUT, SH_GLSL_OUTPUT,
// SH_HLSL9_OUTPUT or SH_HLSL11_OUTPUT.
// resources: Specifies the built-in resources.
COMPILER_EXPORT ShHandle ShConstructCompiler(
ShShaderType type,
ShShaderSpec spec,
ShShaderOutput output,
const ShBuiltInResources* resources);
COMPILER_EXPORT void ShDestruct(ShHandle handle);
//
// Compiles the given shader source.
// If the function succeeds, the return value is nonzero, else zero.
// Parameters:
// handle: Specifies the handle of compiler to be used.
// shaderStrings: Specifies an array of pointers to null-terminated strings
// containing the shader source code.
// numStrings: Specifies the number of elements in shaderStrings array.
// compileOptions: A mask containing the following parameters:
// SH_VALIDATE: Validates shader to ensure that it conforms to the spec
// specified during compiler construction.
// SH_VALIDATE_LOOP_INDEXING: Validates loop and indexing in the shader to
// ensure that they do not exceed the minimum
// functionality mandated in GLSL 1.0 spec,
// Appendix A, Section 4 and 5.
// There is no need to specify this parameter when
// compiling for WebGL - it is implied.
// SH_INTERMEDIATE_TREE: Writes intermediate tree to info log.
// Can be queried by calling ShGetInfoLog().
// SH_OBJECT_CODE: Translates intermediate tree to glsl or hlsl shader.
// Can be queried by calling ShGetObjectCode().
// SH_ATTRIBUTES_UNIFORMS: Extracts attributes and uniforms.
// Can be queried by calling ShGetActiveAttrib() and
// ShGetActiveUniform().
//
COMPILER_EXPORT int ShCompile(
const ShHandle handle,
const char* const shaderStrings[],
size_t numStrings,
int compileOptions
);
// Returns a parameter from a compiled shader.
// Parameters:
// handle: Specifies the compiler
// pname: Specifies the parameter to query.
// The following parameters are defined:
// SH_INFO_LOG_LENGTH: the number of characters in the information log
// including the null termination character.
// SH_OBJECT_CODE_LENGTH: the number of characters in the object code
// including the null termination character.
// SH_ACTIVE_ATTRIBUTES: the number of active attribute variables.
// SH_ACTIVE_ATTRIBUTE_MAX_LENGTH: the length of the longest active attribute
// variable name including the null
// termination character.
// SH_ACTIVE_UNIFORMS: the number of active uniform variables.
// SH_ACTIVE_UNIFORM_MAX_LENGTH: the length of the longest active uniform
// variable name including the null
// termination character.
// SH_MAPPED_NAME_MAX_LENGTH: the length of the mapped variable name including
// the null termination character.
// SH_NAME_MAX_LENGTH: the max length of a user-defined name including the
// null termination character.
// SH_HASHED_NAME_MAX_LENGTH: the max length of a hashed name including the
// null termination character.
// SH_HASHED_NAMES_COUNT: the number of hashed names from the latest compile.
//
// params: Requested parameter
COMPILER_EXPORT void ShGetInfo(const ShHandle handle,
ShShaderInfo pname,
size_t* params);
// Returns nul-terminated information log for a compiled shader.
// Parameters:
// handle: Specifies the compiler
// infoLog: Specifies an array of characters that is used to return
// the information log. It is assumed that infoLog has enough memory
// to accomodate the information log. The size of the buffer required
// to store the returned information log can be obtained by calling
// ShGetInfo with SH_INFO_LOG_LENGTH.
COMPILER_EXPORT void ShGetInfoLog(const ShHandle handle, char* infoLog);
// Returns null-terminated object code for a compiled shader.
// Parameters:
// handle: Specifies the compiler
// infoLog: Specifies an array of characters that is used to return
// the object code. It is assumed that infoLog has enough memory to
// accomodate the object code. The size of the buffer required to
// store the returned object code can be obtained by calling
// ShGetInfo with SH_OBJECT_CODE_LENGTH.
COMPILER_EXPORT void ShGetObjectCode(const ShHandle handle, char* objCode);
// Returns information about an active attribute variable.
// Parameters:
// handle: Specifies the compiler
// index: Specifies the index of the attribute variable to be queried.
// length: Returns the number of characters actually written in the string
// indicated by name (excluding the null terminator) if a value other
// than NULL is passed.
// size: Returns the size of the attribute variable.
// type: Returns the data type of the attribute variable.
// name: Returns a null terminated string containing the name of the
// attribute variable. It is assumed that name has enough memory to
// accomodate the attribute variable name. The size of the buffer
// required to store the attribute variable name can be obtained by
// calling ShGetInfo with SH_ACTIVE_ATTRIBUTE_MAX_LENGTH.
// mappedName: Returns a null terminated string containing the mapped name of
// the attribute variable, It is assumed that mappedName has enough
// memory (SH_MAPPED_NAME_MAX_LENGTH), or NULL if don't care
// about the mapped name. If the name is not mapped, then name and
// mappedName are the same.
COMPILER_EXPORT void ShGetActiveAttrib(const ShHandle handle,
int index,
size_t* length,
int* size,
ShDataType* type,
char* name,
char* mappedName);
// Returns information about an active uniform variable.
// Parameters:
// handle: Specifies the compiler
// index: Specifies the index of the uniform variable to be queried.
// length: Returns the number of characters actually written in the string
// indicated by name (excluding the null terminator) if a value
// other than NULL is passed.
// size: Returns the size of the uniform variable.
// type: Returns the data type of the uniform variable.
// name: Returns a null terminated string containing the name of the
// uniform variable. It is assumed that name has enough memory to
// accomodate the uniform variable name. The size of the buffer required
// to store the uniform variable name can be obtained by calling
// ShGetInfo with SH_ACTIVE_UNIFORMS_MAX_LENGTH.
// mappedName: Returns a null terminated string containing the mapped name of
// the uniform variable, It is assumed that mappedName has enough
// memory (SH_MAPPED_NAME_MAX_LENGTH), or NULL if don't care
// about the mapped name. If the name is not mapped, then name and
// mappedName are the same.
COMPILER_EXPORT void ShGetActiveUniform(const ShHandle handle,
int index,
size_t* length,
int* size,
ShDataType* type,
char* name,
char* mappedName);
// Returns information about a name hashing entry from the latest compile.
// Parameters:
// handle: Specifies the compiler
// index: Specifies the index of the name hashing entry to be queried.
// name: Returns a null terminated string containing the user defined name.
// It is assumed that name has enough memory to accomodate the name.
// The size of the buffer required to store the user defined name can
// be obtained by calling ShGetInfo with SH_NAME_MAX_LENGTH.
// hashedName: Returns a null terminated string containing the hashed name of
// the uniform variable, It is assumed that hashedName has enough
// memory to accomodate the name. The size of the buffer required
// to store the name can be obtained by calling ShGetInfo with
// SH_HASHED_NAME_MAX_LENGTH.
COMPILER_EXPORT void ShGetNameHashingEntry(const ShHandle handle,
int index,
char* name,
char* hashedName);
// Returns a parameter from a compiled shader.
// Parameters:
// handle: Specifies the compiler
// pname: Specifies the parameter to query.
// The following parameters are defined:
// SH_ACTIVE_UNIFORMS_ARRAY: an STL vector of active uniforms. Valid only for
// HLSL output.
// params: Requested parameter
COMPILER_EXPORT void ShGetInfoPointer(const ShHandle handle,
ShShaderInfo pname,
void** params);
#ifdef __cplusplus
}
#endif
#endif // _COMPILER_INTERFACE_INCLUDED_
| 010smithzhang-ddd | include/GLSLANG/ShaderLang.h | C | bsd | 18,135 |
#ifndef __gl2ext_h_
#define __gl2ext_h_
/* $Revision: 16482 $ on $Date:: 2012-01-04 13:44:55 -0500 #$ */
#ifdef __cplusplus
extern "C" {
#endif
/*
* This document is licensed under the SGI Free Software B License Version
* 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
*/
#ifndef GL_APIENTRYP
# define GL_APIENTRYP GL_APIENTRY*
#endif
/*------------------------------------------------------------------------*
* OES extension tokens
*------------------------------------------------------------------------*/
/* GL_OES_compressed_ETC1_RGB8_texture */
#ifndef GL_OES_compressed_ETC1_RGB8_texture
#define GL_ETC1_RGB8_OES 0x8D64
#endif
/* GL_OES_compressed_paletted_texture */
#ifndef GL_OES_compressed_paletted_texture
#define GL_PALETTE4_RGB8_OES 0x8B90
#define GL_PALETTE4_RGBA8_OES 0x8B91
#define GL_PALETTE4_R5_G6_B5_OES 0x8B92
#define GL_PALETTE4_RGBA4_OES 0x8B93
#define GL_PALETTE4_RGB5_A1_OES 0x8B94
#define GL_PALETTE8_RGB8_OES 0x8B95
#define GL_PALETTE8_RGBA8_OES 0x8B96
#define GL_PALETTE8_R5_G6_B5_OES 0x8B97
#define GL_PALETTE8_RGBA4_OES 0x8B98
#define GL_PALETTE8_RGB5_A1_OES 0x8B99
#endif
/* GL_OES_depth24 */
#ifndef GL_OES_depth24
#define GL_DEPTH_COMPONENT24_OES 0x81A6
#endif
/* GL_OES_depth32 */
#ifndef GL_OES_depth32
#define GL_DEPTH_COMPONENT32_OES 0x81A7
#endif
/* GL_OES_depth_texture */
/* No new tokens introduced by this extension. */
/* GL_OES_EGL_image */
#ifndef GL_OES_EGL_image
typedef void* GLeglImageOES;
#endif
/* GL_OES_EGL_image_external */
#ifndef GL_OES_EGL_image_external
/* GLeglImageOES defined in GL_OES_EGL_image already. */
#define GL_TEXTURE_EXTERNAL_OES 0x8D65
#define GL_SAMPLER_EXTERNAL_OES 0x8D66
#define GL_TEXTURE_BINDING_EXTERNAL_OES 0x8D67
#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES 0x8D68
#endif
/* GL_OES_element_index_uint */
#ifndef GL_OES_element_index_uint
#define GL_UNSIGNED_INT 0x1405
#endif
/* GL_OES_get_program_binary */
#ifndef GL_OES_get_program_binary
#define GL_PROGRAM_BINARY_LENGTH_OES 0x8741
#define GL_NUM_PROGRAM_BINARY_FORMATS_OES 0x87FE
#define GL_PROGRAM_BINARY_FORMATS_OES 0x87FF
#endif
/* GL_OES_mapbuffer */
#ifndef GL_OES_mapbuffer
#define GL_WRITE_ONLY_OES 0x88B9
#define GL_BUFFER_ACCESS_OES 0x88BB
#define GL_BUFFER_MAPPED_OES 0x88BC
#define GL_BUFFER_MAP_POINTER_OES 0x88BD
#endif
/* GL_OES_packed_depth_stencil */
#ifndef GL_OES_packed_depth_stencil
#define GL_DEPTH_STENCIL_OES 0x84F9
#define GL_UNSIGNED_INT_24_8_OES 0x84FA
#define GL_DEPTH24_STENCIL8_OES 0x88F0
#endif
/* GL_OES_rgb8_rgba8 */
#ifndef GL_OES_rgb8_rgba8
#define GL_RGB8_OES 0x8051
#define GL_RGBA8_OES 0x8058
#endif
/* GL_OES_standard_derivatives */
#ifndef GL_OES_standard_derivatives
#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES 0x8B8B
#endif
/* GL_OES_stencil1 */
#ifndef GL_OES_stencil1
#define GL_STENCIL_INDEX1_OES 0x8D46
#endif
/* GL_OES_stencil4 */
#ifndef GL_OES_stencil4
#define GL_STENCIL_INDEX4_OES 0x8D47
#endif
/* GL_OES_texture_3D */
#ifndef GL_OES_texture_3D
#define GL_TEXTURE_WRAP_R_OES 0x8072
#define GL_TEXTURE_3D_OES 0x806F
#define GL_TEXTURE_BINDING_3D_OES 0x806A
#define GL_MAX_3D_TEXTURE_SIZE_OES 0x8073
#define GL_SAMPLER_3D_OES 0x8B5F
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES 0x8CD4
#endif
/* GL_OES_texture_float */
/* No new tokens introduced by this extension. */
/* GL_OES_texture_float_linear */
/* No new tokens introduced by this extension. */
/* GL_OES_texture_half_float */
#ifndef GL_OES_texture_half_float
#define GL_HALF_FLOAT_OES 0x8D61
#endif
/* GL_OES_texture_half_float_linear */
/* No new tokens introduced by this extension. */
/* GL_OES_texture_npot */
/* No new tokens introduced by this extension. */
/* GL_OES_vertex_array_object */
#ifndef GL_OES_vertex_array_object
#define GL_VERTEX_ARRAY_BINDING_OES 0x85B5
#endif
/* GL_OES_vertex_half_float */
/* GL_HALF_FLOAT_OES defined in GL_OES_texture_half_float already. */
/* GL_OES_vertex_type_10_10_10_2 */
#ifndef GL_OES_vertex_type_10_10_10_2
#define GL_UNSIGNED_INT_10_10_10_2_OES 0x8DF6
#define GL_INT_10_10_10_2_OES 0x8DF7
#endif
/*------------------------------------------------------------------------*
* AMD extension tokens
*------------------------------------------------------------------------*/
/* GL_AMD_compressed_3DC_texture */
#ifndef GL_AMD_compressed_3DC_texture
#define GL_3DC_X_AMD 0x87F9
#define GL_3DC_XY_AMD 0x87FA
#endif
/* GL_AMD_compressed_ATC_texture */
#ifndef GL_AMD_compressed_ATC_texture
#define GL_ATC_RGB_AMD 0x8C92
#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
#endif
/* GL_AMD_performance_monitor */
#ifndef GL_AMD_performance_monitor
#define GL_COUNTER_TYPE_AMD 0x8BC0
#define GL_COUNTER_RANGE_AMD 0x8BC1
#define GL_UNSIGNED_INT64_AMD 0x8BC2
#define GL_PERCENTAGE_AMD 0x8BC3
#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4
#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5
#define GL_PERFMON_RESULT_AMD 0x8BC6
#endif
/* GL_AMD_program_binary_Z400 */
#ifndef GL_AMD_program_binary_Z400
#define GL_Z400_BINARY_AMD 0x8740
#endif
/*------------------------------------------------------------------------*
* ANGLE extension tokens
*------------------------------------------------------------------------*/
/* GL_ANGLE_framebuffer_blit */
#ifndef GL_ANGLE_framebuffer_blit
#define GL_READ_FRAMEBUFFER_ANGLE 0x8CA8
#define GL_DRAW_FRAMEBUFFER_ANGLE 0x8CA9
#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE 0x8CA6
#define GL_READ_FRAMEBUFFER_BINDING_ANGLE 0x8CAA
#endif
/* GL_ANGLE_framebuffer_multisample */
#ifndef GL_ANGLE_framebuffer_multisample
#define GL_RENDERBUFFER_SAMPLES_ANGLE 0x8CAB
#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE 0x8D56
#define GL_MAX_SAMPLES_ANGLE 0x8D57
#endif
/* GL_ANGLE_pack_reverse_row_order */
#ifndef GL_ANGLE_pack_reverse_row_order
#define GL_PACK_REVERSE_ROW_ORDER_ANGLE 0x93A4
#endif
/* GL_ANGLE_texture_compression_dxt3 */
#ifndef GL_ANGLE_texture_compression_dxt3
#define GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE 0x83F2
#endif
/* GL_ANGLE_texture_compression_dxt5 */
#ifndef GL_ANGLE_texture_compression_dxt5
#define GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE 0x83F3
#endif
/* GL_ANGLE_translated_shader_source */
#ifndef GL_ANGLE_translated_shader_source
#define GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE 0x93A0
#endif
/* GL_ANGLE_texture_usage */
#ifndef GL_ANGLE_texture_usage
#define GL_TEXTURE_USAGE_ANGLE 0x93A2
#define GL_FRAMEBUFFER_ATTACHMENT_ANGLE 0x93A3
#endif
/* GL_ANGLE_instanced_arrays */
#ifndef GL_ANGLE_instanced_arrays
#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE 0x88FE
#endif
/* GL_ANGLE_program_binary */
#ifndef GL_ANGLE_program_binary
#define GL_PROGRAM_BINARY_ANGLE 0x93A6
#endif
/*------------------------------------------------------------------------*
* APPLE extension tokens
*------------------------------------------------------------------------*/
/* GL_APPLE_rgb_422 */
#ifndef GL_APPLE_rgb_422
#define GL_RGB_422_APPLE 0x8A1F
#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA
#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB
#endif
/* GL_APPLE_framebuffer_multisample */
#ifndef GL_APPLE_framebuffer_multisample
#define GL_RENDERBUFFER_SAMPLES_APPLE 0x8CAB
#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE 0x8D56
#define GL_MAX_SAMPLES_APPLE 0x8D57
#define GL_READ_FRAMEBUFFER_APPLE 0x8CA8
#define GL_DRAW_FRAMEBUFFER_APPLE 0x8CA9
#define GL_DRAW_FRAMEBUFFER_BINDING_APPLE 0x8CA6
#define GL_READ_FRAMEBUFFER_BINDING_APPLE 0x8CAA
#endif
/* GL_APPLE_texture_format_BGRA8888 */
#ifndef GL_APPLE_texture_format_BGRA8888
#define GL_BGRA_EXT 0x80E1
#endif
/* GL_APPLE_texture_max_level */
#ifndef GL_APPLE_texture_max_level
#define GL_TEXTURE_MAX_LEVEL_APPLE 0x813D
#endif
/*------------------------------------------------------------------------*
* ARM extension tokens
*------------------------------------------------------------------------*/
/* GL_ARM_mali_shader_binary */
#ifndef GL_ARM_mali_shader_binary
#define GL_MALI_SHADER_BINARY_ARM 0x8F60
#endif
/* GL_ARM_rgba8 */
/* No new tokens introduced by this extension. */
/*------------------------------------------------------------------------*
* EXT extension tokens
*------------------------------------------------------------------------*/
/* GL_EXT_blend_minmax */
#ifndef GL_EXT_blend_minmax
#define GL_MIN_EXT 0x8007
#define GL_MAX_EXT 0x8008
#endif
/* GL_EXT_color_buffer_half_float */
#ifndef GL_EXT_color_buffer_half_float
#define GL_RGBA16F_EXT 0x881A
#define GL_RGB16F_EXT 0x881B
#define GL_RG16F_EXT 0x822F
#define GL_R16F_EXT 0x822D
#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT 0x8211
#define GL_UNSIGNED_NORMALIZED_EXT 0x8C17
#endif
/* GL_EXT_debug_label */
#ifndef GL_EXT_debug_label
#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F
#define GL_PROGRAM_OBJECT_EXT 0x8B40
#define GL_SHADER_OBJECT_EXT 0x8B48
#define GL_BUFFER_OBJECT_EXT 0x9151
#define GL_QUERY_OBJECT_EXT 0x9153
#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154
#endif
/* GL_EXT_debug_marker */
/* No new tokens introduced by this extension. */
/* GL_EXT_discard_framebuffer */
#ifndef GL_EXT_discard_framebuffer
#define GL_COLOR_EXT 0x1800
#define GL_DEPTH_EXT 0x1801
#define GL_STENCIL_EXT 0x1802
#endif
/* GL_EXT_multisampled_render_to_texture */
#ifndef GL_EXT_multisampled_render_to_texture
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT 0x8D6C
#define GL_RENDERBUFFER_SAMPLES_EXT 0x9133
#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x9134
#define GL_MAX_SAMPLES_EXT 0x9135
#endif
/* GL_EXT_multi_draw_arrays */
/* No new tokens introduced by this extension. */
/* GL_EXT_occlusion_query_boolean */
#ifndef GL_EXT_occlusion_query_boolean
#define GL_ANY_SAMPLES_PASSED_EXT 0x8C2F
#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT 0x8D6A
#define GL_CURRENT_QUERY_EXT 0x8865
#define GL_QUERY_RESULT_EXT 0x8866
#define GL_QUERY_RESULT_AVAILABLE_EXT 0x8867
#endif
/* GL_EXT_read_format_bgra */
#ifndef GL_EXT_read_format_bgra
#define GL_BGRA_EXT 0x80E1
#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT 0x8365
#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT 0x8366
#endif
/* GL_EXT_robustness */
#ifndef GL_EXT_robustness
/* reuse GL_NO_ERROR */
#define GL_GUILTY_CONTEXT_RESET_EXT 0x8253
#define GL_INNOCENT_CONTEXT_RESET_EXT 0x8254
#define GL_UNKNOWN_CONTEXT_RESET_EXT 0x8255
#define GL_CONTEXT_ROBUST_ACCESS_EXT 0x90F3
#define GL_RESET_NOTIFICATION_STRATEGY_EXT 0x8256
#define GL_LOSE_CONTEXT_ON_RESET_EXT 0x8252
#define GL_NO_RESET_NOTIFICATION_EXT 0x8261
#endif
/* GL_EXT_separate_shader_objects */
#ifndef GL_EXT_separate_shader_objects
#define GL_VERTEX_SHADER_BIT_EXT 0x00000001
#define GL_FRAGMENT_SHADER_BIT_EXT 0x00000002
#define GL_ALL_SHADER_BITS_EXT 0xFFFFFFFF
#define GL_PROGRAM_SEPARABLE_EXT 0x8258
#define GL_ACTIVE_PROGRAM_EXT 0x8259
#define GL_PROGRAM_PIPELINE_BINDING_EXT 0x825A
#endif
/* GL_EXT_shader_texture_lod */
/* No new tokens introduced by this extension. */
/* GL_EXT_shadow_samplers */
#ifndef GL_EXT_shadow_samplers
#define GL_TEXTURE_COMPARE_MODE_EXT 0x884C
#define GL_TEXTURE_COMPARE_FUNC_EXT 0x884D
#define GL_COMPARE_REF_TO_TEXTURE_EXT 0x884E
#endif
/* GL_EXT_sRGB */
#ifndef GL_EXT_sRGB
#define GL_SRGB_EXT 0x8C40
#define GL_SRGB_ALPHA_EXT 0x8C42
#define GL_SRGB8_ALPHA8_EXT 0x8C43
#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT 0x8210
#endif
/* GL_EXT_texture_compression_dxt1 */
#ifndef GL_EXT_texture_compression_dxt1
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#endif
/* GL_EXT_texture_filter_anisotropic */
#ifndef GL_EXT_texture_filter_anisotropic
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
#endif
/* GL_EXT_texture_format_BGRA8888 */
#ifndef GL_EXT_texture_format_BGRA8888
#define GL_BGRA_EXT 0x80E1
#endif
/* GL_EXT_texture_rg */
#ifndef GL_EXT_texture_rg
#define GL_RED_EXT 0x1903
#define GL_RG_EXT 0x8227
#define GL_R8_EXT 0x8229
#define GL_RG8_EXT 0x822B
#endif
/* GL_EXT_texture_storage */
#ifndef GL_EXT_texture_storage
#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT 0x912F
#define GL_ALPHA8_EXT 0x803C
#define GL_LUMINANCE8_EXT 0x8040
#define GL_LUMINANCE8_ALPHA8_EXT 0x8045
#define GL_RGBA32F_EXT 0x8814
#define GL_RGB32F_EXT 0x8815
#define GL_ALPHA32F_EXT 0x8816
#define GL_LUMINANCE32F_EXT 0x8818
#define GL_LUMINANCE_ALPHA32F_EXT 0x8819
/* reuse GL_RGBA16F_EXT */
#define GL_RGB16F_EXT 0x881B
#define GL_ALPHA16F_EXT 0x881C
#define GL_LUMINANCE16F_EXT 0x881E
#define GL_LUMINANCE_ALPHA16F_EXT 0x881F
#define GL_RGB10_A2_EXT 0x8059
#define GL_RGB10_EXT 0x8052
#define GL_BGRA8_EXT 0x93A1
#endif
/* GL_EXT_texture_type_2_10_10_10_REV */
#ifndef GL_EXT_texture_type_2_10_10_10_REV
#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT 0x8368
#endif
/* GL_EXT_unpack_subimage */
#ifndef GL_EXT_unpack_subimage
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_UNPACK_SKIP_ROWS 0x0CF3
#define GL_UNPACK_SKIP_PIXELS 0x0CF4
#endif
/*------------------------------------------------------------------------*
* DMP extension tokens
*------------------------------------------------------------------------*/
/* GL_DMP_shader_binary */
#ifndef GL_DMP_shader_binary
#define GL_SHADER_BINARY_DMP 0x9250
#endif
/*------------------------------------------------------------------------*
* IMG extension tokens
*------------------------------------------------------------------------*/
/* GL_IMG_program_binary */
#ifndef GL_IMG_program_binary
#define GL_SGX_PROGRAM_BINARY_IMG 0x9130
#endif
/* GL_IMG_read_format */
#ifndef GL_IMG_read_format
#define GL_BGRA_IMG 0x80E1
#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG 0x8365
#endif
/* GL_IMG_shader_binary */
#ifndef GL_IMG_shader_binary
#define GL_SGX_BINARY_IMG 0x8C0A
#endif
/* GL_IMG_texture_compression_pvrtc */
#ifndef GL_IMG_texture_compression_pvrtc
#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
#endif
/* GL_IMG_multisampled_render_to_texture */
#ifndef GL_IMG_multisampled_render_to_texture
#define GL_RENDERBUFFER_SAMPLES_IMG 0x9133
#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG 0x9134
#define GL_MAX_SAMPLES_IMG 0x9135
#define GL_TEXTURE_SAMPLES_IMG 0x9136
#endif
/*------------------------------------------------------------------------*
* NV extension tokens
*------------------------------------------------------------------------*/
/* GL_NV_coverage_sample */
#ifndef GL_NV_coverage_sample
#define GL_COVERAGE_COMPONENT_NV 0x8ED0
#define GL_COVERAGE_COMPONENT4_NV 0x8ED1
#define GL_COVERAGE_ATTACHMENT_NV 0x8ED2
#define GL_COVERAGE_BUFFERS_NV 0x8ED3
#define GL_COVERAGE_SAMPLES_NV 0x8ED4
#define GL_COVERAGE_ALL_FRAGMENTS_NV 0x8ED5
#define GL_COVERAGE_EDGE_FRAGMENTS_NV 0x8ED6
#define GL_COVERAGE_AUTOMATIC_NV 0x8ED7
#define GL_COVERAGE_BUFFER_BIT_NV 0x8000
#endif
/* GL_NV_depth_nonlinear */
#ifndef GL_NV_depth_nonlinear
#define GL_DEPTH_COMPONENT16_NONLINEAR_NV 0x8E2C
#endif
/* GL_NV_draw_buffers */
#ifndef GL_NV_draw_buffers
#define GL_MAX_DRAW_BUFFERS_NV 0x8824
#define GL_DRAW_BUFFER0_NV 0x8825
#define GL_DRAW_BUFFER1_NV 0x8826
#define GL_DRAW_BUFFER2_NV 0x8827
#define GL_DRAW_BUFFER3_NV 0x8828
#define GL_DRAW_BUFFER4_NV 0x8829
#define GL_DRAW_BUFFER5_NV 0x882A
#define GL_DRAW_BUFFER6_NV 0x882B
#define GL_DRAW_BUFFER7_NV 0x882C
#define GL_DRAW_BUFFER8_NV 0x882D
#define GL_DRAW_BUFFER9_NV 0x882E
#define GL_DRAW_BUFFER10_NV 0x882F
#define GL_DRAW_BUFFER11_NV 0x8830
#define GL_DRAW_BUFFER12_NV 0x8831
#define GL_DRAW_BUFFER13_NV 0x8832
#define GL_DRAW_BUFFER14_NV 0x8833
#define GL_DRAW_BUFFER15_NV 0x8834
#define GL_COLOR_ATTACHMENT0_NV 0x8CE0
#define GL_COLOR_ATTACHMENT1_NV 0x8CE1
#define GL_COLOR_ATTACHMENT2_NV 0x8CE2
#define GL_COLOR_ATTACHMENT3_NV 0x8CE3
#define GL_COLOR_ATTACHMENT4_NV 0x8CE4
#define GL_COLOR_ATTACHMENT5_NV 0x8CE5
#define GL_COLOR_ATTACHMENT6_NV 0x8CE6
#define GL_COLOR_ATTACHMENT7_NV 0x8CE7
#define GL_COLOR_ATTACHMENT8_NV 0x8CE8
#define GL_COLOR_ATTACHMENT9_NV 0x8CE9
#define GL_COLOR_ATTACHMENT10_NV 0x8CEA
#define GL_COLOR_ATTACHMENT11_NV 0x8CEB
#define GL_COLOR_ATTACHMENT12_NV 0x8CEC
#define GL_COLOR_ATTACHMENT13_NV 0x8CED
#define GL_COLOR_ATTACHMENT14_NV 0x8CEE
#define GL_COLOR_ATTACHMENT15_NV 0x8CEF
#endif
/* GL_EXT_draw_buffers */
#ifndef GL_EXT_draw_buffers
#define GL_MAX_DRAW_BUFFERS_EXT 0x8824
#define GL_DRAW_BUFFER0_EXT 0x8825
#define GL_DRAW_BUFFER1_EXT 0x8826
#define GL_DRAW_BUFFER2_EXT 0x8827
#define GL_DRAW_BUFFER3_EXT 0x8828
#define GL_DRAW_BUFFER4_EXT 0x8829
#define GL_DRAW_BUFFER5_EXT 0x882A
#define GL_DRAW_BUFFER6_EXT 0x882B
#define GL_DRAW_BUFFER7_EXT 0x882C
#define GL_DRAW_BUFFER8_EXT 0x882D
#define GL_DRAW_BUFFER9_EXT 0x882E
#define GL_DRAW_BUFFER10_EXT 0x882F
#define GL_DRAW_BUFFER11_EXT 0x8830
#define GL_DRAW_BUFFER12_EXT 0x8831
#define GL_DRAW_BUFFER13_EXT 0x8832
#define GL_DRAW_BUFFER14_EXT 0x8833
#define GL_DRAW_BUFFER15_EXT 0x8834
#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1
#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2
#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3
#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4
#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5
#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6
#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7
#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8
#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9
#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA
#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB
#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC
#define GL_COLOR_ATTACHMENT13_EXT 0x8CED
#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE
#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF
#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF
#endif
/* GL_NV_fbo_color_attachments */
#ifndef GL_NV_fbo_color_attachments
#define GL_MAX_COLOR_ATTACHMENTS_NV 0x8CDF
/* GL_COLOR_ATTACHMENT{0-15}_NV defined in GL_NV_draw_buffers already. */
#endif
/* GL_NV_fence */
#ifndef GL_NV_fence
#define GL_ALL_COMPLETED_NV 0x84F2
#define GL_FENCE_STATUS_NV 0x84F3
#define GL_FENCE_CONDITION_NV 0x84F4
#endif
/* GL_NV_read_buffer */
#ifndef GL_NV_read_buffer
#define GL_READ_BUFFER_NV 0x0C02
#endif
/* GL_NV_read_buffer_front */
/* No new tokens introduced by this extension. */
/* GL_NV_read_depth */
/* No new tokens introduced by this extension. */
/* GL_NV_read_depth_stencil */
/* No new tokens introduced by this extension. */
/* GL_NV_read_stencil */
/* No new tokens introduced by this extension. */
/* GL_NV_texture_compression_s3tc_update */
/* No new tokens introduced by this extension. */
/* GL_NV_texture_npot_2D_mipmap */
/* No new tokens introduced by this extension. */
/*------------------------------------------------------------------------*
* QCOM extension tokens
*------------------------------------------------------------------------*/
/* GL_QCOM_alpha_test */
#ifndef GL_QCOM_alpha_test
#define GL_ALPHA_TEST_QCOM 0x0BC0
#define GL_ALPHA_TEST_FUNC_QCOM 0x0BC1
#define GL_ALPHA_TEST_REF_QCOM 0x0BC2
#endif
/* GL_QCOM_driver_control */
/* No new tokens introduced by this extension. */
/* GL_QCOM_extended_get */
#ifndef GL_QCOM_extended_get
#define GL_TEXTURE_WIDTH_QCOM 0x8BD2
#define GL_TEXTURE_HEIGHT_QCOM 0x8BD3
#define GL_TEXTURE_DEPTH_QCOM 0x8BD4
#define GL_TEXTURE_INTERNAL_FORMAT_QCOM 0x8BD5
#define GL_TEXTURE_FORMAT_QCOM 0x8BD6
#define GL_TEXTURE_TYPE_QCOM 0x8BD7
#define GL_TEXTURE_IMAGE_VALID_QCOM 0x8BD8
#define GL_TEXTURE_NUM_LEVELS_QCOM 0x8BD9
#define GL_TEXTURE_TARGET_QCOM 0x8BDA
#define GL_TEXTURE_OBJECT_VALID_QCOM 0x8BDB
#define GL_STATE_RESTORE 0x8BDC
#endif
/* GL_QCOM_extended_get2 */
/* No new tokens introduced by this extension. */
/* GL_QCOM_perfmon_global_mode */
#ifndef GL_QCOM_perfmon_global_mode
#define GL_PERFMON_GLOBAL_MODE_QCOM 0x8FA0
#endif
/* GL_QCOM_writeonly_rendering */
#ifndef GL_QCOM_writeonly_rendering
#define GL_WRITEONLY_RENDERING_QCOM 0x8823
#endif
/* GL_QCOM_tiled_rendering */
#ifndef GL_QCOM_tiled_rendering
#define GL_COLOR_BUFFER_BIT0_QCOM 0x00000001
#define GL_COLOR_BUFFER_BIT1_QCOM 0x00000002
#define GL_COLOR_BUFFER_BIT2_QCOM 0x00000004
#define GL_COLOR_BUFFER_BIT3_QCOM 0x00000008
#define GL_COLOR_BUFFER_BIT4_QCOM 0x00000010
#define GL_COLOR_BUFFER_BIT5_QCOM 0x00000020
#define GL_COLOR_BUFFER_BIT6_QCOM 0x00000040
#define GL_COLOR_BUFFER_BIT7_QCOM 0x00000080
#define GL_DEPTH_BUFFER_BIT0_QCOM 0x00000100
#define GL_DEPTH_BUFFER_BIT1_QCOM 0x00000200
#define GL_DEPTH_BUFFER_BIT2_QCOM 0x00000400
#define GL_DEPTH_BUFFER_BIT3_QCOM 0x00000800
#define GL_DEPTH_BUFFER_BIT4_QCOM 0x00001000
#define GL_DEPTH_BUFFER_BIT5_QCOM 0x00002000
#define GL_DEPTH_BUFFER_BIT6_QCOM 0x00004000
#define GL_DEPTH_BUFFER_BIT7_QCOM 0x00008000
#define GL_STENCIL_BUFFER_BIT0_QCOM 0x00010000
#define GL_STENCIL_BUFFER_BIT1_QCOM 0x00020000
#define GL_STENCIL_BUFFER_BIT2_QCOM 0x00040000
#define GL_STENCIL_BUFFER_BIT3_QCOM 0x00080000
#define GL_STENCIL_BUFFER_BIT4_QCOM 0x00100000
#define GL_STENCIL_BUFFER_BIT5_QCOM 0x00200000
#define GL_STENCIL_BUFFER_BIT6_QCOM 0x00400000
#define GL_STENCIL_BUFFER_BIT7_QCOM 0x00800000
#define GL_MULTISAMPLE_BUFFER_BIT0_QCOM 0x01000000
#define GL_MULTISAMPLE_BUFFER_BIT1_QCOM 0x02000000
#define GL_MULTISAMPLE_BUFFER_BIT2_QCOM 0x04000000
#define GL_MULTISAMPLE_BUFFER_BIT3_QCOM 0x08000000
#define GL_MULTISAMPLE_BUFFER_BIT4_QCOM 0x10000000
#define GL_MULTISAMPLE_BUFFER_BIT5_QCOM 0x20000000
#define GL_MULTISAMPLE_BUFFER_BIT6_QCOM 0x40000000
#define GL_MULTISAMPLE_BUFFER_BIT7_QCOM 0x80000000
#endif
/*------------------------------------------------------------------------*
* VIV extension tokens
*------------------------------------------------------------------------*/
/* GL_VIV_shader_binary */
#ifndef GL_VIV_shader_binary
#define GL_SHADER_BINARY_VIV 0x8FC4
#endif
/*------------------------------------------------------------------------*
* End of extension tokens, start of corresponding extension functions
*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*
* OES extension functions
*------------------------------------------------------------------------*/
/* GL_OES_compressed_ETC1_RGB8_texture */
#ifndef GL_OES_compressed_ETC1_RGB8_texture
#define GL_OES_compressed_ETC1_RGB8_texture 1
#endif
/* GL_OES_compressed_paletted_texture */
#ifndef GL_OES_compressed_paletted_texture
#define GL_OES_compressed_paletted_texture 1
#endif
/* GL_OES_depth24 */
#ifndef GL_OES_depth24
#define GL_OES_depth24 1
#endif
/* GL_OES_depth32 */
#ifndef GL_OES_depth32
#define GL_OES_depth32 1
#endif
/* GL_OES_depth_texture */
#ifndef GL_OES_depth_texture
#define GL_OES_depth_texture 1
#endif
/* GL_OES_EGL_image */
#ifndef GL_OES_EGL_image
#define GL_OES_EGL_image 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
#endif
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
#endif
/* GL_OES_EGL_image_external */
#ifndef GL_OES_EGL_image_external
#define GL_OES_EGL_image_external 1
/* glEGLImageTargetTexture2DOES defined in GL_OES_EGL_image already. */
#endif
/* GL_OES_element_index_uint */
#ifndef GL_OES_element_index_uint
#define GL_OES_element_index_uint 1
#endif
/* GL_OES_fbo_render_mipmap */
#ifndef GL_OES_fbo_render_mipmap
#define GL_OES_fbo_render_mipmap 1
#endif
/* GL_OES_fragment_precision_high */
#ifndef GL_OES_fragment_precision_high
#define GL_OES_fragment_precision_high 1
#endif
/* GL_OES_get_program_binary */
#ifndef GL_OES_get_program_binary
#define GL_OES_get_program_binary 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary);
GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length);
#endif
typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary);
typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length);
#endif
/* GL_OES_mapbuffer */
#ifndef GL_OES_mapbuffer
#define GL_OES_mapbuffer 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void* GL_APIENTRY glMapBufferOES (GLenum target, GLenum access);
GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target);
GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, GLvoid** params);
#endif
typedef void* (GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access);
typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target);
typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, GLvoid** params);
#endif
/* GL_OES_packed_depth_stencil */
#ifndef GL_OES_packed_depth_stencil
#define GL_OES_packed_depth_stencil 1
#endif
/* GL_OES_rgb8_rgba8 */
#ifndef GL_OES_rgb8_rgba8
#define GL_OES_rgb8_rgba8 1
#endif
/* GL_OES_standard_derivatives */
#ifndef GL_OES_standard_derivatives
#define GL_OES_standard_derivatives 1
#endif
/* GL_OES_stencil1 */
#ifndef GL_OES_stencil1
#define GL_OES_stencil1 1
#endif
/* GL_OES_stencil4 */
#ifndef GL_OES_stencil4
#define GL_OES_stencil4 1
#endif
/* GL_OES_texture_3D */
#ifndef GL_OES_texture_3D
#define GL_OES_texture_3D 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
#endif
typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels);
typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data);
typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data);
typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOES) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
#endif
/* GL_OES_texture_float */
#ifndef GL_OES_texture_float
#define GL_OES_texture_float 1
#endif
/* GL_OES_texture_float_linear */
#ifndef GL_OES_texture_float_linear
#define GL_OES_texture_float_linear 1
#endif
/* GL_OES_texture_half_float */
#ifndef GL_OES_texture_half_float
#define GL_OES_texture_half_float 1
#endif
/* GL_OES_texture_half_float_linear */
#ifndef GL_OES_texture_half_float_linear
#define GL_OES_texture_half_float_linear 1
#endif
/* GL_OES_texture_npot */
#ifndef GL_OES_texture_npot
#define GL_OES_texture_npot 1
#endif
/* GL_OES_vertex_array_object */
#ifndef GL_OES_vertex_array_object
#define GL_OES_vertex_array_object 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glBindVertexArrayOES (GLuint array);
GL_APICALL void GL_APIENTRY glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays);
GL_APICALL void GL_APIENTRY glGenVertexArraysOES (GLsizei n, GLuint *arrays);
GL_APICALL GLboolean GL_APIENTRY glIsVertexArrayOES (GLuint array);
#endif
typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOESPROC) (GLuint array);
typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOESPROC) (GLsizei n, const GLuint *arrays);
typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOESPROC) (GLsizei n, GLuint *arrays);
typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOESPROC) (GLuint array);
#endif
/* GL_OES_vertex_half_float */
#ifndef GL_OES_vertex_half_float
#define GL_OES_vertex_half_float 1
#endif
/* GL_OES_vertex_type_10_10_10_2 */
#ifndef GL_OES_vertex_type_10_10_10_2
#define GL_OES_vertex_type_10_10_10_2 1
#endif
/*------------------------------------------------------------------------*
* AMD extension functions
*------------------------------------------------------------------------*/
/* GL_AMD_compressed_3DC_texture */
#ifndef GL_AMD_compressed_3DC_texture
#define GL_AMD_compressed_3DC_texture 1
#endif
/* GL_AMD_compressed_ATC_texture */
#ifndef GL_AMD_compressed_ATC_texture
#define GL_AMD_compressed_ATC_texture 1
#endif
/* AMD_performance_monitor */
#ifndef GL_AMD_performance_monitor
#define GL_AMD_performance_monitor 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, GLvoid *data);
GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);
GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);
GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor);
GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor);
GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
#endif
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, GLvoid *data);
typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
#endif
/* GL_AMD_program_binary_Z400 */
#ifndef GL_AMD_program_binary_Z400
#define GL_AMD_program_binary_Z400 1
#endif
/*------------------------------------------------------------------------*
* ANGLE extension functions
*------------------------------------------------------------------------*/
/* GL_ANGLE_framebuffer_blit */
#ifndef GL_ANGLE_framebuffer_blit
#define GL_ANGLE_framebuffer_blit 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glBlitFramebufferANGLE (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#endif
typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERANGLEPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#endif
/* GL_ANGLE_framebuffer_multisample */
#ifndef GL_ANGLE_framebuffer_multisample
#define GL_ANGLE_framebuffer_multisample 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleANGLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
#endif
typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
#endif
/* GL_ANGLE_pack_reverse_row_order */
#ifndef GL_ANGLE_pack_reverse_row_order
#define GL_ANGLE_pack_reverse_row_order 1
#endif
/* GL_ANGLE_texture_compression_dxt3 */
#ifndef GL_ANGLE_texture_compression_dxt3
#define GL_ANGLE_texture_compression_dxt3 1
#endif
/* GL_ANGLE_texture_compression_dxt5 */
#ifndef GL_ANGLE_texture_compression_dxt5
#define GL_ANGLE_texture_compression_dxt5 1
#endif
/* GL_ANGLE_translated_shader_source */
#ifndef GL_ANGLE_translated_shader_source
#define GL_ANGLE_translated_shader_source 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glGetTranslatedShaderSourceANGLE (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source);
#endif
typedef void (GL_APIENTRYP PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC) (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source);
#endif
/* GL_ANGLE_texture_usage */
#ifndef GL_ANGLE_texture_usage
#define GL_ANGLE_texture_usage 1
#endif
/* GL_ANGLE_instanced_arrays */
#ifndef GL_ANGLE_instanced_arrays
#define GL_ANGLE_instanced_arrays 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE(GLuint index, GLuint divisor);
GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
#endif
typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORANGLEPROC) (GLuint index, GLuint divisor);
typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDANGLEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDANGLEPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
#endif
/*------------------------------------------------------------------------*
* APPLE extension functions
*------------------------------------------------------------------------*/
/* GL_APPLE_rgb_422 */
#ifndef GL_APPLE_rgb_422
#define GL_APPLE_rgb_422 1
#endif
/* GL_APPLE_framebuffer_multisample */
#ifndef GL_APPLE_framebuffer_multisample
#define GL_APPLE_framebuffer_multisample 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleAPPLE (GLenum, GLsizei, GLenum, GLsizei, GLsizei);
GL_APICALL void GL_APIENTRY glResolveMultisampleFramebufferAPPLE (void);
#endif /* GL_GLEXT_PROTOTYPES */
typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC) (void);
#endif
/* GL_APPLE_texture_format_BGRA8888 */
#ifndef GL_APPLE_texture_format_BGRA8888
#define GL_APPLE_texture_format_BGRA8888 1
#endif
/* GL_APPLE_texture_max_level */
#ifndef GL_APPLE_texture_max_level
#define GL_APPLE_texture_max_level 1
#endif
/*------------------------------------------------------------------------*
* ARM extension functions
*------------------------------------------------------------------------*/
/* GL_ARM_mali_shader_binary */
#ifndef GL_ARM_mali_shader_binary
#define GL_ARM_mali_shader_binary 1
#endif
/* GL_ARM_rgba8 */
#ifndef GL_ARM_rgba8
#define GL_ARM_rgba8 1
#endif
/*------------------------------------------------------------------------*
* EXT extension functions
*------------------------------------------------------------------------*/
/* GL_EXT_blend_minmax */
#ifndef GL_EXT_blend_minmax
#define GL_EXT_blend_minmax 1
#endif
/* GL_EXT_color_buffer_half_float */
#ifndef GL_EXT_color_buffer_half_float
#define GL_EXT_color_buffer_half_float 1
#endif
/* GL_EXT_debug_label */
#ifndef GL_EXT_debug_label
#define GL_EXT_debug_label 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label);
GL_APICALL void GL_APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
#endif
typedef void (GL_APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label);
typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
#endif
/* GL_EXT_debug_marker */
#ifndef GL_EXT_debug_marker
#define GL_EXT_debug_marker 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker);
GL_APICALL void GL_APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker);
GL_APICALL void GL_APIENTRY glPopGroupMarkerEXT (void);
#endif
typedef void (GL_APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker);
typedef void (GL_APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker);
typedef void (GL_APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void);
#endif
/* GL_EXT_discard_framebuffer */
#ifndef GL_EXT_discard_framebuffer
#define GL_EXT_discard_framebuffer 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments);
#endif
typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
#endif
/* GL_EXT_multisampled_render_to_texture */
#ifndef GL_EXT_multisampled_render_to_texture
#define GL_EXT_multisampled_render_to_texture 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum, GLsizei, GLenum, GLsizei, GLsizei);
GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLsizei);
#endif
typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
#endif
#ifndef GL_EXT_multi_draw_arrays
#define GL_EXT_multi_draw_arrays 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
GL_APICALL void GL_APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
#endif /* GL_GLEXT_PROTOTYPES */
typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
#endif
/* GL_EXT_occlusion_query_boolean */
#ifndef GL_EXT_occlusion_query_boolean
#define GL_EXT_occlusion_query_boolean 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glGenQueriesEXT (GLsizei n, GLuint *ids);
GL_APICALL void GL_APIENTRY glDeleteQueriesEXT (GLsizei n, const GLuint *ids);
GL_APICALL GLboolean GL_APIENTRY glIsQueryEXT (GLuint id);
GL_APICALL void GL_APIENTRY glBeginQueryEXT (GLenum target, GLuint id);
GL_APICALL void GL_APIENTRY glEndQueryEXT (GLenum target);
GL_APICALL void GL_APIENTRY glGetQueryivEXT (GLenum target, GLenum pname, GLint *params);
GL_APICALL void GL_APIENTRY glGetQueryObjectuivEXT (GLuint id, GLenum pname, GLuint *params);
#endif
typedef void (GL_APIENTRYP PFNGLGENQUERIESEXTPROC) (GLsizei n, GLuint *ids);
typedef void (GL_APIENTRYP PFNGLDELETEQUERIESEXTPROC) (GLsizei n, const GLuint *ids);
typedef GLboolean (GL_APIENTRYP PFNGLISQUERYEXTPROC) (GLuint id);
typedef void (GL_APIENTRYP PFNGLBEGINQUERYEXTPROC) (GLenum target, GLuint id);
typedef void (GL_APIENTRYP PFNGLENDQUERYEXTPROC) (GLenum target);
typedef void (GL_APIENTRYP PFNGLGETQUERYIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVEXTPROC) (GLuint id, GLenum pname, GLuint *params);
#endif
/* GL_EXT_read_format_bgra */
#ifndef GL_EXT_read_format_bgra
#define GL_EXT_read_format_bgra 1
#endif
/* GL_EXT_robustness */
#ifndef GL_EXT_robustness
#define GL_EXT_robustness 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void);
GL_APICALL void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
GL_APICALL void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, float *params);
GL_APICALL void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params);
#endif
typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void);
typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, float *params);
typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
#endif
/* GL_EXT_separate_shader_objects */
#ifndef GL_EXT_separate_shader_objects
#define GL_EXT_separate_shader_objects 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glUseProgramStagesEXT (GLuint pipeline, GLbitfield stages, GLuint program);
GL_APICALL void GL_APIENTRY glActiveShaderProgramEXT (GLuint pipeline, GLuint program);
GL_APICALL GLuint GL_APIENTRY glCreateShaderProgramvEXT (GLenum type, GLsizei count, const GLchar **strings);
GL_APICALL void GL_APIENTRY glBindProgramPipelineEXT (GLuint pipeline);
GL_APICALL void GL_APIENTRY glDeleteProgramPipelinesEXT (GLsizei n, const GLuint *pipelines);
GL_APICALL void GL_APIENTRY glGenProgramPipelinesEXT (GLsizei n, GLuint *pipelines);
GL_APICALL GLboolean GL_APIENTRY glIsProgramPipelineEXT (GLuint pipeline);
GL_APICALL void GL_APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value);
GL_APICALL void GL_APIENTRY glGetProgramPipelineivEXT (GLuint pipeline, GLenum pname, GLint *params);
GL_APICALL void GL_APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint x);
GL_APICALL void GL_APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint x, GLint y);
GL_APICALL void GL_APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint x, GLint y, GLint z);
GL_APICALL void GL_APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint x, GLint y, GLint z, GLint w);
GL_APICALL void GL_APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat x);
GL_APICALL void GL_APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat x, GLfloat y);
GL_APICALL void GL_APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z);
GL_APICALL void GL_APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
GL_APICALL void GL_APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
GL_APICALL void GL_APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
GL_APICALL void GL_APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
GL_APICALL void GL_APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
GL_APICALL void GL_APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GL_APICALL void GL_APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GL_APICALL void GL_APIENTRY glValidateProgramPipelineEXT (GLuint pipeline);
GL_APICALL void GL_APIENTRY glGetProgramPipelineInfoLogEXT (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
#endif
typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESEXTPROC) (GLuint pipeline, GLbitfield stages, GLuint program);
typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMEXTPROC) (GLuint pipeline, GLuint program);
typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVEXTPROC) (GLenum type, GLsizei count, const GLchar **strings);
typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESEXTPROC) (GLsizei n, const GLuint *pipelines);
typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESEXTPROC) (GLsizei n, GLuint *pipelines);
typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value);
typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVEXTPROC) (GLuint pipeline, GLenum pname, GLint *params);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint x);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint x, GLint y);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint x, GLint y, GLint z);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint x, GLint y, GLint z, GLint w);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat x);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
#endif
/* GL_EXT_shader_texture_lod */
#ifndef GL_EXT_shader_texture_lod
#define GL_EXT_shader_texture_lod 1
#endif
/* GL_EXT_shadow_samplers */
#ifndef GL_EXT_shadow_samplers
#define GL_EXT_shadow_samplers 1
#endif
/* GL_EXT_sRGB */
#ifndef GL_EXT_sRGB
#define GL_EXT_sRGB 1
#endif
/* GL_EXT_texture_compression_dxt1 */
#ifndef GL_EXT_texture_compression_dxt1
#define GL_EXT_texture_compression_dxt1 1
#endif
/* GL_EXT_texture_filter_anisotropic */
#ifndef GL_EXT_texture_filter_anisotropic
#define GL_EXT_texture_filter_anisotropic 1
#endif
/* GL_EXT_texture_format_BGRA8888 */
#ifndef GL_EXT_texture_format_BGRA8888
#define GL_EXT_texture_format_BGRA8888 1
#endif
/* GL_EXT_texture_rg */
#ifndef GL_EXT_texture_rg
#define GL_EXT_texture_rg 1
#endif
/* GL_EXT_texture_storage */
#ifndef GL_EXT_texture_storage
#define GL_EXT_texture_storage 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
GL_APICALL void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
GL_APICALL void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
GL_APICALL void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
#endif
typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
#endif
/* GL_EXT_texture_type_2_10_10_10_REV */
#ifndef GL_EXT_texture_type_2_10_10_10_REV
#define GL_EXT_texture_type_2_10_10_10_REV 1
#endif
/* GL_EXT_unpack_subimage */
#ifndef GL_EXT_unpack_subimage
#define GL_EXT_unpack_subimage 1
#endif
/*------------------------------------------------------------------------*
* DMP extension functions
*------------------------------------------------------------------------*/
/* GL_DMP_shader_binary */
#ifndef GL_DMP_shader_binary
#define GL_DMP_shader_binary 1
#endif
/*------------------------------------------------------------------------*
* IMG extension functions
*------------------------------------------------------------------------*/
/* GL_IMG_program_binary */
#ifndef GL_IMG_program_binary
#define GL_IMG_program_binary 1
#endif
/* GL_IMG_read_format */
#ifndef GL_IMG_read_format
#define GL_IMG_read_format 1
#endif
/* GL_IMG_shader_binary */
#ifndef GL_IMG_shader_binary
#define GL_IMG_shader_binary 1
#endif
/* GL_IMG_texture_compression_pvrtc */
#ifndef GL_IMG_texture_compression_pvrtc
#define GL_IMG_texture_compression_pvrtc 1
#endif
/* GL_IMG_multisampled_render_to_texture */
#ifndef GL_IMG_multisampled_render_to_texture
#define GL_IMG_multisampled_render_to_texture 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleIMG (GLenum, GLsizei, GLenum, GLsizei, GLsizei);
GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleIMG (GLenum, GLenum, GLenum, GLuint, GLint, GLsizei);
#endif
typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMG) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
#endif
/*------------------------------------------------------------------------*
* NV extension functions
*------------------------------------------------------------------------*/
/* GL_NV_coverage_sample */
#ifndef GL_NV_coverage_sample
#define GL_NV_coverage_sample 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask);
GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation);
#endif
typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask);
typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation);
#endif
/* GL_NV_depth_nonlinear */
#ifndef GL_NV_depth_nonlinear
#define GL_NV_depth_nonlinear 1
#endif
/* GL_NV_draw_buffers */
#ifndef GL_NV_draw_buffers
#define GL_NV_draw_buffers 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glDrawBuffersNV (GLsizei n, const GLenum *bufs);
#endif
typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSNVPROC) (GLsizei n, const GLenum *bufs);
#endif
#ifndef GL_EXT_draw_buffers
#define GL_EXT_draw_buffers 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glDrawBuffersEXT (GLsizei n, const GLenum *bufs);
#endif
typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSEXTPROC) (GLsizei n, const GLenum *bufs);
#endif
/* GL_NV_fbo_color_attachments */
#ifndef GL_NV_fbo_color_attachments
#define GL_NV_fbo_color_attachments 1
#endif
/* GL_NV_fence */
#ifndef GL_NV_fence
#define GL_NV_fence 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei, GLuint *);
GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint);
GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint);
GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint);
GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint, GLenum);
#endif
typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
#endif
/* GL_NV_read_buffer */
#ifndef GL_NV_read_buffer
#define GL_NV_read_buffer 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glReadBufferNV (GLenum mode);
#endif
typedef void (GL_APIENTRYP PFNGLREADBUFFERNVPROC) (GLenum mode);
#endif
/* GL_NV_read_buffer_front */
#ifndef GL_NV_read_buffer_front
#define GL_NV_read_buffer_front 1
#endif
/* GL_NV_read_depth */
#ifndef GL_NV_read_depth
#define GL_NV_read_depth 1
#endif
/* GL_NV_read_depth_stencil */
#ifndef GL_NV_read_depth_stencil
#define GL_NV_read_depth_stencil 1
#endif
/* GL_NV_read_stencil */
#ifndef GL_NV_read_stencil
#define GL_NV_read_stencil 1
#endif
/* GL_NV_texture_compression_s3tc_update */
#ifndef GL_NV_texture_compression_s3tc_update
#define GL_NV_texture_compression_s3tc_update 1
#endif
/* GL_NV_texture_npot_2D_mipmap */
#ifndef GL_NV_texture_npot_2D_mipmap
#define GL_NV_texture_npot_2D_mipmap 1
#endif
/*------------------------------------------------------------------------*
* QCOM extension functions
*------------------------------------------------------------------------*/
/* GL_QCOM_alpha_test */
#ifndef GL_QCOM_alpha_test
#define GL_QCOM_alpha_test 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glAlphaFuncQCOM (GLenum func, GLclampf ref);
#endif
typedef void (GL_APIENTRYP PFNGLALPHAFUNCQCOMPROC) (GLenum func, GLclampf ref);
#endif
/* GL_QCOM_driver_control */
#ifndef GL_QCOM_driver_control
#define GL_QCOM_driver_control 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls);
GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl);
GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl);
#endif
typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls);
typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
#endif
/* GL_QCOM_extended_get */
#ifndef GL_QCOM_extended_get
#define GL_QCOM_extended_get 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures);
GL_APICALL void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
GL_APICALL void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
GL_APICALL void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
GL_APICALL void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
GL_APICALL void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param);
GL_APICALL void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid *texels);
GL_APICALL void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, GLvoid **params);
#endif
typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures);
typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param);
typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid *texels);
typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, GLvoid **params);
#endif
/* GL_QCOM_extended_get2 */
#ifndef GL_QCOM_extended_get2
#define GL_QCOM_extended_get2 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders);
GL_APICALL void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
GL_APICALL GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program);
GL_APICALL void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
#endif
typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders);
typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program);
typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
#endif
/* GL_QCOM_perfmon_global_mode */
#ifndef GL_QCOM_perfmon_global_mode
#define GL_QCOM_perfmon_global_mode 1
#endif
/* GL_QCOM_writeonly_rendering */
#ifndef GL_QCOM_writeonly_rendering
#define GL_QCOM_writeonly_rendering 1
#endif
/* GL_QCOM_tiled_rendering */
#ifndef GL_QCOM_tiled_rendering
#define GL_QCOM_tiled_rendering 1
#ifdef GL_GLEXT_PROTOTYPES
GL_APICALL void GL_APIENTRY glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
GL_APICALL void GL_APIENTRY glEndTilingQCOM (GLbitfield preserveMask);
#endif
typedef void (GL_APIENTRYP PFNGLSTARTTILINGQCOMPROC) (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask);
#endif
/*------------------------------------------------------------------------*
* VIV extension tokens
*------------------------------------------------------------------------*/
/* GL_VIV_shader_binary */
#ifndef GL_VIV_shader_binary
#define GL_VIV_shader_binary 1
#endif
/* GL_ANGLE_program_binary */
#ifndef GL_ANGLE_program_binary
#define GL_ANGLE_program_binary 1
#endif
#ifdef __cplusplus
}
#endif
#endif /* __gl2ext_h_ */
| 010smithzhang-ddd | include/GLES2/gl2ext.h | C | bsd | 73,181 |
#ifndef __gl2platform_h_
#define __gl2platform_h_
/* $Revision: 10602 $ on $Date:: 2010-03-04 22:35:34 -0800 #$ */
/*
* This document is licensed under the SGI Free Software B License Version
* 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
*/
/* Platform-specific types and definitions for OpenGL ES 2.X gl2.h
*
* Adopters may modify khrplatform.h and this file to suit their platform.
* You are encouraged to submit all modifications to the Khronos group so that
* they can be included in future versions of this file. Please submit changes
* by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
* by filing a bug against product "OpenGL-ES" component "Registry".
*/
#include <KHR/khrplatform.h>
#ifndef GL_APICALL
#define GL_APICALL KHRONOS_APICALL
#endif
#ifndef GL_APIENTRY
#define GL_APIENTRY KHRONOS_APIENTRY
#endif
#endif /* __gl2platform_h_ */
| 010smithzhang-ddd | include/GLES2/gl2platform.h | C | bsd | 909 |
#ifndef __gl2_h_
#define __gl2_h_
/* $Revision: 10602 $ on $Date:: 2010-03-04 22:35:34 -0800 #$ */
#include <GLES2/gl2platform.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* This document is licensed under the SGI Free Software B License Version
* 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
*/
/*-------------------------------------------------------------------------
* Data type definitions
*-----------------------------------------------------------------------*/
typedef void GLvoid;
typedef char GLchar;
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef khronos_int8_t GLbyte;
typedef short GLshort;
typedef int GLint;
typedef int GLsizei;
typedef khronos_uint8_t GLubyte;
typedef unsigned short GLushort;
typedef unsigned int GLuint;
typedef khronos_float_t GLfloat;
typedef khronos_float_t GLclampf;
typedef khronos_int32_t GLfixed;
/* GL types for handling large vertex buffer objects */
typedef khronos_intptr_t GLintptr;
typedef khronos_ssize_t GLsizeiptr;
/* OpenGL ES core versions */
#define GL_ES_VERSION_2_0 1
/* ClearBufferMask */
#define GL_DEPTH_BUFFER_BIT 0x00000100
#define GL_STENCIL_BUFFER_BIT 0x00000400
#define GL_COLOR_BUFFER_BIT 0x00004000
/* Boolean */
#define GL_FALSE 0
#define GL_TRUE 1
/* BeginMode */
#define GL_POINTS 0x0000
#define GL_LINES 0x0001
#define GL_LINE_LOOP 0x0002
#define GL_LINE_STRIP 0x0003
#define GL_TRIANGLES 0x0004
#define GL_TRIANGLE_STRIP 0x0005
#define GL_TRIANGLE_FAN 0x0006
/* AlphaFunction (not supported in ES20) */
/* GL_NEVER */
/* GL_LESS */
/* GL_EQUAL */
/* GL_LEQUAL */
/* GL_GREATER */
/* GL_NOTEQUAL */
/* GL_GEQUAL */
/* GL_ALWAYS */
/* BlendingFactorDest */
#define GL_ZERO 0
#define GL_ONE 1
#define GL_SRC_COLOR 0x0300
#define GL_ONE_MINUS_SRC_COLOR 0x0301
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_DST_ALPHA 0x0304
#define GL_ONE_MINUS_DST_ALPHA 0x0305
/* BlendingFactorSrc */
/* GL_ZERO */
/* GL_ONE */
#define GL_DST_COLOR 0x0306
#define GL_ONE_MINUS_DST_COLOR 0x0307
#define GL_SRC_ALPHA_SATURATE 0x0308
/* GL_SRC_ALPHA */
/* GL_ONE_MINUS_SRC_ALPHA */
/* GL_DST_ALPHA */
/* GL_ONE_MINUS_DST_ALPHA */
/* BlendEquationSeparate */
#define GL_FUNC_ADD 0x8006
#define GL_BLEND_EQUATION 0x8009
#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */
#define GL_BLEND_EQUATION_ALPHA 0x883D
/* BlendSubtract */
#define GL_FUNC_SUBTRACT 0x800A
#define GL_FUNC_REVERSE_SUBTRACT 0x800B
/* Separate Blend Functions */
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_CONSTANT_COLOR 0x8001
#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
#define GL_CONSTANT_ALPHA 0x8003
#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
#define GL_BLEND_COLOR 0x8005
/* Buffer Objects */
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
#define GL_STATIC_DRAW 0x88E4
#define GL_DYNAMIC_DRAW 0x88E8
#define GL_BUFFER_SIZE 0x8764
#define GL_BUFFER_USAGE 0x8765
#define GL_CURRENT_VERTEX_ATTRIB 0x8626
/* CullFaceMode */
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_FRONT_AND_BACK 0x0408
/* DepthFunction */
/* GL_NEVER */
/* GL_LESS */
/* GL_EQUAL */
/* GL_LEQUAL */
/* GL_GREATER */
/* GL_NOTEQUAL */
/* GL_GEQUAL */
/* GL_ALWAYS */
/* EnableCap */
#define GL_TEXTURE_2D 0x0DE1
#define GL_CULL_FACE 0x0B44
#define GL_BLEND 0x0BE2
#define GL_DITHER 0x0BD0
#define GL_STENCIL_TEST 0x0B90
#define GL_DEPTH_TEST 0x0B71
#define GL_SCISSOR_TEST 0x0C11
#define GL_POLYGON_OFFSET_FILL 0x8037
#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
#define GL_SAMPLE_COVERAGE 0x80A0
/* ErrorCode */
#define GL_NO_ERROR 0
#define GL_INVALID_ENUM 0x0500
#define GL_INVALID_VALUE 0x0501
#define GL_INVALID_OPERATION 0x0502
#define GL_OUT_OF_MEMORY 0x0505
/* FrontFaceDirection */
#define GL_CW 0x0900
#define GL_CCW 0x0901
/* GetPName */
#define GL_LINE_WIDTH 0x0B21
#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
#define GL_CULL_FACE_MODE 0x0B45
#define GL_FRONT_FACE 0x0B46
#define GL_DEPTH_RANGE 0x0B70
#define GL_DEPTH_WRITEMASK 0x0B72
#define GL_DEPTH_CLEAR_VALUE 0x0B73
#define GL_DEPTH_FUNC 0x0B74
#define GL_STENCIL_CLEAR_VALUE 0x0B91
#define GL_STENCIL_FUNC 0x0B92
#define GL_STENCIL_FAIL 0x0B94
#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95
#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96
#define GL_STENCIL_REF 0x0B97
#define GL_STENCIL_VALUE_MASK 0x0B93
#define GL_STENCIL_WRITEMASK 0x0B98
#define GL_STENCIL_BACK_FUNC 0x8800
#define GL_STENCIL_BACK_FAIL 0x8801
#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
#define GL_STENCIL_BACK_REF 0x8CA3
#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
#define GL_VIEWPORT 0x0BA2
#define GL_SCISSOR_BOX 0x0C10
/* GL_SCISSOR_TEST */
#define GL_COLOR_CLEAR_VALUE 0x0C22
#define GL_COLOR_WRITEMASK 0x0C23
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_MAX_TEXTURE_SIZE 0x0D33
#define GL_MAX_VIEWPORT_DIMS 0x0D3A
#define GL_SUBPIXEL_BITS 0x0D50
#define GL_RED_BITS 0x0D52
#define GL_GREEN_BITS 0x0D53
#define GL_BLUE_BITS 0x0D54
#define GL_ALPHA_BITS 0x0D55
#define GL_DEPTH_BITS 0x0D56
#define GL_STENCIL_BITS 0x0D57
#define GL_POLYGON_OFFSET_UNITS 0x2A00
/* GL_POLYGON_OFFSET_FILL */
#define GL_POLYGON_OFFSET_FACTOR 0x8038
#define GL_TEXTURE_BINDING_2D 0x8069
#define GL_SAMPLE_BUFFERS 0x80A8
#define GL_SAMPLES 0x80A9
#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
/* GetTextureParameter */
/* GL_TEXTURE_MAG_FILTER */
/* GL_TEXTURE_MIN_FILTER */
/* GL_TEXTURE_WRAP_S */
/* GL_TEXTURE_WRAP_T */
#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
/* HintMode */
#define GL_DONT_CARE 0x1100
#define GL_FASTEST 0x1101
#define GL_NICEST 0x1102
/* HintTarget */
#define GL_GENERATE_MIPMAP_HINT 0x8192
/* DataType */
#define GL_BYTE 0x1400
#define GL_UNSIGNED_BYTE 0x1401
#define GL_SHORT 0x1402
#define GL_UNSIGNED_SHORT 0x1403
#define GL_INT 0x1404
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_FIXED 0x140C
/* PixelFormat */
#define GL_DEPTH_COMPONENT 0x1902
#define GL_ALPHA 0x1906
#define GL_RGB 0x1907
#define GL_RGBA 0x1908
#define GL_LUMINANCE 0x1909
#define GL_LUMINANCE_ALPHA 0x190A
/* PixelType */
/* GL_UNSIGNED_BYTE */
#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
#define GL_UNSIGNED_SHORT_5_6_5 0x8363
/* Shaders */
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_MAX_VERTEX_ATTRIBS 0x8869
#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB
#define GL_MAX_VARYING_VECTORS 0x8DFC
#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD
#define GL_SHADER_TYPE 0x8B4F
#define GL_DELETE_STATUS 0x8B80
#define GL_LINK_STATUS 0x8B82
#define GL_VALIDATE_STATUS 0x8B83
#define GL_ATTACHED_SHADERS 0x8B85
#define GL_ACTIVE_UNIFORMS 0x8B86
#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
#define GL_ACTIVE_ATTRIBUTES 0x8B89
#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
#define GL_CURRENT_PROGRAM 0x8B8D
/* StencilFunction */
#define GL_NEVER 0x0200
#define GL_LESS 0x0201
#define GL_EQUAL 0x0202
#define GL_LEQUAL 0x0203
#define GL_GREATER 0x0204
#define GL_NOTEQUAL 0x0205
#define GL_GEQUAL 0x0206
#define GL_ALWAYS 0x0207
/* StencilOp */
/* GL_ZERO */
#define GL_KEEP 0x1E00
#define GL_REPLACE 0x1E01
#define GL_INCR 0x1E02
#define GL_DECR 0x1E03
#define GL_INVERT 0x150A
#define GL_INCR_WRAP 0x8507
#define GL_DECR_WRAP 0x8508
/* StringName */
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
/* TextureMagFilter */
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
/* TextureMinFilter */
/* GL_NEAREST */
/* GL_LINEAR */
#define GL_NEAREST_MIPMAP_NEAREST 0x2700
#define GL_LINEAR_MIPMAP_NEAREST 0x2701
#define GL_NEAREST_MIPMAP_LINEAR 0x2702
#define GL_LINEAR_MIPMAP_LINEAR 0x2703
/* TextureParameterName */
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
/* TextureTarget */
/* GL_TEXTURE_2D */
#define GL_TEXTURE 0x1702
#define GL_TEXTURE_CUBE_MAP 0x8513
#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
/* TextureUnit */
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE1 0x84C1
#define GL_TEXTURE2 0x84C2
#define GL_TEXTURE3 0x84C3
#define GL_TEXTURE4 0x84C4
#define GL_TEXTURE5 0x84C5
#define GL_TEXTURE6 0x84C6
#define GL_TEXTURE7 0x84C7
#define GL_TEXTURE8 0x84C8
#define GL_TEXTURE9 0x84C9
#define GL_TEXTURE10 0x84CA
#define GL_TEXTURE11 0x84CB
#define GL_TEXTURE12 0x84CC
#define GL_TEXTURE13 0x84CD
#define GL_TEXTURE14 0x84CE
#define GL_TEXTURE15 0x84CF
#define GL_TEXTURE16 0x84D0
#define GL_TEXTURE17 0x84D1
#define GL_TEXTURE18 0x84D2
#define GL_TEXTURE19 0x84D3
#define GL_TEXTURE20 0x84D4
#define GL_TEXTURE21 0x84D5
#define GL_TEXTURE22 0x84D6
#define GL_TEXTURE23 0x84D7
#define GL_TEXTURE24 0x84D8
#define GL_TEXTURE25 0x84D9
#define GL_TEXTURE26 0x84DA
#define GL_TEXTURE27 0x84DB
#define GL_TEXTURE28 0x84DC
#define GL_TEXTURE29 0x84DD
#define GL_TEXTURE30 0x84DE
#define GL_TEXTURE31 0x84DF
#define GL_ACTIVE_TEXTURE 0x84E0
/* TextureWrapMode */
#define GL_REPEAT 0x2901
#define GL_CLAMP_TO_EDGE 0x812F
#define GL_MIRRORED_REPEAT 0x8370
/* Uniform Types */
#define GL_FLOAT_VEC2 0x8B50
#define GL_FLOAT_VEC3 0x8B51
#define GL_FLOAT_VEC4 0x8B52
#define GL_INT_VEC2 0x8B53
#define GL_INT_VEC3 0x8B54
#define GL_INT_VEC4 0x8B55
#define GL_BOOL 0x8B56
#define GL_BOOL_VEC2 0x8B57
#define GL_BOOL_VEC3 0x8B58
#define GL_BOOL_VEC4 0x8B59
#define GL_FLOAT_MAT2 0x8B5A
#define GL_FLOAT_MAT3 0x8B5B
#define GL_FLOAT_MAT4 0x8B5C
#define GL_SAMPLER_2D 0x8B5E
#define GL_SAMPLER_CUBE 0x8B60
/* Vertex Arrays */
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
/* Read Format */
#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A
#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
/* Shader Source */
#define GL_COMPILE_STATUS 0x8B81
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_SHADER_SOURCE_LENGTH 0x8B88
#define GL_SHADER_COMPILER 0x8DFA
/* Shader Binary */
#define GL_SHADER_BINARY_FORMATS 0x8DF8
#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9
/* Shader Precision-Specified Types */
#define GL_LOW_FLOAT 0x8DF0
#define GL_MEDIUM_FLOAT 0x8DF1
#define GL_HIGH_FLOAT 0x8DF2
#define GL_LOW_INT 0x8DF3
#define GL_MEDIUM_INT 0x8DF4
#define GL_HIGH_INT 0x8DF5
/* Framebuffer Object. */
#define GL_FRAMEBUFFER 0x8D40
#define GL_RENDERBUFFER 0x8D41
#define GL_RGBA4 0x8056
#define GL_RGB5_A1 0x8057
#define GL_RGB565 0x8D62
#define GL_DEPTH_COMPONENT16 0x81A5
#define GL_STENCIL_INDEX 0x1901
#define GL_STENCIL_INDEX8 0x8D48
#define GL_RENDERBUFFER_WIDTH 0x8D42
#define GL_RENDERBUFFER_HEIGHT 0x8D43
#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44
#define GL_RENDERBUFFER_RED_SIZE 0x8D50
#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51
#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52
#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53
#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54
#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55
#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
#define GL_COLOR_ATTACHMENT0 0x8CE0
#define GL_DEPTH_ATTACHMENT 0x8D00
#define GL_STENCIL_ATTACHMENT 0x8D20
#define GL_NONE 0
#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9
#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
#define GL_FRAMEBUFFER_BINDING 0x8CA6
#define GL_RENDERBUFFER_BINDING 0x8CA7
#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
/*-------------------------------------------------------------------------
* GL core functions.
*-----------------------------------------------------------------------*/
GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture);
GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader);
GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar* name);
GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
GL_APICALL void GL_APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
GL_APICALL void GL_APIENTRY glBlendEquation ( GLenum mode );
GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage);
GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data);
GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target);
GL_APICALL void GL_APIENTRY glClear (GLbitfield mask);
GL_APICALL void GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
GL_APICALL void GL_APIENTRY glClearDepthf (GLclampf depth);
GL_APICALL void GL_APIENTRY glClearStencil (GLint s);
GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader);
GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data);
GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
GL_APICALL GLuint GL_APIENTRY glCreateProgram (void);
GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type);
GL_APICALL void GL_APIENTRY glCullFace (GLenum mode);
GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint* buffers);
GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint* framebuffers);
GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program);
GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers);
GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader);
GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint* textures);
GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func);
GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag);
GL_APICALL void GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar);
GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader);
GL_APICALL void GL_APIENTRY glDisable (GLenum cap);
GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index);
GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid* indices);
GL_APICALL void GL_APIENTRY glEnable (GLenum cap);
GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index);
GL_APICALL void GL_APIENTRY glFinish (void);
GL_APICALL void GL_APIENTRY glFlush (void);
GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode);
GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint* buffers);
GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target);
GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint* framebuffers);
GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint* renderbuffers);
GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint* textures);
GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name);
GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name);
GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders);
GL_APICALL int GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar* name);
GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean* params);
GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL GLenum GL_APIENTRY glGetError (void);
GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog);
GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog);
GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision);
GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source);
GL_APICALL const GLubyte* GL_APIENTRY glGetString (GLenum name);
GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint* params);
GL_APICALL int GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar* name);
GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params);
GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint* params);
GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, GLvoid** pointer);
GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode);
GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer);
GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap);
GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer);
GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program);
GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer);
GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader);
GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture);
GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width);
GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program);
GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels);
GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void);
GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length);
GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar** string, const GLint* length);
GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask);
GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat* params);
GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint* params);
GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels);
GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat x);
GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint x);
GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat x, GLfloat y);
GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint x, GLint y);
GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z);
GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint x, GLint y, GLint z);
GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat* v);
GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint x, GLint y, GLint z, GLint w);
GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint* v);
GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
GL_APICALL void GL_APIENTRY glUseProgram (GLuint program);
GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program);
GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint indx, GLfloat x);
GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint indx, GLfloat x, GLfloat y);
GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z);
GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint indx, const GLfloat* values);
GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr);
GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef __cplusplus
}
#endif
#endif /* __gl2_h_ */
| 010smithzhang-ddd | include/GLES2/gl2.h | C | bsd | 31,914 |
# Copyright (c) 2010 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'essl_to_glsl',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_glsl',
],
'include_dirs': [
'../include',
],
'sources': [
'translator/translator.cpp',
],
},
],
'conditions': [
['OS=="win"', {
'targets': [
{
'target_name': 'essl_to_hlsl',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_hlsl',
],
'include_dirs': [
'../include',
'../src',
],
'sources': [
'translator/translator.cpp',
'../src/common/debug.cpp',
],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': ['d3d9.lib'],
}
}
},
{
'target_name': 'es_util',
'type': 'static_library',
'dependencies': [
'../src/build_angle.gyp:libEGL',
'../src/build_angle.gyp:libGLESv2',
],
'include_dirs': [
'gles2_book/Common',
'../include',
],
'sources': [
'gles2_book/Common/esShader.c',
'gles2_book/Common/esShapes.c',
'gles2_book/Common/esTransform.c',
'gles2_book/Common/esUtil.c',
'gles2_book/Common/esUtil.h',
'gles2_book/Common/esUtil_win.h',
'gles2_book/Common/Win32/esUtil_TGA.c',
'gles2_book/Common/Win32/esUtil_win32.c',
],
'direct_dependent_settings': {
'include_dirs': [
'gles2_book/Common',
'../include',
],
},
},
{
'target_name': 'hello_triangle',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Hello_Triangle/Hello_Triangle.c',
],
},
{
'target_name': 'mip_map_2d',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/MipMap2D/MipMap2D.c',
],
},
{
'target_name': 'multi_texture',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/MultiTexture/MultiTexture.c',
],
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'gles2_book/MultiTexture/basemap.tga',
'gles2_book/MultiTexture/lightmap.tga',
],
},
],
},
{
'target_name': 'particle_system',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/ParticleSystem/ParticleSystem.c',
],
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'gles2_book/ParticleSystem/smoke.tga',
],
},
],
},
{
'target_name': 'simple_texture_2d',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_Texture2D/Simple_Texture2D.c',
],
},
{
'target_name': 'simple_texture_cubemap',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_TextureCubemap/Simple_TextureCubemap.c',
],
},
{
'target_name': 'simple_vertex_shader',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_VertexShader/Simple_VertexShader.c',
],
},
{
'target_name': 'stencil_test',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Stencil_Test/Stencil_Test.c',
],
},
{
'target_name': 'texture_wrap',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/TextureWrap/TextureWrap.c',
],
},
{
'target_name': 'post_sub_buffer',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/PostSubBuffer/PostSubBuffer.c',
],
},
],
}],
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 010smithzhang-ddd | samples/build_samples.gyp | Python | bsd | 4,866 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// ParticleSystem.c
//
// This is an example that demonstrates rendering a particle system
// using a vertex shader and point sprites.
//
#include <stdlib.h>
#include <math.h>
#include "esUtil.h"
#define NUM_PARTICLES 1000
#define PARTICLE_SIZE 7
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint lifetimeLoc;
GLint startPositionLoc;
GLint endPositionLoc;
// Uniform location
GLint timeLoc;
GLint colorLoc;
GLint centerPositionLoc;
GLint samplerLoc;
// Texture handle
GLuint textureId;
// Particle vertex data
float particleData[ NUM_PARTICLES * PARTICLE_SIZE ];
// Current time
float time;
} UserData;
///
// Load texture from disk
//
GLuint LoadTexture ( char *fileName )
{
int width,
height;
char *buffer = esLoadTGA ( fileName, &width, &height );
GLuint texId;
if ( buffer == NULL )
{
esLogMessage ( "Error loading (%s) image.\n", fileName );
return 0;
}
glGenTextures ( 1, &texId );
glBindTexture ( GL_TEXTURE_2D, texId );
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
free ( buffer );
return texId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
int i;
GLbyte vShaderStr[] =
"uniform float u_time; \n"
"uniform vec3 u_centerPosition; \n"
"attribute float a_lifetime; \n"
"attribute vec3 a_startPosition; \n"
"attribute vec3 a_endPosition; \n"
"varying float v_lifetime; \n"
"void main() \n"
"{ \n"
" if ( u_time <= a_lifetime ) \n"
" { \n"
" gl_Position.xyz = a_startPosition + \n"
" (u_time * a_endPosition); \n"
" gl_Position.xyz += u_centerPosition; \n"
" gl_Position.w = 1.0; \n"
" } \n"
" else \n"
" gl_Position = vec4( -1000, -1000, 0, 0 ); \n"
" v_lifetime = 1.0 - ( u_time / a_lifetime ); \n"
" v_lifetime = clamp ( v_lifetime, 0.0, 1.0 ); \n"
" gl_PointSize = ( v_lifetime * v_lifetime ) * 40.0; \n"
"}";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"uniform vec4 u_color; \n"
"varying float v_lifetime; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" vec4 texColor; \n"
" texColor = texture2D( s_texture, gl_PointCoord ); \n"
" gl_FragColor = vec4( u_color ) * texColor; \n"
" gl_FragColor.a *= v_lifetime; \n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->lifetimeLoc = glGetAttribLocation ( userData->programObject, "a_lifetime" );
userData->startPositionLoc = glGetAttribLocation ( userData->programObject, "a_startPosition" );
userData->endPositionLoc = glGetAttribLocation ( userData->programObject, "a_endPosition" );
// Get the uniform locations
userData->timeLoc = glGetUniformLocation ( userData->programObject, "u_time" );
userData->centerPositionLoc = glGetUniformLocation ( userData->programObject, "u_centerPosition" );
userData->colorLoc = glGetUniformLocation ( userData->programObject, "u_color" );
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
// Fill in particle data array
srand ( 0 );
for ( i = 0; i < NUM_PARTICLES; i++ )
{
float *particleData = &userData->particleData[i * PARTICLE_SIZE];
// Lifetime of particle
(*particleData++) = ( (float)(rand() % 10000) / 10000.0f );
// End position of particle
(*particleData++) = ( (float)(rand() % 10000) / 5000.0f ) - 1.0f;
(*particleData++) = ( (float)(rand() % 10000) / 5000.0f ) - 1.0f;
(*particleData++) = ( (float)(rand() % 10000) / 5000.0f ) - 1.0f;
// Start position of particle
(*particleData++) = ( (float)(rand() % 10000) / 40000.0f ) - 0.125f;
(*particleData++) = ( (float)(rand() % 10000) / 40000.0f ) - 0.125f;
(*particleData++) = ( (float)(rand() % 10000) / 40000.0f ) - 0.125f;
}
// Initialize time to cause reset on first update
userData->time = 1.0f;
userData->textureId = LoadTexture ( "smoke.tga" );
if ( userData->textureId <= 0 )
{
return FALSE;
}
return TRUE;
}
///
// Update time-based variables
//
void Update ( ESContext *esContext, float deltaTime )
{
UserData *userData = esContext->userData;
userData->time += deltaTime;
if ( userData->time >= 1.0f )
{
float centerPos[3];
float color[4];
userData->time = 0.0f;
// Pick a new start location and color
centerPos[0] = ( (float)(rand() % 10000) / 10000.0f ) - 0.5f;
centerPos[1] = ( (float)(rand() % 10000) / 10000.0f ) - 0.5f;
centerPos[2] = ( (float)(rand() % 10000) / 10000.0f ) - 0.5f;
glUniform3fv ( userData->centerPositionLoc, 1, ¢erPos[0] );
// Random color
color[0] = ( (float)(rand() % 10000) / 20000.0f ) + 0.5f;
color[1] = ( (float)(rand() % 10000) / 20000.0f ) + 0.5f;
color[2] = ( (float)(rand() % 10000) / 20000.0f ) + 0.5f;
color[3] = 0.5;
glUniform4fv ( userData->colorLoc, 1, &color[0] );
}
// Load uniform time variable
glUniform1f ( userData->timeLoc, userData->time );
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex attributes
glVertexAttribPointer ( userData->lifetimeLoc, 1, GL_FLOAT,
GL_FALSE, PARTICLE_SIZE * sizeof(GLfloat),
userData->particleData );
glVertexAttribPointer ( userData->endPositionLoc, 3, GL_FLOAT,
GL_FALSE, PARTICLE_SIZE * sizeof(GLfloat),
&userData->particleData[1] );
glVertexAttribPointer ( userData->startPositionLoc, 3, GL_FLOAT,
GL_FALSE, PARTICLE_SIZE * sizeof(GLfloat),
&userData->particleData[4] );
glEnableVertexAttribArray ( userData->lifetimeLoc );
glEnableVertexAttribArray ( userData->endPositionLoc );
glEnableVertexAttribArray ( userData->startPositionLoc );
// Blend particles
glEnable ( GL_BLEND );
glBlendFunc ( GL_SRC_ALPHA, GL_ONE );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
glEnable ( GL_TEXTURE_2D );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
glDrawArrays( GL_POINTS, 0, NUM_PARTICLES );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("ParticleSystem"), 640, 480, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esRegisterUpdateFunc ( &esContext, Update );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/ParticleSystem/ParticleSystem.c | C | bsd | 9,277 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// ESShapes.c
//
// Utility functions for generating shapes
//
///
// Includes
//
#include "esUtil.h"
#include <stdlib.h>
#include <math.h>
///
// Defines
//
#define ES_PI (3.14159265f)
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
//
/// \brief Generates geometry for a sphere. Allocates memory for the vertex data and stores
/// the results in the arrays. Generate index list for a TRIANGLE_STRIP
/// \param numSlices The number of slices in the sphere
/// \param vertices If not NULL, will contain array of float3 positions
/// \param normals If not NULL, will contain array of float3 normals
/// \param texCoords If not NULL, will contain array of float2 texCoords
/// \param indices If not NULL, will contain the array of indices for the triangle strip
/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
/// if it is not NULL ) as a GL_TRIANGLE_STRIP
//
int ESUTIL_API esGenSphere ( int numSlices, float radius, GLfloat **vertices, GLfloat **normals,
GLfloat **texCoords, GLushort **indices )
{
int i;
int j;
int numParallels = numSlices / 2;
int numVertices = ( numParallels + 1 ) * ( numSlices + 1 );
int numIndices = numParallels * numSlices * 6;
float angleStep = (2.0f * ES_PI) / ((float) numSlices);
// Allocate memory for buffers
if ( vertices != NULL )
*vertices = malloc ( sizeof(GLfloat) * 3 * numVertices );
if ( normals != NULL )
*normals = malloc ( sizeof(GLfloat) * 3 * numVertices );
if ( texCoords != NULL )
*texCoords = malloc ( sizeof(GLfloat) * 2 * numVertices );
if ( indices != NULL )
*indices = malloc ( sizeof(GLushort) * numIndices );
for ( i = 0; i < numParallels + 1; i++ )
{
for ( j = 0; j < numSlices + 1; j++ )
{
int vertex = ( i * (numSlices + 1) + j ) * 3;
if ( vertices )
{
(*vertices)[vertex + 0] = radius * sinf ( angleStep * (float)i ) *
sinf ( angleStep * (float)j );
(*vertices)[vertex + 1] = radius * cosf ( angleStep * (float)i );
(*vertices)[vertex + 2] = radius * sinf ( angleStep * (float)i ) *
cosf ( angleStep * (float)j );
}
if ( normals )
{
(*normals)[vertex + 0] = (*vertices)[vertex + 0] / radius;
(*normals)[vertex + 1] = (*vertices)[vertex + 1] / radius;
(*normals)[vertex + 2] = (*vertices)[vertex + 2] / radius;
}
if ( texCoords )
{
int texIndex = ( i * (numSlices + 1) + j ) * 2;
(*texCoords)[texIndex + 0] = (float) j / (float) numSlices;
(*texCoords)[texIndex + 1] = ( 1.0f - (float) i ) / (float) (numParallels - 1 );
}
}
}
// Generate the indices
if ( indices != NULL )
{
GLushort *indexBuf = (*indices);
for ( i = 0; i < numParallels ; i++ )
{
for ( j = 0; j < numSlices; j++ )
{
*indexBuf++ = i * ( numSlices + 1 ) + j;
*indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + j;
*indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + ( j + 1 );
*indexBuf++ = i * ( numSlices + 1 ) + j;
*indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + ( j + 1 );
*indexBuf++ = i * ( numSlices + 1 ) + ( j + 1 );
}
}
}
return numIndices;
}
//
/// \brief Generates geometry for a cube. Allocates memory for the vertex data and stores
/// the results in the arrays. Generate index list for a TRIANGLES
/// \param scale The size of the cube, use 1.0 for a unit cube.
/// \param vertices If not NULL, will contain array of float3 positions
/// \param normals If not NULL, will contain array of float3 normals
/// \param texCoords If not NULL, will contain array of float2 texCoords
/// \param indices If not NULL, will contain the array of indices for the triangle strip
/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
/// if it is not NULL ) as a GL_TRIANGLE_STRIP
//
int ESUTIL_API esGenCube ( float scale, GLfloat **vertices, GLfloat **normals,
GLfloat **texCoords, GLushort **indices )
{
int i;
int numVertices = 24;
int numIndices = 36;
GLfloat cubeVerts[] =
{
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
};
GLfloat cubeNormals[] =
{
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
};
GLfloat cubeTex[] =
{
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f,
0.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
// Allocate memory for buffers
if ( vertices != NULL )
{
*vertices = malloc ( sizeof(GLfloat) * 3 * numVertices );
memcpy( *vertices, cubeVerts, sizeof( cubeVerts ) );
for ( i = 0; i < numVertices; i++ )
{
(*vertices)[i] *= scale;
}
}
if ( normals != NULL )
{
*normals = malloc ( sizeof(GLfloat) * 3 * numVertices );
memcpy( *normals, cubeNormals, sizeof( cubeNormals ) );
}
if ( texCoords != NULL )
{
*texCoords = malloc ( sizeof(GLfloat) * 2 * numVertices );
memcpy( *texCoords, cubeTex, sizeof( cubeTex ) ) ;
}
// Generate the indices
if ( indices != NULL )
{
GLushort cubeIndices[] =
{
0, 2, 1,
0, 3, 2,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 15, 14,
12, 14, 13,
16, 17, 18,
16, 18, 19,
20, 23, 22,
20, 22, 21
};
*indices = malloc ( sizeof(GLushort) * numIndices );
memcpy( *indices, cubeIndices, sizeof( cubeIndices ) );
}
return numIndices;
}
| 010smithzhang-ddd | samples/gles2_book/Common/esShapes.c | C | bsd | 7,785 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// ESShader.c
//
// Utility functions for loading shaders and creating program objects.
//
///
// Includes
//
#include "esUtil.h"
#include <stdlib.h>
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
//
///
/// \brief Load a shader, check for compile errors, print error messages to output log
/// \param type Type of shader (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER)
/// \param shaderSrc Shader source string
/// \return A new shader object on success, 0 on failure
//
GLuint ESUTIL_API esLoadShader ( GLenum type, const char *shaderSrc )
{
GLuint shader;
GLint compiled;
// Create the shader object
shader = glCreateShader ( type );
if ( shader == 0 )
return 0;
// Load the shader source
glShaderSource ( shader, 1, &shaderSrc, NULL );
// Compile the shader
glCompileShader ( shader );
// Check the compile status
glGetShaderiv ( shader, GL_COMPILE_STATUS, &compiled );
if ( !compiled )
{
GLint infoLen = 0;
glGetShaderiv ( shader, GL_INFO_LOG_LENGTH, &infoLen );
if ( infoLen > 1 )
{
char* infoLog = malloc (sizeof(char) * infoLen );
glGetShaderInfoLog ( shader, infoLen, NULL, infoLog );
esLogMessage ( "Error compiling shader:\n%s\n", infoLog );
free ( infoLog );
}
glDeleteShader ( shader );
return 0;
}
return shader;
}
//
///
/// \brief Load a vertex and fragment shader, create a program object, link program.
// Errors output to log.
/// \param vertShaderSrc Vertex shader source code
/// \param fragShaderSrc Fragment shader source code
/// \return A new program object linked with the vertex/fragment shader pair, 0 on failure
//
GLuint ESUTIL_API esLoadProgram ( const char *vertShaderSrc, const char *fragShaderSrc )
{
GLuint vertexShader;
GLuint fragmentShader;
GLuint programObject;
GLint linked;
// Load the vertex/fragment shaders
vertexShader = esLoadShader ( GL_VERTEX_SHADER, vertShaderSrc );
if ( vertexShader == 0 )
return 0;
fragmentShader = esLoadShader ( GL_FRAGMENT_SHADER, fragShaderSrc );
if ( fragmentShader == 0 )
{
glDeleteShader( vertexShader );
return 0;
}
// Create the program object
programObject = glCreateProgram ( );
if ( programObject == 0 )
return 0;
glAttachShader ( programObject, vertexShader );
glAttachShader ( programObject, fragmentShader );
// Link the program
glLinkProgram ( programObject );
// Check the link status
glGetProgramiv ( programObject, GL_LINK_STATUS, &linked );
if ( !linked )
{
GLint infoLen = 0;
glGetProgramiv ( programObject, GL_INFO_LOG_LENGTH, &infoLen );
if ( infoLen > 1 )
{
char* infoLog = malloc (sizeof(char) * infoLen );
glGetProgramInfoLog ( programObject, infoLen, NULL, infoLog );
esLogMessage ( "Error linking program:\n%s\n", infoLog );
free ( infoLog );
}
glDeleteProgram ( programObject );
return 0;
}
// Free up no longer needed shader resources
glDeleteShader ( vertexShader );
glDeleteShader ( fragmentShader );
return programObject;
}
| 010smithzhang-ddd | samples/gles2_book/Common/esShader.c | C | bsd | 3,696 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
//
/// \file ESUtil.h
/// \brief A utility library for OpenGL ES. This library provides a
/// basic common framework for the example applications in the
/// OpenGL ES 2.0 Programming Guide.
//
#ifndef ESUTIL_H
#define ESUTIL_H
///
// Includes
//
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#ifdef __cplusplus
extern "C" {
#endif
///
// Macros
//
#define ESUTIL_API __cdecl
#define ESCALLBACK __cdecl
/// esCreateWindow flag - RGB color buffer
#define ES_WINDOW_RGB 0
/// esCreateWindow flag - ALPHA color buffer
#define ES_WINDOW_ALPHA 1
/// esCreateWindow flag - depth buffer
#define ES_WINDOW_DEPTH 2
/// esCreateWindow flag - stencil buffer
#define ES_WINDOW_STENCIL 4
/// esCreateWindow flag - multi-sample buffer
#define ES_WINDOW_MULTISAMPLE 8
/// esCreateWindow flag - EGL_POST_SUB_BUFFER_NV supported.
#define ES_WINDOW_POST_SUB_BUFFER_SUPPORTED 16
///
// Types
//
typedef struct
{
GLfloat m[4][4];
} ESMatrix;
typedef struct
{
/// Put your user data here...
void* userData;
/// Window width
GLint width;
/// Window height
GLint height;
/// Window handle
EGLNativeWindowType hWnd;
/// EGL display
EGLDisplay eglDisplay;
/// EGL context
EGLContext eglContext;
/// EGL surface
EGLSurface eglSurface;
/// Callbacks
void (ESCALLBACK *drawFunc) ( void* );
void (ESCALLBACK *keyFunc) ( void*, unsigned char, int, int );
void (ESCALLBACK *updateFunc) ( void*, float deltaTime );
} ESContext;
///
// Extensions
//
extern PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR;
extern PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR;
extern PFNEGLPOSTSUBBUFFERNVPROC eglPostSubBufferNV;
extern PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES;
extern PFNGLDELETEFENCESNVPROC glDeleteFencesNV;
extern PFNGLGENFENCESNVPROC glGenFencesNV;
extern PFNGLGETFENCEIVNVPROC glGetFenceivNV;
extern PFNGLISFENCENVPROC glIsFenceNV;
extern PFNGLFINISHFENCENVPROC glFinishFenceNV;
extern PFNGLSETFENCENVPROC glSetFenceNV;
extern PFNGLTESTFENCENVPROC glTestFenceNV;
///
// Public Functions
//
//
///
/// \brief Initialize ES framework context. This must be called before calling any other functions.
/// \param esContext Application context
//
void ESUTIL_API esInitContext ( ESContext *esContext );
//
/// \brief Create a window with the specified parameters
/// \param esContext Application context
/// \param title Name for title bar of window
/// \param width Width in pixels of window to create
/// \param height Height in pixels of window to create
/// \param flags Bitfield for the window creation flags
/// ES_WINDOW_RGB - specifies that the color buffer should have R,G,B channels
/// ES_WINDOW_ALPHA - specifies that the color buffer should have alpha
/// ES_WINDOW_DEPTH - specifies that a depth buffer should be created
/// ES_WINDOW_STENCIL - specifies that a stencil buffer should be created
/// ES_WINDOW_MULTISAMPLE - specifies that a multi-sample buffer should be created
/// ES_WINDOW_POST_SUB_BUFFER_SUPPORTED - specifies that EGL_POST_SUB_BUFFER_NV is supported.
/// \return GL_TRUE if window creation is succesful, GL_FALSE otherwise
GLboolean ESUTIL_API esCreateWindow ( ESContext *esContext, LPCTSTR title, GLint width, GLint height, GLuint flags );
//
/// \brief Start the main loop for the OpenGL ES application
/// \param esContext Application context
//
void ESUTIL_API esMainLoop ( ESContext *esContext );
//
/// \brief Register a draw callback function to be used to render each frame
/// \param esContext Application context
/// \param drawFunc Draw callback function that will be used to render the scene
//
void ESUTIL_API esRegisterDrawFunc ( ESContext *esContext, void (ESCALLBACK *drawFunc) ( ESContext* ) );
//
/// \brief Register an update callback function to be used to update on each time step
/// \param esContext Application context
/// \param updateFunc Update callback function that will be used to render the scene
//
void ESUTIL_API esRegisterUpdateFunc ( ESContext *esContext, void (ESCALLBACK *updateFunc) ( ESContext*, float ) );
//
/// \brief Register an keyboard input processing callback function
/// \param esContext Application context
/// \param keyFunc Key callback function for application processing of keyboard input
//
void ESUTIL_API esRegisterKeyFunc ( ESContext *esContext,
void (ESCALLBACK *drawFunc) ( ESContext*, unsigned char, int, int ) );
//
/// \brief Log a message to the debug output for the platform
/// \param formatStr Format string for error log.
//
void ESUTIL_API esLogMessage ( const char *formatStr, ... );
//
///
/// \brief Load a shader, check for compile errors, print error messages to output log
/// \param type Type of shader (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER)
/// \param shaderSrc Shader source string
/// \return A new shader object on success, 0 on failure
//
GLuint ESUTIL_API esLoadShader ( GLenum type, const char *shaderSrc );
//
///
/// \brief Load a vertex and fragment shader, create a program object, link program.
/// Errors output to log.
/// \param vertShaderSrc Vertex shader source code
/// \param fragShaderSrc Fragment shader source code
/// \return A new program object linked with the vertex/fragment shader pair, 0 on failure
//
GLuint ESUTIL_API esLoadProgram ( const char *vertShaderSrc, const char *fragShaderSrc );
//
/// \brief Generates geometry for a sphere. Allocates memory for the vertex data and stores
/// the results in the arrays. Generate index list for a TRIANGLE_STRIP
/// \param numSlices The number of slices in the sphere
/// \param vertices If not NULL, will contain array of float3 positions
/// \param normals If not NULL, will contain array of float3 normals
/// \param texCoords If not NULL, will contain array of float2 texCoords
/// \param indices If not NULL, will contain the array of indices for the triangle strip
/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
/// if it is not NULL ) as a GL_TRIANGLE_STRIP
//
int ESUTIL_API esGenSphere ( int numSlices, float radius, GLfloat **vertices, GLfloat **normals,
GLfloat **texCoords, GLushort **indices );
//
/// \brief Generates geometry for a cube. Allocates memory for the vertex data and stores
/// the results in the arrays. Generate index list for a TRIANGLES
/// \param scale The size of the cube, use 1.0 for a unit cube.
/// \param vertices If not NULL, will contain array of float3 positions
/// \param normals If not NULL, will contain array of float3 normals
/// \param texCoords If not NULL, will contain array of float2 texCoords
/// \param indices If not NULL, will contain the array of indices for the triangle strip
/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
/// if it is not NULL ) as a GL_TRIANGLES
//
int ESUTIL_API esGenCube ( float scale, GLfloat **vertices, GLfloat **normals,
GLfloat **texCoords, GLushort **indices );
//
/// \brief Loads a 24-bit TGA image from a file
/// \param fileName Name of the file on disk
/// \param width Width of loaded image in pixels
/// \param height Height of loaded image in pixels
/// \return Pointer to loaded image. NULL on failure.
//
char* ESUTIL_API esLoadTGA ( char *fileName, int *width, int *height );
//
/// \brief multiply matrix specified by result with a scaling matrix and return new matrix in result
/// \param result Specifies the input matrix. Scaled matrix is returned in result.
/// \param sx, sy, sz Scale factors along the x, y and z axes respectively
//
void ESUTIL_API esScale(ESMatrix *result, GLfloat sx, GLfloat sy, GLfloat sz);
//
/// \brief multiply matrix specified by result with a translation matrix and return new matrix in result
/// \param result Specifies the input matrix. Translated matrix is returned in result.
/// \param tx, ty, tz Scale factors along the x, y and z axes respectively
//
void ESUTIL_API esTranslate(ESMatrix *result, GLfloat tx, GLfloat ty, GLfloat tz);
//
/// \brief multiply matrix specified by result with a rotation matrix and return new matrix in result
/// \param result Specifies the input matrix. Rotated matrix is returned in result.
/// \param angle Specifies the angle of rotation, in degrees.
/// \param x, y, z Specify the x, y and z coordinates of a vector, respectively
//
void ESUTIL_API esRotate(ESMatrix *result, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
//
// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
/// \param result Specifies the input matrix. new matrix is returned in result.
/// \param left, right Coordinates for the left and right vertical clipping planes
/// \param bottom, top Coordinates for the bottom and top horizontal clipping planes
/// \param nearZ, farZ Distances to the near and far depth clipping planes. Both distances must be positive.
//
void ESUTIL_API esFrustum(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ);
//
/// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
/// \param result Specifies the input matrix. new matrix is returned in result.
/// \param fovy Field of view y angle in degrees
/// \param aspect Aspect ratio of screen
/// \param nearZ Near plane distance
/// \param farZ Far plane distance
//
void ESUTIL_API esPerspective(ESMatrix *result, float fovy, float aspect, float nearZ, float farZ);
//
/// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
/// \param result Specifies the input matrix. new matrix is returned in result.
/// \param left, right Coordinates for the left and right vertical clipping planes
/// \param bottom, top Coordinates for the bottom and top horizontal clipping planes
/// \param nearZ, farZ Distances to the near and far depth clipping planes. These values are negative if plane is behind the viewer
//
void ESUTIL_API esOrtho(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ);
//
/// \brief perform the following operation - result matrix = srcA matrix * srcB matrix
/// \param result Returns multiplied matrix
/// \param srcA, srcB Input matrices to be multiplied
//
void ESUTIL_API esMatrixMultiply(ESMatrix *result, ESMatrix *srcA, ESMatrix *srcB);
//
//// \brief return an indentity matrix
//// \param result returns identity matrix
//
void ESUTIL_API esMatrixLoadIdentity(ESMatrix *result);
#ifdef __cplusplus
}
#endif
#endif // ESUTIL_H
| 010smithzhang-ddd | samples/gles2_book/Common/esUtil.h | C | bsd | 11,194 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// ESUtil.c
//
// A utility library for OpenGL ES. This library provides a
// basic common framework for the example applications in the
// OpenGL ES 2.0 Programming Guide.
//
///
// Includes
//
#include <stdio.h>
#include <stdlib.h>
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "esUtil.h"
#include "esUtil_win.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4204) // nonstandard extension used : non-constant aggregate initializer
#endif
///
// Extensions
//
PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR;
PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR;
PFNEGLPOSTSUBBUFFERNVPROC eglPostSubBufferNV;
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES;
PFNGLDELETEFENCESNVPROC glDeleteFencesNV;
PFNGLGENFENCESNVPROC glGenFencesNV;
PFNGLGETFENCEIVNVPROC glGetFenceivNV;
PFNGLISFENCENVPROC glIsFenceNV;
PFNGLFINISHFENCENVPROC glFinishFenceNV;
PFNGLSETFENCENVPROC glSetFenceNV;
PFNGLTESTFENCENVPROC glTestFenceNV;
///
// CreateEGLContext()
//
// Creates an EGL rendering context and all associated elements
//
EGLBoolean CreateEGLContext ( EGLNativeWindowType hWnd, EGLDisplay* eglDisplay,
EGLContext* eglContext, EGLSurface* eglSurface,
EGLint* configAttribList, EGLint* surfaceAttribList)
{
EGLint numConfigs;
EGLint majorVersion;
EGLint minorVersion;
EGLDisplay display;
EGLContext context;
EGLSurface surface;
EGLConfig config;
EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };
// Get Display
display = eglGetDisplay(GetDC(hWnd));
if ( display == EGL_NO_DISPLAY )
{
return EGL_FALSE;
}
// Initialize EGL
if ( !eglInitialize(display, &majorVersion, &minorVersion) )
{
return EGL_FALSE;
}
// Bind to extensions
eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR");
eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR");
eglPostSubBufferNV = (PFNEGLPOSTSUBBUFFERNVPROC) eglGetProcAddress("eglPostSubBufferNV");
glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES");
glDeleteFencesNV = (PFNGLDELETEFENCESNVPROC) eglGetProcAddress("glDeleteFencesNV");
glGenFencesNV = (PFNGLGENFENCESNVPROC) eglGetProcAddress("glGenFencesNV");
glGetFenceivNV = (PFNGLGETFENCEIVNVPROC) eglGetProcAddress("glGetFenceivNV");
glIsFenceNV = (PFNGLISFENCENVPROC) eglGetProcAddress("glIsFenceNV");
glFinishFenceNV = (PFNGLFINISHFENCENVPROC) eglGetProcAddress("glFinishFenceNV");
glSetFenceNV = (PFNGLSETFENCENVPROC) eglGetProcAddress("glSetFenceNV");
glTestFenceNV = (PFNGLTESTFENCENVPROC) eglGetProcAddress("glTestFenceNV");
// Get configs
if ( !eglGetConfigs(display, NULL, 0, &numConfigs) )
{
return EGL_FALSE;
}
// Choose config
if ( !eglChooseConfig(display, configAttribList, &config, 1, &numConfigs) )
{
return EGL_FALSE;
}
// Create a surface
surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)hWnd, surfaceAttribList);
if ( surface == EGL_NO_SURFACE )
{
return EGL_FALSE;
}
// Create a GL context
context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs );
if ( context == EGL_NO_CONTEXT )
{
return EGL_FALSE;
}
// Make the context current
if ( !eglMakeCurrent(display, surface, surface, context) )
{
return EGL_FALSE;
}
*eglDisplay = display;
*eglSurface = surface;
*eglContext = context;
return EGL_TRUE;
}
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
///
// esInitContext()
//
// Initialize ES utility context. This must be called before calling any other
// functions.
//
void ESUTIL_API esInitContext ( ESContext *esContext )
{
if ( esContext != NULL )
{
memset( esContext, 0, sizeof( ESContext) );
}
}
///
// esCreateWindow()
//
// title - name for title bar of window
// width - width of window to create
// height - height of window to create
// flags - bitwise or of window creation flags
// ES_WINDOW_ALPHA - specifies that the framebuffer should have alpha
// ES_WINDOW_DEPTH - specifies that a depth buffer should be created
// ES_WINDOW_STENCIL - specifies that a stencil buffer should be created
// ES_WINDOW_MULTISAMPLE - specifies that a multi-sample buffer should be created
// ES_WINDOW_POST_SUB_BUFFER_SUPPORTED - specifies that EGL_POST_SUB_BUFFER_NV is supported.
//
GLboolean ESUTIL_API esCreateWindow ( ESContext *esContext, LPCTSTR title, GLint width, GLint height, GLuint flags )
{
EGLint configAttribList[] =
{
EGL_RED_SIZE, 5,
EGL_GREEN_SIZE, 6,
EGL_BLUE_SIZE, 5,
EGL_ALPHA_SIZE, (flags & ES_WINDOW_ALPHA) ? 8 : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (flags & ES_WINDOW_DEPTH) ? 8 : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (flags & ES_WINDOW_STENCIL) ? 8 : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, (flags & ES_WINDOW_MULTISAMPLE) ? 1 : 0,
EGL_NONE
};
EGLint surfaceAttribList[] =
{
EGL_POST_SUB_BUFFER_SUPPORTED_NV, flags & (ES_WINDOW_POST_SUB_BUFFER_SUPPORTED) ? EGL_TRUE : EGL_FALSE,
EGL_NONE, EGL_NONE
};
if ( esContext == NULL )
{
return GL_FALSE;
}
esContext->width = width;
esContext->height = height;
if ( !WinCreate ( esContext, title) )
{
return GL_FALSE;
}
if ( !CreateEGLContext ( esContext->hWnd,
&esContext->eglDisplay,
&esContext->eglContext,
&esContext->eglSurface,
configAttribList,
surfaceAttribList ) )
{
return GL_FALSE;
}
return GL_TRUE;
}
///
// esMainLoop()
//
// Start the main loop for the OpenGL ES application
//
void ESUTIL_API esMainLoop ( ESContext *esContext )
{
WinLoop ( esContext );
}
///
// esRegisterDrawFunc()
//
void ESUTIL_API esRegisterDrawFunc ( ESContext *esContext, void (ESCALLBACK *drawFunc) (ESContext* ) )
{
esContext->drawFunc = drawFunc;
}
///
// esRegisterUpdateFunc()
//
void ESUTIL_API esRegisterUpdateFunc ( ESContext *esContext, void (ESCALLBACK *updateFunc) ( ESContext*, float ) )
{
esContext->updateFunc = updateFunc;
}
///
// esRegisterKeyFunc()
//
void ESUTIL_API esRegisterKeyFunc ( ESContext *esContext,
void (ESCALLBACK *keyFunc) (ESContext*, unsigned char, int, int ) )
{
esContext->keyFunc = keyFunc;
}
///
// esLogMessage()
//
// Log an error message to the debug output for the platform
//
void ESUTIL_API esLogMessage ( const char *formatStr, ... )
{
va_list params;
char buf[BUFSIZ];
va_start ( params, formatStr );
vsprintf_s ( buf, sizeof(buf), formatStr, params );
printf ( "%s", buf );
va_end ( params );
}
///
// esLoadTGA()
//
// Loads a 24-bit TGA image from a file
//
char* ESUTIL_API esLoadTGA ( char *fileName, int *width, int *height )
{
char *buffer;
if ( WinTGALoad ( fileName, &buffer, width, height ) )
{
return buffer;
}
return NULL;
}
| 010smithzhang-ddd | samples/gles2_book/Common/esUtil.c | C | bsd | 7,697 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// esUtil_win32.c
//
// This file contains the Win32 implementation of the windowing functions.
///
// Includes
//
#include <windows.h>
#include "esUtil.h"
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
///
// ESWindowProc()
//
// Main window procedure
//
LRESULT WINAPI ESWindowProc ( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
LRESULT lRet = 1;
switch (uMsg)
{
case WM_CREATE:
break;
case WM_SIZE:
{
ESContext *esContext = (ESContext*)(LONG_PTR) GetWindowLongPtr ( hWnd, GWL_USERDATA );
if ( esContext ) {
esContext->width = LOWORD( lParam );
esContext->height = HIWORD( lParam );
InvalidateRect( esContext->hWnd, NULL, FALSE );
}
}
case WM_PAINT:
{
ESContext *esContext = (ESContext*)(LONG_PTR) GetWindowLongPtr ( hWnd, GWL_USERDATA );
if ( esContext && esContext->drawFunc )
esContext->drawFunc ( esContext );
if ( esContext )
ValidateRect( esContext->hWnd, NULL );
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_CHAR:
{
POINT point;
ESContext *esContext = (ESContext*)(LONG_PTR) GetWindowLongPtr ( hWnd, GWL_USERDATA );
GetCursorPos( &point );
if ( esContext && esContext->keyFunc )
esContext->keyFunc ( esContext, (unsigned char) wParam,
(int) point.x, (int) point.y );
}
break;
default:
lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
break;
}
return lRet;
}
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
///
// WinCreate()
//
// Create Win32 instance and window
//
GLboolean WinCreate ( ESContext *esContext, LPCTSTR title )
{
WNDCLASS wndclass = {0};
DWORD wStyle = 0;
RECT windowRect;
HINSTANCE hInstance = GetModuleHandle(NULL);
wndclass.style = CS_OWNDC;
wndclass.lpfnWndProc = (WNDPROC)ESWindowProc;
wndclass.hInstance = hInstance;
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.lpszClassName = TEXT("opengles2.0");
if (!RegisterClass (&wndclass) )
return FALSE;
wStyle = WS_VISIBLE | WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION | WS_SIZEBOX;
// Adjust the window rectangle so that the client area has
// the correct number of pixels
windowRect.left = 0;
windowRect.top = 0;
windowRect.right = esContext->width;
windowRect.bottom = esContext->height;
AdjustWindowRect ( &windowRect, wStyle, FALSE );
esContext->hWnd = CreateWindow(
TEXT("opengles2.0"),
title,
wStyle,
0,
0,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
NULL,
NULL,
hInstance,
NULL);
// Set the ESContext* to the GWL_USERDATA so that it is available to the
// ESWindowProc
SetWindowLongPtr ( esContext->hWnd, GWL_USERDATA, (LONG) (LONG_PTR) esContext );
if ( esContext->hWnd == NULL )
return GL_FALSE;
ShowWindow ( esContext->hWnd, TRUE );
return GL_TRUE;
}
///
// winLoop()
//
// Start main windows loop
//
void WinLoop ( ESContext *esContext )
{
MSG msg = { 0 };
int done = 0;
DWORD lastTime = GetTickCount();
while (!done)
{
int gotMsg = (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0);
DWORD curTime = GetTickCount();
float deltaTime = (float)( curTime - lastTime ) / 1000.0f;
lastTime = curTime;
if ( gotMsg )
{
if (msg.message==WM_QUIT)
{
done=1;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
SendMessage( esContext->hWnd, WM_PAINT, 0, 0 );
// Call update function if registered
if ( esContext->updateFunc != NULL )
esContext->updateFunc ( esContext, deltaTime );
}
}
| 010smithzhang-ddd | samples/gles2_book/Common/Win32/esUtil_win32.c | C | bsd | 4,788 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// esUtil_TGA.c
//
// This file contains the Win32 implementation of a TGA image loader
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
///
// Macros
//
#define INVERTED_BIT (1 << 5)
///
// Types
//
#pragma pack(push,x1) // Byte alignment (8-bit)
#pragma pack(1)
typedef struct
{
unsigned char IdSize,
MapType,
ImageType;
unsigned short PaletteStart,
PaletteSize;
unsigned char PaletteEntryDepth;
unsigned short X,
Y,
Width,
Height;
unsigned char ColorDepth,
Descriptor;
} TGA_HEADER;
#pragma pack(pop,x1)
////////////////////////////////////////////////////////////////////////////////////
//
// Private Functions
//
////////////////////////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
///
// WinTGALoad()
//
int WinTGALoad( const char *fileName, char **buffer, int *width, int *height )
{
FILE *fp;
TGA_HEADER Header;
if ( fopen_s ( &fp, fileName, "rb" ) != 0 )
{
return FALSE;
}
if ( fp == NULL )
{
return FALSE;
}
fread ( &Header, sizeof(TGA_HEADER), 1, fp );
*width = Header.Width;
*height = Header.Height;
if ( Header.ColorDepth == 24 )
{
RGBTRIPLE *Buffer24;
Buffer24= (RGBTRIPLE*)malloc(sizeof(RGBTRIPLE) * (*width) * (*height));
if(Buffer24)
{
int i=0;
int x,
y;
fread(Buffer24, sizeof(RGBTRIPLE), (*width) * (*height), fp);
*buffer= (LPSTR) malloc(3 * (*width) * (*height));
for ( y = 0; y < *height; y++ )
for( x = 0; x < *width; x++ )
{
int Index= y * (*width) + x;
if(!(Header.Descriptor & INVERTED_BIT))
Index= ((*height) - 1 - y) * (*width) + x;
(*buffer)[(i * 3)]= Buffer24[Index].rgbtRed;
(*buffer)[(i * 3) + 1]= Buffer24[Index].rgbtGreen;
(*buffer)[(i * 3) + 2]= Buffer24[Index].rgbtBlue;
i++;
}
fclose(fp);
free(Buffer24);
return(TRUE);
}
}
return(FALSE);
}
| 010smithzhang-ddd | samples/gles2_book/Common/Win32/esUtil_TGA.c | C | bsd | 2,618 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// esUtil_win.h
//
// API-neutral interface for creating windows. Implementation needs to be provided per-platform.
#ifndef ESUTIL_WIN_H
#define ESUTIL_WIN_H
///
// Includes
//
#ifdef __cplusplus
extern "C" {
#endif
///
// Macros
//
///
// Types
//
///
// Public Functions
//
///
// WinCreate()
//
// Create Win32 instance and window
//
GLboolean WinCreate ( ESContext *esContext, LPCTSTR title );
///
// WinLoop()
//
// Start main windows loop
//
void WinLoop ( ESContext *esContext );
///
// WinTGALoad()
//
// TGA loader win32 implementation
//
int WinTGALoad ( const char *fileName, char **buffer, int *width, int *height );
#ifdef __cplusplus
}
#endif
#endif // ESUTIL_WIN_H
| 010smithzhang-ddd | samples/gles2_book/Common/esUtil_win.h | C | bsd | 1,030 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// ESUtil.c
//
// A utility library for OpenGL ES. This library provides a
// basic common framework for the example applications in the
// OpenGL ES 2.0 Programming Guide.
//
///
// Includes
//
#include "esUtil.h"
#include <math.h>
#define PI 3.1415926535897932384626433832795f
void ESUTIL_API
esScale(ESMatrix *result, GLfloat sx, GLfloat sy, GLfloat sz)
{
result->m[0][0] *= sx;
result->m[0][1] *= sx;
result->m[0][2] *= sx;
result->m[0][3] *= sx;
result->m[1][0] *= sy;
result->m[1][1] *= sy;
result->m[1][2] *= sy;
result->m[1][3] *= sy;
result->m[2][0] *= sz;
result->m[2][1] *= sz;
result->m[2][2] *= sz;
result->m[2][3] *= sz;
}
void ESUTIL_API
esTranslate(ESMatrix *result, GLfloat tx, GLfloat ty, GLfloat tz)
{
result->m[3][0] += (result->m[0][0] * tx + result->m[1][0] * ty + result->m[2][0] * tz);
result->m[3][1] += (result->m[0][1] * tx + result->m[1][1] * ty + result->m[2][1] * tz);
result->m[3][2] += (result->m[0][2] * tx + result->m[1][2] * ty + result->m[2][2] * tz);
result->m[3][3] += (result->m[0][3] * tx + result->m[1][3] * ty + result->m[2][3] * tz);
}
void ESUTIL_API
esRotate(ESMatrix *result, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
{
GLfloat sinAngle, cosAngle;
GLfloat mag = sqrtf(x * x + y * y + z * z);
sinAngle = sinf ( angle * PI / 180.0f );
cosAngle = cosf ( angle * PI / 180.0f );
if ( mag > 0.0f )
{
GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
GLfloat oneMinusCos;
ESMatrix rotMat;
x /= mag;
y /= mag;
z /= mag;
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * sinAngle;
ys = y * sinAngle;
zs = z * sinAngle;
oneMinusCos = 1.0f - cosAngle;
rotMat.m[0][0] = (oneMinusCos * xx) + cosAngle;
rotMat.m[0][1] = (oneMinusCos * xy) - zs;
rotMat.m[0][2] = (oneMinusCos * zx) + ys;
rotMat.m[0][3] = 0.0F;
rotMat.m[1][0] = (oneMinusCos * xy) + zs;
rotMat.m[1][1] = (oneMinusCos * yy) + cosAngle;
rotMat.m[1][2] = (oneMinusCos * yz) - xs;
rotMat.m[1][3] = 0.0F;
rotMat.m[2][0] = (oneMinusCos * zx) - ys;
rotMat.m[2][1] = (oneMinusCos * yz) + xs;
rotMat.m[2][2] = (oneMinusCos * zz) + cosAngle;
rotMat.m[2][3] = 0.0F;
rotMat.m[3][0] = 0.0F;
rotMat.m[3][1] = 0.0F;
rotMat.m[3][2] = 0.0F;
rotMat.m[3][3] = 1.0F;
esMatrixMultiply( result, &rotMat, result );
}
}
void ESUTIL_API
esFrustum(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ)
{
float deltaX = right - left;
float deltaY = top - bottom;
float deltaZ = farZ - nearZ;
ESMatrix frust;
if ( (nearZ <= 0.0f) || (farZ <= 0.0f) ||
(deltaX <= 0.0f) || (deltaY <= 0.0f) || (deltaZ <= 0.0f) )
return;
frust.m[0][0] = 2.0f * nearZ / deltaX;
frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
frust.m[1][1] = 2.0f * nearZ / deltaY;
frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
frust.m[2][0] = (right + left) / deltaX;
frust.m[2][1] = (top + bottom) / deltaY;
frust.m[2][2] = -(nearZ + farZ) / deltaZ;
frust.m[2][3] = -1.0f;
frust.m[3][2] = -2.0f * nearZ * farZ / deltaZ;
frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
esMatrixMultiply(result, &frust, result);
}
void ESUTIL_API
esPerspective(ESMatrix *result, float fovy, float aspect, float nearZ, float farZ)
{
GLfloat frustumW, frustumH;
frustumH = tanf( fovy / 360.0f * PI ) * nearZ;
frustumW = frustumH * aspect;
esFrustum( result, -frustumW, frustumW, -frustumH, frustumH, nearZ, farZ );
}
void ESUTIL_API
esOrtho(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ)
{
float deltaX = right - left;
float deltaY = top - bottom;
float deltaZ = farZ - nearZ;
ESMatrix ortho;
if ( (deltaX == 0.0f) || (deltaY == 0.0f) || (deltaZ == 0.0f) )
return;
esMatrixLoadIdentity(&ortho);
ortho.m[0][0] = 2.0f / deltaX;
ortho.m[3][0] = -(right + left) / deltaX;
ortho.m[1][1] = 2.0f / deltaY;
ortho.m[3][1] = -(top + bottom) / deltaY;
ortho.m[2][2] = -2.0f / deltaZ;
ortho.m[3][2] = -(nearZ + farZ) / deltaZ;
esMatrixMultiply(result, &ortho, result);
}
void ESUTIL_API
esMatrixMultiply(ESMatrix *result, ESMatrix *srcA, ESMatrix *srcB)
{
ESMatrix tmp = { 0.0f };
int i;
for (i=0; i<4; i++)
{
tmp.m[i][0] = (srcA->m[i][0] * srcB->m[0][0]) +
(srcA->m[i][1] * srcB->m[1][0]) +
(srcA->m[i][2] * srcB->m[2][0]) +
(srcA->m[i][3] * srcB->m[3][0]) ;
tmp.m[i][1] = (srcA->m[i][0] * srcB->m[0][1]) +
(srcA->m[i][1] * srcB->m[1][1]) +
(srcA->m[i][2] * srcB->m[2][1]) +
(srcA->m[i][3] * srcB->m[3][1]) ;
tmp.m[i][2] = (srcA->m[i][0] * srcB->m[0][2]) +
(srcA->m[i][1] * srcB->m[1][2]) +
(srcA->m[i][2] * srcB->m[2][2]) +
(srcA->m[i][3] * srcB->m[3][2]) ;
tmp.m[i][3] = (srcA->m[i][0] * srcB->m[0][3]) +
(srcA->m[i][1] * srcB->m[1][3]) +
(srcA->m[i][2] * srcB->m[2][3]) +
(srcA->m[i][3] * srcB->m[3][3]) ;
}
memcpy(result, &tmp, sizeof(ESMatrix));
}
void ESUTIL_API
esMatrixLoadIdentity(ESMatrix *result)
{
memset(result, 0x0, sizeof(ESMatrix));
result->m[0][0] = 1.0f;
result->m[1][1] = 1.0f;
result->m[2][2] = 1.0f;
result->m[3][3] = 1.0f;
}
| 010smithzhang-ddd | samples/gles2_book/Common/esTransform.c | C | bsd | 5,863 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Simple_VertexShader.c
//
// This is a simple example that draws a rotating cube in perspective
// using a vertex shader to transform the object
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
// Uniform locations
GLint mvpLoc;
// Vertex daata
GLfloat *vertices;
GLushort *indices;
int numIndices;
// Rotation angle
GLfloat angle;
// MVP matrix
ESMatrix mvpMatrix;
} UserData;
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"uniform mat4 u_mvpMatrix; \n"
"attribute vec4 a_position; \n"
"void main() \n"
"{ \n"
" gl_Position = u_mvpMatrix * a_position; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"void main() \n"
"{ \n"
" gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); \n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
// Get the uniform locations
userData->mvpLoc = glGetUniformLocation( userData->programObject, "u_mvpMatrix" );
// Generate the vertex data
userData->numIndices = esGenCube( 1.0, &userData->vertices,
NULL, NULL, &userData->indices );
// Starting rotation angle for the cube
userData->angle = 45.0f;
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Update MVP matrix based on time
//
void Update ( ESContext *esContext, float deltaTime )
{
UserData *userData = (UserData*) esContext->userData;
ESMatrix perspective;
ESMatrix modelview;
float aspect;
// Compute a rotation angle based on time to rotate the cube
userData->angle += ( deltaTime * 40.0f );
if( userData->angle >= 360.0f )
userData->angle -= 360.0f;
// Compute the window aspect ratio
aspect = (GLfloat) esContext->width / (GLfloat) esContext->height;
// Generate a perspective matrix with a 60 degree FOV
esMatrixLoadIdentity( &perspective );
esPerspective( &perspective, 60.0f, aspect, 1.0f, 20.0f );
// Generate a model view matrix to rotate/translate the cube
esMatrixLoadIdentity( &modelview );
// Translate away from the viewer
esTranslate( &modelview, 0.0, 0.0, -2.0 );
// Rotate the cube
esRotate( &modelview, userData->angle, 1.0, 0.0, 1.0 );
// Compute the final MVP by multiplying the
// modevleiw and perspective matrices together
esMatrixMultiply( &userData->mvpMatrix, &modelview, &perspective );
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 3 * sizeof(GLfloat), userData->vertices );
glEnableVertexAttribArray ( userData->positionLoc );
// Load the MVP matrix
glUniformMatrix4fv( userData->mvpLoc, 1, GL_FALSE, (GLfloat*) &userData->mvpMatrix.m[0][0] );
// Draw the cube
glDrawElements ( GL_TRIANGLES, userData->numIndices, GL_UNSIGNED_SHORT, userData->indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
if ( userData->vertices != NULL )
{
free ( userData->vertices );
}
if ( userData->indices != NULL )
{
free ( userData->indices );
}
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Simple Vertex Shader"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esRegisterUpdateFunc ( &esContext, Update );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/Simple_VertexShader/Simple_VertexShader.c | C | bsd | 5,248 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Hello_Triangle.c
//
// This is a simple example that draws a single triangle with
// a minimal vertex/fragment shader. The purpose of this
// example is to demonstrate the basic concepts of
// OpenGL ES 2.0 rendering.
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
} UserData;
///
// Create a shader object, load the shader source, and
// compile the shader.
//
GLuint LoadShader ( GLenum type, const char *shaderSrc )
{
GLuint shader;
GLint compiled;
// Create the shader object
shader = glCreateShader ( type );
if ( shader == 0 )
return 0;
// Load the shader source
glShaderSource ( shader, 1, &shaderSrc, NULL );
// Compile the shader
glCompileShader ( shader );
// Check the compile status
glGetShaderiv ( shader, GL_COMPILE_STATUS, &compiled );
if ( !compiled )
{
GLint infoLen = 0;
glGetShaderiv ( shader, GL_INFO_LOG_LENGTH, &infoLen );
if ( infoLen > 1 )
{
char* infoLog = malloc (sizeof(char) * infoLen );
glGetShaderInfoLog ( shader, infoLen, NULL, infoLog );
esLogMessage ( "Error compiling shader:\n%s\n", infoLog );
free ( infoLog );
}
glDeleteShader ( shader );
return 0;
}
return shader;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 vPosition; \n"
"void main() \n"
"{ \n"
" gl_Position = vPosition; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float;\n"\
"void main() \n"
"{ \n"
" gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n"
"} \n";
GLuint vertexShader;
GLuint fragmentShader;
GLuint programObject;
GLint linked;
// Load the vertex/fragment shaders
vertexShader = LoadShader ( GL_VERTEX_SHADER, vShaderStr );
fragmentShader = LoadShader ( GL_FRAGMENT_SHADER, fShaderStr );
// Create the program object
programObject = glCreateProgram ( );
if ( programObject == 0 )
return 0;
glAttachShader ( programObject, vertexShader );
glAttachShader ( programObject, fragmentShader );
// Bind vPosition to attribute 0
glBindAttribLocation ( programObject, 0, "vPosition" );
// Link the program
glLinkProgram ( programObject );
// Check the link status
glGetProgramiv ( programObject, GL_LINK_STATUS, &linked );
if ( !linked )
{
GLint infoLen = 0;
glGetProgramiv ( programObject, GL_INFO_LOG_LENGTH, &infoLen );
if ( infoLen > 1 )
{
char* infoLog = malloc (sizeof(char) * infoLen );
glGetProgramInfoLog ( programObject, infoLen, NULL, infoLog );
esLogMessage ( "Error linking program:\n%s\n", infoLog );
free ( infoLog );
}
glDeleteProgram ( programObject );
return FALSE;
}
// Store the program object
userData->programObject = programObject;
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLfloat vVertices[] = { 0.0f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex data
glVertexAttribPointer ( 0, 3, GL_FLOAT, GL_FALSE, 0, vVertices );
glEnableVertexAttribArray ( 0 );
glDrawArrays ( GL_TRIANGLES, 0, 3 );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Hello Triangle"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/Hello_Triangle/Hello_Triangle.c | C | bsd | 4,836 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Simple_TextureCubemap.c
//
// This is a simple example that draws a sphere with a cubemap image applied.
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint normalLoc;
// Sampler location
GLint samplerLoc;
// Texture handle
GLuint textureId;
// Vertex data
int numIndices;
GLfloat *vertices;
GLfloat *normals;
GLushort *indices;
} UserData;
///
// Create a simple cubemap with a 1x1 face with a different
// color for each face
GLuint CreateSimpleTextureCubemap( )
{
GLuint textureId;
// Six 1x1 RGB faces
GLubyte cubePixels[6][3] =
{
// Face 0 - Red
255, 0, 0,
// Face 1 - Green,
0, 255, 0,
// Face 3 - Blue
0, 0, 255,
// Face 4 - Yellow
255, 255, 0,
// Face 5 - Purple
255, 0, 255,
// Face 6 - White
255, 255, 255
};
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_CUBE_MAP, textureId );
// Load the cube face - Positive X
glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[0] );
// Load the cube face - Negative X
glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[1] );
// Load the cube face - Positive Y
glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[2] );
// Load the cube face - Negative Y
glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[3] );
// Load the cube face - Positive Z
glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[4] );
// Load the cube face - Negative Z
glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[5] );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri ( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 a_position; \n"
"attribute vec3 a_normal; \n"
"varying vec3 v_normal; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_normal = a_normal; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec3 v_normal; \n"
"uniform samplerCube s_texture; \n"
"void main() \n"
"{ \n"
" gl_FragColor = textureCube( s_texture, v_normal );\n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->normalLoc = glGetAttribLocation ( userData->programObject, "a_normal" );
// Get the sampler locations
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Load the texture
userData->textureId = CreateSimpleTextureCubemap ();
// Generate the vertex data
userData->numIndices = esGenSphere ( 20, 0.75f, &userData->vertices, &userData->normals,
NULL, &userData->indices );
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
glCullFace ( GL_BACK );
glEnable ( GL_CULL_FACE );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 0, userData->vertices );
// Load the normal
glVertexAttribPointer ( userData->normalLoc, 3, GL_FLOAT,
GL_FALSE, 0, userData->normals );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->normalLoc );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_CUBE_MAP, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
glDrawElements ( GL_TRIANGLES, userData->numIndices,
GL_UNSIGNED_SHORT, userData->indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
free ( userData->vertices );
free ( userData->normals );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Simple Texture Cubemap"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/Simple_TextureCubemap/Simple_TextureCubemap.c | C | bsd | 6,440 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// MultiTexture.c
//
// This is an example that draws a quad with a basemap and
// lightmap to demonstrate multitexturing.
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler locations
GLint baseMapLoc;
GLint lightMapLoc;
// Texture handle
GLuint baseMapTexId;
GLuint lightMapTexId;
} UserData;
///
// Load texture from disk
//
GLuint LoadTexture ( char *fileName )
{
int width,
height;
char *buffer = esLoadTGA ( fileName, &width, &height );
GLuint texId;
if ( buffer == NULL )
{
esLogMessage ( "Error loading (%s) image.\n", fileName );
return 0;
}
glGenTextures ( 1, &texId );
glBindTexture ( GL_TEXTURE_2D, texId );
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
free ( buffer );
return texId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_baseMap; \n"
"uniform sampler2D s_lightMap; \n"
"void main() \n"
"{ \n"
" vec4 baseColor; \n"
" vec4 lightColor; \n"
" \n"
" baseColor = texture2D( s_baseMap, v_texCoord ); \n"
" lightColor = texture2D( s_lightMap, v_texCoord ); \n"
" gl_FragColor = baseColor * (lightColor + 0.25); \n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
// Get the sampler location
userData->baseMapLoc = glGetUniformLocation ( userData->programObject, "s_baseMap" );
userData->lightMapLoc = glGetUniformLocation ( userData->programObject, "s_lightMap" );
// Load the textures
userData->baseMapTexId = LoadTexture ( "basemap.tga" );
userData->lightMapTexId = LoadTexture ( "lightmap.tga" );
if ( userData->baseMapTexId == 0 || userData->lightMapTexId == 0 )
return FALSE;
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLfloat vVertices[] = { -0.5f, 0.5f, 0.0f, // Position 0
0.0f, 0.0f, // TexCoord 0
-0.5f, -0.5f, 0.0f, // Position 1
0.0f, 1.0f, // TexCoord 1
0.5f, -0.5f, 0.0f, // Position 2
1.0f, 1.0f, // TexCoord 2
0.5f, 0.5f, 0.0f, // Position 3
1.0f, 0.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
// Bind the base map
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->baseMapTexId );
// Set the base map sampler to texture unit to 0
glUniform1i ( userData->baseMapLoc, 0 );
// Bind the light map
glActiveTexture ( GL_TEXTURE1 );
glBindTexture ( GL_TEXTURE_2D, userData->lightMapTexId );
// Set the light map sampler to texture unit 1
glUniform1i ( userData->lightMapLoc, 1 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->baseMapTexId );
glDeleteTextures ( 1, &userData->lightMapTexId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("MultiTexture"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/MultiTexture/MultiTexture.c | C | bsd | 6,478 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// TextureWrap.c
//
// This is an example that demonstrates the three texture
// wrap modes available on 2D textures
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler location
GLint samplerLoc;
// Offset location
GLint offsetLoc;
// Texture handle
GLuint textureId;
} UserData;
///
// Generate an RGB8 checkerboard image
//
GLubyte* GenCheckImage( int width, int height, int checkSize )
{
int x,
y;
GLubyte *pixels = malloc( width * height * 3 );
if ( pixels == NULL )
return NULL;
for ( y = 0; y < height; y++ )
for ( x = 0; x < width; x++ )
{
GLubyte rColor = 0;
GLubyte bColor = 0;
if ( ( x / checkSize ) % 2 == 0 )
{
rColor = 255 * ( ( y / checkSize ) % 2 );
bColor = 255 * ( 1 - ( ( y / checkSize ) % 2 ) );
}
else
{
bColor = 255 * ( ( y / checkSize ) % 2 );
rColor = 255 * ( 1 - ( ( y / checkSize ) % 2 ) );
}
pixels[(y * height + x) * 3] = rColor;
pixels[(y * height + x) * 3 + 1] = 0;
pixels[(y * height + x) * 3 + 2] = bColor;
}
return pixels;
}
///
// Create a mipmapped 2D texture image
//
GLuint CreateTexture2D( )
{
// Texture object handle
GLuint textureId;
int width = 256,
height = 256;
GLubyte *pixels;
pixels = GenCheckImage( width, height, 64 );
if ( pixels == NULL )
return 0;
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_2D, textureId );
// Load mipmap level 0
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGB, GL_UNSIGNED_BYTE, pixels );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"uniform float u_offset; \n"
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" gl_Position.x += u_offset;\n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D( s_texture, v_texCoord );\n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
// Get the sampler location
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Get the offset location
userData->offsetLoc = glGetUniformLocation( userData->programObject, "u_offset" );
// Load the texture
userData->textureId = CreateTexture2D ();
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLfloat vVertices[] = { -0.3f, 0.3f, 0.0f, 1.0f, // Position 0
-1.0f, -1.0f, // TexCoord 0
-0.3f, -0.3f, 0.0f, 1.0f, // Position 1
-1.0f, 2.0f, // TexCoord 1
0.3f, -0.3f, 0.0f, 1.0f, // Position 2
2.0f, 2.0f, // TexCoord 2
0.3f, 0.3f, 0.0f, 1.0f, // Position 3
2.0f, -1.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 4, GL_FLOAT,
GL_FALSE, 6 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 6 * sizeof(GLfloat), &vVertices[4] );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
// Draw quad with repeat wrap mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
glUniform1f ( userData->offsetLoc, -0.7f );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
// Draw quad with clamp to edge wrap mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glUniform1f ( userData->offsetLoc, 0.0f );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
// Draw quad with mirrored repeat
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
glUniform1f ( userData->offsetLoc, 0.7f );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Texture Wrap"), 640, 480, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/TextureWrap/TextureWrap.c | C | bsd | 7,471 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Simple_Texture2D.c
//
// This is a simple example that draws a quad with a 2D
// texture image. The purpose of this example is to demonstrate
// the basics of 2D texturing
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler location
GLint samplerLoc;
// Texture handle
GLuint textureId;
} UserData;
///
// Create a simple 2x2 texture image with four different colors
//
GLuint CreateSimpleTexture2D( )
{
// Texture object handle
GLuint textureId;
// 2x2 Image, 3 bytes per pixel (R, G, B)
GLubyte pixels[4 * 3] =
{
255, 0, 0, // Red
0, 255, 0, // Green
0, 0, 255, // Blue
255, 255, 0 // Yellow
};
// Use tightly packed data
glPixelStorei ( GL_UNPACK_ALIGNMENT, 1 );
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_2D, textureId );
// Load the texture
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D( s_texture, v_texCoord );\n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
// Get the sampler location
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Load the texture
userData->textureId = CreateSimpleTexture2D ();
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLfloat vVertices[] = { -0.5f, 0.5f, 0.0f, // Position 0
0.0f, 0.0f, // TexCoord 0
-0.5f, -0.5f, 0.0f, // Position 1
0.0f, 1.0f, // TexCoord 1
0.5f, -0.5f, 0.0f, // Position 2
1.0f, 1.0f, // TexCoord 2
0.5f, 0.5f, 0.0f, // Position 3
1.0f, 0.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Simple Texture 2D"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/Simple_Texture2D/Simple_Texture2D.c | C | bsd | 5,656 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// MipMap2D.c
//
// This is a simple example that demonstrates generating a mipmap chain
// and rendering with it
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler location
GLint samplerLoc;
// Offset location
GLint offsetLoc;
// Texture handle
GLuint textureId;
} UserData;
///
// From an RGB8 source image, generate the next level mipmap
//
GLboolean GenMipMap2D( GLubyte *src, GLubyte **dst, int srcWidth, int srcHeight, int *dstWidth, int *dstHeight )
{
int x,
y;
int texelSize = 3;
*dstWidth = srcWidth / 2;
if ( *dstWidth <= 0 )
*dstWidth = 1;
*dstHeight = srcHeight / 2;
if ( *dstHeight <= 0 )
*dstHeight = 1;
*dst = malloc ( sizeof(GLubyte) * texelSize * (*dstWidth) * (*dstHeight) );
if ( *dst == NULL )
return GL_FALSE;
for ( y = 0; y < *dstHeight; y++ )
{
for( x = 0; x < *dstWidth; x++ )
{
int srcIndex[4];
float r = 0.0f,
g = 0.0f,
b = 0.0f;
int sample;
// Compute the offsets for 2x2 grid of pixels in previous
// image to perform box filter
srcIndex[0] =
(((y * 2) * srcWidth) + (x * 2)) * texelSize;
srcIndex[1] =
(((y * 2) * srcWidth) + (x * 2 + 1)) * texelSize;
srcIndex[2] =
((((y * 2) + 1) * srcWidth) + (x * 2)) * texelSize;
srcIndex[3] =
((((y * 2) + 1) * srcWidth) + (x * 2 + 1)) * texelSize;
// Sum all pixels
for ( sample = 0; sample < 4; sample++ )
{
r += src[srcIndex[sample]];
g += src[srcIndex[sample] + 1];
b += src[srcIndex[sample] + 2];
}
// Average results
r /= 4.0;
g /= 4.0;
b /= 4.0;
// Store resulting pixels
(*dst)[ ( y * (*dstWidth) + x ) * texelSize ] = (GLubyte)( r );
(*dst)[ ( y * (*dstWidth) + x ) * texelSize + 1] = (GLubyte)( g );
(*dst)[ ( y * (*dstWidth) + x ) * texelSize + 2] = (GLubyte)( b );
}
}
return GL_TRUE;
}
///
// Generate an RGB8 checkerboard image
//
GLubyte* GenCheckImage( int width, int height, int checkSize )
{
int x,
y;
GLubyte *pixels = malloc( width * height * 3 );
if ( pixels == NULL )
return NULL;
for ( y = 0; y < height; y++ )
for ( x = 0; x < width; x++ )
{
GLubyte rColor = 0;
GLubyte bColor = 0;
if ( ( x / checkSize ) % 2 == 0 )
{
rColor = 255 * ( ( y / checkSize ) % 2 );
bColor = 255 * ( 1 - ( ( y / checkSize ) % 2 ) );
}
else
{
bColor = 255 * ( ( y / checkSize ) % 2 );
rColor = 255 * ( 1 - ( ( y / checkSize ) % 2 ) );
}
pixels[(y * height + x) * 3] = rColor;
pixels[(y * height + x) * 3 + 1] = 0;
pixels[(y * height + x) * 3 + 2] = bColor;
}
return pixels;
}
///
// Create a mipmapped 2D texture image
//
GLuint CreateMipMappedTexture2D( )
{
// Texture object handle
GLuint textureId;
int width = 256,
height = 256;
int level;
GLubyte *pixels;
GLubyte *prevImage;
GLubyte *newImage = NULL;
pixels = GenCheckImage( width, height, 8 );
if ( pixels == NULL )
return 0;
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_2D, textureId );
// Load mipmap level 0
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGB, GL_UNSIGNED_BYTE, pixels );
level = 1;
prevImage = &pixels[0];
while ( width > 1 && height > 1 )
{
int newWidth,
newHeight;
// Generate the next mipmap level
GenMipMap2D( prevImage, &newImage, width, height,
&newWidth, &newHeight );
// Load the mipmap level
glTexImage2D( GL_TEXTURE_2D, level, GL_RGB,
newWidth, newHeight, 0, GL_RGB,
GL_UNSIGNED_BYTE, newImage );
// Free the previous image
free ( prevImage );
// Set the previous image for the next iteration
prevImage = newImage;
level++;
// Half the width and height
width = newWidth;
height = newHeight;
}
free ( newImage );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"uniform float u_offset; \n"
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" gl_Position.x += u_offset;\n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D( s_texture, v_texCoord );\n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
// Get the sampler location
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Get the offset location
userData->offsetLoc = glGetUniformLocation( userData->programObject, "u_offset" );
// Load the texture
userData->textureId = CreateMipMappedTexture2D ();
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLfloat vVertices[] = { -0.5f, 0.5f, 0.0f, 1.5f, // Position 0
0.0f, 0.0f, // TexCoord 0
-0.5f, -0.5f, 0.0f, 0.75f, // Position 1
0.0f, 1.0f, // TexCoord 1
0.5f, -0.5f, 0.0f, 0.75f, // Position 2
1.0f, 1.0f, // TexCoord 2
0.5f, 0.5f, 0.0f, 1.5f, // Position 3
1.0f, 0.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 4, GL_FLOAT,
GL_FALSE, 6 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 6 * sizeof(GLfloat), &vVertices[4] );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
// Draw quad with nearest sampling
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glUniform1f ( userData->offsetLoc, -0.6f );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
// Draw quad with trilinear filtering
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glUniform1f ( userData->offsetLoc, 0.6f );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("MipMap 2D"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/MipMap2D/MipMap2D.c | C | bsd | 9,650 |
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Stencil_Test.c
//
// This example shows various stencil buffer
// operations.
//
#include <stdlib.h>
#include "esUtil.h"
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
// Uniform locations
GLint colorLoc;
} UserData;
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 a_position; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"uniform vec4 u_color; \n"
"void main() \n"
"{ \n"
" gl_FragColor = u_color; \n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
// Get the sampler location
userData->colorLoc = glGetUniformLocation ( userData->programObject, "u_color" );
// Set the clear color
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
// Set the stencil clear value
glClearStencil ( 0x1 );
// Set the depth clear value
glClearDepthf( 0.75f );
// Enable the depth and stencil tests
glEnable( GL_DEPTH_TEST );
glEnable( GL_STENCIL_TEST );
return TRUE;
}
///
// Initialize the stencil buffer values, and then use those
// values to control rendering
//
void Draw ( ESContext *esContext )
{
int i;
UserData *userData = esContext->userData;
GLfloat vVertices[] = {
-0.75f, 0.25f, 0.50f, // Quad #0
-0.25f, 0.25f, 0.50f,
-0.25f, 0.75f, 0.50f,
-0.75f, 0.75f, 0.50f,
0.25f, 0.25f, 0.90f, // Quad #1
0.75f, 0.25f, 0.90f,
0.75f, 0.75f, 0.90f,
0.25f, 0.75f, 0.90f,
-0.75f, -0.75f, 0.50f, // Quad #2
-0.25f, -0.75f, 0.50f,
-0.25f, -0.25f, 0.50f,
-0.75f, -0.25f, 0.50f,
0.25f, -0.75f, 0.50f, // Quad #3
0.75f, -0.75f, 0.50f,
0.75f, -0.25f, 0.50f,
0.25f, -0.25f, 0.50f,
-1.00f, -1.00f, 0.00f, // Big Quad
1.00f, -1.00f, 0.00f,
1.00f, 1.00f, 0.00f,
-1.00f, 1.00f, 0.00f
};
GLubyte indices[][6] = {
{ 0, 1, 2, 0, 2, 3 }, // Quad #0
{ 4, 5, 6, 4, 6, 7 }, // Quad #1
{ 8, 9, 10, 8, 10, 11 }, // Quad #2
{ 12, 13, 14, 12, 14, 15 }, // Quad #3
{ 16, 17, 18, 16, 18, 19 } // Big Quad
};
#define NumTests 4
GLfloat colors[NumTests][4] = {
{ 1.0f, 0.0f, 0.0f, 1.0f },
{ 0.0f, 1.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f, 1.0f },
{ 1.0f, 1.0f, 0.0f, 0.0f }
};
GLint numStencilBits;
GLuint stencilValues[NumTests] = {
0x7, // Result of test 0
0x0, // Result of test 1
0x2, // Result of test 2
0xff // Result of test 3. We need to fill this
// value in a run-time
};
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color, depth, and stencil buffers. At this
// point, the stencil buffer will be 0x1 for all pixels
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 0, vVertices );
glEnableVertexAttribArray ( userData->positionLoc );
// Test 0:
//
// Initialize upper-left region. In this case, the
// stencil-buffer values will be replaced because the
// stencil test for the rendered pixels will fail the
// stencil test, which is
//
// ref mask stencil mask
// ( 0x7 & 0x3 ) < ( 0x1 & 0x7 )
//
// The value in the stencil buffer for these pixels will
// be 0x7.
//
glStencilFunc( GL_LESS, 0x7, 0x3 );
glStencilOp( GL_REPLACE, GL_DECR, GL_DECR );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[0] );
// Test 1:
//
// Initialize the upper-right region. Here, we'll decrement
// the stencil-buffer values where the stencil test passes
// but the depth test fails. The stencil test is
//
// ref mask stencil mask
// ( 0x3 & 0x3 ) > ( 0x1 & 0x3 )
//
// but where the geometry fails the depth test. The
// stencil values for these pixels will be 0x0.
//
glStencilFunc( GL_GREATER, 0x3, 0x3 );
glStencilOp( GL_KEEP, GL_DECR, GL_KEEP );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[1] );
// Test 2:
//
// Initialize the lower-left region. Here we'll increment
// (with saturation) the stencil value where both the
// stencil and depth tests pass. The stencil test for
// these pixels will be
//
// ref mask stencil mask
// ( 0x1 & 0x3 ) == ( 0x1 & 0x3 )
//
// The stencil values for these pixels will be 0x2.
//
glStencilFunc( GL_EQUAL, 0x1, 0x3 );
glStencilOp( GL_KEEP, GL_INCR, GL_INCR );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[2] );
// Test 3:
//
// Finally, initialize the lower-right region. We'll invert
// the stencil value where the stencil tests fails. The
// stencil test for these pixels will be
//
// ref mask stencil mask
// ( 0x2 & 0x1 ) == ( 0x1 & 0x1 )
//
// The stencil value here will be set to ~((2^s-1) & 0x1),
// (with the 0x1 being from the stencil clear value),
// where 's' is the number of bits in the stencil buffer
//
glStencilFunc( GL_EQUAL, 0x2, 0x1 );
glStencilOp( GL_INVERT, GL_KEEP, GL_KEEP );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[3] );
// Since we don't know at compile time how many stecil bits are present,
// we'll query, and update the value correct value in the
// stencilValues arrays for the fourth tests. We'll use this value
// later in rendering.
glGetIntegerv( GL_STENCIL_BITS, &numStencilBits );
stencilValues[3] = ~(((1 << numStencilBits) - 1) & 0x1) & 0xff;
// Use the stencil buffer for controlling where rendering will
// occur. We diable writing to the stencil buffer so we
// can test against them without modifying the values we
// generated.
glStencilMask( 0x0 );
for ( i = 0; i < NumTests; ++i )
{
glStencilFunc( GL_EQUAL, stencilValues[i], 0xff );
glUniform4fv( userData->colorLoc, 1, colors[i] );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[4] );
}
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Stencil Test"), 320, 240,
ES_WINDOW_RGB | ES_WINDOW_DEPTH | ES_WINDOW_STENCIL );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/Stencil_Test/Stencil_Test.c | C | bsd | 7,967 |
// Based on a sample from:
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// PostSubBuffer.c
//
// This is a simple example that draws a rotating cube in perspective
// using a vertex shader to transform the object, posting only a subrectangle
// to the window surface.
//
#include <stdlib.h>
#include "esUtil.h"
#define WINDOW_WIDTH 320
#define WINDOW_HEIGHT 240
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
// Uniform locations
GLint mvpLoc;
// Vertex daata
GLfloat *vertices;
GLushort *indices;
int numIndices;
// Rotation angle
GLfloat angle;
// MVP matrix
ESMatrix mvpMatrix;
} UserData;
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"uniform mat4 u_mvpMatrix; \n"
"attribute vec4 a_position; \n"
"void main() \n"
"{ \n"
" gl_Position = u_mvpMatrix * a_position; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"void main() \n"
"{ \n"
" gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); \n"
"} \n";
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
// Get the uniform locations
userData->mvpLoc = glGetUniformLocation( userData->programObject, "u_mvpMatrix" );
// Generate the vertex data
userData->numIndices = esGenCube( 1.0, &userData->vertices,
NULL, NULL, &userData->indices );
// Starting rotation angle for the cube
userData->angle = 45.0f;
// Clear the whole window surface.
glClearColor ( 0.0f, 0.0f, 1.0f, 0.0f );
glClear ( GL_COLOR_BUFFER_BIT );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Update MVP matrix based on time
//
void Update ( ESContext *esContext, float deltaTime )
{
UserData *userData = (UserData*) esContext->userData;
ESMatrix perspective;
ESMatrix modelview;
float aspect;
// Compute a rotation angle based on time to rotate the cube
userData->angle += ( deltaTime * 40.0f );
if( userData->angle >= 360.0f )
userData->angle -= 360.0f;
// Compute the window aspect ratio
aspect = (GLfloat) esContext->width / (GLfloat) esContext->height;
// Generate a perspective matrix with a 60 degree FOV
esMatrixLoadIdentity( &perspective );
esPerspective( &perspective, 60.0f, aspect, 1.0f, 20.0f );
// Generate a model view matrix to rotate/translate the cube
esMatrixLoadIdentity( &modelview );
// Translate away from the viewer
esTranslate( &modelview, 0.0, 0.0, -2.0 );
// Rotate the cube
esRotate( &modelview, userData->angle, 1.0, 0.0, 1.0 );
// Compute the final MVP by multiplying the
// modevleiw and perspective matrices together
esMatrixMultiply( &userData->mvpMatrix, &modelview, &perspective );
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 3 * sizeof(GLfloat), userData->vertices );
glEnableVertexAttribArray ( userData->positionLoc );
// Load the MVP matrix
glUniformMatrix4fv( userData->mvpLoc, 1, GL_FALSE, (GLfloat*) &userData->mvpMatrix.m[0][0] );
// Draw the cube
glDrawElements ( GL_TRIANGLES, userData->numIndices, GL_UNSIGNED_SHORT, userData->indices );
eglPostSubBufferNV ( esContext->eglDisplay, esContext->eglSurface, 60, 60, WINDOW_WIDTH - 120, WINDOW_HEIGHT - 120 );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = esContext->userData;
if ( userData->vertices != NULL )
{
free ( userData->vertices );
}
if ( userData->indices != NULL )
{
free ( userData->indices );
}
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Simple Vertex Shader"), WINDOW_WIDTH, WINDOW_HEIGHT, ES_WINDOW_RGB | ES_WINDOW_POST_SUB_BUFFER_SUPPORTED );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esRegisterUpdateFunc ( &esContext, Update );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/PostSubBuffer/PostSubBuffer.c | C | bsd | 5,676 |
//
// Modified from Simple_Texture2D, found in:
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// MultipleRenderTargets.c
//
// This is a simple example that shows how to use multiple render
// targets in GLES 2.0 using EXT_draw_buffers. The example
// draws to three render targets and displays
// them together in a final pass.
//
#include <stdlib.h>
#include "esUtil.h"
PFNGLDRAWBUFFERSEXTPROC glDrawBuffersEXT;
typedef struct
{
// Handle to a program object
GLuint programObjectMRT;
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler location
GLint samplerLoc;
// Texture handle
GLuint textureId;
// Framebuffer object handle
GLuint framebuffer;
// Framebuffer color attachments
GLuint framebufferTextures[4];
} UserData;
///
// Create a simple 2x2 texture image with four different colors
//
GLuint CreateSimpleTexture2D( )
{
// Texture object handle
GLuint textureId;
// 2x2 Image, 3 bytes per pixel (R, G, B)
GLubyte pixels[4 * 3] =
{
255, 0, 0, // Red
0, 255, 0, // Green
0, 0, 255, // Blue
255, 255, 0 // Yellow
};
// Use tightly packed data
glPixelStorei ( GL_UNPACK_ALIGNMENT, 1 );
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_2D, textureId );
// Load the texture
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
UserData *userData = (UserData*)esContext->userData;
GLbyte vShaderStr[] =
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fMultiShaderStr[] =
"#extension GL_EXT_draw_buffers : enable \n"
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" vec4 color = texture2D( s_texture, v_texCoord ); \n"
" gl_FragData[0] = color; \n"
" gl_FragData[1] = vec4(1.0, 1.0, 1.0, 1.0) - color.brga;\n"
" gl_FragData[2] = vec4(0.2, 1.0, 0.5, 1.0) * color.gbra;\n"
" gl_FragData[3] = color.rrra; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" vec4 color = texture2D( s_texture, v_texCoord ); \n"
" gl_FragColor = color; \n"
"} \n";
int i;
// Check EXT_draw_buffers is supported
if (strstr(glGetString(GL_EXTENSIONS), "GL_EXT_draw_buffers") == 0)
{
return FALSE;
}
// Retrieve the address of glDrawBuffersEXT from EGL
glDrawBuffersEXT = (PFNGLDRAWBUFFERSEXTPROC)eglGetProcAddress("glDrawBuffersEXT");
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( (const char*)vShaderStr, (const char*)fShaderStr );
userData->programObjectMRT = esLoadProgram ( (const char*)vShaderStr, (const char*)fMultiShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
// Get the sampler location
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Load the texture
userData->textureId = CreateSimpleTexture2D ();
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
// Initialize the user framebuffer
glGenFramebuffers(1, &userData->framebuffer);
glGenTextures(4, userData->framebufferTextures);
glBindFramebuffer(GL_FRAMEBUFFER, userData->framebuffer);
for (i = 0; i < 4; i++)
{
// Create textures for the four color attachments
glBindTexture(GL_TEXTURE_2D, userData->framebufferTextures[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, esContext->width, esContext->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, userData->framebufferTextures[i], 0);
}
glBindTexture(GL_TEXTURE_2D, 0);
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = (UserData*)esContext->userData;
GLfloat vVertices[] = { -0.8f, 0.8f, 0.0f, // Position 0
0.0f, 0.0f, // TexCoord 0
-0.8f, -0.8f, 0.0f, // Position 1
0.0f, 1.0f, // TexCoord 1
0.8f, -0.8f, 0.0f, // Position 2
1.0f, 1.0f, // TexCoord 2
0.8f, 0.8f, 0.0f, // Position 3
1.0f, 0.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT };
// Enable drawing to the four color attachments of the user framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, userData->framebuffer);
glDrawBuffersEXT(4, drawBuffers);
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObjectMRT );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
// Draw the textured quad to the four render targets
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
// Enable the default framebuffer and single textured drawing
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram ( userData->programObject );
// Draw the four textured quads to a separate region in the viewport
glBindTexture( GL_TEXTURE_2D, userData->framebufferTextures[0]);
glViewport ( 0, 0, esContext->width/2, esContext->height/2 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
glBindTexture( GL_TEXTURE_2D, userData->framebufferTextures[1]);
glViewport ( esContext->width/2, 0, esContext->width/2, esContext->height/2 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
glBindTexture( GL_TEXTURE_2D, userData->framebufferTextures[2]);
glViewport ( 0, esContext->height/2, esContext->width/2, esContext->height/2 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
glBindTexture( GL_TEXTURE_2D, userData->framebufferTextures[3]);
glViewport ( esContext->width/2, esContext->height/2, esContext->width/2, esContext->height/2 );
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = (UserData*)esContext->userData;
glDeleteTextures(4, userData->framebufferTextures);
glDeleteFramebuffers(1, &userData->framebuffer);
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
eglDestroyContext(esContext->eglDisplay, esContext->eglContext);
eglDestroySurface(esContext->eglDisplay, esContext->eglSurface);
eglTerminate(esContext->eglDisplay);
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Multiple Render Targets"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/gles2_book/MultipleRenderTargets/MultipleRenderTargets.c | C | bsd | 9,989 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "GLSLANG/ShaderLang.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
//
// Return codes from main.
//
enum TFailCode {
ESuccess = 0,
EFailUsage,
EFailCompile,
EFailCompilerCreate,
};
static void usage();
static ShShaderType FindShaderType(const char* fileName);
static bool CompileFile(char* fileName, ShHandle compiler, int compileOptions);
static void LogMsg(const char* msg, const char* name, const int num, const char* logName);
static void PrintActiveVariables(ShHandle compiler, ShShaderInfo varType, bool mapLongVariableNames);
// If NUM_SOURCE_STRINGS is set to a value > 1, the input file data is
// broken into that many chunks.
const unsigned int NUM_SOURCE_STRINGS = 2;
typedef std::vector<char*> ShaderSource;
static bool ReadShaderSource(const char* fileName, ShaderSource& source);
static void FreeShaderSource(ShaderSource& source);
//
// Set up the per compile resources
//
void GenerateResources(ShBuiltInResources* resources)
{
ShInitBuiltInResources(resources);
resources->MaxVertexAttribs = 8;
resources->MaxVertexUniformVectors = 128;
resources->MaxVaryingVectors = 8;
resources->MaxVertexTextureImageUnits = 0;
resources->MaxCombinedTextureImageUnits = 8;
resources->MaxTextureImageUnits = 8;
resources->MaxFragmentUniformVectors = 16;
resources->MaxDrawBuffers = 1;
resources->OES_standard_derivatives = 0;
resources->OES_EGL_image_external = 0;
}
int main(int argc, char* argv[])
{
TFailCode failCode = ESuccess;
int compileOptions = 0;
int numCompiles = 0;
ShHandle vertexCompiler = 0;
ShHandle fragmentCompiler = 0;
char* buffer = 0;
size_t bufferLen = 0;
int numAttribs = 0, numUniforms = 0;
ShShaderSpec spec = SH_GLES2_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShInitialize();
ShBuiltInResources resources;
GenerateResources(&resources);
argc--;
argv++;
for (; (argc >= 1) && (failCode == ESuccess); argc--, argv++) {
if (argv[0][0] == '-') {
switch (argv[0][1]) {
case 'i': compileOptions |= SH_INTERMEDIATE_TREE; break;
case 'm': compileOptions |= SH_MAP_LONG_VARIABLE_NAMES; break;
case 'o': compileOptions |= SH_OBJECT_CODE; break;
case 'u': compileOptions |= SH_ATTRIBUTES_UNIFORMS; break;
case 'l': compileOptions |= SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX; break;
case 'e': compileOptions |= SH_EMULATE_BUILT_IN_FUNCTIONS; break;
case 'd': compileOptions |= SH_DEPENDENCY_GRAPH; break;
case 't': compileOptions |= SH_TIMING_RESTRICTIONS; break;
case 's':
if (argv[0][2] == '=') {
switch (argv[0][3]) {
case 'e': spec = SH_GLES2_SPEC; break;
case 'w': spec = SH_WEBGL_SPEC; break;
case 'c': spec = SH_CSS_SHADERS_SPEC; break;
default: failCode = EFailUsage;
}
} else {
failCode = EFailUsage;
}
break;
case 'b':
if (argv[0][2] == '=') {
switch (argv[0][3]) {
case 'e': output = SH_ESSL_OUTPUT; break;
case 'g': output = SH_GLSL_OUTPUT; break;
case 'h':
if (argv[0][4] == '1' && argv[0][5] == '1')
{
output = SH_HLSL11_OUTPUT;
}
else
{
output = SH_HLSL9_OUTPUT;
}
break;
default: failCode = EFailUsage;
}
} else {
failCode = EFailUsage;
}
break;
case 'x':
if (argv[0][2] == '=') {
switch (argv[0][3]) {
case 'i': resources.OES_EGL_image_external = 1; break;
case 'd': resources.OES_standard_derivatives = 1; break;
case 'r': resources.ARB_texture_rectangle = 1; break;
default: failCode = EFailUsage;
}
} else {
failCode = EFailUsage;
}
break;
default: failCode = EFailUsage;
}
} else {
ShHandle compiler = 0;
switch (FindShaderType(argv[0])) {
case SH_VERTEX_SHADER:
if (vertexCompiler == 0)
vertexCompiler = ShConstructCompiler(
SH_VERTEX_SHADER, spec, output, &resources);
compiler = vertexCompiler;
break;
case SH_FRAGMENT_SHADER:
if (fragmentCompiler == 0)
fragmentCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
compiler = fragmentCompiler;
break;
default: break;
}
if (compiler) {
bool compiled = CompileFile(argv[0], compiler, compileOptions);
LogMsg("BEGIN", "COMPILER", numCompiles, "INFO LOG");
ShGetInfo(compiler, SH_INFO_LOG_LENGTH, &bufferLen);
buffer = (char*) realloc(buffer, bufferLen * sizeof(char));
ShGetInfoLog(compiler, buffer);
puts(buffer);
LogMsg("END", "COMPILER", numCompiles, "INFO LOG");
printf("\n\n");
if (compiled && (compileOptions & SH_OBJECT_CODE)) {
LogMsg("BEGIN", "COMPILER", numCompiles, "OBJ CODE");
ShGetInfo(compiler, SH_OBJECT_CODE_LENGTH, &bufferLen);
buffer = (char*) realloc(buffer, bufferLen * sizeof(char));
ShGetObjectCode(compiler, buffer);
puts(buffer);
LogMsg("END", "COMPILER", numCompiles, "OBJ CODE");
printf("\n\n");
}
if (compiled && (compileOptions & SH_ATTRIBUTES_UNIFORMS)) {
LogMsg("BEGIN", "COMPILER", numCompiles, "ACTIVE ATTRIBS");
PrintActiveVariables(compiler, SH_ACTIVE_ATTRIBUTES, (compileOptions & SH_MAP_LONG_VARIABLE_NAMES) != 0);
LogMsg("END", "COMPILER", numCompiles, "ACTIVE ATTRIBS");
printf("\n\n");
LogMsg("BEGIN", "COMPILER", numCompiles, "ACTIVE UNIFORMS");
PrintActiveVariables(compiler, SH_ACTIVE_UNIFORMS, (compileOptions & SH_MAP_LONG_VARIABLE_NAMES) != 0);
LogMsg("END", "COMPILER", numCompiles, "ACTIVE UNIFORMS");
printf("\n\n");
}
if (!compiled)
failCode = EFailCompile;
++numCompiles;
} else {
failCode = EFailCompilerCreate;
}
}
}
if ((vertexCompiler == 0) && (fragmentCompiler == 0))
failCode = EFailUsage;
if (failCode == EFailUsage)
usage();
if (vertexCompiler)
ShDestruct(vertexCompiler);
if (fragmentCompiler)
ShDestruct(fragmentCompiler);
if (buffer)
free(buffer);
ShFinalize();
return failCode;
}
//
// print usage to stdout
//
void usage()
{
printf("Usage: translate [-i -m -o -u -l -e -b=e -b=g -b=h -x=i -x=d] file1 file2 ...\n"
"Where: filename : filename ending in .frag or .vert\n"
" -i : print intermediate tree\n"
" -m : map long variable names\n"
" -o : print translated code\n"
" -u : print active attribs and uniforms\n"
" -l : unroll for-loops with integer indices\n"
" -e : emulate certain built-in functions (workaround for driver bugs)\n"
" -t : enforce experimental timing restrictions\n"
" -d : print dependency graph used to enforce timing restrictions\n"
" -s=e : use GLES2 spec (this is by default)\n"
" -s=w : use WebGL spec\n"
" -s=c : use CSS Shaders spec\n"
" -b=e : output GLSL ES code (this is by default)\n"
" -b=g : output GLSL code\n"
" -b=h9 : output HLSL9 code\n"
" -b=h11 : output HLSL11 code\n"
" -x=i : enable GL_OES_EGL_image_external\n"
" -x=d : enable GL_OES_EGL_standard_derivatives\n"
" -x=r : enable ARB_texture_rectangle\n");
}
//
// Deduce the shader type from the filename. Files must end in one of the
// following extensions:
//
// .frag* = fragment shader
// .vert* = vertex shader
//
ShShaderType FindShaderType(const char* fileName)
{
assert(fileName);
const char* ext = strrchr(fileName, '.');
if (ext && strcmp(ext, ".sl") == 0)
for (; ext > fileName && ext[0] != '.'; ext--);
ext = strrchr(fileName, '.');
if (ext) {
if (strncmp(ext, ".frag", 4) == 0) return SH_FRAGMENT_SHADER;
if (strncmp(ext, ".vert", 4) == 0) return SH_VERTEX_SHADER;
}
return SH_FRAGMENT_SHADER;
}
//
// Read a file's data into a string, and compile it using ShCompile
//
bool CompileFile(char* fileName, ShHandle compiler, int compileOptions)
{
ShaderSource source;
if (!ReadShaderSource(fileName, source))
return false;
int ret = ShCompile(compiler, &source[0], source.size(), compileOptions);
FreeShaderSource(source);
return ret ? true : false;
}
void LogMsg(const char* msg, const char* name, const int num, const char* logName)
{
printf("#### %s %s %d %s ####\n", msg, name, num, logName);
}
void PrintActiveVariables(ShHandle compiler, ShShaderInfo varType, bool mapLongVariableNames)
{
size_t nameSize = 0;
switch (varType) {
case SH_ACTIVE_ATTRIBUTES:
ShGetInfo(compiler, SH_ACTIVE_ATTRIBUTE_MAX_LENGTH, &nameSize);
break;
case SH_ACTIVE_UNIFORMS:
ShGetInfo(compiler, SH_ACTIVE_UNIFORM_MAX_LENGTH, &nameSize);
break;
default: assert(0);
}
if (nameSize <= 1) return;
char* name = new char[nameSize];
char* mappedName = NULL;
if (mapLongVariableNames) {
size_t mappedNameSize = 0;
ShGetInfo(compiler, SH_MAPPED_NAME_MAX_LENGTH, &mappedNameSize);
mappedName = new char[mappedNameSize];
}
size_t activeVars = 0;
int size = 0;
ShDataType type = SH_NONE;
const char* typeName = NULL;
ShGetInfo(compiler, varType, &activeVars);
for (size_t i = 0; i < activeVars; ++i) {
switch (varType) {
case SH_ACTIVE_ATTRIBUTES:
ShGetActiveAttrib(compiler, static_cast<int>(i), NULL, &size, &type, name, mappedName);
break;
case SH_ACTIVE_UNIFORMS:
ShGetActiveUniform(compiler, static_cast<int>(i), NULL, &size, &type, name, mappedName);
break;
default: assert(0);
}
switch (type) {
case SH_FLOAT: typeName = "GL_FLOAT"; break;
case SH_FLOAT_VEC2: typeName = "GL_FLOAT_VEC2"; break;
case SH_FLOAT_VEC3: typeName = "GL_FLOAT_VEC3"; break;
case SH_FLOAT_VEC4: typeName = "GL_FLOAT_VEC4"; break;
case SH_INT: typeName = "GL_INT"; break;
case SH_INT_VEC2: typeName = "GL_INT_VEC2"; break;
case SH_INT_VEC3: typeName = "GL_INT_VEC3"; break;
case SH_INT_VEC4: typeName = "GL_INT_VEC4"; break;
case SH_BOOL: typeName = "GL_BOOL"; break;
case SH_BOOL_VEC2: typeName = "GL_BOOL_VEC2"; break;
case SH_BOOL_VEC3: typeName = "GL_BOOL_VEC3"; break;
case SH_BOOL_VEC4: typeName = "GL_BOOL_VEC4"; break;
case SH_FLOAT_MAT2: typeName = "GL_FLOAT_MAT2"; break;
case SH_FLOAT_MAT3: typeName = "GL_FLOAT_MAT3"; break;
case SH_FLOAT_MAT4: typeName = "GL_FLOAT_MAT4"; break;
case SH_SAMPLER_2D: typeName = "GL_SAMPLER_2D"; break;
case SH_SAMPLER_CUBE: typeName = "GL_SAMPLER_CUBE"; break;
case SH_SAMPLER_EXTERNAL_OES: typeName = "GL_SAMPLER_EXTERNAL_OES"; break;
default: assert(0);
}
printf("%u: name:%s type:%s size:%d", i, name, typeName, size);
if (mapLongVariableNames)
printf(" mapped name:%s", mappedName);
printf("\n");
}
delete [] name;
if (mappedName)
delete [] mappedName;
}
static bool ReadShaderSource(const char* fileName, ShaderSource& source) {
FILE* in = fopen(fileName, "rb");
if (!in) {
printf("Error: unable to open input file: %s\n", fileName);
return false;
}
// Obtain file size.
fseek(in, 0, SEEK_END);
int count = ftell(in);
rewind(in);
int len = (int)ceil((float)count / (float)NUM_SOURCE_STRINGS);
source.reserve(NUM_SOURCE_STRINGS);
// Notice the usage of do-while instead of a while loop here.
// It is there to handle empty files in which case a single empty
// string is added to vector.
do {
char* data = new char[len + 1];
int nread = fread(data, 1, len, in);
data[nread] = '\0';
source.push_back(data);
count -= nread;
} while (count > 0);
fclose(in);
return true;
}
static void FreeShaderSource(ShaderSource& source) {
for (ShaderSource::size_type i = 0; i < source.size(); ++i) {
delete [] source[i];
}
source.clear();
}
| 010smithzhang-ddd | samples/translator/translator.cpp | C++ | bsd | 14,026 |
//
// Modified from Simple_Texture2D found in:
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
// Simple_Instancing.c
//
// This is a simple example that draws two quads with a 2D
// texture image. The purpose of this example is to demonstrate
// the basics of ANGLE instancing in GLESv2.
//
#include <stdlib.h>
#include "esUtil.h"
#include <GLES2/gl2ext.h>
PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE;
PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE;
PFNGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstancedANGLE;
typedef struct
{
// Handle to a program object
GLuint programObject;
// Attribute locations
GLint positionLoc;
GLint texCoordLoc;
// Sampler location
GLint samplerLoc;
// Texture handle
GLuint textureId;
// Instance VBO
GLint instancePosLoc;
} UserData;
///
// Create a simple 2x2 texture image with four different colors
//
GLuint CreateSimpleTexture2D( )
{
// Texture object handle
GLuint textureId;
// 2x2 Image, 3 bytes per pixel (R, G, B)
GLubyte pixels[4 * 3] =
{
255, 0, 0, // Red
0, 255, 0, // Green
0, 0, 255, // Blue
255, 255, 0 // Yellow
};
// Use tightly packed data
glPixelStorei ( GL_UNPACK_ALIGNMENT, 1 );
// Generate a texture object
glGenTextures ( 1, &textureId );
// Bind the texture object
glBindTexture ( GL_TEXTURE_2D, textureId );
// Load the texture
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels );
// Set the filtering mode
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
return textureId;
}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
// init instancing functions
char *extensionString = (char*) glGetString(GL_EXTENSIONS);
UserData *userData = esContext->userData;
GLbyte vShaderStr[] =
"attribute vec3 a_position; \n"
"attribute vec2 a_texCoord; \n"
"attribute vec3 a_instancePos;\n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = vec4(a_position.xyz + a_instancePos.xyz, 1.0); \n"
" v_texCoord = a_texCoord; \n"
"} \n";
GLbyte fShaderStr[] =
"precision mediump float; \n"
"varying vec2 v_texCoord; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D( s_texture, v_texCoord );\n"
"} \n";
if (strstr(extensionString, "GL_ANGLE_instanced_arrays"))
{
glVertexAttribDivisorANGLE = (PFNGLVERTEXATTRIBDIVISORANGLEPROC)eglGetProcAddress("glVertexAttribDivisorANGLE");
glDrawArraysInstancedANGLE = (PFNGLDRAWARRAYSINSTANCEDANGLEPROC)eglGetProcAddress("glDrawArraysInstancedANGLE");
glDrawElementsInstancedANGLE = (PFNGLDRAWELEMENTSINSTANCEDANGLEPROC)eglGetProcAddress("glDrawElementsInstancedANGLE");
}
// Load the shaders and get a linked program object
userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );
// Get the attribute locations
userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
userData->instancePosLoc = glGetAttribLocation ( userData->programObject, "a_instancePos" );
// Get the sampler location
userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );
// Load the texture
userData->textureId = CreateSimpleTexture2D ();
glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
return TRUE;
}
///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
UserData *userData = (UserData*) esContext->userData;
GLfloat vVertices[] = { -0.2f, 0.2f, 0.0f, // Position 0
0.0f, 0.0f, // TexCoord 0
-0.2f, -0.2f, 0.0f, // Position 1
0.0f, 1.0f, // TexCoord 1
0.2f, -0.2f, 0.0f, // Position 2
1.0f, 1.0f, // TexCoord 2
0.2f, 0.2f, 0.0f, // Position 3
1.0f, 0.0f // TexCoord 3
};
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
GLfloat instanceVerts [] = { -0.3f, -0.3f, 0.0f, 0.3f, 0.3f, 0.0f };
// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );
// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT );
// Use the program object
glUseProgram ( userData->programObject );
// Load the vertex position
glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), vVertices );
// Load the texture coordinate
glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );
// Load the instance position
glVertexAttribPointer ( userData->instancePosLoc, 3, GL_FLOAT,
GL_FALSE, 3 * sizeof(GLfloat), instanceVerts );
glEnableVertexAttribArray ( userData->positionLoc );
glEnableVertexAttribArray ( userData->texCoordLoc );
glEnableVertexAttribArray ( userData->instancePosLoc );
// Enable instancing
glVertexAttribDivisorANGLE( userData->instancePosLoc, 1 );
// Bind the texture
glActiveTexture ( GL_TEXTURE0 );
glBindTexture ( GL_TEXTURE_2D, userData->textureId );
// Set the sampler texture unit to 0
glUniform1i ( userData->samplerLoc, 0 );
glDrawElementsInstancedANGLE ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices, 2 );
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}
///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
UserData *userData = (UserData*) esContext->userData;
// Delete texture object
glDeleteTextures ( 1, &userData->textureId );
// Delete program object
glDeleteProgram ( userData->programObject );
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
UserData userData;
esInitContext ( &esContext );
esContext.userData = &userData;
esCreateWindow ( &esContext, TEXT("Simple Instancing"), 320, 240, ES_WINDOW_RGB );
if ( !Init ( &esContext ) )
return 0;
esRegisterDrawFunc ( &esContext, Draw );
esMainLoop ( &esContext );
ShutDown ( &esContext );
}
| 010smithzhang-ddd | samples/angle/Simple_Instancing/Simple_Instancing.c | C | bsd | 7,135 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class LocationTest : public PreprocessorTest
{
protected:
void expectLocation(int count,
const char* const string[],
const int length[],
const pp::SourceLocation& location)
{
ASSERT_TRUE(mPreprocessor.init(count, string, length));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
EXPECT_EQ(location.file, token.location.file);
EXPECT_EQ(location.line, token.location.line);
}
};
TEST_F(LocationTest, String0_Line1)
{
const char* str = "foo";
pp::SourceLocation loc(0, 1);
SCOPED_TRACE("String0_Line1");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, String0_Line2)
{
const char* str = "\nfoo";
pp::SourceLocation loc(0, 2);
SCOPED_TRACE("String0_Line2");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, String1_Line1)
{
const char* const str[] = {"\n\n", "foo"};
pp::SourceLocation loc(1, 1);
SCOPED_TRACE("String1_Line1");
expectLocation(2, str, NULL, loc);
}
TEST_F(LocationTest, String1_Line2)
{
const char* const str[] = {"\n\n", "\nfoo"};
pp::SourceLocation loc(1, 2);
SCOPED_TRACE("String1_Line2");
expectLocation(2, str, NULL, loc);
}
TEST_F(LocationTest, NewlineInsideCommentCounted)
{
const char* str = "/*\n\n*/foo";
pp::SourceLocation loc(0, 3);
SCOPED_TRACE("NewlineInsideCommentCounted");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, ErrorLocationAfterComment)
{
const char* str = "/*\n\n*/@";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::INVALID_CHARACTER,
pp::SourceLocation(0, 3),
"@"));
pp::Token token;
mPreprocessor.lex(&token);
}
// The location of a token straddling two or more strings is that of the
// first character of the token.
TEST_F(LocationTest, TokenStraddlingTwoStrings)
{
const char* const str[] = {"f", "oo"};
pp::SourceLocation loc(0, 1);
SCOPED_TRACE("TokenStraddlingTwoStrings");
expectLocation(2, str, NULL, loc);
}
TEST_F(LocationTest, TokenStraddlingThreeStrings)
{
const char* const str[] = {"f", "o", "o"};
pp::SourceLocation loc(0, 1);
SCOPED_TRACE("TokenStraddlingThreeStrings");
expectLocation(3, str, NULL, loc);
}
TEST_F(LocationTest, EndOfFileWithoutNewline)
{
const char* const str[] = {"foo"};
ASSERT_TRUE(mPreprocessor.init(1, str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ(1, token.location.line);
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::LAST, token.type);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ(1, token.location.line);
}
TEST_F(LocationTest, EndOfFileAfterNewline)
{
const char* const str[] = {"foo\n"};
ASSERT_TRUE(mPreprocessor.init(1, str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ(1, token.location.line);
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::LAST, token.type);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ(2, token.location.line);
}
TEST_F(LocationTest, EndOfFileAfterEmptyString)
{
const char* const str[] = {"foo\n", "\n", ""};
ASSERT_TRUE(mPreprocessor.init(3, str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ(1, token.location.line);
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::LAST, token.type);
EXPECT_EQ(2, token.location.file);
EXPECT_EQ(1, token.location.line);
}
TEST_F(LocationTest, ValidLineDirective1)
{
const char* str = "#line 10\n"
"foo";
pp::SourceLocation loc(0, 10);
SCOPED_TRACE("ValidLineDirective1");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, ValidLineDirective2)
{
const char* str = "#line 10 20\n"
"foo";
pp::SourceLocation loc(20, 10);
SCOPED_TRACE("ValidLineDirective2");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveCommentsIgnored)
{
const char* str = "/* bar */"
"#"
"/* bar */"
"line"
"/* bar */"
"10"
"/* bar */"
"20"
"/* bar */"
"// bar "
"\n"
"foo";
pp::SourceLocation loc(20, 10);
SCOPED_TRACE("LineDirectiveCommentsIgnored");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveWithMacro1)
{
const char* str = "#define L 10\n"
"#define F(x) x\n"
"#line L F(20)\n"
"foo";
pp::SourceLocation loc(20, 10);
SCOPED_TRACE("LineDirectiveWithMacro1");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveWithMacro2)
{
const char* str = "#define LOC 10 20\n"
"#line LOC\n"
"foo";
pp::SourceLocation loc(20, 10);
SCOPED_TRACE("LineDirectiveWithMacro2");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveWithPredefinedMacro)
{
const char* str = "#line __LINE__ __FILE__\n"
"foo";
pp::SourceLocation loc(0, 1);
SCOPED_TRACE("LineDirectiveWithMacro");
expectLocation(1, &str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveNewlineBeforeStringBreak)
{
const char* const str[] = {"#line 10 20\n", "foo"};
// String number is incremented after it is set by the line directive.
// Also notice that line number is reset after the string break.
pp::SourceLocation loc(21, 1);
SCOPED_TRACE("LineDirectiveNewlineBeforeStringBreak");
expectLocation(2, str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveNewlineAfterStringBreak)
{
const char* const str[] = {"#line 10 20", "\nfoo"};
// String number is incremented before it is set by the line directive.
pp::SourceLocation loc(20, 10);
SCOPED_TRACE("LineDirectiveNewlineAfterStringBreak");
expectLocation(2, str, NULL, loc);
}
TEST_F(LocationTest, LineDirectiveMissingNewline)
{
const char* str = "#line 10";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
// Error reported about EOF.
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));
pp::Token token;
mPreprocessor.lex(&token);
}
struct LineTestParam
{
const char* str;
pp::Diagnostics::ID id;
};
class InvalidLineTest : public LocationTest,
public testing::WithParamInterface<LineTestParam>
{
};
TEST_P(InvalidLineTest, Identified)
{
LineTestParam param = GetParam();
ASSERT_TRUE(mPreprocessor.init(1, ¶m.str, NULL));
using testing::_;
// Invalid line directive call.
EXPECT_CALL(mDiagnostics, print(param.id, pp::SourceLocation(0, 1), _));
pp::Token token;
mPreprocessor.lex(&token);
}
static const LineTestParam kParams[] = {
{"#line\n", pp::Diagnostics::INVALID_LINE_DIRECTIVE},
{"#line foo\n", pp::Diagnostics::INVALID_LINE_NUMBER},
{"#line 10 foo\n", pp::Diagnostics::INVALID_FILE_NUMBER},
{"#line 10 20 foo\n", pp::Diagnostics::UNEXPECTED_TOKEN},
{"#line 0xffffffff\n", pp::Diagnostics::INTEGER_OVERFLOW},
{"#line 10 0xffffffff\n", pp::Diagnostics::INTEGER_OVERFLOW}
};
INSTANTIATE_TEST_CASE_P(All, InvalidLineTest, testing::ValuesIn(kParams));
| 010smithzhang-ddd | tests/preprocessor_tests/location_test.cpp | C++ | bsd | 8,210 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef PREPROCESSOR_TESTS_MOCK_DIRECTIVE_HANDLER_H_
#define PREPROCESSOR_TESTS_MOCK_DIRECTIVE_HANDLER_H_
#include "gmock/gmock.h"
#include "DirectiveHandlerBase.h"
class MockDirectiveHandler : public pp::DirectiveHandler
{
public:
MOCK_METHOD2(handleError,
void(const pp::SourceLocation& loc, const std::string& msg));
MOCK_METHOD3(handlePragma,
void(const pp::SourceLocation& loc,
const std::string& name,
const std::string& value));
MOCK_METHOD3(handleExtension,
void(const pp::SourceLocation& loc,
const std::string& name,
const std::string& behavior));
MOCK_METHOD2(handleVersion,
void(const pp::SourceLocation& loc, int version));
};
#endif // PREPROCESSOR_TESTS_MOCK_DIRECTIVE_HANDLER_H_
| 010smithzhang-ddd | tests/preprocessor_tests/MockDirectiveHandler.h | C++ | bsd | 985 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class DefineTest : public PreprocessorTest
{
};
TEST_F(DefineTest, NonIdentifier)
{
const char* input = "#define 2 foo\n"
"2\n";
const char* expected = "\n"
"2\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::UNEXPECTED_TOKEN,
pp::SourceLocation(0, 1),
"2"));
preprocess(input, expected);
};
TEST_F(DefineTest, RedefinePredefined)
{
const char* input = "#define __LINE__ 10\n"
"__LINE__\n"
"#define __FILE__ 20\n"
"__FILE__\n"
"#define __VERSION__ 200\n"
"__VERSION__\n"
"#define GL_ES 0\n"
"GL_ES\n";
const char* expected = "\n"
"2\n"
"\n"
"0\n"
"\n"
"100\n"
"\n"
"1\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_REDEFINED,
pp::SourceLocation(0, 1),
"__LINE__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_REDEFINED,
pp::SourceLocation(0, 3),
"__FILE__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_REDEFINED,
pp::SourceLocation(0, 5),
"__VERSION__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_REDEFINED,
pp::SourceLocation(0, 7),
"GL_ES"));
preprocess(input, expected);
}
TEST_F(DefineTest, ReservedUnderScore1)
{
const char* input = "#define __foo bar\n"
"__foo\n";
const char* expected = "\n"
"__foo\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_NAME_RESERVED,
pp::SourceLocation(0, 1),
"__foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, ReservedUnderScore2)
{
const char* input = "#define foo__bar baz\n"
"foo__bar\n";
const char* expected = "\n"
"foo__bar\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_NAME_RESERVED,
pp::SourceLocation(0, 1),
"foo__bar"));
preprocess(input, expected);
}
TEST_F(DefineTest, ReservedGL)
{
const char* input = "#define GL_foo bar\n"
"GL_foo\n";
const char* expected = "\n"
"GL_foo\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_NAME_RESERVED,
pp::SourceLocation(0, 1),
"GL_foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, ObjRedefineValid)
{
const char* input = "#define foo (1-1)\n"
"#define foo /* whitespace */ (1-1) /* other */ \n"
"foo\n";
const char* expected = "\n"
"\n"
"(1-1)\n";
// No error or warning.
using testing::_;
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(input, expected);
}
TEST_F(DefineTest, ObjRedefineInvalid)
{
const char* input = "#define foo (0)\n"
"#define foo (1-1)\n"
"foo\n";
const char* expected = "\n"
"\n"
"(0)\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_REDEFINED,
pp::SourceLocation(0, 2),
"foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, FuncRedefineValid)
{
const char* input = "#define foo(a) ( a )\n"
"#define foo( a )( /* whitespace */ a /* other */ )\n"
"foo(b)\n";
const char* expected = "\n"
"\n"
"( b )\n";
// No error or warning.
using testing::_;
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(input, expected);
}
TEST_F(DefineTest, FuncRedefineInvalid)
{
const char* input = "#define foo(b) ( a )\n"
"#define foo(b) ( b )\n"
"foo(1)\n";
const char* expected = "\n"
"\n"
"( a )\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_REDEFINED,
pp::SourceLocation(0, 2),
"foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, ObjBasic)
{
const char* input = "#define foo 1\n"
"foo\n";
const char* expected = "\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjEmpty)
{
const char* input = "#define foo\n"
"foo\n";
const char* expected = "\n"
"\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjChain)
{
const char* input = "#define foo 1\n"
"#define bar foo\n"
"bar\n";
const char* expected = "\n"
"\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjChainReverse)
{
const char* input = "#define bar foo\n"
"#define foo 1\n"
"bar\n";
const char* expected = "\n"
"\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjRecursive)
{
const char* input = "#define foo bar\n"
"#define bar baz\n"
"#define baz foo\n"
"foo\n"
"bar\n"
"baz\n";
const char* expected = "\n"
"\n"
"\n"
"foo\n"
"bar\n"
"baz\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjCompositeChain)
{
const char* input = "#define foo 1\n"
"#define bar a foo\n"
"bar\n";
const char* expected = "\n"
"\n"
"a 1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjCompositeChainReverse)
{
const char* input = "#define bar a foo\n"
"#define foo 1\n"
"bar\n";
const char* expected = "\n"
"\n"
"a 1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjCompositeRecursive)
{
const char* input = "#define foo a bar\n"
"#define bar b baz\n"
"#define baz c foo\n"
"foo\n"
"bar\n"
"baz\n";
const char* expected = "\n"
"\n"
"\n"
"a b c foo\n"
"b c a bar\n"
"c a b baz\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjChainSelfRecursive)
{
const char* input = "#define foo foo\n"
"#define bar foo\n"
"bar\n";
const char* expected = "\n"
"\n"
"foo\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjectLikeWithParens)
{
const char* input = "#define foo ()1\n"
"foo()\n"
"#define bar ()2\n"
"bar()\n";
const char* expected = "\n"
"()1()\n"
"\n"
"()2()\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncEmpty)
{
const char* input = "#define foo()\n"
"foo()\n";
const char* expected = "\n"
"\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncNoArgs)
{
const char* input = "#define foo() bar\n"
"foo()\n";
const char* expected = "\n"
"bar\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncOneArgUnused)
{
const char* input = "#define foo(x) 1\n"
"foo(bar)\n";
const char* expected = "\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncTwoArgsUnused)
{
const char* input = "#define foo(x,y) 1\n"
"foo(bar,baz)\n";
const char* expected = "\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncOneArg)
{
const char* input = "#define foo(x) ((x)+1)\n"
"foo(bar)\n";
const char* expected = "\n"
"((bar)+1)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncTwoArgs)
{
const char* input = "#define foo(x,y) ((x)*(y))\n"
"foo(bar,baz)\n";
const char* expected = "\n"
"((bar)*(baz))\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncEmptyArgs)
{
const char* input = "#define zero() pass\n"
"#define one(x) pass\n"
"#define two(x,y) pass\n"
"zero()\n"
"one()\n"
"two(,)\n";
const char* expected = "\n"
"\n"
"\n"
"pass\n"
"pass\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncMacroAsParam)
{
const char* input = "#define x 0\n"
"#define foo(x) x\n"
"foo(1)\n";
const char* expected = "\n"
"\n"
"1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncOneArgMulti)
{
const char* input = "#define foo(x) (x)\n"
"foo(this is a multi-word argument)\n";
const char* expected = "\n"
"(this is a multi-word argument)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncTwoArgsMulti)
{
const char* input = "#define foo(x,y) x,two fish,red fish,y\n"
"foo(one fish, blue fish)\n";
const char* expected = "\n"
"one fish,two fish,red fish,blue fish\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncCompose)
{
const char* input = "#define bar(x) (1+(x))\n"
"#define foo(y) (2*(y))\n"
"foo(bar(3))\n";
const char* expected = "\n"
"\n"
"(2*((1+(3))))\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncArgWithParens)
{
const char* input = "#define foo(x) (x)\n"
"foo(argument(with parens) FTW)\n";
const char* expected = "\n"
"(argument(with parens) FTW)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncMacroAsNonMacro)
{
const char* input = "#define foo(bar) bar\n"
"foo bar\n";
const char* expected = "\n"
"foo bar\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncExtraNewlines)
{
const char* input = "#define foo(a) (a)\n"
"foo\n"
"(\n"
"1\n"
")\n";
const char* expected = "\n"
"(1)\n"
"\n"
"\n"
"\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFunc)
{
const char* input = "#define foo() pass\n"
"#define bar foo()\n"
"bar\n";
const char* expected = "\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToNonFunc)
{
const char* input = "#define pass() fail\n"
"#define bar pass\n"
"bar\n";
const char* expected = "\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFuncWithArgs)
{
const char* input = "#define foo(fail) fail\n"
"#define bar foo(pass)\n"
"bar\n";
const char* expected = "\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFuncCompose)
{
const char* input = "#define baz(fail) fail\n"
"#define bar(fail) fail\n"
"#define foo bar(baz(pass))\n"
"foo\n";
const char* expected = "\n"
"\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFuncParensInText1)
{
const char* input = "#define fail() pass\n"
"#define foo fail\n"
"foo()\n";
const char* expected = "\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFuncParensInText2)
{
const char* input = "#define bar with,embedded,commas\n"
"#define func(x) pass\n"
"#define foo func\n"
"foo(bar)\n";
const char* expected = "\n"
"\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainObjToFuncMultiLevel)
{
const char* input = "#define foo(x) pass\n"
"#define bar foo\n"
"#define baz bar\n"
"#define joe baz\n"
"joe (fail)\n";
const char* expected = "\n"
"\n"
"\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ObjToFuncRecursive)
{
const char* input = "#define A(a,b) B(a,b)\n"
"#define C A(0,C)\n"
"C\n";
const char* expected = "\n"
"\n"
"B(0,C)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, ChainFuncToFuncCompose)
{
const char* input = "#define baz(fail) fail\n"
"#define bar(fail) fail\n"
"#define foo() bar(baz(pass))\n"
"foo()\n";
const char* expected = "\n"
"\n"
"\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncSelfRecursive)
{
const char* input = "#define foo(a) foo(2*(a))\n"
"foo(3)\n";
const char* expected = "\n"
"foo(2*(3))\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncSelfCompose)
{
const char* input = "#define foo(a) foo(2*(a))\n"
"foo(foo(3))\n";
const char* expected = "\n"
"foo(2*(foo(2*(3))))\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncSelfComposeNonFunc)
{
const char* input = "#define foo(bar) bar\n"
"foo(foo)\n";
const char* expected = "\n"
"foo\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncSelfComposeNonFuncMultiTokenArg)
{
const char* input = "#define foo(bar) bar\n"
"foo(1+foo)\n";
const char* expected = "\n"
"1+foo\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FinalizeUnexpandedMacro)
{
const char* input = "#define expand(x) expand(x once)\n"
"#define foo(x) x\n"
"foo(expand(just))\n";
const char* expected = "\n"
"\n"
"expand(just once)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncArgWithCommas)
{
const char* input = "#define foo(x) pass\n"
"foo(argument (with,embedded, commas) -- baz)\n";
const char* expected = "\n"
"pass\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncArgObjMaroWithComma)
{
const char* input = "#define foo(a) (a)\n"
"#define bar two,words\n"
"foo(bar)\n";
const char* expected = "\n"
"\n"
"(two,words)\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncLeftParenInMacroRightParenInText)
{
const char* input = "#define bar(a) a*2\n"
"#define foo bar(\n"
"foo b)\n";
const char* expected = "\n"
"\n"
"b*2\n";
preprocess(input, expected);
}
TEST_F(DefineTest, RepeatedArg)
{
const char* input = "#define double(x) x x\n"
"double(1)\n";
const char* expected = "\n"
"1 1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, FuncMissingRightParen)
{
const char* input = "#define foo(x) (2*(x))\n"
"foo(3\n";
const char* expected = "\n"
"\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_UNTERMINATED_INVOCATION,
pp::SourceLocation(0, 2),
"foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, FuncIncorrectArgCount)
{
const char* input = "#define foo(x,y) ((x)+(y))\n"
"foo()\n"
"foo(1)\n"
"foo(1,2,3)\n";
const char* expected = "\n"
"\n"
"\n"
"\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_TOO_FEW_ARGS,
pp::SourceLocation(0, 2),
"foo"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_TOO_FEW_ARGS,
pp::SourceLocation(0, 3),
"foo"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_TOO_MANY_ARGS,
pp::SourceLocation(0, 4),
"foo"));
preprocess(input, expected);
}
TEST_F(DefineTest, Undef)
{
const char* input = "#define foo 1\n"
"foo\n"
"#undef foo\n"
"foo\n";
const char* expected = "\n"
"1\n"
"\n"
"foo\n";
preprocess(input, expected);
}
TEST_F(DefineTest, UndefPredefined)
{
const char* input = "#undef __LINE__\n"
"__LINE__\n"
"#undef __FILE__\n"
"__FILE__\n"
"#undef __VERSION__\n"
"__VERSION__\n"
"#undef GL_ES\n"
"GL_ES\n";
const char* expected = "\n"
"2\n"
"\n"
"0\n"
"\n"
"100\n"
"\n"
"1\n";
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_UNDEFINED,
pp::SourceLocation(0, 1),
"__LINE__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_UNDEFINED,
pp::SourceLocation(0, 3),
"__FILE__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_UNDEFINED,
pp::SourceLocation(0, 5),
"__VERSION__"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::MACRO_PREDEFINED_UNDEFINED,
pp::SourceLocation(0, 7),
"GL_ES"));
preprocess(input, expected);
}
TEST_F(DefineTest, UndefRedefine)
{
const char* input = "#define foo 1\n"
"foo\n"
"#undef foo\n"
"foo\n"
"#define foo 2\n"
"foo\n";
const char* expected = "\n"
"1\n"
"\n"
"foo\n"
"\n"
"2\n";
preprocess(input, expected);
}
TEST_F(DefineTest, C99Example)
{
const char* input =
"#define x 3 \n"
"#define f(a) f(x * (a)) \n"
"#undef x \n"
"#define x 2 \n"
"#define g f \n"
"#define z z[0] \n"
"#define h g(~ \n"
"#define m(a) a(w) \n"
"#define w 0,1 \n"
"#define t(a) a \n"
"#define p() int \n"
"#define q(x) x \n"
" \n"
"f(y+1) + f(f(z)) % t(t(g)(0) + t)(1);\n"
"g(x+(3,4)-w) | h 5) & m\n"
" (f)^m(m);\n"
"p() i[q()] = { q(1), 23, 4, 5, };\n";
const char* expected =
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1);\n"
"f(2 * (2+(3,4)-0,1)) | f(2 * (~ 5)) & f(2 * (0,1))\n"
"^m(0,1);\n"
"int i[] = { 1, 23, 4, 5, };\n";
preprocess(input, expected);
}
TEST_F(DefineTest, Predefined_GL_ES)
{
const char* input = "GL_ES\n";
const char* expected = "1\n";
preprocess(input, expected);
}
TEST_F(DefineTest, Predefined_VERSION)
{
const char* input = "__VERSION__\n";
const char* expected = "100\n";
preprocess(input, expected);
}
TEST_F(DefineTest, Predefined_LINE1)
{
const char* str = "\n\n__LINE__";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_INT, token.type);
EXPECT_EQ("3", token.text);
}
TEST_F(DefineTest, Predefined_LINE2)
{
const char* str = "#line 10\n"
"__LINE__\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_INT, token.type);
EXPECT_EQ("10", token.text);
}
TEST_F(DefineTest, Predefined_FILE1)
{
const char* const str[] = {"", "", "__FILE__"};
ASSERT_TRUE(mPreprocessor.init(3, str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_INT, token.type);
EXPECT_EQ("2", token.text);
}
TEST_F(DefineTest, Predefined_FILE2)
{
const char* const str[] = {"#line 10 20\n", "__FILE__"};
ASSERT_TRUE(mPreprocessor.init(2, str, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_INT, token.type);
EXPECT_EQ("21", token.text);
}
| 010smithzhang-ddd | tests/preprocessor_tests/define_test.cpp | C++ | bsd | 24,242 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef PREPROCESSOR_TESTS_MOCK_DIAGNOSTICS_H_
#define PREPROCESSOR_TESTS_MOCK_DIAGNOSTICS_H_
#include "gmock/gmock.h"
#include "DiagnosticsBase.h"
class MockDiagnostics : public pp::Diagnostics
{
public:
MOCK_METHOD3(print,
void(ID id, const pp::SourceLocation& loc, const std::string& text));
};
#endif // PREPROCESSOR_TESTS_MOCK_DIAGNOSTICS_H_
| 010smithzhang-ddd | tests/preprocessor_tests/MockDiagnostics.h | C++ | bsd | 546 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
void PreprocessorTest::preprocess(const char* input, const char* expected)
{
ASSERT_TRUE(mPreprocessor.init(1, &input, NULL));
int line = 1;
pp::Token token;
std::stringstream stream;
do
{
mPreprocessor.lex(&token);
for (; line < token.location.line; ++line)
{
stream << "\n";
}
stream << token;
} while (token.type != pp::Token::LAST);
std::string actual = stream.str();
EXPECT_STREQ(expected, actual.c_str());
}
| 010smithzhang-ddd | tests/preprocessor_tests/PreprocessorTest.cpp | C++ | bsd | 735 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
#define CLOSED_RANGE(x, y) testing::Range(x, static_cast<char>((y) + 1))
class InvalidNumberTest : public PreprocessorTest,
public testing::WithParamInterface<const char*>
{
};
TEST_P(InvalidNumberTest, InvalidNumberIdentified)
{
const char* str = GetParam();
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
using testing::_;
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::INVALID_NUMBER, _, str));
pp::Token token;
mPreprocessor.lex(&token);
}
INSTANTIATE_TEST_CASE_P(InvalidIntegers, InvalidNumberTest,
testing::Values("1a", "08", "0xG"));
INSTANTIATE_TEST_CASE_P(InvalidFloats, InvalidNumberTest,
testing::Values("1eg", "0.a", "0.1.2", ".0a", ".0.1"));
typedef std::tr1::tuple<const char*, char> IntegerParams;
class IntegerTest : public PreprocessorTest,
public testing::WithParamInterface<IntegerParams>
{
};
TEST_P(IntegerTest, Identified)
{
std::string str(std::tr1::get<0>(GetParam())); // prefix.
str.push_back(std::tr1::get<1>(GetParam())); // digit.
const char* cstr = str.c_str();
ASSERT_TRUE(mPreprocessor.init(1, &cstr, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_INT, token.type);
EXPECT_EQ(str, token.text);
}
INSTANTIATE_TEST_CASE_P(DecimalInteger,
IntegerTest,
testing::Combine(testing::Values(""),
CLOSED_RANGE('0', '9')));
INSTANTIATE_TEST_CASE_P(OctalInteger,
IntegerTest,
testing::Combine(testing::Values("0"),
CLOSED_RANGE('0', '7')));
INSTANTIATE_TEST_CASE_P(HexadecimalInteger_0_9,
IntegerTest,
testing::Combine(testing::Values("0x", "0X"),
CLOSED_RANGE('0', '9')));
INSTANTIATE_TEST_CASE_P(HexadecimalInteger_a_f,
IntegerTest,
testing::Combine(testing::Values("0x", "0X"),
CLOSED_RANGE('a', 'f')));
INSTANTIATE_TEST_CASE_P(HexadecimalInteger_A_F,
IntegerTest,
testing::Combine(testing::Values("0x", "0X"),
CLOSED_RANGE('A', 'F')));
class FloatTest : public PreprocessorTest
{
protected:
void expectFloat(const std::string& str)
{
const char* cstr = str.c_str();
ASSERT_TRUE(mPreprocessor.init(1, &cstr, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::CONST_FLOAT, token.type);
EXPECT_EQ(str, token.text);
}
};
typedef std::tr1::tuple<char, char, const char*, char> FloatScientificParams;
class FloatScientificTest :
public FloatTest,
public testing::WithParamInterface<FloatScientificParams>
{
};
// This test covers floating point numbers of form [0-9][eE][+-]?[0-9].
TEST_P(FloatScientificTest, FloatIdentified)
{
std::string str;
str.push_back(std::tr1::get<0>(GetParam())); // significand [0-9].
str.push_back(std::tr1::get<1>(GetParam())); // separator [eE].
str.append(std::tr1::get<2>(GetParam())); // sign [" " "+" "-"].
str.push_back(std::tr1::get<3>(GetParam())); // exponent [0-9].
SCOPED_TRACE("FloatScientificTest");
expectFloat(str);
}
INSTANTIATE_TEST_CASE_P(FloatScientific,
FloatScientificTest,
testing::Combine(CLOSED_RANGE('0', '9'),
testing::Values('e', 'E'),
testing::Values("", "+", "-"),
CLOSED_RANGE('0', '9')));
typedef std::tr1::tuple<char, char> FloatFractionParams;
class FloatFractionTest :
public FloatTest,
public testing::WithParamInterface<FloatFractionParams>
{
};
// This test covers floating point numbers of form [0-9]"." and [0-9]?"."[0-9].
TEST_P(FloatFractionTest, FloatIdentified)
{
std::string str;
char significand = std::tr1::get<0>(GetParam());
if (significand != '\0')
str.push_back(significand);
str.push_back('.');
char fraction = std::tr1::get<1>(GetParam());
if (fraction != '\0')
str.push_back(fraction);
SCOPED_TRACE("FloatFractionTest");
expectFloat(str);
}
INSTANTIATE_TEST_CASE_P(FloatFraction_X_X,
FloatFractionTest,
testing::Combine(CLOSED_RANGE('0', '9'),
CLOSED_RANGE('0', '9')));
INSTANTIATE_TEST_CASE_P(FloatFraction_0_X,
FloatFractionTest,
testing::Combine(testing::Values('\0'),
CLOSED_RANGE('0', '9')));
INSTANTIATE_TEST_CASE_P(FloatFraction_X_0,
FloatFractionTest,
testing::Combine(CLOSED_RANGE('0', '9'),
testing::Values('\0')));
// In the tests above we have tested individual parts of a float separately.
// This test has all parts of a float.
TEST_F(FloatTest, FractionScientific)
{
SCOPED_TRACE("FractionScientific");
expectFloat("0.1e+2");
}
| 010smithzhang-ddd | tests/preprocessor_tests/number_test.cpp | C++ | bsd | 5,556 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class CommentTest : public PreprocessorTest,
public testing::WithParamInterface<const char*>
{
};
TEST_P(CommentTest, CommentIgnored)
{
const char* str = GetParam();
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::LAST, token.type);
}
INSTANTIATE_TEST_CASE_P(LineComment, CommentTest,
testing::Values("//foo\n", // With newline.
"//foo", // Without newline.
"//**/", // Nested block comment.
"////", // Nested line comment.
"//\"")); // Invalid character.
INSTANTIATE_TEST_CASE_P(BlockComment, CommentTest,
testing::Values("/*foo*/",
"/*foo\n*/", // With newline.
"/*//*/", // Nested line comment.
"/*/**/", // Nested block comment.
"/***/", // With lone '*'.
"/*\"*/")); // Invalid character.
class BlockCommentTest : public PreprocessorTest
{
};
TEST_F(BlockCommentTest, CommentReplacedWithSpace)
{
const char* str = "/*foo*/bar";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("bar", token.text);
EXPECT_TRUE(token.hasLeadingSpace());
}
TEST_F(BlockCommentTest, UnterminatedComment)
{
const char* str = "/*foo";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
using testing::_;
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_COMMENT, _, _));
pp::Token token;
mPreprocessor.lex(&token);
}
| 010smithzhang-ddd | tests/preprocessor_tests/comment_test.cpp | C++ | bsd | 2,122 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "gtest/gtest.h"
#include "Token.h"
TEST(TokenTest, DefaultConstructor)
{
pp::Token token;
EXPECT_EQ(0, token.type);
EXPECT_EQ(0, token.flags);
EXPECT_EQ(0, token.location.line);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ("", token.text);
}
TEST(TokenTest, Assignment)
{
pp::Token token;
token.type = 1;
token.flags = 1;
token.location.line = 1;
token.location.file = 1;
token.text.assign("foo");
token = pp::Token();
EXPECT_EQ(0, token.type);
EXPECT_EQ(0, token.flags);
EXPECT_EQ(0, token.location.line);
EXPECT_EQ(0, token.location.file);
EXPECT_EQ("", token.text);
}
TEST(TokenTest, Equals)
{
pp::Token token;
EXPECT_TRUE(token.equals(pp::Token()));
token.type = 1;
EXPECT_FALSE(token.equals(pp::Token()));
token.type = 0;
token.flags = 1;
EXPECT_FALSE(token.equals(pp::Token()));
token.flags = 0;
token.location.line = 1;
EXPECT_FALSE(token.equals(pp::Token()));
token.location.line = 0;
token.location.file = 1;
EXPECT_FALSE(token.equals(pp::Token()));
token.location.file = 0;
token.text.assign("foo");
EXPECT_FALSE(token.equals(pp::Token()));
token.text.clear();
EXPECT_TRUE(token.equals(pp::Token()));
}
TEST(TokenTest, HasLeadingSpace)
{
pp::Token token;
EXPECT_FALSE(token.hasLeadingSpace());
token.setHasLeadingSpace(true);
EXPECT_TRUE(token.hasLeadingSpace());
token.setHasLeadingSpace(false);
EXPECT_FALSE(token.hasLeadingSpace());
}
TEST(TokenTest, Write)
{
pp::Token token;
token.text.assign("foo");
std::stringstream out1;
out1 << token;
EXPECT_TRUE(out1.good());
EXPECT_EQ("foo", out1.str());
token.setHasLeadingSpace(true);
std::stringstream out2;
out2 << token;
EXPECT_TRUE(out2.good());
EXPECT_EQ(" foo", out2.str());
}
| 010smithzhang-ddd | tests/preprocessor_tests/token_test.cpp | C++ | bsd | 2,057 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class ExtensionTest : public PreprocessorTest
{
};
TEST_F(ExtensionTest, Valid)
{
const char* str = "#extension foo : bar\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleExtension(pp::SourceLocation(0, 1), "foo", "bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ExtensionTest, Comments)
{
const char* str = "/*foo*/"
"#"
"/*foo*/"
"extension"
"/*foo*/"
"foo"
"/*foo*/"
":"
"/*foo*/"
"bar"
"/*foo*/"
"//foo"
"\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleExtension(pp::SourceLocation(0, 1), "foo", "bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ExtensionTest, MissingNewline)
{
const char* str = "#extension foo : bar";
const char* expected = "";
using testing::_;
// Directive successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handleExtension(pp::SourceLocation(0, 1), "foo", "bar"));
// Error reported about EOF.
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));
preprocess(str, expected);
}
struct ExtensionTestParam
{
const char* str;
pp::Diagnostics::ID id;
};
using testing::WithParamInterface;
class InvalidExtensionTest : public ExtensionTest,
public WithParamInterface<ExtensionTestParam>
{
};
TEST_P(InvalidExtensionTest, Identified)
{
ExtensionTestParam param = GetParam();
const char* expected = "\n";
using testing::_;
// No handleExtension call.
EXPECT_CALL(mDirectiveHandler, handleExtension(_, _, _)).Times(0);
// Invalid extension directive call.
EXPECT_CALL(mDiagnostics, print(param.id, pp::SourceLocation(0, 1), _));
preprocess(param.str, expected);
}
static const ExtensionTestParam kParams[] = {
{"#extension\n", pp::Diagnostics::INVALID_EXTENSION_DIRECTIVE},
{"#extension 1\n", pp::Diagnostics::INVALID_EXTENSION_NAME},
{"#extension foo bar\n", pp::Diagnostics::UNEXPECTED_TOKEN},
{"#extension foo : \n", pp::Diagnostics::INVALID_EXTENSION_DIRECTIVE},
{"#extension foo : 1\n", pp::Diagnostics::INVALID_EXTENSION_BEHAVIOR},
{"#extension foo : bar baz\n", pp::Diagnostics::UNEXPECTED_TOKEN}
};
INSTANTIATE_TEST_CASE_P(All, InvalidExtensionTest, testing::ValuesIn(kParams));
| 010smithzhang-ddd | tests/preprocessor_tests/extension_test.cpp | C++ | bsd | 2,989 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <algorithm>
#include <climits>
#include "PreprocessorTest.h"
#include "Token.h"
class CharTest : public PreprocessorTest,
public testing::WithParamInterface<int>
{
};
static const char kPunctuators[] = {
'.', '+', '-', '/', '*', '%', '<', '>', '[', ']', '(', ')', '{', '}',
'^', '|', '&', '~', '=', '!', ':', ';', ',', '?'};
static const int kNumPunctuators =
sizeof(kPunctuators) / sizeof(kPunctuators[0]);
bool isPunctuator(char c)
{
static const char* kPunctuatorBeg = kPunctuators;
static const char* kPunctuatorEnd = kPunctuators + kNumPunctuators;
return std::find(kPunctuatorBeg, kPunctuatorEnd, c) != kPunctuatorEnd;
}
static const char kWhitespaces[] = {' ', '\t', '\v', '\f', '\n', '\r'};
static const int kNumWhitespaces =
sizeof(kWhitespaces) / sizeof(kWhitespaces[0]);
bool isWhitespace(char c)
{
static const char* kWhitespaceBeg = kWhitespaces;
static const char* kWhitespaceEnd = kWhitespaces + kNumWhitespaces;
return std::find(kWhitespaceBeg, kWhitespaceEnd, c) != kWhitespaceEnd;
}
TEST_P(CharTest, Identified)
{
std::string str(1, GetParam());
const char* cstr = str.c_str();
int length = 1;
// Note that we pass the length param as well because the invalid
// string may contain the null character.
ASSERT_TRUE(mPreprocessor.init(1, &cstr, &length));
int expectedType = pp::Token::LAST;
std::string expectedValue;
if (str[0] == '#')
{
// Lone '#' is ignored.
}
else if ((str[0] == '_') ||
((str[0] >= 'a') && (str[0] <= 'z')) ||
((str[0] >= 'A') && (str[0] <= 'Z')))
{
expectedType = pp::Token::IDENTIFIER;
expectedValue = str;
}
else if (str[0] >= '0' && str[0] <= '9')
{
expectedType = pp::Token::CONST_INT;
expectedValue = str;
}
else if (isPunctuator(str[0]))
{
expectedType = str[0];
expectedValue = str;
}
else if (isWhitespace(str[0]))
{
// Whitespace is ignored.
}
else
{
// Everything else is invalid.
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INVALID_CHARACTER, _, str));
}
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(expectedType, token.type);
EXPECT_EQ(expectedValue, token.text);
};
// Note +1 for the max-value in range. It is there because the max-value
// not included in the range.
INSTANTIATE_TEST_CASE_P(All, CharTest,
testing::Range(CHAR_MIN, CHAR_MAX + 1));
| 010smithzhang-ddd | tests/preprocessor_tests/char_test.cpp | C++ | bsd | 2,765 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
struct OperatorTestParam
{
const char* str;
int op;
};
class OperatorTest : public PreprocessorTest,
public testing::WithParamInterface<OperatorTestParam>
{
};
TEST_P(OperatorTest, Identified)
{
OperatorTestParam param = GetParam();
ASSERT_TRUE(mPreprocessor.init(1, ¶m.str, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(param.op, token.type);
EXPECT_EQ(param.str, token.text);
}
static const OperatorTestParam kOperators[] = {
{"(", '('},
{")", ')'},
{"[", '['},
{"]", ']'},
{".", '.'},
{"+", '+'},
{"-", '-'},
{"~", '~'},
{"!", '!'},
{"*", '*'},
{"/", '/'},
{"%", '%'},
{"<", '<'},
{">", '>'},
{"&", '&'},
{"^", '^'},
{"|", '|'},
{"?", '?'},
{":", ':'},
{"=", '='},
{",", ','},
{"++", pp::Token::OP_INC},
{"--", pp::Token::OP_DEC},
{"<<", pp::Token::OP_LEFT},
{">>", pp::Token::OP_RIGHT},
{"<=", pp::Token::OP_LE},
{">=", pp::Token::OP_GE},
{"==", pp::Token::OP_EQ},
{"!=", pp::Token::OP_NE},
{"&&", pp::Token::OP_AND},
{"^^", pp::Token::OP_XOR},
{"||", pp::Token::OP_OR},
{"+=", pp::Token::OP_ADD_ASSIGN},
{"-=", pp::Token::OP_SUB_ASSIGN},
{"*=", pp::Token::OP_MUL_ASSIGN},
{"/=", pp::Token::OP_DIV_ASSIGN},
{"%=", pp::Token::OP_MOD_ASSIGN},
{"<<=", pp::Token::OP_LEFT_ASSIGN},
{">>=", pp::Token::OP_RIGHT_ASSIGN},
{"&=", pp::Token::OP_AND_ASSIGN},
{"^=", pp::Token::OP_XOR_ASSIGN},
{"|=", pp::Token::OP_OR_ASSIGN}
};
INSTANTIATE_TEST_CASE_P(All, OperatorTest,
testing::ValuesIn(kOperators));
| 010smithzhang-ddd | tests/preprocessor_tests/operator_test.cpp | C++ | bsd | 1,915 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
#define CLOSED_RANGE(x, y) testing::Range(x, static_cast<char>((y) + 1))
class IdentifierTest : public PreprocessorTest
{
protected:
void expectIdentifier(const std::string& str)
{
const char* cstr = str.c_str();
ASSERT_TRUE(mPreprocessor.init(1, &cstr, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ(str, token.text);
}
};
class SingleLetterIdentifierTest : public IdentifierTest,
public testing::WithParamInterface<char>
{
};
// This test covers identifier names of form [_a-zA-Z].
TEST_P(SingleLetterIdentifierTest, Identified)
{
std::string str(1, GetParam());
expectIdentifier(str);
}
// Test string: '_'
INSTANTIATE_TEST_CASE_P(Underscore,
SingleLetterIdentifierTest,
testing::Values('_'));
// Test string: [a-z]
INSTANTIATE_TEST_CASE_P(a_z,
SingleLetterIdentifierTest,
CLOSED_RANGE('a', 'z'));
// Test string: [A-Z]
INSTANTIATE_TEST_CASE_P(A_Z,
SingleLetterIdentifierTest,
CLOSED_RANGE('A', 'Z'));
typedef std::tr1::tuple<char, char> IdentifierParams;
class DoubleLetterIdentifierTest :
public IdentifierTest,
public testing::WithParamInterface<IdentifierParams>
{
};
// This test covers identifier names of form [_a-zA-Z][_a-zA-Z0-9].
TEST_P(DoubleLetterIdentifierTest, Identified)
{
std::string str;
str.push_back(std::tr1::get<0>(GetParam()));
str.push_back(std::tr1::get<1>(GetParam()));
expectIdentifier(str);
}
// Test string: "__"
INSTANTIATE_TEST_CASE_P(Underscore_Underscore,
DoubleLetterIdentifierTest,
testing::Combine(testing::Values('_'),
testing::Values('_')));
// Test string: "_"[a-z]
INSTANTIATE_TEST_CASE_P(Underscore_a_z,
DoubleLetterIdentifierTest,
testing::Combine(testing::Values('_'),
CLOSED_RANGE('a', 'z')));
// Test string: "_"[A-Z]
INSTANTIATE_TEST_CASE_P(Underscore_A_Z,
DoubleLetterIdentifierTest,
testing::Combine(testing::Values('_'),
CLOSED_RANGE('A', 'Z')));
// Test string: "_"[0-9]
INSTANTIATE_TEST_CASE_P(Underscore_0_9,
DoubleLetterIdentifierTest,
testing::Combine(testing::Values('_'),
CLOSED_RANGE('0', '9')));
// Test string: [a-z]"_"
INSTANTIATE_TEST_CASE_P(a_z_Underscore,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('a', 'z'),
testing::Values('_')));
// Test string: [a-z][a-z]
INSTANTIATE_TEST_CASE_P(a_z_a_z,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('a', 'z'),
CLOSED_RANGE('a', 'z')));
// Test string: [a-z][A-Z]
INSTANTIATE_TEST_CASE_P(a_z_A_Z,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('a', 'z'),
CLOSED_RANGE('A', 'Z')));
// Test string: [a-z][0-9]
INSTANTIATE_TEST_CASE_P(a_z_0_9,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('a', 'z'),
CLOSED_RANGE('0', '9')));
// Test string: [A-Z]"_"
INSTANTIATE_TEST_CASE_P(A_Z_Underscore,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('A', 'Z'),
testing::Values('_')));
// Test string: [A-Z][a-z]
INSTANTIATE_TEST_CASE_P(A_Z_a_z,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('A', 'Z'),
CLOSED_RANGE('a', 'z')));
// Test string: [A-Z][A-Z]
INSTANTIATE_TEST_CASE_P(A_Z_A_Z,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('A', 'Z'),
CLOSED_RANGE('A', 'Z')));
// Test string: [A-Z][0-9]
INSTANTIATE_TEST_CASE_P(A_Z_0_9,
DoubleLetterIdentifierTest,
testing::Combine(CLOSED_RANGE('A', 'Z'),
CLOSED_RANGE('0', '9')));
// The tests above cover one-letter and various combinations of two-letter
// identifier names. This test covers all characters in a single string.
TEST_F(IdentifierTest, AllLetters)
{
std::string str;
for (int c = 'a'; c <= 'z'; ++c)
str.push_back(c);
str.push_back('_');
for (int c = 'A'; c <= 'Z'; ++c)
str.push_back(c);
str.push_back('_');
for (int c = '0'; c <= '9'; ++c)
str.push_back(c);
expectIdentifier(str);
}
| 010smithzhang-ddd | tests/preprocessor_tests/identifier_test.cpp | C++ | bsd | 5,331 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class SpaceTest : public PreprocessorTest
{
protected:
void expectSpace(const std::string& str)
{
const char* cstr = str.c_str();
ASSERT_TRUE(mPreprocessor.init(1, &cstr, 0));
pp::Token token;
// "foo" is returned after ignoring the whitespace characters.
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
// The whitespace character is however recorded with the next token.
EXPECT_TRUE(token.hasLeadingSpace());
}
};
// Whitespace characters allowed in GLSL.
// Note that newline characters (\n) will be tested separately.
static const char kSpaceChars[] = {' ', '\t', '\v', '\f'};
// This test fixture tests the processing of a single whitespace character.
// All tests in this fixture are ran with all possible whitespace character
// allowed in GLSL.
class SpaceCharTest : public SpaceTest,
public testing::WithParamInterface<char>
{
};
TEST_P(SpaceCharTest, SpaceIgnored)
{
// Construct test string with the whitespace char before "foo".
std::string str(1, GetParam());
str.append("foo");
expectSpace(str);
}
INSTANTIATE_TEST_CASE_P(SingleSpaceChar,
SpaceCharTest,
testing::ValuesIn(kSpaceChars));
// This test fixture tests the processing of a string containing consecutive
// whitespace characters. All tests in this fixture are ran with all possible
// combinations of whitespace characters allowed in GLSL.
typedef std::tr1::tuple<char, char, char> SpaceStringParams;
class SpaceStringTest : public SpaceTest,
public testing::WithParamInterface<SpaceStringParams>
{
};
TEST_P(SpaceStringTest, SpaceIgnored)
{
// Construct test string with the whitespace char before "foo".
std::string str;
str.push_back(std::tr1::get<0>(GetParam()));
str.push_back(std::tr1::get<1>(GetParam()));
str.push_back(std::tr1::get<2>(GetParam()));
str.append("foo");
expectSpace(str);
}
INSTANTIATE_TEST_CASE_P(SpaceCharCombination,
SpaceStringTest,
testing::Combine(testing::ValuesIn(kSpaceChars),
testing::ValuesIn(kSpaceChars),
testing::ValuesIn(kSpaceChars)));
// The tests above make sure that the space char is recorded in the
// next token. This test makes sure that a token is not incorrectly marked
// to have leading space.
TEST_F(SpaceTest, LeadingSpace)
{
const char* str = " foo+ -bar";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("foo", token.text);
EXPECT_TRUE(token.hasLeadingSpace());
mPreprocessor.lex(&token);
EXPECT_EQ('+', token.type);
EXPECT_FALSE(token.hasLeadingSpace());
mPreprocessor.lex(&token);
EXPECT_EQ('-', token.type);
EXPECT_TRUE(token.hasLeadingSpace());
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::IDENTIFIER, token.type);
EXPECT_EQ("bar", token.text);
EXPECT_FALSE(token.hasLeadingSpace());
}
| 010smithzhang-ddd | tests/preprocessor_tests/space_test.cpp | C++ | bsd | 3,441 |