code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
//
// 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.
//
// Contains analysis utilities for dealing with HLSL's lack of support for
// the use of intrinsic functions which (implicitly or explicitly) compute
// gradients of functions with discontinuities.
//
#include "compiler/DetectDiscontinuity.h"
#include "compiler/ParseHelper.h"
namespace sh
{
bool DetectLoopDiscontinuity::traverse(TIntermNode *node)
{
mLoopDepth = 0;
mLoopDiscontinuity = false;
node->traverse(this);
return mLoopDiscontinuity;
}
bool DetectLoopDiscontinuity::visitLoop(Visit visit, TIntermLoop *loop)
{
if (visit == PreVisit)
{
++mLoopDepth;
}
else if (visit == PostVisit)
{
--mLoopDepth;
}
return true;
}
bool DetectLoopDiscontinuity::visitBranch(Visit visit, TIntermBranch *node)
{
if (mLoopDiscontinuity)
{
return false;
}
if (!mLoopDepth)
{
return true;
}
switch (node->getFlowOp())
{
case EOpKill:
break;
case EOpBreak:
case EOpContinue:
case EOpReturn:
mLoopDiscontinuity = true;
break;
default: UNREACHABLE();
}
return !mLoopDiscontinuity;
}
bool DetectLoopDiscontinuity::visitAggregate(Visit visit, TIntermAggregate *node)
{
return !mLoopDiscontinuity;
}
bool containsLoopDiscontinuity(TIntermNode *node)
{
DetectLoopDiscontinuity detectLoopDiscontinuity;
return detectLoopDiscontinuity.traverse(node);
}
bool DetectGradientOperation::traverse(TIntermNode *node)
{
mGradientOperation = false;
node->traverse(this);
return mGradientOperation;
}
bool DetectGradientOperation::visitUnary(Visit visit, TIntermUnary *node)
{
if (mGradientOperation)
{
return false;
}
switch (node->getOp())
{
case EOpDFdx:
case EOpDFdy:
mGradientOperation = true;
default:
break;
}
return !mGradientOperation;
}
bool DetectGradientOperation::visitAggregate(Visit visit, TIntermAggregate *node)
{
if (mGradientOperation)
{
return false;
}
if (node->getOp() == EOpFunctionCall)
{
if (!node->isUserDefined())
{
TString name = TFunction::unmangleName(node->getName());
if (name == "texture2D" ||
name == "texture2DProj" ||
name == "textureCube")
{
mGradientOperation = true;
}
}
else
{
// When a user defined function is called, we have to
// conservatively assume it to contain gradient operations
mGradientOperation = true;
}
}
return !mGradientOperation;
}
bool containsGradientOperation(TIntermNode *node)
{
DetectGradientOperation detectGradientOperation;
return detectGradientOperation.traverse(node);
}
}
| C++ |
//
// 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.
//
#ifndef _SYMBOL_TABLE_INCLUDED_
#define _SYMBOL_TABLE_INCLUDED_
//
// Symbol table for parsing. Has these design characteristics:
//
// * Same symbol table can be used to compile many shaders, to preserve
// effort of creating and loading with the large numbers of built-in
// symbols.
//
// * Name mangling will be used to give each function a unique name
// so that symbol table lookups are never ambiguous. This allows
// a simpler symbol table structure.
//
// * Pushing and popping of scope, so symbol table will really be a stack
// of symbol tables. Searched from the top, with new inserts going into
// the top.
//
// * Constants: Compile time constant symbols will keep their values
// in the symbol table. The parser can substitute constants at parse
// time, including doing constant folding and constant propagation.
//
// * No temporaries: Temporaries made from operations (+, --, .xy, etc.)
// are tracked in the intermediate representation, not the symbol table.
//
#include <assert.h>
#include "common/angleutils.h"
#include "compiler/InfoSink.h"
#include "compiler/intermediate.h"
//
// Symbol base class. (Can build functions or variables out of these...)
//
class TSymbol {
public:
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
TSymbol(const TString *n) : name(n) { }
virtual ~TSymbol() { /* don't delete name, it's from the pool */ }
const TString& getName() const { return *name; }
virtual const TString& getMangledName() const { return getName(); }
virtual bool isFunction() const { return false; }
virtual bool isVariable() const { return false; }
void setUniqueId(int id) { uniqueId = id; }
int getUniqueId() const { return uniqueId; }
virtual void dump(TInfoSink &infoSink) const = 0;
void relateToExtension(const TString& ext) { extension = ext; }
const TString& getExtension() const { return extension; }
private:
DISALLOW_COPY_AND_ASSIGN(TSymbol);
const TString *name;
unsigned int uniqueId; // For real comparing during code generation
TString extension;
};
//
// Variable class, meaning a symbol that's not a function.
//
// There could be a separate class heirarchy for Constant variables;
// Only one of int, bool, or float, (or none) is correct for
// any particular use, but it's easy to do this way, and doesn't
// seem worth having separate classes, and "getConst" can't simply return
// different values for different types polymorphically, so this is
// just simple and pragmatic.
//
class TVariable : public TSymbol {
public:
TVariable(const TString *name, const TType& t, bool uT = false ) : TSymbol(name), type(t), userType(uT), unionArray(0) { }
virtual ~TVariable() { }
virtual bool isVariable() const { return true; }
TType& getType() { return type; }
const TType& getType() const { return type; }
bool isUserType() const { return userType; }
void setQualifier(TQualifier qualifier) { type.setQualifier(qualifier); }
virtual void dump(TInfoSink &infoSink) const;
ConstantUnion* getConstPointer()
{
if (!unionArray)
unionArray = new ConstantUnion[type.getObjectSize()];
return unionArray;
}
ConstantUnion* getConstPointer() const { return unionArray; }
void shareConstPointer( ConstantUnion *constArray)
{
if (unionArray == constArray)
return;
delete[] unionArray;
unionArray = constArray;
}
private:
DISALLOW_COPY_AND_ASSIGN(TVariable);
TType type;
bool userType;
// we are assuming that Pool Allocator will free the memory allocated to unionArray
// when this object is destroyed
ConstantUnion *unionArray;
};
//
// The function sub-class of symbols and the parser will need to
// share this definition of a function parameter.
//
struct TParameter {
TString *name;
TType* type;
};
//
// The function sub-class of a symbol.
//
class TFunction : public TSymbol {
public:
TFunction(TOperator o) :
TSymbol(0),
returnType(TType(EbtVoid, EbpUndefined)),
op(o),
defined(false) { }
TFunction(const TString *name, TType& retType, TOperator tOp = EOpNull) :
TSymbol(name),
returnType(retType),
mangledName(TFunction::mangleName(*name)),
op(tOp),
defined(false) { }
virtual ~TFunction();
virtual bool isFunction() const { return true; }
static TString mangleName(const TString& name) { return name + '('; }
static TString unmangleName(const TString& mangledName)
{
return TString(mangledName.c_str(), mangledName.find_first_of('('));
}
void addParameter(TParameter& p)
{
parameters.push_back(p);
mangledName = mangledName + p.type->getMangledName();
}
const TString& getMangledName() const { return mangledName; }
const TType& getReturnType() const { return returnType; }
void relateToOperator(TOperator o) { op = o; }
TOperator getBuiltInOp() const { return op; }
void setDefined() { defined = true; }
bool isDefined() { return defined; }
size_t getParamCount() const { return parameters.size(); }
const TParameter& getParam(size_t i) const { return parameters[i]; }
virtual void dump(TInfoSink &infoSink) const;
private:
DISALLOW_COPY_AND_ASSIGN(TFunction);
typedef TVector<TParameter> TParamList;
TParamList parameters;
TType returnType;
TString mangledName;
TOperator op;
bool defined;
};
class TSymbolTableLevel {
public:
typedef TMap<TString, TSymbol*> tLevel;
typedef tLevel::const_iterator const_iterator;
typedef const tLevel::value_type tLevelPair;
typedef std::pair<tLevel::iterator, bool> tInsertResult;
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
TSymbolTableLevel() { }
~TSymbolTableLevel();
bool insert(TSymbol& symbol)
{
//
// returning true means symbol was added to the table
//
tInsertResult result;
result = level.insert(tLevelPair(symbol.getMangledName(), &symbol));
return result.second;
}
TSymbol* find(const TString& name) const
{
tLevel::const_iterator it = level.find(name);
if (it == level.end())
return 0;
else
return (*it).second;
}
const_iterator begin() const
{
return level.begin();
}
const_iterator end() const
{
return level.end();
}
void relateToOperator(const char* name, TOperator op);
void relateToExtension(const char* name, const TString& ext);
void dump(TInfoSink &infoSink) const;
protected:
tLevel level;
};
class TSymbolTable {
public:
TSymbolTable() : uniqueId(0)
{
//
// The symbol table cannot be used until push() is called, but
// the lack of an initial call to push() can be used to detect
// that the symbol table has not been preloaded with built-ins.
//
}
~TSymbolTable()
{
// level 0 is always built In symbols, so we never pop that out
while (table.size() > 1)
pop();
}
//
// When the symbol table is initialized with the built-ins, there should
// 'push' calls, so that built-ins are at level 0 and the shader
// globals are at level 1.
//
bool isEmpty() { return table.size() == 0; }
bool atBuiltInLevel() { return table.size() == 1; }
bool atGlobalLevel() { return table.size() <= 2; }
void push()
{
table.push_back(new TSymbolTableLevel);
precisionStack.push_back( PrecisionStackLevel() );
}
void pop()
{
delete table[currentLevel()];
table.pop_back();
precisionStack.pop_back();
}
bool insert(TSymbol& symbol)
{
symbol.setUniqueId(++uniqueId);
return table[currentLevel()]->insert(symbol);
}
TSymbol* find(const TString& name, bool* builtIn = 0, bool *sameScope = 0)
{
int level = currentLevel();
TSymbol* symbol;
do {
symbol = table[level]->find(name);
--level;
} while (symbol == 0 && level >= 0);
level++;
if (builtIn)
*builtIn = level == 0;
if (sameScope)
*sameScope = level == currentLevel();
return symbol;
}
TSymbol *findBuiltIn(const TString &name)
{
return table[0]->find(name);
}
TSymbolTableLevel* getGlobalLevel() {
assert(table.size() >= 2);
return table[1];
}
TSymbolTableLevel* getOuterLevel() {
assert(table.size() >= 2);
return table[currentLevel() - 1];
}
void relateToOperator(const char* name, TOperator op) {
table[0]->relateToOperator(name, op);
}
void relateToExtension(const char* name, const TString& ext) {
table[0]->relateToExtension(name, ext);
}
int getMaxSymbolId() { return uniqueId; }
void dump(TInfoSink &infoSink) const;
bool setDefaultPrecision( const TPublicType& type, TPrecision prec ){
if (IsSampler(type.type))
return true; // Skip sampler types for the time being
if (type.type != EbtFloat && type.type != EbtInt)
return false; // Only set default precision for int/float
if (type.size != 1 || type.matrix || type.array)
return false; // Not allowed to set for aggregate types
int indexOfLastElement = static_cast<int>(precisionStack.size()) - 1;
precisionStack[indexOfLastElement][type.type] = prec; // Uses map operator [], overwrites the current value
return true;
}
// Searches down the precisionStack for a precision qualifier for the specified TBasicType
TPrecision getDefaultPrecision( TBasicType type){
if( type != EbtFloat && type != EbtInt ) return EbpUndefined;
int level = static_cast<int>(precisionStack.size()) - 1;
assert( level >= 0); // Just to be safe. Should not happen.
PrecisionStackLevel::iterator it;
TPrecision prec = EbpUndefined; // If we dont find anything we return this. Should we error check this?
while( level >= 0 ){
it = precisionStack[level].find( type );
if( it != precisionStack[level].end() ){
prec = (*it).second;
break;
}
level--;
}
return prec;
}
protected:
int currentLevel() const { return static_cast<int>(table.size()) - 1; }
std::vector<TSymbolTableLevel*> table;
typedef std::map< TBasicType, TPrecision > PrecisionStackLevel;
std::vector< PrecisionStackLevel > precisionStack;
int uniqueId; // for unique identification in code generation
};
#endif // _SYMBOL_TABLE_INCLUDED_
| C++ |
//
// Copyright (c) 2002-2011 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 "compiler/OutputGLSL.h"
TOutputGLSL::TOutputGLSL(TInfoSinkBase& objSink,
ShArrayIndexClampingStrategy clampingStrategy,
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable)
: TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable)
{
}
bool TOutputGLSL::writeVariablePrecision(TPrecision)
{
return false;
}
void TOutputGLSL::visitSymbol(TIntermSymbol* node)
{
TInfoSinkBase& out = objSink();
if (node->getSymbol() == "gl_FragDepthEXT")
{
out << "gl_FragDepth";
}
else
{
TOutputGLSLBase::visitSymbol(node);
}
}
| C++ |
//
// 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.
//
//
// Create strings that declare built-in definitions, add built-ins that
// cannot be expressed in the files, and establish mappings between
// built-in functions and operators.
//
#include "compiler/Initialize.h"
#include "compiler/intermediate.h"
//============================================================================
//
// Prototypes for built-in functions seen by both vertex and fragment shaders.
//
//============================================================================
static TString BuiltInFunctionsCommon(const ShBuiltInResources& resources)
{
TString s;
//
// Angle and Trigonometric Functions.
//
s.append(TString("float radians(float degrees);"));
s.append(TString("vec2 radians(vec2 degrees);"));
s.append(TString("vec3 radians(vec3 degrees);"));
s.append(TString("vec4 radians(vec4 degrees);"));
s.append(TString("float degrees(float radians);"));
s.append(TString("vec2 degrees(vec2 radians);"));
s.append(TString("vec3 degrees(vec3 radians);"));
s.append(TString("vec4 degrees(vec4 radians);"));
s.append(TString("float sin(float angle);"));
s.append(TString("vec2 sin(vec2 angle);"));
s.append(TString("vec3 sin(vec3 angle);"));
s.append(TString("vec4 sin(vec4 angle);"));
s.append(TString("float cos(float angle);"));
s.append(TString("vec2 cos(vec2 angle);"));
s.append(TString("vec3 cos(vec3 angle);"));
s.append(TString("vec4 cos(vec4 angle);"));
s.append(TString("float tan(float angle);"));
s.append(TString("vec2 tan(vec2 angle);"));
s.append(TString("vec3 tan(vec3 angle);"));
s.append(TString("vec4 tan(vec4 angle);"));
s.append(TString("float asin(float x);"));
s.append(TString("vec2 asin(vec2 x);"));
s.append(TString("vec3 asin(vec3 x);"));
s.append(TString("vec4 asin(vec4 x);"));
s.append(TString("float acos(float x);"));
s.append(TString("vec2 acos(vec2 x);"));
s.append(TString("vec3 acos(vec3 x);"));
s.append(TString("vec4 acos(vec4 x);"));
s.append(TString("float atan(float y, float x);"));
s.append(TString("vec2 atan(vec2 y, vec2 x);"));
s.append(TString("vec3 atan(vec3 y, vec3 x);"));
s.append(TString("vec4 atan(vec4 y, vec4 x);"));
s.append(TString("float atan(float y_over_x);"));
s.append(TString("vec2 atan(vec2 y_over_x);"));
s.append(TString("vec3 atan(vec3 y_over_x);"));
s.append(TString("vec4 atan(vec4 y_over_x);"));
//
// Exponential Functions.
//
s.append(TString("float pow(float x, float y);"));
s.append(TString("vec2 pow(vec2 x, vec2 y);"));
s.append(TString("vec3 pow(vec3 x, vec3 y);"));
s.append(TString("vec4 pow(vec4 x, vec4 y);"));
s.append(TString("float exp(float x);"));
s.append(TString("vec2 exp(vec2 x);"));
s.append(TString("vec3 exp(vec3 x);"));
s.append(TString("vec4 exp(vec4 x);"));
s.append(TString("float log(float x);"));
s.append(TString("vec2 log(vec2 x);"));
s.append(TString("vec3 log(vec3 x);"));
s.append(TString("vec4 log(vec4 x);"));
s.append(TString("float exp2(float x);"));
s.append(TString("vec2 exp2(vec2 x);"));
s.append(TString("vec3 exp2(vec3 x);"));
s.append(TString("vec4 exp2(vec4 x);"));
s.append(TString("float log2(float x);"));
s.append(TString("vec2 log2(vec2 x);"));
s.append(TString("vec3 log2(vec3 x);"));
s.append(TString("vec4 log2(vec4 x);"));
s.append(TString("float sqrt(float x);"));
s.append(TString("vec2 sqrt(vec2 x);"));
s.append(TString("vec3 sqrt(vec3 x);"));
s.append(TString("vec4 sqrt(vec4 x);"));
s.append(TString("float inversesqrt(float x);"));
s.append(TString("vec2 inversesqrt(vec2 x);"));
s.append(TString("vec3 inversesqrt(vec3 x);"));
s.append(TString("vec4 inversesqrt(vec4 x);"));
//
// Common Functions.
//
s.append(TString("float abs(float x);"));
s.append(TString("vec2 abs(vec2 x);"));
s.append(TString("vec3 abs(vec3 x);"));
s.append(TString("vec4 abs(vec4 x);"));
s.append(TString("float sign(float x);"));
s.append(TString("vec2 sign(vec2 x);"));
s.append(TString("vec3 sign(vec3 x);"));
s.append(TString("vec4 sign(vec4 x);"));
s.append(TString("float floor(float x);"));
s.append(TString("vec2 floor(vec2 x);"));
s.append(TString("vec3 floor(vec3 x);"));
s.append(TString("vec4 floor(vec4 x);"));
s.append(TString("float ceil(float x);"));
s.append(TString("vec2 ceil(vec2 x);"));
s.append(TString("vec3 ceil(vec3 x);"));
s.append(TString("vec4 ceil(vec4 x);"));
s.append(TString("float fract(float x);"));
s.append(TString("vec2 fract(vec2 x);"));
s.append(TString("vec3 fract(vec3 x);"));
s.append(TString("vec4 fract(vec4 x);"));
s.append(TString("float mod(float x, float y);"));
s.append(TString("vec2 mod(vec2 x, float y);"));
s.append(TString("vec3 mod(vec3 x, float y);"));
s.append(TString("vec4 mod(vec4 x, float y);"));
s.append(TString("vec2 mod(vec2 x, vec2 y);"));
s.append(TString("vec3 mod(vec3 x, vec3 y);"));
s.append(TString("vec4 mod(vec4 x, vec4 y);"));
s.append(TString("float min(float x, float y);"));
s.append(TString("vec2 min(vec2 x, float y);"));
s.append(TString("vec3 min(vec3 x, float y);"));
s.append(TString("vec4 min(vec4 x, float y);"));
s.append(TString("vec2 min(vec2 x, vec2 y);"));
s.append(TString("vec3 min(vec3 x, vec3 y);"));
s.append(TString("vec4 min(vec4 x, vec4 y);"));
s.append(TString("float max(float x, float y);"));
s.append(TString("vec2 max(vec2 x, float y);"));
s.append(TString("vec3 max(vec3 x, float y);"));
s.append(TString("vec4 max(vec4 x, float y);"));
s.append(TString("vec2 max(vec2 x, vec2 y);"));
s.append(TString("vec3 max(vec3 x, vec3 y);"));
s.append(TString("vec4 max(vec4 x, vec4 y);"));
s.append(TString("float clamp(float x, float minVal, float maxVal);"));
s.append(TString("vec2 clamp(vec2 x, float minVal, float maxVal);"));
s.append(TString("vec3 clamp(vec3 x, float minVal, float maxVal);"));
s.append(TString("vec4 clamp(vec4 x, float minVal, float maxVal);"));
s.append(TString("vec2 clamp(vec2 x, vec2 minVal, vec2 maxVal);"));
s.append(TString("vec3 clamp(vec3 x, vec3 minVal, vec3 maxVal);"));
s.append(TString("vec4 clamp(vec4 x, vec4 minVal, vec4 maxVal);"));
s.append(TString("float mix(float x, float y, float a);"));
s.append(TString("vec2 mix(vec2 x, vec2 y, float a);"));
s.append(TString("vec3 mix(vec3 x, vec3 y, float a);"));
s.append(TString("vec4 mix(vec4 x, vec4 y, float a);"));
s.append(TString("vec2 mix(vec2 x, vec2 y, vec2 a);"));
s.append(TString("vec3 mix(vec3 x, vec3 y, vec3 a);"));
s.append(TString("vec4 mix(vec4 x, vec4 y, vec4 a);"));
s.append(TString("float step(float edge, float x);"));
s.append(TString("vec2 step(vec2 edge, vec2 x);"));
s.append(TString("vec3 step(vec3 edge, vec3 x);"));
s.append(TString("vec4 step(vec4 edge, vec4 x);"));
s.append(TString("vec2 step(float edge, vec2 x);"));
s.append(TString("vec3 step(float edge, vec3 x);"));
s.append(TString("vec4 step(float edge, vec4 x);"));
s.append(TString("float smoothstep(float edge0, float edge1, float x);"));
s.append(TString("vec2 smoothstep(vec2 edge0, vec2 edge1, vec2 x);"));
s.append(TString("vec3 smoothstep(vec3 edge0, vec3 edge1, vec3 x);"));
s.append(TString("vec4 smoothstep(vec4 edge0, vec4 edge1, vec4 x);"));
s.append(TString("vec2 smoothstep(float edge0, float edge1, vec2 x);"));
s.append(TString("vec3 smoothstep(float edge0, float edge1, vec3 x);"));
s.append(TString("vec4 smoothstep(float edge0, float edge1, vec4 x);"));
//
// Geometric Functions.
//
s.append(TString("float length(float x);"));
s.append(TString("float length(vec2 x);"));
s.append(TString("float length(vec3 x);"));
s.append(TString("float length(vec4 x);"));
s.append(TString("float distance(float p0, float p1);"));
s.append(TString("float distance(vec2 p0, vec2 p1);"));
s.append(TString("float distance(vec3 p0, vec3 p1);"));
s.append(TString("float distance(vec4 p0, vec4 p1);"));
s.append(TString("float dot(float x, float y);"));
s.append(TString("float dot(vec2 x, vec2 y);"));
s.append(TString("float dot(vec3 x, vec3 y);"));
s.append(TString("float dot(vec4 x, vec4 y);"));
s.append(TString("vec3 cross(vec3 x, vec3 y);"));
s.append(TString("float normalize(float x);"));
s.append(TString("vec2 normalize(vec2 x);"));
s.append(TString("vec3 normalize(vec3 x);"));
s.append(TString("vec4 normalize(vec4 x);"));
s.append(TString("float faceforward(float N, float I, float Nref);"));
s.append(TString("vec2 faceforward(vec2 N, vec2 I, vec2 Nref);"));
s.append(TString("vec3 faceforward(vec3 N, vec3 I, vec3 Nref);"));
s.append(TString("vec4 faceforward(vec4 N, vec4 I, vec4 Nref);"));
s.append(TString("float reflect(float I, float N);"));
s.append(TString("vec2 reflect(vec2 I, vec2 N);"));
s.append(TString("vec3 reflect(vec3 I, vec3 N);"));
s.append(TString("vec4 reflect(vec4 I, vec4 N);"));
s.append(TString("float refract(float I, float N, float eta);"));
s.append(TString("vec2 refract(vec2 I, vec2 N, float eta);"));
s.append(TString("vec3 refract(vec3 I, vec3 N, float eta);"));
s.append(TString("vec4 refract(vec4 I, vec4 N, float eta);"));
//
// Matrix Functions.
//
s.append(TString("mat2 matrixCompMult(mat2 x, mat2 y);"));
s.append(TString("mat3 matrixCompMult(mat3 x, mat3 y);"));
s.append(TString("mat4 matrixCompMult(mat4 x, mat4 y);"));
//
// Vector relational functions.
//
s.append(TString("bvec2 lessThan(vec2 x, vec2 y);"));
s.append(TString("bvec3 lessThan(vec3 x, vec3 y);"));
s.append(TString("bvec4 lessThan(vec4 x, vec4 y);"));
s.append(TString("bvec2 lessThan(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 lessThan(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 lessThan(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 lessThanEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 lessThanEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 lessThanEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 lessThanEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 lessThanEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 lessThanEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 greaterThan(vec2 x, vec2 y);"));
s.append(TString("bvec3 greaterThan(vec3 x, vec3 y);"));
s.append(TString("bvec4 greaterThan(vec4 x, vec4 y);"));
s.append(TString("bvec2 greaterThan(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 greaterThan(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 greaterThan(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 greaterThanEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 greaterThanEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 greaterThanEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 greaterThanEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 greaterThanEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 greaterThanEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 equal(vec2 x, vec2 y);"));
s.append(TString("bvec3 equal(vec3 x, vec3 y);"));
s.append(TString("bvec4 equal(vec4 x, vec4 y);"));
s.append(TString("bvec2 equal(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 equal(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 equal(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 equal(bvec2 x, bvec2 y);"));
s.append(TString("bvec3 equal(bvec3 x, bvec3 y);"));
s.append(TString("bvec4 equal(bvec4 x, bvec4 y);"));
s.append(TString("bvec2 notEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 notEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 notEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 notEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 notEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 notEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 notEqual(bvec2 x, bvec2 y);"));
s.append(TString("bvec3 notEqual(bvec3 x, bvec3 y);"));
s.append(TString("bvec4 notEqual(bvec4 x, bvec4 y);"));
s.append(TString("bool any(bvec2 x);"));
s.append(TString("bool any(bvec3 x);"));
s.append(TString("bool any(bvec4 x);"));
s.append(TString("bool all(bvec2 x);"));
s.append(TString("bool all(bvec3 x);"));
s.append(TString("bool all(bvec4 x);"));
s.append(TString("bvec2 not(bvec2 x);"));
s.append(TString("bvec3 not(bvec3 x);"));
s.append(TString("bvec4 not(bvec4 x);"));
//
// Texture Functions.
//
s.append(TString("vec4 texture2D(sampler2D sampler, vec2 coord);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec3 coord);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec4 coord);"));
s.append(TString("vec4 textureCube(samplerCube sampler, vec3 coord);"));
if (resources.OES_EGL_image_external) {
s.append(TString("vec4 texture2D(samplerExternalOES sampler, vec2 coord);"));
s.append(TString("vec4 texture2DProj(samplerExternalOES sampler, vec3 coord);"));
s.append(TString("vec4 texture2DProj(samplerExternalOES sampler, vec4 coord);"));
}
if (resources.ARB_texture_rectangle) {
s.append(TString("vec4 texture2DRect(sampler2DRect sampler, vec2 coord);"));
s.append(TString("vec4 texture2DRectProj(sampler2DRect sampler, vec3 coord);"));
s.append(TString("vec4 texture2DRectProj(sampler2DRect sampler, vec4 coord);"));
}
//
// Noise functions.
//
//s.append(TString("float noise1(float x);"));
//s.append(TString("float noise1(vec2 x);"));
//s.append(TString("float noise1(vec3 x);"));
//s.append(TString("float noise1(vec4 x);"));
//s.append(TString("vec2 noise2(float x);"));
//s.append(TString("vec2 noise2(vec2 x);"));
//s.append(TString("vec2 noise2(vec3 x);"));
//s.append(TString("vec2 noise2(vec4 x);"));
//s.append(TString("vec3 noise3(float x);"));
//s.append(TString("vec3 noise3(vec2 x);"));
//s.append(TString("vec3 noise3(vec3 x);"));
//s.append(TString("vec3 noise3(vec4 x);"));
//s.append(TString("vec4 noise4(float x);"));
//s.append(TString("vec4 noise4(vec2 x);"));
//s.append(TString("vec4 noise4(vec3 x);"));
//s.append(TString("vec4 noise4(vec4 x);"));
return s;
}
//============================================================================
//
// Prototypes for built-in functions seen by vertex shaders only.
//
//============================================================================
static TString BuiltInFunctionsVertex(const ShBuiltInResources& resources)
{
TString s;
//
// Geometric Functions.
//
//s.append(TString("vec4 ftransform();"));
//
// Texture Functions.
//
s.append(TString("vec4 texture2DLod(sampler2D sampler, vec2 coord, float lod);"));
s.append(TString("vec4 texture2DProjLod(sampler2D sampler, vec3 coord, float lod);"));
s.append(TString("vec4 texture2DProjLod(sampler2D sampler, vec4 coord, float lod);"));
s.append(TString("vec4 textureCubeLod(samplerCube sampler, vec3 coord, float lod);"));
return s;
}
//============================================================================
//
// Prototypes for built-in functions seen by fragment shaders only.
//
//============================================================================
static TString BuiltInFunctionsFragment(const ShBuiltInResources& resources)
{
TString s;
//
// Texture Functions.
//
s.append(TString("vec4 texture2D(sampler2D sampler, vec2 coord, float bias);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec3 coord, float bias);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec4 coord, float bias);"));
s.append(TString("vec4 textureCube(samplerCube sampler, vec3 coord, float bias);"));
if (resources.OES_standard_derivatives) {
s.append(TString("float dFdx(float p);"));
s.append(TString("vec2 dFdx(vec2 p);"));
s.append(TString("vec3 dFdx(vec3 p);"));
s.append(TString("vec4 dFdx(vec4 p);"));
s.append(TString("float dFdy(float p);"));
s.append(TString("vec2 dFdy(vec2 p);"));
s.append(TString("vec3 dFdy(vec3 p);"));
s.append(TString("vec4 dFdy(vec4 p);"));
s.append(TString("float fwidth(float p);"));
s.append(TString("vec2 fwidth(vec2 p);"));
s.append(TString("vec3 fwidth(vec3 p);"));
s.append(TString("vec4 fwidth(vec4 p);"));
}
return s;
}
//============================================================================
//
// Standard uniforms.
//
//============================================================================
static TString StandardUniforms()
{
TString s;
//
// Depth range in window coordinates
//
s.append(TString("struct gl_DepthRangeParameters {"));
s.append(TString(" highp float near;")); // n
s.append(TString(" highp float far;")); // f
s.append(TString(" highp float diff;")); // f - n
s.append(TString("};"));
s.append(TString("uniform gl_DepthRangeParameters gl_DepthRange;"));
return s;
}
//============================================================================
//
// Default precision for vertex shaders.
//
//============================================================================
static TString DefaultPrecisionVertex()
{
TString s;
s.append(TString("precision highp int;"));
s.append(TString("precision highp float;"));
return s;
}
//============================================================================
//
// Default precision for fragment shaders.
//
//============================================================================
static TString DefaultPrecisionFragment()
{
TString s;
s.append(TString("precision mediump int;"));
// No default precision for float in fragment shaders
return s;
}
//============================================================================
//
// Implementation dependent built-in constants.
//
//============================================================================
static TString BuiltInConstants(ShShaderSpec spec, const ShBuiltInResources &resources, const TExtensionBehavior& extensionBehavior)
{
TStringStream s;
s << "const int gl_MaxVertexAttribs = " << resources.MaxVertexAttribs << ";";
s << "const int gl_MaxVertexUniformVectors = " << resources.MaxVertexUniformVectors << ";";
s << "const int gl_MaxVaryingVectors = " << resources.MaxVaryingVectors << ";";
s << "const int gl_MaxVertexTextureImageUnits = " << resources.MaxVertexTextureImageUnits << ";";
s << "const int gl_MaxCombinedTextureImageUnits = " << resources.MaxCombinedTextureImageUnits << ";";
s << "const int gl_MaxTextureImageUnits = " << resources.MaxTextureImageUnits << ";";
s << "const int gl_MaxFragmentUniformVectors = " << resources.MaxFragmentUniformVectors << ";";
if (spec != SH_CSS_SHADERS_SPEC)
{
TExtensionBehavior::const_iterator iter = extensionBehavior.find("GL_EXT_draw_buffers");
const bool usingMRTExtension = (iter != extensionBehavior.end() && (iter->second == EBhEnable || iter->second == EBhRequire));
const int maxDrawBuffers = (usingMRTExtension ? resources.MaxDrawBuffers : 1);
s << "const int gl_MaxDrawBuffers = " << maxDrawBuffers << ";";
}
return s.str();
}
void TBuiltIns::initialize(ShShaderType type, ShShaderSpec spec,
const ShBuiltInResources& resources,
const TExtensionBehavior& extensionBehavior)
{
switch (type) {
case SH_FRAGMENT_SHADER:
builtInStrings.push_back(DefaultPrecisionFragment());
builtInStrings.push_back(BuiltInFunctionsCommon(resources));
builtInStrings.push_back(BuiltInFunctionsFragment(resources));
builtInStrings.push_back(StandardUniforms());
break;
case SH_VERTEX_SHADER:
builtInStrings.push_back(DefaultPrecisionVertex());
builtInStrings.push_back(BuiltInFunctionsCommon(resources));
builtInStrings.push_back(BuiltInFunctionsVertex(resources));
builtInStrings.push_back(StandardUniforms());
break;
default: assert(false && "Language not supported");
}
builtInStrings.push_back(BuiltInConstants(spec, resources, extensionBehavior));
}
void IdentifyBuiltIns(ShShaderType type, ShShaderSpec spec,
const ShBuiltInResources& resources,
TSymbolTable& symbolTable)
{
//
// First, insert some special built-in variables that are not in
// the built-in header files.
//
switch(type) {
case SH_FRAGMENT_SHADER:
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragCoord"), TType(EbtFloat, EbpMedium, EvqFragCoord, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_FrontFacing"), TType(EbtBool, EbpUndefined, EvqFrontFacing, 1)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_PointCoord"), TType(EbtFloat, EbpMedium, EvqPointCoord, 2)));
//
// In CSS Shaders, gl_FragColor, gl_FragData, and gl_MaxDrawBuffers are not available.
// Instead, css_MixColor and css_ColorMatrix are available.
//
if (spec != SH_CSS_SHADERS_SPEC) {
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragColor"), TType(EbtFloat, EbpMedium, EvqFragColor, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragData[gl_MaxDrawBuffers]"), TType(EbtFloat, EbpMedium, EvqFragData, 4)));
if (resources.EXT_frag_depth) {
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragDepthEXT"), TType(EbtFloat, resources.FragmentPrecisionHigh ? EbpHigh : EbpMedium, EvqFragDepth, 1)));
symbolTable.relateToExtension("gl_FragDepthEXT", "GL_EXT_frag_depth");
}
} else {
symbolTable.insert(*new TVariable(NewPoolTString("css_MixColor"), TType(EbtFloat, EbpMedium, EvqGlobal, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("css_ColorMatrix"), TType(EbtFloat, EbpMedium, EvqGlobal, 4, true)));
}
break;
case SH_VERTEX_SHADER:
symbolTable.insert(*new TVariable(NewPoolTString("gl_Position"), TType(EbtFloat, EbpHigh, EvqPosition, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_PointSize"), TType(EbtFloat, EbpMedium, EvqPointSize, 1)));
break;
default: assert(false && "Language not supported");
}
//
// Next, identify which built-ins from the already loaded headers have
// a mapping to an operator. Those that are not identified as such are
// expected to be resolved through a library of functions, versus as
// operations.
//
symbolTable.relateToOperator("not", EOpVectorLogicalNot);
symbolTable.relateToOperator("matrixCompMult", EOpMul);
symbolTable.relateToOperator("equal", EOpVectorEqual);
symbolTable.relateToOperator("notEqual", EOpVectorNotEqual);
symbolTable.relateToOperator("lessThan", EOpLessThan);
symbolTable.relateToOperator("greaterThan", EOpGreaterThan);
symbolTable.relateToOperator("lessThanEqual", EOpLessThanEqual);
symbolTable.relateToOperator("greaterThanEqual", EOpGreaterThanEqual);
symbolTable.relateToOperator("radians", EOpRadians);
symbolTable.relateToOperator("degrees", EOpDegrees);
symbolTable.relateToOperator("sin", EOpSin);
symbolTable.relateToOperator("cos", EOpCos);
symbolTable.relateToOperator("tan", EOpTan);
symbolTable.relateToOperator("asin", EOpAsin);
symbolTable.relateToOperator("acos", EOpAcos);
symbolTable.relateToOperator("atan", EOpAtan);
symbolTable.relateToOperator("pow", EOpPow);
symbolTable.relateToOperator("exp2", EOpExp2);
symbolTable.relateToOperator("log", EOpLog);
symbolTable.relateToOperator("exp", EOpExp);
symbolTable.relateToOperator("log2", EOpLog2);
symbolTable.relateToOperator("sqrt", EOpSqrt);
symbolTable.relateToOperator("inversesqrt", EOpInverseSqrt);
symbolTable.relateToOperator("abs", EOpAbs);
symbolTable.relateToOperator("sign", EOpSign);
symbolTable.relateToOperator("floor", EOpFloor);
symbolTable.relateToOperator("ceil", EOpCeil);
symbolTable.relateToOperator("fract", EOpFract);
symbolTable.relateToOperator("mod", EOpMod);
symbolTable.relateToOperator("min", EOpMin);
symbolTable.relateToOperator("max", EOpMax);
symbolTable.relateToOperator("clamp", EOpClamp);
symbolTable.relateToOperator("mix", EOpMix);
symbolTable.relateToOperator("step", EOpStep);
symbolTable.relateToOperator("smoothstep", EOpSmoothStep);
symbolTable.relateToOperator("length", EOpLength);
symbolTable.relateToOperator("distance", EOpDistance);
symbolTable.relateToOperator("dot", EOpDot);
symbolTable.relateToOperator("cross", EOpCross);
symbolTable.relateToOperator("normalize", EOpNormalize);
symbolTable.relateToOperator("faceforward", EOpFaceForward);
symbolTable.relateToOperator("reflect", EOpReflect);
symbolTable.relateToOperator("refract", EOpRefract);
symbolTable.relateToOperator("any", EOpAny);
symbolTable.relateToOperator("all", EOpAll);
// Map language-specific operators.
switch(type) {
case SH_VERTEX_SHADER:
break;
case SH_FRAGMENT_SHADER:
if (resources.OES_standard_derivatives) {
symbolTable.relateToOperator("dFdx", EOpDFdx);
symbolTable.relateToOperator("dFdy", EOpDFdy);
symbolTable.relateToOperator("fwidth", EOpFwidth);
symbolTable.relateToExtension("dFdx", "GL_OES_standard_derivatives");
symbolTable.relateToExtension("dFdy", "GL_OES_standard_derivatives");
symbolTable.relateToExtension("fwidth", "GL_OES_standard_derivatives");
}
break;
default: break;
}
// Finally add resource-specific variables.
switch(type) {
case SH_FRAGMENT_SHADER:
if (spec != SH_CSS_SHADERS_SPEC) {
// Set up gl_FragData. The array size.
TType fragData(EbtFloat, EbpMedium, EvqFragData, 4, false, true);
fragData.setArraySize(resources.MaxDrawBuffers);
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragData"), fragData));
}
break;
default: break;
}
}
void InitExtensionBehavior(const ShBuiltInResources& resources,
TExtensionBehavior& extBehavior)
{
if (resources.OES_standard_derivatives)
extBehavior["GL_OES_standard_derivatives"] = EBhUndefined;
if (resources.OES_EGL_image_external)
extBehavior["GL_OES_EGL_image_external"] = EBhUndefined;
if (resources.ARB_texture_rectangle)
extBehavior["GL_ARB_texture_rectangle"] = EBhUndefined;
if (resources.EXT_draw_buffers)
extBehavior["GL_EXT_draw_buffers"] = EBhUndefined;
if (resources.EXT_frag_depth)
extBehavior["GL_EXT_frag_depth"] = EBhUndefined;
}
| C++ |
//
// 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 "compiler/timing/RestrictVertexShaderTiming.h"
void RestrictVertexShaderTiming::visitSymbol(TIntermSymbol* node)
{
if (IsSampler(node->getBasicType())) {
++mNumErrors;
mSink.message(EPrefixError,
node->getLine(),
"Samplers are not permitted in vertex shaders");
}
}
| C++ |
//
// 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 "compiler/InfoSink.h"
#include "compiler/ParseHelper.h"
#include "compiler/depgraph/DependencyGraphOutput.h"
#include "compiler/timing/RestrictFragmentShaderTiming.h"
RestrictFragmentShaderTiming::RestrictFragmentShaderTiming(TInfoSinkBase& sink)
: mSink(sink)
, mNumErrors(0)
{
// Sampling ops found only in fragment shaders.
mSamplingOps.insert("texture2D(s21;vf2;f1;");
mSamplingOps.insert("texture2DProj(s21;vf3;f1;");
mSamplingOps.insert("texture2DProj(s21;vf4;f1;");
mSamplingOps.insert("textureCube(sC1;vf3;f1;");
// Sampling ops found in both vertex and fragment shaders.
mSamplingOps.insert("texture2D(s21;vf2;");
mSamplingOps.insert("texture2DProj(s21;vf3;");
mSamplingOps.insert("texture2DProj(s21;vf4;");
mSamplingOps.insert("textureCube(sC1;vf3;");
// Sampling ops provided by OES_EGL_image_external.
mSamplingOps.insert("texture2D(1;vf2;");
mSamplingOps.insert("texture2DProj(1;vf3;");
mSamplingOps.insert("texture2DProj(1;vf4;");
// Sampling ops provided by ARB_texture_rectangle.
mSamplingOps.insert("texture2DRect(1;vf2;");
mSamplingOps.insert("texture2DRectProj(1;vf3;");
mSamplingOps.insert("texture2DRectProj(1;vf4;");
}
// FIXME(mvujovic): We do not know if the execution time of built-in operations like sin, pow, etc.
// can vary based on the value of the input arguments. If so, we should restrict those as well.
void RestrictFragmentShaderTiming::enforceRestrictions(const TDependencyGraph& graph)
{
mNumErrors = 0;
// FIXME(mvujovic): The dependency graph does not support user defined function calls right now,
// so we generate errors for them.
validateUserDefinedFunctionCallUsage(graph);
// Starting from each sampler, traverse the dependency graph and generate an error each time we
// hit a node where sampler dependent values are not allowed.
for (TGraphSymbolVector::const_iterator iter = graph.beginSamplerSymbols();
iter != graph.endSamplerSymbols();
++iter)
{
TGraphSymbol* samplerSymbol = *iter;
clearVisited();
samplerSymbol->traverse(this);
}
}
void RestrictFragmentShaderTiming::validateUserDefinedFunctionCallUsage(const TDependencyGraph& graph)
{
for (TFunctionCallVector::const_iterator iter = graph.beginUserDefinedFunctionCalls();
iter != graph.endUserDefinedFunctionCalls();
++iter)
{
TGraphFunctionCall* functionCall = *iter;
beginError(functionCall->getIntermFunctionCall());
mSink << "A call to a user defined function is not permitted.\n";
}
}
void RestrictFragmentShaderTiming::beginError(const TIntermNode* node)
{
++mNumErrors;
mSink.prefix(EPrefixError);
mSink.location(node->getLine());
}
bool RestrictFragmentShaderTiming::isSamplingOp(const TIntermAggregate* intermFunctionCall) const
{
return !intermFunctionCall->isUserDefined() &&
mSamplingOps.find(intermFunctionCall->getName()) != mSamplingOps.end();
}
void RestrictFragmentShaderTiming::visitArgument(TGraphArgument* parameter)
{
// Texture cache access time might leak sensitive information.
// Thus, we restrict sampler dependent values from affecting the coordinate or LOD bias of a
// sampling operation.
if (isSamplingOp(parameter->getIntermFunctionCall())) {
switch (parameter->getArgumentNumber()) {
case 1:
// Second argument (coord)
beginError(parameter->getIntermFunctionCall());
mSink << "An expression dependent on a sampler is not permitted to be the"
<< " coordinate argument of a sampling operation.\n";
break;
case 2:
// Third argument (bias)
beginError(parameter->getIntermFunctionCall());
mSink << "An expression dependent on a sampler is not permitted to be the"
<< " bias argument of a sampling operation.\n";
break;
default:
// First argument (sampler)
break;
}
}
}
void RestrictFragmentShaderTiming::visitSelection(TGraphSelection* selection)
{
beginError(selection->getIntermSelection());
mSink << "An expression dependent on a sampler is not permitted in a conditional statement.\n";
}
void RestrictFragmentShaderTiming::visitLoop(TGraphLoop* loop)
{
beginError(loop->getIntermLoop());
mSink << "An expression dependent on a sampler is not permitted in a loop condition.\n";
}
void RestrictFragmentShaderTiming::visitLogicalOp(TGraphLogicalOp* logicalOp)
{
beginError(logicalOp->getIntermLogicalOp());
mSink << "An expression dependent on a sampler is not permitted on the left hand side of a logical "
<< logicalOp->getOpString()
<< " operator.\n";
}
| C++ |
//
// 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 COMPILER_TIMING_RESTRICT_VERTEX_SHADER_TIMING_H_
#define COMPILER_TIMING_RESTRICT_VERTEX_SHADER_TIMING_H_
#include "GLSLANG/ShaderLang.h"
#include "compiler/intermediate.h"
#include "compiler/InfoSink.h"
class TInfoSinkBase;
class RestrictVertexShaderTiming : public TIntermTraverser {
public:
RestrictVertexShaderTiming(TInfoSinkBase& sink)
: TIntermTraverser(true, false, false)
, mSink(sink)
, mNumErrors(0) {}
void enforceRestrictions(TIntermNode* root) { root->traverse(this); }
int numErrors() { return mNumErrors; }
virtual void visitSymbol(TIntermSymbol*);
private:
TInfoSinkBase& mSink;
int mNumErrors;
};
#endif // COMPILER_TIMING_RESTRICT_VERTEX_SHADER_TIMING_H_
| C++ |
//
// 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 COMPILER_TIMING_RESTRICT_FRAGMENT_SHADER_TIMING_H_
#define COMPILER_TIMING_RESTRICT_FRAGMENT_SHADER_TIMING_H_
#include "GLSLANG/ShaderLang.h"
#include "compiler/intermediate.h"
#include "compiler/depgraph/DependencyGraph.h"
class TInfoSinkBase;
class RestrictFragmentShaderTiming : TDependencyGraphTraverser {
public:
RestrictFragmentShaderTiming(TInfoSinkBase& sink);
void enforceRestrictions(const TDependencyGraph& graph);
int numErrors() const { return mNumErrors; }
virtual void visitArgument(TGraphArgument* parameter);
virtual void visitSelection(TGraphSelection* selection);
virtual void visitLoop(TGraphLoop* loop);
virtual void visitLogicalOp(TGraphLogicalOp* logicalOp);
private:
void beginError(const TIntermNode* node);
void validateUserDefinedFunctionCallUsage(const TDependencyGraph& graph);
bool isSamplingOp(const TIntermAggregate* intermFunctionCall) const;
TInfoSinkBase& mSink;
int mNumErrors;
typedef std::set<TString> StringSet;
StringSet mSamplingOps;
};
#endif // COMPILER_TIMING_RESTRICT_FRAGMENT_SHADER_TIMING_H_
| C++ |
//
// 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.
//
#ifndef COMPILER_UNIFORM_H_
#define COMPILER_UNIFORM_H_
#include <string>
#include <vector>
#define GL_APICALL
#include <GLES2/gl2.h>
namespace sh
{
struct Uniform
{
Uniform(GLenum type, GLenum precision, const char *name, int arraySize, int registerIndex);
GLenum type;
GLenum precision;
std::string name;
unsigned int arraySize;
int registerIndex;
};
typedef std::vector<Uniform> ActiveUniforms;
}
#endif // COMPILER_UNIFORM_H_
| C++ |
//
// 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 COMPILER_RENAME_FUNCTION
#define COMPILER_RENAME_FUNCTION
#include "compiler/intermediate.h"
//
// Renames a function, including its declaration and any calls to it.
//
class RenameFunction : public TIntermTraverser
{
public:
RenameFunction(const TString& oldFunctionName, const TString& newFunctionName)
: TIntermTraverser(true, false, false)
, mOldFunctionName(oldFunctionName)
, mNewFunctionName(newFunctionName) {}
virtual bool visitAggregate(Visit visit, TIntermAggregate* node)
{
TOperator op = node->getOp();
if ((op == EOpFunction || op == EOpFunctionCall) && node->getName() == mOldFunctionName)
node->setName(mNewFunctionName);
return true;
}
private:
const TString mOldFunctionName;
const TString mNewFunctionName;
};
#endif // COMPILER_RENAME_FUNCTION
| C++ |
//
// 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.
//
#include "compiler/ValidateLimitations.h"
#include "compiler/InfoSink.h"
#include "compiler/InitializeParseContext.h"
#include "compiler/ParseHelper.h"
namespace {
bool IsLoopIndex(const TIntermSymbol* symbol, const TLoopStack& stack) {
for (TLoopStack::const_iterator i = stack.begin(); i != stack.end(); ++i) {
if (i->index.id == symbol->getId())
return true;
}
return false;
}
void MarkLoopForUnroll(const TIntermSymbol* symbol, TLoopStack& stack) {
for (TLoopStack::iterator i = stack.begin(); i != stack.end(); ++i) {
if (i->index.id == symbol->getId()) {
ASSERT(i->loop != NULL);
i->loop->setUnrollFlag(true);
return;
}
}
UNREACHABLE();
}
// Traverses a node to check if it represents a constant index expression.
// Definition:
// constant-index-expressions are a superset of constant-expressions.
// Constant-index-expressions can include loop indices as defined in
// GLSL ES 1.0 spec, Appendix A, section 4.
// The following are constant-index-expressions:
// - Constant expressions
// - Loop indices as defined in section 4
// - Expressions composed of both of the above
class ValidateConstIndexExpr : public TIntermTraverser {
public:
ValidateConstIndexExpr(const TLoopStack& stack)
: mValid(true), mLoopStack(stack) {}
// Returns true if the parsed node represents a constant index expression.
bool isValid() const { return mValid; }
virtual void visitSymbol(TIntermSymbol* symbol) {
// Only constants and loop indices are allowed in a
// constant index expression.
if (mValid) {
mValid = (symbol->getQualifier() == EvqConst) ||
IsLoopIndex(symbol, mLoopStack);
}
}
private:
bool mValid;
const TLoopStack& mLoopStack;
};
// Traverses a node to check if it uses a loop index.
// If an int loop index is used in its body as a sampler array index,
// mark the loop for unroll.
class ValidateLoopIndexExpr : public TIntermTraverser {
public:
ValidateLoopIndexExpr(TLoopStack& stack)
: mUsesFloatLoopIndex(false),
mUsesIntLoopIndex(false),
mLoopStack(stack) {}
bool usesFloatLoopIndex() const { return mUsesFloatLoopIndex; }
bool usesIntLoopIndex() const { return mUsesIntLoopIndex; }
virtual void visitSymbol(TIntermSymbol* symbol) {
if (IsLoopIndex(symbol, mLoopStack)) {
switch (symbol->getBasicType()) {
case EbtFloat:
mUsesFloatLoopIndex = true;
break;
case EbtInt:
mUsesIntLoopIndex = true;
MarkLoopForUnroll(symbol, mLoopStack);
break;
default:
UNREACHABLE();
}
}
}
private:
bool mUsesFloatLoopIndex;
bool mUsesIntLoopIndex;
TLoopStack& mLoopStack;
};
} // namespace
ValidateLimitations::ValidateLimitations(ShShaderType shaderType,
TInfoSinkBase& sink)
: mShaderType(shaderType),
mSink(sink),
mNumErrors(0)
{
}
bool ValidateLimitations::visitBinary(Visit, TIntermBinary* node)
{
// Check if loop index is modified in the loop body.
validateOperation(node, node->getLeft());
// Check indexing.
switch (node->getOp()) {
case EOpIndexDirect:
validateIndexing(node);
break;
case EOpIndexIndirect:
#if defined(__APPLE__)
// Loop unrolling is a work-around for a Mac Cg compiler bug where it
// crashes when a sampler array's index is also the loop index.
// Once Apple fixes this bug, we should remove the code in this CL.
// See http://codereview.appspot.com/4331048/.
if ((node->getLeft() != NULL) && (node->getRight() != NULL) &&
(node->getLeft()->getAsSymbolNode())) {
TIntermSymbol* symbol = node->getLeft()->getAsSymbolNode();
if (IsSampler(symbol->getBasicType()) && symbol->isArray()) {
ValidateLoopIndexExpr validate(mLoopStack);
node->getRight()->traverse(&validate);
if (validate.usesFloatLoopIndex()) {
error(node->getLine(),
"sampler array index is float loop index",
"for");
}
}
}
#endif
validateIndexing(node);
break;
default: break;
}
return true;
}
bool ValidateLimitations::visitUnary(Visit, TIntermUnary* node)
{
// Check if loop index is modified in the loop body.
validateOperation(node, node->getOperand());
return true;
}
bool ValidateLimitations::visitAggregate(Visit, TIntermAggregate* node)
{
switch (node->getOp()) {
case EOpFunctionCall:
validateFunctionCall(node);
break;
default:
break;
}
return true;
}
bool ValidateLimitations::visitLoop(Visit, TIntermLoop* node)
{
if (!validateLoopType(node))
return false;
TLoopInfo info;
memset(&info, 0, sizeof(TLoopInfo));
info.loop = node;
if (!validateForLoopHeader(node, &info))
return false;
TIntermNode* body = node->getBody();
if (body != NULL) {
mLoopStack.push_back(info);
body->traverse(this);
mLoopStack.pop_back();
}
// The loop is fully processed - no need to visit children.
return false;
}
void ValidateLimitations::error(TSourceLoc loc,
const char *reason, const char* token)
{
mSink.prefix(EPrefixError);
mSink.location(loc);
mSink << "'" << token << "' : " << reason << "\n";
++mNumErrors;
}
bool ValidateLimitations::withinLoopBody() const
{
return !mLoopStack.empty();
}
bool ValidateLimitations::isLoopIndex(const TIntermSymbol* symbol) const
{
return IsLoopIndex(symbol, mLoopStack);
}
bool ValidateLimitations::validateLoopType(TIntermLoop* node) {
TLoopType type = node->getType();
if (type == ELoopFor)
return true;
// Reject while and do-while loops.
error(node->getLine(),
"This type of loop is not allowed",
type == ELoopWhile ? "while" : "do");
return false;
}
bool ValidateLimitations::validateForLoopHeader(TIntermLoop* node,
TLoopInfo* info)
{
ASSERT(node->getType() == ELoopFor);
//
// The for statement has the form:
// for ( init-declaration ; condition ; expression ) statement
//
if (!validateForLoopInit(node, info))
return false;
if (!validateForLoopCond(node, info))
return false;
if (!validateForLoopExpr(node, info))
return false;
return true;
}
bool ValidateLimitations::validateForLoopInit(TIntermLoop* node,
TLoopInfo* info)
{
TIntermNode* init = node->getInit();
if (init == NULL) {
error(node->getLine(), "Missing init declaration", "for");
return false;
}
//
// init-declaration has the form:
// type-specifier identifier = constant-expression
//
TIntermAggregate* decl = init->getAsAggregate();
if ((decl == NULL) || (decl->getOp() != EOpDeclaration)) {
error(init->getLine(), "Invalid init declaration", "for");
return false;
}
// To keep things simple do not allow declaration list.
TIntermSequence& declSeq = decl->getSequence();
if (declSeq.size() != 1) {
error(decl->getLine(), "Invalid init declaration", "for");
return false;
}
TIntermBinary* declInit = declSeq[0]->getAsBinaryNode();
if ((declInit == NULL) || (declInit->getOp() != EOpInitialize)) {
error(decl->getLine(), "Invalid init declaration", "for");
return false;
}
TIntermSymbol* symbol = declInit->getLeft()->getAsSymbolNode();
if (symbol == NULL) {
error(declInit->getLine(), "Invalid init declaration", "for");
return false;
}
// The loop index has type int or float.
TBasicType type = symbol->getBasicType();
if ((type != EbtInt) && (type != EbtFloat)) {
error(symbol->getLine(),
"Invalid type for loop index", getBasicString(type));
return false;
}
// The loop index is initialized with constant expression.
if (!isConstExpr(declInit->getRight())) {
error(declInit->getLine(),
"Loop index cannot be initialized with non-constant expression",
symbol->getSymbol().c_str());
return false;
}
info->index.id = symbol->getId();
return true;
}
bool ValidateLimitations::validateForLoopCond(TIntermLoop* node,
TLoopInfo* info)
{
TIntermNode* cond = node->getCondition();
if (cond == NULL) {
error(node->getLine(), "Missing condition", "for");
return false;
}
//
// condition has the form:
// loop_index relational_operator constant_expression
//
TIntermBinary* binOp = cond->getAsBinaryNode();
if (binOp == NULL) {
error(node->getLine(), "Invalid condition", "for");
return false;
}
// Loop index should be to the left of relational operator.
TIntermSymbol* symbol = binOp->getLeft()->getAsSymbolNode();
if (symbol == NULL) {
error(binOp->getLine(), "Invalid condition", "for");
return false;
}
if (symbol->getId() != info->index.id) {
error(symbol->getLine(),
"Expected loop index", symbol->getSymbol().c_str());
return false;
}
// Relational operator is one of: > >= < <= == or !=.
switch (binOp->getOp()) {
case EOpEqual:
case EOpNotEqual:
case EOpLessThan:
case EOpGreaterThan:
case EOpLessThanEqual:
case EOpGreaterThanEqual:
break;
default:
error(binOp->getLine(),
"Invalid relational operator",
getOperatorString(binOp->getOp()));
break;
}
// Loop index must be compared with a constant.
if (!isConstExpr(binOp->getRight())) {
error(binOp->getLine(),
"Loop index cannot be compared with non-constant expression",
symbol->getSymbol().c_str());
return false;
}
return true;
}
bool ValidateLimitations::validateForLoopExpr(TIntermLoop* node,
TLoopInfo* info)
{
TIntermNode* expr = node->getExpression();
if (expr == NULL) {
error(node->getLine(), "Missing expression", "for");
return false;
}
// for expression has one of the following forms:
// loop_index++
// loop_index--
// loop_index += constant_expression
// loop_index -= constant_expression
// ++loop_index
// --loop_index
// The last two forms are not specified in the spec, but I am assuming
// its an oversight.
TIntermUnary* unOp = expr->getAsUnaryNode();
TIntermBinary* binOp = unOp ? NULL : expr->getAsBinaryNode();
TOperator op = EOpNull;
TIntermSymbol* symbol = NULL;
if (unOp != NULL) {
op = unOp->getOp();
symbol = unOp->getOperand()->getAsSymbolNode();
} else if (binOp != NULL) {
op = binOp->getOp();
symbol = binOp->getLeft()->getAsSymbolNode();
}
// The operand must be loop index.
if (symbol == NULL) {
error(expr->getLine(), "Invalid expression", "for");
return false;
}
if (symbol->getId() != info->index.id) {
error(symbol->getLine(),
"Expected loop index", symbol->getSymbol().c_str());
return false;
}
// The operator is one of: ++ -- += -=.
switch (op) {
case EOpPostIncrement:
case EOpPostDecrement:
case EOpPreIncrement:
case EOpPreDecrement:
ASSERT((unOp != NULL) && (binOp == NULL));
break;
case EOpAddAssign:
case EOpSubAssign:
ASSERT((unOp == NULL) && (binOp != NULL));
break;
default:
error(expr->getLine(), "Invalid operator", getOperatorString(op));
return false;
}
// Loop index must be incremented/decremented with a constant.
if (binOp != NULL) {
if (!isConstExpr(binOp->getRight())) {
error(binOp->getLine(),
"Loop index cannot be modified by non-constant expression",
symbol->getSymbol().c_str());
return false;
}
}
return true;
}
bool ValidateLimitations::validateFunctionCall(TIntermAggregate* node)
{
ASSERT(node->getOp() == EOpFunctionCall);
// If not within loop body, there is nothing to check.
if (!withinLoopBody())
return true;
// List of param indices for which loop indices are used as argument.
typedef std::vector<size_t> ParamIndex;
ParamIndex pIndex;
TIntermSequence& params = node->getSequence();
for (TIntermSequence::size_type i = 0; i < params.size(); ++i) {
TIntermSymbol* symbol = params[i]->getAsSymbolNode();
if (symbol && isLoopIndex(symbol))
pIndex.push_back(i);
}
// If none of the loop indices are used as arguments,
// there is nothing to check.
if (pIndex.empty())
return true;
bool valid = true;
TSymbolTable& symbolTable = GlobalParseContext->symbolTable;
TSymbol* symbol = symbolTable.find(node->getName());
ASSERT(symbol && symbol->isFunction());
TFunction* function = static_cast<TFunction*>(symbol);
for (ParamIndex::const_iterator i = pIndex.begin();
i != pIndex.end(); ++i) {
const TParameter& param = function->getParam(*i);
TQualifier qual = param.type->getQualifier();
if ((qual == EvqOut) || (qual == EvqInOut)) {
error(params[*i]->getLine(),
"Loop index cannot be used as argument to a function out or inout parameter",
params[*i]->getAsSymbolNode()->getSymbol().c_str());
valid = false;
}
}
return valid;
}
bool ValidateLimitations::validateOperation(TIntermOperator* node,
TIntermNode* operand) {
// Check if loop index is modified in the loop body.
if (!withinLoopBody() || !node->modifiesState())
return true;
const TIntermSymbol* symbol = operand->getAsSymbolNode();
if (symbol && isLoopIndex(symbol)) {
error(node->getLine(),
"Loop index cannot be statically assigned to within the body of the loop",
symbol->getSymbol().c_str());
}
return true;
}
bool ValidateLimitations::isConstExpr(TIntermNode* node)
{
ASSERT(node != NULL);
return node->getAsConstantUnion() != NULL;
}
bool ValidateLimitations::isConstIndexExpr(TIntermNode* node)
{
ASSERT(node != NULL);
ValidateConstIndexExpr validate(mLoopStack);
node->traverse(&validate);
return validate.isValid();
}
bool ValidateLimitations::validateIndexing(TIntermBinary* node)
{
ASSERT((node->getOp() == EOpIndexDirect) ||
(node->getOp() == EOpIndexIndirect));
bool valid = true;
TIntermTyped* index = node->getRight();
// The index expression must have integral type.
if (!index->isScalar() || (index->getBasicType() != EbtInt)) {
error(index->getLine(),
"Index expression must have integral type",
index->getCompleteString().c_str());
valid = false;
}
// The index expession must be a constant-index-expression unless
// the operand is a uniform in a vertex shader.
TIntermTyped* operand = node->getLeft();
bool skip = (mShaderType == SH_VERTEX_SHADER) &&
(operand->getQualifier() == EvqUniform);
if (!skip && !isConstIndexExpr(index)) {
error(index->getLine(), "Index expression must be constant", "[]");
valid = false;
}
return valid;
}
| C++ |
//
// 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.
//
// debug.cpp: Debugging utilities.
#include "compiler/debug.h"
#include <stdarg.h>
#include <stdio.h>
#include "compiler/InitializeParseContext.h"
#include "compiler/ParseHelper.h"
static const int kTraceBufferLen = 1024;
#ifdef TRACE_ENABLED
extern "C" {
void Trace(const char *format, ...) {
if (!format) return;
TParseContext* parseContext = GetGlobalParseContext();
if (parseContext) {
char buf[kTraceBufferLen];
va_list args;
va_start(args, format);
vsnprintf(buf, kTraceBufferLen, format, args);
va_end(args);
parseContext->trace(buf);
}
}
} // extern "C"
#endif // TRACE_ENABLED
| C++ |
//
// 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.
//
#ifndef _SHHANDLE_INCLUDED_
#define _SHHANDLE_INCLUDED_
//
// Machine independent part of the compiler private objects
// sent as ShHandle to the driver.
//
// This should not be included by driver code.
//
#include "GLSLANG/ShaderLang.h"
#include "compiler/BuiltInFunctionEmulator.h"
#include "compiler/ExtensionBehavior.h"
#include "compiler/HashNames.h"
#include "compiler/InfoSink.h"
#include "compiler/SymbolTable.h"
#include "compiler/VariableInfo.h"
#include "third_party/compiler/ArrayBoundsClamper.h"
class LongNameMap;
class TCompiler;
class TDependencyGraph;
class TranslatorHLSL;
//
// Helper function to identify specs that are based on the WebGL spec,
// like the CSS Shaders spec.
//
bool isWebGLBasedSpec(ShShaderSpec spec);
//
// The base class used to back handles returned to the driver.
//
class TShHandleBase {
public:
TShHandleBase();
virtual ~TShHandleBase();
virtual TCompiler* getAsCompiler() { return 0; }
virtual TranslatorHLSL* getAsTranslatorHLSL() { return 0; }
protected:
// Memory allocator. Allocates and tracks memory required by the compiler.
// Deallocates all memory when compiler is destructed.
TPoolAllocator allocator;
};
//
// The base class for the machine dependent compiler to derive from
// for managing object code from the compile.
//
class TCompiler : public TShHandleBase {
public:
TCompiler(ShShaderType type, ShShaderSpec spec);
virtual ~TCompiler();
virtual TCompiler* getAsCompiler() { return this; }
bool Init(const ShBuiltInResources& resources);
bool compile(const char* const shaderStrings[],
size_t numStrings,
int compileOptions);
// Get results of the last compilation.
TInfoSink& getInfoSink() { return infoSink; }
const TVariableInfoList& getAttribs() const { return attribs; }
const TVariableInfoList& getUniforms() const { return uniforms; }
int getMappedNameMaxLength() const;
ShHashFunction64 getHashFunction() const { return hashFunction; }
NameMap& getNameMap() { return nameMap; }
TSymbolTable& getSymbolTable() { return symbolTable; }
protected:
ShShaderType getShaderType() const { return shaderType; }
ShShaderSpec getShaderSpec() const { return shaderSpec; }
// Initialize symbol-table with built-in symbols.
bool InitBuiltInSymbolTable(const ShBuiltInResources& resources);
// Clears the results from the previous compilation.
void clearResults();
// Return true if function recursion is detected or call depth exceeded.
bool detectCallDepth(TIntermNode* root, TInfoSink& infoSink, bool limitCallStackDepth);
// Rewrites a shader's intermediate tree according to the CSS Shaders spec.
void rewriteCSSShader(TIntermNode* root);
// Returns true if the given shader does not exceed the minimum
// functionality mandated in GLSL 1.0 spec Appendix A.
bool validateLimitations(TIntermNode* root);
// Collect info for all attribs and uniforms.
void collectAttribsUniforms(TIntermNode* root);
// Map long variable names into shorter ones.
void mapLongVariableNames(TIntermNode* root);
// Translate to object code.
virtual void translate(TIntermNode* root) = 0;
// Returns true if, after applying the packing rules in the GLSL 1.017 spec
// Appendix A, section 7, the shader does not use too many uniforms.
bool enforcePackingRestrictions();
// Returns true if the shader passes the restrictions that aim to prevent timing attacks.
bool enforceTimingRestrictions(TIntermNode* root, bool outputGraph);
// Returns true if the shader does not use samplers.
bool enforceVertexShaderTimingRestrictions(TIntermNode* root);
// Returns true if the shader does not use sampler dependent values to affect control
// flow or in operations whose time can depend on the input values.
bool enforceFragmentShaderTimingRestrictions(const TDependencyGraph& graph);
// Return true if the maximum expression complexity below the limit.
bool limitExpressionComplexity(TIntermNode* root);
// Get built-in extensions with default behavior.
const TExtensionBehavior& getExtensionBehavior() const;
// Get the resources set by InitBuiltInSymbolTable
const ShBuiltInResources& getResources() const;
const ArrayBoundsClamper& getArrayBoundsClamper() const;
ShArrayIndexClampingStrategy getArrayIndexClampingStrategy() const;
const BuiltInFunctionEmulator& getBuiltInFunctionEmulator() const;
private:
ShShaderType shaderType;
ShShaderSpec shaderSpec;
int maxUniformVectors;
int maxExpressionComplexity;
int maxCallStackDepth;
ShBuiltInResources compileResources;
// Built-in symbol table for the given language, spec, and resources.
// It is preserved from compile-to-compile.
TSymbolTable symbolTable;
// Built-in extensions with default behavior.
TExtensionBehavior extensionBehavior;
bool fragmentPrecisionHigh;
ArrayBoundsClamper arrayBoundsClamper;
ShArrayIndexClampingStrategy clampingStrategy;
BuiltInFunctionEmulator builtInFunctionEmulator;
// Results of compilation.
TInfoSink infoSink; // Output sink.
TVariableInfoList attribs; // Active attributes in the compiled shader.
TVariableInfoList uniforms; // Active uniforms in the compiled shader.
// Cached copy of the ref-counted singleton.
LongNameMap* longNameMap;
// name hashing.
ShHashFunction64 hashFunction;
NameMap nameMap;
};
//
// This is the interface between the machine independent code
// and the machine dependent code.
//
// The machine dependent code should derive from the classes
// above. Then Construct*() and Delete*() will create and
// destroy the machine dependent objects, which contain the
// above machine independent information.
//
TCompiler* ConstructCompiler(
ShShaderType type, ShShaderSpec spec, ShShaderOutput output);
void DeleteCompiler(TCompiler*);
#endif // _SHHANDLE_INCLUDED_
| C++ |
//
// 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.
//
// SearchSymbol is an AST traverser to detect the use of a given symbol name
//
#ifndef COMPILER_SEARCHSYMBOL_H_
#define COMPILER_SEARCHSYMBOL_H_
#include "compiler/intermediate.h"
#include "compiler/ParseHelper.h"
namespace sh
{
class SearchSymbol : public TIntermTraverser
{
public:
SearchSymbol(const TString &symbol);
void traverse(TIntermNode *node);
void visitSymbol(TIntermSymbol *symbolNode);
bool foundMatch() const;
protected:
const TString &mSymbol;
bool match;
};
}
#endif // COMPILER_SEARCHSYMBOL_H_
| C++ |
//
// 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.
//
#ifndef COMPILER_HASH_NAMES_H_
#define COMPILER_HASH_NAMES_H_
#include <map>
#include "compiler/intermediate.h"
#include "GLSLANG/ShaderLang.h"
#define HASHED_NAME_PREFIX "webgl_"
typedef std::map<TPersistString, TPersistString> NameMap;
#endif // COMPILER_HASH_NAMES_H_
| C++ |
//
// 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.
//
#ifndef _INFOSINK_INCLUDED_
#define _INFOSINK_INCLUDED_
#include <math.h>
#include "compiler/Common.h"
// Returns the fractional part of the given floating-point number.
inline float fractionalPart(float f) {
float intPart = 0.0f;
return modff(f, &intPart);
}
//
// TPrefixType is used to centralize how info log messages start.
// See below.
//
enum TPrefixType {
EPrefixNone,
EPrefixWarning,
EPrefixError,
EPrefixInternalError,
EPrefixUnimplemented,
EPrefixNote
};
//
// Encapsulate info logs for all objects that have them.
//
// The methods are a general set of tools for getting a variety of
// messages and types inserted into the log.
//
class TInfoSinkBase {
public:
TInfoSinkBase() {}
template <typename T>
TInfoSinkBase& operator<<(const T& t) {
TPersistStringStream stream;
stream << t;
sink.append(stream.str());
return *this;
}
// Override << operator for specific types. It is faster to append strings
// and characters directly to the sink.
TInfoSinkBase& operator<<(char c) {
sink.append(1, c);
return *this;
}
TInfoSinkBase& operator<<(const char* str) {
sink.append(str);
return *this;
}
TInfoSinkBase& operator<<(const TPersistString& str) {
sink.append(str);
return *this;
}
TInfoSinkBase& operator<<(const TString& str) {
sink.append(str.c_str());
return *this;
}
// Make sure floats are written with correct precision.
TInfoSinkBase& operator<<(float f) {
// Make sure that at least one decimal point is written. If a number
// does not have a fractional part, the default precision format does
// not write the decimal portion which gets interpreted as integer by
// the compiler.
TPersistStringStream stream;
if (fractionalPart(f) == 0.0f) {
stream.precision(1);
stream << std::showpoint << std::fixed << f;
} else {
stream.unsetf(std::ios::fixed);
stream.unsetf(std::ios::scientific);
stream.precision(8);
stream << f;
}
sink.append(stream.str());
return *this;
}
// Write boolean values as their names instead of integral value.
TInfoSinkBase& operator<<(bool b) {
const char* str = b ? "true" : "false";
sink.append(str);
return *this;
}
void erase() { sink.clear(); }
int size() { return static_cast<int>(sink.size()); }
const TPersistString& str() const { return sink; }
const char* c_str() const { return sink.c_str(); }
void prefix(TPrefixType p);
void location(int file, int line);
void location(const TSourceLoc& loc);
void message(TPrefixType p, const TSourceLoc& loc, const char* m);
private:
TPersistString sink;
};
class TInfoSink {
public:
TInfoSinkBase info;
TInfoSinkBase debug;
TInfoSinkBase obj;
};
#endif // _INFOSINK_INCLUDED_
| C++ |
//
// 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.
//
#include "compiler/Uniform.h"
namespace sh
{
Uniform::Uniform(GLenum type, GLenum precision, const char *name, int arraySize, int registerIndex)
{
this->type = type;
this->precision = precision;
this->name = name;
this->arraySize = arraySize;
this->registerIndex = registerIndex;
}
}
| C++ |
//
// 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 "compiler/OutputHLSL.h"
#include "common/angleutils.h"
#include "compiler/debug.h"
#include "compiler/DetectDiscontinuity.h"
#include "compiler/InfoSink.h"
#include "compiler/SearchSymbol.h"
#include "compiler/UnfoldShortCircuit.h"
#include <algorithm>
#include <cfloat>
#include <stdio.h>
namespace sh
{
// Integer to TString conversion
TString str(int i)
{
char buffer[20];
snprintf(buffer, sizeof(buffer), "%d", i);
return buffer;
}
OutputHLSL::OutputHLSL(TParseContext &context, const ShBuiltInResources& resources, ShShaderOutput outputType)
: TIntermTraverser(true, true, true), mContext(context), mOutputType(outputType)
{
mUnfoldShortCircuit = new UnfoldShortCircuit(context, this);
mInsideFunction = false;
mUsesTexture2D = false;
mUsesTexture2D_bias = false;
mUsesTexture2DProj = false;
mUsesTexture2DProj_bias = false;
mUsesTexture2DProjLod = false;
mUsesTexture2DLod = false;
mUsesTextureCube = false;
mUsesTextureCube_bias = false;
mUsesTextureCubeLod = false;
mUsesTexture2DLod0 = false;
mUsesTexture2DLod0_bias = false;
mUsesTexture2DProjLod0 = false;
mUsesTexture2DProjLod0_bias = false;
mUsesTextureCubeLod0 = false;
mUsesTextureCubeLod0_bias = false;
mUsesFragColor = false;
mUsesFragData = false;
mUsesDepthRange = false;
mUsesFragCoord = false;
mUsesPointCoord = false;
mUsesFrontFacing = false;
mUsesPointSize = false;
mUsesFragDepth = false;
mUsesXor = false;
mUsesMod1 = false;
mUsesMod2v = false;
mUsesMod2f = false;
mUsesMod3v = false;
mUsesMod3f = false;
mUsesMod4v = false;
mUsesMod4f = false;
mUsesFaceforward1 = false;
mUsesFaceforward2 = false;
mUsesFaceforward3 = false;
mUsesFaceforward4 = false;
mUsesEqualMat2 = false;
mUsesEqualMat3 = false;
mUsesEqualMat4 = false;
mUsesEqualVec2 = false;
mUsesEqualVec3 = false;
mUsesEqualVec4 = false;
mUsesEqualIVec2 = false;
mUsesEqualIVec3 = false;
mUsesEqualIVec4 = false;
mUsesEqualBVec2 = false;
mUsesEqualBVec3 = false;
mUsesEqualBVec4 = false;
mUsesAtan2_1 = false;
mUsesAtan2_2 = false;
mUsesAtan2_3 = false;
mUsesAtan2_4 = false;
mNumRenderTargets = resources.EXT_draw_buffers ? resources.MaxDrawBuffers : 1;
mScopeDepth = 0;
mUniqueIndex = 0;
mContainsLoopDiscontinuity = false;
mOutputLod0Function = false;
mInsideDiscontinuousLoop = false;
mExcessiveLoopIndex = NULL;
if (mOutputType == SH_HLSL9_OUTPUT)
{
if (mContext.shaderType == SH_FRAGMENT_SHADER)
{
mUniformRegister = 3; // Reserve registers for dx_DepthRange, dx_ViewCoords and dx_DepthFront
}
else
{
mUniformRegister = 2; // Reserve registers for dx_DepthRange and dx_ViewAdjust
}
}
else
{
mUniformRegister = 0;
}
mSamplerRegister = 0;
}
OutputHLSL::~OutputHLSL()
{
delete mUnfoldShortCircuit;
}
void OutputHLSL::output()
{
mContainsLoopDiscontinuity = mContext.shaderType == SH_FRAGMENT_SHADER && containsLoopDiscontinuity(mContext.treeRoot);
mContext.treeRoot->traverse(this); // Output the body first to determine what has to go in the header
header();
mContext.infoSink().obj << mHeader.c_str();
mContext.infoSink().obj << mBody.c_str();
}
TInfoSinkBase &OutputHLSL::getBodyStream()
{
return mBody;
}
const ActiveUniforms &OutputHLSL::getUniforms()
{
return mActiveUniforms;
}
int OutputHLSL::vectorSize(const TType &type) const
{
int elementSize = type.isMatrix() ? type.getNominalSize() : 1;
int arraySize = type.isArray() ? type.getArraySize() : 1;
return elementSize * arraySize;
}
void OutputHLSL::header()
{
ShShaderType shaderType = mContext.shaderType;
TInfoSinkBase &out = mHeader;
for (StructDeclarations::iterator structDeclaration = mStructDeclarations.begin(); structDeclaration != mStructDeclarations.end(); structDeclaration++)
{
out << *structDeclaration;
}
for (Constructors::iterator constructor = mConstructors.begin(); constructor != mConstructors.end(); constructor++)
{
out << *constructor;
}
TString uniforms;
TString varyings;
TString attributes;
for (ReferencedSymbols::const_iterator uniform = mReferencedUniforms.begin(); uniform != mReferencedUniforms.end(); uniform++)
{
const TType &type = uniform->second->getType();
const TString &name = uniform->second->getSymbol();
if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType())) // Also declare the texture
{
int index = samplerRegister(mReferencedUniforms[name]);
uniforms += "uniform SamplerState sampler_" + decorateUniform(name, type) + arrayString(type) +
" : register(s" + str(index) + ");\n";
uniforms += "uniform " + textureString(type) + " texture_" + decorateUniform(name, type) + arrayString(type) +
" : register(t" + str(index) + ");\n";
}
else
{
uniforms += "uniform " + typeString(type) + " " + decorateUniform(name, type) + arrayString(type) +
" : register(" + registerString(mReferencedUniforms[name]) + ");\n";
}
}
for (ReferencedSymbols::const_iterator varying = mReferencedVaryings.begin(); varying != mReferencedVaryings.end(); varying++)
{
const TType &type = varying->second->getType();
const TString &name = varying->second->getSymbol();
// Program linking depends on this exact format
varyings += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
}
for (ReferencedSymbols::const_iterator attribute = mReferencedAttributes.begin(); attribute != mReferencedAttributes.end(); attribute++)
{
const TType &type = attribute->second->getType();
const TString &name = attribute->second->getSymbol();
attributes += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
}
if (shaderType == SH_FRAGMENT_SHADER)
{
TExtensionBehavior::const_iterator iter = mContext.extensionBehavior().find("GL_EXT_draw_buffers");
const bool usingMRTExtension = (iter != mContext.extensionBehavior().end() && (iter->second == EBhEnable || iter->second == EBhRequire));
const unsigned int numColorValues = usingMRTExtension ? mNumRenderTargets : 1;
out << "// Varyings\n";
out << varyings;
out << "\n"
"static float4 gl_Color[" << numColorValues << "] =\n"
"{\n";
for (unsigned int i = 0; i < numColorValues; i++)
{
out << " float4(0, 0, 0, 0)";
if (i + 1 != numColorValues)
{
out << ",";
}
out << "\n";
}
out << "};\n";
if (mUsesFragDepth)
{
out << "static float gl_Depth = 0.0;\n";
}
if (mUsesFragCoord)
{
out << "static float4 gl_FragCoord = float4(0, 0, 0, 0);\n";
}
if (mUsesPointCoord)
{
out << "static float2 gl_PointCoord = float2(0.5, 0.5);\n";
}
if (mUsesFrontFacing)
{
out << "static bool gl_FrontFacing = false;\n";
}
out << "\n";
if (mUsesDepthRange)
{
out << "struct gl_DepthRangeParameters\n"
"{\n"
" float near;\n"
" float far;\n"
" float diff;\n"
"};\n"
"\n";
}
if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "cbuffer DriverConstants : register(b1)\n"
"{\n";
if (mUsesDepthRange)
{
out << " float3 dx_DepthRange : packoffset(c0);\n";
}
if (mUsesFragCoord)
{
out << " float4 dx_ViewCoords : packoffset(c1);\n";
}
if (mUsesFragCoord || mUsesFrontFacing)
{
out << " float3 dx_DepthFront : packoffset(c2);\n";
}
out << "};\n";
}
else
{
if (mUsesDepthRange)
{
out << "uniform float3 dx_DepthRange : register(c0);";
}
if (mUsesFragCoord)
{
out << "uniform float4 dx_ViewCoords : register(c1);\n";
}
if (mUsesFragCoord || mUsesFrontFacing)
{
out << "uniform float3 dx_DepthFront : register(c2);\n";
}
}
out << "\n";
if (mUsesDepthRange)
{
out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
"\n";
}
out << uniforms;
out << "\n";
if (mUsesTexture2D)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2D(sampler2D s, float2 t)\n"
"{\n"
" return tex2D(s, t);\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2D(Texture2D t, SamplerState s, float2 uv)\n"
"{\n"
" return t.Sample(s, uv);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2D_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2D(sampler2D s, float2 t, float bias)\n"
"{\n"
" return tex2Dbias(s, float4(t.x, t.y, 0, bias));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2D(Texture2D t, SamplerState s, float2 uv, float bias)\n"
"{\n"
" return t.SampleBias(s, uv, bias);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProj)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProj(sampler2D s, float3 t)\n"
"{\n"
" return tex2Dproj(s, float4(t.x, t.y, 0, t.z));\n"
"}\n"
"\n"
"float4 gl_texture2DProj(sampler2D s, float4 t)\n"
"{\n"
" return tex2Dproj(s, t);\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProj(Texture2D t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.Sample(s, float2(uvw.x / uvw.z, uvw.y / uvw.z));\n"
"}\n"
"\n"
"float4 gl_texture2DProj(Texture2D t, SamplerState s, float4 uvw)\n"
"{\n"
" return t.Sample(s, float2(uvw.x / uvw.w, uvw.y / uvw.w));\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProj_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProj(sampler2D s, float3 t, float bias)\n"
"{\n"
" return tex2Dbias(s, float4(t.x / t.z, t.y / t.z, 0, bias));\n"
"}\n"
"\n"
"float4 gl_texture2DProj(sampler2D s, float4 t, float bias)\n"
"{\n"
" return tex2Dbias(s, float4(t.x / t.w, t.y / t.w, 0, bias));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProj(Texture2D t, SamplerState s, float3 uvw, float bias)\n"
"{\n"
" return t.SampleBias(s, float2(uvw.x / uvw.z, uvw.y / uvw.z), bias);\n"
"}\n"
"\n"
"float4 gl_texture2DProj(Texture2D t, SamplerState s, float4 uvw, float bias)\n"
"{\n"
" return t.SampleBias(s, float2(uvw.x / uvw.w, uvw.y / uvw.w), bias);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCube)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCube(samplerCUBE s, float3 t)\n"
"{\n"
" return texCUBE(s, t);\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCube(TextureCube t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.Sample(s, uvw);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCube_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCube(samplerCUBE s, float3 t, float bias)\n"
"{\n"
" return texCUBEbias(s, float4(t.x, t.y, t.z, bias));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCube(TextureCube t, SamplerState s, float3 uvw, float bias)\n"
"{\n"
" return t.SampleBias(s, uvw, bias);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
// These *Lod0 intrinsics are not available in GL fragment shaders.
// They are used to sample using discontinuous texture coordinates.
if (mUsesTexture2DLod0)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DLod0(sampler2D s, float2 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x, t.y, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DLod0(Texture2D t, SamplerState s, float2 uv)\n"
"{\n"
" return t.SampleLevel(s, uv, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DLod0_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DLod0(sampler2D s, float2 t, float bias)\n"
"{\n"
" return tex2Dlod(s, float4(t.x, t.y, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DLod0(Texture2D t, SamplerState s, float2 uv, float bias)\n"
"{\n"
" return t.SampleLevel(s, uv, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProjLod0)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProjLod0(sampler2D s, float3 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.z, t.y / t.z, 0, 0));\n"
"}\n"
"\n"
"float4 gl_texture2DProjLod(sampler2D s, float4 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.w, t.y / t.w, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProjLod0(Texture2D t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.z, uvw.y / uvw.z), 0);\n"
"}\n"
"\n"
"float4 gl_texture2DProjLod0(Texture2D t, SamplerState s, float4 uvw)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.w, uvw.y / uvw.w), 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProjLod0_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProjLod0_bias(sampler2D s, float3 t, float bias)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.z, t.y / t.z, 0, 0));\n"
"}\n"
"\n"
"float4 gl_texture2DProjLod_bias(sampler2D s, float4 t, float bias)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.w, t.y / t.w, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProjLod_bias(Texture2D t, SamplerState s, float3 uvw, float bias)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.z, uvw.y / uvw.z), 0);\n"
"}\n"
"\n"
"float4 gl_texture2DProjLod_bias(Texture2D t, SamplerState s, float4 uvw, float bias)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.w, uvw.y / uvw.w), 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCubeLod0)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCubeLod0(samplerCUBE s, float3 t)\n"
"{\n"
" return texCUBElod(s, float4(t.x, t.y, t.z, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCubeLod0(TextureCube t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.SampleLevel(s, uvw, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCubeLod0_bias)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCubeLod0(samplerCUBE s, float3 t, float bias)\n"
"{\n"
" return texCUBElod(s, float4(t.x, t.y, t.z, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCubeLod0(TextureCube t, SamplerState s, float3 uvw, float bias)\n"
"{\n"
" return t.SampleLevel(s, uvw, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (usingMRTExtension && mNumRenderTargets > 1)
{
out << "#define GL_USES_MRT\n";
}
if (mUsesFragColor)
{
out << "#define GL_USES_FRAG_COLOR\n";
}
if (mUsesFragData)
{
out << "#define GL_USES_FRAG_DATA\n";
}
}
else // Vertex shader
{
out << "// Attributes\n";
out << attributes;
out << "\n"
"static float4 gl_Position = float4(0, 0, 0, 0);\n";
if (mUsesPointSize)
{
out << "static float gl_PointSize = float(1);\n";
}
out << "\n"
"// Varyings\n";
out << varyings;
out << "\n";
if (mUsesDepthRange)
{
out << "struct gl_DepthRangeParameters\n"
"{\n"
" float near;\n"
" float far;\n"
" float diff;\n"
"};\n"
"\n";
}
if (mOutputType == SH_HLSL11_OUTPUT)
{
if (mUsesDepthRange)
{
out << "cbuffer DriverConstants : register(b1)\n"
"{\n"
" float3 dx_DepthRange : packoffset(c0);\n"
"};\n"
"\n";
}
}
else
{
if (mUsesDepthRange)
{
out << "uniform float3 dx_DepthRange : register(c0);\n";
}
out << "uniform float4 dx_ViewAdjust : register(c1);\n"
"\n";
}
if (mUsesDepthRange)
{
out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
"\n";
}
out << uniforms;
out << "\n";
if (mUsesTexture2D)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2D(sampler2D s, float2 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x, t.y, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2D(Texture2D t, SamplerState s, float2 uv)\n"
"{\n"
" return t.SampleLevel(s, uv, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DLod)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DLod(sampler2D s, float2 t, float lod)\n"
"{\n"
" return tex2Dlod(s, float4(t.x, t.y, 0, lod));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DLod(Texture2D t, SamplerState s, float2 uv, float lod)\n"
"{\n"
" return t.SampleLevel(s, uv, lod);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProj)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProj(sampler2D s, float3 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.z, t.y / t.z, 0, 0));\n"
"}\n"
"\n"
"float4 gl_texture2DProj(sampler2D s, float4 t)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.w, t.y / t.w, 0, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProj(Texture2D t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.z, uvw.y / uvw.z), 0);\n"
"}\n"
"\n"
"float4 gl_texture2DProj(Texture2D t, SamplerState s, float4 uvw)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.w, uvw.y / uvw.w), 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTexture2DProjLod)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_texture2DProjLod(sampler2D s, float3 t, float lod)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.z, t.y / t.z, 0, lod));\n"
"}\n"
"\n"
"float4 gl_texture2DProjLod(sampler2D s, float4 t, float lod)\n"
"{\n"
" return tex2Dlod(s, float4(t.x / t.w, t.y / t.w, 0, lod));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_texture2DProj(Texture2D t, SamplerState s, float3 uvw, float lod)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.z, uvw.y / uvw.z), lod);\n"
"}\n"
"\n"
"float4 gl_texture2DProj(Texture2D t, SamplerState s, float4 uvw)\n"
"{\n"
" return t.SampleLevel(s, float2(uvw.x / uvw.w, uvw.y / uvw.w), lod);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCube)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCube(samplerCUBE s, float3 t)\n"
"{\n"
" return texCUBElod(s, float4(t.x, t.y, t.z, 0));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCube(TextureCube t, SamplerState s, float3 uvw)\n"
"{\n"
" return t.SampleLevel(s, uvw, 0);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
if (mUsesTextureCubeLod)
{
if (mOutputType == SH_HLSL9_OUTPUT)
{
out << "float4 gl_textureCubeLod(samplerCUBE s, float3 t, float lod)\n"
"{\n"
" return texCUBElod(s, float4(t.x, t.y, t.z, lod));\n"
"}\n"
"\n";
}
else if (mOutputType == SH_HLSL11_OUTPUT)
{
out << "float4 gl_textureCubeLod(TextureCube t, SamplerState s, float3 uvw, float lod)\n"
"{\n"
" return t.SampleLevel(s, uvw, lod);\n"
"}\n"
"\n";
}
else UNREACHABLE();
}
}
if (mUsesFragCoord)
{
out << "#define GL_USES_FRAG_COORD\n";
}
if (mUsesPointCoord)
{
out << "#define GL_USES_POINT_COORD\n";
}
if (mUsesFrontFacing)
{
out << "#define GL_USES_FRONT_FACING\n";
}
if (mUsesPointSize)
{
out << "#define GL_USES_POINT_SIZE\n";
}
if (mUsesFragDepth)
{
out << "#define GL_USES_FRAG_DEPTH\n";
}
if (mUsesDepthRange)
{
out << "#define GL_USES_DEPTH_RANGE\n";
}
if (mUsesXor)
{
out << "bool xor(bool p, bool q)\n"
"{\n"
" return (p || q) && !(p && q);\n"
"}\n"
"\n";
}
if (mUsesMod1)
{
out << "float mod(float x, float y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod2v)
{
out << "float2 mod(float2 x, float2 y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod2f)
{
out << "float2 mod(float2 x, float y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod3v)
{
out << "float3 mod(float3 x, float3 y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod3f)
{
out << "float3 mod(float3 x, float y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod4v)
{
out << "float4 mod(float4 x, float4 y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesMod4f)
{
out << "float4 mod(float4 x, float y)\n"
"{\n"
" return x - y * floor(x / y);\n"
"}\n"
"\n";
}
if (mUsesFaceforward1)
{
out << "float faceforward(float N, float I, float Nref)\n"
"{\n"
" if(dot(Nref, I) >= 0)\n"
" {\n"
" return -N;\n"
" }\n"
" else\n"
" {\n"
" return N;\n"
" }\n"
"}\n"
"\n";
}
if (mUsesFaceforward2)
{
out << "float2 faceforward(float2 N, float2 I, float2 Nref)\n"
"{\n"
" if(dot(Nref, I) >= 0)\n"
" {\n"
" return -N;\n"
" }\n"
" else\n"
" {\n"
" return N;\n"
" }\n"
"}\n"
"\n";
}
if (mUsesFaceforward3)
{
out << "float3 faceforward(float3 N, float3 I, float3 Nref)\n"
"{\n"
" if(dot(Nref, I) >= 0)\n"
" {\n"
" return -N;\n"
" }\n"
" else\n"
" {\n"
" return N;\n"
" }\n"
"}\n"
"\n";
}
if (mUsesFaceforward4)
{
out << "float4 faceforward(float4 N, float4 I, float4 Nref)\n"
"{\n"
" if(dot(Nref, I) >= 0)\n"
" {\n"
" return -N;\n"
" }\n"
" else\n"
" {\n"
" return N;\n"
" }\n"
"}\n"
"\n";
}
if (mUsesEqualMat2)
{
out << "bool equal(float2x2 m, float2x2 n)\n"
"{\n"
" return m[0][0] == n[0][0] && m[0][1] == n[0][1] &&\n"
" m[1][0] == n[1][0] && m[1][1] == n[1][1];\n"
"}\n";
}
if (mUsesEqualMat3)
{
out << "bool equal(float3x3 m, float3x3 n)\n"
"{\n"
" return m[0][0] == n[0][0] && m[0][1] == n[0][1] && m[0][2] == n[0][2] &&\n"
" m[1][0] == n[1][0] && m[1][1] == n[1][1] && m[1][2] == n[1][2] &&\n"
" m[2][0] == n[2][0] && m[2][1] == n[2][1] && m[2][2] == n[2][2];\n"
"}\n";
}
if (mUsesEqualMat4)
{
out << "bool equal(float4x4 m, float4x4 n)\n"
"{\n"
" return m[0][0] == n[0][0] && m[0][1] == n[0][1] && m[0][2] == n[0][2] && m[0][3] == n[0][3] &&\n"
" m[1][0] == n[1][0] && m[1][1] == n[1][1] && m[1][2] == n[1][2] && m[1][3] == n[1][3] &&\n"
" m[2][0] == n[2][0] && m[2][1] == n[2][1] && m[2][2] == n[2][2] && m[2][3] == n[2][3] &&\n"
" m[3][0] == n[3][0] && m[3][1] == n[3][1] && m[3][2] == n[3][2] && m[3][3] == n[3][3];\n"
"}\n";
}
if (mUsesEqualVec2)
{
out << "bool equal(float2 v, float2 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y;\n"
"}\n";
}
if (mUsesEqualVec3)
{
out << "bool equal(float3 v, float3 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z;\n"
"}\n";
}
if (mUsesEqualVec4)
{
out << "bool equal(float4 v, float4 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
"}\n";
}
if (mUsesEqualIVec2)
{
out << "bool equal(int2 v, int2 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y;\n"
"}\n";
}
if (mUsesEqualIVec3)
{
out << "bool equal(int3 v, int3 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z;\n"
"}\n";
}
if (mUsesEqualIVec4)
{
out << "bool equal(int4 v, int4 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
"}\n";
}
if (mUsesEqualBVec2)
{
out << "bool equal(bool2 v, bool2 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y;\n"
"}\n";
}
if (mUsesEqualBVec3)
{
out << "bool equal(bool3 v, bool3 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z;\n"
"}\n";
}
if (mUsesEqualBVec4)
{
out << "bool equal(bool4 v, bool4 u)\n"
"{\n"
" return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
"}\n";
}
if (mUsesAtan2_1)
{
out << "float atanyx(float y, float x)\n"
"{\n"
" if(x == 0 && y == 0) x = 1;\n" // Avoid producing a NaN
" return atan2(y, x);\n"
"}\n";
}
if (mUsesAtan2_2)
{
out << "float2 atanyx(float2 y, float2 x)\n"
"{\n"
" if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
" if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
" return float2(atan2(y[0], x[0]), atan2(y[1], x[1]));\n"
"}\n";
}
if (mUsesAtan2_3)
{
out << "float3 atanyx(float3 y, float3 x)\n"
"{\n"
" if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
" if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
" if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
" return float3(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]));\n"
"}\n";
}
if (mUsesAtan2_4)
{
out << "float4 atanyx(float4 y, float4 x)\n"
"{\n"
" if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
" if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
" if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
" if(x[3] == 0 && y[3] == 0) x[3] = 1;\n"
" return float4(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]), atan2(y[3], x[3]));\n"
"}\n";
}
}
void OutputHLSL::visitSymbol(TIntermSymbol *node)
{
TInfoSinkBase &out = mBody;
TString name = node->getSymbol();
if (name == "gl_FragColor")
{
out << "gl_Color[0]";
mUsesFragColor = true;
}
else if (name == "gl_FragData")
{
out << "gl_Color";
mUsesFragData = true;
}
else if (name == "gl_DepthRange")
{
mUsesDepthRange = true;
out << name;
}
else if (name == "gl_FragCoord")
{
mUsesFragCoord = true;
out << name;
}
else if (name == "gl_PointCoord")
{
mUsesPointCoord = true;
out << name;
}
else if (name == "gl_FrontFacing")
{
mUsesFrontFacing = true;
out << name;
}
else if (name == "gl_PointSize")
{
mUsesPointSize = true;
out << name;
}
else if (name == "gl_FragDepthEXT")
{
mUsesFragDepth = true;
out << "gl_Depth";
}
else
{
TQualifier qualifier = node->getQualifier();
if (qualifier == EvqUniform)
{
mReferencedUniforms[name] = node;
out << decorateUniform(name, node->getType());
}
else if (qualifier == EvqAttribute)
{
mReferencedAttributes[name] = node;
out << decorate(name);
}
else if (qualifier == EvqVaryingOut || qualifier == EvqInvariantVaryingOut || qualifier == EvqVaryingIn || qualifier == EvqInvariantVaryingIn)
{
mReferencedVaryings[name] = node;
out << decorate(name);
}
else
{
out << decorate(name);
}
}
}
bool OutputHLSL::visitBinary(Visit visit, TIntermBinary *node)
{
TInfoSinkBase &out = mBody;
switch (node->getOp())
{
case EOpAssign: outputTriplet(visit, "(", " = ", ")"); break;
case EOpInitialize:
if (visit == PreVisit)
{
// GLSL allows to write things like "float x = x;" where a new variable x is defined
// and the value of an existing variable x is assigned. HLSL uses C semantics (the
// new variable is created before the assignment is evaluated), so we need to convert
// this to "float t = x, x = t;".
TIntermSymbol *symbolNode = node->getLeft()->getAsSymbolNode();
TIntermTyped *expression = node->getRight();
sh::SearchSymbol searchSymbol(symbolNode->getSymbol());
expression->traverse(&searchSymbol);
bool sameSymbol = searchSymbol.foundMatch();
if (sameSymbol)
{
// Type already printed
out << "t" + str(mUniqueIndex) + " = ";
expression->traverse(this);
out << ", ";
symbolNode->traverse(this);
out << " = t" + str(mUniqueIndex);
mUniqueIndex++;
return false;
}
}
else if (visit == InVisit)
{
out << " = ";
}
break;
case EOpAddAssign: outputTriplet(visit, "(", " += ", ")"); break;
case EOpSubAssign: outputTriplet(visit, "(", " -= ", ")"); break;
case EOpMulAssign: outputTriplet(visit, "(", " *= ", ")"); break;
case EOpVectorTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
case EOpMatrixTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
case EOpVectorTimesMatrixAssign:
if (visit == PreVisit)
{
out << "(";
}
else if (visit == InVisit)
{
out << " = mul(";
node->getLeft()->traverse(this);
out << ", transpose(";
}
else
{
out << ")))";
}
break;
case EOpMatrixTimesMatrixAssign:
if (visit == PreVisit)
{
out << "(";
}
else if (visit == InVisit)
{
out << " = mul(";
node->getLeft()->traverse(this);
out << ", ";
}
else
{
out << "))";
}
break;
case EOpDivAssign: outputTriplet(visit, "(", " /= ", ")"); break;
case EOpIndexDirect: outputTriplet(visit, "", "[", "]"); break;
case EOpIndexIndirect: outputTriplet(visit, "", "[", "]"); break;
case EOpIndexDirectStruct:
if (visit == InVisit)
{
out << "." + decorateField(node->getType().getFieldName(), node->getLeft()->getType());
return false;
}
break;
case EOpVectorSwizzle:
if (visit == InVisit)
{
out << ".";
TIntermAggregate *swizzle = node->getRight()->getAsAggregate();
if (swizzle)
{
TIntermSequence &sequence = swizzle->getSequence();
for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
{
TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
if (element)
{
int i = element->getIConst(0);
switch (i)
{
case 0: out << "x"; break;
case 1: out << "y"; break;
case 2: out << "z"; break;
case 3: out << "w"; break;
default: UNREACHABLE();
}
}
else UNREACHABLE();
}
}
else UNREACHABLE();
return false; // Fully processed
}
break;
case EOpAdd: outputTriplet(visit, "(", " + ", ")"); break;
case EOpSub: outputTriplet(visit, "(", " - ", ")"); break;
case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
case EOpDiv: outputTriplet(visit, "(", " / ", ")"); break;
case EOpEqual:
case EOpNotEqual:
if (node->getLeft()->isScalar())
{
if (node->getOp() == EOpEqual)
{
outputTriplet(visit, "(", " == ", ")");
}
else
{
outputTriplet(visit, "(", " != ", ")");
}
}
else if (node->getLeft()->getBasicType() == EbtStruct)
{
if (node->getOp() == EOpEqual)
{
out << "(";
}
else
{
out << "!(";
}
const TTypeList *fields = node->getLeft()->getType().getStruct();
for (size_t i = 0; i < fields->size(); i++)
{
const TType *fieldType = (*fields)[i];
node->getLeft()->traverse(this);
out << "." + decorateField(fieldType->getFieldName(), node->getLeft()->getType()) + " == ";
node->getRight()->traverse(this);
out << "." + decorateField(fieldType->getFieldName(), node->getLeft()->getType());
if (i < fields->size() - 1)
{
out << " && ";
}
}
out << ")";
return false;
}
else
{
if (node->getLeft()->isMatrix())
{
switch (node->getLeft()->getNominalSize())
{
case 2: mUsesEqualMat2 = true; break;
case 3: mUsesEqualMat3 = true; break;
case 4: mUsesEqualMat4 = true; break;
default: UNREACHABLE();
}
}
else if (node->getLeft()->isVector())
{
switch (node->getLeft()->getBasicType())
{
case EbtFloat:
switch (node->getLeft()->getNominalSize())
{
case 2: mUsesEqualVec2 = true; break;
case 3: mUsesEqualVec3 = true; break;
case 4: mUsesEqualVec4 = true; break;
default: UNREACHABLE();
}
break;
case EbtInt:
switch (node->getLeft()->getNominalSize())
{
case 2: mUsesEqualIVec2 = true; break;
case 3: mUsesEqualIVec3 = true; break;
case 4: mUsesEqualIVec4 = true; break;
default: UNREACHABLE();
}
break;
case EbtBool:
switch (node->getLeft()->getNominalSize())
{
case 2: mUsesEqualBVec2 = true; break;
case 3: mUsesEqualBVec3 = true; break;
case 4: mUsesEqualBVec4 = true; break;
default: UNREACHABLE();
}
break;
default: UNREACHABLE();
}
}
else UNREACHABLE();
if (node->getOp() == EOpEqual)
{
outputTriplet(visit, "equal(", ", ", ")");
}
else
{
outputTriplet(visit, "!equal(", ", ", ")");
}
}
break;
case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
case EOpVectorTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
case EOpMatrixTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
case EOpVectorTimesMatrix: outputTriplet(visit, "mul(", ", transpose(", "))"); break;
case EOpMatrixTimesVector: outputTriplet(visit, "mul(transpose(", "), ", ")"); break;
case EOpMatrixTimesMatrix: outputTriplet(visit, "transpose(mul(transpose(", "), transpose(", ")))"); break;
case EOpLogicalOr:
out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
return false;
case EOpLogicalXor:
mUsesXor = true;
outputTriplet(visit, "xor(", ", ", ")");
break;
case EOpLogicalAnd:
out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
return false;
default: UNREACHABLE();
}
return true;
}
bool OutputHLSL::visitUnary(Visit visit, TIntermUnary *node)
{
switch (node->getOp())
{
case EOpNegative: outputTriplet(visit, "(-", "", ")"); break;
case EOpVectorLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
case EOpLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
case EOpPostIncrement: outputTriplet(visit, "(", "", "++)"); break;
case EOpPostDecrement: outputTriplet(visit, "(", "", "--)"); break;
case EOpPreIncrement: outputTriplet(visit, "(++", "", ")"); break;
case EOpPreDecrement: outputTriplet(visit, "(--", "", ")"); break;
case EOpConvIntToBool:
case EOpConvFloatToBool:
switch (node->getOperand()->getType().getNominalSize())
{
case 1: outputTriplet(visit, "bool(", "", ")"); break;
case 2: outputTriplet(visit, "bool2(", "", ")"); break;
case 3: outputTriplet(visit, "bool3(", "", ")"); break;
case 4: outputTriplet(visit, "bool4(", "", ")"); break;
default: UNREACHABLE();
}
break;
case EOpConvBoolToFloat:
case EOpConvIntToFloat:
switch (node->getOperand()->getType().getNominalSize())
{
case 1: outputTriplet(visit, "float(", "", ")"); break;
case 2: outputTriplet(visit, "float2(", "", ")"); break;
case 3: outputTriplet(visit, "float3(", "", ")"); break;
case 4: outputTriplet(visit, "float4(", "", ")"); break;
default: UNREACHABLE();
}
break;
case EOpConvFloatToInt:
case EOpConvBoolToInt:
switch (node->getOperand()->getType().getNominalSize())
{
case 1: outputTriplet(visit, "int(", "", ")"); break;
case 2: outputTriplet(visit, "int2(", "", ")"); break;
case 3: outputTriplet(visit, "int3(", "", ")"); break;
case 4: outputTriplet(visit, "int4(", "", ")"); break;
default: UNREACHABLE();
}
break;
case EOpRadians: outputTriplet(visit, "radians(", "", ")"); break;
case EOpDegrees: outputTriplet(visit, "degrees(", "", ")"); break;
case EOpSin: outputTriplet(visit, "sin(", "", ")"); break;
case EOpCos: outputTriplet(visit, "cos(", "", ")"); break;
case EOpTan: outputTriplet(visit, "tan(", "", ")"); break;
case EOpAsin: outputTriplet(visit, "asin(", "", ")"); break;
case EOpAcos: outputTriplet(visit, "acos(", "", ")"); break;
case EOpAtan: outputTriplet(visit, "atan(", "", ")"); break;
case EOpExp: outputTriplet(visit, "exp(", "", ")"); break;
case EOpLog: outputTriplet(visit, "log(", "", ")"); break;
case EOpExp2: outputTriplet(visit, "exp2(", "", ")"); break;
case EOpLog2: outputTriplet(visit, "log2(", "", ")"); break;
case EOpSqrt: outputTriplet(visit, "sqrt(", "", ")"); break;
case EOpInverseSqrt: outputTriplet(visit, "rsqrt(", "", ")"); break;
case EOpAbs: outputTriplet(visit, "abs(", "", ")"); break;
case EOpSign: outputTriplet(visit, "sign(", "", ")"); break;
case EOpFloor: outputTriplet(visit, "floor(", "", ")"); break;
case EOpCeil: outputTriplet(visit, "ceil(", "", ")"); break;
case EOpFract: outputTriplet(visit, "frac(", "", ")"); break;
case EOpLength: outputTriplet(visit, "length(", "", ")"); break;
case EOpNormalize: outputTriplet(visit, "normalize(", "", ")"); break;
case EOpDFdx:
if(mInsideDiscontinuousLoop || mOutputLod0Function)
{
outputTriplet(visit, "(", "", ", 0.0)");
}
else
{
outputTriplet(visit, "ddx(", "", ")");
}
break;
case EOpDFdy:
if(mInsideDiscontinuousLoop || mOutputLod0Function)
{
outputTriplet(visit, "(", "", ", 0.0)");
}
else
{
outputTriplet(visit, "ddy(", "", ")");
}
break;
case EOpFwidth:
if(mInsideDiscontinuousLoop || mOutputLod0Function)
{
outputTriplet(visit, "(", "", ", 0.0)");
}
else
{
outputTriplet(visit, "fwidth(", "", ")");
}
break;
case EOpAny: outputTriplet(visit, "any(", "", ")"); break;
case EOpAll: outputTriplet(visit, "all(", "", ")"); break;
default: UNREACHABLE();
}
return true;
}
bool OutputHLSL::visitAggregate(Visit visit, TIntermAggregate *node)
{
TInfoSinkBase &out = mBody;
switch (node->getOp())
{
case EOpSequence:
{
if (mInsideFunction)
{
outputLineDirective(node->getLine().first_line);
out << "{\n";
mScopeDepth++;
if (mScopeBracket.size() < mScopeDepth)
{
mScopeBracket.push_back(0); // New scope level
}
else
{
mScopeBracket[mScopeDepth - 1]++; // New scope at existing level
}
}
for (TIntermSequence::iterator sit = node->getSequence().begin(); sit != node->getSequence().end(); sit++)
{
outputLineDirective((*sit)->getLine().first_line);
traverseStatements(*sit);
out << ";\n";
}
if (mInsideFunction)
{
outputLineDirective(node->getLine().last_line);
out << "}\n";
mScopeDepth--;
}
return false;
}
case EOpDeclaration:
if (visit == PreVisit)
{
TIntermSequence &sequence = node->getSequence();
TIntermTyped *variable = sequence[0]->getAsTyped();
if (variable && (variable->getQualifier() == EvqTemporary || variable->getQualifier() == EvqGlobal))
{
if (variable->getType().getStruct())
{
addConstructor(variable->getType(), scopedStruct(variable->getType().getTypeName()), NULL);
}
if (!variable->getAsSymbolNode() || variable->getAsSymbolNode()->getSymbol() != "") // Variable declaration
{
if (!mInsideFunction)
{
out << "static ";
}
out << typeString(variable->getType()) + " ";
for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
{
TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
if (symbol)
{
symbol->traverse(this);
out << arrayString(symbol->getType());
out << " = " + initializer(variable->getType());
}
else
{
(*sit)->traverse(this);
}
if (*sit != sequence.back())
{
out << ", ";
}
}
}
else if (variable->getAsSymbolNode() && variable->getAsSymbolNode()->getSymbol() == "") // Type (struct) declaration
{
// Already added to constructor map
}
else UNREACHABLE();
}
else if (variable && (variable->getQualifier() == EvqVaryingOut || variable->getQualifier() == EvqInvariantVaryingOut))
{
for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
{
TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
if (symbol)
{
// Vertex (output) varyings which are declared but not written to should still be declared to allow successful linking
mReferencedVaryings[symbol->getSymbol()] = symbol;
}
else
{
(*sit)->traverse(this);
}
}
}
return false;
}
else if (visit == InVisit)
{
out << ", ";
}
break;
case EOpPrototype:
if (visit == PreVisit)
{
out << typeString(node->getType()) << " " << decorate(node->getName()) << (mOutputLod0Function ? "Lod0(" : "(");
TIntermSequence &arguments = node->getSequence();
for (unsigned int i = 0; i < arguments.size(); i++)
{
TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
if (symbol)
{
out << argumentString(symbol);
if (i < arguments.size() - 1)
{
out << ", ";
}
}
else UNREACHABLE();
}
out << ");\n";
// Also prototype the Lod0 variant if needed
if (mContainsLoopDiscontinuity && !mOutputLod0Function)
{
mOutputLod0Function = true;
node->traverse(this);
mOutputLod0Function = false;
}
return false;
}
break;
case EOpComma: outputTriplet(visit, "(", ", ", ")"); break;
case EOpFunction:
{
TString name = TFunction::unmangleName(node->getName());
out << typeString(node->getType()) << " ";
if (name == "main")
{
out << "gl_main(";
}
else
{
out << decorate(name) << (mOutputLod0Function ? "Lod0(" : "(");
}
TIntermSequence &sequence = node->getSequence();
TIntermSequence &arguments = sequence[0]->getAsAggregate()->getSequence();
for (unsigned int i = 0; i < arguments.size(); i++)
{
TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
if (symbol)
{
if (symbol->getType().getStruct())
{
addConstructor(symbol->getType(), scopedStruct(symbol->getType().getTypeName()), NULL);
}
out << argumentString(symbol);
if (i < arguments.size() - 1)
{
out << ", ";
}
}
else UNREACHABLE();
}
out << ")\n"
"{\n";
if (sequence.size() > 1)
{
mInsideFunction = true;
sequence[1]->traverse(this);
mInsideFunction = false;
}
out << "}\n";
if (mContainsLoopDiscontinuity && !mOutputLod0Function)
{
if (name != "main")
{
mOutputLod0Function = true;
node->traverse(this);
mOutputLod0Function = false;
}
}
return false;
}
break;
case EOpFunctionCall:
{
TString name = TFunction::unmangleName(node->getName());
bool lod0 = mInsideDiscontinuousLoop || mOutputLod0Function;
if (node->isUserDefined())
{
out << decorate(name) << (lod0 ? "Lod0(" : "(");
}
else
{
if (name == "texture2D")
{
if (!lod0)
{
if (node->getSequence().size() == 2)
{
mUsesTexture2D = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTexture2D_bias = true;
}
else UNREACHABLE();
out << "gl_texture2D(";
}
else
{
if (node->getSequence().size() == 2)
{
mUsesTexture2DLod0 = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTexture2DLod0_bias = true;
}
else UNREACHABLE();
out << "gl_texture2DLod0(";
}
}
else if (name == "texture2DProj")
{
if (!lod0)
{
if (node->getSequence().size() == 2)
{
mUsesTexture2DProj = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTexture2DProj_bias = true;
}
else UNREACHABLE();
out << "gl_texture2DProj(";
}
else
{
if (node->getSequence().size() == 2)
{
mUsesTexture2DProjLod0 = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTexture2DProjLod0_bias = true;
}
else UNREACHABLE();
out << "gl_texture2DProjLod0(";
}
}
else if (name == "textureCube")
{
if (!lod0)
{
if (node->getSequence().size() == 2)
{
mUsesTextureCube = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTextureCube_bias = true;
}
else UNREACHABLE();
out << "gl_textureCube(";
}
else
{
if (node->getSequence().size() == 2)
{
mUsesTextureCubeLod0 = true;
}
else if (node->getSequence().size() == 3)
{
mUsesTextureCubeLod0_bias = true;
}
else UNREACHABLE();
out << "gl_textureCubeLod0(";
}
}
else if (name == "texture2DLod")
{
if (node->getSequence().size() == 3)
{
mUsesTexture2DLod = true;
}
else UNREACHABLE();
out << "gl_texture2DLod(";
}
else if (name == "texture2DProjLod")
{
if (node->getSequence().size() == 3)
{
mUsesTexture2DProjLod = true;
}
else UNREACHABLE();
out << "gl_texture2DProjLod(";
}
else if (name == "textureCubeLod")
{
if (node->getSequence().size() == 3)
{
mUsesTextureCubeLod = true;
}
else UNREACHABLE();
out << "gl_textureCubeLod(";
}
else UNREACHABLE();
}
TIntermSequence &arguments = node->getSequence();
for (TIntermSequence::iterator arg = arguments.begin(); arg != arguments.end(); arg++)
{
if (mOutputType == SH_HLSL11_OUTPUT && IsSampler((*arg)->getAsTyped()->getBasicType()))
{
out << "texture_";
(*arg)->traverse(this);
out << ", sampler_";
}
(*arg)->traverse(this);
if (arg < arguments.end() - 1)
{
out << ", ";
}
}
out << ")";
return false;
}
break;
case EOpParameters: outputTriplet(visit, "(", ", ", ")\n{\n"); break;
case EOpConstructFloat:
addConstructor(node->getType(), "vec1", &node->getSequence());
outputTriplet(visit, "vec1(", "", ")");
break;
case EOpConstructVec2:
addConstructor(node->getType(), "vec2", &node->getSequence());
outputTriplet(visit, "vec2(", ", ", ")");
break;
case EOpConstructVec3:
addConstructor(node->getType(), "vec3", &node->getSequence());
outputTriplet(visit, "vec3(", ", ", ")");
break;
case EOpConstructVec4:
addConstructor(node->getType(), "vec4", &node->getSequence());
outputTriplet(visit, "vec4(", ", ", ")");
break;
case EOpConstructBool:
addConstructor(node->getType(), "bvec1", &node->getSequence());
outputTriplet(visit, "bvec1(", "", ")");
break;
case EOpConstructBVec2:
addConstructor(node->getType(), "bvec2", &node->getSequence());
outputTriplet(visit, "bvec2(", ", ", ")");
break;
case EOpConstructBVec3:
addConstructor(node->getType(), "bvec3", &node->getSequence());
outputTriplet(visit, "bvec3(", ", ", ")");
break;
case EOpConstructBVec4:
addConstructor(node->getType(), "bvec4", &node->getSequence());
outputTriplet(visit, "bvec4(", ", ", ")");
break;
case EOpConstructInt:
addConstructor(node->getType(), "ivec1", &node->getSequence());
outputTriplet(visit, "ivec1(", "", ")");
break;
case EOpConstructIVec2:
addConstructor(node->getType(), "ivec2", &node->getSequence());
outputTriplet(visit, "ivec2(", ", ", ")");
break;
case EOpConstructIVec3:
addConstructor(node->getType(), "ivec3", &node->getSequence());
outputTriplet(visit, "ivec3(", ", ", ")");
break;
case EOpConstructIVec4:
addConstructor(node->getType(), "ivec4", &node->getSequence());
outputTriplet(visit, "ivec4(", ", ", ")");
break;
case EOpConstructMat2:
addConstructor(node->getType(), "mat2", &node->getSequence());
outputTriplet(visit, "mat2(", ", ", ")");
break;
case EOpConstructMat3:
addConstructor(node->getType(), "mat3", &node->getSequence());
outputTriplet(visit, "mat3(", ", ", ")");
break;
case EOpConstructMat4:
addConstructor(node->getType(), "mat4", &node->getSequence());
outputTriplet(visit, "mat4(", ", ", ")");
break;
case EOpConstructStruct:
addConstructor(node->getType(), scopedStruct(node->getType().getTypeName()), &node->getSequence());
outputTriplet(visit, structLookup(node->getType().getTypeName()) + "_ctor(", ", ", ")");
break;
case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
case EOpVectorEqual: outputTriplet(visit, "(", " == ", ")"); break;
case EOpVectorNotEqual: outputTriplet(visit, "(", " != ", ")"); break;
case EOpMod:
{
// We need to look at the number of components in both arguments
switch (node->getSequence()[0]->getAsTyped()->getNominalSize() * 10
+ node->getSequence()[1]->getAsTyped()->getNominalSize())
{
case 11: mUsesMod1 = true; break;
case 22: mUsesMod2v = true; break;
case 21: mUsesMod2f = true; break;
case 33: mUsesMod3v = true; break;
case 31: mUsesMod3f = true; break;
case 44: mUsesMod4v = true; break;
case 41: mUsesMod4f = true; break;
default: UNREACHABLE();
}
outputTriplet(visit, "mod(", ", ", ")");
}
break;
case EOpPow: outputTriplet(visit, "pow(", ", ", ")"); break;
case EOpAtan:
ASSERT(node->getSequence().size() == 2); // atan(x) is a unary operator
switch (node->getSequence()[0]->getAsTyped()->getNominalSize())
{
case 1: mUsesAtan2_1 = true; break;
case 2: mUsesAtan2_2 = true; break;
case 3: mUsesAtan2_3 = true; break;
case 4: mUsesAtan2_4 = true; break;
default: UNREACHABLE();
}
outputTriplet(visit, "atanyx(", ", ", ")");
break;
case EOpMin: outputTriplet(visit, "min(", ", ", ")"); break;
case EOpMax: outputTriplet(visit, "max(", ", ", ")"); break;
case EOpClamp: outputTriplet(visit, "clamp(", ", ", ")"); break;
case EOpMix: outputTriplet(visit, "lerp(", ", ", ")"); break;
case EOpStep: outputTriplet(visit, "step(", ", ", ")"); break;
case EOpSmoothStep: outputTriplet(visit, "smoothstep(", ", ", ")"); break;
case EOpDistance: outputTriplet(visit, "distance(", ", ", ")"); break;
case EOpDot: outputTriplet(visit, "dot(", ", ", ")"); break;
case EOpCross: outputTriplet(visit, "cross(", ", ", ")"); break;
case EOpFaceForward:
{
switch (node->getSequence()[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
{
case 1: mUsesFaceforward1 = true; break;
case 2: mUsesFaceforward2 = true; break;
case 3: mUsesFaceforward3 = true; break;
case 4: mUsesFaceforward4 = true; break;
default: UNREACHABLE();
}
outputTriplet(visit, "faceforward(", ", ", ")");
}
break;
case EOpReflect: outputTriplet(visit, "reflect(", ", ", ")"); break;
case EOpRefract: outputTriplet(visit, "refract(", ", ", ")"); break;
case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
default: UNREACHABLE();
}
return true;
}
bool OutputHLSL::visitSelection(Visit visit, TIntermSelection *node)
{
TInfoSinkBase &out = mBody;
if (node->usesTernaryOperator())
{
out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
}
else // if/else statement
{
mUnfoldShortCircuit->traverse(node->getCondition());
out << "if(";
node->getCondition()->traverse(this);
out << ")\n";
outputLineDirective(node->getLine().first_line);
out << "{\n";
if (node->getTrueBlock())
{
traverseStatements(node->getTrueBlock());
}
outputLineDirective(node->getLine().first_line);
out << ";\n}\n";
if (node->getFalseBlock())
{
out << "else\n";
outputLineDirective(node->getFalseBlock()->getLine().first_line);
out << "{\n";
outputLineDirective(node->getFalseBlock()->getLine().first_line);
traverseStatements(node->getFalseBlock());
outputLineDirective(node->getFalseBlock()->getLine().first_line);
out << ";\n}\n";
}
}
return false;
}
void OutputHLSL::visitConstantUnion(TIntermConstantUnion *node)
{
writeConstantUnion(node->getType(), node->getUnionArrayPointer());
}
bool OutputHLSL::visitLoop(Visit visit, TIntermLoop *node)
{
bool wasDiscontinuous = mInsideDiscontinuousLoop;
if (mContainsLoopDiscontinuity && !mInsideDiscontinuousLoop)
{
mInsideDiscontinuousLoop = containsLoopDiscontinuity(node);
}
if (mOutputType == SH_HLSL9_OUTPUT)
{
if (handleExcessiveLoop(node))
{
return false;
}
}
TInfoSinkBase &out = mBody;
if (node->getType() == ELoopDoWhile)
{
out << "{do\n";
outputLineDirective(node->getLine().first_line);
out << "{\n";
}
else
{
out << "{for(";
if (node->getInit())
{
node->getInit()->traverse(this);
}
out << "; ";
if (node->getCondition())
{
node->getCondition()->traverse(this);
}
out << "; ";
if (node->getExpression())
{
node->getExpression()->traverse(this);
}
out << ")\n";
outputLineDirective(node->getLine().first_line);
out << "{\n";
}
if (node->getBody())
{
traverseStatements(node->getBody());
}
outputLineDirective(node->getLine().first_line);
out << ";}\n";
if (node->getType() == ELoopDoWhile)
{
outputLineDirective(node->getCondition()->getLine().first_line);
out << "while(\n";
node->getCondition()->traverse(this);
out << ");";
}
out << "}\n";
mInsideDiscontinuousLoop = wasDiscontinuous;
return false;
}
bool OutputHLSL::visitBranch(Visit visit, TIntermBranch *node)
{
TInfoSinkBase &out = mBody;
switch (node->getFlowOp())
{
case EOpKill: outputTriplet(visit, "discard;\n", "", ""); break;
case EOpBreak:
if (visit == PreVisit)
{
if (mExcessiveLoopIndex)
{
out << "{Break";
mExcessiveLoopIndex->traverse(this);
out << " = true; break;}\n";
}
else
{
out << "break;\n";
}
}
break;
case EOpContinue: outputTriplet(visit, "continue;\n", "", ""); break;
case EOpReturn:
if (visit == PreVisit)
{
if (node->getExpression())
{
out << "return ";
}
else
{
out << "return;\n";
}
}
else if (visit == PostVisit)
{
if (node->getExpression())
{
out << ";\n";
}
}
break;
default: UNREACHABLE();
}
return true;
}
void OutputHLSL::traverseStatements(TIntermNode *node)
{
if (isSingleStatement(node))
{
mUnfoldShortCircuit->traverse(node);
}
node->traverse(this);
}
bool OutputHLSL::isSingleStatement(TIntermNode *node)
{
TIntermAggregate *aggregate = node->getAsAggregate();
if (aggregate)
{
if (aggregate->getOp() == EOpSequence)
{
return false;
}
else
{
for (TIntermSequence::iterator sit = aggregate->getSequence().begin(); sit != aggregate->getSequence().end(); sit++)
{
if (!isSingleStatement(*sit))
{
return false;
}
}
return true;
}
}
return true;
}
// Handle loops with more than 254 iterations (unsupported by D3D9) by splitting them
// (The D3D documentation says 255 iterations, but the compiler complains at anything more than 254).
bool OutputHLSL::handleExcessiveLoop(TIntermLoop *node)
{
const int MAX_LOOP_ITERATIONS = 254;
TInfoSinkBase &out = mBody;
// Parse loops of the form:
// for(int index = initial; index [comparator] limit; index += increment)
TIntermSymbol *index = NULL;
TOperator comparator = EOpNull;
int initial = 0;
int limit = 0;
int increment = 0;
// Parse index name and intial value
if (node->getInit())
{
TIntermAggregate *init = node->getInit()->getAsAggregate();
if (init)
{
TIntermSequence &sequence = init->getSequence();
TIntermTyped *variable = sequence[0]->getAsTyped();
if (variable && variable->getQualifier() == EvqTemporary)
{
TIntermBinary *assign = variable->getAsBinaryNode();
if (assign->getOp() == EOpInitialize)
{
TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
if (symbol && constant)
{
if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
{
index = symbol;
initial = constant->getIConst(0);
}
}
}
}
}
}
// Parse comparator and limit value
if (index != NULL && node->getCondition())
{
TIntermBinary *test = node->getCondition()->getAsBinaryNode();
if (test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
{
TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
if (constant)
{
if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
{
comparator = test->getOp();
limit = constant->getIConst(0);
}
}
}
}
// Parse increment
if (index != NULL && comparator != EOpNull && node->getExpression())
{
TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
if (binaryTerminal)
{
TOperator op = binaryTerminal->getOp();
TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
if (constant)
{
if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
{
int value = constant->getIConst(0);
switch (op)
{
case EOpAddAssign: increment = value; break;
case EOpSubAssign: increment = -value; break;
default: UNIMPLEMENTED();
}
}
}
}
else if (unaryTerminal)
{
TOperator op = unaryTerminal->getOp();
switch (op)
{
case EOpPostIncrement: increment = 1; break;
case EOpPostDecrement: increment = -1; break;
case EOpPreIncrement: increment = 1; break;
case EOpPreDecrement: increment = -1; break;
default: UNIMPLEMENTED();
}
}
}
if (index != NULL && comparator != EOpNull && increment != 0)
{
if (comparator == EOpLessThanEqual)
{
comparator = EOpLessThan;
limit += 1;
}
if (comparator == EOpLessThan)
{
int iterations = (limit - initial) / increment;
if (iterations <= MAX_LOOP_ITERATIONS)
{
return false; // Not an excessive loop
}
TIntermSymbol *restoreIndex = mExcessiveLoopIndex;
mExcessiveLoopIndex = index;
out << "{int ";
index->traverse(this);
out << ";\n"
"bool Break";
index->traverse(this);
out << " = false;\n";
bool firstLoopFragment = true;
while (iterations > 0)
{
int clampedLimit = initial + increment * std::min(MAX_LOOP_ITERATIONS, iterations);
if (!firstLoopFragment)
{
out << "if(!Break";
index->traverse(this);
out << ") {\n";
}
if (iterations <= MAX_LOOP_ITERATIONS) // Last loop fragment
{
mExcessiveLoopIndex = NULL; // Stops setting the Break flag
}
// for(int index = initial; index < clampedLimit; index += increment)
out << "for(";
index->traverse(this);
out << " = ";
out << initial;
out << "; ";
index->traverse(this);
out << " < ";
out << clampedLimit;
out << "; ";
index->traverse(this);
out << " += ";
out << increment;
out << ")\n";
outputLineDirective(node->getLine().first_line);
out << "{\n";
if (node->getBody())
{
node->getBody()->traverse(this);
}
outputLineDirective(node->getLine().first_line);
out << ";}\n";
if (!firstLoopFragment)
{
out << "}\n";
}
firstLoopFragment = false;
initial += MAX_LOOP_ITERATIONS * increment;
iterations -= MAX_LOOP_ITERATIONS;
}
out << "}";
mExcessiveLoopIndex = restoreIndex;
return true;
}
else UNIMPLEMENTED();
}
return false; // Not handled as an excessive loop
}
void OutputHLSL::outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString)
{
TInfoSinkBase &out = mBody;
if (visit == PreVisit)
{
out << preString;
}
else if (visit == InVisit)
{
out << inString;
}
else if (visit == PostVisit)
{
out << postString;
}
}
void OutputHLSL::outputLineDirective(int line)
{
if ((mContext.compileOptions & SH_LINE_DIRECTIVES) && (line > 0))
{
mBody << "\n";
mBody << "#line " << line;
if (mContext.sourcePath)
{
mBody << " \"" << mContext.sourcePath << "\"";
}
mBody << "\n";
}
}
TString OutputHLSL::argumentString(const TIntermSymbol *symbol)
{
TQualifier qualifier = symbol->getQualifier();
const TType &type = symbol->getType();
TString name = symbol->getSymbol();
if (name.empty()) // HLSL demands named arguments, also for prototypes
{
name = "x" + str(mUniqueIndex++);
}
else
{
name = decorate(name);
}
if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType()))
{
return qualifierString(qualifier) + " " + textureString(type) + " texture_" + name + arrayString(type) + ", " +
qualifierString(qualifier) + " SamplerState sampler_" + name + arrayString(type);
}
return qualifierString(qualifier) + " " + typeString(type) + " " + name + arrayString(type);
}
TString OutputHLSL::qualifierString(TQualifier qualifier)
{
switch(qualifier)
{
case EvqIn: return "in";
case EvqOut: return "out";
case EvqInOut: return "inout";
case EvqConstReadOnly: return "const";
default: UNREACHABLE();
}
return "";
}
TString OutputHLSL::typeString(const TType &type)
{
if (type.getBasicType() == EbtStruct)
{
if (type.getTypeName() != "")
{
return structLookup(type.getTypeName());
}
else // Nameless structure, define in place
{
const TTypeList &fields = *type.getStruct();
TString string = "struct\n"
"{\n";
for (unsigned int i = 0; i < fields.size(); i++)
{
const TType &field = *fields[i];
string += " " + typeString(field) + " " + decorate(field.getFieldName()) + arrayString(field) + ";\n";
}
string += "} ";
return string;
}
}
else if (type.isMatrix())
{
switch (type.getNominalSize())
{
case 2: return "float2x2";
case 3: return "float3x3";
case 4: return "float4x4";
}
}
else
{
switch (type.getBasicType())
{
case EbtFloat:
switch (type.getNominalSize())
{
case 1: return "float";
case 2: return "float2";
case 3: return "float3";
case 4: return "float4";
}
case EbtInt:
switch (type.getNominalSize())
{
case 1: return "int";
case 2: return "int2";
case 3: return "int3";
case 4: return "int4";
}
case EbtBool:
switch (type.getNominalSize())
{
case 1: return "bool";
case 2: return "bool2";
case 3: return "bool3";
case 4: return "bool4";
}
case EbtVoid:
return "void";
case EbtSampler2D:
return "sampler2D";
case EbtSamplerCube:
return "samplerCUBE";
case EbtSamplerExternalOES:
return "sampler2D";
default:
break;
}
}
UNREACHABLE();
return "<unknown type>";
}
TString OutputHLSL::textureString(const TType &type)
{
switch (type.getBasicType())
{
case EbtSampler2D:
return "Texture2D";
case EbtSamplerCube:
return "TextureCube";
case EbtSamplerExternalOES:
return "Texture2D";
default:
break;
}
UNREACHABLE();
return "<unknown texture type>";
}
TString OutputHLSL::arrayString(const TType &type)
{
if (!type.isArray())
{
return "";
}
return "[" + str(type.getArraySize()) + "]";
}
TString OutputHLSL::initializer(const TType &type)
{
TString string;
size_t size = type.getObjectSize();
for (size_t component = 0; component < size; component++)
{
string += "0";
if (component + 1 < size)
{
string += ", ";
}
}
return "{" + string + "}";
}
void OutputHLSL::addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters)
{
if (name == "")
{
return; // Nameless structures don't have constructors
}
if (type.getStruct() && mStructNames.find(decorate(name)) != mStructNames.end())
{
return; // Already added
}
TType ctorType = type;
ctorType.clearArrayness();
ctorType.setPrecision(EbpHigh);
ctorType.setQualifier(EvqTemporary);
TString ctorName = type.getStruct() ? decorate(name) : name;
typedef std::vector<TType> ParameterArray;
ParameterArray ctorParameters;
if (type.getStruct())
{
mStructNames.insert(decorate(name));
TString structure;
structure += "struct " + decorate(name) + "\n"
"{\n";
const TTypeList &fields = *type.getStruct();
for (unsigned int i = 0; i < fields.size(); i++)
{
const TType &field = *fields[i];
structure += " " + typeString(field) + " " + decorateField(field.getFieldName(), type) + arrayString(field) + ";\n";
}
structure += "};\n";
if (std::find(mStructDeclarations.begin(), mStructDeclarations.end(), structure) == mStructDeclarations.end())
{
mStructDeclarations.push_back(structure);
}
for (unsigned int i = 0; i < fields.size(); i++)
{
ctorParameters.push_back(*fields[i]);
}
}
else if (parameters)
{
for (TIntermSequence::const_iterator parameter = parameters->begin(); parameter != parameters->end(); parameter++)
{
ctorParameters.push_back((*parameter)->getAsTyped()->getType());
}
}
else UNREACHABLE();
TString constructor;
if (ctorType.getStruct())
{
constructor += ctorName + " " + ctorName + "_ctor(";
}
else // Built-in type
{
constructor += typeString(ctorType) + " " + ctorName + "(";
}
for (unsigned int parameter = 0; parameter < ctorParameters.size(); parameter++)
{
const TType &type = ctorParameters[parameter];
constructor += typeString(type) + " x" + str(parameter) + arrayString(type);
if (parameter < ctorParameters.size() - 1)
{
constructor += ", ";
}
}
constructor += ")\n"
"{\n";
if (ctorType.getStruct())
{
constructor += " " + ctorName + " structure = {";
}
else
{
constructor += " return " + typeString(ctorType) + "(";
}
if (ctorType.isMatrix() && ctorParameters.size() == 1)
{
int dim = ctorType.getNominalSize();
const TType ¶meter = ctorParameters[0];
if (parameter.isScalar())
{
for (int row = 0; row < dim; row++)
{
for (int col = 0; col < dim; col++)
{
constructor += TString((row == col) ? "x0" : "0.0");
if (row < dim - 1 || col < dim - 1)
{
constructor += ", ";
}
}
}
}
else if (parameter.isMatrix())
{
for (int row = 0; row < dim; row++)
{
for (int col = 0; col < dim; col++)
{
if (row < parameter.getNominalSize() && col < parameter.getNominalSize())
{
constructor += TString("x0") + "[" + str(row) + "]" + "[" + str(col) + "]";
}
else
{
constructor += TString((row == col) ? "1.0" : "0.0");
}
if (row < dim - 1 || col < dim - 1)
{
constructor += ", ";
}
}
}
}
else UNREACHABLE();
}
else
{
size_t remainingComponents = ctorType.getObjectSize();
size_t parameterIndex = 0;
while (remainingComponents > 0)
{
const TType ¶meter = ctorParameters[parameterIndex];
const size_t parameterSize = parameter.getObjectSize();
bool moreParameters = parameterIndex + 1 < ctorParameters.size();
constructor += "x" + str(parameterIndex);
if (parameter.isScalar())
{
ASSERT(parameterSize <= remainingComponents);
remainingComponents -= parameterSize;
}
else if (parameter.isVector())
{
if (remainingComponents == parameterSize || moreParameters)
{
ASSERT(parameterSize <= remainingComponents);
remainingComponents -= parameterSize;
}
else if (remainingComponents < static_cast<size_t>(parameter.getNominalSize()))
{
switch (remainingComponents)
{
case 1: constructor += ".x"; break;
case 2: constructor += ".xy"; break;
case 3: constructor += ".xyz"; break;
case 4: constructor += ".xyzw"; break;
default: UNREACHABLE();
}
remainingComponents = 0;
}
else UNREACHABLE();
}
else if (parameter.isMatrix() || parameter.getStruct())
{
ASSERT(remainingComponents == parameterSize || moreParameters);
ASSERT(parameterSize <= remainingComponents);
remainingComponents -= parameterSize;
}
else UNREACHABLE();
if (moreParameters)
{
parameterIndex++;
}
if (remainingComponents)
{
constructor += ", ";
}
}
}
if (ctorType.getStruct())
{
constructor += "};\n"
" return structure;\n"
"}\n";
}
else
{
constructor += ");\n"
"}\n";
}
mConstructors.insert(constructor);
}
const ConstantUnion *OutputHLSL::writeConstantUnion(const TType &type, const ConstantUnion *constUnion)
{
TInfoSinkBase &out = mBody;
if (type.getBasicType() == EbtStruct)
{
out << structLookup(type.getTypeName()) + "_ctor(";
const TTypeList *structure = type.getStruct();
for (size_t i = 0; i < structure->size(); i++)
{
const TType *fieldType = (*structure)[i];
constUnion = writeConstantUnion(*fieldType, constUnion);
if (i != structure->size() - 1)
{
out << ", ";
}
}
out << ")";
}
else
{
size_t size = type.getObjectSize();
bool writeType = size > 1;
if (writeType)
{
out << typeString(type) << "(";
}
for (size_t i = 0; i < size; i++, constUnion++)
{
switch (constUnion->getType())
{
case EbtFloat: out << std::min(FLT_MAX, std::max(-FLT_MAX, constUnion->getFConst())); break;
case EbtInt: out << constUnion->getIConst(); break;
case EbtBool: out << constUnion->getBConst(); break;
default: UNREACHABLE();
}
if (i != size - 1)
{
out << ", ";
}
}
if (writeType)
{
out << ")";
}
}
return constUnion;
}
TString OutputHLSL::scopeString(unsigned int depthLimit)
{
TString string;
for (unsigned int i = 0; i < mScopeBracket.size() && i < depthLimit; i++)
{
string += "_" + str(i);
}
return string;
}
TString OutputHLSL::scopedStruct(const TString &typeName)
{
if (typeName == "")
{
return typeName;
}
return typeName + scopeString(mScopeDepth);
}
TString OutputHLSL::structLookup(const TString &typeName)
{
for (int depth = mScopeDepth; depth >= 0; depth--)
{
TString scopedName = decorate(typeName + scopeString(depth));
for (StructNames::iterator structName = mStructNames.begin(); structName != mStructNames.end(); structName++)
{
if (*structName == scopedName)
{
return scopedName;
}
}
}
UNREACHABLE(); // Should have found a matching constructor
return typeName;
}
TString OutputHLSL::decorate(const TString &string)
{
if (string.compare(0, 3, "gl_") != 0 && string.compare(0, 3, "dx_") != 0)
{
return "_" + string;
}
return string;
}
TString OutputHLSL::decorateUniform(const TString &string, const TType &type)
{
if (type.getBasicType() == EbtSamplerExternalOES)
{
return "ex_" + string;
}
return decorate(string);
}
TString OutputHLSL::decorateField(const TString &string, const TType &structure)
{
if (structure.getTypeName().compare(0, 3, "gl_") != 0)
{
return decorate(string);
}
return string;
}
TString OutputHLSL::registerString(TIntermSymbol *operand)
{
ASSERT(operand->getQualifier() == EvqUniform);
if (IsSampler(operand->getBasicType()))
{
return "s" + str(samplerRegister(operand));
}
return "c" + str(uniformRegister(operand));
}
int OutputHLSL::samplerRegister(TIntermSymbol *sampler)
{
const TType &type = sampler->getType();
ASSERT(IsSampler(type.getBasicType()));
int index = mSamplerRegister;
mSamplerRegister += sampler->totalRegisterCount();
declareUniform(type, sampler->getSymbol(), index);
return index;
}
int OutputHLSL::uniformRegister(TIntermSymbol *uniform)
{
const TType &type = uniform->getType();
ASSERT(!IsSampler(type.getBasicType()));
int index = mUniformRegister;
mUniformRegister += uniform->totalRegisterCount();
declareUniform(type, uniform->getSymbol(), index);
return index;
}
void OutputHLSL::declareUniform(const TType &type, const TString &name, int index)
{
const TTypeList *structure = type.getStruct();
if (!structure)
{
mActiveUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(), index));
}
else
{
if (type.isArray())
{
int elementIndex = index;
for (int i = 0; i < type.getArraySize(); i++)
{
for (size_t j = 0; j < structure->size(); j++)
{
const TType &fieldType = *(*structure)[j];
const TString &fieldName = fieldType.getFieldName();
const TString uniformName = name + "[" + str(i) + "]." + fieldName;
declareUniform(fieldType, uniformName, elementIndex);
elementIndex += fieldType.totalRegisterCount();
}
}
}
else
{
int fieldIndex = index;
for (size_t i = 0; i < structure->size(); i++)
{
const TType &fieldType = *(*structure)[i];
const TString &fieldName = fieldType.getFieldName();
const TString uniformName = name + "." + fieldName;
declareUniform(fieldType, uniformName, fieldIndex);
fieldIndex += fieldType.totalRegisterCount();
}
}
}
}
GLenum OutputHLSL::glVariableType(const TType &type)
{
if (type.getBasicType() == EbtFloat)
{
if (type.isScalar())
{
return GL_FLOAT;
}
else if (type.isVector())
{
switch(type.getNominalSize())
{
case 2: return GL_FLOAT_VEC2;
case 3: return GL_FLOAT_VEC3;
case 4: return GL_FLOAT_VEC4;
default: UNREACHABLE();
}
}
else if (type.isMatrix())
{
switch(type.getNominalSize())
{
case 2: return GL_FLOAT_MAT2;
case 3: return GL_FLOAT_MAT3;
case 4: return GL_FLOAT_MAT4;
default: UNREACHABLE();
}
}
else UNREACHABLE();
}
else if (type.getBasicType() == EbtInt)
{
if (type.isScalar())
{
return GL_INT;
}
else if (type.isVector())
{
switch(type.getNominalSize())
{
case 2: return GL_INT_VEC2;
case 3: return GL_INT_VEC3;
case 4: return GL_INT_VEC4;
default: UNREACHABLE();
}
}
else UNREACHABLE();
}
else if (type.getBasicType() == EbtBool)
{
if (type.isScalar())
{
return GL_BOOL;
}
else if (type.isVector())
{
switch(type.getNominalSize())
{
case 2: return GL_BOOL_VEC2;
case 3: return GL_BOOL_VEC3;
case 4: return GL_BOOL_VEC4;
default: UNREACHABLE();
}
}
else UNREACHABLE();
}
else if (type.getBasicType() == EbtSampler2D)
{
return GL_SAMPLER_2D;
}
else if (type.getBasicType() == EbtSamplerCube)
{
return GL_SAMPLER_CUBE;
}
else UNREACHABLE();
return GL_NONE;
}
GLenum OutputHLSL::glVariablePrecision(const TType &type)
{
if (type.getBasicType() == EbtFloat)
{
switch (type.getPrecision())
{
case EbpHigh: return GL_HIGH_FLOAT;
case EbpMedium: return GL_MEDIUM_FLOAT;
case EbpLow: return GL_LOW_FLOAT;
case EbpUndefined:
// Should be defined as the default precision by the parser
default: UNREACHABLE();
}
}
else if (type.getBasicType() == EbtInt)
{
switch (type.getPrecision())
{
case EbpHigh: return GL_HIGH_INT;
case EbpMedium: return GL_MEDIUM_INT;
case EbpLow: return GL_LOW_INT;
case EbpUndefined:
// Should be defined as the default precision by the parser
default: UNREACHABLE();
}
}
// Other types (boolean, sampler) don't have a precision
return GL_NONE;
}
}
| C++ |
//
// Copyright (c) 2002-2011 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_VARIABLE_INFO_H_
#define COMPILER_VARIABLE_INFO_H_
#include "GLSLANG/ShaderLang.h"
#include "compiler/intermediate.h"
// Provides information about a variable.
// It is currently being used to store info about active attribs and uniforms.
struct TVariableInfo {
TVariableInfo(ShDataType type, int size);
TVariableInfo();
TPersistString name;
TPersistString mappedName;
ShDataType type;
int size;
};
typedef std::vector<TVariableInfo> TVariableInfoList;
// Traverses intermediate tree to collect all attributes and uniforms.
class CollectAttribsUniforms : public TIntermTraverser {
public:
CollectAttribsUniforms(TVariableInfoList& attribs,
TVariableInfoList& uniforms,
ShHashFunction64 hashFunction);
virtual void visitSymbol(TIntermSymbol*);
virtual void visitConstantUnion(TIntermConstantUnion*);
virtual bool visitBinary(Visit, TIntermBinary*);
virtual bool visitUnary(Visit, TIntermUnary*);
virtual bool visitSelection(Visit, TIntermSelection*);
virtual bool visitAggregate(Visit, TIntermAggregate*);
virtual bool visitLoop(Visit, TIntermLoop*);
virtual bool visitBranch(Visit, TIntermBranch*);
private:
TVariableInfoList& mAttribs;
TVariableInfoList& mUniforms;
ShHashFunction64 mHashFunction;
};
#endif // COMPILER_VARIABLE_INFO_H_
| C++ |
//
// 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.
//
#include "GLSLANG/ShaderLang.h"
#include "compiler/intermediate.h"
class TInfoSinkBase;
struct TLoopInfo {
struct TIndex {
int id; // symbol id.
} index;
TIntermLoop* loop;
};
typedef TVector<TLoopInfo> TLoopStack;
// Traverses intermediate tree to ensure that the shader does not exceed the
// minimum functionality mandated in GLSL 1.0 spec, Appendix A.
class ValidateLimitations : public TIntermTraverser {
public:
ValidateLimitations(ShShaderType shaderType, TInfoSinkBase& sink);
int numErrors() const { return mNumErrors; }
virtual bool visitBinary(Visit, TIntermBinary*);
virtual bool visitUnary(Visit, TIntermUnary*);
virtual bool visitAggregate(Visit, TIntermAggregate*);
virtual bool visitLoop(Visit, TIntermLoop*);
private:
void error(TSourceLoc loc, const char *reason, const char* token);
bool withinLoopBody() const;
bool isLoopIndex(const TIntermSymbol* symbol) const;
bool validateLoopType(TIntermLoop* node);
bool validateForLoopHeader(TIntermLoop* node, TLoopInfo* info);
bool validateForLoopInit(TIntermLoop* node, TLoopInfo* info);
bool validateForLoopCond(TIntermLoop* node, TLoopInfo* info);
bool validateForLoopExpr(TIntermLoop* node, TLoopInfo* info);
// Returns true if none of the loop indices is used as the argument to
// the given function out or inout parameter.
bool validateFunctionCall(TIntermAggregate* node);
bool validateOperation(TIntermOperator* node, TIntermNode* operand);
// Returns true if indexing does not exceed the minimum functionality
// mandated in GLSL 1.0 spec, Appendix A, Section 5.
bool isConstExpr(TIntermNode* node);
bool isConstIndexExpr(TIntermNode* node);
bool validateIndexing(TIntermBinary* node);
ShShaderType mShaderType;
TInfoSinkBase& mSink;
int mNumErrors;
TLoopStack mLoopStack;
};
| C++ |
//
// 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.
//
#ifndef _MMAP_INCLUDED_
#define _MMAP_INCLUDED_
//
// Encapsulate memory mapped files
//
class TMMap {
public:
TMMap(const char* fileName) :
fSize(-1), // -1 is the error value returned by GetFileSize()
fp(NULL),
fBuff(0) // 0 is the error value returned by MapViewOfFile()
{
if ((fp = fopen(fileName, "r")) == NULL)
return;
char c = getc(fp);
fSize = 0;
while (c != EOF) {
fSize++;
c = getc(fp);
}
if (c == EOF)
fSize++;
rewind(fp);
fBuff = (char*)malloc(sizeof(char) * fSize);
int count = 0;
c = getc(fp);
while (c != EOF) {
fBuff[count++] = c;
c = getc(fp);
}
fBuff[count++] = c;
}
char* getData() { return fBuff; }
int getSize() { return fSize; }
~TMMap() {
if (fp != NULL)
fclose(fp);
}
private:
int fSize; // size of file to map in
FILE *fp;
char* fBuff; // the actual data;
};
#endif // _MMAP_INCLUDED_
| C++ |
//
// Copyright (c) 2002-2011 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 CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
#define CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
#include <set>
#include "compiler/ForLoopUnroll.h"
#include "compiler/intermediate.h"
#include "compiler/ParseHelper.h"
class TOutputGLSLBase : public TIntermTraverser
{
public:
TOutputGLSLBase(TInfoSinkBase& objSink,
ShArrayIndexClampingStrategy clampingStrategy,
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable);
protected:
TInfoSinkBase& objSink() { return mObjSink; }
void writeTriplet(Visit visit, const char* preStr, const char* inStr, const char* postStr);
void writeVariableType(const TType& type);
virtual bool writeVariablePrecision(TPrecision precision) = 0;
void writeFunctionParameters(const TIntermSequence& args);
const ConstantUnion* writeConstantUnion(const TType& type, const ConstantUnion* pConstUnion);
TString getTypeName(const TType& type);
virtual void visitSymbol(TIntermSymbol* node);
virtual void visitConstantUnion(TIntermConstantUnion* node);
virtual bool visitBinary(Visit visit, TIntermBinary* node);
virtual bool visitUnary(Visit visit, TIntermUnary* node);
virtual bool visitSelection(Visit visit, TIntermSelection* node);
virtual bool visitAggregate(Visit visit, TIntermAggregate* node);
virtual bool visitLoop(Visit visit, TIntermLoop* node);
virtual bool visitBranch(Visit visit, TIntermBranch* node);
void visitCodeBlock(TIntermNode* node);
// Return the original name if hash function pointer is NULL;
// otherwise return the hashed name.
TString hashName(const TString& name);
// Same as hashName(), but without hashing built-in variables.
TString hashVariableName(const TString& name);
// Same as hashName(), but without hashing built-in functions.
TString hashFunctionName(const TString& mangled_name);
private:
TInfoSinkBase& mObjSink;
bool mDeclaringVariables;
// Structs are declared as the tree is traversed. This set contains all
// the structs already declared. It is maintained so that a struct is
// declared only once.
typedef std::set<TString> DeclaredStructs;
DeclaredStructs mDeclaredStructs;
ForLoopUnroll mLoopUnroll;
ShArrayIndexClampingStrategy mClampingStrategy;
// name hashing.
ShHashFunction64 mHashFunction;
NameMap& mNameMap;
TSymbolTable& mSymbolTable;
};
#endif // CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
| C++ |
//
// 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.
//
#include "compiler/intermediate.h"
#include "compiler/RemoveTree.h"
//
// Code to recursively delete the intermediate tree.
//
class RemoveTree : public TIntermTraverser
{
public:
RemoveTree() : TIntermTraverser(false, false, true)
{
}
protected:
void visitSymbol(TIntermSymbol*);
void visitConstantUnion(TIntermConstantUnion*);
bool visitBinary(Visit visit, TIntermBinary*);
bool visitUnary(Visit visit, TIntermUnary*);
bool visitSelection(Visit visit, TIntermSelection*);
bool visitAggregate(Visit visit, TIntermAggregate*);
};
void RemoveTree::visitSymbol(TIntermSymbol* node)
{
delete node;
}
bool RemoveTree::visitBinary(Visit visit, TIntermBinary* node)
{
delete node;
return true;
}
bool RemoveTree::visitUnary(Visit visit, TIntermUnary* node)
{
delete node;
return true;
}
bool RemoveTree::visitAggregate(Visit visit, TIntermAggregate* node)
{
delete node;
return true;
}
bool RemoveTree::visitSelection(Visit visit, TIntermSelection* node)
{
delete node;
return true;
}
void RemoveTree::visitConstantUnion(TIntermConstantUnion* node)
{
delete node;
}
//
// Entry point.
//
void RemoveAllTreeNodes(TIntermNode* root)
{
RemoveTree it;
root->traverse(&it);
}
| C++ |
//
// 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.
//
#include "compiler/TranslatorGLSL.h"
#include "compiler/OutputGLSL.h"
#include "compiler/VersionGLSL.h"
static void writeVersion(ShShaderType type, TIntermNode* root,
TInfoSinkBase& sink) {
TVersionGLSL versionGLSL(type);
root->traverse(&versionGLSL);
int version = versionGLSL.getVersion();
// We need to write version directive only if it is greater than 110.
// If there is no version directive in the shader, 110 is implied.
if (version > 110) {
sink << "#version " << version << "\n";
}
}
TranslatorGLSL::TranslatorGLSL(ShShaderType type, ShShaderSpec spec)
: TCompiler(type, spec) {
}
void TranslatorGLSL::translate(TIntermNode* root) {
TInfoSinkBase& sink = getInfoSink().obj;
// Write GLSL version.
writeVersion(getShaderType(), root, sink);
// Write emulated built-in functions if needed.
getBuiltInFunctionEmulator().OutputEmulatedFunctionDefinition(
sink, false);
// Write array bounds clamping emulation if needed.
getArrayBoundsClamper().OutputClampingFunctionDefinition(sink);
// Write translated shader.
TOutputGLSL outputGLSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable());
root->traverse(&outputGLSL);
}
| C++ |
//
// 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.
//
//
// Implement the top-level of interface to the compiler,
// as defined in ShaderLang.h
//
#include "GLSLANG/ShaderLang.h"
#include "compiler/InitializeDll.h"
#include "compiler/preprocessor/length_limits.h"
#include "compiler/ShHandle.h"
#include "compiler/TranslatorHLSL.h"
//
// This is the platform independent interface between an OGL driver
// and the shading language compiler.
//
static bool checkActiveUniformAndAttribMaxLengths(const ShHandle handle,
size_t expectedValue)
{
size_t activeUniformLimit = 0;
ShGetInfo(handle, SH_ACTIVE_UNIFORM_MAX_LENGTH, &activeUniformLimit);
size_t activeAttribLimit = 0;
ShGetInfo(handle, SH_ACTIVE_ATTRIBUTE_MAX_LENGTH, &activeAttribLimit);
return (expectedValue == activeUniformLimit && expectedValue == activeAttribLimit);
}
static bool checkMappedNameMaxLength(const ShHandle handle, size_t expectedValue)
{
size_t mappedNameMaxLength = 0;
ShGetInfo(handle, SH_MAPPED_NAME_MAX_LENGTH, &mappedNameMaxLength);
return (expectedValue == mappedNameMaxLength);
}
static void getVariableInfo(ShShaderInfo varType,
const ShHandle handle,
int index,
size_t* length,
int* size,
ShDataType* type,
char* name,
char* mappedName)
{
if (!handle || !size || !type || !name)
return;
ASSERT((varType == SH_ACTIVE_ATTRIBUTES) ||
(varType == SH_ACTIVE_UNIFORMS));
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (compiler == 0)
return;
const TVariableInfoList& varList = varType == SH_ACTIVE_ATTRIBUTES ?
compiler->getAttribs() : compiler->getUniforms();
if (index < 0 || index >= static_cast<int>(varList.size()))
return;
const TVariableInfo& varInfo = varList[index];
if (length) *length = varInfo.name.size();
*size = varInfo.size;
*type = varInfo.type;
// This size must match that queried by
// SH_ACTIVE_UNIFORM_MAX_LENGTH and SH_ACTIVE_ATTRIBUTE_MAX_LENGTH
// in ShGetInfo, below.
size_t activeUniformAndAttribLength = 1 + MAX_SYMBOL_NAME_LEN;
ASSERT(checkActiveUniformAndAttribMaxLengths(handle, activeUniformAndAttribLength));
strncpy(name, varInfo.name.c_str(), activeUniformAndAttribLength);
name[activeUniformAndAttribLength - 1] = 0;
if (mappedName) {
// This size must match that queried by
// SH_MAPPED_NAME_MAX_LENGTH in ShGetInfo, below.
size_t maxMappedNameLength = 1 + MAX_SYMBOL_NAME_LEN;
ASSERT(checkMappedNameMaxLength(handle, maxMappedNameLength));
strncpy(mappedName, varInfo.mappedName.c_str(), maxMappedNameLength);
mappedName[maxMappedNameLength - 1] = 0;
}
}
//
// Driver must call this first, once, before doing any other
// compiler operations.
//
int ShInitialize()
{
if (!InitProcess())
return 0;
return 1;
}
//
// Cleanup symbol tables
//
int ShFinalize()
{
if (!DetachProcess())
return 0;
return 1;
}
//
// Initialize built-in resources with minimum expected values.
//
void ShInitBuiltInResources(ShBuiltInResources* resources)
{
// Constants.
resources->MaxVertexAttribs = 8;
resources->MaxVertexUniformVectors = 128;
resources->MaxVaryingVectors = 8;
resources->MaxVertexTextureImageUnits = 0;
resources->MaxCombinedTextureImageUnits = 8;
resources->MaxTextureImageUnits = 8;
resources->MaxFragmentUniformVectors = 16;
resources->MaxDrawBuffers = 1;
// Extensions.
resources->OES_standard_derivatives = 0;
resources->OES_EGL_image_external = 0;
resources->ARB_texture_rectangle = 0;
resources->EXT_draw_buffers = 0;
resources->EXT_frag_depth = 0;
// Disable highp precision in fragment shader by default.
resources->FragmentPrecisionHigh = 0;
// Disable name hashing by default.
resources->HashFunction = NULL;
resources->ArrayIndexClampingStrategy = SH_CLAMP_WITH_CLAMP_INTRINSIC;
}
//
// Driver calls these to create and destroy compiler objects.
//
ShHandle ShConstructCompiler(ShShaderType type, ShShaderSpec spec,
ShShaderOutput output,
const ShBuiltInResources* resources)
{
if (!InitThread())
return 0;
TShHandleBase* base = static_cast<TShHandleBase*>(ConstructCompiler(type, spec, output));
TCompiler* compiler = base->getAsCompiler();
if (compiler == 0)
return 0;
// Generate built-in symbol table.
if (!compiler->Init(*resources)) {
ShDestruct(base);
return 0;
}
return reinterpret_cast<void*>(base);
}
void ShDestruct(ShHandle handle)
{
if (handle == 0)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
if (base->getAsCompiler())
DeleteCompiler(base->getAsCompiler());
}
//
// Do an actual compile on the given strings. The result is left
// in the given compile object.
//
// Return: The return value of ShCompile is really boolean, indicating
// success or failure.
//
int ShCompile(
const ShHandle handle,
const char* const shaderStrings[],
size_t numStrings,
int compileOptions)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (compiler == 0)
return 0;
bool success = compiler->compile(shaderStrings, numStrings, compileOptions);
return success ? 1 : 0;
}
void ShGetInfo(const ShHandle handle, ShShaderInfo pname, size_t* params)
{
if (!handle || !params)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (!compiler) return;
switch(pname)
{
case SH_INFO_LOG_LENGTH:
*params = compiler->getInfoSink().info.size() + 1;
break;
case SH_OBJECT_CODE_LENGTH:
*params = compiler->getInfoSink().obj.size() + 1;
break;
case SH_ACTIVE_UNIFORMS:
*params = compiler->getUniforms().size();
break;
case SH_ACTIVE_UNIFORM_MAX_LENGTH:
*params = 1 + MAX_SYMBOL_NAME_LEN;
break;
case SH_ACTIVE_ATTRIBUTES:
*params = compiler->getAttribs().size();
break;
case SH_ACTIVE_ATTRIBUTE_MAX_LENGTH:
*params = 1 + MAX_SYMBOL_NAME_LEN;
break;
case SH_MAPPED_NAME_MAX_LENGTH:
// Use longer length than MAX_SHORTENED_IDENTIFIER_SIZE to
// handle array and struct dereferences.
*params = 1 + MAX_SYMBOL_NAME_LEN;
break;
case SH_NAME_MAX_LENGTH:
*params = 1 + MAX_SYMBOL_NAME_LEN;
break;
case SH_HASHED_NAME_MAX_LENGTH:
if (compiler->getHashFunction() == NULL) {
*params = 0;
} else {
// 64 bits hashing output requires 16 bytes for hex
// representation.
const char HashedNamePrefix[] = HASHED_NAME_PREFIX;
*params = 16 + sizeof(HashedNamePrefix);
}
break;
case SH_HASHED_NAMES_COUNT:
*params = compiler->getNameMap().size();
break;
default: UNREACHABLE();
}
}
//
// Return any compiler log of messages for the application.
//
void ShGetInfoLog(const ShHandle handle, char* infoLog)
{
if (!handle || !infoLog)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (!compiler) return;
TInfoSink& infoSink = compiler->getInfoSink();
strcpy(infoLog, infoSink.info.c_str());
}
//
// Return any object code.
//
void ShGetObjectCode(const ShHandle handle, char* objCode)
{
if (!handle || !objCode)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (!compiler) return;
TInfoSink& infoSink = compiler->getInfoSink();
strcpy(objCode, infoSink.obj.c_str());
}
void ShGetActiveAttrib(const ShHandle handle,
int index,
size_t* length,
int* size,
ShDataType* type,
char* name,
char* mappedName)
{
getVariableInfo(SH_ACTIVE_ATTRIBUTES,
handle, index, length, size, type, name, mappedName);
}
void ShGetActiveUniform(const ShHandle handle,
int index,
size_t* length,
int* size,
ShDataType* type,
char* name,
char* mappedName)
{
getVariableInfo(SH_ACTIVE_UNIFORMS,
handle, index, length, size, type, name, mappedName);
}
void ShGetNameHashingEntry(const ShHandle handle,
int index,
char* name,
char* hashedName)
{
if (!handle || !name || !hashedName || index < 0)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (!compiler) return;
const NameMap& nameMap = compiler->getNameMap();
if (index >= static_cast<int>(nameMap.size()))
return;
NameMap::const_iterator it = nameMap.begin();
for (int i = 0; i < index; ++i)
++it;
size_t len = it->first.length() + 1;
size_t max_len = 0;
ShGetInfo(handle, SH_NAME_MAX_LENGTH, &max_len);
if (len > max_len) {
ASSERT(false);
len = max_len;
}
strncpy(name, it->first.c_str(), len);
// To be on the safe side in case the source is longer than expected.
name[len - 1] = '\0';
len = it->second.length() + 1;
max_len = 0;
ShGetInfo(handle, SH_HASHED_NAME_MAX_LENGTH, &max_len);
if (len > max_len) {
ASSERT(false);
len = max_len;
}
strncpy(hashedName, it->second.c_str(), len);
// To be on the safe side in case the source is longer than expected.
hashedName[len - 1] = '\0';
}
void ShGetInfoPointer(const ShHandle handle, ShShaderInfo pname, void** params)
{
if (!handle || !params)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TranslatorHLSL* translator = base->getAsTranslatorHLSL();
if (!translator) return;
switch(pname)
{
case SH_ACTIVE_UNIFORMS_ARRAY:
*params = (void*)&translator->getUniforms();
break;
default: UNREACHABLE();
}
}
| C++ |
//
// 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.
//
#include "compiler/ParseHelper.h"
//
// Use this class to carry along data from node to node in
// the traversal
//
class TConstTraverser : public TIntermTraverser {
public:
TConstTraverser(ConstantUnion* cUnion, bool singleConstParam, TOperator constructType, TInfoSink& sink, TSymbolTable& symTable, TType& t)
: error(false),
index(0),
unionArray(cUnion),
type(t),
constructorType(constructType),
singleConstantParam(singleConstParam),
infoSink(sink),
symbolTable(symTable),
size(0),
isMatrix(false),
matrixSize(0) {
}
bool error;
protected:
void visitSymbol(TIntermSymbol*);
void visitConstantUnion(TIntermConstantUnion*);
bool visitBinary(Visit visit, TIntermBinary*);
bool visitUnary(Visit visit, TIntermUnary*);
bool visitSelection(Visit visit, TIntermSelection*);
bool visitAggregate(Visit visit, TIntermAggregate*);
bool visitLoop(Visit visit, TIntermLoop*);
bool visitBranch(Visit visit, TIntermBranch*);
size_t index;
ConstantUnion *unionArray;
TType type;
TOperator constructorType;
bool singleConstantParam;
TInfoSink& infoSink;
TSymbolTable& symbolTable;
size_t size; // size of the constructor ( 4 for vec4)
bool isMatrix;
size_t matrixSize; // dimension of the matrix (nominal size and not the instance size)
};
//
// The rest of the file are the traversal functions. The last one
// is the one that starts the traversal.
//
// Return true from interior nodes to have the external traversal
// continue on to children. If you process children yourself,
// return false.
//
void TConstTraverser::visitSymbol(TIntermSymbol* node)
{
infoSink.info.message(EPrefixInternalError, node->getLine(), "Symbol Node found in constant constructor");
return;
}
bool TConstTraverser::visitBinary(Visit visit, TIntermBinary* node)
{
TQualifier qualifier = node->getType().getQualifier();
if (qualifier != EvqConst) {
TString buf;
buf.append("'constructor' : assigning non-constant to ");
buf.append(type.getCompleteString());
infoSink.info.message(EPrefixError, node->getLine(), buf.c_str());
error = true;
return false;
}
infoSink.info.message(EPrefixInternalError, node->getLine(), "Binary Node found in constant constructor");
return false;
}
bool TConstTraverser::visitUnary(Visit visit, TIntermUnary* node)
{
TString buf;
buf.append("'constructor' : assigning non-constant to ");
buf.append(type.getCompleteString());
infoSink.info.message(EPrefixError, node->getLine(), buf.c_str());
error = true;
return false;
}
bool TConstTraverser::visitAggregate(Visit visit, TIntermAggregate* node)
{
if (!node->isConstructor() && node->getOp() != EOpComma) {
TString buf;
buf.append("'constructor' : assigning non-constant to ");
buf.append(type.getCompleteString());
infoSink.info.message(EPrefixError, node->getLine(), buf.c_str());
error = true;
return false;
}
if (node->getSequence().size() == 0) {
error = true;
return false;
}
bool flag = node->getSequence().size() == 1 && node->getSequence()[0]->getAsTyped()->getAsConstantUnion();
if (flag)
{
singleConstantParam = true;
constructorType = node->getOp();
size = node->getType().getObjectSize();
if (node->getType().isMatrix()) {
isMatrix = true;
matrixSize = node->getType().getNominalSize();
}
}
for (TIntermSequence::iterator p = node->getSequence().begin();
p != node->getSequence().end(); p++) {
if (node->getOp() == EOpComma)
index = 0;
(*p)->traverse(this);
}
if (flag)
{
singleConstantParam = false;
constructorType = EOpNull;
size = 0;
isMatrix = false;
matrixSize = 0;
}
return false;
}
bool TConstTraverser::visitSelection(Visit visit, TIntermSelection* node)
{
infoSink.info.message(EPrefixInternalError, node->getLine(), "Selection Node found in constant constructor");
error = true;
return false;
}
void TConstTraverser::visitConstantUnion(TIntermConstantUnion* node)
{
if (!node->getUnionArrayPointer())
{
// The constant was not initialized, this should already have been logged
assert(infoSink.info.size() != 0);
return;
}
ConstantUnion* leftUnionArray = unionArray;
size_t instanceSize = type.getObjectSize();
if (index >= instanceSize)
return;
if (!singleConstantParam) {
size_t size = node->getType().getObjectSize();
ConstantUnion *rightUnionArray = node->getUnionArrayPointer();
for (size_t i = 0; i < size; i++) {
if (index >= instanceSize)
return;
leftUnionArray[index] = rightUnionArray[i];
(index)++;
}
} else {
size_t totalSize = index + size;
ConstantUnion *rightUnionArray = node->getUnionArrayPointer();
if (!isMatrix) {
size_t count = 0;
for (size_t i = index; i < totalSize; i++) {
if (i >= instanceSize)
return;
leftUnionArray[i] = rightUnionArray[count];
(index)++;
if (node->getType().getObjectSize() > 1)
count++;
}
} else { // for matrix constructors
size_t count = 0;
size_t element = index;
for (size_t i = index; i < totalSize; i++) {
if (i >= instanceSize)
return;
if (element - i == 0 || (i - element) % (matrixSize + 1) == 0 )
leftUnionArray[i] = rightUnionArray[count];
else
leftUnionArray[i].setFConst(0.0f);
(index)++;
if (node->getType().getObjectSize() > 1)
count++;
}
}
}
}
bool TConstTraverser::visitLoop(Visit visit, TIntermLoop* node)
{
infoSink.info.message(EPrefixInternalError, node->getLine(), "Loop Node found in constant constructor");
error = true;
return false;
}
bool TConstTraverser::visitBranch(Visit visit, TIntermBranch* node)
{
infoSink.info.message(EPrefixInternalError, node->getLine(), "Branch Node found in constant constructor");
error = true;
return false;
}
//
// This function is the one to call externally to start the traversal.
// Individual functions can be initialized to 0 to skip processing of that
// type of node. It's children will still be processed.
//
bool TIntermediate::parseConstTree(const TSourceLoc& line, TIntermNode* root, ConstantUnion* unionArray, TOperator constructorType, TSymbolTable& symbolTable, TType t, bool singleConstantParam)
{
if (root == 0)
return false;
TConstTraverser it(unionArray, singleConstantParam, constructorType, infoSink, symbolTable, t);
root->traverse(&it);
if (it.error)
return true;
else
return false;
}
| C++ |
//
// 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 "compiler/TranslatorHLSL.h"
//
// This function must be provided to create the actual
// compile object used by higher level code. It returns
// a subclass of TCompiler.
//
TCompiler* ConstructCompiler(
ShShaderType type, ShShaderSpec spec, ShShaderOutput output)
{
switch (output)
{
case SH_HLSL9_OUTPUT:
case SH_HLSL11_OUTPUT:
return new TranslatorHLSL(type, spec, output);
default:
return NULL;
}
}
//
// Delete the compiler made by ConstructCompiler
//
void DeleteCompiler(TCompiler* compiler)
{
delete compiler;
}
| C++ |
//
// 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.
//
#include "compiler/PoolAlloc.h"
#ifndef _MSC_VER
#include <stdint.h>
#endif
#include <stdio.h>
#include "common/angleutils.h"
#include "compiler/InitializeGlobals.h"
#include "compiler/osinclude.h"
OS_TLSIndex PoolIndex = OS_INVALID_TLS_INDEX;
void InitializeGlobalPools()
{
TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
if (globalPools)
return;
TThreadGlobalPools* threadData = new TThreadGlobalPools();
threadData->globalPoolAllocator = 0;
OS_SetTLSValue(PoolIndex, threadData);
}
void FreeGlobalPools()
{
// Release the allocated memory for this thread.
TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
if (!globalPools)
return;
delete globalPools;
}
bool InitializePoolIndex()
{
// Allocate a TLS index.
if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)
return false;
return true;
}
void FreePoolIndex()
{
// Release the TLS index.
OS_FreeTLSIndex(PoolIndex);
}
TPoolAllocator& GetGlobalPoolAllocator()
{
TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
return *threadData->globalPoolAllocator;
}
void SetGlobalPoolAllocator(TPoolAllocator* poolAllocator)
{
TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
threadData->globalPoolAllocator = poolAllocator;
}
//
// Implement the functionality of the TPoolAllocator class, which
// is documented in PoolAlloc.h.
//
TPoolAllocator::TPoolAllocator(int growthIncrement, int allocationAlignment) :
pageSize(growthIncrement),
alignment(allocationAlignment),
freeList(0),
inUseList(0),
numCalls(0),
totalBytes(0)
{
//
// Don't allow page sizes we know are smaller than all common
// OS page sizes.
//
if (pageSize < 4*1024)
pageSize = 4*1024;
//
// A large currentPageOffset indicates a new page needs to
// be obtained to allocate memory.
//
currentPageOffset = pageSize;
//
// Adjust alignment to be at least pointer aligned and
// power of 2.
//
size_t minAlign = sizeof(void*);
alignment &= ~(minAlign - 1);
if (alignment < minAlign)
alignment = minAlign;
size_t a = 1;
while (a < alignment)
a <<= 1;
alignment = a;
alignmentMask = a - 1;
//
// Align header skip
//
headerSkip = minAlign;
if (headerSkip < sizeof(tHeader)) {
headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;
}
}
TPoolAllocator::~TPoolAllocator()
{
while (inUseList) {
tHeader* next = inUseList->nextPage;
inUseList->~tHeader();
delete [] reinterpret_cast<char*>(inUseList);
inUseList = next;
}
// We should not check the guard blocks
// here, because we did it already when the block was
// placed into the free list.
//
while (freeList) {
tHeader* next = freeList->nextPage;
delete [] reinterpret_cast<char*>(freeList);
freeList = next;
}
}
// Support MSVC++ 6.0
const unsigned char TAllocation::guardBlockBeginVal = 0xfb;
const unsigned char TAllocation::guardBlockEndVal = 0xfe;
const unsigned char TAllocation::userDataFill = 0xcd;
#ifdef GUARD_BLOCKS
const size_t TAllocation::guardBlockSize = 16;
#else
const size_t TAllocation::guardBlockSize = 0;
#endif
//
// Check a single guard block for damage
//
void TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const
{
#ifdef GUARD_BLOCKS
for (size_t x = 0; x < guardBlockSize; x++) {
if (blockMem[x] != val) {
char assertMsg[80];
// We don't print the assert message. It's here just to be helpful.
#if defined(_MSC_VER)
snprintf(assertMsg, sizeof(assertMsg), "PoolAlloc: Damage %s %Iu byte allocation at 0x%p\n",
locText, size, data());
#else
snprintf(assertMsg, sizeof(assertMsg), "PoolAlloc: Damage %s %zu byte allocation at 0x%p\n",
locText, size, data());
#endif
assert(0 && "PoolAlloc: Damage in guard block");
}
}
#endif
}
void TPoolAllocator::push()
{
tAllocState state = { currentPageOffset, inUseList };
stack.push_back(state);
//
// Indicate there is no current page to allocate from.
//
currentPageOffset = pageSize;
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred since the last push(), or since the
// last pop(), or since the object's creation.
//
// The deallocated pages are saved for future allocations.
//
void TPoolAllocator::pop()
{
if (stack.size() < 1)
return;
tHeader* page = stack.back().page;
currentPageOffset = stack.back().offset;
while (inUseList != page) {
// invoke destructor to free allocation list
inUseList->~tHeader();
tHeader* nextInUse = inUseList->nextPage;
if (inUseList->pageCount > 1)
delete [] reinterpret_cast<char*>(inUseList);
else {
inUseList->nextPage = freeList;
freeList = inUseList;
}
inUseList = nextInUse;
}
stack.pop_back();
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred.
//
void TPoolAllocator::popAll()
{
while (stack.size() > 0)
pop();
}
void* TPoolAllocator::allocate(size_t numBytes)
{
//
// Just keep some interesting statistics.
//
++numCalls;
totalBytes += numBytes;
// If we are using guard blocks, all allocations are bracketed by
// them: [guardblock][allocation][guardblock]. numBytes is how
// much memory the caller asked for. allocationSize is the total
// size including guard blocks. In release build,
// guardBlockSize=0 and this all gets optimized away.
size_t allocationSize = TAllocation::allocationSize(numBytes);
// Detect integer overflow.
if (allocationSize < numBytes)
return 0;
//
// Do the allocation, most likely case first, for efficiency.
// This step could be moved to be inline sometime.
//
if (allocationSize <= pageSize - currentPageOffset) {
//
// Safe to allocate from currentPageOffset.
//
unsigned char* memory = reinterpret_cast<unsigned char *>(inUseList) + currentPageOffset;
currentPageOffset += allocationSize;
currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;
return initializeAllocation(inUseList, memory, numBytes);
}
if (allocationSize > pageSize - headerSkip) {
//
// Do a multi-page allocation. Don't mix these with the others.
// The OS is efficient and allocating and free-ing multiple pages.
//
size_t numBytesToAlloc = allocationSize + headerSkip;
// Detect integer overflow.
if (numBytesToAlloc < allocationSize)
return 0;
tHeader* memory = reinterpret_cast<tHeader*>(::new char[numBytesToAlloc]);
if (memory == 0)
return 0;
// Use placement-new to initialize header
new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) / pageSize);
inUseList = memory;
currentPageOffset = pageSize; // make next allocation come from a new page
// No guard blocks for multi-page allocations (yet)
return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(memory) + headerSkip);
}
//
// Need a simple page to allocate from.
//
tHeader* memory;
if (freeList) {
memory = freeList;
freeList = freeList->nextPage;
} else {
memory = reinterpret_cast<tHeader*>(::new char[pageSize]);
if (memory == 0)
return 0;
}
// Use placement-new to initialize header
new(memory) tHeader(inUseList, 1);
inUseList = memory;
unsigned char* ret = reinterpret_cast<unsigned char *>(inUseList) + headerSkip;
currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;
return initializeAllocation(inUseList, ret, numBytes);
}
//
// Check all allocations in a list for damage by calling check on each.
//
void TAllocation::checkAllocList() const
{
for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)
alloc->check();
}
| C++ |
//
// Copyright (c) 2002-2011 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 CROSSCOMPILERGLSL_OUTPUTGLSL_H_
#define CROSSCOMPILERGLSL_OUTPUTGLSL_H_
#include "compiler/OutputGLSLBase.h"
class TOutputGLSL : public TOutputGLSLBase
{
public:
TOutputGLSL(TInfoSinkBase& objSink,
ShArrayIndexClampingStrategy clampingStrategy,
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable);
protected:
virtual bool writeVariablePrecision(TPrecision);
virtual void visitSymbol(TIntermSymbol* node);
};
#endif // CROSSCOMPILERGLSL_OUTPUTGLSL_H_
| C++ |
//
// 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 COMPILER_DIAGNOSTICS_H_
#define COMPILER_DIAGNOSTICS_H_
#include "compiler/preprocessor/DiagnosticsBase.h"
class TInfoSink;
class TDiagnostics : public pp::Diagnostics
{
public:
TDiagnostics(TInfoSink& infoSink);
virtual ~TDiagnostics();
TInfoSink& infoSink() { return mInfoSink; }
int numErrors() const { return mNumErrors; }
int numWarnings() const { return mNumWarnings; }
void writeInfo(Severity severity,
const pp::SourceLocation& loc,
const std::string& reason,
const std::string& token,
const std::string& extra);
void writeDebug(const std::string& str);
protected:
virtual void print(ID id,
const pp::SourceLocation& loc,
const std::string& text);
private:
TInfoSink& mInfoSink;
int mNumErrors;
int mNumWarnings;
};
#endif // COMPILER_DIAGNOSTICS_H_
| C++ |
//
// Copyright (c) 2011 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 COMPILIER_BUILT_IN_FUNCTION_EMULATOR_H_
#define COMPILIER_BUILT_IN_FUNCTION_EMULATOR_H_
#include "GLSLANG/ShaderLang.h"
#include "compiler/InfoSink.h"
#include "compiler/intermediate.h"
//
// This class decides which built-in functions need to be replaced with the
// emulated ones.
// It's only a workaround for OpenGL driver bugs, and isn't needed in general.
//
class BuiltInFunctionEmulator {
public:
BuiltInFunctionEmulator(ShShaderType shaderType);
// Records that a function is called by the shader and might needs to be
// emulated. If the function's group is not in mFunctionGroupFilter, this
// becomes an no-op.
// Returns true if the function call needs to be replaced with an emulated
// one.
bool SetFunctionCalled(TOperator op, const TType& param);
bool SetFunctionCalled(
TOperator op, const TType& param1, const TType& param2);
// Output function emulation definition. This should be before any other
// shader source.
void OutputEmulatedFunctionDefinition(TInfoSinkBase& out, bool withPrecision) const;
void MarkBuiltInFunctionsForEmulation(TIntermNode* root);
void Cleanup();
// "name(" becomes "webgl_name_emu(".
static TString GetEmulatedFunctionName(const TString& name);
private:
//
// Built-in functions.
//
enum TBuiltInFunction {
TFunctionCos1 = 0, // float cos(float);
TFunctionCos2, // vec2 cos(vec2);
TFunctionCos3, // vec3 cos(vec3);
TFunctionCos4, // vec4 cos(vec4);
TFunctionDistance1_1, // float distance(float, float);
TFunctionDistance2_2, // vec2 distance(vec2, vec2);
TFunctionDistance3_3, // vec3 distance(vec3, vec3);
TFunctionDistance4_4, // vec4 distance(vec4, vec4);
TFunctionDot1_1, // float dot(float, float);
TFunctionDot2_2, // vec2 dot(vec2, vec2);
TFunctionDot3_3, // vec3 dot(vec3, vec3);
TFunctionDot4_4, // vec4 dot(vec4, vec4);
TFunctionLength1, // float length(float);
TFunctionLength2, // float length(vec2);
TFunctionLength3, // float length(vec3);
TFunctionLength4, // float length(vec4);
TFunctionNormalize1, // float normalize(float);
TFunctionNormalize2, // vec2 normalize(vec2);
TFunctionNormalize3, // vec3 normalize(vec3);
TFunctionNormalize4, // vec4 normalize(vec4);
TFunctionReflect1_1, // float reflect(float, float);
TFunctionReflect2_2, // vec2 reflect(vec2, vec2);
TFunctionReflect3_3, // vec3 reflect(vec3, vec3);
TFunctionReflect4_4, // vec4 reflect(vec4, vec4);
TFunctionUnknown
};
TBuiltInFunction IdentifyFunction(TOperator op, const TType& param);
TBuiltInFunction IdentifyFunction(
TOperator op, const TType& param1, const TType& param2);
bool SetFunctionCalled(TBuiltInFunction function);
std::vector<TBuiltInFunction> mFunctions;
const bool* mFunctionMask; // a boolean flag for each function.
const char** mFunctionSource;
};
#endif // COMPILIER_BUILT_IN_FUNCTION_EMULATOR_H_
| C++ |
//
// 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.
//
// UnfoldShortCircuit is an AST traverser to output short-circuiting operators as if-else statements
//
#ifndef COMPILER_UNFOLDSHORTCIRCUIT_H_
#define COMPILER_UNFOLDSHORTCIRCUIT_H_
#include "compiler/intermediate.h"
#include "compiler/ParseHelper.h"
namespace sh
{
class OutputHLSL;
class UnfoldShortCircuit : public TIntermTraverser
{
public:
UnfoldShortCircuit(TParseContext &context, OutputHLSL *outputHLSL);
void traverse(TIntermNode *node);
bool visitBinary(Visit visit, TIntermBinary*);
bool visitSelection(Visit visit, TIntermSelection *node);
bool visitLoop(Visit visit, TIntermLoop *node);
int getNextTemporaryIndex();
protected:
TParseContext &mContext;
OutputHLSL *const mOutputHLSL;
int mTemporaryIndex;
};
}
#endif // COMPILER_UNFOLDSHORTCIRCUIT_H_
| C++ |
//
// 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 COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_OUTPUT_H
#define COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_OUTPUT_H
#include "compiler/depgraph/DependencyGraph.h"
#include "compiler/InfoSink.h"
class TDependencyGraphOutput : public TDependencyGraphTraverser {
public:
TDependencyGraphOutput(TInfoSinkBase& sink) : mSink(sink) {}
virtual void visitSymbol(TGraphSymbol* symbol);
virtual void visitArgument(TGraphArgument* parameter);
virtual void visitFunctionCall(TGraphFunctionCall* functionCall);
virtual void visitSelection(TGraphSelection* selection);
virtual void visitLoop(TGraphLoop* loop);
virtual void visitLogicalOp(TGraphLogicalOp* logicalOp);
void outputAllSpanningTrees(TDependencyGraph& graph);
private:
void outputIndentation();
TInfoSinkBase& mSink;
};
#endif // COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_OUTPUT_H
| C++ |
//
// 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 "compiler/depgraph/DependencyGraphOutput.h"
void TDependencyGraphOutput::outputIndentation()
{
for (int i = 0; i < getDepth(); ++i)
mSink << " ";
}
void TDependencyGraphOutput::visitArgument(TGraphArgument* parameter)
{
outputIndentation();
mSink << "argument " << parameter->getArgumentNumber() << " of call to "
<< parameter->getIntermFunctionCall()->getName() << "\n";
}
void TDependencyGraphOutput::visitFunctionCall(TGraphFunctionCall* functionCall)
{
outputIndentation();
mSink << "function call " << functionCall->getIntermFunctionCall()->getName() << "\n";
}
void TDependencyGraphOutput::visitSymbol(TGraphSymbol* symbol)
{
outputIndentation();
mSink << symbol->getIntermSymbol()->getSymbol() << " (symbol id: "
<< symbol->getIntermSymbol()->getId() << ")\n";
}
void TDependencyGraphOutput::visitSelection(TGraphSelection* selection)
{
outputIndentation();
mSink << "selection\n";
}
void TDependencyGraphOutput::visitLoop(TGraphLoop* loop)
{
outputIndentation();
mSink << "loop condition\n";
}
void TDependencyGraphOutput::visitLogicalOp(TGraphLogicalOp* logicalOp)
{
outputIndentation();
mSink << "logical " << logicalOp->getOpString() << "\n";
}
void TDependencyGraphOutput::outputAllSpanningTrees(TDependencyGraph& graph)
{
mSink << "\n";
for (TGraphNodeVector::const_iterator iter = graph.begin(); iter != graph.end(); ++iter)
{
TGraphNode* symbol = *iter;
mSink << "--- Dependency graph spanning tree ---\n";
clearVisited();
symbol->traverse(this);
mSink << "\n";
}
}
| C++ |
//
// 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 "compiler/depgraph/DependencyGraphBuilder.h"
void TDependencyGraphBuilder::build(TIntermNode* node, TDependencyGraph* graph)
{
TDependencyGraphBuilder builder(graph);
builder.build(node);
}
bool TDependencyGraphBuilder::visitAggregate(Visit visit, TIntermAggregate* intermAggregate)
{
switch (intermAggregate->getOp()) {
case EOpFunction: visitFunctionDefinition(intermAggregate); break;
case EOpFunctionCall: visitFunctionCall(intermAggregate); break;
default: visitAggregateChildren(intermAggregate); break;
}
return false;
}
void TDependencyGraphBuilder::visitFunctionDefinition(TIntermAggregate* intermAggregate)
{
// Currently, we do not support user defined functions.
if (intermAggregate->getName() != "main(")
return;
visitAggregateChildren(intermAggregate);
}
// Takes an expression like "f(x)" and creates a dependency graph like
// "x -> argument 0 -> function call".
void TDependencyGraphBuilder::visitFunctionCall(TIntermAggregate* intermFunctionCall)
{
TGraphFunctionCall* functionCall = mGraph->createFunctionCall(intermFunctionCall);
// Run through the function call arguments.
int argumentNumber = 0;
TIntermSequence& intermArguments = intermFunctionCall->getSequence();
for (TIntermSequence::const_iterator iter = intermArguments.begin();
iter != intermArguments.end();
++iter, ++argumentNumber)
{
TNodeSetMaintainer nodeSetMaintainer(this);
TIntermNode* intermArgument = *iter;
intermArgument->traverse(this);
if (TParentNodeSet* argumentNodes = mNodeSets.getTopSet()) {
TGraphArgument* argument = mGraph->createArgument(intermFunctionCall, argumentNumber);
connectMultipleNodesToSingleNode(argumentNodes, argument);
argument->addDependentNode(functionCall);
}
}
// Push the leftmost symbol of this function call into the current set of dependent symbols to
// represent the result of this function call.
// Thus, an expression like "y = f(x)" will yield a dependency graph like
// "x -> argument 0 -> function call -> y".
// This line essentially passes the function call node back up to an earlier visitAssignment
// call, which will create the connection "function call -> y".
mNodeSets.insertIntoTopSet(functionCall);
}
void TDependencyGraphBuilder::visitAggregateChildren(TIntermAggregate* intermAggregate)
{
TIntermSequence& sequence = intermAggregate->getSequence();
for(TIntermSequence::const_iterator iter = sequence.begin(); iter != sequence.end(); ++iter)
{
TIntermNode* intermChild = *iter;
intermChild->traverse(this);
}
}
void TDependencyGraphBuilder::visitSymbol(TIntermSymbol* intermSymbol)
{
// Push this symbol into the set of dependent symbols for the current assignment or condition
// that we are traversing.
TGraphSymbol* symbol = mGraph->getOrCreateSymbol(intermSymbol);
mNodeSets.insertIntoTopSet(symbol);
// If this symbol is the current leftmost symbol under an assignment, replace the previous
// leftmost symbol with this symbol.
if (!mLeftmostSymbols.empty() && mLeftmostSymbols.top() != &mRightSubtree) {
mLeftmostSymbols.pop();
mLeftmostSymbols.push(symbol);
}
}
bool TDependencyGraphBuilder::visitBinary(Visit visit, TIntermBinary* intermBinary)
{
TOperator op = intermBinary->getOp();
if (op == EOpInitialize || intermBinary->modifiesState())
visitAssignment(intermBinary);
else if (op == EOpLogicalAnd || op == EOpLogicalOr)
visitLogicalOp(intermBinary);
else
visitBinaryChildren(intermBinary);
return false;
}
void TDependencyGraphBuilder::visitAssignment(TIntermBinary* intermAssignment)
{
TIntermTyped* intermLeft = intermAssignment->getLeft();
if (!intermLeft)
return;
TGraphSymbol* leftmostSymbol = NULL;
{
TNodeSetMaintainer nodeSetMaintainer(this);
{
TLeftmostSymbolMaintainer leftmostSymbolMaintainer(this, mLeftSubtree);
intermLeft->traverse(this);
leftmostSymbol = mLeftmostSymbols.top();
// After traversing the left subtree of this assignment, we should have found a real
// leftmost symbol, and the leftmost symbol should not be a placeholder.
ASSERT(leftmostSymbol != &mLeftSubtree);
ASSERT(leftmostSymbol != &mRightSubtree);
}
if (TIntermTyped* intermRight = intermAssignment->getRight()) {
TLeftmostSymbolMaintainer leftmostSymbolMaintainer(this, mRightSubtree);
intermRight->traverse(this);
}
if (TParentNodeSet* assignmentNodes = mNodeSets.getTopSet())
connectMultipleNodesToSingleNode(assignmentNodes, leftmostSymbol);
}
// Push the leftmost symbol of this assignment into the current set of dependent symbols to
// represent the result of this assignment.
// An expression like "a = (b = c)" will yield a dependency graph like "c -> b -> a".
// This line essentially passes the leftmost symbol of the nested assignment ("b" in this
// example) back up to the earlier visitAssignment call for the outer assignment, which will
// create the connection "b -> a".
mNodeSets.insertIntoTopSet(leftmostSymbol);
}
void TDependencyGraphBuilder::visitLogicalOp(TIntermBinary* intermLogicalOp)
{
if (TIntermTyped* intermLeft = intermLogicalOp->getLeft()) {
TNodeSetPropagatingMaintainer nodeSetMaintainer(this);
intermLeft->traverse(this);
if (TParentNodeSet* leftNodes = mNodeSets.getTopSet()) {
TGraphLogicalOp* logicalOp = mGraph->createLogicalOp(intermLogicalOp);
connectMultipleNodesToSingleNode(leftNodes, logicalOp);
}
}
if (TIntermTyped* intermRight = intermLogicalOp->getRight()) {
TLeftmostSymbolMaintainer leftmostSymbolMaintainer(this, mRightSubtree);
intermRight->traverse(this);
}
}
void TDependencyGraphBuilder::visitBinaryChildren(TIntermBinary* intermBinary)
{
if (TIntermTyped* intermLeft = intermBinary->getLeft())
intermLeft->traverse(this);
if (TIntermTyped* intermRight = intermBinary->getRight()) {
TLeftmostSymbolMaintainer leftmostSymbolMaintainer(this, mRightSubtree);
intermRight->traverse(this);
}
}
bool TDependencyGraphBuilder::visitSelection(Visit visit, TIntermSelection* intermSelection)
{
if (TIntermNode* intermCondition = intermSelection->getCondition()) {
TNodeSetMaintainer nodeSetMaintainer(this);
intermCondition->traverse(this);
if (TParentNodeSet* conditionNodes = mNodeSets.getTopSet()) {
TGraphSelection* selection = mGraph->createSelection(intermSelection);
connectMultipleNodesToSingleNode(conditionNodes, selection);
}
}
if (TIntermNode* intermTrueBlock = intermSelection->getTrueBlock())
intermTrueBlock->traverse(this);
if (TIntermNode* intermFalseBlock = intermSelection->getFalseBlock())
intermFalseBlock->traverse(this);
return false;
}
bool TDependencyGraphBuilder::visitLoop(Visit visit, TIntermLoop* intermLoop)
{
if (TIntermTyped* intermCondition = intermLoop->getCondition()) {
TNodeSetMaintainer nodeSetMaintainer(this);
intermCondition->traverse(this);
if (TParentNodeSet* conditionNodes = mNodeSets.getTopSet()) {
TGraphLoop* loop = mGraph->createLoop(intermLoop);
connectMultipleNodesToSingleNode(conditionNodes, loop);
}
}
if (TIntermNode* intermBody = intermLoop->getBody())
intermBody->traverse(this);
if (TIntermTyped* intermExpression = intermLoop->getExpression())
intermExpression->traverse(this);
return false;
}
void TDependencyGraphBuilder::connectMultipleNodesToSingleNode(TParentNodeSet* nodes,
TGraphNode* node) const
{
for (TParentNodeSet::const_iterator iter = nodes->begin(); iter != nodes->end(); ++iter)
{
TGraphParentNode* currentNode = *iter;
currentNode->addDependentNode(node);
}
}
| C++ |
//
// 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 COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
#define COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
#include "compiler/depgraph/DependencyGraph.h"
//
// Creates a dependency graph of symbols, function calls, conditions etc. by traversing a
// intermediate tree.
//
class TDependencyGraphBuilder : public TIntermTraverser {
public:
static void build(TIntermNode* node, TDependencyGraph* graph);
virtual void visitSymbol(TIntermSymbol*);
virtual bool visitBinary(Visit visit, TIntermBinary*);
virtual bool visitSelection(Visit visit, TIntermSelection*);
virtual bool visitAggregate(Visit visit, TIntermAggregate*);
virtual bool visitLoop(Visit visit, TIntermLoop*);
private:
typedef std::stack<TGraphSymbol*> TSymbolStack;
typedef std::set<TGraphParentNode*> TParentNodeSet;
//
// For collecting the dependent nodes of assignments, conditions, etc.
// while traversing the intermediate tree.
//
// This data structure is stack of sets. Each set contains dependency graph parent nodes.
//
class TNodeSetStack {
public:
TNodeSetStack() {};
~TNodeSetStack() { clear(); }
// This should only be called after a pushSet.
// Returns NULL if the top set is empty.
TParentNodeSet* getTopSet() const
{
ASSERT(!nodeSets.empty());
TParentNodeSet* topSet = nodeSets.top();
return !topSet->empty() ? topSet : NULL;
}
void pushSet() { nodeSets.push(new TParentNodeSet()); }
void popSet()
{
ASSERT(!nodeSets.empty());
delete nodeSets.top();
nodeSets.pop();
}
// Pops the top set and adds its contents to the new top set.
// This should only be called after a pushSet.
// If there is no set below the top set, the top set is just deleted.
void popSetIntoNext()
{
ASSERT(!nodeSets.empty());
TParentNodeSet* oldTopSet = nodeSets.top();
nodeSets.pop();
if (!nodeSets.empty()) {
TParentNodeSet* newTopSet = nodeSets.top();
newTopSet->insert(oldTopSet->begin(), oldTopSet->end());
}
delete oldTopSet;
}
// Does nothing if there is no top set.
// This can be called when there is no top set if we are visiting
// symbols that are not under an assignment or condition.
// We don't need to track those symbols.
void insertIntoTopSet(TGraphParentNode* node)
{
if (nodeSets.empty())
return;
nodeSets.top()->insert(node);
}
void clear()
{
while (!nodeSets.empty())
popSet();
}
private:
typedef std::stack<TParentNodeSet*> TParentNodeSetStack;
TParentNodeSetStack nodeSets;
};
//
// An instance of this class pushes a new node set when instantiated.
// When the instance goes out of scope, it and pops the node set.
//
class TNodeSetMaintainer {
public:
TNodeSetMaintainer(TDependencyGraphBuilder* factory)
: sets(factory->mNodeSets) { sets.pushSet(); }
~TNodeSetMaintainer() { sets.popSet(); }
protected:
TNodeSetStack& sets;
};
//
// An instance of this class pushes a new node set when instantiated.
// When the instance goes out of scope, it and pops the top node set and adds its contents to
// the new top node set.
//
class TNodeSetPropagatingMaintainer {
public:
TNodeSetPropagatingMaintainer(TDependencyGraphBuilder* factory)
: sets(factory->mNodeSets) { sets.pushSet(); }
~TNodeSetPropagatingMaintainer() { sets.popSetIntoNext(); }
protected:
TNodeSetStack& sets;
};
//
// An instance of this class keeps track of the leftmost symbol while we're exploring an
// assignment.
// It will push the placeholder symbol kLeftSubtree when instantiated under a left subtree,
// and kRightSubtree under a right subtree.
// When it goes out of scope, it will pop the leftmost symbol at the top of the scope.
// During traversal, the TDependencyGraphBuilder will replace kLeftSubtree with a real symbol.
// kRightSubtree will never be replaced by a real symbol because we are tracking the leftmost
// symbol.
//
class TLeftmostSymbolMaintainer {
public:
TLeftmostSymbolMaintainer(TDependencyGraphBuilder* factory, TGraphSymbol& subtree)
: leftmostSymbols(factory->mLeftmostSymbols)
{
needsPlaceholderSymbol = leftmostSymbols.empty() || leftmostSymbols.top() != &subtree;
if (needsPlaceholderSymbol)
leftmostSymbols.push(&subtree);
}
~TLeftmostSymbolMaintainer()
{
if (needsPlaceholderSymbol)
leftmostSymbols.pop();
}
protected:
TSymbolStack& leftmostSymbols;
bool needsPlaceholderSymbol;
};
TDependencyGraphBuilder(TDependencyGraph* graph)
: TIntermTraverser(true, false, false)
, mLeftSubtree(NULL)
, mRightSubtree(NULL)
, mGraph(graph) {}
void build(TIntermNode* intermNode) { intermNode->traverse(this); }
void connectMultipleNodesToSingleNode(TParentNodeSet* nodes, TGraphNode* node) const;
void visitAssignment(TIntermBinary*);
void visitLogicalOp(TIntermBinary*);
void visitBinaryChildren(TIntermBinary*);
void visitFunctionDefinition(TIntermAggregate*);
void visitFunctionCall(TIntermAggregate* intermFunctionCall);
void visitAggregateChildren(TIntermAggregate*);
TGraphSymbol mLeftSubtree;
TGraphSymbol mRightSubtree;
TDependencyGraph* mGraph;
TNodeSetStack mNodeSets;
TSymbolStack mLeftmostSymbols;
};
#endif // COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
| C++ |
//
// 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 "compiler/depgraph/DependencyGraph.h"
// These methods do a breadth-first traversal through the graph and mark visited nodes.
void TGraphNode::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->markVisited(this);
}
void TGraphParentNode::traverse(TDependencyGraphTraverser* graphTraverser)
{
TGraphNode::traverse(graphTraverser);
graphTraverser->incrementDepth();
// Visit the parent node's children.
for (TGraphNodeSet::const_iterator iter = mDependentNodes.begin();
iter != mDependentNodes.end();
++iter)
{
TGraphNode* node = *iter;
if (!graphTraverser->isVisited(node))
node->traverse(graphTraverser);
}
graphTraverser->decrementDepth();
}
void TGraphArgument::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitArgument(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphFunctionCall::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitFunctionCall(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphSymbol::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitSymbol(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphSelection::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitSelection(this);
TGraphNode::traverse(graphTraverser);
}
void TGraphLoop::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitLoop(this);
TGraphNode::traverse(graphTraverser);
}
void TGraphLogicalOp::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitLogicalOp(this);
TGraphNode::traverse(graphTraverser);
}
| C++ |
//
// 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 COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_H
#define COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_H
#include "compiler/intermediate.h"
#include <set>
#include <stack>
class TGraphNode;
class TGraphParentNode;
class TGraphArgument;
class TGraphFunctionCall;
class TGraphSymbol;
class TGraphSelection;
class TGraphLoop;
class TGraphLogicalOp;
class TDependencyGraphTraverser;
class TDependencyGraphOutput;
typedef std::set<TGraphNode*> TGraphNodeSet;
typedef std::vector<TGraphNode*> TGraphNodeVector;
typedef std::vector<TGraphSymbol*> TGraphSymbolVector;
typedef std::vector<TGraphFunctionCall*> TFunctionCallVector;
//
// Base class for all dependency graph nodes.
//
class TGraphNode {
public:
TGraphNode(TIntermNode* node) : intermNode(node) {}
virtual ~TGraphNode() {}
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
protected:
TIntermNode* intermNode;
};
//
// Base class for dependency graph nodes that may have children.
//
class TGraphParentNode : public TGraphNode {
public:
TGraphParentNode(TIntermNode* node) : TGraphNode(node) {}
virtual ~TGraphParentNode() {}
void addDependentNode(TGraphNode* node) { if (node != this) mDependentNodes.insert(node); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
private:
TGraphNodeSet mDependentNodes;
};
//
// Handle function call arguments.
//
class TGraphArgument : public TGraphParentNode {
public:
TGraphArgument(TIntermAggregate* intermFunctionCall, int argumentNumber)
: TGraphParentNode(intermFunctionCall)
, mArgumentNumber(argumentNumber) {}
virtual ~TGraphArgument() {}
const TIntermAggregate* getIntermFunctionCall() const { return intermNode->getAsAggregate(); }
int getArgumentNumber() const { return mArgumentNumber; }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
private:
int mArgumentNumber;
};
//
// Handle function calls.
//
class TGraphFunctionCall : public TGraphParentNode {
public:
TGraphFunctionCall(TIntermAggregate* intermFunctionCall)
: TGraphParentNode(intermFunctionCall) {}
virtual ~TGraphFunctionCall() {}
const TIntermAggregate* getIntermFunctionCall() const { return intermNode->getAsAggregate(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle symbols.
//
class TGraphSymbol : public TGraphParentNode {
public:
TGraphSymbol(TIntermSymbol* intermSymbol) : TGraphParentNode(intermSymbol) {}
virtual ~TGraphSymbol() {}
const TIntermSymbol* getIntermSymbol() const { return intermNode->getAsSymbolNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle if statements and ternary operators.
//
class TGraphSelection : public TGraphNode {
public:
TGraphSelection(TIntermSelection* intermSelection) : TGraphNode(intermSelection) {}
virtual ~TGraphSelection() {}
const TIntermSelection* getIntermSelection() const { return intermNode->getAsSelectionNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle for, do-while, and while loops.
//
class TGraphLoop : public TGraphNode {
public:
TGraphLoop(TIntermLoop* intermLoop) : TGraphNode(intermLoop) {}
virtual ~TGraphLoop() {}
const TIntermLoop* getIntermLoop() const { return intermNode->getAsLoopNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle logical and, or.
//
class TGraphLogicalOp : public TGraphNode {
public:
TGraphLogicalOp(TIntermBinary* intermLogicalOp) : TGraphNode(intermLogicalOp) {}
virtual ~TGraphLogicalOp() {}
const TIntermBinary* getIntermLogicalOp() const { return intermNode->getAsBinaryNode(); }
const char* getOpString() const;
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// A dependency graph of symbols, function calls, conditions etc.
//
// This class provides an interface to the entry points of the dependency graph.
//
// Dependency graph nodes should be created by using one of the provided "create..." methods.
// This class (and nobody else) manages the memory of the created nodes.
// Nodes may not be removed after being added, so all created nodes will exist while the
// TDependencyGraph instance exists.
//
class TDependencyGraph {
public:
TDependencyGraph(TIntermNode* intermNode);
~TDependencyGraph();
TGraphNodeVector::const_iterator begin() const { return mAllNodes.begin(); }
TGraphNodeVector::const_iterator end() const { return mAllNodes.end(); }
TGraphSymbolVector::const_iterator beginSamplerSymbols() const
{
return mSamplerSymbols.begin();
}
TGraphSymbolVector::const_iterator endSamplerSymbols() const
{
return mSamplerSymbols.end();
}
TFunctionCallVector::const_iterator beginUserDefinedFunctionCalls() const
{
return mUserDefinedFunctionCalls.begin();
}
TFunctionCallVector::const_iterator endUserDefinedFunctionCalls() const
{
return mUserDefinedFunctionCalls.end();
}
TGraphArgument* createArgument(TIntermAggregate* intermFunctionCall, int argumentNumber);
TGraphFunctionCall* createFunctionCall(TIntermAggregate* intermFunctionCall);
TGraphSymbol* getOrCreateSymbol(TIntermSymbol* intermSymbol);
TGraphSelection* createSelection(TIntermSelection* intermSelection);
TGraphLoop* createLoop(TIntermLoop* intermLoop);
TGraphLogicalOp* createLogicalOp(TIntermBinary* intermLogicalOp);
private:
typedef TMap<int, TGraphSymbol*> TSymbolIdMap;
typedef std::pair<int, TGraphSymbol*> TSymbolIdPair;
TGraphNodeVector mAllNodes;
TGraphSymbolVector mSamplerSymbols;
TFunctionCallVector mUserDefinedFunctionCalls;
TSymbolIdMap mSymbolIdMap;
};
//
// For traversing the dependency graph. Users should derive from this,
// put their traversal specific data in it, and then pass it to a
// traverse method.
//
// When using this, just fill in the methods for nodes you want visited.
//
class TDependencyGraphTraverser {
public:
TDependencyGraphTraverser() : mDepth(0) {}
virtual void visitSymbol(TGraphSymbol* symbol) {};
virtual void visitArgument(TGraphArgument* selection) {};
virtual void visitFunctionCall(TGraphFunctionCall* functionCall) {};
virtual void visitSelection(TGraphSelection* selection) {};
virtual void visitLoop(TGraphLoop* loop) {};
virtual void visitLogicalOp(TGraphLogicalOp* logicalOp) {};
int getDepth() const { return mDepth; }
void incrementDepth() { ++mDepth; }
void decrementDepth() { --mDepth; }
void clearVisited() { mVisited.clear(); }
void markVisited(TGraphNode* node) { mVisited.insert(node); }
bool isVisited(TGraphNode* node) const { return mVisited.find(node) != mVisited.end(); }
private:
int mDepth;
TGraphNodeSet mVisited;
};
#endif
| C++ |
//
// 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.
//
#pragma warning(disable: 4718)
#include "compiler/depgraph/DependencyGraph.h"
#include "compiler/depgraph/DependencyGraphBuilder.h"
TDependencyGraph::TDependencyGraph(TIntermNode* intermNode)
{
TDependencyGraphBuilder::build(intermNode, this);
}
TDependencyGraph::~TDependencyGraph()
{
for (TGraphNodeVector::const_iterator iter = mAllNodes.begin(); iter != mAllNodes.end(); ++iter)
{
TGraphNode* node = *iter;
delete node;
}
}
TGraphArgument* TDependencyGraph::createArgument(TIntermAggregate* intermFunctionCall,
int argumentNumber)
{
TGraphArgument* argument = new TGraphArgument(intermFunctionCall, argumentNumber);
mAllNodes.push_back(argument);
return argument;
}
TGraphFunctionCall* TDependencyGraph::createFunctionCall(TIntermAggregate* intermFunctionCall)
{
TGraphFunctionCall* functionCall = new TGraphFunctionCall(intermFunctionCall);
mAllNodes.push_back(functionCall);
if (functionCall->getIntermFunctionCall()->isUserDefined())
mUserDefinedFunctionCalls.push_back(functionCall);
return functionCall;
}
TGraphSymbol* TDependencyGraph::getOrCreateSymbol(TIntermSymbol* intermSymbol)
{
TSymbolIdMap::const_iterator iter = mSymbolIdMap.find(intermSymbol->getId());
TGraphSymbol* symbol = NULL;
if (iter != mSymbolIdMap.end()) {
TSymbolIdPair pair = *iter;
symbol = pair.second;
} else {
symbol = new TGraphSymbol(intermSymbol);
mAllNodes.push_back(symbol);
TSymbolIdPair pair(intermSymbol->getId(), symbol);
mSymbolIdMap.insert(pair);
// We save all sampler symbols in a collection, so we can start graph traversals from them quickly.
if (IsSampler(intermSymbol->getBasicType()))
mSamplerSymbols.push_back(symbol);
}
return symbol;
}
TGraphSelection* TDependencyGraph::createSelection(TIntermSelection* intermSelection)
{
TGraphSelection* selection = new TGraphSelection(intermSelection);
mAllNodes.push_back(selection);
return selection;
}
TGraphLoop* TDependencyGraph::createLoop(TIntermLoop* intermLoop)
{
TGraphLoop* loop = new TGraphLoop(intermLoop);
mAllNodes.push_back(loop);
return loop;
}
TGraphLogicalOp* TDependencyGraph::createLogicalOp(TIntermBinary* intermLogicalOp)
{
TGraphLogicalOp* logicalOp = new TGraphLogicalOp(intermLogicalOp);
mAllNodes.push_back(logicalOp);
return logicalOp;
}
const char* TGraphLogicalOp::getOpString() const
{
const char* opString = NULL;
switch (getIntermLogicalOp()->getOp()) {
case EOpLogicalAnd: opString = "and"; break;
case EOpLogicalOr: opString = "or"; break;
default: opString = "unknown"; break;
}
return opString;
}
| C++ |
//
// 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.
//
#include "compiler/InitializeDll.h"
#include "compiler/InitializeGlobals.h"
#include "compiler/InitializeParseContext.h"
#include "compiler/osinclude.h"
OS_TLSIndex ThreadInitializeIndex = OS_INVALID_TLS_INDEX;
bool InitProcess()
{
if (ThreadInitializeIndex != OS_INVALID_TLS_INDEX) {
//
// Function is re-entrant.
//
return true;
}
ThreadInitializeIndex = OS_AllocTLSIndex();
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "InitProcess(): Failed to allocate TLS area for init flag");
return false;
}
if (!InitializePoolIndex()) {
assert(0 && "InitProcess(): Failed to initalize global pool");
return false;
}
if (!InitializeParseContextIndex()) {
assert(0 && "InitProcess(): Failed to initalize parse context");
return false;
}
return InitThread();
}
bool DetachProcess()
{
bool success = true;
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX)
return true;
success = DetachThread();
if (!FreeParseContextIndex())
success = false;
FreePoolIndex();
OS_FreeTLSIndex(ThreadInitializeIndex);
ThreadInitializeIndex = OS_INVALID_TLS_INDEX;
return success;
}
bool InitThread()
{
//
// This function is re-entrant
//
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "InitThread(): Process hasn't been initalised.");
return false;
}
if (OS_GetTLSValue(ThreadInitializeIndex) != 0)
return true;
InitializeGlobalPools();
if (!InitializeGlobalParseContext())
return false;
if (!OS_SetTLSValue(ThreadInitializeIndex, (void *)1)) {
assert(0 && "InitThread(): Unable to set init flag.");
return false;
}
return true;
}
bool DetachThread()
{
bool success = true;
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX)
return true;
//
// Function is re-entrant and this thread may not have been initalised.
//
if (OS_GetTLSValue(ThreadInitializeIndex) != 0) {
if (!OS_SetTLSValue(ThreadInitializeIndex, (void *)0)) {
assert(0 && "DetachThread(): Unable to clear init flag.");
success = false;
}
if (!FreeParseContext())
success = false;
FreeGlobalPools();
}
return success;
}
| C++ |
//
// 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.
//
#include "compiler/InfoSink.h"
void TInfoSinkBase::prefix(TPrefixType p) {
switch(p) {
case EPrefixNone:
break;
case EPrefixWarning:
sink.append("WARNING: ");
break;
case EPrefixError:
sink.append("ERROR: ");
break;
case EPrefixInternalError:
sink.append("INTERNAL ERROR: ");
break;
case EPrefixUnimplemented:
sink.append("UNIMPLEMENTED: ");
break;
case EPrefixNote:
sink.append("NOTE: ");
break;
default:
sink.append("UNKOWN ERROR: ");
break;
}
}
void TInfoSinkBase::location(int file, int line) {
TPersistStringStream stream;
if (line)
stream << file << ":" << line;
else
stream << file << ":? ";
stream << ": ";
sink.append(stream.str());
}
void TInfoSinkBase::location(const TSourceLoc& loc) {
location(loc.first_file, loc.first_line);
}
void TInfoSinkBase::message(TPrefixType p, const TSourceLoc& loc, const char* m) {
prefix(p);
location(loc);
sink.append(m);
sink.append("\n");
}
| C++ |
//
// 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.
//
#ifndef _VARIABLEPACKER_INCLUDED_
#define _VARIABLEPACKER_INCLUDED_
#include <vector>
#include "compiler/ShHandle.h"
class VariablePacker {
public:
// Returns true if the passed in variables pack in maxVectors following
// the packing rules from the GLSL 1.017 spec, Appendix A, section 7.
bool CheckVariablesWithinPackingLimits(
int maxVectors,
const TVariableInfoList& in_variables);
// Gets how many components in a row a data type takes.
static int GetNumComponentsPerRow(ShDataType type);
// Gets how many rows a data type takes.
static int GetNumRows(ShDataType type);
private:
static const int kNumColumns = 4;
static const unsigned kColumnMask = (1 << kNumColumns) - 1;
unsigned makeColumnFlags(int column, int numComponentsPerRow);
void fillColumns(int topRow, int numRows, int column, int numComponentsPerRow);
bool searchColumn(int column, int numRows, int* destRow, int* destSize);
int topNonFullRow_;
int bottomNonFullRow_;
int maxRows_;
std::vector<unsigned> rows_;
};
#endif // _VARIABLEPACKER_INCLUDED_
| C++ |
//
// 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.
//
#ifndef COMPILER_TRANSLATORGLSL_H_
#define COMPILER_TRANSLATORGLSL_H_
#include "compiler/ShHandle.h"
class TranslatorGLSL : public TCompiler {
public:
TranslatorGLSL(ShShaderType type, ShShaderSpec spec);
protected:
virtual void translate(TIntermNode* root);
};
#endif // COMPILER_TRANSLATORGLSL_H_
| C++ |
//
// Copyright (c) 2002-2011 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 "compiler/DetectCallDepth.h"
#include "compiler/InfoSink.h"
DetectCallDepth::FunctionNode::FunctionNode(const TString& fname)
: name(fname),
visit(PreVisit)
{
}
const TString& DetectCallDepth::FunctionNode::getName() const
{
return name;
}
void DetectCallDepth::FunctionNode::addCallee(
DetectCallDepth::FunctionNode* callee)
{
for (size_t i = 0; i < callees.size(); ++i) {
if (callees[i] == callee)
return;
}
callees.push_back(callee);
}
int DetectCallDepth::FunctionNode::detectCallDepth(DetectCallDepth* detectCallDepth, int depth)
{
ASSERT(visit == PreVisit);
ASSERT(detectCallDepth);
int maxDepth = depth;
visit = InVisit;
for (size_t i = 0; i < callees.size(); ++i) {
switch (callees[i]->visit) {
case InVisit:
// cycle detected, i.e., recursion detected.
return kInfiniteCallDepth;
case PostVisit:
break;
case PreVisit: {
// Check before we recurse so we don't go too depth
if (detectCallDepth->checkExceedsMaxDepth(depth))
return depth;
int callDepth = callees[i]->detectCallDepth(detectCallDepth, depth + 1);
// Check after we recurse so we can exit immediately and provide info.
if (detectCallDepth->checkExceedsMaxDepth(callDepth)) {
detectCallDepth->getInfoSink().info << "<-" << callees[i]->getName();
return callDepth;
}
maxDepth = std::max(callDepth, maxDepth);
break;
}
default:
UNREACHABLE();
break;
}
}
visit = PostVisit;
return maxDepth;
}
void DetectCallDepth::FunctionNode::reset()
{
visit = PreVisit;
}
DetectCallDepth::DetectCallDepth(TInfoSink& infoSink, bool limitCallStackDepth, int maxCallStackDepth)
: TIntermTraverser(true, false, true, false),
currentFunction(NULL),
infoSink(infoSink),
maxDepth(limitCallStackDepth ? maxCallStackDepth : FunctionNode::kInfiniteCallDepth)
{
}
DetectCallDepth::~DetectCallDepth()
{
for (size_t i = 0; i < functions.size(); ++i)
delete functions[i];
}
bool DetectCallDepth::visitAggregate(Visit visit, TIntermAggregate* node)
{
switch (node->getOp())
{
case EOpPrototype:
// Function declaration.
// Don't add FunctionNode here because node->getName() is the
// unmangled function name.
break;
case EOpFunction: {
// Function definition.
if (visit == PreVisit) {
currentFunction = findFunctionByName(node->getName());
if (currentFunction == NULL) {
currentFunction = new FunctionNode(node->getName());
functions.push_back(currentFunction);
}
} else if (visit == PostVisit) {
currentFunction = NULL;
}
break;
}
case EOpFunctionCall: {
// Function call.
if (visit == PreVisit) {
FunctionNode* func = findFunctionByName(node->getName());
if (func == NULL) {
func = new FunctionNode(node->getName());
functions.push_back(func);
}
if (currentFunction)
currentFunction->addCallee(func);
}
break;
}
default:
break;
}
return true;
}
bool DetectCallDepth::checkExceedsMaxDepth(int depth)
{
return depth >= maxDepth;
}
void DetectCallDepth::resetFunctionNodes()
{
for (size_t i = 0; i < functions.size(); ++i) {
functions[i]->reset();
}
}
DetectCallDepth::ErrorCode DetectCallDepth::detectCallDepthForFunction(FunctionNode* func)
{
currentFunction = NULL;
resetFunctionNodes();
int maxCallDepth = func->detectCallDepth(this, 1);
if (maxCallDepth == FunctionNode::kInfiniteCallDepth)
return kErrorRecursion;
if (maxCallDepth >= maxDepth)
return kErrorMaxDepthExceeded;
return kErrorNone;
}
DetectCallDepth::ErrorCode DetectCallDepth::detectCallDepth()
{
if (maxDepth != FunctionNode::kInfiniteCallDepth) {
// Check all functions because the driver may fail on them
// TODO: Before detectingRecursion, strip unused functions.
for (size_t i = 0; i < functions.size(); ++i) {
ErrorCode error = detectCallDepthForFunction(functions[i]);
if (error != kErrorNone)
return error;
}
} else {
FunctionNode* main = findFunctionByName("main(");
if (main == NULL)
return kErrorMissingMain;
return detectCallDepthForFunction(main);
}
return kErrorNone;
}
DetectCallDepth::FunctionNode* DetectCallDepth::findFunctionByName(
const TString& name)
{
for (size_t i = 0; i < functions.size(); ++i) {
if (functions[i]->getName() == name)
return functions[i];
}
return NULL;
}
| C++ |
//
// 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.
//
#include "compiler/MapLongVariableNames.h"
namespace {
TString mapLongName(size_t id, const TString& name, bool isGlobal)
{
ASSERT(name.size() > MAX_SHORTENED_IDENTIFIER_SIZE);
TStringStream stream;
stream << "webgl_";
if (isGlobal)
stream << "g";
stream << id;
if (name[0] != '_')
stream << "_";
stream << name.substr(0, MAX_SHORTENED_IDENTIFIER_SIZE - stream.str().size());
return stream.str();
}
LongNameMap* gLongNameMapInstance = NULL;
} // anonymous namespace
LongNameMap::LongNameMap()
: refCount(0)
{
}
LongNameMap::~LongNameMap()
{
}
// static
LongNameMap* LongNameMap::GetInstance()
{
if (gLongNameMapInstance == NULL)
gLongNameMapInstance = new LongNameMap;
gLongNameMapInstance->refCount++;
return gLongNameMapInstance;
}
void LongNameMap::Release()
{
ASSERT(gLongNameMapInstance == this);
ASSERT(refCount > 0);
refCount--;
if (refCount == 0) {
delete gLongNameMapInstance;
gLongNameMapInstance = NULL;
}
}
const char* LongNameMap::Find(const char* originalName) const
{
std::map<std::string, std::string>::const_iterator it = mLongNameMap.find(
originalName);
if (it != mLongNameMap.end())
return (*it).second.c_str();
return NULL;
}
void LongNameMap::Insert(const char* originalName, const char* mappedName)
{
mLongNameMap.insert(std::map<std::string, std::string>::value_type(
originalName, mappedName));
}
size_t LongNameMap::Size() const
{
return mLongNameMap.size();
}
MapLongVariableNames::MapLongVariableNames(LongNameMap* globalMap)
{
ASSERT(globalMap);
mGlobalMap = globalMap;
}
void MapLongVariableNames::visitSymbol(TIntermSymbol* symbol)
{
ASSERT(symbol != NULL);
if (symbol->getSymbol().size() > MAX_SHORTENED_IDENTIFIER_SIZE) {
switch (symbol->getQualifier()) {
case EvqVaryingIn:
case EvqVaryingOut:
case EvqInvariantVaryingIn:
case EvqInvariantVaryingOut:
case EvqUniform:
symbol->setSymbol(
mapGlobalLongName(symbol->getSymbol()));
break;
default:
symbol->setSymbol(
mapLongName(symbol->getId(), symbol->getSymbol(), false));
break;
};
}
}
bool MapLongVariableNames::visitLoop(Visit, TIntermLoop* node)
{
if (node->getInit())
node->getInit()->traverse(this);
return true;
}
TString MapLongVariableNames::mapGlobalLongName(const TString& name)
{
ASSERT(mGlobalMap);
const char* mappedName = mGlobalMap->Find(name.c_str());
if (mappedName != NULL)
return mappedName;
size_t id = mGlobalMap->Size();
TString rt = mapLongName(id, name, true);
mGlobalMap->Insert(name.c_str(), rt.c_str());
return rt;
}
| C++ |
//
// 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.
//
// Config.h: Defines the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.4] section 3.4 page 15.
#ifndef INCLUDE_CONFIG_H_
#define INCLUDE_CONFIG_H_
#define EGLAPI
#include <EGL/egl.h>
#include <set>
#include "libGLESv2/renderer/Renderer.h"
#include "common/angleutils.h"
namespace egl
{
class Display;
class Config
{
public:
Config(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight);
EGLConfig getHandle() const;
const GLenum mRenderTargetFormat;
const GLenum mDepthStencilFormat;
const GLint mMultiSample;
EGLint mBufferSize; // Depth of the color buffer
EGLint mRedSize; // Bits of Red in the color buffer
EGLint mGreenSize; // Bits of Green in the color buffer
EGLint mBlueSize; // Bits of Blue in the color buffer
EGLint mLuminanceSize; // Bits of Luminance in the color buffer
EGLint mAlphaSize; // Bits of Alpha in the color buffer
EGLint mAlphaMaskSize; // Bits of Alpha Mask in the mask buffer
EGLBoolean mBindToTextureRGB; // True if bindable to RGB textures.
EGLBoolean mBindToTextureRGBA; // True if bindable to RGBA textures.
EGLenum mColorBufferType; // Color buffer type
EGLenum mConfigCaveat; // Any caveats for the configuration
EGLint mConfigID; // Unique EGLConfig identifier
EGLint mConformant; // Whether contexts created with this config are conformant
EGLint mDepthSize; // Bits of Z in the depth buffer
EGLint mLevel; // Frame buffer level
EGLBoolean mMatchNativePixmap; // Match the native pixmap format
EGLint mMaxPBufferWidth; // Maximum width of pbuffer
EGLint mMaxPBufferHeight; // Maximum height of pbuffer
EGLint mMaxPBufferPixels; // Maximum size of pbuffer
EGLint mMaxSwapInterval; // Maximum swap interval
EGLint mMinSwapInterval; // Minimum swap interval
EGLBoolean mNativeRenderable; // EGL_TRUE if native rendering APIs can render to surface
EGLint mNativeVisualID; // Handle of corresponding native visual
EGLint mNativeVisualType; // Native visual type of the associated visual
EGLint mRenderableType; // Which client rendering APIs are supported.
EGLint mSampleBuffers; // Number of multisample buffers
EGLint mSamples; // Number of samples per pixel
EGLint mStencilSize; // Bits of Stencil in the stencil buffer
EGLint mSurfaceType; // Which types of EGL surfaces are supported.
EGLenum mTransparentType; // Type of transparency supported
EGLint mTransparentRedValue; // Transparent red value
EGLint mTransparentGreenValue; // Transparent green value
EGLint mTransparentBlueValue; // Transparent blue value
};
// Function object used by STL sorting routines for ordering Configs according to [EGL] section 3.4.1 page 24.
class SortConfig
{
public:
explicit SortConfig(const EGLint *attribList);
bool operator()(const Config *x, const Config *y) const;
bool operator()(const Config &x, const Config &y) const;
private:
void scanForWantedComponents(const EGLint *attribList);
EGLint wantedComponentsSize(const Config &config) const;
bool mWantRed;
bool mWantGreen;
bool mWantBlue;
bool mWantAlpha;
bool mWantLuminance;
};
class ConfigSet
{
friend Display;
public:
ConfigSet();
void add(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight);
size_t size() const;
bool getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig);
const egl::Config *get(EGLConfig configHandle);
private:
DISALLOW_COPY_AND_ASSIGN(ConfigSet);
typedef std::set<Config, SortConfig> Set;
typedef Set::iterator Iterator;
Set mSet;
static const EGLint mSortAttribs[];
};
}
#endif // INCLUDE_CONFIG_H_
| C++ |
//
// 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.
//
// Display.h: Defines the egl::Display class, representing the abstract
// display on which graphics are drawn. Implements EGLDisplay.
// [EGL 1.4] section 2.1.2 page 3.
#ifndef LIBEGL_DISPLAY_H_
#define LIBEGL_DISPLAY_H_
#include "common/system.h"
#include <set>
#include <vector>
#include "libEGL/Config.h"
namespace gl
{
class Context;
}
namespace egl
{
class Surface;
class Display
{
public:
~Display();
bool initialize();
void terminate();
static egl::Display *getDisplay(EGLNativeDisplayType displayId);
bool getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig);
bool getConfigAttrib(EGLConfig config, EGLint attribute, EGLint *value);
EGLSurface createWindowSurface(HWND window, EGLConfig config, const EGLint *attribList);
EGLSurface createOffscreenSurface(EGLConfig config, HANDLE shareHandle, const EGLint *attribList);
EGLContext createContext(EGLConfig configHandle, const gl::Context *shareContext, bool notifyResets, bool robustAccess);
void destroySurface(egl::Surface *surface);
void destroyContext(gl::Context *context);
bool isInitialized() const;
bool isValidConfig(EGLConfig config);
bool isValidContext(gl::Context *context);
bool isValidSurface(egl::Surface *surface);
bool hasExistingWindowSurface(HWND window);
rx::Renderer *getRenderer() { return mRenderer; };
// exported methods must be virtual
virtual void notifyDeviceLost();
virtual void recreateSwapChains();
const char *getExtensionString() const;
const char *getVendorString() const;
private:
DISALLOW_COPY_AND_ASSIGN(Display);
Display(EGLNativeDisplayType displayId, HDC deviceContext);
bool restoreLostDevice();
EGLNativeDisplayType mDisplayId;
const HDC mDc;
bool mSoftwareDevice;
typedef std::set<Surface*> SurfaceSet;
SurfaceSet mSurfaceSet;
ConfigSet mConfigSet;
typedef std::set<gl::Context*> ContextSet;
ContextSet mContextSet;
rx::Renderer *mRenderer;
void initExtensionString();
void initVendorString();
std::string mExtensionString;
std::string mVendorString;
};
}
#endif // LIBEGL_DISPLAY_H_
| C++ |
//
// 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.
//
// Display.cpp: Implements the egl::Display class, representing the abstract
// display on which graphics are drawn. Implements EGLDisplay.
// [EGL 1.4] section 2.1.2 page 3.
#include "libEGL/Display.h"
#include <algorithm>
#include <map>
#include <vector>
#include "common/debug.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/main.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libEGL/main.h"
#include "libEGL/Surface.h"
namespace egl
{
namespace
{
typedef std::map<EGLNativeDisplayType, Display*> DisplayMap;
DisplayMap displays;
}
egl::Display *Display::getDisplay(EGLNativeDisplayType displayId)
{
if (displays.find(displayId) != displays.end())
{
return displays[displayId];
}
// FIXME: Check if displayId is a valid display device context
egl::Display *display = new egl::Display(displayId, (HDC)displayId);
displays[displayId] = display;
return display;
}
Display::Display(EGLNativeDisplayType displayId, HDC deviceContext) : mDc(deviceContext)
{
mDisplayId = displayId;
mRenderer = NULL;
}
Display::~Display()
{
terminate();
DisplayMap::iterator thisDisplay = displays.find(mDisplayId);
if (thisDisplay != displays.end())
{
displays.erase(thisDisplay);
}
}
bool Display::initialize()
{
if (isInitialized())
{
return true;
}
mRenderer = glCreateRenderer(this, mDc, mDisplayId);
if (!mRenderer)
{
terminate();
return error(EGL_NOT_INITIALIZED, false);
}
EGLint minSwapInterval = mRenderer->getMinSwapInterval();
EGLint maxSwapInterval = mRenderer->getMaxSwapInterval();
EGLint maxTextureWidth = mRenderer->getMaxTextureWidth();
EGLint maxTextureHeight = mRenderer->getMaxTextureHeight();
rx::ConfigDesc *descList;
int numConfigs = mRenderer->generateConfigs(&descList);
ConfigSet configSet;
for (int i = 0; i < numConfigs; ++i)
configSet.add(descList[i], minSwapInterval, maxSwapInterval,
maxTextureWidth, maxTextureHeight);
// Give the sorted configs a unique ID and store them internally
EGLint index = 1;
for (ConfigSet::Iterator config = configSet.mSet.begin(); config != configSet.mSet.end(); config++)
{
Config configuration = *config;
configuration.mConfigID = index;
index++;
mConfigSet.mSet.insert(configuration);
}
mRenderer->deleteConfigs(descList);
descList = NULL;
if (!isInitialized())
{
terminate();
return false;
}
initExtensionString();
initVendorString();
return true;
}
void Display::terminate()
{
while (!mSurfaceSet.empty())
{
destroySurface(*mSurfaceSet.begin());
}
while (!mContextSet.empty())
{
destroyContext(*mContextSet.begin());
}
glDestroyRenderer(mRenderer);
mRenderer = NULL;
}
bool Display::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)
{
return mConfigSet.getConfigs(configs, attribList, configSize, numConfig);
}
bool Display::getConfigAttrib(EGLConfig config, EGLint attribute, EGLint *value)
{
const egl::Config *configuration = mConfigSet.get(config);
switch (attribute)
{
case EGL_BUFFER_SIZE: *value = configuration->mBufferSize; break;
case EGL_ALPHA_SIZE: *value = configuration->mAlphaSize; break;
case EGL_BLUE_SIZE: *value = configuration->mBlueSize; break;
case EGL_GREEN_SIZE: *value = configuration->mGreenSize; break;
case EGL_RED_SIZE: *value = configuration->mRedSize; break;
case EGL_DEPTH_SIZE: *value = configuration->mDepthSize; break;
case EGL_STENCIL_SIZE: *value = configuration->mStencilSize; break;
case EGL_CONFIG_CAVEAT: *value = configuration->mConfigCaveat; break;
case EGL_CONFIG_ID: *value = configuration->mConfigID; break;
case EGL_LEVEL: *value = configuration->mLevel; break;
case EGL_NATIVE_RENDERABLE: *value = configuration->mNativeRenderable; break;
case EGL_NATIVE_VISUAL_TYPE: *value = configuration->mNativeVisualType; break;
case EGL_SAMPLES: *value = configuration->mSamples; break;
case EGL_SAMPLE_BUFFERS: *value = configuration->mSampleBuffers; break;
case EGL_SURFACE_TYPE: *value = configuration->mSurfaceType; break;
case EGL_TRANSPARENT_TYPE: *value = configuration->mTransparentType; break;
case EGL_TRANSPARENT_BLUE_VALUE: *value = configuration->mTransparentBlueValue; break;
case EGL_TRANSPARENT_GREEN_VALUE: *value = configuration->mTransparentGreenValue; break;
case EGL_TRANSPARENT_RED_VALUE: *value = configuration->mTransparentRedValue; break;
case EGL_BIND_TO_TEXTURE_RGB: *value = configuration->mBindToTextureRGB; break;
case EGL_BIND_TO_TEXTURE_RGBA: *value = configuration->mBindToTextureRGBA; break;
case EGL_MIN_SWAP_INTERVAL: *value = configuration->mMinSwapInterval; break;
case EGL_MAX_SWAP_INTERVAL: *value = configuration->mMaxSwapInterval; break;
case EGL_LUMINANCE_SIZE: *value = configuration->mLuminanceSize; break;
case EGL_ALPHA_MASK_SIZE: *value = configuration->mAlphaMaskSize; break;
case EGL_COLOR_BUFFER_TYPE: *value = configuration->mColorBufferType; break;
case EGL_RENDERABLE_TYPE: *value = configuration->mRenderableType; break;
case EGL_MATCH_NATIVE_PIXMAP: *value = false; UNIMPLEMENTED(); break;
case EGL_CONFORMANT: *value = configuration->mConformant; break;
case EGL_MAX_PBUFFER_WIDTH: *value = configuration->mMaxPBufferWidth; break;
case EGL_MAX_PBUFFER_HEIGHT: *value = configuration->mMaxPBufferHeight; break;
case EGL_MAX_PBUFFER_PIXELS: *value = configuration->mMaxPBufferPixels; break;
default:
return false;
}
return true;
}
EGLSurface Display::createWindowSurface(HWND window, EGLConfig config, const EGLint *attribList)
{
const Config *configuration = mConfigSet.get(config);
EGLint postSubBufferSupported = EGL_FALSE;
if (attribList)
{
while (*attribList != EGL_NONE)
{
switch (attribList[0])
{
case EGL_RENDER_BUFFER:
switch (attribList[1])
{
case EGL_BACK_BUFFER:
break;
case EGL_SINGLE_BUFFER:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE); // Rendering directly to front buffer not supported
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_POST_SUB_BUFFER_SUPPORTED_NV:
postSubBufferSupported = attribList[1];
break;
case EGL_VG_COLORSPACE:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
case EGL_VG_ALPHA_FORMAT:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
attribList += 2;
}
}
if (hasExistingWindowSurface(window))
{
return error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
if (mRenderer->testDeviceLost(false))
{
if (!restoreLostDevice())
return EGL_NO_SURFACE;
}
Surface *surface = new Surface(this, configuration, window, postSubBufferSupported);
if (!surface->initialize())
{
delete surface;
return EGL_NO_SURFACE;
}
mSurfaceSet.insert(surface);
return success(surface);
}
EGLSurface Display::createOffscreenSurface(EGLConfig config, HANDLE shareHandle, const EGLint *attribList)
{
EGLint width = 0, height = 0;
EGLenum textureFormat = EGL_NO_TEXTURE;
EGLenum textureTarget = EGL_NO_TEXTURE;
const Config *configuration = mConfigSet.get(config);
if (attribList)
{
while (*attribList != EGL_NONE)
{
switch (attribList[0])
{
case EGL_WIDTH:
width = attribList[1];
break;
case EGL_HEIGHT:
height = attribList[1];
break;
case EGL_LARGEST_PBUFFER:
if (attribList[1] != EGL_FALSE)
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_FORMAT:
switch (attribList[1])
{
case EGL_NO_TEXTURE:
case EGL_TEXTURE_RGB:
case EGL_TEXTURE_RGBA:
textureFormat = attribList[1];
break;
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_TEXTURE_TARGET:
switch (attribList[1])
{
case EGL_NO_TEXTURE:
case EGL_TEXTURE_2D:
textureTarget = attribList[1];
break;
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_MIPMAP_TEXTURE:
if (attribList[1] != EGL_FALSE)
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
break;
case EGL_VG_COLORSPACE:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
case EGL_VG_ALPHA_FORMAT:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
attribList += 2;
}
}
if (width < 0 || height < 0)
{
return error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
if (width == 0 || height == 0)
{
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
if (textureFormat != EGL_NO_TEXTURE && !mRenderer->getNonPower2TextureSupport() && (!gl::isPow2(width) || !gl::isPow2(height)))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if ((textureFormat != EGL_NO_TEXTURE && textureTarget == EGL_NO_TEXTURE) ||
(textureFormat == EGL_NO_TEXTURE && textureTarget != EGL_NO_TEXTURE))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if (!(configuration->mSurfaceType & EGL_PBUFFER_BIT))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if ((textureFormat == EGL_TEXTURE_RGB && configuration->mBindToTextureRGB != EGL_TRUE) ||
(textureFormat == EGL_TEXTURE_RGBA && configuration->mBindToTextureRGBA != EGL_TRUE))
{
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
if (mRenderer->testDeviceLost(false))
{
if (!restoreLostDevice())
return EGL_NO_SURFACE;
}
Surface *surface = new Surface(this, configuration, shareHandle, width, height, textureFormat, textureTarget);
if (!surface->initialize())
{
delete surface;
return EGL_NO_SURFACE;
}
mSurfaceSet.insert(surface);
return success(surface);
}
EGLContext Display::createContext(EGLConfig configHandle, const gl::Context *shareContext, bool notifyResets, bool robustAccess)
{
if (!mRenderer)
{
return NULL;
}
else if (mRenderer->testDeviceLost(false)) // Lost device
{
if (!restoreLostDevice())
return NULL;
}
gl::Context *context = glCreateContext(shareContext, mRenderer, notifyResets, robustAccess);
mContextSet.insert(context);
return context;
}
bool Display::restoreLostDevice()
{
for (ContextSet::iterator ctx = mContextSet.begin(); ctx != mContextSet.end(); ctx++)
{
if ((*ctx)->isResetNotificationEnabled())
return false; // If reset notifications have been requested, application must delete all contexts first
}
// Release surface resources to make the Reset() succeed
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->release();
}
if (!mRenderer->resetDevice())
{
return error(EGL_BAD_ALLOC, false);
}
// Restore any surfaces that may have been lost
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->resetSwapChain();
}
return true;
}
void Display::destroySurface(egl::Surface *surface)
{
delete surface;
mSurfaceSet.erase(surface);
}
void Display::destroyContext(gl::Context *context)
{
glDestroyContext(context);
mContextSet.erase(context);
}
void Display::notifyDeviceLost()
{
for (ContextSet::iterator context = mContextSet.begin(); context != mContextSet.end(); context++)
{
(*context)->markContextLost();
}
egl::error(EGL_CONTEXT_LOST);
}
void Display::recreateSwapChains()
{
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->getSwapChain()->recreate();
}
}
bool Display::isInitialized() const
{
return mRenderer != NULL && mConfigSet.size() > 0;
}
bool Display::isValidConfig(EGLConfig config)
{
return mConfigSet.get(config) != NULL;
}
bool Display::isValidContext(gl::Context *context)
{
return mContextSet.find(context) != mContextSet.end();
}
bool Display::isValidSurface(egl::Surface *surface)
{
return mSurfaceSet.find(surface) != mSurfaceSet.end();
}
bool Display::hasExistingWindowSurface(HWND window)
{
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
if ((*surface)->getWindowHandle() == window)
{
return true;
}
}
return false;
}
void Display::initExtensionString()
{
HMODULE swiftShader = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
bool shareHandleSupported = mRenderer->getShareHandleSupport();
mExtensionString = "";
// Multi-vendor (EXT) extensions
mExtensionString += "EGL_EXT_create_context_robustness ";
// ANGLE-specific extensions
if (shareHandleSupported)
{
mExtensionString += "EGL_ANGLE_d3d_share_handle_client_buffer ";
}
mExtensionString += "EGL_ANGLE_query_surface_pointer ";
if (swiftShader)
{
mExtensionString += "EGL_ANGLE_software_display ";
}
if (shareHandleSupported)
{
mExtensionString += "EGL_ANGLE_surface_d3d_texture_2d_share_handle ";
}
if (mRenderer->getPostSubBufferSupport())
{
mExtensionString += "EGL_NV_post_sub_buffer";
}
std::string::size_type end = mExtensionString.find_last_not_of(' ');
if (end != std::string::npos)
{
mExtensionString.resize(end+1);
}
}
const char *Display::getExtensionString() const
{
return mExtensionString.c_str();
}
void Display::initVendorString()
{
mVendorString = "Google Inc.";
LUID adapterLuid = {0};
if (mRenderer && mRenderer->getLUID(&adapterLuid))
{
char adapterLuidString[64];
sprintf_s(adapterLuidString, sizeof(adapterLuidString), " (adapter LUID: %08x%08x)", adapterLuid.HighPart, adapterLuid.LowPart);
mVendorString += adapterLuidString;
}
}
const char *Display::getVendorString() const
{
return mVendorString.c_str();
}
}
| C++ |
//
// 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.
//
// main.cpp: DLL entry point and management of thread-local data.
#include "libEGL/main.h"
#include "common/debug.h"
static DWORD currentTLS = TLS_OUT_OF_INDEXES;
extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
#if !defined(ANGLE_DISABLE_TRACE)
FILE *debug = fopen(TRACE_OUTPUT_FILE, "rt");
if (debug)
{
fclose(debug);
debug = fopen(TRACE_OUTPUT_FILE, "wt"); // Erase
if (debug)
{
fclose(debug);
}
}
#endif
currentTLS = TlsAlloc();
if (currentTLS == TLS_OUT_OF_INDEXES)
{
return FALSE;
}
}
// Fall throught to initialize index
case DLL_THREAD_ATTACH:
{
egl::Current *current = (egl::Current*)LocalAlloc(LPTR, sizeof(egl::Current));
if (current)
{
TlsSetValue(currentTLS, current);
current->error = EGL_SUCCESS;
current->API = EGL_OPENGL_ES_API;
current->display = EGL_NO_DISPLAY;
current->drawSurface = EGL_NO_SURFACE;
current->readSurface = EGL_NO_SURFACE;
}
}
break;
case DLL_THREAD_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
}
break;
case DLL_PROCESS_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
TlsFree(currentTLS);
}
break;
default:
break;
}
return TRUE;
}
namespace egl
{
void setCurrentError(EGLint error)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->error = error;
}
EGLint getCurrentError()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->error;
}
void setCurrentAPI(EGLenum API)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->API = API;
}
EGLenum getCurrentAPI()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->API;
}
void setCurrentDisplay(EGLDisplay dpy)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->display = dpy;
}
EGLDisplay getCurrentDisplay()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->display;
}
void setCurrentDrawSurface(EGLSurface surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->drawSurface = surface;
}
EGLSurface getCurrentDrawSurface()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->drawSurface;
}
void setCurrentReadSurface(EGLSurface surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->readSurface = surface;
}
EGLSurface getCurrentReadSurface()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->readSurface;
}
void error(EGLint errorCode)
{
egl::setCurrentError(errorCode);
}
}
| C++ |
//
// 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.
//
// main.h: Management of thread-local data.
#ifndef LIBEGL_MAIN_H_
#define LIBEGL_MAIN_H_
#define EGLAPI
#include <EGL/egl.h>
#include <EGL/eglext.h>
namespace egl
{
struct Current
{
EGLint error;
EGLenum API;
EGLDisplay display;
EGLSurface drawSurface;
EGLSurface readSurface;
};
void setCurrentError(EGLint error);
EGLint getCurrentError();
void setCurrentAPI(EGLenum API);
EGLenum getCurrentAPI();
void setCurrentDisplay(EGLDisplay dpy);
EGLDisplay getCurrentDisplay();
void setCurrentDrawSurface(EGLSurface surface);
EGLSurface getCurrentDrawSurface();
void setCurrentReadSurface(EGLSurface surface);
EGLSurface getCurrentReadSurface();
void error(EGLint errorCode);
template<class T>
const T &error(EGLint errorCode, const T &returnValue)
{
error(errorCode);
return returnValue;
}
template<class T>
const T &success(const T &returnValue)
{
egl::setCurrentError(EGL_SUCCESS);
return returnValue;
}
}
#endif // LIBEGL_MAIN_H_
| C++ |
//
// 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.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
HWND Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
| C++ |
//
// 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.
//
// Surface.h: Defines the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#ifndef LIBEGL_SURFACE_H_
#define LIBEGL_SURFACE_H_
#define EGLAPI
#include <EGL/egl.h>
#include "common/angleutils.h"
namespace gl
{
class Texture2D;
}
namespace rx
{
class Renderer;
class SwapChain;
}
namespace egl
{
class Display;
class Config;
class Surface
{
public:
Surface(Display *display, const egl::Config *config, HWND window, EGLint postSubBufferSupported);
Surface(Display *display, const egl::Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureTarget);
~Surface();
bool initialize();
void release();
bool resetSwapChain();
HWND getWindowHandle();
bool swap();
bool postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height);
virtual EGLint getWidth() const;
virtual EGLint getHeight() const;
virtual EGLint isPostSubBufferSupported() const;
virtual rx::SwapChain *getSwapChain() const;
void setSwapInterval(EGLint interval);
bool checkForOutOfDateSwapChain(); // Returns true if swapchain changed due to resize or interval update
virtual EGLenum getTextureFormat() const;
virtual EGLenum getTextureTarget() const;
virtual EGLenum getFormat() const;
virtual void setBoundTexture(gl::Texture2D *texture);
virtual gl::Texture2D *getBoundTexture() const;
private:
DISALLOW_COPY_AND_ASSIGN(Surface);
Display *const mDisplay;
rx::Renderer *mRenderer;
HANDLE mShareHandle;
rx::SwapChain *mSwapChain;
void subclassWindow();
void unsubclassWindow();
bool resizeSwapChain(int backbufferWidth, int backbufferHeight);
bool resetSwapChain(int backbufferWidth, int backbufferHeight);
bool swapRect(EGLint x, EGLint y, EGLint width, EGLint height);
const HWND mWindow; // Window that the surface is created for.
bool mWindowSubclassed; // Indicates whether we successfully subclassed mWindow for WM_RESIZE hooking
const egl::Config *mConfig; // EGL config surface was created with
EGLint mHeight; // Height of surface
EGLint mWidth; // Width of surface
// EGLint horizontalResolution; // Horizontal dot pitch
// EGLint verticalResolution; // Vertical dot pitch
// EGLBoolean largestPBuffer; // If true, create largest pbuffer possible
// EGLBoolean mipmapTexture; // True if texture has mipmaps
// EGLint mipmapLevel; // Mipmap level to render to
// EGLenum multisampleResolve; // Multisample resolve behavior
EGLint mPixelAspectRatio; // Display aspect ratio
EGLenum mRenderBuffer; // Render buffer
EGLenum mSwapBehavior; // Buffer swap behavior
EGLenum mTextureFormat; // Format of texture: RGB, RGBA, or no texture
EGLenum mTextureTarget; // Type of texture: 2D or no texture
// EGLenum vgAlphaFormat; // Alpha format for OpenVG
// EGLenum vgColorSpace; // Color space for OpenVG
EGLint mSwapInterval;
EGLint mPostSubBufferSupported;
bool mSwapIntervalDirty;
gl::Texture2D *mTexture;
};
}
#endif // LIBEGL_SURFACE_H_
| C++ |
//
// 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.
//
// Config.cpp: Implements the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.4] section 3.4 page 15.
#include "libEGL/Config.h"
#include <algorithm>
#include <vector>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "common/debug.h"
using namespace std;
namespace egl
{
Config::Config(rx::ConfigDesc desc, EGLint minInterval, EGLint maxInterval, EGLint texWidth, EGLint texHeight)
: mRenderTargetFormat(desc.renderTargetFormat), mDepthStencilFormat(desc.depthStencilFormat), mMultiSample(desc.multiSample)
{
mBindToTextureRGB = EGL_FALSE;
mBindToTextureRGBA = EGL_FALSE;
switch (desc.renderTargetFormat)
{
case GL_RGB5_A1:
mBufferSize = 16;
mRedSize = 5;
mGreenSize = 5;
mBlueSize = 5;
mAlphaSize = 1;
break;
case GL_RGBA8_OES:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 8;
mBindToTextureRGBA = true;
break;
case GL_RGB565:
mBufferSize = 16;
mRedSize = 5;
mGreenSize = 6;
mBlueSize = 5;
mAlphaSize = 0;
break;
case GL_RGB8_OES:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 0;
mBindToTextureRGB = true;
break;
case GL_BGRA8_EXT:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 8;
mBindToTextureRGBA = true;
break;
default:
UNREACHABLE(); // Other formats should not be valid
}
mLuminanceSize = 0;
mAlphaMaskSize = 0;
mColorBufferType = EGL_RGB_BUFFER;
mConfigCaveat = (desc.fastConfig) ? EGL_NONE : EGL_SLOW_CONFIG;
mConfigID = 0;
mConformant = EGL_OPENGL_ES2_BIT;
switch (desc.depthStencilFormat)
{
case GL_NONE:
mDepthSize = 0;
mStencilSize = 0;
break;
case GL_DEPTH_COMPONENT32_OES:
mDepthSize = 32;
mStencilSize = 0;
break;
case GL_DEPTH24_STENCIL8_OES:
mDepthSize = 24;
mStencilSize = 8;
break;
case GL_DEPTH_COMPONENT24_OES:
mDepthSize = 24;
mStencilSize = 0;
break;
case GL_DEPTH_COMPONENT16:
mDepthSize = 16;
mStencilSize = 0;
break;
default:
UNREACHABLE();
}
mLevel = 0;
mMatchNativePixmap = EGL_NONE;
mMaxPBufferWidth = texWidth;
mMaxPBufferHeight = texHeight;
mMaxPBufferPixels = texWidth*texHeight;
mMaxSwapInterval = maxInterval;
mMinSwapInterval = minInterval;
mNativeRenderable = EGL_FALSE;
mNativeVisualID = 0;
mNativeVisualType = 0;
mRenderableType = EGL_OPENGL_ES2_BIT;
mSampleBuffers = desc.multiSample ? 1 : 0;
mSamples = desc.multiSample;
mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
mTransparentType = EGL_NONE;
mTransparentRedValue = 0;
mTransparentGreenValue = 0;
mTransparentBlueValue = 0;
}
EGLConfig Config::getHandle() const
{
return (EGLConfig)(size_t)mConfigID;
}
SortConfig::SortConfig(const EGLint *attribList)
: mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false)
{
scanForWantedComponents(attribList);
}
void SortConfig::scanForWantedComponents(const EGLint *attribList)
{
// [EGL] section 3.4.1 page 24
// Sorting rule #3: by larger total number of color bits, not considering
// components that are 0 or don't-care.
for (const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2)
{
if (attr[1] != 0 && attr[1] != EGL_DONT_CARE)
{
switch (attr[0])
{
case EGL_RED_SIZE: mWantRed = true; break;
case EGL_GREEN_SIZE: mWantGreen = true; break;
case EGL_BLUE_SIZE: mWantBlue = true; break;
case EGL_ALPHA_SIZE: mWantAlpha = true; break;
case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;
}
}
}
}
EGLint SortConfig::wantedComponentsSize(const Config &config) const
{
EGLint total = 0;
if (mWantRed) total += config.mRedSize;
if (mWantGreen) total += config.mGreenSize;
if (mWantBlue) total += config.mBlueSize;
if (mWantAlpha) total += config.mAlphaSize;
if (mWantLuminance) total += config.mLuminanceSize;
return total;
}
bool SortConfig::operator()(const Config *x, const Config *y) const
{
return (*this)(*x, *y);
}
bool SortConfig::operator()(const Config &x, const Config &y) const
{
#define SORT(attribute) \
if (x.attribute != y.attribute) \
{ \
return x.attribute < y.attribute; \
}
META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);
SORT(mConfigCaveat);
META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);
SORT(mColorBufferType);
// By larger total number of color bits, only considering those that are requested to be > 0.
EGLint xComponentsSize = wantedComponentsSize(x);
EGLint yComponentsSize = wantedComponentsSize(y);
if (xComponentsSize != yComponentsSize)
{
return xComponentsSize > yComponentsSize;
}
SORT(mBufferSize);
SORT(mSampleBuffers);
SORT(mSamples);
SORT(mDepthSize);
SORT(mStencilSize);
SORT(mAlphaMaskSize);
SORT(mNativeVisualType);
SORT(mConfigID);
#undef SORT
return false;
}
// We'd like to use SortConfig to also eliminate duplicate configs.
// This works as long as we never have two configs with different per-RGB-component layouts,
// but the same total.
// 5551 and 565 are different because R+G+B is different.
// 5551 and 555 are different because bufferSize is different.
const EGLint ConfigSet::mSortAttribs[] =
{
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_LUMINANCE_SIZE, 1,
// BUT NOT ALPHA
EGL_NONE
};
ConfigSet::ConfigSet()
: mSet(SortConfig(mSortAttribs))
{
}
void ConfigSet::add(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight)
{
Config config(desc, minSwapInterval, maxSwapInterval, texWidth, texHeight);
mSet.insert(config);
}
size_t ConfigSet::size() const
{
return mSet.size();
}
bool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)
{
vector<const Config*> passed;
passed.reserve(mSet.size());
for (Iterator config = mSet.begin(); config != mSet.end(); config++)
{
bool match = true;
const EGLint *attribute = attribList;
while (attribute[0] != EGL_NONE)
{
switch (attribute[0])
{
case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break;
case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break;
case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break;
case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break;
case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break;
case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break;
case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break;
case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == (EGLenum) attribute[1]; break;
case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break;
case EGL_LEVEL: match = config->mLevel >= attribute[1]; break;
case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == (EGLBoolean) attribute[1]; break;
case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break;
case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break;
case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break;
case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break;
case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == (EGLenum) attribute[1]; break;
case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break;
case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break;
case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break;
case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == (EGLBoolean) attribute[1]; break;
case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == (EGLBoolean) attribute[1]; break;
case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break;
case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break;
case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break;
case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break;
case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == (EGLenum) attribute[1]; break;
case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break;
case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break;
case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break;
case EGL_MAX_PBUFFER_WIDTH: match = config->mMaxPBufferWidth >= attribute[1]; break;
case EGL_MAX_PBUFFER_HEIGHT: match = config->mMaxPBufferHeight >= attribute[1]; break;
case EGL_MAX_PBUFFER_PIXELS: match = config->mMaxPBufferPixels >= attribute[1]; break;
default:
return false;
}
if (!match)
{
break;
}
attribute += 2;
}
if (match)
{
passed.push_back(&*config);
}
}
if (configs)
{
sort(passed.begin(), passed.end(), SortConfig(attribList));
EGLint index;
for (index = 0; index < configSize && index < static_cast<EGLint>(passed.size()); index++)
{
configs[index] = passed[index]->getHandle();
}
*numConfig = index;
}
else
{
*numConfig = passed.size();
}
return true;
}
const egl::Config *ConfigSet::get(EGLConfig configHandle)
{
for (Iterator config = mSet.begin(); config != mSet.end(); config++)
{
if (config->getHandle() == configHandle)
{
return &(*config);
}
}
return NULL;
}
}
| C++ |
//
// 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.
//
// libEGL.cpp: Implements the exported EGL functions.
#include <exception>
#include "common/debug.h"
#include "common/version.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
#include "libEGL/Surface.h"
bool validateDisplay(egl::Display *display)
{
if (display == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, false);
}
if (!display->isInitialized())
{
return egl::error(EGL_NOT_INITIALIZED, false);
}
return true;
}
bool validateConfig(egl::Display *display, EGLConfig config)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidConfig(config))
{
return egl::error(EGL_BAD_CONFIG, false);
}
return true;
}
bool validateContext(egl::Display *display, gl::Context *context)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidContext(context))
{
return egl::error(EGL_BAD_CONTEXT, false);
}
return true;
}
bool validateSurface(egl::Display *display, egl::Surface *surface)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidSurface(surface))
{
return egl::error(EGL_BAD_SURFACE, false);
}
return true;
}
extern "C"
{
EGLint __stdcall eglGetError(void)
{
EVENT("()");
EGLint error = egl::getCurrentError();
if (error != EGL_SUCCESS)
{
egl::setCurrentError(EGL_SUCCESS);
}
return error;
}
EGLDisplay __stdcall eglGetDisplay(EGLNativeDisplayType display_id)
{
EVENT("(EGLNativeDisplayType display_id = 0x%0.8p)", display_id);
try
{
return egl::Display::getDisplay(display_id);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_DISPLAY);
}
}
EGLBoolean __stdcall eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint *major = 0x%0.8p, EGLint *minor = 0x%0.8p)",
dpy, major, minor);
try
{
if (dpy == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!display->initialize())
{
return egl::error(EGL_NOT_INITIALIZED, EGL_FALSE);
}
if (major) *major = 1;
if (minor) *minor = 4;
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglTerminate(EGLDisplay dpy)
{
EVENT("(EGLDisplay dpy = 0x%0.8p)", dpy);
try
{
if (dpy == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
display->terminate();
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
const char *__stdcall eglQueryString(EGLDisplay dpy, EGLint name)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint name = %d)", dpy, name);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return NULL;
}
switch (name)
{
case EGL_CLIENT_APIS:
return egl::success("OpenGL_ES");
case EGL_EXTENSIONS:
return egl::success(display->getExtensionString());
case EGL_VENDOR:
return egl::success(display->getVendorString());
case EGL_VERSION:
return egl::success("1.4 (ANGLE " VERSION_STRING ")");
}
return egl::error(EGL_BAD_PARAMETER, (const char*)NULL);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, (const char*)NULL);
}
}
EGLBoolean __stdcall eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig *configs = 0x%0.8p, "
"EGLint config_size = %d, EGLint *num_config = 0x%0.8p)",
dpy, configs, config_size, num_config);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
if (!num_config)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
const EGLint attribList[] = {EGL_NONE};
if (!display->getConfigs(configs, attribList, config_size, num_config))
{
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p, "
"EGLConfig *configs = 0x%0.8p, EGLint config_size = %d, EGLint *num_config = 0x%0.8p)",
dpy, attrib_list, configs, config_size, num_config);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
if (!num_config)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
const EGLint attribList[] = {EGL_NONE};
if (!attrib_list)
{
attrib_list = attribList;
}
display->getConfigs(configs, attrib_list, config_size, num_config);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, config, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_FALSE;
}
if (!display->getConfigAttrib(config, attribute, value))
{
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLSurface __stdcall eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLNativeWindowType win = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, win, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
HWND window = (HWND)win;
if (!IsWindow(window))
{
return egl::error(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
}
return display->createWindowSurface(window, config, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLSurface __stdcall eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p)",
dpy, config, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
return display->createOffscreenSurface(config, NULL, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLSurface __stdcall eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLNativePixmapType pixmap = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, pixmap, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(EGL_NO_SURFACE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLBoolean __stdcall eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p)", dpy, surface);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
display->destroySurface((egl::Surface*)surface);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
switch (attribute)
{
case EGL_VG_ALPHA_FORMAT:
UNIMPLEMENTED(); // FIXME
break;
case EGL_VG_COLORSPACE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_CONFIG_ID:
UNIMPLEMENTED(); // FIXME
break;
case EGL_HEIGHT:
*value = eglSurface->getHeight();
break;
case EGL_HORIZONTAL_RESOLUTION:
UNIMPLEMENTED(); // FIXME
break;
case EGL_LARGEST_PBUFFER:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MIPMAP_TEXTURE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MIPMAP_LEVEL:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MULTISAMPLE_RESOLVE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_PIXEL_ASPECT_RATIO:
UNIMPLEMENTED(); // FIXME
break;
case EGL_RENDER_BUFFER:
UNIMPLEMENTED(); // FIXME
break;
case EGL_SWAP_BEHAVIOR:
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_FORMAT:
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_TARGET:
UNIMPLEMENTED(); // FIXME
break;
case EGL_VERTICAL_RESOLUTION:
UNIMPLEMENTED(); // FIXME
break;
case EGL_WIDTH:
*value = eglSurface->getWidth();
break;
case EGL_POST_SUB_BUFFER_SUPPORTED_NV:
*value = eglSurface->isPostSubBufferSupported();
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglQuerySurfacePointerANGLE(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value)
{
TRACE("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, void **value = 0x%0.8p)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
switch (attribute)
{
case EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE:
{
rx::SwapChain *swapchain = eglSurface->getSwapChain();
*value = (void*) (swapchain ? swapchain->getShareHandle() : NULL);
}
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglBindAPI(EGLenum api)
{
EVENT("(EGLenum api = 0x%X)", api);
try
{
switch (api)
{
case EGL_OPENGL_API:
case EGL_OPENVG_API:
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE); // Not supported by this implementation
case EGL_OPENGL_ES_API:
break;
default:
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
egl::setCurrentAPI(api);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLenum __stdcall eglQueryAPI(void)
{
EVENT("()");
try
{
EGLenum API = egl::getCurrentAPI();
return egl::success(API);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitClient(void)
{
EVENT("()");
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglReleaseThread(void)
{
EVENT("()");
try
{
eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_CONTEXT, EGL_NO_SURFACE, EGL_NO_SURFACE);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLSurface __stdcall eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLenum buftype = 0x%X, EGLClientBuffer buffer = 0x%0.8p, "
"EGLConfig config = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p)",
dpy, buftype, buffer, config, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
if (buftype != EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE || !buffer)
{
return egl::error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
return display->createOffscreenSurface(config, (HANDLE)buffer, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLBoolean __stdcall eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, EGLint value = %d)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint buffer = %d)", dpy, surface, buffer);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (buffer != EGL_BACK_BUFFER)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE || eglSurface->getWindowHandle())
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->getBoundTexture())
{
return egl::error(EGL_BAD_ACCESS, EGL_FALSE);
}
if (eglSurface->getTextureFormat() == EGL_NO_TEXTURE)
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
if (!glBindTexImage(eglSurface))
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint buffer = %d)", dpy, surface, buffer);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (buffer != EGL_BACK_BUFFER)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE || eglSurface->getWindowHandle())
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->getTextureFormat() == EGL_NO_TEXTURE)
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
gl::Texture2D *texture = eglSurface->getBoundTexture();
if (texture)
{
texture->releaseTexImage();
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglSwapInterval(EGLDisplay dpy, EGLint interval)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint interval = %d)", dpy, interval);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
egl::Surface *draw_surface = static_cast<egl::Surface*>(egl::getCurrentDrawSurface());
if (draw_surface == NULL)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
draw_surface->setSwapInterval(interval);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLContext __stdcall eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLContext share_context = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, share_context, attrib_list);
try
{
// Get the requested client version (default is 1) and check it is two.
EGLint client_version = 1;
bool reset_notification = false;
bool robust_access = false;
if (attrib_list)
{
for (const EGLint* attribute = attrib_list; attribute[0] != EGL_NONE; attribute += 2)
{
switch (attribute[0])
{
case EGL_CONTEXT_CLIENT_VERSION:
client_version = attribute[1];
break;
case EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT:
if (attribute[1] == EGL_TRUE)
{
return egl::error(EGL_BAD_CONFIG, EGL_NO_CONTEXT); // Unimplemented
// robust_access = true;
}
else if (attribute[1] != EGL_FALSE)
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
break;
case EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT:
if (attribute[1] == EGL_LOSE_CONTEXT_ON_RESET_EXT)
reset_notification = true;
else if (attribute[1] != EGL_NO_RESET_NOTIFICATION_EXT)
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
}
}
}
if (client_version != 2)
{
return egl::error(EGL_BAD_CONFIG, EGL_NO_CONTEXT);
}
if (share_context && static_cast<gl::Context*>(share_context)->isResetNotificationEnabled() != reset_notification)
{
return egl::error(EGL_BAD_MATCH, EGL_NO_CONTEXT);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_CONTEXT;
}
EGLContext context = display->createContext(config, static_cast<gl::Context*>(share_context), reset_notification, robust_access);
if (context)
return egl::success(context);
else
return egl::error(EGL_CONTEXT_LOST, EGL_NO_CONTEXT);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
}
}
EGLBoolean __stdcall eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLContext ctx = 0x%0.8p)", dpy, ctx);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (!validateContext(display, context))
{
return EGL_FALSE;
}
if (ctx == EGL_NO_CONTEXT)
{
return egl::error(EGL_BAD_CONTEXT, EGL_FALSE);
}
display->destroyContext(context);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface draw = 0x%0.8p, EGLSurface read = 0x%0.8p, EGLContext ctx = 0x%0.8p)",
dpy, draw, read, ctx);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (ctx != EGL_NO_CONTEXT && !validateContext(display, context))
{
return EGL_FALSE;
}
rx::Renderer *renderer = display->getRenderer();
if (renderer->testDeviceLost(true))
{
return EGL_FALSE;
}
if (renderer->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if ((draw != EGL_NO_SURFACE && !validateSurface(display, static_cast<egl::Surface*>(draw))) ||
(read != EGL_NO_SURFACE && !validateSurface(display, static_cast<egl::Surface*>(read))))
{
return EGL_FALSE;
}
if (draw != read)
{
UNIMPLEMENTED(); // FIXME
}
egl::setCurrentDisplay(dpy);
egl::setCurrentDrawSurface(draw);
egl::setCurrentReadSurface(read);
glMakeCurrent(context, display, static_cast<egl::Surface*>(draw));
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLContext __stdcall eglGetCurrentContext(void)
{
EVENT("()");
try
{
EGLContext context = glGetCurrentContext();
return egl::success(context);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
}
}
EGLSurface __stdcall eglGetCurrentSurface(EGLint readdraw)
{
EVENT("(EGLint readdraw = %d)", readdraw);
try
{
if (readdraw == EGL_READ)
{
EGLSurface read = egl::getCurrentReadSurface();
return egl::success(read);
}
else if (readdraw == EGL_DRAW)
{
EGLSurface draw = egl::getCurrentDrawSurface();
return egl::success(draw);
}
else
{
return egl::error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLDisplay __stdcall eglGetCurrentDisplay(void)
{
EVENT("()");
try
{
EGLDisplay dpy = egl::getCurrentDisplay();
return egl::success(dpy);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_DISPLAY);
}
}
EGLBoolean __stdcall eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLContext ctx = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, ctx, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (!validateContext(display, context))
{
return EGL_FALSE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitGL(void)
{
EVENT("()");
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitNative(EGLint engine)
{
EVENT("(EGLint engine = %d)", engine);
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglSwapBuffers(EGLDisplay dpy, EGLSurface surface)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p)", dpy, surface);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->swap())
{
return egl::success(EGL_TRUE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
return EGL_FALSE;
}
EGLBoolean __stdcall eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLNativePixmapType target = 0x%0.8p)", dpy, surface, target);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglPostSubBufferNV(EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint x = %d, EGLint y = %d, EGLint width = %d, EGLint height = %d)", dpy, surface, x, y, width, height);
try
{
if (x < 0 || y < 0 || width < 0 || height < 0)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->postSubBuffer(x, y, width, height))
{
return egl::success(EGL_TRUE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
return EGL_FALSE;
}
__eglMustCastToProperFunctionPointerType __stdcall eglGetProcAddress(const char *procname)
{
EVENT("(const char *procname = \"%s\")", procname);
try
{
struct Extension
{
const char *name;
__eglMustCastToProperFunctionPointerType address;
};
static const Extension eglExtensions[] =
{
{"eglQuerySurfacePointerANGLE", (__eglMustCastToProperFunctionPointerType)eglQuerySurfacePointerANGLE},
{"eglPostSubBufferNV", (__eglMustCastToProperFunctionPointerType)eglPostSubBufferNV},
{"", NULL},
};
for (unsigned int ext = 0; ext < ArraySize(eglExtensions); ext++)
{
if (strcmp(procname, eglExtensions[ext].name) == 0)
{
return (__eglMustCastToProperFunctionPointerType)eglExtensions[ext].address;
}
}
return glGetProcAddress(procname);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, (__eglMustCastToProperFunctionPointerType)NULL);
}
}
}
| C++ |
//
// 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.
//
// RefCountObject.h: Defines the gl::RefCountObject base class that provides
// lifecycle support for GL objects using the traditional BindObject scheme, but
// that need to be reference counted for correct cross-context deletion.
// (Concretely, textures, buffers and renderbuffers.)
#ifndef COMMON_REFCOUNTOBJECT_H_
#define COMMON_REFCOUNTOBJECT_H_
#include <cstddef>
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/debug.h"
class RefCountObject
{
public:
explicit RefCountObject(GLuint id);
virtual ~RefCountObject();
virtual void addRef() const;
virtual void release() const;
GLuint id() const { return mId; }
private:
GLuint mId;
mutable std::size_t mRefCount;
};
class RefCountObjectBindingPointer
{
protected:
RefCountObjectBindingPointer() : mObject(NULL) { }
~RefCountObjectBindingPointer() { ASSERT(mObject == NULL); } // Objects have to be released before the resource manager is destroyed, so they must be explicitly cleaned up.
void set(RefCountObject *newObject);
RefCountObject *get() const { return mObject; }
public:
GLuint id() const { return (mObject != NULL) ? mObject->id() : 0; }
bool operator ! () const { return (get() == NULL); }
private:
RefCountObject *mObject;
};
template <class ObjectType>
class BindingPointer : public RefCountObjectBindingPointer
{
public:
void set(ObjectType *newObject) { RefCountObjectBindingPointer::set(newObject); }
ObjectType *get() const { return static_cast<ObjectType*>(RefCountObjectBindingPointer::get()); }
ObjectType *operator -> () const { return get(); }
};
#endif // COMMON_REFCOUNTOBJECT_H_
| C++ |
#include "precompiled.h"
//
// 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.
//
// RefCountObject.cpp: Defines the gl::RefCountObject base class that provides
// lifecycle support for GL objects using the traditional BindObject scheme, but
// that need to be reference counted for correct cross-context deletion.
// (Concretely, textures, buffers and renderbuffers.)
#include "RefCountObject.h"
RefCountObject::RefCountObject(GLuint id)
{
mId = id;
mRefCount = 0;
}
RefCountObject::~RefCountObject()
{
ASSERT(mRefCount == 0);
}
void RefCountObject::addRef() const
{
mRefCount++;
}
void RefCountObject::release() const
{
ASSERT(mRefCount > 0);
if (--mRefCount == 0)
{
delete this;
}
}
void RefCountObjectBindingPointer::set(RefCountObject *newObject)
{
// addRef first in case newObject == mObject and this is the last reference to it.
if (newObject != NULL) newObject->addRef();
if (mObject != NULL) mObject->release();
mObject = newObject;
}
| C++ |
//
// 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.
//
// debug.cpp: Debugging utilities.
#include "common/debug.h"
#include "common/system.h"
#include <d3d9.h>
namespace gl
{
typedef void (WINAPI *PerfOutputFunction)(D3DCOLOR, LPCWSTR);
static void output(bool traceFileDebugOnly, PerfOutputFunction perfFunc, const char *format, va_list vararg)
{
#if !defined(ANGLE_DISABLE_PERF)
if (perfActive())
{
char message[32768];
int len = vsprintf_s(message, format, vararg);
if (len < 0)
{
return;
}
// There are no ASCII variants of these D3DPERF functions.
wchar_t wideMessage[32768];
for (int i = 0; i < len; ++i)
{
wideMessage[i] = message[i];
}
wideMessage[len] = 0;
perfFunc(0, wideMessage);
}
#endif
#if !defined(ANGLE_DISABLE_TRACE)
#if defined(NDEBUG)
if (traceFileDebugOnly)
{
return;
}
#endif
FILE* file = fopen(TRACE_OUTPUT_FILE, "a");
if (file)
{
vfprintf(file, format, vararg);
fclose(file);
}
#endif
}
void trace(bool traceFileDebugOnly, const char *format, ...)
{
va_list vararg;
va_start(vararg, format);
#if defined(ANGLE_DISABLE_PERF)
output(traceFileDebugOnly, NULL, format, vararg);
#else
output(traceFileDebugOnly, D3DPERF_SetMarker, format, vararg);
#endif
va_end(vararg);
}
bool perfActive()
{
#if defined(ANGLE_DISABLE_PERF)
return false;
#else
static bool active = D3DPERF_GetStatus() != 0;
return active;
#endif
}
ScopedPerfEventHelper::ScopedPerfEventHelper(const char* format, ...)
{
#if !defined(ANGLE_DISABLE_PERF)
#if defined(ANGLE_DISABLE_TRACE)
if (!perfActive())
{
return;
}
#endif
va_list vararg;
va_start(vararg, format);
output(true, reinterpret_cast<PerfOutputFunction>(D3DPERF_BeginEvent), format, vararg);
va_end(vararg);
#endif
}
ScopedPerfEventHelper::~ScopedPerfEventHelper()
{
#if !defined(ANGLE_DISABLE_PERF)
if (perfActive())
{
D3DPERF_EndEvent();
}
#endif
}
}
| C++ |
//
// 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.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
#include <stddef.h>
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
template <typename T, unsigned int N>
void SafeRelease(T (&resourceBlock)[N])
{
for (unsigned int i = 0; i < N; i++)
{
SafeRelease(resourceBlock[i]);
}
}
template <typename T>
void SafeRelease(T& resource)
{
if (resource)
{
resource->Release();
resource = NULL;
}
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
| C++ |
//
// 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.
//
// debug.h: Debugging utilities.
#ifndef COMMON_DEBUG_H_
#define COMMON_DEBUG_H_
#include <stdio.h>
#include <assert.h>
#include "common/angleutils.h"
#if !defined(TRACE_OUTPUT_FILE)
#define TRACE_OUTPUT_FILE "debug.txt"
#endif
namespace gl
{
// Outputs text to the debugging log
void trace(bool traceFileDebugOnly, const char *format, ...);
// Returns whether D3DPERF is active.
bool perfActive();
// Pairs a D3D begin event with an end event.
class ScopedPerfEventHelper
{
public:
ScopedPerfEventHelper(const char* format, ...);
~ScopedPerfEventHelper();
private:
DISALLOW_COPY_AND_ASSIGN(ScopedPerfEventHelper);
};
}
// A macro to output a trace of a function call and its arguments to the debugging log
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define TRACE(message, ...) (void(0))
#else
#define TRACE(message, ...) gl::trace(true, "trace: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to output a function call and its arguments to the debugging log, to denote an item in need of fixing.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define FIXME(message, ...) (void(0))
#else
#define FIXME(message, ...) gl::trace(false, "fixme: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to output a function call and its arguments to the debugging log, in case of error.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define ERR(message, ...) (void(0))
#else
#define ERR(message, ...) gl::trace(false, "err: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to log a performance event around a scope.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define EVENT(message, ...) (void(0))
#elif defined(_MSC_VER)
#define EVENT(message, ...) gl::ScopedPerfEventHelper scopedPerfEventHelper ## __LINE__(__FUNCTION__ message "\n", __VA_ARGS__);
#else
#define EVENT(message, ...) gl::ScopedPerfEventHelper scopedPerfEventHelper(message "\n", ##__VA_ARGS__);
#endif
// A macro asserting a condition and outputting failures to the debug log
#if !defined(NDEBUG)
#define ASSERT(expression) do { \
if(!(expression)) \
ERR("\t! Assert failed in %s(%d): "#expression"\n", __FUNCTION__, __LINE__); \
assert(expression); \
} while(0)
#else
#define ASSERT(expression) (void(0))
#endif
// A macro to indicate unimplemented functionality
#if !defined(NDEBUG)
#define UNIMPLEMENTED() do { \
FIXME("\t! Unimplemented: %s(%d)\n", __FUNCTION__, __LINE__); \
assert(false); \
} while(0)
#else
#define UNIMPLEMENTED() FIXME("\t! Unimplemented: %s(%d)\n", __FUNCTION__, __LINE__)
#endif
// A macro for code which is not expected to be reached under valid assumptions
#if !defined(NDEBUG)
#define UNREACHABLE() do { \
ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__); \
assert(false); \
} while(0)
#else
#define UNREACHABLE() ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__)
#endif
// A macro that determines whether an object has a given runtime type.
#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI))
#define HAS_DYNAMIC_TYPE(type, obj) (dynamic_cast<type >(obj) != NULL)
#else
#define HAS_DYNAMIC_TYPE(type, obj) true
#endif
// A macro functioning as a compile-time assert to validate constant conditions
#define META_ASSERT(condition) typedef int COMPILE_TIME_ASSERT_##__LINE__[static_cast<bool>(condition)?1:-1]
#endif // COMMON_DEBUG_H_
| C++ |
//
// 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.
//
// BinaryStream.h: Provides binary serialization of simple types.
#ifndef LIBGLESV2_BINARYSTREAM_H_
#define LIBGLESV2_BINARYSTREAM_H_
#include "common/angleutils.h"
namespace gl
{
class BinaryInputStream
{
public:
BinaryInputStream(const void *data, size_t length)
{
mError = false;
mOffset = 0;
mData = static_cast<const char*>(data);
mLength = length;
}
template <typename T>
void read(T *v, size_t num)
{
union
{
T dummy; // Compilation error for non-trivial types
} dummy;
(void) dummy;
if (mError)
{
return;
}
size_t length = num * sizeof(T);
if (mOffset + length > mLength)
{
mError = true;
return;
}
memcpy(v, mData + mOffset, length);
mOffset += length;
}
template <typename T>
void read(T * v)
{
read(v, 1);
}
void read(std::string *v)
{
size_t length;
read(&length);
if (mError)
{
return;
}
if (mOffset + length > mLength)
{
mError = true;
return;
}
v->assign(mData + mOffset, length);
mOffset += length;
}
void skip(size_t length)
{
if (mOffset + length > mLength)
{
mError = true;
return;
}
mOffset += length;
}
size_t offset() const
{
return mOffset;
}
bool error() const
{
return mError;
}
bool endOfStream() const
{
return mOffset == mLength;
}
private:
DISALLOW_COPY_AND_ASSIGN(BinaryInputStream);
bool mError;
size_t mOffset;
const char *mData;
size_t mLength;
};
class BinaryOutputStream
{
public:
BinaryOutputStream()
{
}
template <typename T>
void write(const T *v, size_t num)
{
union
{
T dummy; // Compilation error for non-trivial types
} dummy;
(void) dummy;
const char *asBytes = reinterpret_cast<const char*>(v);
mData.insert(mData.end(), asBytes, asBytes + num * sizeof(T));
}
template <typename T>
void write(const T &v)
{
write(&v, 1);
}
void write(const std::string &v)
{
size_t length = v.length();
write(length);
write(v.c_str(), length);
}
size_t length() const
{
return mData.size();
}
const void* data() const
{
return mData.size() ? &mData[0] : NULL;
}
private:
DISALLOW_COPY_AND_ASSIGN(BinaryOutputStream);
std::vector<char> mData;
};
}
#endif // LIBGLESV2_BINARYSTREAM_H_
| C++ |
//
// 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.cpp: Precompiled header source file for libGLESv2.
#include "precompiled.h"
| C++ |
#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.
//
// Renderbuffer.cpp: the gl::Renderbuffer class and its derived classes
// Colorbuffer, Depthbuffer and Stencilbuffer. Implements GL renderbuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4.3 page 108.
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/renderer/RenderTarget.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/utilities.h"
namespace gl
{
unsigned int RenderbufferStorage::mCurrentSerial = 1;
RenderbufferInterface::RenderbufferInterface()
{
}
// The default case for classes inherited from RenderbufferInterface is not to
// need to do anything upon the reference count to the parent Renderbuffer incrementing
// or decrementing.
void RenderbufferInterface::addProxyRef(const Renderbuffer *proxy)
{
}
void RenderbufferInterface::releaseProxy(const Renderbuffer *proxy)
{
}
GLuint RenderbufferInterface::getRedSize() const
{
return gl::GetRedSize(getActualFormat());
}
GLuint RenderbufferInterface::getGreenSize() const
{
return gl::GetGreenSize(getActualFormat());
}
GLuint RenderbufferInterface::getBlueSize() const
{
return gl::GetBlueSize(getActualFormat());
}
GLuint RenderbufferInterface::getAlphaSize() const
{
return gl::GetAlphaSize(getActualFormat());
}
GLuint RenderbufferInterface::getDepthSize() const
{
return gl::GetDepthSize(getActualFormat());
}
GLuint RenderbufferInterface::getStencilSize() const
{
return gl::GetStencilSize(getActualFormat());
}
///// RenderbufferTexture2D Implementation ////////
RenderbufferTexture2D::RenderbufferTexture2D(Texture2D *texture, GLenum target) : mTarget(target)
{
mTexture2D.set(texture);
}
RenderbufferTexture2D::~RenderbufferTexture2D()
{
mTexture2D.set(NULL);
}
// Textures need to maintain their own reference count for references via
// Renderbuffers acting as proxies. Here, we notify the texture of a reference.
void RenderbufferTexture2D::addProxyRef(const Renderbuffer *proxy)
{
mTexture2D->addProxyRef(proxy);
}
void RenderbufferTexture2D::releaseProxy(const Renderbuffer *proxy)
{
mTexture2D->releaseProxy(proxy);
}
rx::RenderTarget *RenderbufferTexture2D::getRenderTarget()
{
return mTexture2D->getRenderTarget(mTarget);
}
rx::RenderTarget *RenderbufferTexture2D::getDepthStencil()
{
return mTexture2D->getDepthStencil(mTarget);
}
GLsizei RenderbufferTexture2D::getWidth() const
{
return mTexture2D->getWidth(0);
}
GLsizei RenderbufferTexture2D::getHeight() const
{
return mTexture2D->getHeight(0);
}
GLenum RenderbufferTexture2D::getInternalFormat() const
{
return mTexture2D->getInternalFormat(0);
}
GLenum RenderbufferTexture2D::getActualFormat() const
{
return mTexture2D->getActualFormat(0);
}
GLsizei RenderbufferTexture2D::getSamples() const
{
return 0;
}
unsigned int RenderbufferTexture2D::getSerial() const
{
return mTexture2D->getRenderTargetSerial(mTarget);
}
///// RenderbufferTextureCubeMap Implementation ////////
RenderbufferTextureCubeMap::RenderbufferTextureCubeMap(TextureCubeMap *texture, GLenum target) : mTarget(target)
{
mTextureCubeMap.set(texture);
}
RenderbufferTextureCubeMap::~RenderbufferTextureCubeMap()
{
mTextureCubeMap.set(NULL);
}
// Textures need to maintain their own reference count for references via
// Renderbuffers acting as proxies. Here, we notify the texture of a reference.
void RenderbufferTextureCubeMap::addProxyRef(const Renderbuffer *proxy)
{
mTextureCubeMap->addProxyRef(proxy);
}
void RenderbufferTextureCubeMap::releaseProxy(const Renderbuffer *proxy)
{
mTextureCubeMap->releaseProxy(proxy);
}
rx::RenderTarget *RenderbufferTextureCubeMap::getRenderTarget()
{
return mTextureCubeMap->getRenderTarget(mTarget);
}
rx::RenderTarget *RenderbufferTextureCubeMap::getDepthStencil()
{
return NULL;
}
GLsizei RenderbufferTextureCubeMap::getWidth() const
{
return mTextureCubeMap->getWidth(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLsizei RenderbufferTextureCubeMap::getHeight() const
{
return mTextureCubeMap->getHeight(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLenum RenderbufferTextureCubeMap::getInternalFormat() const
{
return mTextureCubeMap->getInternalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLenum RenderbufferTextureCubeMap::getActualFormat() const
{
return mTextureCubeMap->getActualFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLsizei RenderbufferTextureCubeMap::getSamples() const
{
return 0;
}
unsigned int RenderbufferTextureCubeMap::getSerial() const
{
return mTextureCubeMap->getRenderTargetSerial(mTarget);
}
////// Renderbuffer Implementation //////
Renderbuffer::Renderbuffer(rx::Renderer *renderer, GLuint id, RenderbufferInterface *instance) : RefCountObject(id)
{
ASSERT(instance != NULL);
mInstance = instance;
}
Renderbuffer::~Renderbuffer()
{
delete mInstance;
}
// The RenderbufferInterface contained in this Renderbuffer may need to maintain
// its own reference count, so we pass it on here.
void Renderbuffer::addRef() const
{
mInstance->addProxyRef(this);
RefCountObject::addRef();
}
void Renderbuffer::release() const
{
mInstance->releaseProxy(this);
RefCountObject::release();
}
rx::RenderTarget *Renderbuffer::getRenderTarget()
{
return mInstance->getRenderTarget();
}
rx::RenderTarget *Renderbuffer::getDepthStencil()
{
return mInstance->getDepthStencil();
}
GLsizei Renderbuffer::getWidth() const
{
return mInstance->getWidth();
}
GLsizei Renderbuffer::getHeight() const
{
return mInstance->getHeight();
}
GLenum Renderbuffer::getInternalFormat() const
{
return mInstance->getInternalFormat();
}
GLenum Renderbuffer::getActualFormat() const
{
return mInstance->getActualFormat();
}
GLuint Renderbuffer::getRedSize() const
{
return mInstance->getRedSize();
}
GLuint Renderbuffer::getGreenSize() const
{
return mInstance->getGreenSize();
}
GLuint Renderbuffer::getBlueSize() const
{
return mInstance->getBlueSize();
}
GLuint Renderbuffer::getAlphaSize() const
{
return mInstance->getAlphaSize();
}
GLuint Renderbuffer::getDepthSize() const
{
return mInstance->getDepthSize();
}
GLuint Renderbuffer::getStencilSize() const
{
return mInstance->getStencilSize();
}
GLsizei Renderbuffer::getSamples() const
{
return mInstance->getSamples();
}
unsigned int Renderbuffer::getSerial() const
{
return mInstance->getSerial();
}
void Renderbuffer::setStorage(RenderbufferStorage *newStorage)
{
ASSERT(newStorage != NULL);
delete mInstance;
mInstance = newStorage;
}
RenderbufferStorage::RenderbufferStorage() : mSerial(issueSerial())
{
mWidth = 0;
mHeight = 0;
mInternalFormat = GL_RGBA4;
mActualFormat = GL_RGBA8_OES;
mSamples = 0;
}
RenderbufferStorage::~RenderbufferStorage()
{
}
rx::RenderTarget *RenderbufferStorage::getRenderTarget()
{
return NULL;
}
rx::RenderTarget *RenderbufferStorage::getDepthStencil()
{
return NULL;
}
GLsizei RenderbufferStorage::getWidth() const
{
return mWidth;
}
GLsizei RenderbufferStorage::getHeight() const
{
return mHeight;
}
GLenum RenderbufferStorage::getInternalFormat() const
{
return mInternalFormat;
}
GLenum RenderbufferStorage::getActualFormat() const
{
return mActualFormat;
}
GLsizei RenderbufferStorage::getSamples() const
{
return mSamples;
}
unsigned int RenderbufferStorage::getSerial() const
{
return mSerial;
}
unsigned int RenderbufferStorage::issueSerial()
{
return mCurrentSerial++;
}
unsigned int RenderbufferStorage::issueCubeSerials()
{
unsigned int firstSerial = mCurrentSerial;
mCurrentSerial += 6;
return firstSerial;
}
Colorbuffer::Colorbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain)
{
mRenderTarget = renderer->createRenderTarget(swapChain, false);
if (mRenderTarget)
{
mWidth = mRenderTarget->getWidth();
mHeight = mRenderTarget->getHeight();
mInternalFormat = mRenderTarget->getInternalFormat();
mActualFormat = mRenderTarget->getActualFormat();
mSamples = mRenderTarget->getSamples();
}
}
Colorbuffer::Colorbuffer(rx::Renderer *renderer, int width, int height, GLenum format, GLsizei samples) : mRenderTarget(NULL)
{
mRenderTarget = renderer->createRenderTarget(width, height, format, samples, false);
if (mRenderTarget)
{
mWidth = width;
mHeight = height;
mInternalFormat = format;
mActualFormat = mRenderTarget->getActualFormat();
mSamples = mRenderTarget->getSamples();
}
}
Colorbuffer::~Colorbuffer()
{
if (mRenderTarget)
{
delete mRenderTarget;
}
}
rx::RenderTarget *Colorbuffer::getRenderTarget()
{
if (mRenderTarget)
{
return mRenderTarget;
}
return NULL;
}
DepthStencilbuffer::DepthStencilbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain)
{
mDepthStencil = renderer->createRenderTarget(swapChain, true);
if (mDepthStencil)
{
mWidth = mDepthStencil->getWidth();
mHeight = mDepthStencil->getHeight();
mInternalFormat = mDepthStencil->getInternalFormat();
mSamples = mDepthStencil->getSamples();
mActualFormat = mDepthStencil->getActualFormat();
}
}
DepthStencilbuffer::DepthStencilbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples)
{
mDepthStencil = renderer->createRenderTarget(width, height, GL_DEPTH24_STENCIL8_OES, samples, true);
mWidth = mDepthStencil->getWidth();
mHeight = mDepthStencil->getHeight();
mInternalFormat = GL_DEPTH24_STENCIL8_OES;
mActualFormat = mDepthStencil->getActualFormat();
mSamples = mDepthStencil->getSamples();
}
DepthStencilbuffer::~DepthStencilbuffer()
{
if (mDepthStencil)
{
delete mDepthStencil;
}
}
rx::RenderTarget *DepthStencilbuffer::getDepthStencil()
{
if (mDepthStencil)
{
return mDepthStencil;
}
return NULL;
}
Depthbuffer::Depthbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples) : DepthStencilbuffer(renderer, width, height, samples)
{
if (mDepthStencil)
{
mInternalFormat = GL_DEPTH_COMPONENT16; // If the renderbuffer parameters are queried, the calling function
// will expect one of the valid renderbuffer formats for use in
// glRenderbufferStorage
}
}
Depthbuffer::~Depthbuffer()
{
}
Stencilbuffer::Stencilbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples) : DepthStencilbuffer(renderer, width, height, samples)
{
if (mDepthStencil)
{
mInternalFormat = GL_STENCIL_INDEX8; // If the renderbuffer parameters are queried, the calling function
// will expect one of the valid renderbuffer formats for use in
// glRenderbufferStorage
}
}
Stencilbuffer::~Stencilbuffer()
{
}
}
| C++ |
#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.
//
// Query.cpp: Implements the gl::Query class
#include "libGLESv2/Query.h"
#include "libGLESv2/renderer/QueryImpl.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Query::Query(rx::Renderer *renderer, GLenum type, GLuint id) : RefCountObject(id)
{
mQuery = renderer->createQuery(type);
}
Query::~Query()
{
delete mQuery;
}
void Query::begin()
{
mQuery->begin();
}
void Query::end()
{
mQuery->end();
}
GLuint Query::getResult()
{
return mQuery->getResult();
}
GLboolean Query::isResultAvailable()
{
return mQuery->isResultAvailable();
}
GLenum Query::getType() const
{
return mQuery->getType();
}
}
| C++ |
//
// 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.
//
// Framebuffer.h: Defines the gl::Framebuffer class. Implements GL framebuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
#ifndef LIBGLESV2_FRAMEBUFFER_H_
#define LIBGLESV2_FRAMEBUFFER_H_
#include "common/angleutils.h"
#include "common/RefCountObject.h"
#include "constants.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class Renderbuffer;
class Colorbuffer;
class Depthbuffer;
class Stencilbuffer;
class DepthStencilbuffer;
class Framebuffer
{
public:
explicit Framebuffer(rx::Renderer *renderer);
virtual ~Framebuffer();
void setColorbuffer(unsigned int colorAttachment, GLenum type, GLuint colorbuffer);
void setDepthbuffer(GLenum type, GLuint depthbuffer);
void setStencilbuffer(GLenum type, GLuint stencilbuffer);
void detachTexture(GLuint texture);
void detachRenderbuffer(GLuint renderbuffer);
unsigned int getRenderTargetSerial(unsigned int colorAttachment) const;
unsigned int getDepthbufferSerial() const;
unsigned int getStencilbufferSerial() const;
Renderbuffer *getColorbuffer(unsigned int colorAttachment) const;
Renderbuffer *getDepthbuffer() const;
Renderbuffer *getStencilbuffer() const;
Renderbuffer *getDepthOrStencilbuffer() const;
Renderbuffer *getReadColorbuffer() const;
GLenum getReadColorbufferType() const;
Renderbuffer *getFirstColorbuffer() const;
GLenum getColorbufferType(unsigned int colorAttachment) const;
GLenum getDepthbufferType() const;
GLenum getStencilbufferType() const;
GLuint getColorbufferHandle(unsigned int colorAttachment) const;
GLuint getDepthbufferHandle() const;
GLuint getStencilbufferHandle() const;
GLenum getDrawBufferState(unsigned int colorAttachment) const;
void setDrawBufferState(unsigned int colorAttachment, GLenum drawBuffer);
bool isEnabledColorAttachment(unsigned int colorAttachment) const;
bool hasEnabledColorAttachment() const;
bool hasStencil() const;
int getSamples() const;
bool usingExtendedDrawBuffers() const;
virtual GLenum completeness() const;
protected:
GLenum mColorbufferTypes[IMPLEMENTATION_MAX_DRAW_BUFFERS];
BindingPointer<Renderbuffer> mColorbufferPointers[IMPLEMENTATION_MAX_DRAW_BUFFERS];
GLenum mDrawBufferStates[IMPLEMENTATION_MAX_DRAW_BUFFERS];
GLenum mReadBufferState;
GLenum mDepthbufferType;
BindingPointer<Renderbuffer> mDepthbufferPointer;
GLenum mStencilbufferType;
BindingPointer<Renderbuffer> mStencilbufferPointer;
rx::Renderer *mRenderer;
private:
DISALLOW_COPY_AND_ASSIGN(Framebuffer);
Renderbuffer *lookupRenderbuffer(GLenum type, GLuint handle) const;
};
class DefaultFramebuffer : public Framebuffer
{
public:
DefaultFramebuffer(rx::Renderer *Renderer, Colorbuffer *colorbuffer, DepthStencilbuffer *depthStencil);
virtual GLenum completeness() const;
private:
DISALLOW_COPY_AND_ASSIGN(DefaultFramebuffer);
};
}
#endif // LIBGLESV2_FRAMEBUFFER_H_
| C++ |
#include "precompiled.h"
//
// 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.
//
// ResourceManager.cpp: Implements the gl::ResourceManager class, which tracks and
// retrieves objects which may be shared by multiple Contexts.
#include "libGLESv2/ResourceManager.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Shader.h"
#include "libGLESv2/Texture.h"
namespace gl
{
ResourceManager::ResourceManager(rx::Renderer *renderer)
{
mRefCount = 1;
mRenderer = renderer;
}
ResourceManager::~ResourceManager()
{
while (!mBufferMap.empty())
{
deleteBuffer(mBufferMap.begin()->first);
}
while (!mProgramMap.empty())
{
deleteProgram(mProgramMap.begin()->first);
}
while (!mShaderMap.empty())
{
deleteShader(mShaderMap.begin()->first);
}
while (!mRenderbufferMap.empty())
{
deleteRenderbuffer(mRenderbufferMap.begin()->first);
}
while (!mTextureMap.empty())
{
deleteTexture(mTextureMap.begin()->first);
}
}
void ResourceManager::addRef()
{
mRefCount++;
}
void ResourceManager::release()
{
if (--mRefCount == 0)
{
delete this;
}
}
// Returns an unused buffer name
GLuint ResourceManager::createBuffer()
{
GLuint handle = mBufferHandleAllocator.allocate();
mBufferMap[handle] = NULL;
return handle;
}
// Returns an unused shader/program name
GLuint ResourceManager::createShader(GLenum type)
{
GLuint handle = mProgramShaderHandleAllocator.allocate();
if (type == GL_VERTEX_SHADER)
{
mShaderMap[handle] = new VertexShader(this, mRenderer, handle);
}
else if (type == GL_FRAGMENT_SHADER)
{
mShaderMap[handle] = new FragmentShader(this, mRenderer, handle);
}
else UNREACHABLE();
return handle;
}
// Returns an unused program/shader name
GLuint ResourceManager::createProgram()
{
GLuint handle = mProgramShaderHandleAllocator.allocate();
mProgramMap[handle] = new Program(mRenderer, this, handle);
return handle;
}
// Returns an unused texture name
GLuint ResourceManager::createTexture()
{
GLuint handle = mTextureHandleAllocator.allocate();
mTextureMap[handle] = NULL;
return handle;
}
// Returns an unused renderbuffer name
GLuint ResourceManager::createRenderbuffer()
{
GLuint handle = mRenderbufferHandleAllocator.allocate();
mRenderbufferMap[handle] = NULL;
return handle;
}
void ResourceManager::deleteBuffer(GLuint buffer)
{
BufferMap::iterator bufferObject = mBufferMap.find(buffer);
if (bufferObject != mBufferMap.end())
{
mBufferHandleAllocator.release(bufferObject->first);
if (bufferObject->second) bufferObject->second->release();
mBufferMap.erase(bufferObject);
}
}
void ResourceManager::deleteShader(GLuint shader)
{
ShaderMap::iterator shaderObject = mShaderMap.find(shader);
if (shaderObject != mShaderMap.end())
{
if (shaderObject->second->getRefCount() == 0)
{
mProgramShaderHandleAllocator.release(shaderObject->first);
delete shaderObject->second;
mShaderMap.erase(shaderObject);
}
else
{
shaderObject->second->flagForDeletion();
}
}
}
void ResourceManager::deleteProgram(GLuint program)
{
ProgramMap::iterator programObject = mProgramMap.find(program);
if (programObject != mProgramMap.end())
{
if (programObject->second->getRefCount() == 0)
{
mProgramShaderHandleAllocator.release(programObject->first);
delete programObject->second;
mProgramMap.erase(programObject);
}
else
{
programObject->second->flagForDeletion();
}
}
}
void ResourceManager::deleteTexture(GLuint texture)
{
TextureMap::iterator textureObject = mTextureMap.find(texture);
if (textureObject != mTextureMap.end())
{
mTextureHandleAllocator.release(textureObject->first);
if (textureObject->second) textureObject->second->release();
mTextureMap.erase(textureObject);
}
}
void ResourceManager::deleteRenderbuffer(GLuint renderbuffer)
{
RenderbufferMap::iterator renderbufferObject = mRenderbufferMap.find(renderbuffer);
if (renderbufferObject != mRenderbufferMap.end())
{
mRenderbufferHandleAllocator.release(renderbufferObject->first);
if (renderbufferObject->second) renderbufferObject->second->release();
mRenderbufferMap.erase(renderbufferObject);
}
}
Buffer *ResourceManager::getBuffer(unsigned int handle)
{
BufferMap::iterator buffer = mBufferMap.find(handle);
if (buffer == mBufferMap.end())
{
return NULL;
}
else
{
return buffer->second;
}
}
Shader *ResourceManager::getShader(unsigned int handle)
{
ShaderMap::iterator shader = mShaderMap.find(handle);
if (shader == mShaderMap.end())
{
return NULL;
}
else
{
return shader->second;
}
}
Texture *ResourceManager::getTexture(unsigned int handle)
{
if (handle == 0) return NULL;
TextureMap::iterator texture = mTextureMap.find(handle);
if (texture == mTextureMap.end())
{
return NULL;
}
else
{
return texture->second;
}
}
Program *ResourceManager::getProgram(unsigned int handle)
{
ProgramMap::iterator program = mProgramMap.find(handle);
if (program == mProgramMap.end())
{
return NULL;
}
else
{
return program->second;
}
}
Renderbuffer *ResourceManager::getRenderbuffer(unsigned int handle)
{
RenderbufferMap::iterator renderbuffer = mRenderbufferMap.find(handle);
if (renderbuffer == mRenderbufferMap.end())
{
return NULL;
}
else
{
return renderbuffer->second;
}
}
void ResourceManager::setRenderbuffer(GLuint handle, Renderbuffer *buffer)
{
mRenderbufferMap[handle] = buffer;
}
void ResourceManager::checkBufferAllocation(unsigned int buffer)
{
if (buffer != 0 && !getBuffer(buffer))
{
Buffer *bufferObject = new Buffer(mRenderer, buffer);
mBufferMap[buffer] = bufferObject;
bufferObject->addRef();
}
}
void ResourceManager::checkTextureAllocation(GLuint texture, TextureType type)
{
if (!getTexture(texture) && texture != 0)
{
Texture *textureObject;
if (type == TEXTURE_2D)
{
textureObject = new Texture2D(mRenderer, texture);
}
else if (type == TEXTURE_CUBE)
{
textureObject = new TextureCubeMap(mRenderer, texture);
}
else
{
UNREACHABLE();
return;
}
mTextureMap[texture] = textureObject;
textureObject->addRef();
}
}
void ResourceManager::checkRenderbufferAllocation(GLuint renderbuffer)
{
if (renderbuffer != 0 && !getRenderbuffer(renderbuffer))
{
Renderbuffer *renderbufferObject = new Renderbuffer(mRenderer, renderbuffer, new Colorbuffer(mRenderer, 0, 0, GL_RGBA4, 0));
mRenderbufferMap[renderbuffer] = renderbufferObject;
renderbufferObject->addRef();
}
}
}
| C++ |
//
// 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.
//
// Shader.h: Defines the abstract gl::Shader class and its concrete derived
// classes VertexShader and FragmentShader. Implements GL shader objects and
// related functionality. [OpenGL ES 2.0.24] section 2.10 page 24 and section
// 3.8 page 84.
#ifndef LIBGLESV2_SHADER_H_
#define LIBGLESV2_SHADER_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <string>
#include <list>
#include <vector>
#include "compiler/Uniform.h"
#include "common/angleutils.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class ResourceManager;
struct Varying
{
Varying(GLenum type, const std::string &name, int size, bool array)
: type(type), name(name), size(size), array(array), reg(-1), col(-1)
{
}
GLenum type;
std::string name;
int size; // Number of 'type' elements
bool array;
int reg; // First varying register, assigned during link
int col; // First register element, assigned during link
};
typedef std::list<Varying> VaryingList;
class Shader
{
friend class ProgramBinary;
public:
Shader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle);
virtual ~Shader();
virtual GLenum getType() = 0;
GLuint getHandle() const;
void deleteSource();
void setSource(GLsizei count, const char **string, const GLint *length);
int getInfoLogLength() const;
void getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog);
int getSourceLength() const;
void getSource(GLsizei bufSize, GLsizei *length, char *buffer);
int getTranslatedSourceLength() const;
void getTranslatedSource(GLsizei bufSize, GLsizei *length, char *buffer);
const sh::ActiveUniforms &getUniforms();
virtual void compile() = 0;
virtual void uncompile();
bool isCompiled();
const char *getHLSL();
void addRef();
void release();
unsigned int getRefCount() const;
bool isFlaggedForDeletion() const;
void flagForDeletion();
static void releaseCompiler();
protected:
void parseVaryings();
void resetVaryingsRegisterAssignment();
void compileToHLSL(void *compiler);
void getSourceImpl(char *source, GLsizei bufSize, GLsizei *length, char *buffer);
static GLenum parseType(const std::string &type);
static bool compareVarying(const Varying &x, const Varying &y);
const rx::Renderer *const mRenderer;
VaryingList mVaryings;
bool mUsesMultipleRenderTargets;
bool mUsesFragColor;
bool mUsesFragData;
bool mUsesFragCoord;
bool mUsesFrontFacing;
bool mUsesPointSize;
bool mUsesPointCoord;
bool mUsesDepthRange;
bool mUsesFragDepth;
static void *mFragmentCompiler;
static void *mVertexCompiler;
private:
DISALLOW_COPY_AND_ASSIGN(Shader);
void initializeCompiler();
const GLuint mHandle;
unsigned int mRefCount; // Number of program objects this shader is attached to
bool mDeleteStatus; // Flag to indicate that the shader can be deleted when no longer in use
char *mSource;
char *mHlsl;
char *mInfoLog;
sh::ActiveUniforms mActiveUniforms;
ResourceManager *mResourceManager;
};
struct Attribute
{
Attribute() : type(GL_NONE), name("")
{
}
Attribute(GLenum type, const std::string &name) : type(type), name(name)
{
}
GLenum type;
std::string name;
};
typedef std::vector<Attribute> AttributeArray;
class VertexShader : public Shader
{
friend class ProgramBinary;
public:
VertexShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle);
~VertexShader();
virtual GLenum getType();
virtual void compile();
virtual void uncompile();
int getSemanticIndex(const std::string &attributeName);
private:
DISALLOW_COPY_AND_ASSIGN(VertexShader);
void parseAttributes();
AttributeArray mAttributes;
};
class FragmentShader : public Shader
{
public:
FragmentShader(ResourceManager *manager,const rx::Renderer *renderer, GLuint handle);
~FragmentShader();
virtual GLenum getType();
virtual void compile();
private:
DISALLOW_COPY_AND_ASSIGN(FragmentShader);
};
}
#endif // LIBGLESV2_SHADER_H_
| C++ |
#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.
//
// Buffer.cpp: Implements 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.
#include "libGLESv2/Buffer.h"
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/IndexBuffer.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Buffer::Buffer(rx::Renderer *renderer, GLuint id) : RefCountObject(id)
{
mRenderer = renderer;
mUsage = GL_DYNAMIC_DRAW;
mBufferStorage = renderer->createBufferStorage();
mStaticVertexBuffer = NULL;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
Buffer::~Buffer()
{
delete mBufferStorage;
delete mStaticVertexBuffer;
delete mStaticIndexBuffer;
}
void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
mBufferStorage->clear();
mBufferStorage->setData(data, size, 0);
mUsage = usage;
invalidateStaticData();
if (usage == GL_STATIC_DRAW)
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
mBufferStorage->setData(data, size, offset);
if ((mStaticVertexBuffer && mStaticVertexBuffer->getBufferSize() != 0) || (mStaticIndexBuffer && mStaticIndexBuffer->getBufferSize() != 0))
{
invalidateStaticData();
}
mUnmodifiedDataUse = 0;
}
rx::BufferStorage *Buffer::getStorage() const
{
return mBufferStorage;
}
unsigned int Buffer::size()
{
return mBufferStorage->getSize();
}
GLenum Buffer::usage() const
{
return mUsage;
}
rx::StaticVertexBufferInterface *Buffer::getStaticVertexBuffer()
{
return mStaticVertexBuffer;
}
rx::StaticIndexBufferInterface *Buffer::getStaticIndexBuffer()
{
return mStaticIndexBuffer;
}
void Buffer::invalidateStaticData()
{
delete mStaticVertexBuffer;
mStaticVertexBuffer = NULL;
delete mStaticIndexBuffer;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
// Creates static buffers if sufficient used data has been left unmodified
void Buffer::promoteStaticUsage(int dataSize)
{
if (!mStaticVertexBuffer && !mStaticIndexBuffer)
{
mUnmodifiedDataUse += dataSize;
if (mUnmodifiedDataUse > 3 * mBufferStorage->getSize())
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
}
}
| C++ |
#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.
//
// Framebuffer.cpp: Implements the gl::Framebuffer class. Implements GL framebuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Renderbuffer.h"
namespace gl
{
Framebuffer::Framebuffer(rx::Renderer *renderer)
: mRenderer(renderer)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mDrawBufferStates[colorAttachment] = GL_NONE;
}
mDrawBufferStates[0] = GL_COLOR_ATTACHMENT0_EXT;
mReadBufferState = GL_COLOR_ATTACHMENT0_EXT;
mDepthbufferType = GL_NONE;
mStencilbufferType = GL_NONE;
}
Framebuffer::~Framebuffer()
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
mColorbufferPointers[colorAttachment].set(NULL);
}
mDepthbufferPointer.set(NULL);
mStencilbufferPointer.set(NULL);
}
Renderbuffer *Framebuffer::lookupRenderbuffer(GLenum type, GLuint handle) const
{
gl::Context *context = gl::getContext();
Renderbuffer *buffer = NULL;
if (type == GL_NONE)
{
buffer = NULL;
}
else if (type == GL_RENDERBUFFER)
{
buffer = context->getRenderbuffer(handle);
}
else if (IsInternalTextureTarget(type))
{
buffer = context->getTexture(handle)->getRenderbuffer(type);
}
else
{
UNREACHABLE();
}
return buffer;
}
void Framebuffer::setColorbuffer(unsigned int colorAttachment, GLenum type, GLuint colorbuffer)
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
mColorbufferTypes[colorAttachment] = (colorbuffer != 0) ? type : GL_NONE;
mColorbufferPointers[colorAttachment].set(lookupRenderbuffer(type, colorbuffer));
}
void Framebuffer::setDepthbuffer(GLenum type, GLuint depthbuffer)
{
mDepthbufferType = (depthbuffer != 0) ? type : GL_NONE;
mDepthbufferPointer.set(lookupRenderbuffer(type, depthbuffer));
}
void Framebuffer::setStencilbuffer(GLenum type, GLuint stencilbuffer)
{
mStencilbufferType = (stencilbuffer != 0) ? type : GL_NONE;
mStencilbufferPointer.set(lookupRenderbuffer(type, stencilbuffer));
}
void Framebuffer::detachTexture(GLuint texture)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferPointers[colorAttachment].id() == texture && IsInternalTextureTarget(mColorbufferTypes[colorAttachment]))
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mColorbufferPointers[colorAttachment].set(NULL);
}
}
if (mDepthbufferPointer.id() == texture && IsInternalTextureTarget(mDepthbufferType))
{
mDepthbufferType = GL_NONE;
mDepthbufferPointer.set(NULL);
}
if (mStencilbufferPointer.id() == texture && IsInternalTextureTarget(mStencilbufferType))
{
mStencilbufferType = GL_NONE;
mStencilbufferPointer.set(NULL);
}
}
void Framebuffer::detachRenderbuffer(GLuint renderbuffer)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferPointers[colorAttachment].id() == renderbuffer && mColorbufferTypes[colorAttachment] == GL_RENDERBUFFER)
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mColorbufferPointers[colorAttachment].set(NULL);
}
}
if (mDepthbufferPointer.id() == renderbuffer && mDepthbufferType == GL_RENDERBUFFER)
{
mDepthbufferType = GL_NONE;
mDepthbufferPointer.set(NULL);
}
if (mStencilbufferPointer.id() == renderbuffer && mStencilbufferType == GL_RENDERBUFFER)
{
mStencilbufferType = GL_NONE;
mStencilbufferPointer.set(NULL);
}
}
unsigned int Framebuffer::getRenderTargetSerial(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
Renderbuffer *colorbuffer = mColorbufferPointers[colorAttachment].get();
if (colorbuffer)
{
return colorbuffer->getSerial();
}
return 0;
}
unsigned int Framebuffer::getDepthbufferSerial() const
{
Renderbuffer *depthbuffer = mDepthbufferPointer.get();
if (depthbuffer)
{
return depthbuffer->getSerial();
}
return 0;
}
unsigned int Framebuffer::getStencilbufferSerial() const
{
Renderbuffer *stencilbuffer = mStencilbufferPointer.get();
if (stencilbuffer)
{
return stencilbuffer->getSerial();
}
return 0;
}
Renderbuffer *Framebuffer::getColorbuffer(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferPointers[colorAttachment].get();
}
Renderbuffer *Framebuffer::getDepthbuffer() const
{
return mDepthbufferPointer.get();
}
Renderbuffer *Framebuffer::getStencilbuffer() const
{
return mStencilbufferPointer.get();
}
Renderbuffer *Framebuffer::getDepthOrStencilbuffer() const
{
Renderbuffer *depthstencilbuffer = mDepthbufferPointer.get();
if (!depthstencilbuffer)
{
depthstencilbuffer = mStencilbufferPointer.get();
}
return depthstencilbuffer;
}
Renderbuffer *Framebuffer::getReadColorbuffer() const
{
// Will require more logic if glReadBuffers is supported
return mColorbufferPointers[0].get();
}
GLenum Framebuffer::getReadColorbufferType() const
{
// Will require more logic if glReadBuffers is supported
return mColorbufferTypes[0];
}
Renderbuffer *Framebuffer::getFirstColorbuffer() const
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
return mColorbufferPointers[colorAttachment].get();
}
}
return NULL;
}
GLenum Framebuffer::getColorbufferType(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferTypes[colorAttachment];
}
GLenum Framebuffer::getDepthbufferType() const
{
return mDepthbufferType;
}
GLenum Framebuffer::getStencilbufferType() const
{
return mStencilbufferType;
}
GLuint Framebuffer::getColorbufferHandle(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferPointers[colorAttachment].id();
}
GLuint Framebuffer::getDepthbufferHandle() const
{
return mDepthbufferPointer.id();
}
GLuint Framebuffer::getStencilbufferHandle() const
{
return mStencilbufferPointer.id();
}
GLenum Framebuffer::getDrawBufferState(unsigned int colorAttachment) const
{
return mDrawBufferStates[colorAttachment];
}
void Framebuffer::setDrawBufferState(unsigned int colorAttachment, GLenum drawBuffer)
{
mDrawBufferStates[colorAttachment] = drawBuffer;
}
bool Framebuffer::isEnabledColorAttachment(unsigned int colorAttachment) const
{
return (mColorbufferTypes[colorAttachment] != GL_NONE && mDrawBufferStates[colorAttachment] != GL_NONE);
}
bool Framebuffer::hasEnabledColorAttachment() const
{
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (isEnabledColorAttachment(colorAttachment))
{
return true;
}
}
return false;
}
bool Framebuffer::hasStencil() const
{
if (mStencilbufferType != GL_NONE)
{
const Renderbuffer *stencilbufferObject = getStencilbuffer();
if (stencilbufferObject)
{
return stencilbufferObject->getStencilSize() > 0;
}
}
return false;
}
bool Framebuffer::usingExtendedDrawBuffers() const
{
for (unsigned int colorAttachment = 1; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (isEnabledColorAttachment(colorAttachment))
{
return true;
}
}
return false;
}
GLenum Framebuffer::completeness() const
{
int width = 0;
int height = 0;
int colorbufferSize = 0;
int samples = -1;
bool missingAttachment = true;
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
const Renderbuffer *colorbuffer = getColorbuffer(colorAttachment);
if (!colorbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mColorbufferTypes[colorAttachment] == GL_RENDERBUFFER)
{
if (!gl::IsColorRenderable(colorbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mColorbufferTypes[colorAttachment]))
{
GLint internalformat = colorbuffer->getInternalFormat();
GLenum format = gl::ExtractFormat(internalformat);
if (IsCompressed(format) ||
format == GL_ALPHA ||
format == GL_LUMINANCE ||
format == GL_LUMINANCE_ALPHA)
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
bool filtering, renderable;
if ((gl::IsFloat32Format(internalformat) && !mRenderer->getFloat32TextureSupport(&filtering, &renderable)) ||
(gl::IsFloat16Format(internalformat) && !mRenderer->getFloat16TextureSupport(&filtering, &renderable)))
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
if (gl::IsDepthTexture(internalformat) || gl::IsStencilTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!missingAttachment)
{
// all color attachments must have the same width and height
if (colorbuffer->getWidth() != width || colorbuffer->getHeight() != height)
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
// APPLE_framebuffer_multisample, which EXT_draw_buffers refers to, requires that
// all color attachments have the same number of samples for the FBO to be complete.
if (colorbuffer->getSamples() != samples)
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT;
}
// all color attachments attachments must have the same number of bitplanes
if (gl::ComputePixelSize(colorbuffer->getInternalFormat()) != colorbufferSize)
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
// D3D11 does not allow for overlapping RenderTargetViews, so ensure uniqueness
for (unsigned int previousColorAttachment = 0; previousColorAttachment < colorAttachment; previousColorAttachment++)
{
if (mColorbufferPointers[colorAttachment].get() == mColorbufferPointers[previousColorAttachment].get())
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
}
}
else
{
width = colorbuffer->getWidth();
height = colorbuffer->getHeight();
samples = colorbuffer->getSamples();
colorbufferSize = gl::ComputePixelSize(colorbuffer->getInternalFormat());
missingAttachment = false;
}
}
}
const Renderbuffer *depthbuffer = NULL;
const Renderbuffer *stencilbuffer = NULL;
if (mDepthbufferType != GL_NONE)
{
depthbuffer = getDepthbuffer();
if (!depthbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (depthbuffer->getWidth() == 0 || depthbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mDepthbufferType == GL_RENDERBUFFER)
{
if (!gl::IsDepthRenderable(depthbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mDepthbufferType))
{
GLint internalformat = depthbuffer->getInternalFormat();
// depth texture attachments require OES/ANGLE_depth_texture
if (!mRenderer->getDepthTextureSupport())
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!gl::IsDepthTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (missingAttachment)
{
width = depthbuffer->getWidth();
height = depthbuffer->getHeight();
samples = depthbuffer->getSamples();
missingAttachment = false;
}
else if (width != depthbuffer->getWidth() || height != depthbuffer->getHeight())
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
else if (samples != depthbuffer->getSamples())
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE;
}
}
if (mStencilbufferType != GL_NONE)
{
stencilbuffer = getStencilbuffer();
if (!stencilbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (stencilbuffer->getWidth() == 0 || stencilbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mStencilbufferType == GL_RENDERBUFFER)
{
if (!gl::IsStencilRenderable(stencilbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mStencilbufferType))
{
GLint internalformat = stencilbuffer->getInternalFormat();
// texture stencil attachments come along as part
// of OES_packed_depth_stencil + OES/ANGLE_depth_texture
if (!mRenderer->getDepthTextureSupport())
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!gl::IsStencilTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (missingAttachment)
{
width = stencilbuffer->getWidth();
height = stencilbuffer->getHeight();
samples = stencilbuffer->getSamples();
missingAttachment = false;
}
else if (width != stencilbuffer->getWidth() || height != stencilbuffer->getHeight())
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
else if (samples != stencilbuffer->getSamples())
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE;
}
}
// if we have both a depth and stencil buffer, they must refer to the same object
// since we only support packed_depth_stencil and not separate depth and stencil
if (depthbuffer && stencilbuffer && (depthbuffer != stencilbuffer))
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
// we need to have at least one attachment to be complete
if (missingAttachment)
{
return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
}
return GL_FRAMEBUFFER_COMPLETE;
}
DefaultFramebuffer::DefaultFramebuffer(rx::Renderer *renderer, Colorbuffer *colorbuffer, DepthStencilbuffer *depthStencil)
: Framebuffer(renderer)
{
mColorbufferPointers[0].set(new Renderbuffer(mRenderer, 0, colorbuffer));
Renderbuffer *depthStencilRenderbuffer = new Renderbuffer(mRenderer, 0, depthStencil);
mDepthbufferPointer.set(depthStencilRenderbuffer);
mStencilbufferPointer.set(depthStencilRenderbuffer);
mColorbufferTypes[0] = GL_RENDERBUFFER;
mDepthbufferType = (depthStencilRenderbuffer->getDepthSize() != 0) ? GL_RENDERBUFFER : GL_NONE;
mStencilbufferType = (depthStencilRenderbuffer->getStencilSize() != 0) ? GL_RENDERBUFFER : GL_NONE;
mDrawBufferStates[0] = GL_BACK;
mReadBufferState = GL_BACK;
}
int Framebuffer::getSamples() const
{
if (completeness() == GL_FRAMEBUFFER_COMPLETE)
{
// for a complete framebuffer, all attachments must have the same sample count
// in this case return the first nonzero sample size
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
return getColorbuffer(colorAttachment)->getSamples();
}
}
}
return 0;
}
GLenum DefaultFramebuffer::completeness() const
{
// The default framebuffer *must* always be complete, though it may not be
// subject to the same rules as application FBOs. ie, it could have 0x0 size.
return GL_FRAMEBUFFER_COMPLETE;
}
}
| C++ |
//
// 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.
//
// ResourceManager.h : Defines the ResourceManager class, which tracks objects
// shared by multiple GL contexts.
#ifndef LIBGLESV2_RESOURCEMANAGER_H_
#define LIBGLESV2_RESOURCEMANAGER_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#ifdef _MSC_VER
#include <hash_map>
#else
#include <unordered_map>
#endif
#include "common/angleutils.h"
#include "libGLESv2/angletypes.h"
#include "libGLESv2/HandleAllocator.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class Buffer;
class Shader;
class Program;
class Texture;
class Renderbuffer;
class ResourceManager
{
public:
explicit ResourceManager(rx::Renderer *renderer);
~ResourceManager();
void addRef();
void release();
GLuint createBuffer();
GLuint createShader(GLenum type);
GLuint createProgram();
GLuint createTexture();
GLuint createRenderbuffer();
void deleteBuffer(GLuint buffer);
void deleteShader(GLuint shader);
void deleteProgram(GLuint program);
void deleteTexture(GLuint texture);
void deleteRenderbuffer(GLuint renderbuffer);
Buffer *getBuffer(GLuint handle);
Shader *getShader(GLuint handle);
Program *getProgram(GLuint handle);
Texture *getTexture(GLuint handle);
Renderbuffer *getRenderbuffer(GLuint handle);
void setRenderbuffer(GLuint handle, Renderbuffer *renderbuffer);
void checkBufferAllocation(unsigned int buffer);
void checkTextureAllocation(GLuint texture, TextureType type);
void checkRenderbufferAllocation(GLuint renderbuffer);
private:
DISALLOW_COPY_AND_ASSIGN(ResourceManager);
std::size_t mRefCount;
rx::Renderer *mRenderer;
#ifndef HASH_MAP
# ifdef _MSC_VER
# define HASH_MAP stdext::hash_map
# else
# define HASH_MAP std::unordered_map
# endif
#endif
typedef HASH_MAP<GLuint, Buffer*> BufferMap;
BufferMap mBufferMap;
HandleAllocator mBufferHandleAllocator;
typedef HASH_MAP<GLuint, Shader*> ShaderMap;
ShaderMap mShaderMap;
typedef HASH_MAP<GLuint, Program*> ProgramMap;
ProgramMap mProgramMap;
HandleAllocator mProgramShaderHandleAllocator;
typedef HASH_MAP<GLuint, Texture*> TextureMap;
TextureMap mTextureMap;
HandleAllocator mTextureHandleAllocator;
typedef HASH_MAP<GLuint, Renderbuffer*> RenderbufferMap;
RenderbufferMap mRenderbufferMap;
HandleAllocator mRenderbufferHandleAllocator;
};
}
#endif // LIBGLESV2_RESOURCEMANAGER_H_
| C++ |
//
// 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.
//
// angletypes.h : Defines a variety of structures and enum types that are used throughout libGLESv2
#ifndef LIBGLESV2_ANGLETYPES_H_
#define LIBGLESV2_ANGLETYPES_H_
namespace gl
{
enum TextureType
{
TEXTURE_2D,
TEXTURE_CUBE,
TEXTURE_TYPE_COUNT,
TEXTURE_UNKNOWN
};
enum SamplerType
{
SAMPLER_PIXEL,
SAMPLER_VERTEX
};
struct Color
{
float red;
float green;
float blue;
float alpha;
};
struct Rectangle
{
int x;
int y;
int width;
int height;
};
struct RasterizerState
{
bool cullFace;
GLenum cullMode;
GLenum frontFace;
bool polygonOffsetFill;
GLfloat polygonOffsetFactor;
GLfloat polygonOffsetUnits;
bool pointDrawMode;
bool multiSample;
};
struct BlendState
{
bool blend;
GLenum sourceBlendRGB;
GLenum destBlendRGB;
GLenum sourceBlendAlpha;
GLenum destBlendAlpha;
GLenum blendEquationRGB;
GLenum blendEquationAlpha;
bool colorMaskRed;
bool colorMaskGreen;
bool colorMaskBlue;
bool colorMaskAlpha;
bool sampleAlphaToCoverage;
bool dither;
};
struct DepthStencilState
{
bool depthTest;
GLenum depthFunc;
bool depthMask;
bool stencilTest;
GLenum stencilFunc;
GLuint stencilMask;
GLenum stencilFail;
GLenum stencilPassDepthFail;
GLenum stencilPassDepthPass;
GLuint stencilWritemask;
GLenum stencilBackFunc;
GLuint stencilBackMask;
GLenum stencilBackFail;
GLenum stencilBackPassDepthFail;
GLenum stencilBackPassDepthPass;
GLuint stencilBackWritemask;
};
struct SamplerState
{
GLenum minFilter;
GLenum magFilter;
GLenum wrapS;
GLenum wrapT;
float maxAnisotropy;
int lodOffset;
};
struct ClearParameters
{
GLbitfield mask;
Color colorClearValue;
bool colorMaskRed;
bool colorMaskGreen;
bool colorMaskBlue;
bool colorMaskAlpha;
float depthClearValue;
GLint stencilClearValue;
GLuint stencilWriteMask;
};
}
#endif // LIBGLESV2_ANGLETYPES_H_
| C++ |
#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.
//
// Shader.cpp: Implements the gl::Shader class and its derived classes
// VertexShader and FragmentShader. Implements GL shader objects and related
// functionality. [OpenGL ES 2.0.24] section 2.10 page 24 and section 3.8 page 84.
#include "libGLESv2/Shader.h"
#include "GLSLANG/ShaderLang.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Constants.h"
#include "libGLESv2/ResourceManager.h"
namespace gl
{
void *Shader::mFragmentCompiler = NULL;
void *Shader::mVertexCompiler = NULL;
Shader::Shader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: mHandle(handle), mRenderer(renderer), mResourceManager(manager)
{
mSource = NULL;
mHlsl = NULL;
mInfoLog = NULL;
uncompile();
initializeCompiler();
mRefCount = 0;
mDeleteStatus = false;
}
Shader::~Shader()
{
delete[] mSource;
delete[] mHlsl;
delete[] mInfoLog;
}
GLuint Shader::getHandle() const
{
return mHandle;
}
void Shader::setSource(GLsizei count, const char **string, const GLint *length)
{
delete[] mSource;
int totalLength = 0;
for (int i = 0; i < count; i++)
{
if (length && length[i] >= 0)
{
totalLength += length[i];
}
else
{
totalLength += (int)strlen(string[i]);
}
}
mSource = new char[totalLength + 1];
char *code = mSource;
for (int i = 0; i < count; i++)
{
int stringLength;
if (length && length[i] >= 0)
{
stringLength = length[i];
}
else
{
stringLength = (int)strlen(string[i]);
}
strncpy(code, string[i], stringLength);
code += stringLength;
}
mSource[totalLength] = '\0';
}
int Shader::getInfoLogLength() const
{
if (!mInfoLog)
{
return 0;
}
else
{
return strlen(mInfoLog) + 1;
}
}
void Shader::getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
int index = 0;
if (bufSize > 0)
{
if (mInfoLog)
{
index = std::min(bufSize - 1, (int)strlen(mInfoLog));
memcpy(infoLog, mInfoLog, index);
}
infoLog[index] = '\0';
}
if (length)
{
*length = index;
}
}
int Shader::getSourceLength() const
{
if (!mSource)
{
return 0;
}
else
{
return strlen(mSource) + 1;
}
}
int Shader::getTranslatedSourceLength() const
{
if (!mHlsl)
{
return 0;
}
else
{
return strlen(mHlsl) + 1;
}
}
void Shader::getSourceImpl(char *source, GLsizei bufSize, GLsizei *length, char *buffer)
{
int index = 0;
if (bufSize > 0)
{
if (source)
{
index = std::min(bufSize - 1, (int)strlen(source));
memcpy(buffer, source, index);
}
buffer[index] = '\0';
}
if (length)
{
*length = index;
}
}
void Shader::getSource(GLsizei bufSize, GLsizei *length, char *buffer)
{
getSourceImpl(mSource, bufSize, length, buffer);
}
void Shader::getTranslatedSource(GLsizei bufSize, GLsizei *length, char *buffer)
{
getSourceImpl(mHlsl, bufSize, length, buffer);
}
const sh::ActiveUniforms &Shader::getUniforms()
{
return mActiveUniforms;
}
bool Shader::isCompiled()
{
return mHlsl != NULL;
}
const char *Shader::getHLSL()
{
return mHlsl;
}
void Shader::addRef()
{
mRefCount++;
}
void Shader::release()
{
mRefCount--;
if (mRefCount == 0 && mDeleteStatus)
{
mResourceManager->deleteShader(mHandle);
}
}
unsigned int Shader::getRefCount() const
{
return mRefCount;
}
bool Shader::isFlaggedForDeletion() const
{
return mDeleteStatus;
}
void Shader::flagForDeletion()
{
mDeleteStatus = true;
}
// Perform a one-time initialization of the shader compiler (or after being destructed by releaseCompiler)
void Shader::initializeCompiler()
{
if (!mFragmentCompiler)
{
int result = ShInitialize();
if (result)
{
ShShaderOutput hlslVersion = (mRenderer->getMajorShaderModel() >= 4) ? SH_HLSL11_OUTPUT : SH_HLSL9_OUTPUT;
ShBuiltInResources resources;
ShInitBuiltInResources(&resources);
resources.MaxVertexAttribs = MAX_VERTEX_ATTRIBS;
resources.MaxVertexUniformVectors = mRenderer->getMaxVertexUniformVectors();
resources.MaxVaryingVectors = mRenderer->getMaxVaryingVectors();
resources.MaxVertexTextureImageUnits = mRenderer->getMaxVertexTextureImageUnits();
resources.MaxCombinedTextureImageUnits = mRenderer->getMaxCombinedTextureImageUnits();
resources.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
resources.MaxFragmentUniformVectors = mRenderer->getMaxFragmentUniformVectors();
resources.MaxDrawBuffers = mRenderer->getMaxRenderTargets();
resources.OES_standard_derivatives = mRenderer->getDerivativeInstructionSupport();
resources.EXT_draw_buffers = mRenderer->getMaxRenderTargets() > 1;
// resources.OES_EGL_image_external = mRenderer->getShareHandleSupport() ? 1 : 0; // TODO: commented out until the extension is actually supported.
resources.FragmentPrecisionHigh = 1; // Shader Model 2+ always supports FP24 (s16e7) which corresponds to highp
resources.EXT_frag_depth = 1; // Shader Model 2+ always supports explicit depth output
mFragmentCompiler = ShConstructCompiler(SH_FRAGMENT_SHADER, SH_GLES2_SPEC, hlslVersion, &resources);
mVertexCompiler = ShConstructCompiler(SH_VERTEX_SHADER, SH_GLES2_SPEC, hlslVersion, &resources);
}
}
}
void Shader::releaseCompiler()
{
ShDestruct(mFragmentCompiler);
ShDestruct(mVertexCompiler);
mFragmentCompiler = NULL;
mVertexCompiler = NULL;
ShFinalize();
}
void Shader::parseVaryings()
{
if (mHlsl)
{
const char *input = strstr(mHlsl, "// Varyings") + 12;
while(true)
{
char varyingType[256];
char varyingName[256];
int matches = sscanf(input, "static %255s %255s", varyingType, varyingName);
if (matches != 2)
{
break;
}
char *array = strstr(varyingName, "[");
int size = 1;
if (array)
{
size = atoi(array + 1);
*array = '\0';
}
mVaryings.push_back(Varying(parseType(varyingType), varyingName, size, array != NULL));
input = strstr(input, ";") + 2;
}
mUsesMultipleRenderTargets = strstr(mHlsl, "GL_USES_MRT") != NULL;
mUsesFragColor = strstr(mHlsl, "GL_USES_FRAG_COLOR") != NULL;
mUsesFragData = strstr(mHlsl, "GL_USES_FRAG_DATA") != NULL;
mUsesFragCoord = strstr(mHlsl, "GL_USES_FRAG_COORD") != NULL;
mUsesFrontFacing = strstr(mHlsl, "GL_USES_FRONT_FACING") != NULL;
mUsesPointSize = strstr(mHlsl, "GL_USES_POINT_SIZE") != NULL;
mUsesPointCoord = strstr(mHlsl, "GL_USES_POINT_COORD") != NULL;
mUsesDepthRange = strstr(mHlsl, "GL_USES_DEPTH_RANGE") != NULL;
mUsesFragDepth = strstr(mHlsl, "GL_USES_FRAG_DEPTH") != NULL;
}
}
void Shader::resetVaryingsRegisterAssignment()
{
for (VaryingList::iterator var = mVaryings.begin(); var != mVaryings.end(); var++)
{
var->reg = -1;
var->col = -1;
}
}
// initialize/clean up previous state
void Shader::uncompile()
{
// set by compileToHLSL
delete[] mHlsl;
mHlsl = NULL;
delete[] mInfoLog;
mInfoLog = NULL;
// set by parseVaryings
mVaryings.clear();
mUsesMultipleRenderTargets = false;
mUsesFragColor = false;
mUsesFragData = false;
mUsesFragCoord = false;
mUsesFrontFacing = false;
mUsesPointSize = false;
mUsesPointCoord = false;
mUsesDepthRange = false;
mUsesFragDepth = false;
mActiveUniforms.clear();
}
void Shader::compileToHLSL(void *compiler)
{
// ensure we don't pass a NULL source to the compiler
const char *source = "\0";
if (mSource)
{
source = mSource;
}
// ensure the compiler is loaded
initializeCompiler();
int compileOptions = SH_OBJECT_CODE;
std::string sourcePath;
if (perfActive())
{
sourcePath = getTempPath();
writeFile(sourcePath.c_str(), source, strlen(source));
compileOptions |= SH_LINE_DIRECTIVES;
}
int result;
if (sourcePath.empty())
{
result = ShCompile(compiler, &source, 1, compileOptions);
}
else
{
const char* sourceStrings[2] =
{
sourcePath.c_str(),
source
};
result = ShCompile(compiler, sourceStrings, 2, compileOptions | SH_SOURCE_PATH);
}
if (result)
{
size_t objCodeLen = 0;
ShGetInfo(compiler, SH_OBJECT_CODE_LENGTH, &objCodeLen);
mHlsl = new char[objCodeLen];
ShGetObjectCode(compiler, mHlsl);
void *activeUniforms;
ShGetInfoPointer(compiler, SH_ACTIVE_UNIFORMS_ARRAY, &activeUniforms);
mActiveUniforms = *(sh::ActiveUniforms*)activeUniforms;
}
else
{
size_t infoLogLen = 0;
ShGetInfo(compiler, SH_INFO_LOG_LENGTH, &infoLogLen);
mInfoLog = new char[infoLogLen];
ShGetInfoLog(compiler, mInfoLog);
TRACE("\n%s", mInfoLog);
}
}
GLenum Shader::parseType(const std::string &type)
{
if (type == "float")
{
return GL_FLOAT;
}
else if (type == "float2")
{
return GL_FLOAT_VEC2;
}
else if (type == "float3")
{
return GL_FLOAT_VEC3;
}
else if (type == "float4")
{
return GL_FLOAT_VEC4;
}
else if (type == "float2x2")
{
return GL_FLOAT_MAT2;
}
else if (type == "float3x3")
{
return GL_FLOAT_MAT3;
}
else if (type == "float4x4")
{
return GL_FLOAT_MAT4;
}
else UNREACHABLE();
return GL_NONE;
}
// true if varying x has a higher priority in packing than y
bool Shader::compareVarying(const Varying &x, const Varying &y)
{
if(x.type == y.type)
{
return x.size > y.size;
}
switch (x.type)
{
case GL_FLOAT_MAT4: return true;
case GL_FLOAT_MAT2:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return true;
case GL_FLOAT_VEC4: return true;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC4:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return true;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_MAT3:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC3:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return false;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC2:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return false;
case GL_FLOAT_VEC3: return false;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT: return false;
default: UNREACHABLE();
}
return false;
}
VertexShader::VertexShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: Shader(manager, renderer, handle)
{
}
VertexShader::~VertexShader()
{
}
GLenum VertexShader::getType()
{
return GL_VERTEX_SHADER;
}
void VertexShader::uncompile()
{
Shader::uncompile();
// set by ParseAttributes
mAttributes.clear();
}
void VertexShader::compile()
{
uncompile();
compileToHLSL(mVertexCompiler);
parseAttributes();
parseVaryings();
}
int VertexShader::getSemanticIndex(const std::string &attributeName)
{
if (!attributeName.empty())
{
int semanticIndex = 0;
for (AttributeArray::iterator attribute = mAttributes.begin(); attribute != mAttributes.end(); attribute++)
{
if (attribute->name == attributeName)
{
return semanticIndex;
}
semanticIndex += VariableRowCount(attribute->type);
}
}
return -1;
}
void VertexShader::parseAttributes()
{
const char *hlsl = getHLSL();
if (hlsl)
{
const char *input = strstr(hlsl, "// Attributes") + 14;
while(true)
{
char attributeType[256];
char attributeName[256];
int matches = sscanf(input, "static %255s _%255s", attributeType, attributeName);
if (matches != 2)
{
break;
}
mAttributes.push_back(Attribute(parseType(attributeType), attributeName));
input = strstr(input, ";") + 2;
}
}
}
FragmentShader::FragmentShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: Shader(manager, renderer, handle)
{
}
FragmentShader::~FragmentShader()
{
}
GLenum FragmentShader::getType()
{
return GL_FRAGMENT_SHADER;
}
void FragmentShader::compile()
{
uncompile();
compileToHLSL(mFragmentCompiler);
parseVaryings();
mVaryings.sort(compareVarying);
}
}
| C++ |
//
// 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.
//
// Query.h: Defines the gl::Query class
#ifndef LIBGLESV2_QUERY_H_
#define LIBGLESV2_QUERY_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/angleutils.h"
#include "common/RefCountObject.h"
namespace rx
{
class Renderer;
class QueryImpl;
}
namespace gl
{
class Query : public RefCountObject
{
public:
Query(rx::Renderer *renderer, GLenum type, GLuint id);
virtual ~Query();
void begin();
void end();
GLuint getResult();
GLboolean isResultAvailable();
GLenum getType() const;
private:
DISALLOW_COPY_AND_ASSIGN(Query);
rx::QueryImpl *mQuery;
};
}
#endif // LIBGLESV2_QUERY_H_
| C++ |
//
// Copyright (c) 2002-2011 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.
//
// HandleAllocator.h: Defines the gl::HandleAllocator class, which is used to
// allocate GL handles.
#ifndef LIBGLESV2_HANDLEALLOCATOR_H_
#define LIBGLESV2_HANDLEALLOCATOR_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <vector>
#include "common/angleutils.h"
namespace gl
{
class HandleAllocator
{
public:
HandleAllocator();
virtual ~HandleAllocator();
void setBaseHandle(GLuint value);
GLuint allocate();
void release(GLuint handle);
private:
DISALLOW_COPY_AND_ASSIGN(HandleAllocator);
GLuint mBaseValue;
GLuint mNextValue;
typedef std::vector<GLuint> HandleList;
HandleList mFreeValues;
};
}
#endif // LIBGLESV2_HANDLEALLOCATOR_H_
| C++ |
//
// 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.h: Defines the abstract gl::Texture class and its concrete derived
// classes Texture2D and TextureCubeMap. Implements GL texture objects and
// related functionality. [OpenGL ES 2.0.24] section 3.7 page 63.
#ifndef LIBGLESV2_TEXTURE_H_
#define LIBGLESV2_TEXTURE_H_
#include <vector>
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/debug.h"
#include "common/RefCountObject.h"
#include "libGLESv2/angletypes.h"
namespace egl
{
class Surface;
}
namespace rx
{
class Renderer;
class TextureStorageInterface;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class RenderTarget;
class Image;
}
namespace gl
{
class Framebuffer;
class Renderbuffer;
enum
{
// These are the maximums the implementation can support
// The actual GL caps are limited by the device caps
// and should be queried from the Context
IMPLEMENTATION_MAX_TEXTURE_SIZE = 16384,
IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE = 16384,
IMPLEMENTATION_MAX_TEXTURE_LEVELS = 15 // 1+log2 of MAX_TEXTURE_SIZE
};
class Texture : public RefCountObject
{
public:
Texture(rx::Renderer *renderer, GLuint id);
virtual ~Texture();
virtual void addProxyRef(const Renderbuffer *proxy) = 0;
virtual void releaseProxy(const Renderbuffer *proxy) = 0;
virtual GLenum getTarget() const = 0;
bool setMinFilter(GLenum filter);
bool setMagFilter(GLenum filter);
bool setWrapS(GLenum wrap);
bool setWrapT(GLenum wrap);
bool setMaxAnisotropy(float textureMaxAnisotropy, float contextMaxAnisotropy);
bool setUsage(GLenum usage);
GLenum getMinFilter() const;
GLenum getMagFilter() const;
GLenum getWrapS() const;
GLenum getWrapT() const;
float getMaxAnisotropy() const;
int getLodOffset();
void getSamplerState(SamplerState *sampler);
GLenum getUsage() const;
bool isMipmapFiltered() const;
virtual bool isSamplerComplete() const = 0;
rx::TextureStorageInterface *getNativeTexture();
virtual Renderbuffer *getRenderbuffer(GLenum target) = 0;
virtual void generateMipmaps() = 0;
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source) = 0;
bool hasDirtyParameters() const;
bool hasDirtyImages() const;
void resetDirty();
unsigned int getTextureSerial();
unsigned int getRenderTargetSerial(GLenum target);
bool isImmutable() const;
static const GLuint INCOMPLETE_TEXTURE_ID = static_cast<GLuint>(-1); // Every texture takes an id at creation time. The value is arbitrary because it is never registered with the resource manager.
protected:
void setImage(GLint unpackAlignment, const void *pixels, rx::Image *image);
bool subImage(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels, rx::Image *image);
void setCompressedImage(GLsizei imageSize, const void *pixels, rx::Image *image);
bool subImageCompressed(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels, rx::Image *image);
GLint creationLevels(GLsizei width, GLsizei height) const;
GLint creationLevels(GLsizei size) const;
virtual void createTexture() = 0;
virtual void updateTexture() = 0;
virtual void convertToRenderTarget() = 0;
virtual rx::RenderTarget *getRenderTarget(GLenum target) = 0;
virtual int levelCount() = 0;
rx::Renderer *mRenderer;
SamplerState mSamplerState;
GLenum mUsage;
bool mDirtyImages;
bool mImmutable;
private:
DISALLOW_COPY_AND_ASSIGN(Texture);
virtual rx::TextureStorageInterface *getStorage(bool renderTarget) = 0;
};
class Texture2D : public Texture
{
public:
Texture2D(rx::Renderer *renderer, GLuint id);
~Texture2D();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
virtual GLenum getTarget() const;
GLsizei getWidth(GLint level) const;
GLsizei getHeight(GLint level) const;
GLenum getInternalFormat(GLint level) const;
GLenum getActualFormat(GLint level) const;
bool isCompressed(GLint level) const;
bool isDepth(GLint level) const;
void setImage(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setCompressedImage(GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);
void subImage(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void subImageCompressed(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
void copyImage(GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
void storage(GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
virtual bool isSamplerComplete() const;
virtual void bindTexImage(egl::Surface *surface);
virtual void releaseTexImage();
virtual void generateMipmaps();
virtual Renderbuffer *getRenderbuffer(GLenum target);
protected:
friend class RenderbufferTexture2D;
virtual rx::RenderTarget *getRenderTarget(GLenum target);
virtual rx::RenderTarget *getDepthStencil(GLenum target);
virtual int levelCount();
private:
DISALLOW_COPY_AND_ASSIGN(Texture2D);
virtual void createTexture();
virtual void updateTexture();
virtual void convertToRenderTarget();
virtual rx::TextureStorageInterface *getStorage(bool renderTarget);
bool isMipmapComplete() const;
void redefineImage(GLint level, GLint internalformat, GLsizei width, GLsizei height);
void commitRect(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
rx::Image *mImageArray[IMPLEMENTATION_MAX_TEXTURE_LEVELS];
rx::TextureStorageInterface2D *mTexStorage;
egl::Surface *mSurface;
// A specific internal reference count is kept for colorbuffer proxy references,
// because, as the renderbuffer acting as proxy will maintain a binding pointer
// back to this texture, there would be a circular reference if we used a binding
// pointer here. This reference count will cause the pointer to be set to NULL if
// the count drops to zero, but will not cause deletion of the Renderbuffer.
Renderbuffer *mColorbufferProxy;
unsigned int mProxyRefs;
};
class TextureCubeMap : public Texture
{
public:
TextureCubeMap(rx::Renderer *renderer, GLuint id);
~TextureCubeMap();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
virtual GLenum getTarget() const;
GLsizei getWidth(GLenum target, GLint level) const;
GLsizei getHeight(GLenum target, GLint level) const;
GLenum getInternalFormat(GLenum target, GLint level) const;
GLenum getActualFormat(GLenum target, GLint level) const;
bool isCompressed(GLenum target, GLint level) const;
void setImagePosX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImagePosY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImagePosZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setCompressedImage(GLenum face, GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);
void subImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void subImageCompressed(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
void copyImage(GLenum target, GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
void storage(GLsizei levels, GLenum internalformat, GLsizei size);
virtual bool isSamplerComplete() const;
virtual void generateMipmaps();
virtual Renderbuffer *getRenderbuffer(GLenum target);
static unsigned int faceIndex(GLenum face);
protected:
friend class RenderbufferTextureCubeMap;
virtual rx::RenderTarget *getRenderTarget(GLenum target);
virtual int levelCount();
private:
DISALLOW_COPY_AND_ASSIGN(TextureCubeMap);
virtual void createTexture();
virtual void updateTexture();
virtual void convertToRenderTarget();
virtual rx::TextureStorageInterface *getStorage(bool renderTarget);
bool isCubeComplete() const;
bool isMipmapCubeComplete() const;
void setImage(int faceIndex, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void commitRect(int faceIndex, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
void redefineImage(int faceIndex, GLint level, GLint internalformat, GLsizei width, GLsizei height);
rx::Image *mImageArray[6][IMPLEMENTATION_MAX_TEXTURE_LEVELS];
rx::TextureStorageInterfaceCube *mTexStorage;
// A specific internal reference count is kept for colorbuffer proxy references,
// because, as the renderbuffer acting as proxy will maintain a binding pointer
// back to this texture, there would be a circular reference if we used a binding
// pointer here. This reference count will cause the pointer to be set to NULL if
// the count drops to zero, but will not cause deletion of the Renderbuffer.
Renderbuffer *mFaceProxies[6];
unsigned int *mFaceProxyRefs[6];
};
}
#endif // LIBGLESV2_TEXTURE_H_
| C++ |
//
// 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.
//
// Contants.h: Defines some implementation specific and gl constants
#ifndef LIBGLESV2_CONSTANTS_H_
#define LIBGLESV2_CONSTANTS_H_
namespace gl
{
enum
{
MAX_VERTEX_ATTRIBS = 16,
MAX_TEXTURE_IMAGE_UNITS = 16,
// Implementation upper limits, real maximums depend on the hardware
IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
};
const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
}
#endif // LIBGLESV2_CONSTANTS_H_
| C++ |
#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.
//
// utilities.cpp: Conversion functions and other utility routines.
#include "libGLESv2/utilities.h"
#include "libGLESv2/mathutil.h"
namespace gl
{
int UniformComponentCount(GLenum type)
{
switch (type)
{
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT2:
return 4;
case GL_FLOAT_MAT3:
return 9;
case GL_FLOAT_MAT4:
return 16;
default:
UNREACHABLE();
}
return 0;
}
GLenum UniformComponentType(GLenum type)
{
switch(type)
{
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
return GL_BOOL;
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:
return GL_FLOAT;
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
return GL_INT;
default:
UNREACHABLE();
}
return GL_NONE;
}
size_t UniformComponentSize(GLenum type)
{
switch(type)
{
case GL_BOOL: return sizeof(GLint);
case GL_FLOAT: return sizeof(GLfloat);
case GL_INT: return sizeof(GLint);
default: UNREACHABLE();
}
return 0;
}
size_t UniformInternalSize(GLenum type)
{
// Expanded to 4-element vectors
return UniformComponentSize(UniformComponentType(type)) * VariableRowCount(type) * 4;
}
size_t UniformExternalSize(GLenum type)
{
return UniformComponentSize(UniformComponentType(type)) * UniformComponentCount(type);
}
int VariableRowCount(GLenum type)
{
switch (type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_FLOAT_MAT2:
return 2;
case GL_FLOAT_MAT3:
return 3;
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE();
}
return 0;
}
int VariableColumnCount(GLenum type)
{
switch (type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_FLOAT_MAT2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_FLOAT_MAT3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE();
}
return 0;
}
int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize)
{
ASSERT(allocationSize <= bitsSize);
unsigned int mask = std::numeric_limits<unsigned int>::max() >> (std::numeric_limits<unsigned int>::digits - allocationSize);
for (unsigned int i = 0; i < bitsSize - allocationSize + 1; i++)
{
if ((*bits & mask) == 0)
{
*bits |= mask;
return i;
}
mask <<= 1;
}
return -1;
}
GLsizei ComputePitch(GLsizei width, GLint internalformat, GLint alignment)
{
ASSERT(alignment > 0 && isPow2(alignment));
GLsizei rawPitch = ComputePixelSize(internalformat) * width;
return (rawPitch + alignment - 1) & ~(alignment - 1);
}
GLsizei ComputeCompressedPitch(GLsizei width, GLenum internalformat)
{
return ComputeCompressedSize(width, 1, internalformat);
}
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum internalformat)
{
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return 8 * ((width + 3) / 4) * ((height + 3) / 4);
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return 16 * ((width + 3) / 4) * ((height + 3) / 4);
default:
return 0;
}
}
bool IsCompressed(GLenum format)
{
if(format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE ||
format == GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE)
{
return true;
}
else
{
return false;
}
}
bool IsDepthTexture(GLenum format)
{
if (format == GL_DEPTH_COMPONENT ||
format == GL_DEPTH_STENCIL_OES ||
format == GL_DEPTH_COMPONENT16 ||
format == GL_DEPTH_COMPONENT32_OES ||
format == GL_DEPTH24_STENCIL8_OES)
{
return true;
}
return false;
}
bool IsStencilTexture(GLenum format)
{
if (format == GL_DEPTH_STENCIL_OES ||
format == GL_DEPTH24_STENCIL8_OES)
{
return true;
}
return false;
}
void MakeValidSize(bool isImage, bool isCompressed, GLsizei *requestWidth, GLsizei *requestHeight, int *levelOffset)
{
int upsampleCount = 0;
if (isCompressed)
{
// Don't expand the size of full textures that are at least 4x4
// already.
if (isImage || *requestWidth < 4 || *requestHeight < 4)
{
while (*requestWidth % 4 != 0 || *requestHeight % 4 != 0)
{
*requestWidth <<= 1;
*requestHeight <<= 1;
upsampleCount++;
}
}
}
*levelOffset = upsampleCount;
}
// Returns the size, in bytes, of a single texel in an Image
int ComputePixelSize(GLint internalformat)
{
switch (internalformat)
{
case GL_ALPHA8_EXT: return sizeof(unsigned char);
case GL_LUMINANCE8_EXT: return sizeof(unsigned char);
case GL_ALPHA32F_EXT: return sizeof(float);
case GL_LUMINANCE32F_EXT: return sizeof(float);
case GL_ALPHA16F_EXT: return sizeof(unsigned short);
case GL_LUMINANCE16F_EXT: return sizeof(unsigned short);
case GL_LUMINANCE8_ALPHA8_EXT: return sizeof(unsigned char) * 2;
case GL_LUMINANCE_ALPHA32F_EXT: return sizeof(float) * 2;
case GL_LUMINANCE_ALPHA16F_EXT: return sizeof(unsigned short) * 2;
case GL_RGB8_OES: return sizeof(unsigned char) * 3;
case GL_RGB565: return sizeof(unsigned short);
case GL_RGB32F_EXT: return sizeof(float) * 3;
case GL_RGB16F_EXT: return sizeof(unsigned short) * 3;
case GL_RGBA8_OES: return sizeof(unsigned char) * 4;
case GL_RGBA4: return sizeof(unsigned short);
case GL_RGB5_A1: return sizeof(unsigned short);
case GL_RGBA32F_EXT: return sizeof(float) * 4;
case GL_RGBA16F_EXT: return sizeof(unsigned short) * 4;
case GL_BGRA8_EXT: return sizeof(unsigned char) * 4;
case GL_BGRA4_ANGLEX: return sizeof(unsigned short);
case GL_BGR5_A1_ANGLEX: return sizeof(unsigned short);
default: UNREACHABLE();
}
return 0;
}
bool IsCubemapTextureTarget(GLenum target)
{
return (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
}
bool IsInternalTextureTarget(GLenum target)
{
return target == GL_TEXTURE_2D || IsCubemapTextureTarget(target);
}
GLint ConvertSizedInternalFormat(GLenum format, GLenum type)
{
switch (format)
{
case GL_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_ALPHA8_EXT;
case GL_FLOAT: return GL_ALPHA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_ALPHA16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_LUMINANCE:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_EXT;
case GL_FLOAT: return GL_LUMINANCE32F_EXT;
case GL_HALF_FLOAT_OES: return GL_LUMINANCE16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_LUMINANCE_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_ALPHA8_EXT;
case GL_FLOAT: return GL_LUMINANCE_ALPHA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_LUMINANCE_ALPHA16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_RGB8_OES;
case GL_UNSIGNED_SHORT_5_6_5: return GL_RGB565;
case GL_FLOAT: return GL_RGB32F_EXT;
case GL_HALF_FLOAT_OES: return GL_RGB16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_RGBA8_OES;
case GL_UNSIGNED_SHORT_4_4_4_4: return GL_RGBA4;
case GL_UNSIGNED_SHORT_5_5_5_1: return GL_RGB5_A1;
case GL_FLOAT: return GL_RGBA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_RGBA16F_EXT;
break;
default: UNIMPLEMENTED();
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_BGRA8_EXT;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return GL_BGRA4_ANGLEX;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return GL_BGR5_A1_ANGLEX;
default: UNIMPLEMENTED();
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return format;
case GL_DEPTH_COMPONENT:
switch (type)
{
case GL_UNSIGNED_SHORT: return GL_DEPTH_COMPONENT16;
case GL_UNSIGNED_INT: return GL_DEPTH_COMPONENT32_OES;
default: UNIMPLEMENTED();
}
break;
case GL_DEPTH_STENCIL_OES:
switch (type)
{
case GL_UNSIGNED_INT_24_8_OES: return GL_DEPTH24_STENCIL8_OES;
default: UNIMPLEMENTED();
}
break;
default:
UNIMPLEMENTED();
}
return GL_NONE;
}
GLenum ExtractFormat(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGB565: return GL_RGB;
case GL_RGBA4: return GL_RGBA;
case GL_RGB5_A1: return GL_RGBA;
case GL_RGB8_OES: return GL_RGB;
case GL_RGBA8_OES: return GL_RGBA;
case GL_LUMINANCE8_ALPHA8_EXT: return GL_LUMINANCE_ALPHA;
case GL_LUMINANCE8_EXT: return GL_LUMINANCE;
case GL_ALPHA8_EXT: return GL_ALPHA;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
case GL_RGBA32F_EXT: return GL_RGBA;
case GL_RGB32F_EXT: return GL_RGB;
case GL_ALPHA32F_EXT: return GL_ALPHA;
case GL_LUMINANCE32F_EXT: return GL_LUMINANCE;
case GL_LUMINANCE_ALPHA32F_EXT: return GL_LUMINANCE_ALPHA;
case GL_RGBA16F_EXT: return GL_RGBA;
case GL_RGB16F_EXT: return GL_RGB;
case GL_ALPHA16F_EXT: return GL_ALPHA;
case GL_LUMINANCE16F_EXT: return GL_LUMINANCE;
case GL_LUMINANCE_ALPHA16F_EXT: return GL_LUMINANCE_ALPHA;
case GL_BGRA8_EXT: return GL_BGRA_EXT;
case GL_DEPTH_COMPONENT16: return GL_DEPTH_COMPONENT;
case GL_DEPTH_COMPONENT32_OES: return GL_DEPTH_COMPONENT;
case GL_DEPTH24_STENCIL8_OES: return GL_DEPTH_STENCIL_OES;
default: return GL_NONE; // Unsupported
}
}
GLenum ExtractType(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGB565: return GL_UNSIGNED_SHORT_5_6_5;
case GL_RGBA4: return GL_UNSIGNED_SHORT_4_4_4_4;
case GL_RGB5_A1: return GL_UNSIGNED_SHORT_5_5_5_1;
case GL_RGB8_OES: return GL_UNSIGNED_BYTE;
case GL_RGBA8_OES: return GL_UNSIGNED_BYTE;
case GL_LUMINANCE8_ALPHA8_EXT: return GL_UNSIGNED_BYTE;
case GL_LUMINANCE8_EXT: return GL_UNSIGNED_BYTE;
case GL_ALPHA8_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_UNSIGNED_BYTE;
case GL_RGBA32F_EXT: return GL_FLOAT;
case GL_RGB32F_EXT: return GL_FLOAT;
case GL_ALPHA32F_EXT: return GL_FLOAT;
case GL_LUMINANCE32F_EXT: return GL_FLOAT;
case GL_LUMINANCE_ALPHA32F_EXT: return GL_FLOAT;
case GL_RGBA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_RGB16F_EXT: return GL_HALF_FLOAT_OES;
case GL_ALPHA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_LUMINANCE16F_EXT: return GL_HALF_FLOAT_OES;
case GL_LUMINANCE_ALPHA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_BGRA8_EXT: return GL_UNSIGNED_BYTE;
case GL_DEPTH_COMPONENT16: return GL_UNSIGNED_SHORT;
case GL_DEPTH_COMPONENT32_OES: return GL_UNSIGNED_INT;
case GL_DEPTH24_STENCIL8_OES: return GL_UNSIGNED_INT_24_8_OES;
default: return GL_NONE; // Unsupported
}
}
bool IsColorRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
return true;
case GL_DEPTH_COMPONENT16:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
return false;
case GL_BGRA8_EXT:
return true;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsDepthRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH24_STENCIL8_OES:
return true;
case GL_STENCIL_INDEX8:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsStencilRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
return true;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_DEPTH_COMPONENT16:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsFloat32Format(GLint internalformat)
{
switch (internalformat)
{
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
return true;
default:
return false;
}
}
bool IsFloat16Format(GLint internalformat)
{
switch (internalformat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
return true;
default:
return false;
}
}
unsigned int GetAlphaSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
return 16;
case GL_RGBA32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
return 8;
case GL_RGB5_A1:
return 1;
case GL_RGB8_OES:
case GL_RGB565:
case GL_RGB32F_EXT:
case GL_RGB16F_EXT:
return 0;
default:
return 0;
}
}
unsigned int GetRedSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
case GL_RGB565:
return 5;
default:
return 0;
}
}
unsigned int GetGreenSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
return 5;
case GL_RGB565:
return 6;
default:
return 0;
}
}
unsigned int GetBlueSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
case GL_RGB565:
return 5;
default:
return 0;
}
}
unsigned int GetDepthSize(GLenum depthFormat)
{
switch (depthFormat)
{
case GL_DEPTH_COMPONENT16: return 16;
case GL_DEPTH_COMPONENT32_OES: return 32;
case GL_DEPTH24_STENCIL8_OES: return 24;
default: return 0;
}
}
unsigned int GetStencilSize(GLenum stencilFormat)
{
switch (stencilFormat)
{
case GL_DEPTH24_STENCIL8_OES: return 8;
default: return 0;
}
}
bool IsTriangleMode(GLenum drawMode)
{
switch (drawMode)
{
case GL_TRIANGLES:
case GL_TRIANGLE_FAN:
case GL_TRIANGLE_STRIP:
return true;
case GL_POINTS:
case GL_LINES:
case GL_LINE_LOOP:
case GL_LINE_STRIP:
return false;
default: UNREACHABLE();
}
return false;
}
}
std::string getTempPath()
{
char path[MAX_PATH];
DWORD pathLen = GetTempPathA(sizeof(path) / sizeof(path[0]), path);
if (pathLen == 0)
{
UNREACHABLE();
return std::string();
}
UINT unique = GetTempFileNameA(path, "sh", 0, path);
if (unique == 0)
{
UNREACHABLE();
return std::string();
}
return path;
}
void writeFile(const char* path, const void* content, size_t size)
{
FILE* file = fopen(path, "w");
if (!file)
{
UNREACHABLE();
return;
}
fwrite(content, sizeof(char), size, file);
fclose(file);
}
| C++ |
#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.
//
// main.cpp: DLL entry point and management of thread-local data.
#include "libGLESv2/main.h"
#include "libGLESv2/Context.h"
static DWORD currentTLS = TLS_OUT_OF_INDEXES;
extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
currentTLS = TlsAlloc();
if (currentTLS == TLS_OUT_OF_INDEXES)
{
return FALSE;
}
}
// Fall throught to initialize index
case DLL_THREAD_ATTACH:
{
gl::Current *current = (gl::Current*)LocalAlloc(LPTR, sizeof(gl::Current));
if (current)
{
TlsSetValue(currentTLS, current);
current->context = NULL;
current->display = NULL;
}
}
break;
case DLL_THREAD_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
}
break;
case DLL_PROCESS_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
TlsFree(currentTLS);
}
break;
default:
break;
}
return TRUE;
}
namespace gl
{
void makeCurrent(Context *context, egl::Display *display, egl::Surface *surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->context = context;
current->display = display;
if (context && display && surface)
{
context->makeCurrent(surface);
}
}
Context *getContext()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->context;
}
Context *getNonLostContext()
{
Context *context = getContext();
if (context)
{
if (context->isContextLost())
{
gl::error(GL_OUT_OF_MEMORY);
return NULL;
}
else
{
return context;
}
}
return NULL;
}
egl::Display *getDisplay()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->display;
}
// Records an error code
void error(GLenum errorCode)
{
gl::Context *context = glGetCurrentContext();
if (context)
{
switch (errorCode)
{
case GL_INVALID_ENUM:
context->recordInvalidEnum();
TRACE("\t! Error generated: invalid enum\n");
break;
case GL_INVALID_VALUE:
context->recordInvalidValue();
TRACE("\t! Error generated: invalid value\n");
break;
case GL_INVALID_OPERATION:
context->recordInvalidOperation();
TRACE("\t! Error generated: invalid operation\n");
break;
case GL_OUT_OF_MEMORY:
context->recordOutOfMemory();
TRACE("\t! Error generated: out of memory\n");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
context->recordInvalidFramebufferOperation();
TRACE("\t! Error generated: invalid framebuffer operation\n");
break;
default: UNREACHABLE();
}
}
}
}
| C++ |
//
// 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.
//
// utilities.h: Conversion functions and other utility routines.
#ifndef LIBGLESV2_UTILITIES_H
#define LIBGLESV2_UTILITIES_H
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <string>
namespace gl
{
struct Color;
int UniformComponentCount(GLenum type);
GLenum UniformComponentType(GLenum type);
size_t UniformInternalSize(GLenum type);
size_t UniformExternalSize(GLenum type);
int VariableRowCount(GLenum type);
int VariableColumnCount(GLenum type);
int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize);
void MakeValidSize(bool isImage, bool isCompressed, GLsizei *requestWidth, GLsizei *requestHeight, int *levelOffset);
int ComputePixelSize(GLint internalformat);
GLsizei ComputePitch(GLsizei width, GLint internalformat, GLint alignment);
GLsizei ComputeCompressedPitch(GLsizei width, GLenum format);
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format);
bool IsCompressed(GLenum format);
bool IsDepthTexture(GLenum format);
bool IsStencilTexture(GLenum format);
bool IsCubemapTextureTarget(GLenum target);
bool IsInternalTextureTarget(GLenum target);
GLint ConvertSizedInternalFormat(GLenum format, GLenum type);
GLenum ExtractFormat(GLenum internalformat);
GLenum ExtractType(GLenum internalformat);
bool IsColorRenderable(GLenum internalformat);
bool IsDepthRenderable(GLenum internalformat);
bool IsStencilRenderable(GLenum internalformat);
bool IsFloat32Format(GLint internalformat);
bool IsFloat16Format(GLint internalformat);
GLuint GetAlphaSize(GLenum colorFormat);
GLuint GetRedSize(GLenum colorFormat);
GLuint GetGreenSize(GLenum colorFormat);
GLuint GetBlueSize(GLenum colorFormat);
GLuint GetDepthSize(GLenum depthFormat);
GLuint GetStencilSize(GLenum stencilFormat);
bool IsTriangleMode(GLenum drawMode);
}
std::string getTempPath();
void writeFile(const char* path, const void* data, size_t size);
#endif // LIBGLESV2_UTILITIES_H
| C++ |
//
// 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.
//
// main.h: Management of thread-local data.
#ifndef LIBGLESV2_MAIN_H_
#define LIBGLESV2_MAIN_H_
#include "common/debug.h"
#include "common/system.h"
namespace egl
{
class Display;
class Surface;
}
namespace gl
{
class Context;
struct Current
{
Context *context;
egl::Display *display;
};
void makeCurrent(Context *context, egl::Display *display, egl::Surface *surface);
Context *getContext();
Context *getNonLostContext();
egl::Display *getDisplay();
void error(GLenum errorCode);
template<class T>
const T &error(GLenum errorCode, const T &returnValue)
{
error(errorCode);
return returnValue;
}
}
namespace rx
{
class Renderer;
}
extern "C"
{
// Exported functions for use by EGL
gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess);
void glDestroyContext(gl::Context *context);
void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface);
gl::Context *glGetCurrentContext();
rx::Renderer *glCreateRenderer(egl::Display *display, HDC hDc, EGLNativeDisplayType displayId);
void glDestroyRenderer(rx::Renderer *renderer);
__eglMustCastToProperFunctionPointerType __stdcall glGetProcAddress(const char *procname);
bool __stdcall glBindTexImage(egl::Surface *surface);
}
#endif // LIBGLESV2_MAIN_H_
| C++ |
#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.
//
// Program.cpp: Implements the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/ResourceManager.h"
namespace gl
{
const char * const g_fakepath = "C:\\fakepath";
AttributeBindings::AttributeBindings()
{
}
AttributeBindings::~AttributeBindings()
{
}
InfoLog::InfoLog() : mInfoLog(NULL)
{
}
InfoLog::~InfoLog()
{
delete[] mInfoLog;
}
int InfoLog::getLength() const
{
if (!mInfoLog)
{
return 0;
}
else
{
return strlen(mInfoLog) + 1;
}
}
void InfoLog::getLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
int index = 0;
if (bufSize > 0)
{
if (mInfoLog)
{
index = std::min(bufSize - 1, (int)strlen(mInfoLog));
memcpy(infoLog, mInfoLog, index);
}
infoLog[index] = '\0';
}
if (length)
{
*length = index;
}
}
// append a santized message to the program info log.
// The D3D compiler includes a fake file path in some of the warning or error
// messages, so lets remove all occurrences of this fake file path from the log.
void InfoLog::appendSanitized(const char *message)
{
std::string msg(message);
size_t found;
do
{
found = msg.find(g_fakepath);
if (found != std::string::npos)
{
msg.erase(found, strlen(g_fakepath));
}
}
while (found != std::string::npos);
append("%s", msg.c_str());
}
void InfoLog::append(const char *format, ...)
{
if (!format)
{
return;
}
char info[1024];
va_list vararg;
va_start(vararg, format);
vsnprintf(info, sizeof(info), format, vararg);
va_end(vararg);
size_t infoLength = strlen(info);
if (!mInfoLog)
{
mInfoLog = new char[infoLength + 2];
strcpy(mInfoLog, info);
strcpy(mInfoLog + infoLength, "\n");
}
else
{
size_t logLength = strlen(mInfoLog);
char *newLog = new char[logLength + infoLength + 2];
strcpy(newLog, mInfoLog);
strcpy(newLog + logLength, info);
strcpy(newLog + logLength + infoLength, "\n");
delete[] mInfoLog;
mInfoLog = newLog;
}
}
void InfoLog::reset()
{
if (mInfoLog)
{
delete [] mInfoLog;
mInfoLog = NULL;
}
}
Program::Program(rx::Renderer *renderer, ResourceManager *manager, GLuint handle) : mResourceManager(manager), mHandle(handle)
{
mFragmentShader = NULL;
mVertexShader = NULL;
mProgramBinary.set(NULL);
mDeleteStatus = false;
mLinked = false;
mRefCount = 0;
mRenderer = renderer;
}
Program::~Program()
{
unlink(true);
if (mVertexShader != NULL)
{
mVertexShader->release();
}
if (mFragmentShader != NULL)
{
mFragmentShader->release();
}
}
bool Program::attachShader(Shader *shader)
{
if (shader->getType() == GL_VERTEX_SHADER)
{
if (mVertexShader)
{
return false;
}
mVertexShader = (VertexShader*)shader;
mVertexShader->addRef();
}
else if (shader->getType() == GL_FRAGMENT_SHADER)
{
if (mFragmentShader)
{
return false;
}
mFragmentShader = (FragmentShader*)shader;
mFragmentShader->addRef();
}
else UNREACHABLE();
return true;
}
bool Program::detachShader(Shader *shader)
{
if (shader->getType() == GL_VERTEX_SHADER)
{
if (mVertexShader != shader)
{
return false;
}
mVertexShader->release();
mVertexShader = NULL;
}
else if (shader->getType() == GL_FRAGMENT_SHADER)
{
if (mFragmentShader != shader)
{
return false;
}
mFragmentShader->release();
mFragmentShader = NULL;
}
else UNREACHABLE();
return true;
}
int Program::getAttachedShadersCount() const
{
return (mVertexShader ? 1 : 0) + (mFragmentShader ? 1 : 0);
}
void AttributeBindings::bindAttributeLocation(GLuint index, const char *name)
{
if (index < MAX_VERTEX_ATTRIBS)
{
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
mAttributeBinding[i].erase(name);
}
mAttributeBinding[index].insert(name);
}
}
void Program::bindAttributeLocation(GLuint index, const char *name)
{
mAttributeBindings.bindAttributeLocation(index, name);
}
// Links the HLSL code of the vertex and pixel shader by matching up their varyings,
// compiling them into binaries, determining the attribute mappings, and collecting
// a list of uniforms
bool Program::link()
{
unlink(false);
mInfoLog.reset();
mProgramBinary.set(new ProgramBinary(mRenderer));
mLinked = mProgramBinary->link(mInfoLog, mAttributeBindings, mFragmentShader, mVertexShader);
return mLinked;
}
int AttributeBindings::getAttributeBinding(const std::string &name) const
{
for (int location = 0; location < MAX_VERTEX_ATTRIBS; location++)
{
if (mAttributeBinding[location].find(name) != mAttributeBinding[location].end())
{
return location;
}
}
return -1;
}
// Returns the program object to an unlinked state, before re-linking, or at destruction
void Program::unlink(bool destroy)
{
if (destroy) // Object being destructed
{
if (mFragmentShader)
{
mFragmentShader->release();
mFragmentShader = NULL;
}
if (mVertexShader)
{
mVertexShader->release();
mVertexShader = NULL;
}
}
mProgramBinary.set(NULL);
mLinked = false;
}
bool Program::isLinked()
{
return mLinked;
}
ProgramBinary* Program::getProgramBinary()
{
return mProgramBinary.get();
}
bool Program::setProgramBinary(const void *binary, GLsizei length)
{
unlink(false);
mInfoLog.reset();
mProgramBinary.set(new ProgramBinary(mRenderer));
mLinked = mProgramBinary->load(mInfoLog, binary, length);
if (!mLinked)
{
mProgramBinary.set(NULL);
}
return mLinked;
}
void Program::release()
{
mRefCount--;
if (mRefCount == 0 && mDeleteStatus)
{
mResourceManager->deleteProgram(mHandle);
}
}
void Program::addRef()
{
mRefCount++;
}
unsigned int Program::getRefCount() const
{
return mRefCount;
}
GLint Program::getProgramBinaryLength() const
{
ProgramBinary *programBinary = mProgramBinary.get();
if (programBinary)
{
return programBinary->getLength();
}
else
{
return 0;
}
}
int Program::getInfoLogLength() const
{
return mInfoLog.getLength();
}
void Program::getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
return mInfoLog.getLog(bufSize, length, infoLog);
}
void Program::getAttachedShaders(GLsizei maxCount, GLsizei *count, GLuint *shaders)
{
int total = 0;
if (mVertexShader)
{
if (total < maxCount)
{
shaders[total] = mVertexShader->getHandle();
}
total++;
}
if (mFragmentShader)
{
if (total < maxCount)
{
shaders[total] = mFragmentShader->getHandle();
}
total++;
}
if (count)
{
*count = total;
}
}
void Program::getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
programBinary->getActiveAttribute(index, bufsize, length, size, type, name);
}
else
{
if (bufsize > 0)
{
name[0] = '\0';
}
if (length)
{
*length = 0;
}
*type = GL_NONE;
*size = 1;
}
}
GLint Program::getActiveAttributeCount()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveAttributeCount();
}
else
{
return 0;
}
}
GLint Program::getActiveAttributeMaxLength()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveAttributeMaxLength();
}
else
{
return 0;
}
}
void Program::getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniform(index, bufsize, length, size, type, name);
}
else
{
if (bufsize > 0)
{
name[0] = '\0';
}
if (length)
{
*length = 0;
}
*size = 0;
*type = GL_NONE;
}
}
GLint Program::getActiveUniformCount()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniformCount();
}
else
{
return 0;
}
}
GLint Program::getActiveUniformMaxLength()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniformMaxLength();
}
else
{
return 0;
}
}
void Program::flagForDeletion()
{
mDeleteStatus = true;
}
bool Program::isFlaggedForDeletion() const
{
return mDeleteStatus;
}
void Program::validate()
{
mInfoLog.reset();
ProgramBinary *programBinary = getProgramBinary();
if (isLinked() && programBinary)
{
programBinary->validate(mInfoLog);
}
else
{
mInfoLog.append("Program has not been successfully linked.");
}
}
bool Program::isValidated() const
{
ProgramBinary *programBinary = mProgramBinary.get();
if (programBinary)
{
return programBinary->isValidated();
}
else
{
return false;
}
}
}
| C++ |
#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.
//
// Context.cpp: Implements the gl::Context class, managing all GL state and performing
// rendering operations. It is the GLES2 specific implementation of EGLContext.
#include "libGLESv2/Context.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Fence.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Query.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/ResourceManager.h"
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/RenderTarget.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libEGL/Surface.h"
#undef near
#undef far
namespace gl
{
static const char* makeStaticString(const std::string& str)
{
static std::set<std::string> strings;
std::set<std::string>::iterator it = strings.find(str);
if (it != strings.end())
return it->c_str();
return strings.insert(str).first->c_str();
}
Context::Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess) : mRenderer(renderer)
{
ASSERT(robustAccess == false); // Unimplemented
mFenceHandleAllocator.setBaseHandle(0);
setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
mState.depthClearValue = 1.0f;
mState.stencilClearValue = 0;
mState.rasterizer.cullFace = false;
mState.rasterizer.cullMode = GL_BACK;
mState.rasterizer.frontFace = GL_CCW;
mState.rasterizer.polygonOffsetFill = false;
mState.rasterizer.polygonOffsetFactor = 0.0f;
mState.rasterizer.polygonOffsetUnits = 0.0f;
mState.rasterizer.pointDrawMode = false;
mState.rasterizer.multiSample = false;
mState.scissorTest = false;
mState.scissor.x = 0;
mState.scissor.y = 0;
mState.scissor.width = 0;
mState.scissor.height = 0;
mState.blend.blend = false;
mState.blend.sourceBlendRGB = GL_ONE;
mState.blend.sourceBlendAlpha = GL_ONE;
mState.blend.destBlendRGB = GL_ZERO;
mState.blend.destBlendAlpha = GL_ZERO;
mState.blend.blendEquationRGB = GL_FUNC_ADD;
mState.blend.blendEquationAlpha = GL_FUNC_ADD;
mState.blend.sampleAlphaToCoverage = false;
mState.blend.dither = true;
mState.blendColor.red = 0;
mState.blendColor.green = 0;
mState.blendColor.blue = 0;
mState.blendColor.alpha = 0;
mState.depthStencil.depthTest = false;
mState.depthStencil.depthFunc = GL_LESS;
mState.depthStencil.depthMask = true;
mState.depthStencil.stencilTest = false;
mState.depthStencil.stencilFunc = GL_ALWAYS;
mState.depthStencil.stencilMask = -1;
mState.depthStencil.stencilWritemask = -1;
mState.depthStencil.stencilBackFunc = GL_ALWAYS;
mState.depthStencil.stencilBackMask = - 1;
mState.depthStencil.stencilBackWritemask = -1;
mState.depthStencil.stencilFail = GL_KEEP;
mState.depthStencil.stencilPassDepthFail = GL_KEEP;
mState.depthStencil.stencilPassDepthPass = GL_KEEP;
mState.depthStencil.stencilBackFail = GL_KEEP;
mState.depthStencil.stencilBackPassDepthFail = GL_KEEP;
mState.depthStencil.stencilBackPassDepthPass = GL_KEEP;
mState.stencilRef = 0;
mState.stencilBackRef = 0;
mState.sampleCoverage = false;
mState.sampleCoverageValue = 1.0f;
mState.sampleCoverageInvert = false;
mState.generateMipmapHint = GL_DONT_CARE;
mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
mState.lineWidth = 1.0f;
mState.viewport.x = 0;
mState.viewport.y = 0;
mState.viewport.width = 0;
mState.viewport.height = 0;
mState.zNear = 0.0f;
mState.zFar = 1.0f;
mState.blend.colorMaskRed = true;
mState.blend.colorMaskGreen = true;
mState.blend.colorMaskBlue = true;
mState.blend.colorMaskAlpha = true;
if (shareContext != NULL)
{
mResourceManager = shareContext->mResourceManager;
mResourceManager->addRef();
}
else
{
mResourceManager = new ResourceManager(mRenderer);
}
// [OpenGL ES 2.0.24] section 3.7 page 83:
// In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
// and cube map texture state vectors respectively associated with them.
// In order that access to these initial textures not be lost, they are treated as texture
// objects all of whose names are 0.
mTexture2DZero.set(new Texture2D(mRenderer, 0));
mTextureCubeMapZero.set(new TextureCubeMap(mRenderer, 0));
mState.activeSampler = 0;
bindArrayBuffer(0);
bindElementArrayBuffer(0);
bindTextureCubeMap(0);
bindTexture2D(0);
bindReadFramebuffer(0);
bindDrawFramebuffer(0);
bindRenderbuffer(0);
mState.currentProgram = 0;
mCurrentProgramBinary.set(NULL);
mState.packAlignment = 4;
mState.unpackAlignment = 4;
mState.packReverseRowOrder = false;
mExtensionString = NULL;
mRendererString = NULL;
mInvalidEnum = false;
mInvalidValue = false;
mInvalidOperation = false;
mOutOfMemory = false;
mInvalidFramebufferOperation = false;
mHasBeenCurrent = false;
mContextLost = false;
mResetStatus = GL_NO_ERROR;
mResetStrategy = (notifyResets ? GL_LOSE_CONTEXT_ON_RESET_EXT : GL_NO_RESET_NOTIFICATION_EXT);
mRobustAccess = robustAccess;
mSupportsBGRATextures = false;
mSupportsDXT1Textures = false;
mSupportsDXT3Textures = false;
mSupportsDXT5Textures = false;
mSupportsEventQueries = false;
mSupportsOcclusionQueries = false;
mNumCompressedTextureFormats = 0;
}
Context::~Context()
{
if (mState.currentProgram != 0)
{
Program *programObject = mResourceManager->getProgram(mState.currentProgram);
if (programObject)
{
programObject->release();
}
mState.currentProgram = 0;
}
mCurrentProgramBinary.set(NULL);
while (!mFramebufferMap.empty())
{
deleteFramebuffer(mFramebufferMap.begin()->first);
}
while (!mFenceMap.empty())
{
deleteFence(mFenceMap.begin()->first);
}
while (!mQueryMap.empty())
{
deleteQuery(mQueryMap.begin()->first);
}
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
for (int sampler = 0; sampler < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
{
mState.samplerTexture[type][sampler].set(NULL);
}
}
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
mIncompleteTextures[type].set(NULL);
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
mState.vertexAttribute[i].mBoundBuffer.set(NULL);
}
for (int i = 0; i < QUERY_TYPE_COUNT; i++)
{
mState.activeQuery[i].set(NULL);
}
mState.arrayBuffer.set(NULL);
mState.elementArrayBuffer.set(NULL);
mState.renderbuffer.set(NULL);
mTexture2DZero.set(NULL);
mTextureCubeMapZero.set(NULL);
mResourceManager->release();
}
void Context::makeCurrent(egl::Surface *surface)
{
if (!mHasBeenCurrent)
{
mMajorShaderModel = mRenderer->getMajorShaderModel();
mMaximumPointSize = mRenderer->getMaxPointSize();
mSupportsVertexTexture = mRenderer->getVertexTextureSupport();
mSupportsNonPower2Texture = mRenderer->getNonPower2TextureSupport();
mSupportsInstancing = mRenderer->getInstancingSupport();
mMaxViewportDimension = mRenderer->getMaxViewportDimension();
mMaxTextureDimension = std::min(std::min(mRenderer->getMaxTextureWidth(), mRenderer->getMaxTextureHeight()),
(int)gl::IMPLEMENTATION_MAX_TEXTURE_SIZE);
mMaxCubeTextureDimension = std::min(mMaxTextureDimension, (int)gl::IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE);
mMaxRenderbufferDimension = mMaxTextureDimension;
mMaxTextureLevel = log2(mMaxTextureDimension) + 1;
mMaxTextureAnisotropy = mRenderer->getTextureMaxAnisotropy();
TRACE("MaxTextureDimension=%d, MaxCubeTextureDimension=%d, MaxRenderbufferDimension=%d, MaxTextureLevel=%d, MaxTextureAnisotropy=%f",
mMaxTextureDimension, mMaxCubeTextureDimension, mMaxRenderbufferDimension, mMaxTextureLevel, mMaxTextureAnisotropy);
mSupportsEventQueries = mRenderer->getEventQuerySupport();
mSupportsOcclusionQueries = mRenderer->getOcclusionQuerySupport();
mSupportsBGRATextures = mRenderer->getBGRATextureSupport();
mSupportsDXT1Textures = mRenderer->getDXT1TextureSupport();
mSupportsDXT3Textures = mRenderer->getDXT3TextureSupport();
mSupportsDXT5Textures = mRenderer->getDXT5TextureSupport();
mSupportsFloat32Textures = mRenderer->getFloat32TextureSupport(&mSupportsFloat32LinearFilter, &mSupportsFloat32RenderableTextures);
mSupportsFloat16Textures = mRenderer->getFloat16TextureSupport(&mSupportsFloat16LinearFilter, &mSupportsFloat16RenderableTextures);
mSupportsLuminanceTextures = mRenderer->getLuminanceTextureSupport();
mSupportsLuminanceAlphaTextures = mRenderer->getLuminanceAlphaTextureSupport();
mSupportsDepthTextures = mRenderer->getDepthTextureSupport();
mSupportsTextureFilterAnisotropy = mRenderer->getTextureFilterAnisotropySupport();
mSupports32bitIndices = mRenderer->get32BitIndexSupport();
mNumCompressedTextureFormats = 0;
if (supportsDXT1Textures())
{
mNumCompressedTextureFormats += 2;
}
if (supportsDXT3Textures())
{
mNumCompressedTextureFormats += 1;
}
if (supportsDXT5Textures())
{
mNumCompressedTextureFormats += 1;
}
initExtensionString();
initRendererString();
mState.viewport.x = 0;
mState.viewport.y = 0;
mState.viewport.width = surface->getWidth();
mState.viewport.height = surface->getHeight();
mState.scissor.x = 0;
mState.scissor.y = 0;
mState.scissor.width = surface->getWidth();
mState.scissor.height = surface->getHeight();
mHasBeenCurrent = true;
}
// Wrap the existing swapchain resources into GL objects and assign them to the '0' names
rx::SwapChain *swapchain = surface->getSwapChain();
Colorbuffer *colorbufferZero = new Colorbuffer(mRenderer, swapchain);
DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(mRenderer, swapchain);
Framebuffer *framebufferZero = new DefaultFramebuffer(mRenderer, colorbufferZero, depthStencilbufferZero);
setFramebufferZero(framebufferZero);
}
// NOTE: this function should not assume that this context is current!
void Context::markContextLost()
{
if (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT)
mResetStatus = GL_UNKNOWN_CONTEXT_RESET_EXT;
mContextLost = true;
}
bool Context::isContextLost()
{
return mContextLost;
}
void Context::setClearColor(float red, float green, float blue, float alpha)
{
mState.colorClearValue.red = red;
mState.colorClearValue.green = green;
mState.colorClearValue.blue = blue;
mState.colorClearValue.alpha = alpha;
}
void Context::setClearDepth(float depth)
{
mState.depthClearValue = depth;
}
void Context::setClearStencil(int stencil)
{
mState.stencilClearValue = stencil;
}
void Context::setCullFace(bool enabled)
{
mState.rasterizer.cullFace = enabled;
}
bool Context::isCullFaceEnabled() const
{
return mState.rasterizer.cullFace;
}
void Context::setCullMode(GLenum mode)
{
mState.rasterizer.cullMode = mode;
}
void Context::setFrontFace(GLenum front)
{
mState.rasterizer.frontFace = front;
}
void Context::setDepthTest(bool enabled)
{
mState.depthStencil.depthTest = enabled;
}
bool Context::isDepthTestEnabled() const
{
return mState.depthStencil.depthTest;
}
void Context::setDepthFunc(GLenum depthFunc)
{
mState.depthStencil.depthFunc = depthFunc;
}
void Context::setDepthRange(float zNear, float zFar)
{
mState.zNear = zNear;
mState.zFar = zFar;
}
void Context::setBlend(bool enabled)
{
mState.blend.blend = enabled;
}
bool Context::isBlendEnabled() const
{
return mState.blend.blend;
}
void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
{
mState.blend.sourceBlendRGB = sourceRGB;
mState.blend.destBlendRGB = destRGB;
mState.blend.sourceBlendAlpha = sourceAlpha;
mState.blend.destBlendAlpha = destAlpha;
}
void Context::setBlendColor(float red, float green, float blue, float alpha)
{
mState.blendColor.red = red;
mState.blendColor.green = green;
mState.blendColor.blue = blue;
mState.blendColor.alpha = alpha;
}
void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
{
mState.blend.blendEquationRGB = rgbEquation;
mState.blend.blendEquationAlpha = alphaEquation;
}
void Context::setStencilTest(bool enabled)
{
mState.depthStencil.stencilTest = enabled;
}
bool Context::isStencilTestEnabled() const
{
return mState.depthStencil.stencilTest;
}
void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
{
mState.depthStencil.stencilFunc = stencilFunc;
mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
mState.depthStencil.stencilMask = stencilMask;
}
void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
{
mState.depthStencil.stencilBackFunc = stencilBackFunc;
mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
mState.depthStencil.stencilBackMask = stencilBackMask;
}
void Context::setStencilWritemask(GLuint stencilWritemask)
{
mState.depthStencil.stencilWritemask = stencilWritemask;
}
void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
{
mState.depthStencil.stencilBackWritemask = stencilBackWritemask;
}
void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
{
mState.depthStencil.stencilFail = stencilFail;
mState.depthStencil.stencilPassDepthFail = stencilPassDepthFail;
mState.depthStencil.stencilPassDepthPass = stencilPassDepthPass;
}
void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
{
mState.depthStencil.stencilBackFail = stencilBackFail;
mState.depthStencil.stencilBackPassDepthFail = stencilBackPassDepthFail;
mState.depthStencil.stencilBackPassDepthPass = stencilBackPassDepthPass;
}
void Context::setPolygonOffsetFill(bool enabled)
{
mState.rasterizer.polygonOffsetFill = enabled;
}
bool Context::isPolygonOffsetFillEnabled() const
{
return mState.rasterizer.polygonOffsetFill;
}
void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
{
// An application can pass NaN values here, so handle this gracefully
mState.rasterizer.polygonOffsetFactor = factor != factor ? 0.0f : factor;
mState.rasterizer.polygonOffsetUnits = units != units ? 0.0f : units;
}
void Context::setSampleAlphaToCoverage(bool enabled)
{
mState.blend.sampleAlphaToCoverage = enabled;
}
bool Context::isSampleAlphaToCoverageEnabled() const
{
return mState.blend.sampleAlphaToCoverage;
}
void Context::setSampleCoverage(bool enabled)
{
mState.sampleCoverage = enabled;
}
bool Context::isSampleCoverageEnabled() const
{
return mState.sampleCoverage;
}
void Context::setSampleCoverageParams(GLclampf value, bool invert)
{
mState.sampleCoverageValue = value;
mState.sampleCoverageInvert = invert;
}
void Context::setScissorTest(bool enabled)
{
mState.scissorTest = enabled;
}
bool Context::isScissorTestEnabled() const
{
return mState.scissorTest;
}
void Context::setDither(bool enabled)
{
mState.blend.dither = enabled;
}
bool Context::isDitherEnabled() const
{
return mState.blend.dither;
}
void Context::setLineWidth(GLfloat width)
{
mState.lineWidth = width;
}
void Context::setGenerateMipmapHint(GLenum hint)
{
mState.generateMipmapHint = hint;
}
void Context::setFragmentShaderDerivativeHint(GLenum hint)
{
mState.fragmentShaderDerivativeHint = hint;
// TODO: Propagate the hint to shader translator so we can write
// ddx, ddx_coarse, or ddx_fine depending on the hint.
// Ignore for now. It is valid for implementations to ignore hint.
}
void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
{
mState.viewport.x = x;
mState.viewport.y = y;
mState.viewport.width = width;
mState.viewport.height = height;
}
void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
{
mState.scissor.x = x;
mState.scissor.y = y;
mState.scissor.width = width;
mState.scissor.height = height;
}
void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
{
mState.blend.colorMaskRed = red;
mState.blend.colorMaskGreen = green;
mState.blend.colorMaskBlue = blue;
mState.blend.colorMaskAlpha = alpha;
}
void Context::setDepthMask(bool mask)
{
mState.depthStencil.depthMask = mask;
}
void Context::setActiveSampler(unsigned int active)
{
mState.activeSampler = active;
}
GLuint Context::getReadFramebufferHandle() const
{
return mState.readFramebuffer;
}
GLuint Context::getDrawFramebufferHandle() const
{
return mState.drawFramebuffer;
}
GLuint Context::getRenderbufferHandle() const
{
return mState.renderbuffer.id();
}
GLuint Context::getArrayBufferHandle() const
{
return mState.arrayBuffer.id();
}
GLuint Context::getActiveQuery(GLenum target) const
{
Query *queryObject = NULL;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED].get();
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE].get();
break;
default:
ASSERT(false);
}
if (queryObject)
{
return queryObject->id();
}
else
{
return 0;
}
}
void Context::setEnableVertexAttribArray(unsigned int attribNum, bool enabled)
{
mState.vertexAttribute[attribNum].mArrayEnabled = enabled;
}
const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum)
{
return mState.vertexAttribute[attribNum];
}
void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
GLsizei stride, const void *pointer)
{
mState.vertexAttribute[attribNum].mBoundBuffer.set(boundBuffer);
mState.vertexAttribute[attribNum].mSize = size;
mState.vertexAttribute[attribNum].mType = type;
mState.vertexAttribute[attribNum].mNormalized = normalized;
mState.vertexAttribute[attribNum].mStride = stride;
mState.vertexAttribute[attribNum].mPointer = pointer;
}
const void *Context::getVertexAttribPointer(unsigned int attribNum) const
{
return mState.vertexAttribute[attribNum].mPointer;
}
void Context::setPackAlignment(GLint alignment)
{
mState.packAlignment = alignment;
}
GLint Context::getPackAlignment() const
{
return mState.packAlignment;
}
void Context::setUnpackAlignment(GLint alignment)
{
mState.unpackAlignment = alignment;
}
GLint Context::getUnpackAlignment() const
{
return mState.unpackAlignment;
}
void Context::setPackReverseRowOrder(bool reverseRowOrder)
{
mState.packReverseRowOrder = reverseRowOrder;
}
bool Context::getPackReverseRowOrder() const
{
return mState.packReverseRowOrder;
}
GLuint Context::createBuffer()
{
return mResourceManager->createBuffer();
}
GLuint Context::createProgram()
{
return mResourceManager->createProgram();
}
GLuint Context::createShader(GLenum type)
{
return mResourceManager->createShader(type);
}
GLuint Context::createTexture()
{
return mResourceManager->createTexture();
}
GLuint Context::createRenderbuffer()
{
return mResourceManager->createRenderbuffer();
}
// Returns an unused framebuffer name
GLuint Context::createFramebuffer()
{
GLuint handle = mFramebufferHandleAllocator.allocate();
mFramebufferMap[handle] = NULL;
return handle;
}
GLuint Context::createFence()
{
GLuint handle = mFenceHandleAllocator.allocate();
mFenceMap[handle] = new Fence(mRenderer);
return handle;
}
// Returns an unused query name
GLuint Context::createQuery()
{
GLuint handle = mQueryHandleAllocator.allocate();
mQueryMap[handle] = NULL;
return handle;
}
void Context::deleteBuffer(GLuint buffer)
{
if (mResourceManager->getBuffer(buffer))
{
detachBuffer(buffer);
}
mResourceManager->deleteBuffer(buffer);
}
void Context::deleteShader(GLuint shader)
{
mResourceManager->deleteShader(shader);
}
void Context::deleteProgram(GLuint program)
{
mResourceManager->deleteProgram(program);
}
void Context::deleteTexture(GLuint texture)
{
if (mResourceManager->getTexture(texture))
{
detachTexture(texture);
}
mResourceManager->deleteTexture(texture);
}
void Context::deleteRenderbuffer(GLuint renderbuffer)
{
if (mResourceManager->getRenderbuffer(renderbuffer))
{
detachRenderbuffer(renderbuffer);
}
mResourceManager->deleteRenderbuffer(renderbuffer);
}
void Context::deleteFramebuffer(GLuint framebuffer)
{
FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
if (framebufferObject != mFramebufferMap.end())
{
detachFramebuffer(framebuffer);
mFramebufferHandleAllocator.release(framebufferObject->first);
delete framebufferObject->second;
mFramebufferMap.erase(framebufferObject);
}
}
void Context::deleteFence(GLuint fence)
{
FenceMap::iterator fenceObject = mFenceMap.find(fence);
if (fenceObject != mFenceMap.end())
{
mFenceHandleAllocator.release(fenceObject->first);
delete fenceObject->second;
mFenceMap.erase(fenceObject);
}
}
void Context::deleteQuery(GLuint query)
{
QueryMap::iterator queryObject = mQueryMap.find(query);
if (queryObject != mQueryMap.end())
{
mQueryHandleAllocator.release(queryObject->first);
if (queryObject->second)
{
queryObject->second->release();
}
mQueryMap.erase(queryObject);
}
}
Buffer *Context::getBuffer(GLuint handle)
{
return mResourceManager->getBuffer(handle);
}
Shader *Context::getShader(GLuint handle)
{
return mResourceManager->getShader(handle);
}
Program *Context::getProgram(GLuint handle)
{
return mResourceManager->getProgram(handle);
}
Texture *Context::getTexture(GLuint handle)
{
return mResourceManager->getTexture(handle);
}
Renderbuffer *Context::getRenderbuffer(GLuint handle)
{
return mResourceManager->getRenderbuffer(handle);
}
Framebuffer *Context::getReadFramebuffer()
{
return getFramebuffer(mState.readFramebuffer);
}
Framebuffer *Context::getDrawFramebuffer()
{
return mBoundDrawFramebuffer;
}
void Context::bindArrayBuffer(unsigned int buffer)
{
mResourceManager->checkBufferAllocation(buffer);
mState.arrayBuffer.set(getBuffer(buffer));
}
void Context::bindElementArrayBuffer(unsigned int buffer)
{
mResourceManager->checkBufferAllocation(buffer);
mState.elementArrayBuffer.set(getBuffer(buffer));
}
void Context::bindTexture2D(GLuint texture)
{
mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
mState.samplerTexture[TEXTURE_2D][mState.activeSampler].set(getTexture(texture));
}
void Context::bindTextureCubeMap(GLuint texture)
{
mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].set(getTexture(texture));
}
void Context::bindReadFramebuffer(GLuint framebuffer)
{
if (!getFramebuffer(framebuffer))
{
mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
}
mState.readFramebuffer = framebuffer;
}
void Context::bindDrawFramebuffer(GLuint framebuffer)
{
if (!getFramebuffer(framebuffer))
{
mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
}
mState.drawFramebuffer = framebuffer;
mBoundDrawFramebuffer = getFramebuffer(framebuffer);
}
void Context::bindRenderbuffer(GLuint renderbuffer)
{
mResourceManager->checkRenderbufferAllocation(renderbuffer);
mState.renderbuffer.set(getRenderbuffer(renderbuffer));
}
void Context::useProgram(GLuint program)
{
GLuint priorProgram = mState.currentProgram;
mState.currentProgram = program; // Must switch before trying to delete, otherwise it only gets flagged.
if (priorProgram != program)
{
Program *newProgram = mResourceManager->getProgram(program);
Program *oldProgram = mResourceManager->getProgram(priorProgram);
mCurrentProgramBinary.set(NULL);
if (newProgram)
{
newProgram->addRef();
mCurrentProgramBinary.set(newProgram->getProgramBinary());
}
if (oldProgram)
{
oldProgram->release();
}
}
}
void Context::linkProgram(GLuint program)
{
Program *programObject = mResourceManager->getProgram(program);
bool linked = programObject->link();
// if the current program was relinked successfully we
// need to install the new executables
if (linked && program == mState.currentProgram)
{
mCurrentProgramBinary.set(programObject->getProgramBinary());
}
}
void Context::setProgramBinary(GLuint program, const void *binary, GLint length)
{
Program *programObject = mResourceManager->getProgram(program);
bool loaded = programObject->setProgramBinary(binary, length);
// if the current program was reloaded successfully we
// need to install the new executables
if (loaded && program == mState.currentProgram)
{
mCurrentProgramBinary.set(programObject->getProgramBinary());
}
}
void Context::beginQuery(GLenum target, GLuint query)
{
// From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
// of zero, if the active query object name for <target> is non-zero (for the
// targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
// the active query for either target is non-zero), if <id> is the name of an
// existing query object whose type does not match <target>, or if <id> is the
// active query object name for any query type, the error INVALID_OPERATION is
// generated.
// Ensure no other queries are active
// NOTE: If other queries than occlusion are supported, we will need to check
// separately that:
// a) The query ID passed is not the current active query for any target/type
// b) There are no active queries for the requested target (and in the case
// of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
// no query may be active for either if glBeginQuery targets either.
for (int i = 0; i < QUERY_TYPE_COUNT; i++)
{
if (mState.activeQuery[i].get() != NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
}
QueryType qType;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
qType = QUERY_ANY_SAMPLES_PASSED;
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
break;
default:
ASSERT(false);
return;
}
Query *queryObject = getQuery(query, true, target);
// check that name was obtained with glGenQueries
if (!queryObject)
{
return gl::error(GL_INVALID_OPERATION);
}
// check for type mismatch
if (queryObject->getType() != target)
{
return gl::error(GL_INVALID_OPERATION);
}
// set query as active for specified target
mState.activeQuery[qType].set(queryObject);
// begin query
queryObject->begin();
}
void Context::endQuery(GLenum target)
{
QueryType qType;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
qType = QUERY_ANY_SAMPLES_PASSED;
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
break;
default:
ASSERT(false);
return;
}
Query *queryObject = mState.activeQuery[qType].get();
if (queryObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
queryObject->end();
mState.activeQuery[qType].set(NULL);
}
void Context::setFramebufferZero(Framebuffer *buffer)
{
delete mFramebufferMap[0];
mFramebufferMap[0] = buffer;
if (mState.drawFramebuffer == 0)
{
mBoundDrawFramebuffer = buffer;
}
}
void Context::setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples)
{
RenderbufferStorage *renderbuffer = NULL;
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
renderbuffer = new gl::Depthbuffer(mRenderer, width, height, samples);
break;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
renderbuffer = new gl::Colorbuffer(mRenderer,width, height, internalformat, samples);
break;
case GL_STENCIL_INDEX8:
renderbuffer = new gl::Stencilbuffer(mRenderer, width, height, samples);
break;
case GL_DEPTH24_STENCIL8_OES:
renderbuffer = new gl::DepthStencilbuffer(mRenderer, width, height, samples);
break;
default:
UNREACHABLE(); return;
}
Renderbuffer *renderbufferObject = mState.renderbuffer.get();
renderbufferObject->setStorage(renderbuffer);
}
Framebuffer *Context::getFramebuffer(unsigned int handle)
{
FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
if (framebuffer == mFramebufferMap.end())
{
return NULL;
}
else
{
return framebuffer->second;
}
}
Fence *Context::getFence(unsigned int handle)
{
FenceMap::iterator fence = mFenceMap.find(handle);
if (fence == mFenceMap.end())
{
return NULL;
}
else
{
return fence->second;
}
}
Query *Context::getQuery(unsigned int handle, bool create, GLenum type)
{
QueryMap::iterator query = mQueryMap.find(handle);
if (query == mQueryMap.end())
{
return NULL;
}
else
{
if (!query->second && create)
{
query->second = new Query(mRenderer, type, handle);
query->second->addRef();
}
return query->second;
}
}
Buffer *Context::getArrayBuffer()
{
return mState.arrayBuffer.get();
}
Buffer *Context::getElementArrayBuffer()
{
return mState.elementArrayBuffer.get();
}
ProgramBinary *Context::getCurrentProgramBinary()
{
return mCurrentProgramBinary.get();
}
Texture2D *Context::getTexture2D()
{
return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
}
TextureCubeMap *Context::getTextureCubeMap()
{
return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
}
Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
{
GLuint texid = mState.samplerTexture[type][sampler].id();
if (texid == 0) // Special case: 0 refers to different initial textures based on the target
{
switch (type)
{
default: UNREACHABLE();
case TEXTURE_2D: return mTexture2DZero.get();
case TEXTURE_CUBE: return mTextureCubeMapZero.get();
}
}
return mState.samplerTexture[type][sampler].get();
}
bool Context::getBooleanv(GLenum pname, GLboolean *params)
{
switch (pname)
{
case GL_SHADER_COMPILER: *params = GL_TRUE; break;
case GL_SAMPLE_COVERAGE_INVERT: *params = mState.sampleCoverageInvert; break;
case GL_DEPTH_WRITEMASK: *params = mState.depthStencil.depthMask; break;
case GL_COLOR_WRITEMASK:
params[0] = mState.blend.colorMaskRed;
params[1] = mState.blend.colorMaskGreen;
params[2] = mState.blend.colorMaskBlue;
params[3] = mState.blend.colorMaskAlpha;
break;
case GL_CULL_FACE: *params = mState.rasterizer.cullFace; break;
case GL_POLYGON_OFFSET_FILL: *params = mState.rasterizer.polygonOffsetFill; break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.blend.sampleAlphaToCoverage; break;
case GL_SAMPLE_COVERAGE: *params = mState.sampleCoverage; break;
case GL_SCISSOR_TEST: *params = mState.scissorTest; break;
case GL_STENCIL_TEST: *params = mState.depthStencil.stencilTest; break;
case GL_DEPTH_TEST: *params = mState.depthStencil.depthTest; break;
case GL_BLEND: *params = mState.blend.blend; break;
case GL_DITHER: *params = mState.blend.dither; break;
case GL_CONTEXT_ROBUST_ACCESS_EXT: *params = mRobustAccess ? GL_TRUE : GL_FALSE; break;
default:
return false;
}
return true;
}
bool Context::getFloatv(GLenum pname, GLfloat *params)
{
// Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
// GetIntegerv as its native query function. As it would require conversion in any
// case, this should make no difference to the calling application.
switch (pname)
{
case GL_LINE_WIDTH: *params = mState.lineWidth; break;
case GL_SAMPLE_COVERAGE_VALUE: *params = mState.sampleCoverageValue; break;
case GL_DEPTH_CLEAR_VALUE: *params = mState.depthClearValue; break;
case GL_POLYGON_OFFSET_FACTOR: *params = mState.rasterizer.polygonOffsetFactor; break;
case GL_POLYGON_OFFSET_UNITS: *params = mState.rasterizer.polygonOffsetUnits; break;
case GL_ALIASED_LINE_WIDTH_RANGE:
params[0] = gl::ALIASED_LINE_WIDTH_RANGE_MIN;
params[1] = gl::ALIASED_LINE_WIDTH_RANGE_MAX;
break;
case GL_ALIASED_POINT_SIZE_RANGE:
params[0] = gl::ALIASED_POINT_SIZE_RANGE_MIN;
params[1] = getMaximumPointSize();
break;
case GL_DEPTH_RANGE:
params[0] = mState.zNear;
params[1] = mState.zFar;
break;
case GL_COLOR_CLEAR_VALUE:
params[0] = mState.colorClearValue.red;
params[1] = mState.colorClearValue.green;
params[2] = mState.colorClearValue.blue;
params[3] = mState.colorClearValue.alpha;
break;
case GL_BLEND_COLOR:
params[0] = mState.blendColor.red;
params[1] = mState.blendColor.green;
params[2] = mState.blendColor.blue;
params[3] = mState.blendColor.alpha;
break;
case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
if (!supportsTextureFilterAnisotropy())
{
return false;
}
*params = mMaxTextureAnisotropy;
break;
default:
return false;
}
return true;
}
bool Context::getIntegerv(GLenum pname, GLint *params)
{
if (pname >= GL_DRAW_BUFFER0_EXT && pname <= GL_DRAW_BUFFER15_EXT)
{
unsigned int colorAttachment = (pname - GL_DRAW_BUFFER0_EXT);
if (colorAttachment >= mRenderer->getMaxRenderTargets())
{
// return true to stop further operation in the parent call
return gl::error(GL_INVALID_OPERATION, true);
}
Framebuffer *framebuffer = getDrawFramebuffer();
*params = framebuffer->getDrawBufferState(colorAttachment);
return true;
}
// Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
// GetIntegerv as its native query function. As it would require conversion in any
// case, this should make no difference to the calling application. You may find it in
// Context::getFloatv.
switch (pname)
{
case GL_MAX_VERTEX_ATTRIBS: *params = gl::MAX_VERTEX_ATTRIBS; break;
case GL_MAX_VERTEX_UNIFORM_VECTORS: *params = mRenderer->getMaxVertexUniformVectors(); break;
case GL_MAX_VARYING_VECTORS: *params = mRenderer->getMaxVaryingVectors(); break;
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = mRenderer->getMaxCombinedTextureImageUnits(); break;
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: *params = mRenderer->getMaxVertexTextureImageUnits(); break;
case GL_MAX_TEXTURE_IMAGE_UNITS: *params = gl::MAX_TEXTURE_IMAGE_UNITS; break;
case GL_MAX_FRAGMENT_UNIFORM_VECTORS: *params = mRenderer->getMaxFragmentUniformVectors(); break;
case GL_MAX_RENDERBUFFER_SIZE: *params = getMaximumRenderbufferDimension(); break;
case GL_MAX_COLOR_ATTACHMENTS_EXT: *params = mRenderer->getMaxRenderTargets(); break;
case GL_MAX_DRAW_BUFFERS_EXT: *params = mRenderer->getMaxRenderTargets(); break;
case GL_NUM_SHADER_BINARY_FORMATS: *params = 0; break;
case GL_SHADER_BINARY_FORMATS: /* no shader binary formats are supported */ break;
case GL_ARRAY_BUFFER_BINDING: *params = mState.arrayBuffer.id(); break;
case GL_ELEMENT_ARRAY_BUFFER_BINDING: *params = mState.elementArrayBuffer.id(); break;
//case GL_FRAMEBUFFER_BINDING: // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE: *params = mState.drawFramebuffer; break;
case GL_READ_FRAMEBUFFER_BINDING_ANGLE: *params = mState.readFramebuffer; break;
case GL_RENDERBUFFER_BINDING: *params = mState.renderbuffer.id(); break;
case GL_CURRENT_PROGRAM: *params = mState.currentProgram; break;
case GL_PACK_ALIGNMENT: *params = mState.packAlignment; break;
case GL_PACK_REVERSE_ROW_ORDER_ANGLE: *params = mState.packReverseRowOrder; break;
case GL_UNPACK_ALIGNMENT: *params = mState.unpackAlignment; break;
case GL_GENERATE_MIPMAP_HINT: *params = mState.generateMipmapHint; break;
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
case GL_ACTIVE_TEXTURE: *params = (mState.activeSampler + GL_TEXTURE0); break;
case GL_STENCIL_FUNC: *params = mState.depthStencil.stencilFunc; break;
case GL_STENCIL_REF: *params = mState.stencilRef; break;
case GL_STENCIL_VALUE_MASK: *params = mState.depthStencil.stencilMask; break;
case GL_STENCIL_BACK_FUNC: *params = mState.depthStencil.stencilBackFunc; break;
case GL_STENCIL_BACK_REF: *params = mState.stencilBackRef; break;
case GL_STENCIL_BACK_VALUE_MASK: *params = mState.depthStencil.stencilBackMask; break;
case GL_STENCIL_FAIL: *params = mState.depthStencil.stencilFail; break;
case GL_STENCIL_PASS_DEPTH_FAIL: *params = mState.depthStencil.stencilPassDepthFail; break;
case GL_STENCIL_PASS_DEPTH_PASS: *params = mState.depthStencil.stencilPassDepthPass; break;
case GL_STENCIL_BACK_FAIL: *params = mState.depthStencil.stencilBackFail; break;
case GL_STENCIL_BACK_PASS_DEPTH_FAIL: *params = mState.depthStencil.stencilBackPassDepthFail; break;
case GL_STENCIL_BACK_PASS_DEPTH_PASS: *params = mState.depthStencil.stencilBackPassDepthPass; break;
case GL_DEPTH_FUNC: *params = mState.depthStencil.depthFunc; break;
case GL_BLEND_SRC_RGB: *params = mState.blend.sourceBlendRGB; break;
case GL_BLEND_SRC_ALPHA: *params = mState.blend.sourceBlendAlpha; break;
case GL_BLEND_DST_RGB: *params = mState.blend.destBlendRGB; break;
case GL_BLEND_DST_ALPHA: *params = mState.blend.destBlendAlpha; break;
case GL_BLEND_EQUATION_RGB: *params = mState.blend.blendEquationRGB; break;
case GL_BLEND_EQUATION_ALPHA: *params = mState.blend.blendEquationAlpha; break;
case GL_STENCIL_WRITEMASK: *params = mState.depthStencil.stencilWritemask; break;
case GL_STENCIL_BACK_WRITEMASK: *params = mState.depthStencil.stencilBackWritemask; break;
case GL_STENCIL_CLEAR_VALUE: *params = mState.stencilClearValue; break;
case GL_SUBPIXEL_BITS: *params = 4; break;
case GL_MAX_TEXTURE_SIZE: *params = getMaximumTextureDimension(); break;
case GL_MAX_CUBE_MAP_TEXTURE_SIZE: *params = getMaximumCubeTextureDimension(); break;
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
params[0] = mNumCompressedTextureFormats;
break;
case GL_MAX_SAMPLES_ANGLE:
{
GLsizei maxSamples = getMaxSupportedSamples();
if (maxSamples != 0)
{
*params = maxSamples;
}
else
{
return false;
}
break;
}
case GL_SAMPLE_BUFFERS:
case GL_SAMPLES:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
if (framebuffer->completeness() == GL_FRAMEBUFFER_COMPLETE)
{
switch (pname)
{
case GL_SAMPLE_BUFFERS:
if (framebuffer->getSamples() != 0)
{
*params = 1;
}
else
{
*params = 0;
}
break;
case GL_SAMPLES:
*params = framebuffer->getSamples();
break;
}
}
else
{
*params = 0;
}
}
break;
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
{
GLenum format, type;
if (getCurrentReadFormatType(&format, &type))
{
if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT)
*params = format;
else
*params = type;
}
}
break;
case GL_MAX_VIEWPORT_DIMS:
{
params[0] = mMaxViewportDimension;
params[1] = mMaxViewportDimension;
}
break;
case GL_COMPRESSED_TEXTURE_FORMATS:
{
if (supportsDXT1Textures())
{
*params++ = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
}
if (supportsDXT3Textures())
{
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
}
if (supportsDXT5Textures())
{
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
}
}
break;
case GL_VIEWPORT:
params[0] = mState.viewport.x;
params[1] = mState.viewport.y;
params[2] = mState.viewport.width;
params[3] = mState.viewport.height;
break;
case GL_SCISSOR_BOX:
params[0] = mState.scissor.x;
params[1] = mState.scissor.y;
params[2] = mState.scissor.width;
params[3] = mState.scissor.height;
break;
case GL_CULL_FACE_MODE: *params = mState.rasterizer.cullMode; break;
case GL_FRONT_FACE: *params = mState.rasterizer.frontFace; break;
case GL_RED_BITS:
case GL_GREEN_BITS:
case GL_BLUE_BITS:
case GL_ALPHA_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *colorbuffer = framebuffer->getFirstColorbuffer();
if (colorbuffer)
{
switch (pname)
{
case GL_RED_BITS: *params = colorbuffer->getRedSize(); break;
case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
case GL_BLUE_BITS: *params = colorbuffer->getBlueSize(); break;
case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
}
}
else
{
*params = 0;
}
}
break;
case GL_DEPTH_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
if (depthbuffer)
{
*params = depthbuffer->getDepthSize();
}
else
{
*params = 0;
}
}
break;
case GL_STENCIL_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
if (stencilbuffer)
{
*params = stencilbuffer->getStencilSize();
}
else
{
*params = 0;
}
}
break;
case GL_TEXTURE_BINDING_2D:
{
if (mState.activeSampler > mRenderer->getMaxCombinedTextureImageUnits() - 1)
{
gl::error(GL_INVALID_OPERATION);
return false;
}
*params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].id();
}
break;
case GL_TEXTURE_BINDING_CUBE_MAP:
{
if (mState.activeSampler > mRenderer->getMaxCombinedTextureImageUnits() - 1)
{
gl::error(GL_INVALID_OPERATION);
return false;
}
*params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].id();
}
break;
case GL_RESET_NOTIFICATION_STRATEGY_EXT:
*params = mResetStrategy;
break;
case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
*params = 1;
break;
case GL_PROGRAM_BINARY_FORMATS_OES:
*params = GL_PROGRAM_BINARY_ANGLE;
break;
default:
return false;
}
return true;
}
bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
{
if (pname >= GL_DRAW_BUFFER0_EXT && pname <= GL_DRAW_BUFFER15_EXT)
{
*type = GL_INT;
*numParams = 1;
return true;
}
// Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
// is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
// to the fact that it is stored internally as a float, and so would require conversion
// if returned from Context::getIntegerv. Since this conversion is already implemented
// in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
// place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
// application.
switch (pname)
{
case GL_COMPRESSED_TEXTURE_FORMATS:
{
*type = GL_INT;
*numParams = mNumCompressedTextureFormats;
}
break;
case GL_SHADER_BINARY_FORMATS:
{
*type = GL_INT;
*numParams = 0;
}
break;
case GL_MAX_VERTEX_ATTRIBS:
case GL_MAX_VERTEX_UNIFORM_VECTORS:
case GL_MAX_VARYING_VECTORS:
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
case GL_MAX_TEXTURE_IMAGE_UNITS:
case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
case GL_MAX_RENDERBUFFER_SIZE:
case GL_MAX_COLOR_ATTACHMENTS_EXT:
case GL_MAX_DRAW_BUFFERS_EXT:
case GL_NUM_SHADER_BINARY_FORMATS:
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
case GL_ARRAY_BUFFER_BINDING:
case GL_FRAMEBUFFER_BINDING:
case GL_RENDERBUFFER_BINDING:
case GL_CURRENT_PROGRAM:
case GL_PACK_ALIGNMENT:
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
case GL_UNPACK_ALIGNMENT:
case GL_GENERATE_MIPMAP_HINT:
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
case GL_RED_BITS:
case GL_GREEN_BITS:
case GL_BLUE_BITS:
case GL_ALPHA_BITS:
case GL_DEPTH_BITS:
case GL_STENCIL_BITS:
case GL_ELEMENT_ARRAY_BUFFER_BINDING:
case GL_CULL_FACE_MODE:
case GL_FRONT_FACE:
case GL_ACTIVE_TEXTURE:
case GL_STENCIL_FUNC:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_REF:
case GL_STENCIL_FAIL:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_VALUE_MASK:
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS:
case GL_DEPTH_FUNC:
case GL_BLEND_SRC_RGB:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_DST_ALPHA:
case GL_BLEND_EQUATION_RGB:
case GL_BLEND_EQUATION_ALPHA:
case GL_STENCIL_WRITEMASK:
case GL_STENCIL_BACK_WRITEMASK:
case GL_STENCIL_CLEAR_VALUE:
case GL_SUBPIXEL_BITS:
case GL_MAX_TEXTURE_SIZE:
case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
case GL_SAMPLE_BUFFERS:
case GL_SAMPLES:
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
case GL_TEXTURE_BINDING_2D:
case GL_TEXTURE_BINDING_CUBE_MAP:
case GL_RESET_NOTIFICATION_STRATEGY_EXT:
case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
case GL_PROGRAM_BINARY_FORMATS_OES:
{
*type = GL_INT;
*numParams = 1;
}
break;
case GL_MAX_SAMPLES_ANGLE:
{
if (getMaxSupportedSamples() != 0)
{
*type = GL_INT;
*numParams = 1;
}
else
{
return false;
}
}
break;
case GL_MAX_VIEWPORT_DIMS:
{
*type = GL_INT;
*numParams = 2;
}
break;
case GL_VIEWPORT:
case GL_SCISSOR_BOX:
{
*type = GL_INT;
*numParams = 4;
}
break;
case GL_SHADER_COMPILER:
case GL_SAMPLE_COVERAGE_INVERT:
case GL_DEPTH_WRITEMASK:
case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
case GL_SAMPLE_COVERAGE:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST:
case GL_DEPTH_TEST:
case GL_BLEND:
case GL_DITHER:
case GL_CONTEXT_ROBUST_ACCESS_EXT:
{
*type = GL_BOOL;
*numParams = 1;
}
break;
case GL_COLOR_WRITEMASK:
{
*type = GL_BOOL;
*numParams = 4;
}
break;
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS:
case GL_SAMPLE_COVERAGE_VALUE:
case GL_DEPTH_CLEAR_VALUE:
case GL_LINE_WIDTH:
{
*type = GL_FLOAT;
*numParams = 1;
}
break;
case GL_ALIASED_LINE_WIDTH_RANGE:
case GL_ALIASED_POINT_SIZE_RANGE:
case GL_DEPTH_RANGE:
{
*type = GL_FLOAT;
*numParams = 2;
}
break;
case GL_COLOR_CLEAR_VALUE:
case GL_BLEND_COLOR:
{
*type = GL_FLOAT;
*numParams = 4;
}
break;
case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
if (!supportsTextureFilterAnisotropy())
{
return false;
}
*type = GL_FLOAT;
*numParams = 1;
break;
default:
return false;
}
return true;
}
// Applies the render target surface, depth stencil surface, viewport rectangle and
// scissor rectangle to the renderer
bool Context::applyRenderTarget(GLenum drawMode, bool ignoreViewport)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
}
mRenderer->applyRenderTarget(framebufferObject);
if (!mRenderer->setViewport(mState.viewport, mState.zNear, mState.zFar, drawMode, mState.rasterizer.frontFace,
ignoreViewport))
{
return false;
}
mRenderer->setScissorRectangle(mState.scissor, mState.scissorTest);
return true;
}
// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc) to the Direct3D 9 device
void Context::applyState(GLenum drawMode)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
int samples = framebufferObject->getSamples();
mState.rasterizer.pointDrawMode = (drawMode == GL_POINTS);
mState.rasterizer.multiSample = (samples != 0);
mRenderer->setRasterizerState(mState.rasterizer);
unsigned int mask = 0;
if (mState.sampleCoverage)
{
if (mState.sampleCoverageValue != 0)
{
float threshold = 0.5f;
for (int i = 0; i < samples; ++i)
{
mask <<= 1;
if ((i + 1) * mState.sampleCoverageValue >= threshold)
{
threshold += 1.0f;
mask |= 1;
}
}
}
if (mState.sampleCoverageInvert)
{
mask = ~mask;
}
}
else
{
mask = 0xFFFFFFFF;
}
mRenderer->setBlendState(mState.blend, mState.blendColor, mask);
mRenderer->setDepthStencilState(mState.depthStencil, mState.stencilRef, mState.stencilBackRef,
mState.rasterizer.frontFace == GL_CCW);
}
// Applies the shaders and shader constants to the Direct3D 9 device
void Context::applyShaders()
{
ProgramBinary *programBinary = getCurrentProgramBinary();
mRenderer->applyShaders(programBinary);
programBinary->applyUniforms();
}
// Applies the textures and sampler states to the Direct3D 9 device
void Context::applyTextures()
{
applyTextures(SAMPLER_PIXEL);
if (mSupportsVertexTexture)
{
applyTextures(SAMPLER_VERTEX);
}
}
// For each Direct3D 9 sampler of either the pixel or vertex stage,
// looks up the corresponding OpenGL texture image unit and texture type,
// and sets the texture and its addressing/filtering state (or NULL when inactive).
void Context::applyTextures(SamplerType type)
{
ProgramBinary *programBinary = getCurrentProgramBinary();
// Range of Direct3D samplers of given sampler type
int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : mRenderer->getMaxVertexTextureImageUnits();
int samplerRange = programBinary->getUsedSamplerRange(type);
for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
{
int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
if (textureUnit != -1)
{
TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
Texture *texture = getSamplerTexture(textureUnit, textureType);
if (texture->isSamplerComplete())
{
SamplerState samplerState;
texture->getSamplerState(&samplerState);
mRenderer->setSamplerState(type, samplerIndex, samplerState);
mRenderer->setTexture(type, samplerIndex, texture);
texture->resetDirty();
}
else
{
mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
}
}
else
{
mRenderer->setTexture(type, samplerIndex, NULL);
}
}
for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
{
mRenderer->setTexture(type, samplerIndex, NULL);
}
}
void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
{
Framebuffer *framebuffer = getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), getPackAlignment());
// sized query sanity check
if (bufSize)
{
int requiredSize = outputPitch * height;
if (requiredSize > *bufSize)
{
return gl::error(GL_INVALID_OPERATION);
}
}
mRenderer->readPixels(framebuffer, x, y, width, height, format, type, outputPitch, getPackReverseRowOrder(), getPackAlignment(), pixels);
}
void Context::clear(GLbitfield mask)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
DWORD flags = 0;
GLbitfield finalMask = 0;
if (mask & GL_COLOR_BUFFER_BIT)
{
mask &= ~GL_COLOR_BUFFER_BIT;
if (framebufferObject->hasEnabledColorAttachment())
{
finalMask |= GL_COLOR_BUFFER_BIT;
}
}
if (mask & GL_DEPTH_BUFFER_BIT)
{
mask &= ~GL_DEPTH_BUFFER_BIT;
if (mState.depthStencil.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
{
finalMask |= GL_DEPTH_BUFFER_BIT;
}
}
if (mask & GL_STENCIL_BUFFER_BIT)
{
mask &= ~GL_STENCIL_BUFFER_BIT;
if (framebufferObject->getStencilbufferType() != GL_NONE)
{
rx::RenderTarget *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
return;
}
if (GetStencilSize(depthStencil->getActualFormat()) > 0)
{
finalMask |= GL_STENCIL_BUFFER_BIT;
}
}
}
if (mask != 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (!applyRenderTarget(GL_TRIANGLES, true)) // Clips the clear to the scissor rectangle but not the viewport
{
return;
}
ClearParameters clearParams;
clearParams.mask = finalMask;
clearParams.colorClearValue = mState.colorClearValue;
clearParams.colorMaskRed = mState.blend.colorMaskRed;
clearParams.colorMaskGreen = mState.blend.colorMaskGreen;
clearParams.colorMaskBlue = mState.blend.colorMaskBlue;
clearParams.colorMaskAlpha = mState.blend.colorMaskAlpha;
clearParams.depthClearValue = mState.depthClearValue;
clearParams.stencilClearValue = mState.stencilClearValue;
clearParams.stencilWriteMask = mState.depthStencil.stencilWritemask;
mRenderer->clear(clearParams, framebufferObject);
}
void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
{
if (!mState.currentProgram)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!mRenderer->applyPrimitiveType(mode, count))
{
return;
}
if (!applyRenderTarget(mode, false))
{
return;
}
applyState(mode);
ProgramBinary *programBinary = getCurrentProgramBinary();
GLenum err = mRenderer->applyVertexBuffer(programBinary, mState.vertexAttribute, first, count, instances);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
applyShaders();
applyTextures();
if (!programBinary->validateSamplers(NULL))
{
return gl::error(GL_INVALID_OPERATION);
}
if (!skipDraw(mode))
{
mRenderer->drawArrays(mode, count, instances);
}
}
void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
{
if (!mState.currentProgram)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!indices && !mState.elementArrayBuffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!mRenderer->applyPrimitiveType(mode, count))
{
return;
}
if (!applyRenderTarget(mode, false))
{
return;
}
applyState(mode);
rx::TranslatedIndexData indexInfo;
GLenum err = mRenderer->applyIndexBuffer(indices, mState.elementArrayBuffer.get(), count, mode, type, &indexInfo);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
ProgramBinary *programBinary = getCurrentProgramBinary();
GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
err = mRenderer->applyVertexBuffer(programBinary, mState.vertexAttribute, indexInfo.minIndex, vertexCount, instances);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
applyShaders();
applyTextures();
if (!programBinary->validateSamplers(NULL))
{
return gl::error(GL_INVALID_OPERATION);
}
if (!skipDraw(mode))
{
mRenderer->drawElements(mode, count, type, indices, mState.elementArrayBuffer.get(), indexInfo, instances);
}
}
// Implements glFlush when block is false, glFinish when block is true
void Context::sync(bool block)
{
mRenderer->sync(block);
}
void Context::recordInvalidEnum()
{
mInvalidEnum = true;
}
void Context::recordInvalidValue()
{
mInvalidValue = true;
}
void Context::recordInvalidOperation()
{
mInvalidOperation = true;
}
void Context::recordOutOfMemory()
{
mOutOfMemory = true;
}
void Context::recordInvalidFramebufferOperation()
{
mInvalidFramebufferOperation = true;
}
// Get one of the recorded errors and clear its flag, if any.
// [OpenGL ES 2.0.24] section 2.5 page 13.
GLenum Context::getError()
{
if (mInvalidEnum)
{
mInvalidEnum = false;
return GL_INVALID_ENUM;
}
if (mInvalidValue)
{
mInvalidValue = false;
return GL_INVALID_VALUE;
}
if (mInvalidOperation)
{
mInvalidOperation = false;
return GL_INVALID_OPERATION;
}
if (mOutOfMemory)
{
mOutOfMemory = false;
return GL_OUT_OF_MEMORY;
}
if (mInvalidFramebufferOperation)
{
mInvalidFramebufferOperation = false;
return GL_INVALID_FRAMEBUFFER_OPERATION;
}
return GL_NO_ERROR;
}
GLenum Context::getResetStatus()
{
if (mResetStatus == GL_NO_ERROR && !mContextLost)
{
// mResetStatus will be set by the markContextLost callback
// in the case a notification is sent
mRenderer->testDeviceLost(true);
}
GLenum status = mResetStatus;
if (mResetStatus != GL_NO_ERROR)
{
ASSERT(mContextLost);
if (mRenderer->testDeviceResettable())
{
mResetStatus = GL_NO_ERROR;
}
}
return status;
}
bool Context::isResetNotificationEnabled()
{
return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
}
int Context::getMajorShaderModel() const
{
return mMajorShaderModel;
}
float Context::getMaximumPointSize() const
{
return mMaximumPointSize;
}
unsigned int Context::getMaximumCombinedTextureImageUnits() const
{
return mRenderer->getMaxCombinedTextureImageUnits();
}
int Context::getMaxSupportedSamples() const
{
return mRenderer->getMaxSupportedSamples();
}
unsigned int Context::getMaximumRenderTargets() const
{
return mRenderer->getMaxRenderTargets();
}
bool Context::supportsEventQueries() const
{
return mSupportsEventQueries;
}
bool Context::supportsOcclusionQueries() const
{
return mSupportsOcclusionQueries;
}
bool Context::supportsBGRATextures() const
{
return mSupportsBGRATextures;
}
bool Context::supportsDXT1Textures() const
{
return mSupportsDXT1Textures;
}
bool Context::supportsDXT3Textures() const
{
return mSupportsDXT3Textures;
}
bool Context::supportsDXT5Textures() const
{
return mSupportsDXT5Textures;
}
bool Context::supportsFloat32Textures() const
{
return mSupportsFloat32Textures;
}
bool Context::supportsFloat32LinearFilter() const
{
return mSupportsFloat32LinearFilter;
}
bool Context::supportsFloat32RenderableTextures() const
{
return mSupportsFloat32RenderableTextures;
}
bool Context::supportsFloat16Textures() const
{
return mSupportsFloat16Textures;
}
bool Context::supportsFloat16LinearFilter() const
{
return mSupportsFloat16LinearFilter;
}
bool Context::supportsFloat16RenderableTextures() const
{
return mSupportsFloat16RenderableTextures;
}
int Context::getMaximumRenderbufferDimension() const
{
return mMaxRenderbufferDimension;
}
int Context::getMaximumTextureDimension() const
{
return mMaxTextureDimension;
}
int Context::getMaximumCubeTextureDimension() const
{
return mMaxCubeTextureDimension;
}
int Context::getMaximumTextureLevel() const
{
return mMaxTextureLevel;
}
bool Context::supportsLuminanceTextures() const
{
return mSupportsLuminanceTextures;
}
bool Context::supportsLuminanceAlphaTextures() const
{
return mSupportsLuminanceAlphaTextures;
}
bool Context::supportsDepthTextures() const
{
return mSupportsDepthTextures;
}
bool Context::supports32bitIndices() const
{
return mSupports32bitIndices;
}
bool Context::supportsNonPower2Texture() const
{
return mSupportsNonPower2Texture;
}
bool Context::supportsInstancing() const
{
return mSupportsInstancing;
}
bool Context::supportsTextureFilterAnisotropy() const
{
return mSupportsTextureFilterAnisotropy;
}
float Context::getTextureMaxAnisotropy() const
{
return mMaxTextureAnisotropy;
}
bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
{
Framebuffer *framebuffer = getReadFramebuffer();
if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_OPERATION, false);
}
Renderbuffer *renderbuffer = framebuffer->getReadColorbuffer();
if (!renderbuffer)
{
return gl::error(GL_INVALID_OPERATION, false);
}
*format = gl::ExtractFormat(renderbuffer->getActualFormat());
*type = gl::ExtractType(renderbuffer->getActualFormat());
return true;
}
void Context::detachBuffer(GLuint buffer)
{
// [OpenGL ES 2.0.24] section 2.9 page 22:
// If a buffer object is deleted while it is bound, all bindings to that object in the current context
// (i.e. in the thread that called Delete-Buffers) are reset to zero.
if (mState.arrayBuffer.id() == buffer)
{
mState.arrayBuffer.set(NULL);
}
if (mState.elementArrayBuffer.id() == buffer)
{
mState.elementArrayBuffer.set(NULL);
}
for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
{
if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
{
mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
}
}
}
void Context::detachTexture(GLuint texture)
{
// [OpenGL ES 2.0.24] section 3.8 page 84:
// If a texture object is deleted, it is as if all texture units which are bound to that texture object are
// rebound to texture object zero
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
for (int sampler = 0; sampler < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
{
if (mState.samplerTexture[type][sampler].id() == texture)
{
mState.samplerTexture[type][sampler].set(NULL);
}
}
}
// [OpenGL ES 2.0.24] section 4.4 page 112:
// If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
// as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
// image was attached in the currently bound framebuffer.
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (readFramebuffer)
{
readFramebuffer->detachTexture(texture);
}
if (drawFramebuffer && drawFramebuffer != readFramebuffer)
{
drawFramebuffer->detachTexture(texture);
}
}
void Context::detachFramebuffer(GLuint framebuffer)
{
// [OpenGL ES 2.0.24] section 4.4 page 107:
// If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
// BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
if (mState.readFramebuffer == framebuffer)
{
bindReadFramebuffer(0);
}
if (mState.drawFramebuffer == framebuffer)
{
bindDrawFramebuffer(0);
}
}
void Context::detachRenderbuffer(GLuint renderbuffer)
{
// [OpenGL ES 2.0.24] section 4.4 page 109:
// If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
// had been executed with the target RENDERBUFFER and name of zero.
if (mState.renderbuffer.id() == renderbuffer)
{
bindRenderbuffer(0);
}
// [OpenGL ES 2.0.24] section 4.4 page 111:
// If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
// then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
// point to which this image was attached in the currently bound framebuffer.
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (readFramebuffer)
{
readFramebuffer->detachRenderbuffer(renderbuffer);
}
if (drawFramebuffer && drawFramebuffer != readFramebuffer)
{
drawFramebuffer->detachRenderbuffer(renderbuffer);
}
}
Texture *Context::getIncompleteTexture(TextureType type)
{
Texture *t = mIncompleteTextures[type].get();
if (t == NULL)
{
static const GLubyte color[] = { 0, 0, 0, 255 };
switch (type)
{
default:
UNREACHABLE();
// default falls through to TEXTURE_2D
case TEXTURE_2D:
{
Texture2D *incomplete2d = new Texture2D(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
t = incomplete2d;
}
break;
case TEXTURE_CUBE:
{
TextureCubeMap *incompleteCube = new TextureCubeMap(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
t = incompleteCube;
}
break;
}
mIncompleteTextures[type].set(t);
}
return t;
}
bool Context::skipDraw(GLenum drawMode)
{
if (drawMode == GL_POINTS)
{
// ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
// which affects varying interpolation. Since the value of gl_PointSize is
// undefined when not written, just skip drawing to avoid unexpected results.
if (!getCurrentProgramBinary()->usesPointSize())
{
// This is stictly speaking not an error, but developers should be
// notified of risking undefined behavior.
ERR("Point rendering without writing to gl_PointSize.");
return true;
}
}
else if (IsTriangleMode(drawMode))
{
if (mState.rasterizer.cullFace && mState.rasterizer.cullMode == GL_FRONT_AND_BACK)
{
return true;
}
}
return false;
}
void Context::setVertexAttrib(GLuint index, const GLfloat *values)
{
ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
mState.vertexAttribute[index].mCurrentValue[0] = values[0];
mState.vertexAttribute[index].mCurrentValue[1] = values[1];
mState.vertexAttribute[index].mCurrentValue[2] = values[2];
mState.vertexAttribute[index].mCurrentValue[3] = values[3];
}
void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
{
ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
mState.vertexAttribute[index].mDivisor = divisor;
}
// keep list sorted in following order
// OES extensions
// EXT extensions
// Vendor extensions
void Context::initExtensionString()
{
std::string extensionString = "";
// OES extensions
if (supports32bitIndices())
{
extensionString += "GL_OES_element_index_uint ";
}
extensionString += "GL_OES_packed_depth_stencil ";
extensionString += "GL_OES_get_program_binary ";
extensionString += "GL_OES_rgb8_rgba8 ";
if (mRenderer->getDerivativeInstructionSupport())
{
extensionString += "GL_OES_standard_derivatives ";
}
if (supportsFloat16Textures())
{
extensionString += "GL_OES_texture_half_float ";
}
if (supportsFloat16LinearFilter())
{
extensionString += "GL_OES_texture_half_float_linear ";
}
if (supportsFloat32Textures())
{
extensionString += "GL_OES_texture_float ";
}
if (supportsFloat32LinearFilter())
{
extensionString += "GL_OES_texture_float_linear ";
}
if (supportsNonPower2Texture())
{
extensionString += "GL_OES_texture_npot ";
}
// Multi-vendor (EXT) extensions
if (supportsOcclusionQueries())
{
extensionString += "GL_EXT_occlusion_query_boolean ";
}
extensionString += "GL_EXT_read_format_bgra ";
extensionString += "GL_EXT_robustness ";
if (supportsDXT1Textures())
{
extensionString += "GL_EXT_texture_compression_dxt1 ";
}
if (supportsTextureFilterAnisotropy())
{
extensionString += "GL_EXT_texture_filter_anisotropic ";
}
if (supportsBGRATextures())
{
extensionString += "GL_EXT_texture_format_BGRA8888 ";
}
if (mRenderer->getMaxRenderTargets() > 1)
{
extensionString += "GL_EXT_draw_buffers ";
}
extensionString += "GL_EXT_texture_storage ";
extensionString += "GL_EXT_frag_depth ";
// ANGLE-specific extensions
if (supportsDepthTextures())
{
extensionString += "GL_ANGLE_depth_texture ";
}
extensionString += "GL_ANGLE_framebuffer_blit ";
if (getMaxSupportedSamples() != 0)
{
extensionString += "GL_ANGLE_framebuffer_multisample ";
}
if (supportsInstancing())
{
extensionString += "GL_ANGLE_instanced_arrays ";
}
extensionString += "GL_ANGLE_pack_reverse_row_order ";
if (supportsDXT3Textures())
{
extensionString += "GL_ANGLE_texture_compression_dxt3 ";
}
if (supportsDXT5Textures())
{
extensionString += "GL_ANGLE_texture_compression_dxt5 ";
}
extensionString += "GL_ANGLE_texture_usage ";
extensionString += "GL_ANGLE_translated_shader_source ";
// Other vendor-specific extensions
if (supportsEventQueries())
{
extensionString += "GL_NV_fence ";
}
std::string::size_type end = extensionString.find_last_not_of(' ');
if (end != std::string::npos)
{
extensionString.resize(end+1);
}
mExtensionString = makeStaticString(extensionString);
}
const char *Context::getExtensionString() const
{
return mExtensionString;
}
void Context::initRendererString()
{
std::ostringstream rendererString;
rendererString << "ANGLE (";
rendererString << mRenderer->getRendererDescription();
rendererString << ")";
mRendererString = makeStaticString(rendererString.str());
}
const char *Context::getRendererString() const
{
return mRendererString;
}
void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask)
{
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
!drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (drawFramebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
Renderbuffer *readColorBuffer = readFramebuffer->getReadColorbuffer();
Renderbuffer *drawColorBuffer = drawFramebuffer->getFirstColorbuffer();
if (drawColorBuffer == NULL)
{
ERR("Draw buffers formats don't match, which is not supported in this implementation of BlitFramebufferANGLE");
return gl::error(GL_INVALID_OPERATION);
}
int readBufferWidth = readColorBuffer->getWidth();
int readBufferHeight = readColorBuffer->getHeight();
int drawBufferWidth = drawColorBuffer->getWidth();
int drawBufferHeight = drawColorBuffer->getHeight();
Rectangle sourceRect;
Rectangle destRect;
if (srcX0 < srcX1)
{
sourceRect.x = srcX0;
destRect.x = dstX0;
sourceRect.width = srcX1 - srcX0;
destRect.width = dstX1 - dstX0;
}
else
{
sourceRect.x = srcX1;
destRect.x = dstX1;
sourceRect.width = srcX0 - srcX1;
destRect.width = dstX0 - dstX1;
}
if (srcY0 < srcY1)
{
sourceRect.height = srcY1 - srcY0;
destRect.height = dstY1 - dstY0;
sourceRect.y = srcY0;
destRect.y = dstY0;
}
else
{
sourceRect.height = srcY0 - srcY1;
destRect.height = dstY0 - srcY1;
sourceRect.y = srcY1;
destRect.y = dstY1;
}
Rectangle sourceScissoredRect = sourceRect;
Rectangle destScissoredRect = destRect;
if (mState.scissorTest)
{
// Only write to parts of the destination framebuffer which pass the scissor test.
if (destRect.x < mState.scissor.x)
{
int xDiff = mState.scissor.x - destRect.x;
destScissoredRect.x = mState.scissor.x;
destScissoredRect.width -= xDiff;
sourceScissoredRect.x += xDiff;
sourceScissoredRect.width -= xDiff;
}
if (destRect.x + destRect.width > mState.scissor.x + mState.scissor.width)
{
int xDiff = (destRect.x + destRect.width) - (mState.scissor.x + mState.scissor.width);
destScissoredRect.width -= xDiff;
sourceScissoredRect.width -= xDiff;
}
if (destRect.y < mState.scissor.y)
{
int yDiff = mState.scissor.y - destRect.y;
destScissoredRect.y = mState.scissor.y;
destScissoredRect.height -= yDiff;
sourceScissoredRect.y += yDiff;
sourceScissoredRect.height -= yDiff;
}
if (destRect.y + destRect.height > mState.scissor.y + mState.scissor.height)
{
int yDiff = (destRect.y + destRect.height) - (mState.scissor.y + mState.scissor.height);
destScissoredRect.height -= yDiff;
sourceScissoredRect.height -= yDiff;
}
}
bool blitRenderTarget = false;
bool blitDepthStencil = false;
Rectangle sourceTrimmedRect = sourceScissoredRect;
Rectangle destTrimmedRect = destScissoredRect;
// The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
// the actual draw and read surfaces.
if (sourceTrimmedRect.x < 0)
{
int xDiff = 0 - sourceTrimmedRect.x;
sourceTrimmedRect.x = 0;
sourceTrimmedRect.width -= xDiff;
destTrimmedRect.x += xDiff;
destTrimmedRect.width -= xDiff;
}
if (sourceTrimmedRect.x + sourceTrimmedRect.width > readBufferWidth)
{
int xDiff = (sourceTrimmedRect.x + sourceTrimmedRect.width) - readBufferWidth;
sourceTrimmedRect.width -= xDiff;
destTrimmedRect.width -= xDiff;
}
if (sourceTrimmedRect.y < 0)
{
int yDiff = 0 - sourceTrimmedRect.y;
sourceTrimmedRect.y = 0;
sourceTrimmedRect.height -= yDiff;
destTrimmedRect.y += yDiff;
destTrimmedRect.height -= yDiff;
}
if (sourceTrimmedRect.y + sourceTrimmedRect.height > readBufferHeight)
{
int yDiff = (sourceTrimmedRect.y + sourceTrimmedRect.height) - readBufferHeight;
sourceTrimmedRect.height -= yDiff;
destTrimmedRect.height -= yDiff;
}
if (destTrimmedRect.x < 0)
{
int xDiff = 0 - destTrimmedRect.x;
destTrimmedRect.x = 0;
destTrimmedRect.width -= xDiff;
sourceTrimmedRect.x += xDiff;
sourceTrimmedRect.width -= xDiff;
}
if (destTrimmedRect.x + destTrimmedRect.width > drawBufferWidth)
{
int xDiff = (destTrimmedRect.x + destTrimmedRect.width) - drawBufferWidth;
destTrimmedRect.width -= xDiff;
sourceTrimmedRect.width -= xDiff;
}
if (destTrimmedRect.y < 0)
{
int yDiff = 0 - destTrimmedRect.y;
destTrimmedRect.y = 0;
destTrimmedRect.height -= yDiff;
sourceTrimmedRect.y += yDiff;
sourceTrimmedRect.height -= yDiff;
}
if (destTrimmedRect.y + destTrimmedRect.height > drawBufferHeight)
{
int yDiff = (destTrimmedRect.y + destTrimmedRect.height) - drawBufferHeight;
destTrimmedRect.height -= yDiff;
sourceTrimmedRect.height -= yDiff;
}
bool partialBufferCopy = false;
if (sourceTrimmedRect.height < readBufferHeight ||
sourceTrimmedRect.width < readBufferWidth ||
destTrimmedRect.height < drawBufferHeight ||
destTrimmedRect.width < drawBufferWidth ||
sourceTrimmedRect.y != 0 || destTrimmedRect.y != 0 || sourceTrimmedRect.x != 0 || destTrimmedRect.x != 0)
{
partialBufferCopy = true;
}
if (mask & GL_COLOR_BUFFER_BIT)
{
const GLenum readColorbufferType = readFramebuffer->getReadColorbufferType();
const bool validReadType = (readColorbufferType == GL_TEXTURE_2D) || (readColorbufferType == GL_RENDERBUFFER);
bool validDrawType = true;
bool validDrawFormat = true;
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (drawFramebuffer->isEnabledColorAttachment(colorAttachment))
{
if (drawFramebuffer->getColorbufferType(colorAttachment) != GL_TEXTURE_2D &&
drawFramebuffer->getColorbufferType(colorAttachment) != GL_RENDERBUFFER)
{
validDrawType = false;
}
if (drawFramebuffer->getColorbuffer(colorAttachment)->getActualFormat() != readColorBuffer->getActualFormat())
{
validDrawFormat = false;
}
}
}
if (!validReadType || !validDrawType || !validDrawFormat)
{
ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
return gl::error(GL_INVALID_OPERATION);
}
if (partialBufferCopy && readFramebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
blitRenderTarget = true;
}
if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
{
Renderbuffer *readDSBuffer = NULL;
Renderbuffer *drawDSBuffer = NULL;
// We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
// both a depth and stencil buffer, it will be the same buffer.
if (mask & GL_DEPTH_BUFFER_BIT)
{
if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
{
if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
readFramebuffer->getDepthbuffer()->getActualFormat() != drawFramebuffer->getDepthbuffer()->getActualFormat())
{
return gl::error(GL_INVALID_OPERATION);
}
blitDepthStencil = true;
readDSBuffer = readFramebuffer->getDepthbuffer();
drawDSBuffer = drawFramebuffer->getDepthbuffer();
}
}
if (mask & GL_STENCIL_BUFFER_BIT)
{
if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
{
if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
readFramebuffer->getStencilbuffer()->getActualFormat() != drawFramebuffer->getStencilbuffer()->getActualFormat())
{
return gl::error(GL_INVALID_OPERATION);
}
blitDepthStencil = true;
readDSBuffer = readFramebuffer->getStencilbuffer();
drawDSBuffer = drawFramebuffer->getStencilbuffer();
}
}
if (partialBufferCopy)
{
ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
return gl::error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
}
if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
(readDSBuffer && readDSBuffer->getSamples() != 0))
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (blitRenderTarget || blitDepthStencil)
{
mRenderer->blitRect(readFramebuffer, sourceTrimmedRect, drawFramebuffer, destTrimmedRect, blitRenderTarget, blitDepthStencil);
}
}
}
extern "C"
{
gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
{
return new gl::Context(shareContext, renderer, notifyResets, robustAccess);
}
void glDestroyContext(gl::Context *context)
{
delete context;
if (context == gl::getContext())
{
gl::makeCurrent(NULL, NULL, NULL);
}
}
void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
{
gl::makeCurrent(context, display, surface);
}
gl::Context *glGetCurrentContext()
{
return gl::getContext();
}
}
| C++ |
#include "precompiled.h"
//
// Copyright (c) 2002-2011 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.
//
// HandleAllocator.cpp: Implements the gl::HandleAllocator class, which is used
// to allocate GL handles.
#include "libGLESv2/HandleAllocator.h"
#include "libGLESv2/main.h"
namespace gl
{
HandleAllocator::HandleAllocator() : mBaseValue(1), mNextValue(1)
{
}
HandleAllocator::~HandleAllocator()
{
}
void HandleAllocator::setBaseHandle(GLuint value)
{
ASSERT(mBaseValue == mNextValue);
mBaseValue = value;
mNextValue = value;
}
GLuint HandleAllocator::allocate()
{
if (mFreeValues.size())
{
GLuint handle = mFreeValues.back();
mFreeValues.pop_back();
return handle;
}
return mNextValue++;
}
void HandleAllocator::release(GLuint handle)
{
if (handle == mNextValue - 1)
{
// Don't drop below base value
if(mNextValue > mBaseValue)
{
mNextValue--;
}
}
else
{
// Only free handles that we own - don't drop below the base value
if (handle >= mBaseValue)
{
mFreeValues.push_back(handle);
}
}
}
}
| C++ |
//
// 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.
//
// Context.h: Defines the gl::Context class, managing all GL state and performing
// rendering operations. It is the GLES2 specific implementation of EGLContext.
#ifndef LIBGLESV2_CONTEXT_H_
#define LIBGLESV2_CONTEXT_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#define EGLAPI
#include <EGL/egl.h>
#include <string>
#include <map>
#ifdef _MSC_VER
#include <hash_map>
#else
#include <unordered_map>
#endif
#include "common/angleutils.h"
#include "common/RefCountObject.h"
#include "libGLESv2/HandleAllocator.h"
#include "libGLESv2/angletypes.h"
#include "libGLESv2/Constants.h"
namespace rx
{
class Renderer;
}
namespace egl
{
class Display;
class Surface;
}
namespace gl
{
class Shader;
class Program;
class ProgramBinary;
class Texture;
class Texture2D;
class TextureCubeMap;
class Framebuffer;
class Renderbuffer;
class RenderbufferStorage;
class Colorbuffer;
class Depthbuffer;
class Stencilbuffer;
class DepthStencilbuffer;
class Fence;
class Query;
class ResourceManager;
class Buffer;
enum QueryType
{
QUERY_ANY_SAMPLES_PASSED,
QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE,
QUERY_TYPE_COUNT
};
// Helper structure describing a single vertex attribute
class VertexAttribute
{
public:
VertexAttribute() : mType(GL_FLOAT), mSize(0), mNormalized(false), mStride(0), mPointer(NULL), mArrayEnabled(false), mDivisor(0)
{
mCurrentValue[0] = 0.0f;
mCurrentValue[1] = 0.0f;
mCurrentValue[2] = 0.0f;
mCurrentValue[3] = 1.0f;
}
int typeSize() const
{
switch (mType)
{
case GL_BYTE: return mSize * sizeof(GLbyte);
case GL_UNSIGNED_BYTE: return mSize * sizeof(GLubyte);
case GL_SHORT: return mSize * sizeof(GLshort);
case GL_UNSIGNED_SHORT: return mSize * sizeof(GLushort);
case GL_FIXED: return mSize * sizeof(GLfixed);
case GL_FLOAT: return mSize * sizeof(GLfloat);
default: UNREACHABLE(); return mSize * sizeof(GLfloat);
}
}
GLsizei stride() const
{
return mStride ? mStride : typeSize();
}
// From glVertexAttribPointer
GLenum mType;
GLint mSize;
bool mNormalized;
GLsizei mStride; // 0 means natural stride
union
{
const void *mPointer;
intptr_t mOffset;
};
BindingPointer<Buffer> mBoundBuffer; // Captured when glVertexAttribPointer is called.
bool mArrayEnabled; // From glEnable/DisableVertexAttribArray
float mCurrentValue[4]; // From glVertexAttrib
unsigned int mDivisor;
};
// Helper structure to store all raw state
struct State
{
Color colorClearValue;
GLclampf depthClearValue;
int stencilClearValue;
RasterizerState rasterizer;
bool scissorTest;
Rectangle scissor;
BlendState blend;
Color blendColor;
bool sampleCoverage;
GLclampf sampleCoverageValue;
bool sampleCoverageInvert;
DepthStencilState depthStencil;
GLint stencilRef;
GLint stencilBackRef;
GLfloat lineWidth;
GLenum generateMipmapHint;
GLenum fragmentShaderDerivativeHint;
Rectangle viewport;
float zNear;
float zFar;
unsigned int activeSampler; // Active texture unit selector - GL_TEXTURE0
BindingPointer<Buffer> arrayBuffer;
BindingPointer<Buffer> elementArrayBuffer;
GLuint readFramebuffer;
GLuint drawFramebuffer;
BindingPointer<Renderbuffer> renderbuffer;
GLuint currentProgram;
VertexAttribute vertexAttribute[MAX_VERTEX_ATTRIBS];
BindingPointer<Texture> samplerTexture[TEXTURE_TYPE_COUNT][IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS];
BindingPointer<Query> activeQuery[QUERY_TYPE_COUNT];
GLint unpackAlignment;
GLint packAlignment;
bool packReverseRowOrder;
};
class Context
{
public:
Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess);
~Context();
void makeCurrent(egl::Surface *surface);
virtual void markContextLost();
bool isContextLost();
// State manipulation
void setClearColor(float red, float green, float blue, float alpha);
void setClearDepth(float depth);
void setClearStencil(int stencil);
void setCullFace(bool enabled);
bool isCullFaceEnabled() const;
void setCullMode(GLenum mode);
void setFrontFace(GLenum front);
void setDepthTest(bool enabled);
bool isDepthTestEnabled() const;
void setDepthFunc(GLenum depthFunc);
void setDepthRange(float zNear, float zFar);
void setBlend(bool enabled);
bool isBlendEnabled() const;
void setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha);
void setBlendColor(float red, float green, float blue, float alpha);
void setBlendEquation(GLenum rgbEquation, GLenum alphaEquation);
void setStencilTest(bool enabled);
bool isStencilTestEnabled() const;
void setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask);
void setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask);
void setStencilWritemask(GLuint stencilWritemask);
void setStencilBackWritemask(GLuint stencilBackWritemask);
void setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass);
void setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass);
void setPolygonOffsetFill(bool enabled);
bool isPolygonOffsetFillEnabled() const;
void setPolygonOffsetParams(GLfloat factor, GLfloat units);
void setSampleAlphaToCoverage(bool enabled);
bool isSampleAlphaToCoverageEnabled() const;
void setSampleCoverage(bool enabled);
bool isSampleCoverageEnabled() const;
void setSampleCoverageParams(GLclampf value, bool invert);
void setScissorTest(bool enabled);
bool isScissorTestEnabled() const;
void setDither(bool enabled);
bool isDitherEnabled() const;
void setLineWidth(GLfloat width);
void setGenerateMipmapHint(GLenum hint);
void setFragmentShaderDerivativeHint(GLenum hint);
void setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height);
void setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height);
void setColorMask(bool red, bool green, bool blue, bool alpha);
void setDepthMask(bool mask);
void setActiveSampler(unsigned int active);
GLuint getReadFramebufferHandle() const;
GLuint getDrawFramebufferHandle() const;
GLuint getRenderbufferHandle() const;
GLuint getArrayBufferHandle() const;
GLuint getActiveQuery(GLenum target) const;
void setEnableVertexAttribArray(unsigned int attribNum, bool enabled);
const VertexAttribute &getVertexAttribState(unsigned int attribNum);
void setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type,
bool normalized, GLsizei stride, const void *pointer);
const void *getVertexAttribPointer(unsigned int attribNum) const;
void setUnpackAlignment(GLint alignment);
GLint getUnpackAlignment() const;
void setPackAlignment(GLint alignment);
GLint getPackAlignment() const;
void setPackReverseRowOrder(bool reverseRowOrder);
bool getPackReverseRowOrder() const;
// These create and destroy methods are merely pass-throughs to
// ResourceManager, which owns these object types
GLuint createBuffer();
GLuint createShader(GLenum type);
GLuint createProgram();
GLuint createTexture();
GLuint createRenderbuffer();
void deleteBuffer(GLuint buffer);
void deleteShader(GLuint shader);
void deleteProgram(GLuint program);
void deleteTexture(GLuint texture);
void deleteRenderbuffer(GLuint renderbuffer);
// Framebuffers are owned by the Context, so these methods do not pass through
GLuint createFramebuffer();
void deleteFramebuffer(GLuint framebuffer);
// Fences are owned by the Context.
GLuint createFence();
void deleteFence(GLuint fence);
// Queries are owned by the Context;
GLuint createQuery();
void deleteQuery(GLuint query);
void bindArrayBuffer(GLuint buffer);
void bindElementArrayBuffer(GLuint buffer);
void bindTexture2D(GLuint texture);
void bindTextureCubeMap(GLuint texture);
void bindReadFramebuffer(GLuint framebuffer);
void bindDrawFramebuffer(GLuint framebuffer);
void bindRenderbuffer(GLuint renderbuffer);
void useProgram(GLuint program);
void linkProgram(GLuint program);
void setProgramBinary(GLuint program, const void *binary, GLint length);
void beginQuery(GLenum target, GLuint query);
void endQuery(GLenum target);
void setFramebufferZero(Framebuffer *framebuffer);
void setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples);
void setVertexAttrib(GLuint index, const GLfloat *values);
void setVertexAttribDivisor(GLuint index, GLuint divisor);
Buffer *getBuffer(GLuint handle);
Fence *getFence(GLuint handle);
Shader *getShader(GLuint handle);
Program *getProgram(GLuint handle);
Texture *getTexture(GLuint handle);
Framebuffer *getFramebuffer(GLuint handle);
Renderbuffer *getRenderbuffer(GLuint handle);
Query *getQuery(GLuint handle, bool create, GLenum type);
Buffer *getArrayBuffer();
Buffer *getElementArrayBuffer();
ProgramBinary *getCurrentProgramBinary();
Texture2D *getTexture2D();
TextureCubeMap *getTextureCubeMap();
Texture *getSamplerTexture(unsigned int sampler, TextureType type);
Framebuffer *getReadFramebuffer();
Framebuffer *getDrawFramebuffer();
bool getFloatv(GLenum pname, GLfloat *params);
bool getIntegerv(GLenum pname, GLint *params);
bool getBooleanv(GLenum pname, GLboolean *params);
bool getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams);
void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei *bufSize, void* pixels);
void clear(GLbitfield mask);
void drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances);
void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances);
void sync(bool block); // flush/finish
void recordInvalidEnum();
void recordInvalidValue();
void recordInvalidOperation();
void recordOutOfMemory();
void recordInvalidFramebufferOperation();
GLenum getError();
GLenum getResetStatus();
virtual bool isResetNotificationEnabled();
int getMajorShaderModel() const;
float getMaximumPointSize() const;
unsigned int getMaximumCombinedTextureImageUnits() const;
int getMaximumRenderbufferDimension() const;
int getMaximumTextureDimension() const;
int getMaximumCubeTextureDimension() const;
int getMaximumTextureLevel() const;
unsigned int getMaximumRenderTargets() const;
GLsizei getMaxSupportedSamples() const;
const char *getExtensionString() const;
const char *getRendererString() const;
bool supportsEventQueries() const;
bool supportsOcclusionQueries() const;
bool supportsBGRATextures() const;
bool supportsDXT1Textures() const;
bool supportsDXT3Textures() const;
bool supportsDXT5Textures() const;
bool supportsFloat32Textures() const;
bool supportsFloat32LinearFilter() const;
bool supportsFloat32RenderableTextures() const;
bool supportsFloat16Textures() const;
bool supportsFloat16LinearFilter() const;
bool supportsFloat16RenderableTextures() const;
bool supportsLuminanceTextures() const;
bool supportsLuminanceAlphaTextures() const;
bool supportsDepthTextures() const;
bool supports32bitIndices() const;
bool supportsNonPower2Texture() const;
bool supportsInstancing() const;
bool supportsTextureFilterAnisotropy() const;
bool getCurrentReadFormatType(GLenum *format, GLenum *type);
float getTextureMaxAnisotropy() const;
void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask);
private:
DISALLOW_COPY_AND_ASSIGN(Context);
bool applyRenderTarget(GLenum drawMode, bool ignoreViewport);
void applyState(GLenum drawMode);
void applyShaders();
void applyTextures();
void applyTextures(SamplerType type);
void detachBuffer(GLuint buffer);
void detachTexture(GLuint texture);
void detachFramebuffer(GLuint framebuffer);
void detachRenderbuffer(GLuint renderbuffer);
Texture *getIncompleteTexture(TextureType type);
bool skipDraw(GLenum drawMode);
void initExtensionString();
void initRendererString();
rx::Renderer *const mRenderer;
State mState;
BindingPointer<Texture2D> mTexture2DZero;
BindingPointer<TextureCubeMap> mTextureCubeMapZero;
#ifndef HASH_MAP
# ifdef _MSC_VER
# define HASH_MAP stdext::hash_map
# else
# define HASH_MAP std::unordered_map
# endif
#endif
typedef HASH_MAP<GLuint, Framebuffer*> FramebufferMap;
FramebufferMap mFramebufferMap;
HandleAllocator mFramebufferHandleAllocator;
typedef HASH_MAP<GLuint, Fence*> FenceMap;
FenceMap mFenceMap;
HandleAllocator mFenceHandleAllocator;
typedef HASH_MAP<GLuint, Query*> QueryMap;
QueryMap mQueryMap;
HandleAllocator mQueryHandleAllocator;
const char *mExtensionString;
const char *mRendererString;
BindingPointer<Texture> mIncompleteTextures[TEXTURE_TYPE_COUNT];
// Recorded errors
bool mInvalidEnum;
bool mInvalidValue;
bool mInvalidOperation;
bool mOutOfMemory;
bool mInvalidFramebufferOperation;
// Current/lost context flags
bool mHasBeenCurrent;
bool mContextLost;
GLenum mResetStatus;
GLenum mResetStrategy;
bool mRobustAccess;
BindingPointer<ProgramBinary> mCurrentProgramBinary;
Framebuffer *mBoundDrawFramebuffer;
int mMajorShaderModel;
float mMaximumPointSize;
bool mSupportsVertexTexture;
bool mSupportsNonPower2Texture;
bool mSupportsInstancing;
int mMaxViewportDimension;
int mMaxRenderbufferDimension;
int mMaxTextureDimension;
int mMaxCubeTextureDimension;
int mMaxTextureLevel;
float mMaxTextureAnisotropy;
bool mSupportsEventQueries;
bool mSupportsOcclusionQueries;
bool mSupportsBGRATextures;
bool mSupportsDXT1Textures;
bool mSupportsDXT3Textures;
bool mSupportsDXT5Textures;
bool mSupportsFloat32Textures;
bool mSupportsFloat32LinearFilter;
bool mSupportsFloat32RenderableTextures;
bool mSupportsFloat16Textures;
bool mSupportsFloat16LinearFilter;
bool mSupportsFloat16RenderableTextures;
bool mSupportsLuminanceTextures;
bool mSupportsLuminanceAlphaTextures;
bool mSupportsDepthTextures;
bool mSupports32bitIndices;
bool mSupportsTextureFilterAnisotropy;
int mNumCompressedTextureFormats;
ResourceManager *mResourceManager;
};
}
#endif // INCLUDE_CONTEXT_H_
| C++ |
#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.
//
// libGLESv2.cpp: Implements the exported OpenGL ES 2.0 functions.
#include "common/version.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Fence.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/Query.h"
#include "libGLESv2/Context.h"
bool validImageSize(GLint level, GLsizei width, GLsizei height)
{
if (level < 0 || width < 0 || height < 0)
{
return false;
}
if (gl::getContext() && gl::getContext()->supportsNonPower2Texture())
{
return true;
}
if (level == 0)
{
return true;
}
if (gl::isPow2(width) && gl::isPow2(height))
{
return true;
}
return false;
}
// Verify that format/type are one of the combinations from table 3.4.
bool checkTextureFormatType(GLenum format, GLenum type)
{
// validate <format> by itself (used as secondary key below)
switch (format)
{
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
break;
default:
return gl::error(GL_INVALID_ENUM, false);
}
// invalid <type> -> sets INVALID_ENUM
// invalid <format>+<type> combination -> sets INVALID_OPERATION
switch (type)
{
case GL_UNSIGNED_BYTE:
switch (format)
{
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
switch (format)
{
case GL_RGBA:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
switch (format)
{
case GL_RGBA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT_5_6_5:
switch (format)
{
case GL_RGB:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
switch (format)
{
case GL_DEPTH_COMPONENT:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_INT_24_8_OES:
switch (format)
{
case GL_DEPTH_STENCIL_OES:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
default:
return gl::error(GL_INVALID_ENUM, false);
}
}
bool validateSubImageParams2D(bool compressed, GLsizei width, GLsizei height,
GLint xoffset, GLint yoffset, GLint level, GLenum format, GLenum type,
gl::Texture2D *texture)
{
if (!texture)
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (compressed != texture->isCompressed(level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (format != GL_NONE)
{
GLenum internalformat = gl::ConvertSizedInternalFormat(format, type);
if (internalformat != texture->getInternalFormat(level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (compressed)
{
if ((width % 4 != 0 && width != texture->getWidth(0)) ||
(height % 4 != 0 && height != texture->getHeight(0)))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (xoffset + width > texture->getWidth(level) ||
yoffset + height > texture->getHeight(level))
{
return gl::error(GL_INVALID_VALUE, false);
}
return true;
}
bool validateSubImageParamsCube(bool compressed, GLsizei width, GLsizei height,
GLint xoffset, GLint yoffset, GLenum target, GLint level, GLenum format, GLenum type,
gl::TextureCubeMap *texture)
{
if (!texture)
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (compressed != texture->isCompressed(target, level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (format != GL_NONE)
{
GLenum internalformat = gl::ConvertSizedInternalFormat(format, type);
if (internalformat != texture->getInternalFormat(target, level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (compressed)
{
if ((width % 4 != 0 && width != texture->getWidth(target, 0)) ||
(height % 4 != 0 && height != texture->getHeight(target, 0)))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (xoffset + width > texture->getWidth(target, level) ||
yoffset + height > texture->getHeight(target, level))
{
return gl::error(GL_INVALID_VALUE, false);
}
return true;
}
// check for combinations of format and type that are valid for ReadPixels
bool validReadFormatType(GLenum format, GLenum type)
{
switch (format)
{
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
break;
default:
return false;
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
break;
default:
return false;
}
break;
default:
return false;
}
return true;
}
extern "C"
{
void __stdcall glActiveTexture(GLenum texture)
{
EVENT("(GLenum texture = 0x%X)", texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (texture < GL_TEXTURE0 || texture > GL_TEXTURE0 + context->getMaximumCombinedTextureImageUnits() - 1)
{
return gl::error(GL_INVALID_ENUM);
}
context->setActiveSampler(texture - GL_TEXTURE0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glAttachShader(GLuint program, GLuint shader)
{
EVENT("(GLuint program = %d, GLuint shader = %d)", program, shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
gl::Shader *shaderObject = context->getShader(shader);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (!programObject->attachShader(shaderObject))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBeginQueryEXT(GLenum target, GLuint id)
{
EVENT("(GLenum target = 0x%X, GLuint %d)", target, id);
try
{
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (id == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->beginQuery(target, id);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindAttribLocation(GLuint program, GLuint index, const GLchar* name)
{
EVENT("(GLuint program = %d, GLuint index = %d, const GLchar* name = 0x%0.8p)", program, index, name);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (strncmp(name, "gl_", 3) == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
programObject->bindAttributeLocation(index, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindBuffer(GLenum target, GLuint buffer)
{
EVENT("(GLenum target = 0x%X, GLuint buffer = %d)", target, buffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_ARRAY_BUFFER:
context->bindArrayBuffer(buffer);
return;
case GL_ELEMENT_ARRAY_BUFFER:
context->bindElementArrayBuffer(buffer);
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindFramebuffer(GLenum target, GLuint framebuffer)
{
EVENT("(GLenum target = 0x%X, GLuint framebuffer = %d)", target, framebuffer);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target == GL_READ_FRAMEBUFFER_ANGLE || target == GL_FRAMEBUFFER)
{
context->bindReadFramebuffer(framebuffer);
}
if (target == GL_DRAW_FRAMEBUFFER_ANGLE || target == GL_FRAMEBUFFER)
{
context->bindDrawFramebuffer(framebuffer);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindRenderbuffer(GLenum target, GLuint renderbuffer)
{
EVENT("(GLenum target = 0x%X, GLuint renderbuffer = %d)", target, renderbuffer);
try
{
if (target != GL_RENDERBUFFER)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->bindRenderbuffer(renderbuffer);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindTexture(GLenum target, GLuint texture)
{
EVENT("(GLenum target = 0x%X, GLuint texture = %d)", target, texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *textureObject = context->getTexture(texture);
if (textureObject && textureObject->getTarget() != target && texture != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_2D:
context->bindTexture2D(texture);
return;
case GL_TEXTURE_CUBE_MAP:
context->bindTextureCubeMap(texture);
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
EVENT("(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)",
red, green, blue, alpha);
try
{
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setBlendColor(gl::clamp01(red), gl::clamp01(green), gl::clamp01(blue), gl::clamp01(alpha));
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendEquation(GLenum mode)
{
glBlendEquationSeparate(mode, mode);
}
void __stdcall glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
{
EVENT("(GLenum modeRGB = 0x%X, GLenum modeAlpha = 0x%X)", modeRGB, modeAlpha);
try
{
switch (modeRGB)
{
case GL_FUNC_ADD:
case GL_FUNC_SUBTRACT:
case GL_FUNC_REVERSE_SUBTRACT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (modeAlpha)
{
case GL_FUNC_ADD:
case GL_FUNC_SUBTRACT:
case GL_FUNC_REVERSE_SUBTRACT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setBlendEquation(modeRGB, modeAlpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendFunc(GLenum sfactor, GLenum dfactor)
{
glBlendFuncSeparate(sfactor, dfactor, sfactor, dfactor);
}
void __stdcall glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
{
EVENT("(GLenum srcRGB = 0x%X, GLenum dstRGB = 0x%X, GLenum srcAlpha = 0x%X, GLenum dstAlpha = 0x%X)",
srcRGB, dstRGB, srcAlpha, dstAlpha);
try
{
switch (srcRGB)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
case GL_SRC_ALPHA_SATURATE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (dstRGB)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (srcAlpha)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
case GL_SRC_ALPHA_SATURATE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (dstAlpha)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
bool constantColorUsed = (srcRGB == GL_CONSTANT_COLOR || srcRGB == GL_ONE_MINUS_CONSTANT_COLOR ||
dstRGB == GL_CONSTANT_COLOR || dstRGB == GL_ONE_MINUS_CONSTANT_COLOR);
bool constantAlphaUsed = (srcRGB == GL_CONSTANT_ALPHA || srcRGB == GL_ONE_MINUS_CONSTANT_ALPHA ||
dstRGB == GL_CONSTANT_ALPHA || dstRGB == GL_ONE_MINUS_CONSTANT_ALPHA);
if (constantColorUsed && constantAlphaUsed)
{
ERR("Simultaneous use of GL_CONSTANT_ALPHA/GL_ONE_MINUS_CONSTANT_ALPHA and GL_CONSTANT_COLOR/GL_ONE_MINUS_CONSTANT_COLOR invalid under WebGL");
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setBlendFactors(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage)
{
EVENT("(GLenum target = 0x%X, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p, GLenum usage = %d)",
target, size, data, usage);
try
{
if (size < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (usage)
{
case GL_STREAM_DRAW:
case GL_STATIC_DRAW:
case GL_DYNAMIC_DRAW:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
return gl::error(GL_INVALID_OPERATION);
}
buffer->bufferData(data, size, usage);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p)",
target, offset, size, data);
try
{
if (size < 0 || offset < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (data == NULL)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if ((size_t)size + offset > buffer->size())
{
return gl::error(GL_INVALID_VALUE);
}
buffer->bufferSubData(data, size, offset);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glCheckFramebufferStatus(GLenum target)
{
EVENT("(GLenum target = 0x%X)", target);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM, 0);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Framebuffer *framebuffer = NULL;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
}
else
{
framebuffer = context->getDrawFramebuffer();
}
return framebuffer->completeness();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
void __stdcall glClear(GLbitfield mask)
{
EVENT("(GLbitfield mask = %X)", mask);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->clear(mask);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
EVENT("(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)",
red, green, blue, alpha);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearColor(red, green, blue, alpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearDepthf(GLclampf depth)
{
EVENT("(GLclampf depth = %f)", depth);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearDepth(depth);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearStencil(GLint s)
{
EVENT("(GLint s = %d)", s);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearStencil(s);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
EVENT("(GLboolean red = %d, GLboolean green = %d, GLboolean blue = %d, GLboolean alpha = %d)",
red, green, blue, alpha);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setColorMask(red == GL_TRUE, green == GL_TRUE, blue == GL_TRUE, alpha == GL_TRUE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompileShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
shaderObject->compile();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height,
GLint border, GLsizei imageSize, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, GLsizei width = %d, "
"GLsizei height = %d, GLint border = %d, GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)",
target, level, internalformat, width, height, border, imageSize, data);
try
{
if (!validImageSize(level, width, height) || border != 0 || imageSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (border != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (width != 1 && width != 2 && width % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (height != 1 && height != 2 && height % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (internalformat) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
default: UNREACHABLE();
}
if (imageSize != gl::ComputeCompressedSize(width, height, internalformat))
{
return gl::error(GL_INVALID_VALUE);
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->setCompressedImage(level, internalformat, width, height, imageSize, data);
}
else
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
texture->setCompressedImage(target, level, internalformat, width, height, imageSize, data);
break;
default: UNREACHABLE();
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLsizei imageSize, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, "
"GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)",
target, level, xoffset, yoffset, width, height, format, imageSize, data);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (xoffset < 0 || yoffset < 0 || !validImageSize(level, width, height) || imageSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (format)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (width == 0 || height == 0 || data == NULL)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (format) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
default: UNREACHABLE();
}
if (imageSize != gl::ComputeCompressedSize(width, height, format))
{
return gl::error(GL_INVALID_VALUE);
}
if (xoffset % 4 != 0 || yoffset % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION); // we wait to check the offsets until this point, because the multiple-of-four restriction
// does not exist unless DXT textures are supported.
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (validateSubImageParams2D(true, width, height, xoffset, yoffset, level, format, GL_NONE, texture))
{
texture->subImageCompressed(level, xoffset, yoffset, width, height, format, imageSize, data);
}
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (validateSubImageParamsCube(true, width, height, xoffset, yoffset, target, level, format, GL_NONE, texture))
{
texture->subImageCompressed(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
}
else
{
UNREACHABLE();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "
"GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, GLint border = %d)",
target, level, internalformat, x, y, width, height, border);
try
{
if (!validImageSize(level, width, height))
{
return gl::error(GL_INVALID_VALUE);
}
if (border != 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Framebuffer *framebuffer = context->getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (context->getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *source = framebuffer->getReadColorbuffer();
GLenum colorbufferFormat = source->getInternalFormat();
// [OpenGL ES 2.0.24] table 3.9
switch (internalformat)
{
case GL_ALPHA:
if (colorbufferFormat != GL_ALPHA8_EXT &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE:
case GL_RGB:
if (colorbufferFormat != GL_RGB565 &&
colorbufferFormat != GL_RGB8_OES &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE_ALPHA:
case GL_RGBA:
if (colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_STENCIL_OES:
case GL_DEPTH24_STENCIL8_OES:
if (context->supportsDepthTextures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
default:
return gl::error(GL_INVALID_ENUM);
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->copyImage(level, internalformat, x, y, width, height, framebuffer);
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->copyImage(target, level, internalformat, x, y, width, height, framebuffer);
}
else UNREACHABLE();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)",
target, level, xoffset, yoffset, x, y, width, height);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (level < 0 || xoffset < 0 || yoffset < 0 || width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (std::numeric_limits<GLsizei>::max() - xoffset < width || std::numeric_limits<GLsizei>::max() - yoffset < height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width == 0 || height == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
gl::Framebuffer *framebuffer = context->getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (context->getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *source = framebuffer->getReadColorbuffer();
GLenum colorbufferFormat = source->getInternalFormat();
gl::Texture *texture = NULL;
GLenum textureFormat = GL_RGBA;
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *tex2d = context->getTexture2D();
if (!validateSubImageParams2D(false, width, height, xoffset, yoffset, level, GL_NONE, GL_NONE, tex2d))
{
return; // error already registered by validateSubImageParams
}
textureFormat = gl::ExtractFormat(tex2d->getInternalFormat(level));
texture = tex2d;
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texcube = context->getTextureCubeMap();
if (!validateSubImageParamsCube(false, width, height, xoffset, yoffset, target, level, GL_NONE, GL_NONE, texcube))
{
return; // error already registered by validateSubImageParams
}
textureFormat = gl::ExtractFormat(texcube->getInternalFormat(target, level));
texture = texcube;
}
else UNREACHABLE();
// [OpenGL ES 2.0.24] table 3.9
switch (textureFormat)
{
case GL_ALPHA:
if (colorbufferFormat != GL_ALPHA8_EXT &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE:
case GL_RGB:
if (colorbufferFormat != GL_RGB565 &&
colorbufferFormat != GL_RGB8_OES &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE_ALPHA:
case GL_RGBA:
if (colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return gl::error(GL_INVALID_OPERATION);
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
return gl::error(GL_INVALID_OPERATION);
default:
return gl::error(GL_INVALID_OPERATION);
}
texture->copySubImage(target, level, xoffset, yoffset, x, y, width, height, framebuffer);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLuint __stdcall glCreateProgram(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
return context->createProgram();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
GLuint __stdcall glCreateShader(GLenum type)
{
EVENT("(GLenum type = 0x%X)", type);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_FRAGMENT_SHADER:
case GL_VERTEX_SHADER:
return context->createShader(type);
default:
return gl::error(GL_INVALID_ENUM, 0);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
void __stdcall glCullFace(GLenum mode)
{
EVENT("(GLenum mode = 0x%X)", mode);
try
{
switch (mode)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setCullMode(mode);
}
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteBuffers(GLsizei n, const GLuint* buffers)
{
EVENT("(GLsizei n = %d, const GLuint* buffers = 0x%0.8p)", n, buffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteBuffer(buffers[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteFencesNV(GLsizei n, const GLuint* fences)
{
EVENT("(GLsizei n = %d, const GLuint* fences = 0x%0.8p)", n, fences);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteFence(fences[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers)
{
EVENT("(GLsizei n = %d, const GLuint* framebuffers = 0x%0.8p)", n, framebuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
if (framebuffers[i] != 0)
{
context->deleteFramebuffer(framebuffers[i]);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
if (program == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!context->getProgram(program))
{
if(context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->deleteProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteQueriesEXT(GLsizei n, const GLuint *ids)
{
EVENT("(GLsizei n = %d, const GLuint *ids = 0x%0.8p)", n, ids);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteQuery(ids[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers)
{
EVENT("(GLsizei n = %d, const GLuint* renderbuffers = 0x%0.8p)", n, renderbuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteRenderbuffer(renderbuffers[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
if (shader == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!context->getShader(shader))
{
if(context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->deleteShader(shader);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteTextures(GLsizei n, const GLuint* textures)
{
EVENT("(GLsizei n = %d, const GLuint* textures = 0x%0.8p)", n, textures);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
if (textures[i] != 0)
{
context->deleteTexture(textures[i]);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthFunc(GLenum func)
{
EVENT("(GLenum func = 0x%X)", func);
try
{
switch (func)
{
case GL_NEVER:
case GL_ALWAYS:
case GL_LESS:
case GL_LEQUAL:
case GL_EQUAL:
case GL_GREATER:
case GL_GEQUAL:
case GL_NOTEQUAL:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthFunc(func);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthMask(GLboolean flag)
{
EVENT("(GLboolean flag = %d)", flag);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthMask(flag != GL_FALSE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthRangef(GLclampf zNear, GLclampf zFar)
{
EVENT("(GLclampf zNear = %f, GLclampf zFar = %f)", zNear, zFar);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthRange(zNear, zFar);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDetachShader(GLuint program, GLuint shader)
{
EVENT("(GLuint program = %d, GLuint shader = %d)", program, shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
gl::Shader *shaderObject = context->getShader(shader);
if (!programObject)
{
gl::Shader *shaderByProgramHandle;
shaderByProgramHandle = context->getShader(program);
if (!shaderByProgramHandle)
{
return gl::error(GL_INVALID_VALUE);
}
else
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (!shaderObject)
{
gl::Program *programByShaderHandle = context->getProgram(shader);
if (!programByShaderHandle)
{
return gl::error(GL_INVALID_VALUE);
}
else
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (!programObject->detachShader(shaderObject))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDisable(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: context->setCullFace(false); break;
case GL_POLYGON_OFFSET_FILL: context->setPolygonOffsetFill(false); break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: context->setSampleAlphaToCoverage(false); break;
case GL_SAMPLE_COVERAGE: context->setSampleCoverage(false); break;
case GL_SCISSOR_TEST: context->setScissorTest(false); break;
case GL_STENCIL_TEST: context->setStencilTest(false); break;
case GL_DEPTH_TEST: context->setDepthTest(false); break;
case GL_BLEND: context->setBlend(false); break;
case GL_DITHER: context->setDither(false); break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDisableVertexAttribArray(GLuint index)
{
EVENT("(GLuint index = %d)", index);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setEnableVertexAttribArray(index, false);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawArrays(GLenum mode, GLint first, GLsizei count)
{
EVENT("(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d)", mode, first, count);
try
{
if (count < 0 || first < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->drawArrays(mode, first, count, 0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
{
EVENT("(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d, GLsizei primcount = %d)", mode, first, count, primcount);
try
{
if (count < 0 || first < 0 || primcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (primcount > 0)
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->drawArrays(mode, first, count, primcount);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
EVENT("(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p)",
mode, count, type, indices);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT:
break;
case GL_UNSIGNED_INT:
if (!context->supports32bitIndices())
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
context->drawElements(mode, count, type, indices, 0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount)
{
EVENT("(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p, GLsizei primcount = %d)",
mode, count, type, indices, primcount);
try
{
if (count < 0 || primcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (primcount > 0)
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT:
break;
case GL_UNSIGNED_INT:
if (!context->supports32bitIndices())
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
context->drawElements(mode, count, type, indices, primcount);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEnable(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: context->setCullFace(true); break;
case GL_POLYGON_OFFSET_FILL: context->setPolygonOffsetFill(true); break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: context->setSampleAlphaToCoverage(true); break;
case GL_SAMPLE_COVERAGE: context->setSampleCoverage(true); break;
case GL_SCISSOR_TEST: context->setScissorTest(true); break;
case GL_STENCIL_TEST: context->setStencilTest(true); break;
case GL_DEPTH_TEST: context->setDepthTest(true); break;
case GL_BLEND: context->setBlend(true); break;
case GL_DITHER: context->setDither(true); break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEnableVertexAttribArray(GLuint index)
{
EVENT("(GLuint index = %d)", index);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setEnableVertexAttribArray(index, true);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEndQueryEXT(GLenum target)
{
EVENT("GLenum target = 0x%X)", target);
try
{
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->endQuery(target);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFinishFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence* fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->finishFence();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFinish(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->sync(true);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFlush(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->sync(false);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum renderbuffertarget = 0x%X, "
"GLuint renderbuffer = %d)", target, attachment, renderbuffertarget, renderbuffer);
try
{
if ((target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
|| (renderbuffertarget != GL_RENDERBUFFER && renderbuffer != 0))
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Framebuffer *framebuffer = NULL;
GLuint framebufferHandle = 0;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
framebufferHandle = context->getReadFramebufferHandle();
}
else
{
framebuffer = context->getDrawFramebuffer();
framebufferHandle = context->getDrawFramebufferHandle();
}
if (!framebuffer || (framebufferHandle == 0 && renderbuffer != 0))
{
return gl::error(GL_INVALID_OPERATION);
}
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
framebuffer->setColorbuffer(colorAttachment, GL_RENDERBUFFER, renderbuffer);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
framebuffer->setDepthbuffer(GL_RENDERBUFFER, renderbuffer);
break;
case GL_STENCIL_ATTACHMENT:
framebuffer->setStencilbuffer(GL_RENDERBUFFER, renderbuffer);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum textarget = 0x%X, "
"GLuint texture = %d, GLint level = %d)", target, attachment, textarget, texture, level);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
case GL_STENCIL_ATTACHMENT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
if (texture == 0)
{
textarget = GL_NONE;
}
else
{
gl::Texture *tex = context->getTexture(texture);
if (tex == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (textarget)
{
case GL_TEXTURE_2D:
{
if (tex->getTarget() != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Texture2D *tex2d = static_cast<gl::Texture2D *>(tex);
if (tex2d->isCompressed(0))
{
return gl::error(GL_INVALID_OPERATION);
}
break;
}
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
{
if (tex->getTarget() != GL_TEXTURE_CUBE_MAP)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::TextureCubeMap *texcube = static_cast<gl::TextureCubeMap *>(tex);
if (texcube->isCompressed(textarget, level))
{
return gl::error(GL_INVALID_OPERATION);
}
break;
}
default:
return gl::error(GL_INVALID_ENUM);
}
if (level != 0)
{
return gl::error(GL_INVALID_VALUE);
}
}
gl::Framebuffer *framebuffer = NULL;
GLuint framebufferHandle = 0;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
framebufferHandle = context->getReadFramebufferHandle();
}
else
{
framebuffer = context->getDrawFramebuffer();
framebufferHandle = context->getDrawFramebufferHandle();
}
if (framebufferHandle == 0 || !framebuffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
framebuffer->setColorbuffer(colorAttachment, textarget, texture);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT: framebuffer->setDepthbuffer(textarget, texture); break;
case GL_STENCIL_ATTACHMENT: framebuffer->setStencilbuffer(textarget, texture); break;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFrontFace(GLenum mode)
{
EVENT("(GLenum mode = 0x%X)", mode);
try
{
switch (mode)
{
case GL_CW:
case GL_CCW:
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setFrontFace(mode);
}
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenBuffers(GLsizei n, GLuint* buffers)
{
EVENT("(GLsizei n = %d, GLuint* buffers = 0x%0.8p)", n, buffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
buffers[i] = context->createBuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenerateMipmap(GLenum target)
{
EVENT("(GLenum target = 0x%X)", target);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_TEXTURE_2D:
{
gl::Texture2D *tex2d = context->getTexture2D();
if (tex2d->isCompressed(0))
{
return gl::error(GL_INVALID_OPERATION);
}
if (tex2d->isDepth(0))
{
return gl::error(GL_INVALID_OPERATION);
}
tex2d->generateMipmaps();
break;
}
case GL_TEXTURE_CUBE_MAP:
{
gl::TextureCubeMap *texcube = context->getTextureCubeMap();
if (texcube->isCompressed(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0))
{
return gl::error(GL_INVALID_OPERATION);
}
texcube->generateMipmaps();
break;
}
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenFencesNV(GLsizei n, GLuint* fences)
{
EVENT("(GLsizei n = %d, GLuint* fences = 0x%0.8p)", n, fences);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
fences[i] = context->createFence();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenFramebuffers(GLsizei n, GLuint* framebuffers)
{
EVENT("(GLsizei n = %d, GLuint* framebuffers = 0x%0.8p)", n, framebuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
framebuffers[i] = context->createFramebuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenQueriesEXT(GLsizei n, GLuint* ids)
{
EVENT("(GLsizei n = %d, GLuint* ids = 0x%0.8p)", n, ids);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
ids[i] = context->createQuery();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
{
EVENT("(GLsizei n = %d, GLuint* renderbuffers = 0x%0.8p)", n, renderbuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
renderbuffers[i] = context->createRenderbuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenTextures(GLsizei n, GLuint* textures)
{
EVENT("(GLsizei n = %d, GLuint* textures = 0x%0.8p)", n, textures);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
textures[i] = context->createTexture();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
EVENT("(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, GLsizei *length = 0x%0.8p, "
"GLint *size = 0x%0.8p, GLenum *type = %0.8p, GLchar *name = %0.8p)",
program, index, bufsize, length, size, type, name);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (index >= (GLuint)programObject->getActiveAttributeCount())
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getActiveAttribute(index, bufsize, length, size, type, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name)
{
EVENT("(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, "
"GLsizei* length = 0x%0.8p, GLint* size = 0x%0.8p, GLenum* type = 0x%0.8p, GLchar* name = 0x%0.8p)",
program, index, bufsize, length, size, type, name);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (index >= (GLuint)programObject->getActiveUniformCount())
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getActiveUniform(index, bufsize, length, size, type, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
{
EVENT("(GLuint program = %d, GLsizei maxcount = %d, GLsizei* count = 0x%0.8p, GLuint* shaders = 0x%0.8p)",
program, maxcount, count, shaders);
try
{
if (maxcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
return programObject->getAttachedShaders(maxcount, count, shaders);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
int __stdcall glGetAttribLocation(GLuint program, const GLchar* name)
{
EVENT("(GLuint program = %d, const GLchar* name = %s)", program, name);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION, -1);
}
else
{
return gl::error(GL_INVALID_VALUE, -1);
}
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programObject->isLinked() || !programBinary)
{
return gl::error(GL_INVALID_OPERATION, -1);
}
return programBinary->getAttributeLocation(name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, -1);
}
return -1;
}
void __stdcall glGetBooleanv(GLenum pname, GLboolean* params)
{
EVENT("(GLenum pname = 0x%X, GLboolean* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getBooleanv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that the pname is valid, but there are no parameters to return
if (nativeType == GL_FLOAT)
{
GLfloat *floatParams = NULL;
floatParams = new GLfloat[numParams];
context->getFloatv(pname, floatParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (floatParams[i] == 0.0f)
params[i] = GL_FALSE;
else
params[i] = GL_TRUE;
}
delete [] floatParams;
}
else if (nativeType == GL_INT)
{
GLint *intParams = NULL;
intParams = new GLint[numParams];
context->getIntegerv(pname, intParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (intParams[i] == 0)
params[i] = GL_FALSE;
else
params[i] = GL_TRUE;
}
delete [] intParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default: return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
// A null buffer means that "0" is bound to the requested buffer target
return gl::error(GL_INVALID_OPERATION);
}
switch (pname)
{
case GL_BUFFER_USAGE:
*params = buffer->usage();
break;
case GL_BUFFER_SIZE:
*params = buffer->size();
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glGetError(void)
{
EVENT("()");
gl::Context *context = gl::getContext();
if (context)
{
return context->getError();
}
return GL_NO_ERROR;
}
void __stdcall glGetFenceivNV(GLuint fence, GLenum pname, GLint *params)
{
EVENT("(GLuint fence = %d, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", fence, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->getFenceiv(pname, params);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetFloatv(GLenum pname, GLfloat* params)
{
EVENT("(GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getFloatv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that the pname is valid, but that there are no parameters to return.
if (nativeType == GL_BOOL)
{
GLboolean *boolParams = NULL;
boolParams = new GLboolean[numParams];
context->getBooleanv(pname, boolParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (boolParams[i] == GL_FALSE)
params[i] = 0.0f;
else
params[i] = 1.0f;
}
delete [] boolParams;
}
else if (nativeType == GL_INT)
{
GLint *intParams = NULL;
intParams = new GLint[numParams];
context->getIntegerv(pname, intParams);
for (unsigned int i = 0; i < numParams; ++i)
{
params[i] = (GLfloat)intParams[i];
}
delete [] intParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)",
target, attachment, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Framebuffer *framebuffer = NULL;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
if(context->getReadFramebufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
framebuffer = context->getReadFramebuffer();
}
else
{
if (context->getDrawFramebufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
framebuffer = context->getDrawFramebuffer();
}
GLenum attachmentType;
GLuint attachmentHandle;
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_ENUM);
}
attachmentType = framebuffer->getColorbufferType(colorAttachment);
attachmentHandle = framebuffer->getColorbufferHandle(colorAttachment);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
attachmentType = framebuffer->getDepthbufferType();
attachmentHandle = framebuffer->getDepthbufferHandle();
break;
case GL_STENCIL_ATTACHMENT:
attachmentType = framebuffer->getStencilbufferType();
attachmentHandle = framebuffer->getStencilbufferHandle();
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
GLenum attachmentObjectType; // Type category
if (attachmentType == GL_NONE || attachmentType == GL_RENDERBUFFER)
{
attachmentObjectType = attachmentType;
}
else if (gl::IsInternalTextureTarget(attachmentType))
{
attachmentObjectType = GL_TEXTURE;
}
else
{
UNREACHABLE();
return;
}
switch (pname)
{
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
*params = attachmentObjectType;
break;
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
if (attachmentObjectType == GL_RENDERBUFFER || attachmentObjectType == GL_TEXTURE)
{
*params = attachmentHandle;
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
if (attachmentObjectType == GL_TEXTURE)
{
*params = 0; // FramebufferTexture2D will not allow level to be set to anything else in GL ES 2.0
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
if (attachmentObjectType == GL_TEXTURE)
{
if (gl::IsCubemapTextureTarget(attachmentType))
{
*params = attachmentType;
}
else
{
*params = 0;
}
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glGetGraphicsResetStatusEXT(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getContext();
if (context)
{
return context->getResetStatus();
}
return GL_NO_ERROR;
}
catch(std::bad_alloc&)
{
return GL_OUT_OF_MEMORY;
}
}
void __stdcall glGetIntegerv(GLenum pname, GLint* params)
{
EVENT("(GLenum pname = 0x%X, GLint* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getIntegerv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that pname is valid, but there are no parameters to return
if (nativeType == GL_BOOL)
{
GLboolean *boolParams = NULL;
boolParams = new GLboolean[numParams];
context->getBooleanv(pname, boolParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (boolParams[i] == GL_FALSE)
params[i] = 0;
else
params[i] = 1;
}
delete [] boolParams;
}
else if (nativeType == GL_FLOAT)
{
GLfloat *floatParams = NULL;
floatParams = new GLfloat[numParams];
context->getFloatv(pname, floatParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (pname == GL_DEPTH_RANGE || pname == GL_COLOR_CLEAR_VALUE || pname == GL_DEPTH_CLEAR_VALUE || pname == GL_BLEND_COLOR)
{
params[i] = (GLint)(((GLfloat)(0xFFFFFFFF) * floatParams[i] - 1.0f) / 2.0f);
}
else
params[i] = (GLint)(floatParams[i] > 0.0f ? floor(floatParams[i] + 0.5) : ceil(floatParams[i] - 0.5));
}
delete [] floatParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramiv(GLuint program, GLenum pname, GLint* params)
{
EVENT("(GLuint program = %d, GLenum pname = %d, GLint* params = 0x%0.8p)", program, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_VALUE);
}
switch (pname)
{
case GL_DELETE_STATUS:
*params = programObject->isFlaggedForDeletion();
return;
case GL_LINK_STATUS:
*params = programObject->isLinked();
return;
case GL_VALIDATE_STATUS:
*params = programObject->isValidated();
return;
case GL_INFO_LOG_LENGTH:
*params = programObject->getInfoLogLength();
return;
case GL_ATTACHED_SHADERS:
*params = programObject->getAttachedShadersCount();
return;
case GL_ACTIVE_ATTRIBUTES:
*params = programObject->getActiveAttributeCount();
return;
case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
*params = programObject->getActiveAttributeMaxLength();
return;
case GL_ACTIVE_UNIFORMS:
*params = programObject->getActiveUniformCount();
return;
case GL_ACTIVE_UNIFORM_MAX_LENGTH:
*params = programObject->getActiveUniformMaxLength();
return;
case GL_PROGRAM_BINARY_LENGTH_OES:
*params = programObject->getProgramBinaryLength();
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog)
{
EVENT("(GLuint program = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)",
program, bufsize, length, infolog);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getInfoLog(bufsize, length, infolog);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetQueryivEXT(GLenum target, GLenum pname, GLint *params)
{
EVENT("GLenum target = 0x%X, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", target, pname, params);
try
{
switch (pname)
{
case GL_CURRENT_QUERY_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
params[0] = context->getActiveQuery(target);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetQueryObjectuivEXT(GLuint id, GLenum pname, GLuint *params)
{
EVENT("(GLuint id = %d, GLenum pname = 0x%X, GLuint *params = 0x%0.8p)", id, pname, params);
try
{
switch (pname)
{
case GL_QUERY_RESULT_EXT:
case GL_QUERY_RESULT_AVAILABLE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Query *queryObject = context->getQuery(id, false, GL_NONE);
if (!queryObject)
{
return gl::error(GL_INVALID_OPERATION);
}
if (context->getActiveQuery(queryObject->getType()) == id)
{
return gl::error(GL_INVALID_OPERATION);
}
switch(pname)
{
case GL_QUERY_RESULT_EXT:
params[0] = queryObject->getResult();
break;
case GL_QUERY_RESULT_AVAILABLE_EXT:
params[0] = queryObject->isResultAvailable();
break;
default:
ASSERT(false);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target != GL_RENDERBUFFER)
{
return gl::error(GL_INVALID_ENUM);
}
if (context->getRenderbufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *renderbuffer = context->getRenderbuffer(context->getRenderbufferHandle());
switch (pname)
{
case GL_RENDERBUFFER_WIDTH: *params = renderbuffer->getWidth(); break;
case GL_RENDERBUFFER_HEIGHT: *params = renderbuffer->getHeight(); break;
case GL_RENDERBUFFER_INTERNAL_FORMAT: *params = renderbuffer->getInternalFormat(); break;
case GL_RENDERBUFFER_RED_SIZE: *params = renderbuffer->getRedSize(); break;
case GL_RENDERBUFFER_GREEN_SIZE: *params = renderbuffer->getGreenSize(); break;
case GL_RENDERBUFFER_BLUE_SIZE: *params = renderbuffer->getBlueSize(); break;
case GL_RENDERBUFFER_ALPHA_SIZE: *params = renderbuffer->getAlphaSize(); break;
case GL_RENDERBUFFER_DEPTH_SIZE: *params = renderbuffer->getDepthSize(); break;
case GL_RENDERBUFFER_STENCIL_SIZE: *params = renderbuffer->getStencilSize(); break;
case GL_RENDERBUFFER_SAMPLES_ANGLE:
if (context->getMaxSupportedSamples() != 0)
{
*params = renderbuffer->getSamples();
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
{
EVENT("(GLuint shader = %d, GLenum pname = %d, GLint* params = 0x%0.8p)", shader, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_VALUE);
}
switch (pname)
{
case GL_SHADER_TYPE:
*params = shaderObject->getType();
return;
case GL_DELETE_STATUS:
*params = shaderObject->isFlaggedForDeletion();
return;
case GL_COMPILE_STATUS:
*params = shaderObject->isCompiled() ? GL_TRUE : GL_FALSE;
return;
case GL_INFO_LOG_LENGTH:
*params = shaderObject->getInfoLogLength();
return;
case GL_SHADER_SOURCE_LENGTH:
*params = shaderObject->getSourceLength();
return;
case GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE:
*params = shaderObject->getTranslatedSourceLength();
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)",
shader, bufsize, length, infolog);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_VALUE);
}
shaderObject->getInfoLog(bufsize, length, infolog);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
{
EVENT("(GLenum shadertype = 0x%X, GLenum precisiontype = 0x%X, GLint* range = 0x%0.8p, GLint* precision = 0x%0.8p)",
shadertype, precisiontype, range, precision);
try
{
switch (shadertype)
{
case GL_VERTEX_SHADER:
case GL_FRAGMENT_SHADER:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (precisiontype)
{
case GL_LOW_FLOAT:
case GL_MEDIUM_FLOAT:
case GL_HIGH_FLOAT:
// Assume IEEE 754 precision
range[0] = 127;
range[1] = 127;
*precision = 23;
break;
case GL_LOW_INT:
case GL_MEDIUM_INT:
case GL_HIGH_INT:
// Some (most) hardware only supports single-precision floating-point numbers,
// which can accurately represent integers up to +/-16777216
range[0] = 24;
range[1] = 24;
*precision = 0;
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)",
shader, bufsize, length, source);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_OPERATION);
}
shaderObject->getSource(bufsize, length, source);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetTranslatedShaderSourceANGLE(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)",
shader, bufsize, length, source);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_OPERATION);
}
shaderObject->getTranslatedSource(bufsize, length, source);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
const GLubyte* __stdcall glGetString(GLenum name)
{
EVENT("(GLenum name = 0x%X)", name);
try
{
gl::Context *context = gl::getNonLostContext();
switch (name)
{
case GL_VENDOR:
return (GLubyte*)"Google Inc.";
case GL_RENDERER:
return (GLubyte*)((context != NULL) ? context->getRendererString() : "ANGLE");
case GL_VERSION:
return (GLubyte*)"OpenGL ES 2.0 (ANGLE " VERSION_STRING ")";
case GL_SHADING_LANGUAGE_VERSION:
return (GLubyte*)"OpenGL ES GLSL ES 1.00 (ANGLE " VERSION_STRING ")";
case GL_EXTENSIONS:
return (GLubyte*)((context != NULL) ? context->getExtensionString() : "");
default:
return gl::error(GL_INVALID_ENUM, (GLubyte*)NULL);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, (GLubyte*)NULL);
}
}
void __stdcall glGetTexParameterfv(GLenum target, GLenum pname, GLfloat* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_MAG_FILTER:
*params = (GLfloat)texture->getMagFilter();
break;
case GL_TEXTURE_MIN_FILTER:
*params = (GLfloat)texture->getMinFilter();
break;
case GL_TEXTURE_WRAP_S:
*params = (GLfloat)texture->getWrapS();
break;
case GL_TEXTURE_WRAP_T:
*params = (GLfloat)texture->getWrapT();
break;
case GL_TEXTURE_IMMUTABLE_FORMAT_EXT:
*params = (GLfloat)(texture->isImmutable() ? GL_TRUE : GL_FALSE);
break;
case GL_TEXTURE_USAGE_ANGLE:
*params = (GLfloat)texture->getUsage();
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
*params = (GLfloat)texture->getMaxAnisotropy();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetTexParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_MAG_FILTER:
*params = texture->getMagFilter();
break;
case GL_TEXTURE_MIN_FILTER:
*params = texture->getMinFilter();
break;
case GL_TEXTURE_WRAP_S:
*params = texture->getWrapS();
break;
case GL_TEXTURE_WRAP_T:
*params = texture->getWrapT();
break;
case GL_TEXTURE_IMMUTABLE_FORMAT_EXT:
*params = texture->isImmutable() ? GL_TRUE : GL_FALSE;
break;
case GL_TEXTURE_USAGE_ANGLE:
*params = texture->getUsage();
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
*params = (GLint)texture->getMaxAnisotropy();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetnUniformfvEXT(GLuint program, GLint location, GLsizei bufSize, GLfloat* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLfloat* params = 0x%0.8p)",
program, location, bufSize, params);
try
{
if (bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformfv(location, &bufSize, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetUniformfv(GLuint program, GLint location, GLfloat* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLfloat* params = 0x%0.8p)", program, location, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformfv(location, NULL, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetnUniformivEXT(GLuint program, GLint location, GLsizei bufSize, GLint* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLint* params = 0x%0.8p)",
program, location, bufSize, params);
try
{
if (bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformiv(location, &bufSize, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetUniformiv(GLuint program, GLint location, GLint* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLint* params = 0x%0.8p)", program, location, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformiv(location, NULL, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
int __stdcall glGetUniformLocation(GLuint program, const GLchar* name)
{
EVENT("(GLuint program = %d, const GLchar* name = 0x%0.8p)", program, name);
try
{
gl::Context *context = gl::getNonLostContext();
if (strstr(name, "gl_") == name)
{
return -1;
}
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION, -1);
}
else
{
return gl::error(GL_INVALID_VALUE, -1);
}
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programObject->isLinked() || !programBinary)
{
return gl::error(GL_INVALID_OPERATION, -1);
}
return programBinary->getUniformLocation(name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, -1);
}
return -1;
}
void __stdcall glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", index, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
const gl::VertexAttribute &attribState = context->getVertexAttribState(index);
switch (pname)
{
case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
*params = (GLfloat)(attribState.mArrayEnabled ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_SIZE:
*params = (GLfloat)attribState.mSize;
break;
case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
*params = (GLfloat)attribState.mStride;
break;
case GL_VERTEX_ATTRIB_ARRAY_TYPE:
*params = (GLfloat)attribState.mType;
break;
case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
*params = (GLfloat)(attribState.mNormalized ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
*params = (GLfloat)attribState.mBoundBuffer.id();
break;
case GL_CURRENT_VERTEX_ATTRIB:
for (int i = 0; i < 4; ++i)
{
params[i] = attribState.mCurrentValue[i];
}
break;
case GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:
*params = (GLfloat)attribState.mDivisor;
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", index, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
const gl::VertexAttribute &attribState = context->getVertexAttribState(index);
switch (pname)
{
case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
*params = (attribState.mArrayEnabled ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_SIZE:
*params = attribState.mSize;
break;
case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
*params = attribState.mStride;
break;
case GL_VERTEX_ATTRIB_ARRAY_TYPE:
*params = attribState.mType;
break;
case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
*params = (attribState.mNormalized ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
*params = attribState.mBoundBuffer.id();
break;
case GL_CURRENT_VERTEX_ATTRIB:
for (int i = 0; i < 4; ++i)
{
float currentValue = attribState.mCurrentValue[i];
params[i] = (GLint)(currentValue > 0.0f ? floor(currentValue + 0.5f) : ceil(currentValue - 0.5f));
}
break;
case GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:
*params = (GLint)attribState.mDivisor;
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetVertexAttribPointerv(GLuint index, GLenum pname, GLvoid** pointer)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLvoid** pointer = 0x%0.8p)", index, pname, pointer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER)
{
return gl::error(GL_INVALID_ENUM);
}
*pointer = const_cast<GLvoid*>(context->getVertexAttribPointer(index));
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glHint(GLenum target, GLenum mode)
{
EVENT("(GLenum target = 0x%X, GLenum mode = 0x%X)", target, mode);
try
{
switch (mode)
{
case GL_FASTEST:
case GL_NICEST:
case GL_DONT_CARE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
switch (target)
{
case GL_GENERATE_MIPMAP_HINT:
if (context) context->setGenerateMipmapHint(mode);
break;
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
if (context) context->setFragmentShaderDerivativeHint(mode);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLboolean __stdcall glIsBuffer(GLuint buffer)
{
EVENT("(GLuint buffer = %d)", buffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && buffer)
{
gl::Buffer *bufferObject = context->getBuffer(buffer);
if (bufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsEnabled(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: return context->isCullFaceEnabled();
case GL_POLYGON_OFFSET_FILL: return context->isPolygonOffsetFillEnabled();
case GL_SAMPLE_ALPHA_TO_COVERAGE: return context->isSampleAlphaToCoverageEnabled();
case GL_SAMPLE_COVERAGE: return context->isSampleCoverageEnabled();
case GL_SCISSOR_TEST: return context->isScissorTestEnabled();
case GL_STENCIL_TEST: return context->isStencilTestEnabled();
case GL_DEPTH_TEST: return context->isDepthTestEnabled();
case GL_BLEND: return context->isBlendEnabled();
case GL_DITHER: return context->isDitherEnabled();
default:
return gl::error(GL_INVALID_ENUM, false);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, false);
}
return false;
}
GLboolean __stdcall glIsFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return GL_FALSE;
}
return fenceObject->isFence();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsFramebuffer(GLuint framebuffer)
{
EVENT("(GLuint framebuffer = %d)", framebuffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && framebuffer)
{
gl::Framebuffer *framebufferObject = context->getFramebuffer(framebuffer);
if (framebufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && program)
{
gl::Program *programObject = context->getProgram(program);
if (programObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsQueryEXT(GLuint id)
{
EVENT("(GLuint id = %d)", id);
try
{
if (id == 0)
{
return GL_FALSE;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Query *queryObject = context->getQuery(id, false, GL_NONE);
if (queryObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsRenderbuffer(GLuint renderbuffer)
{
EVENT("(GLuint renderbuffer = %d)", renderbuffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && renderbuffer)
{
gl::Renderbuffer *renderbufferObject = context->getRenderbuffer(renderbuffer);
if (renderbufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && shader)
{
gl::Shader *shaderObject = context->getShader(shader);
if (shaderObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsTexture(GLuint texture)
{
EVENT("(GLuint texture = %d)", texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && texture)
{
gl::Texture *textureObject = context->getTexture(texture);
if (textureObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
void __stdcall glLineWidth(GLfloat width)
{
EVENT("(GLfloat width = %f)", width);
try
{
if (width <= 0.0f)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setLineWidth(width);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glLinkProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->linkProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glPixelStorei(GLenum pname, GLint param)
{
EVENT("(GLenum pname = 0x%X, GLint param = %d)", pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (pname)
{
case GL_UNPACK_ALIGNMENT:
if (param != 1 && param != 2 && param != 4 && param != 8)
{
return gl::error(GL_INVALID_VALUE);
}
context->setUnpackAlignment(param);
break;
case GL_PACK_ALIGNMENT:
if (param != 1 && param != 2 && param != 4 && param != 8)
{
return gl::error(GL_INVALID_VALUE);
}
context->setPackAlignment(param);
break;
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
context->setPackReverseRowOrder(param != 0);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glPolygonOffset(GLfloat factor, GLfloat units)
{
EVENT("(GLfloat factor = %f, GLfloat units = %f)", factor, units);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setPolygonOffsetParams(factor, units);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReadnPixelsEXT(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLsizei bufSize,
GLvoid *data)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "
"GLenum format = 0x%X, GLenum type = 0x%X, GLsizei bufSize = 0x%d, GLvoid *data = 0x%0.8p)",
x, y, width, height, format, type, bufSize, data);
try
{
if (width < 0 || height < 0 || bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLenum currentFormat, currentType;
// Failure in getCurrentReadFormatType indicates that no color attachment is currently bound,
// and attempting to read back if that's the case is an error. The error will be registered
// by getCurrentReadFormat.
if (!context->getCurrentReadFormatType(¤tFormat, ¤tType))
return;
if (!(currentFormat == format && currentType == type) && !validReadFormatType(format, type))
{
return gl::error(GL_INVALID_OPERATION);
}
context->readPixels(x, y, width, height, format, type, &bufSize, data);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLvoid* pixels)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "
"GLenum format = 0x%X, GLenum type = 0x%X, GLvoid* pixels = 0x%0.8p)",
x, y, width, height, format, type, pixels);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLenum currentFormat, currentType;
// Failure in getCurrentReadFormatType indicates that no color attachment is currently bound,
// and attempting to read back if that's the case is an error. The error will be registered
// by getCurrentReadFormat.
if (!context->getCurrentReadFormatType(¤tFormat, ¤tType))
return;
if (!(currentFormat == format && currentType == type) && !validReadFormatType(format, type))
{
return gl::error(GL_INVALID_OPERATION);
}
context->readPixels(x, y, width, height, format, type, NULL, pixels);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReleaseShaderCompiler(void)
{
EVENT("()");
try
{
gl::Shader::releaseCompiler();
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glRenderbufferStorageMultisampleANGLE(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLsizei samples = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
target, samples, internalformat, width, height);
try
{
switch (target)
{
case GL_RENDERBUFFER:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!gl::IsColorRenderable(internalformat) && !gl::IsDepthRenderable(internalformat) && !gl::IsStencilRenderable(internalformat))
{
return gl::error(GL_INVALID_ENUM);
}
if (width < 0 || height < 0 || samples < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (width > context->getMaximumRenderbufferDimension() ||
height > context->getMaximumRenderbufferDimension() ||
samples > context->getMaxSupportedSamples())
{
return gl::error(GL_INVALID_VALUE);
}
GLuint handle = context->getRenderbufferHandle();
if (handle == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
context->setRenderbufferStorage(width, height, internalformat, samples);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
glRenderbufferStorageMultisampleANGLE(target, 0, internalformat, width, height);
}
void __stdcall glSampleCoverage(GLclampf value, GLboolean invert)
{
EVENT("(GLclampf value = %f, GLboolean invert = %d)", value, invert);
try
{
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setSampleCoverageParams(gl::clamp01(value), invert == GL_TRUE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glSetFenceNV(GLuint fence, GLenum condition)
{
EVENT("(GLuint fence = %d, GLenum condition = 0x%X)", fence, condition);
try
{
if (condition != GL_ALL_COMPLETED_NV)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->setFence(condition);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glScissor(GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)", x, y, width, height);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setScissorParams(x, y, width, height);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glShaderBinary(GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length)
{
EVENT("(GLsizei n = %d, const GLuint* shaders = 0x%0.8p, GLenum binaryformat = 0x%X, "
"const GLvoid* binary = 0x%0.8p, GLsizei length = %d)",
n, shaders, binaryformat, binary, length);
try
{
// No binary shader formats are supported.
return gl::error(GL_INVALID_ENUM);
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length)
{
EVENT("(GLuint shader = %d, GLsizei count = %d, const GLchar** string = 0x%0.8p, const GLint* length = 0x%0.8p)",
shader, count, string, length);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
shaderObject->setSource(count, string, length);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilFunc(GLenum func, GLint ref, GLuint mask)
{
glStencilFuncSeparate(GL_FRONT_AND_BACK, func, ref, mask);
}
void __stdcall glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
{
EVENT("(GLenum face = 0x%X, GLenum func = 0x%X, GLint ref = %d, GLuint mask = %d)", face, func, ref, mask);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (func)
{
case GL_NEVER:
case GL_ALWAYS:
case GL_LESS:
case GL_LEQUAL:
case GL_EQUAL:
case GL_GEQUAL:
case GL_GREATER:
case GL_NOTEQUAL:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilParams(func, ref, mask);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackParams(func, ref, mask);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilMask(GLuint mask)
{
glStencilMaskSeparate(GL_FRONT_AND_BACK, mask);
}
void __stdcall glStencilMaskSeparate(GLenum face, GLuint mask)
{
EVENT("(GLenum face = 0x%X, GLuint mask = %d)", face, mask);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilWritemask(mask);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackWritemask(mask);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
{
glStencilOpSeparate(GL_FRONT_AND_BACK, fail, zfail, zpass);
}
void __stdcall glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
EVENT("(GLenum face = 0x%X, GLenum fail = 0x%X, GLenum zfail = 0x%X, GLenum zpas = 0x%Xs)",
face, fail, zfail, zpass);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (fail)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (zfail)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (zpass)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilOperations(fail, zfail, zpass);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackOperations(fail, zfail, zpass);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLboolean __stdcall glTestFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION, GL_TRUE);
}
return fenceObject->testFence();
}
}
catch(std::bad_alloc&)
{
gl::error(GL_OUT_OF_MEMORY);
}
return GL_TRUE;
}
void __stdcall glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height,
GLint border, GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint internalformat = %d, GLsizei width = %d, GLsizei height = %d, "
"GLint border = %d, GLenum format = 0x%X, GLenum type = 0x%X, const GLvoid* pixels = 0x%0.8p)",
target, level, internalformat, width, height, border, format, type, pixels);
try
{
if (!validImageSize(level, width, height))
{
return gl::error(GL_INVALID_VALUE);
}
if (internalformat != GLint(format))
{
return gl::error(GL_INVALID_OPERATION);
}
// validate <type> by itself (used as secondary key below)
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_24_8_OES:
case GL_HALF_FLOAT_OES:
case GL_FLOAT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
// validate <format> + <type> combinations
// - invalid <format> -> sets INVALID_ENUM
// - invalid <format>+<type> combination -> sets INVALID_OPERATION
switch (format)
{
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: // error cases for compressed textures are handled below
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
case GL_DEPTH_COMPONENT:
switch (type)
{
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_DEPTH_STENCIL_OES:
switch (type)
{
case GL_UNSIGNED_INT_24_8_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (border != 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (format) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_VALUE);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// OES_depth_texture supports loading depth data and multiple levels,
// but ANGLE_depth_texture does not
if (pixels != NULL || level != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
break;
}
if (type == GL_FLOAT)
{
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (type == GL_HALF_FLOAT_OES)
{
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->setImage(level, width, height, format, type, context->getUnpackAlignment(), pixels);
}
else
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
texture->setImagePosX(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
texture->setImageNegX(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
texture->setImagePosY(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
texture->setImageNegY(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
texture->setImagePosZ(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
texture->setImageNegZ(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
default: UNREACHABLE();
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameterf(GLenum target, GLenum pname, GLfloat param)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %f)", target, pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_WRAP_S:
if (!texture->setWrapS((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_WRAP_T:
if (!texture->setWrapT((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MIN_FILTER:
if (!texture->setMinFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAG_FILTER:
if (!texture->setMagFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_USAGE_ANGLE:
if (!texture->setUsage((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
if (!texture->setMaxAnisotropy((float)param, context->getTextureMaxAnisotropy()))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameterfv(GLenum target, GLenum pname, const GLfloat* params)
{
glTexParameterf(target, pname, (GLfloat)*params);
}
void __stdcall glTexParameteri(GLenum target, GLenum pname, GLint param)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %d)", target, pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_WRAP_S:
if (!texture->setWrapS((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_WRAP_T:
if (!texture->setWrapT((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MIN_FILTER:
if (!texture->setMinFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAG_FILTER:
if (!texture->setMagFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_USAGE_ANGLE:
if (!texture->setUsage((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
if (!texture->setMaxAnisotropy((float)param, context->getTextureMaxAnisotropy()))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameteriv(GLenum target, GLenum pname, const GLint* params)
{
glTexParameteri(target, pname, *params);
}
void __stdcall glTexStorage2DEXT(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLsizei levels = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
target, levels, internalformat, width, height);
try
{
if (target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP)
{
return gl::error(GL_INVALID_ENUM);
}
if (width < 1 || height < 1 || levels < 1)
{
return gl::error(GL_INVALID_VALUE);
}
if (target == GL_TEXTURE_CUBE_MAP && width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (levels != 1 && levels != gl::log2(std::max(width, height)) + 1)
{
return gl::error(GL_INVALID_OPERATION);
}
GLenum format = gl::ExtractFormat(internalformat);
GLenum type = gl::ExtractType(internalformat);
if (format == GL_NONE || type == GL_NONE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_TEXTURE_2D:
if (width > context->getMaximumTextureDimension() ||
height > context->getMaximumTextureDimension())
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP:
if (width > context->getMaximumCubeTextureDimension() ||
height > context->getMaximumCubeTextureDimension())
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (levels != 1 && !context->supportsNonPower2Texture())
{
if (!gl::isPow2(width) || !gl::isPow2(height))
{
return gl::error(GL_INVALID_OPERATION);
}
}
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH24_STENCIL8_OES:
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_ENUM);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// ANGLE_depth_texture only supports 1-level textures
if (levels != 1)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
break;
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture || texture->id() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->storage(levels, internalformat, width, height);
}
else if (target == GL_TEXTURE_CUBE_MAP)
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture || texture->id() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->storage(levels, internalformat, width);
}
else UNREACHABLE();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, GLenum type = 0x%X, "
"const GLvoid* pixels = 0x%0.8p)",
target, level, xoffset, yoffset, width, height, format, type, pixels);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (level < 0 || xoffset < 0 || yoffset < 0 || width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (std::numeric_limits<GLsizei>::max() - xoffset < width || std::numeric_limits<GLsizei>::max() - yoffset < height)
{
return gl::error(GL_INVALID_VALUE);
}
if (!checkTextureFormatType(format, type))
{
return; // error is set by helper function
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
if (format == GL_FLOAT)
{
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (format == GL_HALF_FLOAT_OES)
{
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (gl::IsDepthTexture(format))
{
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_ENUM);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// OES_depth_texture supports loading depth data, but ANGLE_depth_texture does not
return gl::error(GL_INVALID_OPERATION);
}
if (width == 0 || height == 0 || pixels == NULL)
{
return;
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (validateSubImageParams2D(false, width, height, xoffset, yoffset, level, format, type, texture))
{
texture->subImage(level, xoffset, yoffset, width, height, format, type, context->getUnpackAlignment(), pixels);
}
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (validateSubImageParamsCube(false, width, height, xoffset, yoffset, target, level, format, type, texture))
{
texture->subImage(target, level, xoffset, yoffset, width, height, format, type, context->getUnpackAlignment(), pixels);
}
}
else
{
UNREACHABLE();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform1f(GLint location, GLfloat x)
{
glUniform1fv(location, 1, &x);
}
void __stdcall glUniform1fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform1fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform1i(GLint location, GLint x)
{
glUniform1iv(location, 1, &x);
}
void __stdcall glUniform1iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform1iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform2f(GLint location, GLfloat x, GLfloat y)
{
GLfloat xy[2] = {x, y};
glUniform2fv(location, 1, (GLfloat*)&xy);
}
void __stdcall glUniform2fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform2fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform2i(GLint location, GLint x, GLint y)
{
GLint xy[4] = {x, y};
glUniform2iv(location, 1, (GLint*)&xy);
}
void __stdcall glUniform2iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform2iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z)
{
GLfloat xyz[3] = {x, y, z};
glUniform3fv(location, 1, (GLfloat*)&xyz);
}
void __stdcall glUniform3fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform3fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform3i(GLint location, GLint x, GLint y, GLint z)
{
GLint xyz[3] = {x, y, z};
glUniform3iv(location, 1, (GLint*)&xyz);
}
void __stdcall glUniform3iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform3iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
GLfloat xyzw[4] = {x, y, z, w};
glUniform4fv(location, 1, (GLfloat*)&xyzw);
}
void __stdcall glUniform4fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform4fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform4i(GLint location, GLint x, GLint y, GLint z, GLint w)
{
GLint xyzw[4] = {x, y, z, w};
glUniform4iv(location, 1, (GLint*)&xyzw);
}
void __stdcall glUniform4iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform4iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix2fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix3fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix4fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUseProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject && program != 0)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (program != 0 && !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
context->useProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glValidateProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
programObject->validate();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib1f(GLuint index, GLfloat x)
{
EVENT("(GLuint index = %d, GLfloat x = %f)", index, x);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, 0, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib1fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], 0, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f)", index, x, y);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib2fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], values[1], 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f)", index, x, y, z);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, z, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib3fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], values[1], values[2], 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f, GLfloat w = %f)", index, x, y, z, w);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, z, w };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib4fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttrib(index, values);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttribDivisorANGLE(GLuint index, GLuint divisor)
{
EVENT("(GLuint index = %d, GLuint divisor = %d)", index, divisor);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttribDivisor(index, divisor);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr)
{
EVENT("(GLuint index = %d, GLint size = %d, GLenum type = 0x%X, "
"GLboolean normalized = %d, GLsizei stride = %d, const GLvoid* ptr = 0x%0.8p)",
index, size, type, normalized, stride, ptr);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
if (size < 1 || size > 4)
{
return gl::error(GL_INVALID_VALUE);
}
switch (type)
{
case GL_BYTE:
case GL_UNSIGNED_BYTE:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_FIXED:
case GL_FLOAT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (stride < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttribState(index, context->getArrayBuffer(), size, type, (normalized == GL_TRUE), stride, ptr);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)", x, y, width, height);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setViewportParams(x, y, width, height);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlitFramebufferANGLE(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter)
{
EVENT("(GLint srcX0 = %d, GLint srcY0 = %d, GLint srcX1 = %d, GLint srcY1 = %d, "
"GLint dstX0 = %d, GLint dstY0 = %d, GLint dstX1 = %d, GLint dstY1 = %d, "
"GLbitfield mask = 0x%X, GLenum filter = 0x%X)",
srcX0, srcY0, srcX1, srcX1, dstX0, dstY0, dstX1, dstY1, mask, filter);
try
{
switch (filter)
{
case GL_NEAREST:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if ((mask & ~(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)) != 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0)
{
ERR("Scaling and flipping in BlitFramebufferANGLE not supported by this implementation");
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (context->getReadFramebufferHandle() == context->getDrawFramebufferHandle())
{
ERR("Blits with the same source and destination framebuffer are not supported by this implementation.");
return gl::error(GL_INVALID_OPERATION);
}
context->blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexImage3DOES(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth,
GLint border, GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "
"GLsizei width = %d, GLsizei height = %d, GLsizei depth = %d, GLint border = %d, "
"GLenum format = 0x%X, GLenum type = 0x%x, const GLvoid* pixels = 0x%0.8p)",
target, level, internalformat, width, height, depth, border, format, type, pixels);
try
{
UNIMPLEMENTED(); // FIXME
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length,
GLenum *binaryFormat, void *binary)
{
EVENT("(GLenum program = 0x%X, bufSize = %d, length = 0x%0.8p, binaryFormat = 0x%0.8p, binary = 0x%0.8p)",
program, bufSize, length, binaryFormat, binary);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->save(binary, bufSize, length))
{
return gl::error(GL_INVALID_OPERATION);
}
*binaryFormat = GL_PROGRAM_BINARY_ANGLE;
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glProgramBinaryOES(GLuint program, GLenum binaryFormat,
const void *binary, GLint length)
{
EVENT("(GLenum program = 0x%X, binaryFormat = 0x%x, binary = 0x%0.8p, length = %d)",
program, binaryFormat, binary, length);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (binaryFormat != GL_PROGRAM_BINARY_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_OPERATION);
}
context->setProgramBinary(program, binary, length);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawBuffersEXT(GLsizei n, const GLenum *bufs)
{
EVENT("(GLenum n = %d, bufs = 0x%0.8p)", n, bufs);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (n < 0 || (unsigned int)n > context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
if (context->getDrawFramebufferHandle() == 0)
{
if (n != 1)
{
return gl::error(GL_INVALID_OPERATION);
}
if (bufs[0] != GL_NONE && bufs[0] != GL_BACK)
{
return gl::error(GL_INVALID_OPERATION);
}
}
else
{
for (int colorAttachment = 0; colorAttachment < n; colorAttachment++)
{
const GLenum attachment = GL_COLOR_ATTACHMENT0_EXT + colorAttachment;
if (bufs[colorAttachment] != GL_NONE && bufs[colorAttachment] != attachment)
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
gl::Framebuffer *framebuffer = context->getDrawFramebuffer();
for (int colorAttachment = 0; colorAttachment < n; colorAttachment++)
{
framebuffer->setDrawBufferState(colorAttachment, bufs[colorAttachment]);
}
for (int colorAttachment = n; colorAttachment < (int)context->getMaximumRenderTargets(); colorAttachment++)
{
framebuffer->setDrawBufferState(colorAttachment, GL_NONE);
}
}
}
catch (std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
__eglMustCastToProperFunctionPointerType __stdcall glGetProcAddress(const char *procname)
{
struct Extension
{
const char *name;
__eglMustCastToProperFunctionPointerType address;
};
static const Extension glExtensions[] =
{
{"glTexImage3DOES", (__eglMustCastToProperFunctionPointerType)glTexImage3DOES},
{"glBlitFramebufferANGLE", (__eglMustCastToProperFunctionPointerType)glBlitFramebufferANGLE},
{"glRenderbufferStorageMultisampleANGLE", (__eglMustCastToProperFunctionPointerType)glRenderbufferStorageMultisampleANGLE},
{"glDeleteFencesNV", (__eglMustCastToProperFunctionPointerType)glDeleteFencesNV},
{"glGenFencesNV", (__eglMustCastToProperFunctionPointerType)glGenFencesNV},
{"glIsFenceNV", (__eglMustCastToProperFunctionPointerType)glIsFenceNV},
{"glTestFenceNV", (__eglMustCastToProperFunctionPointerType)glTestFenceNV},
{"glGetFenceivNV", (__eglMustCastToProperFunctionPointerType)glGetFenceivNV},
{"glFinishFenceNV", (__eglMustCastToProperFunctionPointerType)glFinishFenceNV},
{"glSetFenceNV", (__eglMustCastToProperFunctionPointerType)glSetFenceNV},
{"glGetTranslatedShaderSourceANGLE", (__eglMustCastToProperFunctionPointerType)glGetTranslatedShaderSourceANGLE},
{"glTexStorage2DEXT", (__eglMustCastToProperFunctionPointerType)glTexStorage2DEXT},
{"glGetGraphicsResetStatusEXT", (__eglMustCastToProperFunctionPointerType)glGetGraphicsResetStatusEXT},
{"glReadnPixelsEXT", (__eglMustCastToProperFunctionPointerType)glReadnPixelsEXT},
{"glGetnUniformfvEXT", (__eglMustCastToProperFunctionPointerType)glGetnUniformfvEXT},
{"glGetnUniformivEXT", (__eglMustCastToProperFunctionPointerType)glGetnUniformivEXT},
{"glGenQueriesEXT", (__eglMustCastToProperFunctionPointerType)glGenQueriesEXT},
{"glDeleteQueriesEXT", (__eglMustCastToProperFunctionPointerType)glDeleteQueriesEXT},
{"glIsQueryEXT", (__eglMustCastToProperFunctionPointerType)glIsQueryEXT},
{"glBeginQueryEXT", (__eglMustCastToProperFunctionPointerType)glBeginQueryEXT},
{"glEndQueryEXT", (__eglMustCastToProperFunctionPointerType)glEndQueryEXT},
{"glGetQueryivEXT", (__eglMustCastToProperFunctionPointerType)glGetQueryivEXT},
{"glGetQueryObjectuivEXT", (__eglMustCastToProperFunctionPointerType)glGetQueryObjectuivEXT},
{"glDrawBuffersEXT", (__eglMustCastToProperFunctionPointerType)glDrawBuffersEXT},
{"glVertexAttribDivisorANGLE", (__eglMustCastToProperFunctionPointerType)glVertexAttribDivisorANGLE},
{"glDrawArraysInstancedANGLE", (__eglMustCastToProperFunctionPointerType)glDrawArraysInstancedANGLE},
{"glDrawElementsInstancedANGLE", (__eglMustCastToProperFunctionPointerType)glDrawElementsInstancedANGLE},
{"glGetProgramBinaryOES", (__eglMustCastToProperFunctionPointerType)glGetProgramBinaryOES},
{"glProgramBinaryOES", (__eglMustCastToProperFunctionPointerType)glProgramBinaryOES}, };
for (unsigned int ext = 0; ext < ArraySize(glExtensions); ext++)
{
if (strcmp(procname, glExtensions[ext].name) == 0)
{
return (__eglMustCastToProperFunctionPointerType)glExtensions[ext].address;
}
}
return NULL;
}
// Non-public functions used by EGL
bool __stdcall glBindTexImage(egl::Surface *surface)
{
EVENT("(egl::Surface* surface = 0x%0.8p)",
surface);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture2D *textureObject = context->getTexture2D();
if (textureObject->isImmutable())
{
return false;
}
if (textureObject)
{
textureObject->bindTexImage(surface);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, false);
}
return true;
}
}
| C++ |
#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.
//
// This file is automatically generated.
namespace gl
{
const static unsigned g_mantissa[2048] = {
0x00000000,
0x33800000,
0x34000000,
0x34400000,
0x34800000,
0x34a00000,
0x34c00000,
0x34e00000,
0x35000000,
0x35100000,
0x35200000,
0x35300000,
0x35400000,
0x35500000,
0x35600000,
0x35700000,
0x35800000,
0x35880000,
0x35900000,
0x35980000,
0x35a00000,
0x35a80000,
0x35b00000,
0x35b80000,
0x35c00000,
0x35c80000,
0x35d00000,
0x35d80000,
0x35e00000,
0x35e80000,
0x35f00000,
0x35f80000,
0x36000000,
0x36040000,
0x36080000,
0x360c0000,
0x36100000,
0x36140000,
0x36180000,
0x361c0000,
0x36200000,
0x36240000,
0x36280000,
0x362c0000,
0x36300000,
0x36340000,
0x36380000,
0x363c0000,
0x36400000,
0x36440000,
0x36480000,
0x364c0000,
0x36500000,
0x36540000,
0x36580000,
0x365c0000,
0x36600000,
0x36640000,
0x36680000,
0x366c0000,
0x36700000,
0x36740000,
0x36780000,
0x367c0000,
0x36800000,
0x36820000,
0x36840000,
0x36860000,
0x36880000,
0x368a0000,
0x368c0000,
0x368e0000,
0x36900000,
0x36920000,
0x36940000,
0x36960000,
0x36980000,
0x369a0000,
0x369c0000,
0x369e0000,
0x36a00000,
0x36a20000,
0x36a40000,
0x36a60000,
0x36a80000,
0x36aa0000,
0x36ac0000,
0x36ae0000,
0x36b00000,
0x36b20000,
0x36b40000,
0x36b60000,
0x36b80000,
0x36ba0000,
0x36bc0000,
0x36be0000,
0x36c00000,
0x36c20000,
0x36c40000,
0x36c60000,
0x36c80000,
0x36ca0000,
0x36cc0000,
0x36ce0000,
0x36d00000,
0x36d20000,
0x36d40000,
0x36d60000,
0x36d80000,
0x36da0000,
0x36dc0000,
0x36de0000,
0x36e00000,
0x36e20000,
0x36e40000,
0x36e60000,
0x36e80000,
0x36ea0000,
0x36ec0000,
0x36ee0000,
0x36f00000,
0x36f20000,
0x36f40000,
0x36f60000,
0x36f80000,
0x36fa0000,
0x36fc0000,
0x36fe0000,
0x37000000,
0x37010000,
0x37020000,
0x37030000,
0x37040000,
0x37050000,
0x37060000,
0x37070000,
0x37080000,
0x37090000,
0x370a0000,
0x370b0000,
0x370c0000,
0x370d0000,
0x370e0000,
0x370f0000,
0x37100000,
0x37110000,
0x37120000,
0x37130000,
0x37140000,
0x37150000,
0x37160000,
0x37170000,
0x37180000,
0x37190000,
0x371a0000,
0x371b0000,
0x371c0000,
0x371d0000,
0x371e0000,
0x371f0000,
0x37200000,
0x37210000,
0x37220000,
0x37230000,
0x37240000,
0x37250000,
0x37260000,
0x37270000,
0x37280000,
0x37290000,
0x372a0000,
0x372b0000,
0x372c0000,
0x372d0000,
0x372e0000,
0x372f0000,
0x37300000,
0x37310000,
0x37320000,
0x37330000,
0x37340000,
0x37350000,
0x37360000,
0x37370000,
0x37380000,
0x37390000,
0x373a0000,
0x373b0000,
0x373c0000,
0x373d0000,
0x373e0000,
0x373f0000,
0x37400000,
0x37410000,
0x37420000,
0x37430000,
0x37440000,
0x37450000,
0x37460000,
0x37470000,
0x37480000,
0x37490000,
0x374a0000,
0x374b0000,
0x374c0000,
0x374d0000,
0x374e0000,
0x374f0000,
0x37500000,
0x37510000,
0x37520000,
0x37530000,
0x37540000,
0x37550000,
0x37560000,
0x37570000,
0x37580000,
0x37590000,
0x375a0000,
0x375b0000,
0x375c0000,
0x375d0000,
0x375e0000,
0x375f0000,
0x37600000,
0x37610000,
0x37620000,
0x37630000,
0x37640000,
0x37650000,
0x37660000,
0x37670000,
0x37680000,
0x37690000,
0x376a0000,
0x376b0000,
0x376c0000,
0x376d0000,
0x376e0000,
0x376f0000,
0x37700000,
0x37710000,
0x37720000,
0x37730000,
0x37740000,
0x37750000,
0x37760000,
0x37770000,
0x37780000,
0x37790000,
0x377a0000,
0x377b0000,
0x377c0000,
0x377d0000,
0x377e0000,
0x377f0000,
0x37800000,
0x37808000,
0x37810000,
0x37818000,
0x37820000,
0x37828000,
0x37830000,
0x37838000,
0x37840000,
0x37848000,
0x37850000,
0x37858000,
0x37860000,
0x37868000,
0x37870000,
0x37878000,
0x37880000,
0x37888000,
0x37890000,
0x37898000,
0x378a0000,
0x378a8000,
0x378b0000,
0x378b8000,
0x378c0000,
0x378c8000,
0x378d0000,
0x378d8000,
0x378e0000,
0x378e8000,
0x378f0000,
0x378f8000,
0x37900000,
0x37908000,
0x37910000,
0x37918000,
0x37920000,
0x37928000,
0x37930000,
0x37938000,
0x37940000,
0x37948000,
0x37950000,
0x37958000,
0x37960000,
0x37968000,
0x37970000,
0x37978000,
0x37980000,
0x37988000,
0x37990000,
0x37998000,
0x379a0000,
0x379a8000,
0x379b0000,
0x379b8000,
0x379c0000,
0x379c8000,
0x379d0000,
0x379d8000,
0x379e0000,
0x379e8000,
0x379f0000,
0x379f8000,
0x37a00000,
0x37a08000,
0x37a10000,
0x37a18000,
0x37a20000,
0x37a28000,
0x37a30000,
0x37a38000,
0x37a40000,
0x37a48000,
0x37a50000,
0x37a58000,
0x37a60000,
0x37a68000,
0x37a70000,
0x37a78000,
0x37a80000,
0x37a88000,
0x37a90000,
0x37a98000,
0x37aa0000,
0x37aa8000,
0x37ab0000,
0x37ab8000,
0x37ac0000,
0x37ac8000,
0x37ad0000,
0x37ad8000,
0x37ae0000,
0x37ae8000,
0x37af0000,
0x37af8000,
0x37b00000,
0x37b08000,
0x37b10000,
0x37b18000,
0x37b20000,
0x37b28000,
0x37b30000,
0x37b38000,
0x37b40000,
0x37b48000,
0x37b50000,
0x37b58000,
0x37b60000,
0x37b68000,
0x37b70000,
0x37b78000,
0x37b80000,
0x37b88000,
0x37b90000,
0x37b98000,
0x37ba0000,
0x37ba8000,
0x37bb0000,
0x37bb8000,
0x37bc0000,
0x37bc8000,
0x37bd0000,
0x37bd8000,
0x37be0000,
0x37be8000,
0x37bf0000,
0x37bf8000,
0x37c00000,
0x37c08000,
0x37c10000,
0x37c18000,
0x37c20000,
0x37c28000,
0x37c30000,
0x37c38000,
0x37c40000,
0x37c48000,
0x37c50000,
0x37c58000,
0x37c60000,
0x37c68000,
0x37c70000,
0x37c78000,
0x37c80000,
0x37c88000,
0x37c90000,
0x37c98000,
0x37ca0000,
0x37ca8000,
0x37cb0000,
0x37cb8000,
0x37cc0000,
0x37cc8000,
0x37cd0000,
0x37cd8000,
0x37ce0000,
0x37ce8000,
0x37cf0000,
0x37cf8000,
0x37d00000,
0x37d08000,
0x37d10000,
0x37d18000,
0x37d20000,
0x37d28000,
0x37d30000,
0x37d38000,
0x37d40000,
0x37d48000,
0x37d50000,
0x37d58000,
0x37d60000,
0x37d68000,
0x37d70000,
0x37d78000,
0x37d80000,
0x37d88000,
0x37d90000,
0x37d98000,
0x37da0000,
0x37da8000,
0x37db0000,
0x37db8000,
0x37dc0000,
0x37dc8000,
0x37dd0000,
0x37dd8000,
0x37de0000,
0x37de8000,
0x37df0000,
0x37df8000,
0x37e00000,
0x37e08000,
0x37e10000,
0x37e18000,
0x37e20000,
0x37e28000,
0x37e30000,
0x37e38000,
0x37e40000,
0x37e48000,
0x37e50000,
0x37e58000,
0x37e60000,
0x37e68000,
0x37e70000,
0x37e78000,
0x37e80000,
0x37e88000,
0x37e90000,
0x37e98000,
0x37ea0000,
0x37ea8000,
0x37eb0000,
0x37eb8000,
0x37ec0000,
0x37ec8000,
0x37ed0000,
0x37ed8000,
0x37ee0000,
0x37ee8000,
0x37ef0000,
0x37ef8000,
0x37f00000,
0x37f08000,
0x37f10000,
0x37f18000,
0x37f20000,
0x37f28000,
0x37f30000,
0x37f38000,
0x37f40000,
0x37f48000,
0x37f50000,
0x37f58000,
0x37f60000,
0x37f68000,
0x37f70000,
0x37f78000,
0x37f80000,
0x37f88000,
0x37f90000,
0x37f98000,
0x37fa0000,
0x37fa8000,
0x37fb0000,
0x37fb8000,
0x37fc0000,
0x37fc8000,
0x37fd0000,
0x37fd8000,
0x37fe0000,
0x37fe8000,
0x37ff0000,
0x37ff8000,
0x38000000,
0x38004000,
0x38008000,
0x3800c000,
0x38010000,
0x38014000,
0x38018000,
0x3801c000,
0x38020000,
0x38024000,
0x38028000,
0x3802c000,
0x38030000,
0x38034000,
0x38038000,
0x3803c000,
0x38040000,
0x38044000,
0x38048000,
0x3804c000,
0x38050000,
0x38054000,
0x38058000,
0x3805c000,
0x38060000,
0x38064000,
0x38068000,
0x3806c000,
0x38070000,
0x38074000,
0x38078000,
0x3807c000,
0x38080000,
0x38084000,
0x38088000,
0x3808c000,
0x38090000,
0x38094000,
0x38098000,
0x3809c000,
0x380a0000,
0x380a4000,
0x380a8000,
0x380ac000,
0x380b0000,
0x380b4000,
0x380b8000,
0x380bc000,
0x380c0000,
0x380c4000,
0x380c8000,
0x380cc000,
0x380d0000,
0x380d4000,
0x380d8000,
0x380dc000,
0x380e0000,
0x380e4000,
0x380e8000,
0x380ec000,
0x380f0000,
0x380f4000,
0x380f8000,
0x380fc000,
0x38100000,
0x38104000,
0x38108000,
0x3810c000,
0x38110000,
0x38114000,
0x38118000,
0x3811c000,
0x38120000,
0x38124000,
0x38128000,
0x3812c000,
0x38130000,
0x38134000,
0x38138000,
0x3813c000,
0x38140000,
0x38144000,
0x38148000,
0x3814c000,
0x38150000,
0x38154000,
0x38158000,
0x3815c000,
0x38160000,
0x38164000,
0x38168000,
0x3816c000,
0x38170000,
0x38174000,
0x38178000,
0x3817c000,
0x38180000,
0x38184000,
0x38188000,
0x3818c000,
0x38190000,
0x38194000,
0x38198000,
0x3819c000,
0x381a0000,
0x381a4000,
0x381a8000,
0x381ac000,
0x381b0000,
0x381b4000,
0x381b8000,
0x381bc000,
0x381c0000,
0x381c4000,
0x381c8000,
0x381cc000,
0x381d0000,
0x381d4000,
0x381d8000,
0x381dc000,
0x381e0000,
0x381e4000,
0x381e8000,
0x381ec000,
0x381f0000,
0x381f4000,
0x381f8000,
0x381fc000,
0x38200000,
0x38204000,
0x38208000,
0x3820c000,
0x38210000,
0x38214000,
0x38218000,
0x3821c000,
0x38220000,
0x38224000,
0x38228000,
0x3822c000,
0x38230000,
0x38234000,
0x38238000,
0x3823c000,
0x38240000,
0x38244000,
0x38248000,
0x3824c000,
0x38250000,
0x38254000,
0x38258000,
0x3825c000,
0x38260000,
0x38264000,
0x38268000,
0x3826c000,
0x38270000,
0x38274000,
0x38278000,
0x3827c000,
0x38280000,
0x38284000,
0x38288000,
0x3828c000,
0x38290000,
0x38294000,
0x38298000,
0x3829c000,
0x382a0000,
0x382a4000,
0x382a8000,
0x382ac000,
0x382b0000,
0x382b4000,
0x382b8000,
0x382bc000,
0x382c0000,
0x382c4000,
0x382c8000,
0x382cc000,
0x382d0000,
0x382d4000,
0x382d8000,
0x382dc000,
0x382e0000,
0x382e4000,
0x382e8000,
0x382ec000,
0x382f0000,
0x382f4000,
0x382f8000,
0x382fc000,
0x38300000,
0x38304000,
0x38308000,
0x3830c000,
0x38310000,
0x38314000,
0x38318000,
0x3831c000,
0x38320000,
0x38324000,
0x38328000,
0x3832c000,
0x38330000,
0x38334000,
0x38338000,
0x3833c000,
0x38340000,
0x38344000,
0x38348000,
0x3834c000,
0x38350000,
0x38354000,
0x38358000,
0x3835c000,
0x38360000,
0x38364000,
0x38368000,
0x3836c000,
0x38370000,
0x38374000,
0x38378000,
0x3837c000,
0x38380000,
0x38384000,
0x38388000,
0x3838c000,
0x38390000,
0x38394000,
0x38398000,
0x3839c000,
0x383a0000,
0x383a4000,
0x383a8000,
0x383ac000,
0x383b0000,
0x383b4000,
0x383b8000,
0x383bc000,
0x383c0000,
0x383c4000,
0x383c8000,
0x383cc000,
0x383d0000,
0x383d4000,
0x383d8000,
0x383dc000,
0x383e0000,
0x383e4000,
0x383e8000,
0x383ec000,
0x383f0000,
0x383f4000,
0x383f8000,
0x383fc000,
0x38400000,
0x38404000,
0x38408000,
0x3840c000,
0x38410000,
0x38414000,
0x38418000,
0x3841c000,
0x38420000,
0x38424000,
0x38428000,
0x3842c000,
0x38430000,
0x38434000,
0x38438000,
0x3843c000,
0x38440000,
0x38444000,
0x38448000,
0x3844c000,
0x38450000,
0x38454000,
0x38458000,
0x3845c000,
0x38460000,
0x38464000,
0x38468000,
0x3846c000,
0x38470000,
0x38474000,
0x38478000,
0x3847c000,
0x38480000,
0x38484000,
0x38488000,
0x3848c000,
0x38490000,
0x38494000,
0x38498000,
0x3849c000,
0x384a0000,
0x384a4000,
0x384a8000,
0x384ac000,
0x384b0000,
0x384b4000,
0x384b8000,
0x384bc000,
0x384c0000,
0x384c4000,
0x384c8000,
0x384cc000,
0x384d0000,
0x384d4000,
0x384d8000,
0x384dc000,
0x384e0000,
0x384e4000,
0x384e8000,
0x384ec000,
0x384f0000,
0x384f4000,
0x384f8000,
0x384fc000,
0x38500000,
0x38504000,
0x38508000,
0x3850c000,
0x38510000,
0x38514000,
0x38518000,
0x3851c000,
0x38520000,
0x38524000,
0x38528000,
0x3852c000,
0x38530000,
0x38534000,
0x38538000,
0x3853c000,
0x38540000,
0x38544000,
0x38548000,
0x3854c000,
0x38550000,
0x38554000,
0x38558000,
0x3855c000,
0x38560000,
0x38564000,
0x38568000,
0x3856c000,
0x38570000,
0x38574000,
0x38578000,
0x3857c000,
0x38580000,
0x38584000,
0x38588000,
0x3858c000,
0x38590000,
0x38594000,
0x38598000,
0x3859c000,
0x385a0000,
0x385a4000,
0x385a8000,
0x385ac000,
0x385b0000,
0x385b4000,
0x385b8000,
0x385bc000,
0x385c0000,
0x385c4000,
0x385c8000,
0x385cc000,
0x385d0000,
0x385d4000,
0x385d8000,
0x385dc000,
0x385e0000,
0x385e4000,
0x385e8000,
0x385ec000,
0x385f0000,
0x385f4000,
0x385f8000,
0x385fc000,
0x38600000,
0x38604000,
0x38608000,
0x3860c000,
0x38610000,
0x38614000,
0x38618000,
0x3861c000,
0x38620000,
0x38624000,
0x38628000,
0x3862c000,
0x38630000,
0x38634000,
0x38638000,
0x3863c000,
0x38640000,
0x38644000,
0x38648000,
0x3864c000,
0x38650000,
0x38654000,
0x38658000,
0x3865c000,
0x38660000,
0x38664000,
0x38668000,
0x3866c000,
0x38670000,
0x38674000,
0x38678000,
0x3867c000,
0x38680000,
0x38684000,
0x38688000,
0x3868c000,
0x38690000,
0x38694000,
0x38698000,
0x3869c000,
0x386a0000,
0x386a4000,
0x386a8000,
0x386ac000,
0x386b0000,
0x386b4000,
0x386b8000,
0x386bc000,
0x386c0000,
0x386c4000,
0x386c8000,
0x386cc000,
0x386d0000,
0x386d4000,
0x386d8000,
0x386dc000,
0x386e0000,
0x386e4000,
0x386e8000,
0x386ec000,
0x386f0000,
0x386f4000,
0x386f8000,
0x386fc000,
0x38700000,
0x38704000,
0x38708000,
0x3870c000,
0x38710000,
0x38714000,
0x38718000,
0x3871c000,
0x38720000,
0x38724000,
0x38728000,
0x3872c000,
0x38730000,
0x38734000,
0x38738000,
0x3873c000,
0x38740000,
0x38744000,
0x38748000,
0x3874c000,
0x38750000,
0x38754000,
0x38758000,
0x3875c000,
0x38760000,
0x38764000,
0x38768000,
0x3876c000,
0x38770000,
0x38774000,
0x38778000,
0x3877c000,
0x38780000,
0x38784000,
0x38788000,
0x3878c000,
0x38790000,
0x38794000,
0x38798000,
0x3879c000,
0x387a0000,
0x387a4000,
0x387a8000,
0x387ac000,
0x387b0000,
0x387b4000,
0x387b8000,
0x387bc000,
0x387c0000,
0x387c4000,
0x387c8000,
0x387cc000,
0x387d0000,
0x387d4000,
0x387d8000,
0x387dc000,
0x387e0000,
0x387e4000,
0x387e8000,
0x387ec000,
0x387f0000,
0x387f4000,
0x387f8000,
0x387fc000,
0x38000000,
0x38002000,
0x38004000,
0x38006000,
0x38008000,
0x3800a000,
0x3800c000,
0x3800e000,
0x38010000,
0x38012000,
0x38014000,
0x38016000,
0x38018000,
0x3801a000,
0x3801c000,
0x3801e000,
0x38020000,
0x38022000,
0x38024000,
0x38026000,
0x38028000,
0x3802a000,
0x3802c000,
0x3802e000,
0x38030000,
0x38032000,
0x38034000,
0x38036000,
0x38038000,
0x3803a000,
0x3803c000,
0x3803e000,
0x38040000,
0x38042000,
0x38044000,
0x38046000,
0x38048000,
0x3804a000,
0x3804c000,
0x3804e000,
0x38050000,
0x38052000,
0x38054000,
0x38056000,
0x38058000,
0x3805a000,
0x3805c000,
0x3805e000,
0x38060000,
0x38062000,
0x38064000,
0x38066000,
0x38068000,
0x3806a000,
0x3806c000,
0x3806e000,
0x38070000,
0x38072000,
0x38074000,
0x38076000,
0x38078000,
0x3807a000,
0x3807c000,
0x3807e000,
0x38080000,
0x38082000,
0x38084000,
0x38086000,
0x38088000,
0x3808a000,
0x3808c000,
0x3808e000,
0x38090000,
0x38092000,
0x38094000,
0x38096000,
0x38098000,
0x3809a000,
0x3809c000,
0x3809e000,
0x380a0000,
0x380a2000,
0x380a4000,
0x380a6000,
0x380a8000,
0x380aa000,
0x380ac000,
0x380ae000,
0x380b0000,
0x380b2000,
0x380b4000,
0x380b6000,
0x380b8000,
0x380ba000,
0x380bc000,
0x380be000,
0x380c0000,
0x380c2000,
0x380c4000,
0x380c6000,
0x380c8000,
0x380ca000,
0x380cc000,
0x380ce000,
0x380d0000,
0x380d2000,
0x380d4000,
0x380d6000,
0x380d8000,
0x380da000,
0x380dc000,
0x380de000,
0x380e0000,
0x380e2000,
0x380e4000,
0x380e6000,
0x380e8000,
0x380ea000,
0x380ec000,
0x380ee000,
0x380f0000,
0x380f2000,
0x380f4000,
0x380f6000,
0x380f8000,
0x380fa000,
0x380fc000,
0x380fe000,
0x38100000,
0x38102000,
0x38104000,
0x38106000,
0x38108000,
0x3810a000,
0x3810c000,
0x3810e000,
0x38110000,
0x38112000,
0x38114000,
0x38116000,
0x38118000,
0x3811a000,
0x3811c000,
0x3811e000,
0x38120000,
0x38122000,
0x38124000,
0x38126000,
0x38128000,
0x3812a000,
0x3812c000,
0x3812e000,
0x38130000,
0x38132000,
0x38134000,
0x38136000,
0x38138000,
0x3813a000,
0x3813c000,
0x3813e000,
0x38140000,
0x38142000,
0x38144000,
0x38146000,
0x38148000,
0x3814a000,
0x3814c000,
0x3814e000,
0x38150000,
0x38152000,
0x38154000,
0x38156000,
0x38158000,
0x3815a000,
0x3815c000,
0x3815e000,
0x38160000,
0x38162000,
0x38164000,
0x38166000,
0x38168000,
0x3816a000,
0x3816c000,
0x3816e000,
0x38170000,
0x38172000,
0x38174000,
0x38176000,
0x38178000,
0x3817a000,
0x3817c000,
0x3817e000,
0x38180000,
0x38182000,
0x38184000,
0x38186000,
0x38188000,
0x3818a000,
0x3818c000,
0x3818e000,
0x38190000,
0x38192000,
0x38194000,
0x38196000,
0x38198000,
0x3819a000,
0x3819c000,
0x3819e000,
0x381a0000,
0x381a2000,
0x381a4000,
0x381a6000,
0x381a8000,
0x381aa000,
0x381ac000,
0x381ae000,
0x381b0000,
0x381b2000,
0x381b4000,
0x381b6000,
0x381b8000,
0x381ba000,
0x381bc000,
0x381be000,
0x381c0000,
0x381c2000,
0x381c4000,
0x381c6000,
0x381c8000,
0x381ca000,
0x381cc000,
0x381ce000,
0x381d0000,
0x381d2000,
0x381d4000,
0x381d6000,
0x381d8000,
0x381da000,
0x381dc000,
0x381de000,
0x381e0000,
0x381e2000,
0x381e4000,
0x381e6000,
0x381e8000,
0x381ea000,
0x381ec000,
0x381ee000,
0x381f0000,
0x381f2000,
0x381f4000,
0x381f6000,
0x381f8000,
0x381fa000,
0x381fc000,
0x381fe000,
0x38200000,
0x38202000,
0x38204000,
0x38206000,
0x38208000,
0x3820a000,
0x3820c000,
0x3820e000,
0x38210000,
0x38212000,
0x38214000,
0x38216000,
0x38218000,
0x3821a000,
0x3821c000,
0x3821e000,
0x38220000,
0x38222000,
0x38224000,
0x38226000,
0x38228000,
0x3822a000,
0x3822c000,
0x3822e000,
0x38230000,
0x38232000,
0x38234000,
0x38236000,
0x38238000,
0x3823a000,
0x3823c000,
0x3823e000,
0x38240000,
0x38242000,
0x38244000,
0x38246000,
0x38248000,
0x3824a000,
0x3824c000,
0x3824e000,
0x38250000,
0x38252000,
0x38254000,
0x38256000,
0x38258000,
0x3825a000,
0x3825c000,
0x3825e000,
0x38260000,
0x38262000,
0x38264000,
0x38266000,
0x38268000,
0x3826a000,
0x3826c000,
0x3826e000,
0x38270000,
0x38272000,
0x38274000,
0x38276000,
0x38278000,
0x3827a000,
0x3827c000,
0x3827e000,
0x38280000,
0x38282000,
0x38284000,
0x38286000,
0x38288000,
0x3828a000,
0x3828c000,
0x3828e000,
0x38290000,
0x38292000,
0x38294000,
0x38296000,
0x38298000,
0x3829a000,
0x3829c000,
0x3829e000,
0x382a0000,
0x382a2000,
0x382a4000,
0x382a6000,
0x382a8000,
0x382aa000,
0x382ac000,
0x382ae000,
0x382b0000,
0x382b2000,
0x382b4000,
0x382b6000,
0x382b8000,
0x382ba000,
0x382bc000,
0x382be000,
0x382c0000,
0x382c2000,
0x382c4000,
0x382c6000,
0x382c8000,
0x382ca000,
0x382cc000,
0x382ce000,
0x382d0000,
0x382d2000,
0x382d4000,
0x382d6000,
0x382d8000,
0x382da000,
0x382dc000,
0x382de000,
0x382e0000,
0x382e2000,
0x382e4000,
0x382e6000,
0x382e8000,
0x382ea000,
0x382ec000,
0x382ee000,
0x382f0000,
0x382f2000,
0x382f4000,
0x382f6000,
0x382f8000,
0x382fa000,
0x382fc000,
0x382fe000,
0x38300000,
0x38302000,
0x38304000,
0x38306000,
0x38308000,
0x3830a000,
0x3830c000,
0x3830e000,
0x38310000,
0x38312000,
0x38314000,
0x38316000,
0x38318000,
0x3831a000,
0x3831c000,
0x3831e000,
0x38320000,
0x38322000,
0x38324000,
0x38326000,
0x38328000,
0x3832a000,
0x3832c000,
0x3832e000,
0x38330000,
0x38332000,
0x38334000,
0x38336000,
0x38338000,
0x3833a000,
0x3833c000,
0x3833e000,
0x38340000,
0x38342000,
0x38344000,
0x38346000,
0x38348000,
0x3834a000,
0x3834c000,
0x3834e000,
0x38350000,
0x38352000,
0x38354000,
0x38356000,
0x38358000,
0x3835a000,
0x3835c000,
0x3835e000,
0x38360000,
0x38362000,
0x38364000,
0x38366000,
0x38368000,
0x3836a000,
0x3836c000,
0x3836e000,
0x38370000,
0x38372000,
0x38374000,
0x38376000,
0x38378000,
0x3837a000,
0x3837c000,
0x3837e000,
0x38380000,
0x38382000,
0x38384000,
0x38386000,
0x38388000,
0x3838a000,
0x3838c000,
0x3838e000,
0x38390000,
0x38392000,
0x38394000,
0x38396000,
0x38398000,
0x3839a000,
0x3839c000,
0x3839e000,
0x383a0000,
0x383a2000,
0x383a4000,
0x383a6000,
0x383a8000,
0x383aa000,
0x383ac000,
0x383ae000,
0x383b0000,
0x383b2000,
0x383b4000,
0x383b6000,
0x383b8000,
0x383ba000,
0x383bc000,
0x383be000,
0x383c0000,
0x383c2000,
0x383c4000,
0x383c6000,
0x383c8000,
0x383ca000,
0x383cc000,
0x383ce000,
0x383d0000,
0x383d2000,
0x383d4000,
0x383d6000,
0x383d8000,
0x383da000,
0x383dc000,
0x383de000,
0x383e0000,
0x383e2000,
0x383e4000,
0x383e6000,
0x383e8000,
0x383ea000,
0x383ec000,
0x383ee000,
0x383f0000,
0x383f2000,
0x383f4000,
0x383f6000,
0x383f8000,
0x383fa000,
0x383fc000,
0x383fe000,
0x38400000,
0x38402000,
0x38404000,
0x38406000,
0x38408000,
0x3840a000,
0x3840c000,
0x3840e000,
0x38410000,
0x38412000,
0x38414000,
0x38416000,
0x38418000,
0x3841a000,
0x3841c000,
0x3841e000,
0x38420000,
0x38422000,
0x38424000,
0x38426000,
0x38428000,
0x3842a000,
0x3842c000,
0x3842e000,
0x38430000,
0x38432000,
0x38434000,
0x38436000,
0x38438000,
0x3843a000,
0x3843c000,
0x3843e000,
0x38440000,
0x38442000,
0x38444000,
0x38446000,
0x38448000,
0x3844a000,
0x3844c000,
0x3844e000,
0x38450000,
0x38452000,
0x38454000,
0x38456000,
0x38458000,
0x3845a000,
0x3845c000,
0x3845e000,
0x38460000,
0x38462000,
0x38464000,
0x38466000,
0x38468000,
0x3846a000,
0x3846c000,
0x3846e000,
0x38470000,
0x38472000,
0x38474000,
0x38476000,
0x38478000,
0x3847a000,
0x3847c000,
0x3847e000,
0x38480000,
0x38482000,
0x38484000,
0x38486000,
0x38488000,
0x3848a000,
0x3848c000,
0x3848e000,
0x38490000,
0x38492000,
0x38494000,
0x38496000,
0x38498000,
0x3849a000,
0x3849c000,
0x3849e000,
0x384a0000,
0x384a2000,
0x384a4000,
0x384a6000,
0x384a8000,
0x384aa000,
0x384ac000,
0x384ae000,
0x384b0000,
0x384b2000,
0x384b4000,
0x384b6000,
0x384b8000,
0x384ba000,
0x384bc000,
0x384be000,
0x384c0000,
0x384c2000,
0x384c4000,
0x384c6000,
0x384c8000,
0x384ca000,
0x384cc000,
0x384ce000,
0x384d0000,
0x384d2000,
0x384d4000,
0x384d6000,
0x384d8000,
0x384da000,
0x384dc000,
0x384de000,
0x384e0000,
0x384e2000,
0x384e4000,
0x384e6000,
0x384e8000,
0x384ea000,
0x384ec000,
0x384ee000,
0x384f0000,
0x384f2000,
0x384f4000,
0x384f6000,
0x384f8000,
0x384fa000,
0x384fc000,
0x384fe000,
0x38500000,
0x38502000,
0x38504000,
0x38506000,
0x38508000,
0x3850a000,
0x3850c000,
0x3850e000,
0x38510000,
0x38512000,
0x38514000,
0x38516000,
0x38518000,
0x3851a000,
0x3851c000,
0x3851e000,
0x38520000,
0x38522000,
0x38524000,
0x38526000,
0x38528000,
0x3852a000,
0x3852c000,
0x3852e000,
0x38530000,
0x38532000,
0x38534000,
0x38536000,
0x38538000,
0x3853a000,
0x3853c000,
0x3853e000,
0x38540000,
0x38542000,
0x38544000,
0x38546000,
0x38548000,
0x3854a000,
0x3854c000,
0x3854e000,
0x38550000,
0x38552000,
0x38554000,
0x38556000,
0x38558000,
0x3855a000,
0x3855c000,
0x3855e000,
0x38560000,
0x38562000,
0x38564000,
0x38566000,
0x38568000,
0x3856a000,
0x3856c000,
0x3856e000,
0x38570000,
0x38572000,
0x38574000,
0x38576000,
0x38578000,
0x3857a000,
0x3857c000,
0x3857e000,
0x38580000,
0x38582000,
0x38584000,
0x38586000,
0x38588000,
0x3858a000,
0x3858c000,
0x3858e000,
0x38590000,
0x38592000,
0x38594000,
0x38596000,
0x38598000,
0x3859a000,
0x3859c000,
0x3859e000,
0x385a0000,
0x385a2000,
0x385a4000,
0x385a6000,
0x385a8000,
0x385aa000,
0x385ac000,
0x385ae000,
0x385b0000,
0x385b2000,
0x385b4000,
0x385b6000,
0x385b8000,
0x385ba000,
0x385bc000,
0x385be000,
0x385c0000,
0x385c2000,
0x385c4000,
0x385c6000,
0x385c8000,
0x385ca000,
0x385cc000,
0x385ce000,
0x385d0000,
0x385d2000,
0x385d4000,
0x385d6000,
0x385d8000,
0x385da000,
0x385dc000,
0x385de000,
0x385e0000,
0x385e2000,
0x385e4000,
0x385e6000,
0x385e8000,
0x385ea000,
0x385ec000,
0x385ee000,
0x385f0000,
0x385f2000,
0x385f4000,
0x385f6000,
0x385f8000,
0x385fa000,
0x385fc000,
0x385fe000,
0x38600000,
0x38602000,
0x38604000,
0x38606000,
0x38608000,
0x3860a000,
0x3860c000,
0x3860e000,
0x38610000,
0x38612000,
0x38614000,
0x38616000,
0x38618000,
0x3861a000,
0x3861c000,
0x3861e000,
0x38620000,
0x38622000,
0x38624000,
0x38626000,
0x38628000,
0x3862a000,
0x3862c000,
0x3862e000,
0x38630000,
0x38632000,
0x38634000,
0x38636000,
0x38638000,
0x3863a000,
0x3863c000,
0x3863e000,
0x38640000,
0x38642000,
0x38644000,
0x38646000,
0x38648000,
0x3864a000,
0x3864c000,
0x3864e000,
0x38650000,
0x38652000,
0x38654000,
0x38656000,
0x38658000,
0x3865a000,
0x3865c000,
0x3865e000,
0x38660000,
0x38662000,
0x38664000,
0x38666000,
0x38668000,
0x3866a000,
0x3866c000,
0x3866e000,
0x38670000,
0x38672000,
0x38674000,
0x38676000,
0x38678000,
0x3867a000,
0x3867c000,
0x3867e000,
0x38680000,
0x38682000,
0x38684000,
0x38686000,
0x38688000,
0x3868a000,
0x3868c000,
0x3868e000,
0x38690000,
0x38692000,
0x38694000,
0x38696000,
0x38698000,
0x3869a000,
0x3869c000,
0x3869e000,
0x386a0000,
0x386a2000,
0x386a4000,
0x386a6000,
0x386a8000,
0x386aa000,
0x386ac000,
0x386ae000,
0x386b0000,
0x386b2000,
0x386b4000,
0x386b6000,
0x386b8000,
0x386ba000,
0x386bc000,
0x386be000,
0x386c0000,
0x386c2000,
0x386c4000,
0x386c6000,
0x386c8000,
0x386ca000,
0x386cc000,
0x386ce000,
0x386d0000,
0x386d2000,
0x386d4000,
0x386d6000,
0x386d8000,
0x386da000,
0x386dc000,
0x386de000,
0x386e0000,
0x386e2000,
0x386e4000,
0x386e6000,
0x386e8000,
0x386ea000,
0x386ec000,
0x386ee000,
0x386f0000,
0x386f2000,
0x386f4000,
0x386f6000,
0x386f8000,
0x386fa000,
0x386fc000,
0x386fe000,
0x38700000,
0x38702000,
0x38704000,
0x38706000,
0x38708000,
0x3870a000,
0x3870c000,
0x3870e000,
0x38710000,
0x38712000,
0x38714000,
0x38716000,
0x38718000,
0x3871a000,
0x3871c000,
0x3871e000,
0x38720000,
0x38722000,
0x38724000,
0x38726000,
0x38728000,
0x3872a000,
0x3872c000,
0x3872e000,
0x38730000,
0x38732000,
0x38734000,
0x38736000,
0x38738000,
0x3873a000,
0x3873c000,
0x3873e000,
0x38740000,
0x38742000,
0x38744000,
0x38746000,
0x38748000,
0x3874a000,
0x3874c000,
0x3874e000,
0x38750000,
0x38752000,
0x38754000,
0x38756000,
0x38758000,
0x3875a000,
0x3875c000,
0x3875e000,
0x38760000,
0x38762000,
0x38764000,
0x38766000,
0x38768000,
0x3876a000,
0x3876c000,
0x3876e000,
0x38770000,
0x38772000,
0x38774000,
0x38776000,
0x38778000,
0x3877a000,
0x3877c000,
0x3877e000,
0x38780000,
0x38782000,
0x38784000,
0x38786000,
0x38788000,
0x3878a000,
0x3878c000,
0x3878e000,
0x38790000,
0x38792000,
0x38794000,
0x38796000,
0x38798000,
0x3879a000,
0x3879c000,
0x3879e000,
0x387a0000,
0x387a2000,
0x387a4000,
0x387a6000,
0x387a8000,
0x387aa000,
0x387ac000,
0x387ae000,
0x387b0000,
0x387b2000,
0x387b4000,
0x387b6000,
0x387b8000,
0x387ba000,
0x387bc000,
0x387be000,
0x387c0000,
0x387c2000,
0x387c4000,
0x387c6000,
0x387c8000,
0x387ca000,
0x387cc000,
0x387ce000,
0x387d0000,
0x387d2000,
0x387d4000,
0x387d6000,
0x387d8000,
0x387da000,
0x387dc000,
0x387de000,
0x387e0000,
0x387e2000,
0x387e4000,
0x387e6000,
0x387e8000,
0x387ea000,
0x387ec000,
0x387ee000,
0x387f0000,
0x387f2000,
0x387f4000,
0x387f6000,
0x387f8000,
0x387fa000,
0x387fc000,
0x387fe000,
};
const static unsigned g_exponent[64] = {
0x00000000,
0x00800000,
0x01000000,
0x01800000,
0x02000000,
0x02800000,
0x03000000,
0x03800000,
0x04000000,
0x04800000,
0x05000000,
0x05800000,
0x06000000,
0x06800000,
0x07000000,
0x07800000,
0x08000000,
0x08800000,
0x09000000,
0x09800000,
0x0a000000,
0x0a800000,
0x0b000000,
0x0b800000,
0x0c000000,
0x0c800000,
0x0d000000,
0x0d800000,
0x0e000000,
0x0e800000,
0x0f000000,
0x47800000,
0x80000000,
0x80800000,
0x81000000,
0x81800000,
0x82000000,
0x82800000,
0x83000000,
0x83800000,
0x84000000,
0x84800000,
0x85000000,
0x85800000,
0x86000000,
0x86800000,
0x87000000,
0x87800000,
0x88000000,
0x88800000,
0x89000000,
0x89800000,
0x8a000000,
0x8a800000,
0x8b000000,
0x8b800000,
0x8c000000,
0x8c800000,
0x8d000000,
0x8d800000,
0x8e000000,
0x8e800000,
0x8f000000,
0xc7800000,
};
const static unsigned g_offset[64] = {
0x00000000,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000000,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
};
float float16ToFloat32(unsigned short h)
{
unsigned i32 = g_mantissa[g_offset[h >> 10] + (h & 0x3ff)] + g_exponent[h >> 10];
return *(float*) &i32;
}
}
| C++ |
#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.
//
// Program.cpp: Implements the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#include "libGLESv2/BinaryStream.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/renderer/ShaderExecutable.h"
#include "common/debug.h"
#include "common/version.h"
#include "utilities.h"
#include "libGLESv2/main.h"
#include "libGLESv2/Shader.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#undef near
#undef far
namespace gl
{
std::string str(int i)
{
char buffer[20];
snprintf(buffer, sizeof(buffer), "%d", i);
return buffer;
}
UniformLocation::UniformLocation(const std::string &name, unsigned int element, unsigned int index)
: name(name), element(element), index(index)
{
}
unsigned int ProgramBinary::mCurrentSerial = 1;
ProgramBinary::ProgramBinary(rx::Renderer *renderer) : mRenderer(renderer), RefCountObject(0), mSerial(issueSerial())
{
mPixelExecutable = NULL;
mVertexExecutable = NULL;
mGeometryExecutable = NULL;
mValidated = false;
for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++)
{
mSemanticIndex[index] = -1;
}
for (int index = 0; index < MAX_TEXTURE_IMAGE_UNITS; index++)
{
mSamplersPS[index].active = false;
}
for (int index = 0; index < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; index++)
{
mSamplersVS[index].active = false;
}
mUsedVertexSamplerRange = 0;
mUsedPixelSamplerRange = 0;
mUsesPointSize = false;
}
ProgramBinary::~ProgramBinary()
{
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mVertexExecutable;
mVertexExecutable = NULL;
delete mGeometryExecutable;
mGeometryExecutable = NULL;
while (!mUniforms.empty())
{
delete mUniforms.back();
mUniforms.pop_back();
}
}
unsigned int ProgramBinary::getSerial() const
{
return mSerial;
}
unsigned int ProgramBinary::issueSerial()
{
return mCurrentSerial++;
}
rx::ShaderExecutable *ProgramBinary::getPixelExecutable()
{
return mPixelExecutable;
}
rx::ShaderExecutable *ProgramBinary::getVertexExecutable()
{
return mVertexExecutable;
}
rx::ShaderExecutable *ProgramBinary::getGeometryExecutable()
{
return mGeometryExecutable;
}
GLuint ProgramBinary::getAttributeLocation(const char *name)
{
if (name)
{
for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++)
{
if (mLinkedAttribute[index].name == std::string(name))
{
return index;
}
}
}
return -1;
}
int ProgramBinary::getSemanticIndex(int attributeIndex)
{
ASSERT(attributeIndex >= 0 && attributeIndex < MAX_VERTEX_ATTRIBS);
return mSemanticIndex[attributeIndex];
}
// Returns one more than the highest sampler index used.
GLint ProgramBinary::getUsedSamplerRange(SamplerType type)
{
switch (type)
{
case SAMPLER_PIXEL:
return mUsedPixelSamplerRange;
case SAMPLER_VERTEX:
return mUsedVertexSamplerRange;
default:
UNREACHABLE();
return 0;
}
}
bool ProgramBinary::usesPointSize() const
{
return mUsesPointSize;
}
bool ProgramBinary::usesPointSpriteEmulation() const
{
return mUsesPointSize && mRenderer->getMajorShaderModel() >= 4;
}
bool ProgramBinary::usesGeometryShader() const
{
return usesPointSpriteEmulation();
}
// Returns the index of the texture image unit (0-19) corresponding to a Direct3D 9 sampler
// index (0-15 for the pixel shader and 0-3 for the vertex shader).
GLint ProgramBinary::getSamplerMapping(SamplerType type, unsigned int samplerIndex)
{
GLint logicalTextureUnit = -1;
switch (type)
{
case SAMPLER_PIXEL:
ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0]));
if (mSamplersPS[samplerIndex].active)
{
logicalTextureUnit = mSamplersPS[samplerIndex].logicalTextureUnit;
}
break;
case SAMPLER_VERTEX:
ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0]));
if (mSamplersVS[samplerIndex].active)
{
logicalTextureUnit = mSamplersVS[samplerIndex].logicalTextureUnit;
}
break;
default: UNREACHABLE();
}
if (logicalTextureUnit >= 0 && logicalTextureUnit < (GLint)mRenderer->getMaxCombinedTextureImageUnits())
{
return logicalTextureUnit;
}
return -1;
}
// Returns the texture type for a given Direct3D 9 sampler type and
// index (0-15 for the pixel shader and 0-3 for the vertex shader).
TextureType ProgramBinary::getSamplerTextureType(SamplerType type, unsigned int samplerIndex)
{
switch (type)
{
case SAMPLER_PIXEL:
ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0]));
ASSERT(mSamplersPS[samplerIndex].active);
return mSamplersPS[samplerIndex].textureType;
case SAMPLER_VERTEX:
ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0]));
ASSERT(mSamplersVS[samplerIndex].active);
return mSamplersVS[samplerIndex].textureType;
default: UNREACHABLE();
}
return TEXTURE_2D;
}
GLint ProgramBinary::getUniformLocation(std::string name)
{
unsigned int subscript = 0;
// Strip any trailing array operator and retrieve the subscript
size_t open = name.find_last_of('[');
size_t close = name.find_last_of(']');
if (open != std::string::npos && close == name.length() - 1)
{
subscript = atoi(name.substr(open + 1).c_str());
name.erase(open);
}
unsigned int numUniforms = mUniformIndex.size();
for (unsigned int location = 0; location < numUniforms; location++)
{
if (mUniformIndex[location].name == name &&
mUniformIndex[location].element == subscript)
{
return location;
}
}
return -1;
}
bool ProgramBinary::setUniform1fv(GLint location, GLsizei count, const GLfloat* v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = 0;
target[2] = 0;
target[3] = 0;
target += 4;
v += 1;
}
}
else if (targetUniform->type == GL_BOOL)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = GL_FALSE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 1;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform2fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC2)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = 0;
target[3] = 0;
target += 4;
v += 2;
}
}
else if (targetUniform->type == GL_BOOL_VEC2)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 2;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform3fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC3)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = 0;
target += 4;
v += 3;
}
}
else if (targetUniform->type == GL_BOOL_VEC3)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 3;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform4fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC4)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = v[3];
target += 4;
v += 4;
}
}
else if (targetUniform->type == GL_BOOL_VEC4)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[3] = (v[3] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams += 4;
v += 4;
}
}
else
{
return false;
}
return true;
}
template<typename T, int targetWidth, int targetHeight, int srcWidth, int srcHeight>
void transposeMatrix(T *target, const GLfloat *value)
{
int copyWidth = std::min(targetWidth, srcWidth);
int copyHeight = std::min(targetHeight, srcHeight);
for (int x = 0; x < copyWidth; x++)
{
for (int y = 0; y < copyHeight; y++)
{
target[x * targetWidth + y] = (T)value[y * srcWidth + x];
}
}
// clear unfilled right side
for (int y = 0; y < copyHeight; y++)
{
for (int x = srcWidth; x < targetWidth; x++)
{
target[y * targetWidth + x] = (T)0;
}
}
// clear unfilled bottom.
for (int y = srcHeight; y < targetHeight; y++)
{
for (int x = 0; x < targetWidth; x++)
{
target[y * targetWidth + x] = (T)0;
}
}
}
bool ProgramBinary::setUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT2)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8;
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,2,2,2>(target, value);
target += 8;
value += 4;
}
return true;
}
bool ProgramBinary::setUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT3)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12;
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,3,3,3>(target, value);
target += 12;
value += 9;
}
return true;
}
bool ProgramBinary::setUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT4)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)(targetUniform->data + mUniformIndex[location].element * sizeof(GLfloat) * 16);
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,4,4,4>(target, value);
target += 16;
value += 16;
}
return true;
}
bool ProgramBinary::setUniform1iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT ||
targetUniform->type == GL_SAMPLER_2D ||
targetUniform->type == GL_SAMPLER_CUBE)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = 0;
target[2] = 0;
target[3] = 0;
target += 4;
v += 1;
}
}
else if (targetUniform->type == GL_BOOL)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = GL_FALSE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 1;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform2iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC2)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = 0;
target[3] = 0;
target += 4;
v += 2;
}
}
else if (targetUniform->type == GL_BOOL_VEC2)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 2;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform3iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC3)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = 0;
target += 4;
v += 3;
}
}
else if (targetUniform->type == GL_BOOL_VEC3)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0) ? GL_FALSE : GL_TRUE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 3;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform4iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC4)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = v[3];
target += 4;
v += 4;
}
}
else if (targetUniform->type == GL_BOOL_VEC4)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0) ? GL_FALSE : GL_TRUE;
boolParams[3] = (v[3] == 0) ? GL_FALSE : GL_TRUE;
boolParams += 4;
v += 4;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::getUniformfv(GLint location, GLsizei *bufSize, GLfloat *params)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
// sized queries -- ensure the provided buffer is large enough
if (bufSize)
{
int requiredBytes = UniformExternalSize(targetUniform->type);
if (*bufSize < requiredBytes)
{
return false;
}
}
switch (targetUniform->type)
{
case GL_FLOAT_MAT2:
transposeMatrix<GLfloat,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8);
break;
case GL_FLOAT_MAT3:
transposeMatrix<GLfloat,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12);
break;
case GL_FLOAT_MAT4:
transposeMatrix<GLfloat,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16);
break;
default:
{
unsigned int size = UniformComponentCount(targetUniform->type);
switch (UniformComponentType(targetUniform->type))
{
case GL_BOOL:
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (boolParams[i] == GL_FALSE) ? 0.0f : 1.0f;
}
}
break;
case GL_FLOAT:
memcpy(params, targetUniform->data + mUniformIndex[location].element * 4 * sizeof(GLfloat),
size * sizeof(GLfloat));
break;
case GL_INT:
{
GLint *intParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (float)intParams[i];
}
}
break;
default: UNREACHABLE();
}
}
}
return true;
}
bool ProgramBinary::getUniformiv(GLint location, GLsizei *bufSize, GLint *params)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
// sized queries -- ensure the provided buffer is large enough
if (bufSize)
{
int requiredBytes = UniformExternalSize(targetUniform->type);
if (*bufSize < requiredBytes)
{
return false;
}
}
switch (targetUniform->type)
{
case GL_FLOAT_MAT2:
transposeMatrix<GLint,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8);
break;
case GL_FLOAT_MAT3:
transposeMatrix<GLint,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12);
break;
case GL_FLOAT_MAT4:
transposeMatrix<GLint,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16);
break;
default:
{
unsigned int size = VariableColumnCount(targetUniform->type);
switch (UniformComponentType(targetUniform->type))
{
case GL_BOOL:
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = boolParams[i];
}
}
break;
case GL_FLOAT:
{
GLfloat *floatParams = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (GLint)floatParams[i];
}
}
break;
case GL_INT:
memcpy(params, targetUniform->data + mUniformIndex[location].element * 4 * sizeof(GLint),
size * sizeof(GLint));
break;
default: UNREACHABLE();
}
}
}
return true;
}
void ProgramBinary::dirtyAllUniforms()
{
unsigned int numUniforms = mUniforms.size();
for (unsigned int index = 0; index < numUniforms; index++)
{
mUniforms[index]->dirty = true;
}
}
// Applies all the uniforms set for this program object to the renderer
void ProgramBinary::applyUniforms()
{
// Retrieve sampler uniform values
for (std::vector<Uniform*>::iterator ub = mUniforms.begin(), ue = mUniforms.end(); ub != ue; ++ub)
{
Uniform *targetUniform = *ub;
if (targetUniform->dirty)
{
if (targetUniform->type == GL_SAMPLER_2D ||
targetUniform->type == GL_SAMPLER_CUBE)
{
int count = targetUniform->elementCount();
GLint (*v)[4] = (GLint(*)[4])targetUniform->data;
if (targetUniform->psRegisterIndex >= 0)
{
unsigned int firstIndex = targetUniform->psRegisterIndex;
for (int i = 0; i < count; i++)
{
unsigned int samplerIndex = firstIndex + i;
if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS)
{
ASSERT(mSamplersPS[samplerIndex].active);
mSamplersPS[samplerIndex].logicalTextureUnit = v[i][0];
}
}
}
if (targetUniform->vsRegisterIndex >= 0)
{
unsigned int firstIndex = targetUniform->vsRegisterIndex;
for (int i = 0; i < count; i++)
{
unsigned int samplerIndex = firstIndex + i;
if (samplerIndex < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS)
{
ASSERT(mSamplersVS[samplerIndex].active);
mSamplersVS[samplerIndex].logicalTextureUnit = v[i][0];
}
}
}
}
}
}
mRenderer->applyUniforms(this, &mUniforms);
}
// Packs varyings into generic varying registers, using the algorithm from [OpenGL ES Shading Language 1.00 rev. 17] appendix A section 7 page 111
// Returns the number of used varying registers, or -1 if unsuccesful
int ProgramBinary::packVaryings(InfoLog &infoLog, const Varying *packing[][4], FragmentShader *fragmentShader)
{
const int maxVaryingVectors = mRenderer->getMaxVaryingVectors();
fragmentShader->resetVaryingsRegisterAssignment();
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
int n = VariableRowCount(varying->type) * varying->size;
int m = VariableColumnCount(varying->type);
bool success = false;
if (m == 2 || m == 3 || m == 4)
{
for (int r = 0; r <= maxVaryingVectors - n && !success; r++)
{
bool available = true;
for (int y = 0; y < n && available; y++)
{
for (int x = 0; x < m && available; x++)
{
if (packing[r + y][x])
{
available = false;
}
}
}
if (available)
{
varying->reg = r;
varying->col = 0;
for (int y = 0; y < n; y++)
{
for (int x = 0; x < m; x++)
{
packing[r + y][x] = &*varying;
}
}
success = true;
}
}
if (!success && m == 2)
{
for (int r = maxVaryingVectors - n; r >= 0 && !success; r--)
{
bool available = true;
for (int y = 0; y < n && available; y++)
{
for (int x = 2; x < 4 && available; x++)
{
if (packing[r + y][x])
{
available = false;
}
}
}
if (available)
{
varying->reg = r;
varying->col = 2;
for (int y = 0; y < n; y++)
{
for (int x = 2; x < 4; x++)
{
packing[r + y][x] = &*varying;
}
}
success = true;
}
}
}
}
else if (m == 1)
{
int space[4] = {0};
for (int y = 0; y < maxVaryingVectors; y++)
{
for (int x = 0; x < 4; x++)
{
space[x] += packing[y][x] ? 0 : 1;
}
}
int column = 0;
for (int x = 0; x < 4; x++)
{
if (space[x] >= n && space[x] < space[column])
{
column = x;
}
}
if (space[column] >= n)
{
for (int r = 0; r < maxVaryingVectors; r++)
{
if (!packing[r][column])
{
varying->reg = r;
for (int y = r; y < r + n; y++)
{
packing[y][column] = &*varying;
}
break;
}
}
varying->col = column;
success = true;
}
}
else UNREACHABLE();
if (!success)
{
infoLog.append("Could not pack varying %s", varying->name.c_str());
return -1;
}
}
// Return the number of used registers
int registers = 0;
for (int r = 0; r < maxVaryingVectors; r++)
{
if (packing[r][0] || packing[r][1] || packing[r][2] || packing[r][3])
{
registers++;
}
}
return registers;
}
bool ProgramBinary::linkVaryings(InfoLog &infoLog, int registers, const Varying *packing[][4],
std::string& pixelHLSL, std::string& vertexHLSL,
FragmentShader *fragmentShader, VertexShader *vertexShader)
{
if (pixelHLSL.empty() || vertexHLSL.empty())
{
return false;
}
bool usesMRT = fragmentShader->mUsesMultipleRenderTargets;
bool usesFragColor = fragmentShader->mUsesFragColor;
bool usesFragData = fragmentShader->mUsesFragData;
if (usesFragColor && usesFragData)
{
infoLog.append("Cannot use both gl_FragColor and gl_FragData in the same fragment shader.");
return false;
}
// Write the HLSL input/output declarations
const int shaderModel = mRenderer->getMajorShaderModel();
const int maxVaryingVectors = mRenderer->getMaxVaryingVectors();
const int registersNeeded = registers + (fragmentShader->mUsesFragCoord ? 1 : 0) + (fragmentShader->mUsesPointCoord ? 1 : 0);
// The output color is broadcast to all enabled draw buffers when writing to gl_FragColor
const bool broadcast = fragmentShader->mUsesFragColor;
const unsigned int numRenderTargets = (broadcast || usesMRT ? mRenderer->getMaxRenderTargets() : 1);
if (registersNeeded > maxVaryingVectors)
{
infoLog.append("No varying registers left to support gl_FragCoord/gl_PointCoord");
return false;
}
vertexShader->resetVaryingsRegisterAssignment();
for (VaryingList::iterator input = fragmentShader->mVaryings.begin(); input != fragmentShader->mVaryings.end(); input++)
{
bool matched = false;
for (VaryingList::iterator output = vertexShader->mVaryings.begin(); output != vertexShader->mVaryings.end(); output++)
{
if (output->name == input->name)
{
if (output->type != input->type || output->size != input->size)
{
infoLog.append("Type of vertex varying %s does not match that of the fragment varying", output->name.c_str());
return false;
}
output->reg = input->reg;
output->col = input->col;
matched = true;
break;
}
}
if (!matched)
{
infoLog.append("Fragment varying %s does not match any vertex varying", input->name.c_str());
return false;
}
}
mUsesPointSize = vertexShader->mUsesPointSize;
std::string varyingSemantic = (mUsesPointSize && shaderModel == 3) ? "COLOR" : "TEXCOORD";
std::string targetSemantic = (shaderModel >= 4) ? "SV_Target" : "COLOR";
std::string positionSemantic = (shaderModel >= 4) ? "SV_Position" : "POSITION";
std::string depthSemantic = (shaderModel >= 4) ? "SV_Depth" : "DEPTH";
// special varyings that use reserved registers
int reservedRegisterIndex = registers;
std::string fragCoordSemantic;
std::string pointCoordSemantic;
if (fragmentShader->mUsesFragCoord)
{
fragCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
if (fragmentShader->mUsesPointCoord)
{
// Shader model 3 uses a special TEXCOORD semantic for point sprite texcoords.
// In DX11 we compute this in the GS.
if (shaderModel == 3)
{
pointCoordSemantic = "TEXCOORD0";
}
else if (shaderModel >= 4)
{
pointCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
}
vertexHLSL += "struct VS_INPUT\n"
"{\n";
int semanticIndex = 0;
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
switch (attribute->type)
{
case GL_FLOAT: vertexHLSL += " float "; break;
case GL_FLOAT_VEC2: vertexHLSL += " float2 "; break;
case GL_FLOAT_VEC3: vertexHLSL += " float3 "; break;
case GL_FLOAT_VEC4: vertexHLSL += " float4 "; break;
case GL_FLOAT_MAT2: vertexHLSL += " float2x2 "; break;
case GL_FLOAT_MAT3: vertexHLSL += " float3x3 "; break;
case GL_FLOAT_MAT4: vertexHLSL += " float4x4 "; break;
default: UNREACHABLE();
}
vertexHLSL += decorateAttribute(attribute->name) + " : TEXCOORD" + str(semanticIndex) + ";\n";
semanticIndex += VariableRowCount(attribute->type);
}
vertexHLSL += "};\n"
"\n"
"struct VS_OUTPUT\n"
"{\n";
if (shaderModel < 4)
{
vertexHLSL += " float4 gl_Position : " + positionSemantic + ";\n";
}
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
vertexHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
vertexHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (vertexShader->mUsesPointSize && shaderModel >= 3)
{
vertexHLSL += " float gl_PointSize : PSIZE;\n";
}
if (shaderModel >= 4)
{
vertexHLSL += " float4 gl_Position : " + positionSemantic + ";\n";
}
vertexHLSL += "};\n"
"\n"
"VS_OUTPUT main(VS_INPUT input)\n"
"{\n";
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
vertexHLSL += " " + decorateAttribute(attribute->name) + " = ";
if (VariableRowCount(attribute->type) > 1) // Matrix
{
vertexHLSL += "transpose";
}
vertexHLSL += "(input." + decorateAttribute(attribute->name) + ");\n";
}
if (shaderModel >= 4)
{
vertexHLSL += "\n"
" gl_main();\n"
"\n"
" VS_OUTPUT output;\n"
" output.gl_Position.x = gl_Position.x;\n"
" output.gl_Position.y = -gl_Position.y;\n"
" output.gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
" output.gl_Position.w = gl_Position.w;\n";
}
else
{
vertexHLSL += "\n"
" gl_main();\n"
"\n"
" VS_OUTPUT output;\n"
" output.gl_Position.x = gl_Position.x * dx_ViewAdjust.z + dx_ViewAdjust.x * gl_Position.w;\n"
" output.gl_Position.y = -(gl_Position.y * dx_ViewAdjust.w + dx_ViewAdjust.y * gl_Position.w);\n"
" output.gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
" output.gl_Position.w = gl_Position.w;\n";
}
if (vertexShader->mUsesPointSize && shaderModel >= 3)
{
vertexHLSL += " output.gl_PointSize = gl_PointSize;\n";
}
if (fragmentShader->mUsesFragCoord)
{
vertexHLSL += " output.gl_FragCoord = gl_Position;\n";
}
for (VaryingList::iterator varying = vertexShader->mVaryings.begin(); varying != vertexShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
int r = varying->reg + i * rows + j;
vertexHLSL += " output.v" + str(r);
bool sharedRegister = false; // Register used by multiple varyings
for (int x = 0; x < 4; x++)
{
if (packing[r][x] && packing[r][x] != packing[r][0])
{
sharedRegister = true;
break;
}
}
if(sharedRegister)
{
vertexHLSL += ".";
for (int x = 0; x < 4; x++)
{
if (packing[r][x] == &*varying)
{
switch(x)
{
case 0: vertexHLSL += "x"; break;
case 1: vertexHLSL += "y"; break;
case 2: vertexHLSL += "z"; break;
case 3: vertexHLSL += "w"; break;
}
}
}
}
vertexHLSL += " = " + varying->name;
if (varying->array)
{
vertexHLSL += "[" + str(i) + "]";
}
if (rows > 1)
{
vertexHLSL += "[" + str(j) + "]";
}
vertexHLSL += ";\n";
}
}
}
}
vertexHLSL += "\n"
" return output;\n"
"}\n";
pixelHLSL += "struct PS_INPUT\n"
"{\n";
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
std::string n = str(varying->reg + i * rows + j);
pixelHLSL += " float" + str(VariableColumnCount(varying->type)) + " v" + n + " : " + varyingSemantic + n + ";\n";
}
}
}
else UNREACHABLE();
}
if (fragmentShader->mUsesFragCoord)
{
pixelHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (fragmentShader->mUsesPointCoord && shaderModel >= 3)
{
pixelHLSL += " float2 gl_PointCoord : " + pointCoordSemantic + ";\n";
}
// Must consume the PSIZE element if the geometry shader is not active
// We won't know if we use a GS until we draw
if (vertexShader->mUsesPointSize && shaderModel >= 4)
{
pixelHLSL += " float gl_PointSize : PSIZE;\n";
}
if (fragmentShader->mUsesFragCoord)
{
if (shaderModel >= 4)
{
pixelHLSL += " float4 dx_VPos : SV_Position;\n";
}
else if (shaderModel >= 3)
{
pixelHLSL += " float2 dx_VPos : VPOS;\n";
}
}
pixelHLSL += "};\n"
"\n"
"struct PS_OUTPUT\n"
"{\n";
for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets; renderTargetIndex++)
{
pixelHLSL += " float4 gl_Color" + str(renderTargetIndex) + " : " + targetSemantic + str(renderTargetIndex) + ";\n";
}
if (fragmentShader->mUsesFragDepth)
{
pixelHLSL += " float gl_Depth : " + depthSemantic + ";\n";
}
pixelHLSL += "};\n"
"\n";
if (fragmentShader->mUsesFrontFacing)
{
if (shaderModel >= 4)
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input, bool isFrontFace : SV_IsFrontFace)\n"
"{\n";
}
else
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input, float vFace : VFACE)\n"
"{\n";
}
}
else
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input)\n"
"{\n";
}
if (fragmentShader->mUsesFragCoord)
{
pixelHLSL += " float rhw = 1.0 / input.gl_FragCoord.w;\n";
if (shaderModel >= 4)
{
pixelHLSL += " gl_FragCoord.x = input.dx_VPos.x;\n"
" gl_FragCoord.y = input.dx_VPos.y;\n";
}
else if (shaderModel >= 3)
{
pixelHLSL += " gl_FragCoord.x = input.dx_VPos.x + 0.5;\n"
" gl_FragCoord.y = input.dx_VPos.y + 0.5;\n";
}
else
{
// dx_ViewCoords contains the viewport width/2, height/2, center.x and center.y. See Renderer::setViewport()
pixelHLSL += " gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_ViewCoords.x + dx_ViewCoords.z;\n"
" gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_ViewCoords.y + dx_ViewCoords.w;\n";
}
pixelHLSL += " gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_DepthFront.x + dx_DepthFront.y;\n"
" gl_FragCoord.w = rhw;\n";
}
if (fragmentShader->mUsesPointCoord && shaderModel >= 3)
{
pixelHLSL += " gl_PointCoord.x = input.gl_PointCoord.x;\n";
pixelHLSL += " gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n";
}
if (fragmentShader->mUsesFrontFacing)
{
if (shaderModel <= 3)
{
pixelHLSL += " gl_FrontFacing = (vFace * dx_DepthFront.z >= 0.0);\n";
}
else
{
pixelHLSL += " gl_FrontFacing = isFrontFace;\n";
}
}
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
std::string n = str(varying->reg + i * rows + j);
pixelHLSL += " " + varying->name;
if (varying->array)
{
pixelHLSL += "[" + str(i) + "]";
}
if (rows > 1)
{
pixelHLSL += "[" + str(j) + "]";
}
switch (VariableColumnCount(varying->type))
{
case 1: pixelHLSL += " = input.v" + n + ".x;\n"; break;
case 2: pixelHLSL += " = input.v" + n + ".xy;\n"; break;
case 3: pixelHLSL += " = input.v" + n + ".xyz;\n"; break;
case 4: pixelHLSL += " = input.v" + n + ";\n"; break;
default: UNREACHABLE();
}
}
}
}
else UNREACHABLE();
}
pixelHLSL += "\n"
" gl_main();\n"
"\n"
" PS_OUTPUT output;\n";
for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets; renderTargetIndex++)
{
unsigned int sourceColorIndex = broadcast ? 0 : renderTargetIndex;
pixelHLSL += " output.gl_Color" + str(renderTargetIndex) + " = gl_Color[" + str(sourceColorIndex) + "];\n";
}
if (fragmentShader->mUsesFragDepth)
{
pixelHLSL += " output.gl_Depth = gl_Depth;\n";
}
pixelHLSL += "\n"
" return output;\n"
"}\n";
return true;
}
bool ProgramBinary::load(InfoLog &infoLog, const void *binary, GLsizei length)
{
BinaryInputStream stream(binary, length);
int format = 0;
stream.read(&format);
if (format != GL_PROGRAM_BINARY_ANGLE)
{
infoLog.append("Invalid program binary format.");
return false;
}
int version = 0;
stream.read(&version);
if (version != VERSION_DWORD)
{
infoLog.append("Invalid program binary version.");
return false;
}
int compileFlags = 0;
stream.read(&compileFlags);
if (compileFlags != ANGLE_COMPILE_OPTIMIZATION_LEVEL)
{
infoLog.append("Mismatched compilation flags.");
return false;
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; ++i)
{
stream.read(&mLinkedAttribute[i].type);
std::string name;
stream.read(&name);
mLinkedAttribute[i].name = name;
stream.read(&mSemanticIndex[i]);
}
for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.read(&mSamplersPS[i].active);
stream.read(&mSamplersPS[i].logicalTextureUnit);
int textureType;
stream.read(&textureType);
mSamplersPS[i].textureType = (TextureType) textureType;
}
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.read(&mSamplersVS[i].active);
stream.read(&mSamplersVS[i].logicalTextureUnit);
int textureType;
stream.read(&textureType);
mSamplersVS[i].textureType = (TextureType) textureType;
}
stream.read(&mUsedVertexSamplerRange);
stream.read(&mUsedPixelSamplerRange);
stream.read(&mUsesPointSize);
size_t size;
stream.read(&size);
if (stream.error())
{
infoLog.append("Invalid program binary.");
return false;
}
mUniforms.resize(size);
for (unsigned int i = 0; i < size; ++i)
{
GLenum type;
GLenum precision;
std::string name;
unsigned int arraySize;
stream.read(&type);
stream.read(&precision);
stream.read(&name);
stream.read(&arraySize);
mUniforms[i] = new Uniform(type, precision, name, arraySize);
stream.read(&mUniforms[i]->psRegisterIndex);
stream.read(&mUniforms[i]->vsRegisterIndex);
stream.read(&mUniforms[i]->registerCount);
}
stream.read(&size);
if (stream.error())
{
infoLog.append("Invalid program binary.");
return false;
}
mUniformIndex.resize(size);
for (unsigned int i = 0; i < size; ++i)
{
stream.read(&mUniformIndex[i].name);
stream.read(&mUniformIndex[i].element);
stream.read(&mUniformIndex[i].index);
}
unsigned int pixelShaderSize;
stream.read(&pixelShaderSize);
unsigned int vertexShaderSize;
stream.read(&vertexShaderSize);
unsigned int geometryShaderSize;
stream.read(&geometryShaderSize);
const char *ptr = (const char*) binary + stream.offset();
const GUID *binaryIdentifier = (const GUID *) ptr;
ptr += sizeof(GUID);
GUID identifier = mRenderer->getAdapterIdentifier();
if (memcmp(&identifier, binaryIdentifier, sizeof(GUID)) != 0)
{
infoLog.append("Invalid program binary.");
return false;
}
const char *pixelShaderFunction = ptr;
ptr += pixelShaderSize;
const char *vertexShaderFunction = ptr;
ptr += vertexShaderSize;
const char *geometryShaderFunction = geometryShaderSize > 0 ? ptr : NULL;
ptr += geometryShaderSize;
mPixelExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(pixelShaderFunction),
pixelShaderSize, rx::SHADER_PIXEL);
if (!mPixelExecutable)
{
infoLog.append("Could not create pixel shader.");
return false;
}
mVertexExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(vertexShaderFunction),
vertexShaderSize, rx::SHADER_VERTEX);
if (!mVertexExecutable)
{
infoLog.append("Could not create vertex shader.");
delete mPixelExecutable;
mPixelExecutable = NULL;
return false;
}
if (geometryShaderFunction != NULL && geometryShaderSize > 0)
{
mGeometryExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(geometryShaderFunction),
geometryShaderSize, rx::SHADER_GEOMETRY);
if (!mGeometryExecutable)
{
infoLog.append("Could not create geometry shader.");
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mVertexExecutable;
mVertexExecutable = NULL;
return false;
}
}
else
{
mGeometryExecutable = NULL;
}
return true;
}
bool ProgramBinary::save(void* binary, GLsizei bufSize, GLsizei *length)
{
BinaryOutputStream stream;
stream.write(GL_PROGRAM_BINARY_ANGLE);
stream.write(VERSION_DWORD);
stream.write(ANGLE_COMPILE_OPTIMIZATION_LEVEL);
for (unsigned int i = 0; i < MAX_VERTEX_ATTRIBS; ++i)
{
stream.write(mLinkedAttribute[i].type);
stream.write(mLinkedAttribute[i].name);
stream.write(mSemanticIndex[i]);
}
for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.write(mSamplersPS[i].active);
stream.write(mSamplersPS[i].logicalTextureUnit);
stream.write((int) mSamplersPS[i].textureType);
}
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.write(mSamplersVS[i].active);
stream.write(mSamplersVS[i].logicalTextureUnit);
stream.write((int) mSamplersVS[i].textureType);
}
stream.write(mUsedVertexSamplerRange);
stream.write(mUsedPixelSamplerRange);
stream.write(mUsesPointSize);
stream.write(mUniforms.size());
for (unsigned int i = 0; i < mUniforms.size(); ++i)
{
stream.write(mUniforms[i]->type);
stream.write(mUniforms[i]->precision);
stream.write(mUniforms[i]->name);
stream.write(mUniforms[i]->arraySize);
stream.write(mUniforms[i]->psRegisterIndex);
stream.write(mUniforms[i]->vsRegisterIndex);
stream.write(mUniforms[i]->registerCount);
}
stream.write(mUniformIndex.size());
for (unsigned int i = 0; i < mUniformIndex.size(); ++i)
{
stream.write(mUniformIndex[i].name);
stream.write(mUniformIndex[i].element);
stream.write(mUniformIndex[i].index);
}
UINT pixelShaderSize = mPixelExecutable->getLength();
stream.write(pixelShaderSize);
UINT vertexShaderSize = mVertexExecutable->getLength();
stream.write(vertexShaderSize);
UINT geometryShaderSize = (mGeometryExecutable != NULL) ? mGeometryExecutable->getLength() : 0;
stream.write(geometryShaderSize);
GUID identifier = mRenderer->getAdapterIdentifier();
GLsizei streamLength = stream.length();
const void *streamData = stream.data();
GLsizei totalLength = streamLength + sizeof(GUID) + pixelShaderSize + vertexShaderSize + geometryShaderSize;
if (totalLength > bufSize)
{
if (length)
{
*length = 0;
}
return false;
}
if (binary)
{
char *ptr = (char*) binary;
memcpy(ptr, streamData, streamLength);
ptr += streamLength;
memcpy(ptr, &identifier, sizeof(GUID));
ptr += sizeof(GUID);
memcpy(ptr, mPixelExecutable->getFunction(), pixelShaderSize);
ptr += pixelShaderSize;
memcpy(ptr, mVertexExecutable->getFunction(), vertexShaderSize);
ptr += vertexShaderSize;
if (mGeometryExecutable != NULL && geometryShaderSize > 0)
{
memcpy(ptr, mGeometryExecutable->getFunction(), geometryShaderSize);
ptr += geometryShaderSize;
}
ASSERT(ptr - totalLength == binary);
}
if (length)
{
*length = totalLength;
}
return true;
}
GLint ProgramBinary::getLength()
{
GLint length;
if (save(NULL, INT_MAX, &length))
{
return length;
}
else
{
return 0;
}
}
bool ProgramBinary::link(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader)
{
if (!fragmentShader || !fragmentShader->isCompiled())
{
return false;
}
if (!vertexShader || !vertexShader->isCompiled())
{
return false;
}
std::string pixelHLSL = fragmentShader->getHLSL();
std::string vertexHLSL = vertexShader->getHLSL();
// Map the varyings to the register file
const Varying *packing[IMPLEMENTATION_MAX_VARYING_VECTORS][4] = {NULL};
int registers = packVaryings(infoLog, packing, fragmentShader);
if (registers < 0)
{
return false;
}
if (!linkVaryings(infoLog, registers, packing, pixelHLSL, vertexHLSL, fragmentShader, vertexShader))
{
return false;
}
bool success = true;
mVertexExecutable = mRenderer->compileToExecutable(infoLog, vertexHLSL.c_str(), rx::SHADER_VERTEX);
mPixelExecutable = mRenderer->compileToExecutable(infoLog, pixelHLSL.c_str(), rx::SHADER_PIXEL);
if (usesGeometryShader())
{
std::string geometryHLSL = generateGeometryShaderHLSL(registers, packing, fragmentShader, vertexShader);
mGeometryExecutable = mRenderer->compileToExecutable(infoLog, geometryHLSL.c_str(), rx::SHADER_GEOMETRY);
}
if (!mVertexExecutable || !mPixelExecutable || (usesGeometryShader() && !mGeometryExecutable))
{
infoLog.append("Failed to create D3D shaders.");
success = false;
delete mVertexExecutable;
mVertexExecutable = NULL;
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mGeometryExecutable;
mGeometryExecutable = NULL;
}
if (!linkAttributes(infoLog, attributeBindings, fragmentShader, vertexShader))
{
success = false;
}
if (!linkUniforms(infoLog, vertexShader->getUniforms(), fragmentShader->getUniforms()))
{
success = false;
}
// special case for gl_DepthRange, the only built-in uniform (also a struct)
if (vertexShader->mUsesDepthRange || fragmentShader->mUsesDepthRange)
{
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.near", 0));
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.far", 0));
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.diff", 0));
}
return success;
}
// Determines the mapping between GL attributes and Direct3D 9 vertex stream usage indices
bool ProgramBinary::linkAttributes(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader)
{
unsigned int usedLocations = 0;
// Link attributes that have a binding location
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
int location = attributeBindings.getAttributeBinding(attribute->name);
if (location != -1) // Set by glBindAttribLocation
{
if (!mLinkedAttribute[location].name.empty())
{
// Multiple active attributes bound to the same location; not an error
}
mLinkedAttribute[location] = *attribute;
int rows = VariableRowCount(attribute->type);
if (rows + location > MAX_VERTEX_ATTRIBS)
{
infoLog.append("Active attribute (%s) at location %d is too big to fit", attribute->name.c_str(), location);
return false;
}
for (int i = 0; i < rows; i++)
{
usedLocations |= 1 << (location + i);
}
}
}
// Link attributes that don't have a binding location
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
int location = attributeBindings.getAttributeBinding(attribute->name);
if (location == -1) // Not set by glBindAttribLocation
{
int rows = VariableRowCount(attribute->type);
int availableIndex = AllocateFirstFreeBits(&usedLocations, rows, MAX_VERTEX_ATTRIBS);
if (availableIndex == -1 || availableIndex + rows > MAX_VERTEX_ATTRIBS)
{
infoLog.append("Too many active attributes (%s)", attribute->name.c_str());
return false; // Fail to link
}
mLinkedAttribute[availableIndex] = *attribute;
}
}
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; )
{
int index = vertexShader->getSemanticIndex(mLinkedAttribute[attributeIndex].name);
int rows = std::max(VariableRowCount(mLinkedAttribute[attributeIndex].type), 1);
for (int r = 0; r < rows; r++)
{
mSemanticIndex[attributeIndex++] = index++;
}
}
return true;
}
bool ProgramBinary::linkUniforms(InfoLog &infoLog, const sh::ActiveUniforms &vertexUniforms, const sh::ActiveUniforms &fragmentUniforms)
{
for (sh::ActiveUniforms::const_iterator uniform = vertexUniforms.begin(); uniform != vertexUniforms.end(); uniform++)
{
if (!defineUniform(GL_VERTEX_SHADER, *uniform, infoLog))
{
return false;
}
}
for (sh::ActiveUniforms::const_iterator uniform = fragmentUniforms.begin(); uniform != fragmentUniforms.end(); uniform++)
{
if (!defineUniform(GL_FRAGMENT_SHADER, *uniform, infoLog))
{
return false;
}
}
return true;
}
bool ProgramBinary::defineUniform(GLenum shader, const sh::Uniform &constant, InfoLog &infoLog)
{
if (constant.type == GL_SAMPLER_2D ||
constant.type == GL_SAMPLER_CUBE)
{
unsigned int samplerIndex = constant.registerIndex;
do
{
if (shader == GL_VERTEX_SHADER)
{
if (samplerIndex < mRenderer->getMaxVertexTextureImageUnits())
{
mSamplersVS[samplerIndex].active = true;
mSamplersVS[samplerIndex].textureType = (constant.type == GL_SAMPLER_CUBE) ? TEXTURE_CUBE : TEXTURE_2D;
mSamplersVS[samplerIndex].logicalTextureUnit = 0;
mUsedVertexSamplerRange = std::max(samplerIndex + 1, mUsedVertexSamplerRange);
}
else
{
infoLog.append("Vertex shader sampler count exceeds the maximum vertex texture units (%d).", mRenderer->getMaxVertexTextureImageUnits());
return false;
}
}
else if (shader == GL_FRAGMENT_SHADER)
{
if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS)
{
mSamplersPS[samplerIndex].active = true;
mSamplersPS[samplerIndex].textureType = (constant.type == GL_SAMPLER_CUBE) ? TEXTURE_CUBE : TEXTURE_2D;
mSamplersPS[samplerIndex].logicalTextureUnit = 0;
mUsedPixelSamplerRange = std::max(samplerIndex + 1, mUsedPixelSamplerRange);
}
else
{
infoLog.append("Pixel shader sampler count exceeds MAX_TEXTURE_IMAGE_UNITS (%d).", MAX_TEXTURE_IMAGE_UNITS);
return false;
}
}
else UNREACHABLE();
samplerIndex++;
}
while (samplerIndex < constant.registerIndex + constant.arraySize);
}
Uniform *uniform = NULL;
GLint location = getUniformLocation(constant.name);
if (location >= 0) // Previously defined, type and precision must match
{
uniform = mUniforms[mUniformIndex[location].index];
if (uniform->type != constant.type)
{
infoLog.append("Types for uniform %s do not match between the vertex and fragment shader", uniform->name.c_str());
return false;
}
if (uniform->precision != constant.precision)
{
infoLog.append("Precisions for uniform %s do not match between the vertex and fragment shader", uniform->name.c_str());
return false;
}
}
else
{
uniform = new Uniform(constant.type, constant.precision, constant.name, constant.arraySize);
}
if (!uniform)
{
return false;
}
if (shader == GL_FRAGMENT_SHADER)
{
uniform->psRegisterIndex = constant.registerIndex;
}
else if (shader == GL_VERTEX_SHADER)
{
uniform->vsRegisterIndex = constant.registerIndex;
}
else UNREACHABLE();
if (location >= 0)
{
return uniform->type == constant.type;
}
mUniforms.push_back(uniform);
unsigned int uniformIndex = mUniforms.size() - 1;
for (unsigned int i = 0; i < uniform->elementCount(); i++)
{
mUniformIndex.push_back(UniformLocation(constant.name, i, uniformIndex));
}
if (shader == GL_VERTEX_SHADER)
{
if (constant.registerIndex + uniform->registerCount > mRenderer->getReservedVertexUniformVectors() + mRenderer->getMaxVertexUniformVectors())
{
infoLog.append("Vertex shader active uniforms exceed GL_MAX_VERTEX_UNIFORM_VECTORS (%u)", mRenderer->getMaxVertexUniformVectors());
return false;
}
}
else if (shader == GL_FRAGMENT_SHADER)
{
if (constant.registerIndex + uniform->registerCount > mRenderer->getReservedFragmentUniformVectors() + mRenderer->getMaxFragmentUniformVectors())
{
infoLog.append("Fragment shader active uniforms exceed GL_MAX_FRAGMENT_UNIFORM_VECTORS (%u)", mRenderer->getMaxFragmentUniformVectors());
return false;
}
}
else UNREACHABLE();
return true;
}
std::string ProgramBinary::generateGeometryShaderHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const
{
// for now we only handle point sprite emulation
ASSERT(usesPointSpriteEmulation());
return generatePointSpriteHLSL(registers, packing, fragmentShader, vertexShader);
}
std::string ProgramBinary::generatePointSpriteHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const
{
ASSERT(registers >= 0);
ASSERT(vertexShader->mUsesPointSize);
ASSERT(mRenderer->getMajorShaderModel() >= 4);
std::string geomHLSL;
std::string varyingSemantic = "TEXCOORD";
std::string fragCoordSemantic;
std::string pointCoordSemantic;
int reservedRegisterIndex = registers;
if (fragmentShader->mUsesFragCoord)
{
fragCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
if (fragmentShader->mUsesPointCoord)
{
pointCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
geomHLSL += "uniform float4 dx_ViewCoords : register(c1);\n"
"\n"
"struct GS_INPUT\n"
"{\n";
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
geomHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
geomHLSL += " float gl_PointSize : PSIZE;\n"
" float4 gl_Position : SV_Position;\n"
"};\n"
"\n"
"struct GS_OUTPUT\n"
"{\n";
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
geomHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (fragmentShader->mUsesPointCoord)
{
geomHLSL += " float2 gl_PointCoord : " + pointCoordSemantic + ";\n";
}
geomHLSL += " float gl_PointSize : PSIZE;\n"
" float4 gl_Position : SV_Position;\n"
"};\n"
"\n"
"static float2 pointSpriteCorners[] = \n"
"{\n"
" float2( 0.5f, -0.5f),\n"
" float2( 0.5f, 0.5f),\n"
" float2(-0.5f, -0.5f),\n"
" float2(-0.5f, 0.5f)\n"
"};\n"
"\n"
"static float2 pointSpriteTexcoords[] = \n"
"{\n"
" float2(1.0f, 1.0f),\n"
" float2(1.0f, 0.0f),\n"
" float2(0.0f, 1.0f),\n"
" float2(0.0f, 0.0f)\n"
"};\n"
"\n"
"static float minPointSize = " + str(ALIASED_POINT_SIZE_RANGE_MIN) + ".0f;\n"
"static float maxPointSize = " + str(mRenderer->getMaxPointSize()) + ".0f;\n"
"\n"
"[maxvertexcount(4)]\n"
"void main(point GS_INPUT input[1], inout TriangleStream<GS_OUTPUT> outStream)\n"
"{\n"
" GS_OUTPUT output = (GS_OUTPUT)0;\n"
" output.gl_PointSize = input[0].gl_PointSize;\n";
for (int r = 0; r < registers; r++)
{
geomHLSL += " output.v" + str(r) + " = input[0].v" + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " output.gl_FragCoord = input[0].gl_FragCoord;\n";
}
geomHLSL += " \n"
" float gl_PointSize = clamp(input[0].gl_PointSize, minPointSize, maxPointSize);\n"
" float4 gl_Position = input[0].gl_Position;\n"
" float2 viewportScale = float2(1.0f / dx_ViewCoords.x, 1.0f / dx_ViewCoords.y) * gl_Position.w;\n";
for (int corner = 0; corner < 4; corner++)
{
geomHLSL += " \n"
" output.gl_Position = gl_Position + float4(pointSpriteCorners[" + str(corner) + "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
if (fragmentShader->mUsesPointCoord)
{
geomHLSL += " output.gl_PointCoord = pointSpriteTexcoords[" + str(corner) + "];\n";
}
geomHLSL += " outStream.Append(output);\n";
}
geomHLSL += " \n"
" outStream.RestartStrip();\n"
"}\n";
return geomHLSL;
}
// This method needs to match OutputHLSL::decorate
std::string ProgramBinary::decorateAttribute(const std::string &name)
{
if (name.compare(0, 3, "gl_") != 0 && name.compare(0, 3, "dx_") != 0)
{
return "_" + name;
}
return name;
}
bool ProgramBinary::isValidated() const
{
return mValidated;
}
void ProgramBinary::getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const
{
// Skip over inactive attributes
unsigned int activeAttribute = 0;
unsigned int attribute;
for (attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
{
if (mLinkedAttribute[attribute].name.empty())
{
continue;
}
if (activeAttribute == index)
{
break;
}
activeAttribute++;
}
if (bufsize > 0)
{
const char *string = mLinkedAttribute[attribute].name.c_str();
strncpy(name, string, bufsize);
name[bufsize - 1] = '\0';
if (length)
{
*length = strlen(name);
}
}
*size = 1; // Always a single 'type' instance
*type = mLinkedAttribute[attribute].type;
}
GLint ProgramBinary::getActiveAttributeCount() const
{
int count = 0;
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
{
if (!mLinkedAttribute[attributeIndex].name.empty())
{
count++;
}
}
return count;
}
GLint ProgramBinary::getActiveAttributeMaxLength() const
{
int maxLength = 0;
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
{
if (!mLinkedAttribute[attributeIndex].name.empty())
{
maxLength = std::max((int)(mLinkedAttribute[attributeIndex].name.length() + 1), maxLength);
}
}
return maxLength;
}
void ProgramBinary::getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const
{
ASSERT(index < mUniforms.size()); // index must be smaller than getActiveUniformCount()
if (bufsize > 0)
{
std::string string = mUniforms[index]->name;
if (mUniforms[index]->isArray())
{
string += "[0]";
}
strncpy(name, string.c_str(), bufsize);
name[bufsize - 1] = '\0';
if (length)
{
*length = strlen(name);
}
}
*size = mUniforms[index]->elementCount();
*type = mUniforms[index]->type;
}
GLint ProgramBinary::getActiveUniformCount() const
{
return mUniforms.size();
}
GLint ProgramBinary::getActiveUniformMaxLength() const
{
int maxLength = 0;
unsigned int numUniforms = mUniforms.size();
for (unsigned int uniformIndex = 0; uniformIndex < numUniforms; uniformIndex++)
{
if (!mUniforms[uniformIndex]->name.empty())
{
int length = (int)(mUniforms[uniformIndex]->name.length() + 1);
if (mUniforms[uniformIndex]->isArray())
{
length += 3; // Counting in "[0]".
}
maxLength = std::max(length, maxLength);
}
}
return maxLength;
}
void ProgramBinary::validate(InfoLog &infoLog)
{
applyUniforms();
if (!validateSamplers(&infoLog))
{
mValidated = false;
}
else
{
mValidated = true;
}
}
bool ProgramBinary::validateSamplers(InfoLog *infoLog)
{
// if any two active samplers in a program are of different types, but refer to the same
// texture image unit, and this is the current program, then ValidateProgram will fail, and
// DrawArrays and DrawElements will issue the INVALID_OPERATION error.
const unsigned int maxCombinedTextureImageUnits = mRenderer->getMaxCombinedTextureImageUnits();
TextureType textureUnitType[IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS];
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++i)
{
textureUnitType[i] = TEXTURE_UNKNOWN;
}
for (unsigned int i = 0; i < mUsedPixelSamplerRange; ++i)
{
if (mSamplersPS[i].active)
{
unsigned int unit = mSamplersPS[i].logicalTextureUnit;
if (unit >= maxCombinedTextureImageUnits)
{
if (infoLog)
{
infoLog->append("Sampler uniform (%d) exceeds IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits);
}
return false;
}
if (textureUnitType[unit] != TEXTURE_UNKNOWN)
{
if (mSamplersPS[i].textureType != textureUnitType[unit])
{
if (infoLog)
{
infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit);
}
return false;
}
}
else
{
textureUnitType[unit] = mSamplersPS[i].textureType;
}
}
}
for (unsigned int i = 0; i < mUsedVertexSamplerRange; ++i)
{
if (mSamplersVS[i].active)
{
unsigned int unit = mSamplersVS[i].logicalTextureUnit;
if (unit >= maxCombinedTextureImageUnits)
{
if (infoLog)
{
infoLog->append("Sampler uniform (%d) exceeds IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits);
}
return false;
}
if (textureUnitType[unit] != TEXTURE_UNKNOWN)
{
if (mSamplersVS[i].textureType != textureUnitType[unit])
{
if (infoLog)
{
infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit);
}
return false;
}
}
else
{
textureUnitType[unit] = mSamplersVS[i].textureType;
}
}
}
return true;
}
ProgramBinary::Sampler::Sampler() : active(false), logicalTextureUnit(0), textureType(TEXTURE_2D)
{
}
struct AttributeSorter
{
AttributeSorter(const int (&semanticIndices)[MAX_VERTEX_ATTRIBS])
: originalIndices(semanticIndices)
{
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
indices[i] = i;
}
std::sort(&indices[0], &indices[MAX_VERTEX_ATTRIBS], *this);
}
bool operator()(int a, int b)
{
return originalIndices[a] == -1 ? false : originalIndices[a] < originalIndices[b];
}
int indices[MAX_VERTEX_ATTRIBS];
const int (&originalIndices)[MAX_VERTEX_ATTRIBS];
};
void ProgramBinary::sortAttributesByLayout(rx::TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS], int sortedSemanticIndices[MAX_VERTEX_ATTRIBS]) const
{
AttributeSorter sorter(mSemanticIndex);
int oldIndices[MAX_VERTEX_ATTRIBS];
rx::TranslatedAttribute oldTranslatedAttributes[MAX_VERTEX_ATTRIBS];
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
oldIndices[i] = mSemanticIndex[i];
oldTranslatedAttributes[i] = attributes[i];
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
int oldIndex = sorter.indices[i];
sortedSemanticIndices[i] = oldIndices[oldIndex];
attributes[i] = oldTranslatedAttributes[oldIndex];
}
}
}
| C++ |
#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.
//
// Image.h: Implements the rx::Image class, an abstract base class for the
// renderer-specific classes which will define the interface to the underlying
// surfaces or resources.
#include "libGLESv2/renderer/Image.h"
namespace rx
{
Image::Image()
{
mWidth = 0;
mHeight = 0;
mInternalFormat = GL_NONE;
mActualFormat = GL_NONE;
}
void Image::loadAlphaDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadAlphaDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width);
}
}
void Image::loadAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadLuminanceDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
if (!native) // BGRA8 destination format
{
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 0xFF;
}
}
else // L8 destination format
{
memcpy(dest, source, width);
}
}
}
void Image::loadLuminanceFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 1.0f;
}
}
}
void Image::loadLuminanceFloatDataToRGB(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[3 * x + 0] = source[x];
dest[3 * x + 1] = source[x];
dest[3 * x + 2] = source[x];
}
}
}
void Image::loadLuminanceHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
}
void Image::loadLuminanceAlphaDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
if (!native) // BGRA8 destination format
{
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
else
{
memcpy(dest, source, width * 2);
}
}
}
void Image::loadLuminanceAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
}
void Image::loadLuminanceAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
}
void Image::loadRGBUByteDataToBGRX(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 2];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 0];
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGBUByteDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGB565DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x001F) << 3) | ((rgba & 0x001F) >> 2);
dest[4 * x + 1] = ((rgba & 0x07E0) >> 3) | ((rgba & 0x07E0) >> 9);
dest[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGB565DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 1] = ((rgba & 0x07E0) >> 3) | ((rgba & 0x07E0) >> 9);
dest[4 * x + 2] = ((rgba & 0x001F) << 3) | ((rgba & 0x001F) >> 2);
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGBFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 1.0f;
}
}
}
void Image::loadRGBFloatDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 12);
}
}
void Image::loadRGBHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
}
void Image::loadRGBAUByteDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned int *source = NULL;
unsigned int *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned int*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
unsigned int rgba = source[x];
dest[x] = (_rotl(rgba, 16) & 0x00ff00ff) | (rgba & 0xff00ff00);
}
}
}
void Image::loadRGBAUByteDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned int *source = NULL;
unsigned int *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned int*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 4);
}
}
void Image::loadRGBA4444DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest[4 * x + 2] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
}
void Image::loadRGBA4444DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest[4 * x + 2] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
}
void Image::loadRGBA5551DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
}
void Image::loadRGBA5551DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest[4 * x + 2] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
}
void Image::loadRGBAFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 16);
}
}
void Image::loadRGBAHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width * 8);
}
}
void Image::loadBGRADataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width*4);
}
}
}
| C++ |
//
// 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.h: Defines the D3D9 VertexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
#define LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
#include "libGLESv2/renderer/VertexBuffer.h"
namespace rx
{
class Renderer9;
class VertexBuffer9 : public VertexBuffer
{
public:
explicit VertexBuffer9(rx::Renderer9 *const renderer);
virtual ~VertexBuffer9();
virtual bool initialize(unsigned int size, bool dynamicUsage);
static VertexBuffer9 *makeVertexBuffer9(VertexBuffer *vertexBuffer);
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;
unsigned int getVertexSize(const gl::VertexAttribute &attrib) const;
D3DDECLTYPE getDeclType(const gl::VertexAttribute &attrib) const;
virtual unsigned int getBufferSize() const;
virtual bool setBufferSize(unsigned int size);
virtual bool discard();
IDirect3DVertexBuffer9 *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(VertexBuffer9);
rx::Renderer9 *const mRenderer;
IDirect3DVertexBuffer9 *mVertexBuffer;
unsigned int mBufferSize;
bool mDynamicUsage;
// Attribute format conversion
enum { NUM_GL_VERTEX_ATTRIB_TYPES = 6 };
struct FormatConverter
{
bool identity;
std::size_t outputElementSize;
void (*convertArray)(const void *in, std::size_t stride, std::size_t n, void *out);
D3DDECLTYPE d3dDeclType;
};
static bool mTranslationsInitialized;
static void initializeTranslations(DWORD declTypes);
// [GL types as enumerated by typeIndex()][normalized][size - 1]
static FormatConverter mFormatConverters[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
struct TranslationDescription
{
DWORD capsFlag;
FormatConverter preferredConversion;
FormatConverter fallbackConversion;
};
// This table is used to generate mFormatConverters.
// [GL types as enumerated by typeIndex()][normalized][size - 1]
static const TranslationDescription mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
static unsigned int typeIndex(GLenum type);
static const FormatConverter &formatConverter(const gl::VertexAttribute &attribute);
static unsigned int spaceRequired(const gl::VertexAttribute &attrib, std::size_t count, GLsizei instances);
};
}
#endif // LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
| C++ |
#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.
//
// InputLayoutCache.cpp: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#include "libGLESv2/renderer/InputLayoutCache.h"
#include "libGLESv2/renderer/VertexBuffer11.h"
#include "libGLESv2/renderer/BufferStorage11.h"
#include "libGLESv2/renderer/ShaderExecutable11.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
const unsigned int InputLayoutCache::kMaxInputLayouts = 1024;
InputLayoutCache::InputLayoutCache() : mInputLayoutMap(kMaxInputLayouts, hashInputLayout, compareInputLayouts)
{
mCounter = 0;
mDevice = NULL;
mDeviceContext = NULL;
}
InputLayoutCache::~InputLayoutCache()
{
clear();
}
void InputLayoutCache::initialize(ID3D11Device *device, ID3D11DeviceContext *context)
{
clear();
mDevice = device;
mDeviceContext = context;
}
void InputLayoutCache::clear()
{
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
i->second.inputLayout->Release();
}
mInputLayoutMap.clear();
}
GLenum InputLayoutCache::applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary)
{
int sortedSemanticIndices[gl::MAX_VERTEX_ATTRIBS];
programBinary->sortAttributesByLayout(attributes, sortedSemanticIndices);
if (!mDevice || !mDeviceContext)
{
ERR("InputLayoutCache is not initialized.");
return GL_INVALID_OPERATION;
}
InputLayoutKey ilKey = { 0 };
ID3D11Buffer *vertexBuffers[gl::MAX_VERTEX_ATTRIBS] = { NULL };
UINT vertexStrides[gl::MAX_VERTEX_ATTRIBS] = { 0 };
UINT vertexOffsets[gl::MAX_VERTEX_ATTRIBS] = { 0 };
static const char* semanticName = "TEXCOORD";
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
VertexBuffer11 *vertexBuffer = VertexBuffer11::makeVertexBuffer11(attributes[i].vertexBuffer);
BufferStorage11 *bufferStorage = attributes[i].storage ? BufferStorage11::makeBufferStorage11(attributes[i].storage) : NULL;
D3D11_INPUT_CLASSIFICATION inputClass = attributes[i].divisor > 0 ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
// Record the type of the associated vertex shader vector in our key
// This will prevent mismatched vertex shaders from using the same input layout
GLint attributeSize;
programBinary->getActiveAttribute(ilKey.elementCount, 0, NULL, &attributeSize, &ilKey.glslElementType[ilKey.elementCount], NULL);
ilKey.elements[ilKey.elementCount].SemanticName = semanticName;
ilKey.elements[ilKey.elementCount].SemanticIndex = sortedSemanticIndices[i];
ilKey.elements[ilKey.elementCount].Format = attributes[i].attribute->mArrayEnabled ? vertexBuffer->getDXGIFormat(*attributes[i].attribute) : DXGI_FORMAT_R32G32B32A32_FLOAT;
ilKey.elements[ilKey.elementCount].InputSlot = i;
ilKey.elements[ilKey.elementCount].AlignedByteOffset = 0;
ilKey.elements[ilKey.elementCount].InputSlotClass = inputClass;
ilKey.elements[ilKey.elementCount].InstanceDataStepRate = attributes[i].divisor;
ilKey.elementCount++;
vertexBuffers[i] = bufferStorage ? bufferStorage->getBuffer() : vertexBuffer->getBuffer();
vertexStrides[i] = attributes[i].stride;
vertexOffsets[i] = attributes[i].offset;
}
}
ID3D11InputLayout *inputLayout = NULL;
InputLayoutMap::iterator i = mInputLayoutMap.find(ilKey);
if (i != mInputLayoutMap.end())
{
inputLayout = i->second.inputLayout;
i->second.lastUsedTime = mCounter++;
}
else
{
ShaderExecutable11 *shader = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutable());
HRESULT result = mDevice->CreateInputLayout(ilKey.elements, ilKey.elementCount, shader->getFunction(), shader->getLength(), &inputLayout);
if (FAILED(result))
{
ERR("Failed to crate input layout, result: 0x%08x", result);
return GL_INVALID_OPERATION;
}
if (mInputLayoutMap.size() >= kMaxInputLayouts)
{
TRACE("Overflowed the limit of %u input layouts, removing the least recently used "
"to make room.", kMaxInputLayouts);
InputLayoutMap::iterator leastRecentlyUsed = mInputLayoutMap.begin();
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
if (i->second.lastUsedTime < leastRecentlyUsed->second.lastUsedTime)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.inputLayout->Release();
mInputLayoutMap.erase(leastRecentlyUsed);
}
InputLayoutCounterPair inputCounterPair;
inputCounterPair.inputLayout = inputLayout;
inputCounterPair.lastUsedTime = mCounter++;
mInputLayoutMap.insert(std::make_pair(ilKey, inputCounterPair));
}
mDeviceContext->IASetInputLayout(inputLayout);
mDeviceContext->IASetVertexBuffers(0, gl::MAX_VERTEX_ATTRIBS, vertexBuffers, vertexStrides, vertexOffsets);
return GL_NO_ERROR;
}
std::size_t InputLayoutCache::hashInputLayout(const InputLayoutKey &inputLayout)
{
static const unsigned int seed = 0xDEADBEEF;
std::size_t hash = 0;
MurmurHash3_x86_32(&inputLayout, sizeof(InputLayoutKey), seed, &hash);
return hash;
}
bool InputLayoutCache::compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b)
{
return memcmp(&a, &b, sizeof(InputLayoutKey)) == 0;
}
}
| C++ |
//
// 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.
//
// Indexffer9.h: Defines the D3D9 IndexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_INDEXBUFFER9_H_
#define LIBGLESV2_RENDERER_INDEXBUFFER9_H_
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
class Renderer9;
class IndexBuffer9 : public IndexBuffer
{
public:
explicit IndexBuffer9(Renderer9 *const renderer);
virtual ~IndexBuffer9();
virtual bool initialize(unsigned int bufferSize, GLenum indexType, bool dynamic);
static IndexBuffer9 *makeIndexBuffer9(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();
D3DFORMAT getIndexFormat() const;
IDirect3DIndexBuffer9 *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(IndexBuffer9);
rx::Renderer9 *const mRenderer;
IDirect3DIndexBuffer9 *mIndexBuffer;
unsigned int mBufferSize;
GLenum mIndexType;
bool mDynamic;
};
}
#endif // LIBGLESV2_RENDERER_INDEXBUFFER9_H_
| C++ |
#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.
//
// VertexBuffer.cpp: Defines the abstract VertexBuffer class and VertexBufferInterface
// class with derivations, classes that perform graphics API agnostic vertex buffer operations.
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Context.h"
namespace rx
{
unsigned int VertexBuffer::mNextSerial = 1;
VertexBuffer::VertexBuffer()
{
updateSerial();
}
VertexBuffer::~VertexBuffer()
{
}
void VertexBuffer::updateSerial()
{
mSerial = mNextSerial++;
}
unsigned int VertexBuffer::getSerial() const
{
return mSerial;
}
VertexBufferInterface::VertexBufferInterface(rx::Renderer *renderer, bool dynamic) : mRenderer(renderer)
{
mDynamic = dynamic;
mWritePosition = 0;
mReservedSpace = 0;
mVertexBuffer = renderer->createVertexBuffer();
}
VertexBufferInterface::~VertexBufferInterface()
{
delete mVertexBuffer;
}
unsigned int VertexBufferInterface::getSerial() const
{
return mVertexBuffer->getSerial();
}
unsigned int VertexBufferInterface::getBufferSize() const
{
return mVertexBuffer->getBufferSize();
}
bool VertexBufferInterface::setBufferSize(unsigned int size)
{
if (mVertexBuffer->getBufferSize() == 0)
{
return mVertexBuffer->initialize(size, mDynamic);
}
else
{
return mVertexBuffer->setBufferSize(size);
}
}
unsigned int VertexBufferInterface::getWritePosition() const
{
return mWritePosition;
}
void VertexBufferInterface::setWritePosition(unsigned int writePosition)
{
mWritePosition = writePosition;
}
bool VertexBufferInterface::discard()
{
return mVertexBuffer->discard();
}
int VertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances)
{
if (!reserveSpace(mReservedSpace))
{
return -1;
}
mReservedSpace = 0;
if (!mVertexBuffer->storeVertexAttributes(attrib, start, count, instances, mWritePosition))
{
return -1;
}
int oldWritePos = static_cast<int>(mWritePosition);
mWritePosition += mVertexBuffer->getSpaceRequired(attrib, count, instances);
return oldWritePos;
}
int VertexBufferInterface::storeRawData(const void* data, unsigned int size)
{
if (!reserveSpace(mReservedSpace))
{
return -1;
}
mReservedSpace = 0;
if (!mVertexBuffer->storeRawData(data, size, mWritePosition))
{
return -1;
}
int oldWritePos = static_cast<int>(mWritePosition);
mWritePosition += size;
return oldWritePos;
}
void VertexBufferInterface::reserveVertexSpace(const gl::VertexAttribute &attribute, GLsizei count, GLsizei instances)
{
mReservedSpace += mVertexBuffer->getSpaceRequired(attribute, count, instances);
}
void VertexBufferInterface::reserveRawDataSpace(unsigned int size)
{
mReservedSpace += size;
}
VertexBuffer* VertexBufferInterface::getVertexBuffer() const
{
return mVertexBuffer;
}
StreamingVertexBufferInterface::StreamingVertexBufferInterface(rx::Renderer *renderer, std::size_t initialSize) : VertexBufferInterface(renderer, true)
{
setBufferSize(initialSize);
}
StreamingVertexBufferInterface::~StreamingVertexBufferInterface()
{
}
bool StreamingVertexBufferInterface::reserveSpace(unsigned int size)
{
bool result = true;
unsigned int curBufferSize = getBufferSize();
if (size > curBufferSize)
{
result = setBufferSize(std::max(size, 3 * curBufferSize / 2));
setWritePosition(0);
}
else if (getWritePosition() + size > curBufferSize)
{
if (!discard())
{
return false;
}
setWritePosition(0);
}
return result;
}
StaticVertexBufferInterface::StaticVertexBufferInterface(rx::Renderer *renderer) : VertexBufferInterface(renderer, false)
{
}
StaticVertexBufferInterface::~StaticVertexBufferInterface()
{
}
int StaticVertexBufferInterface::lookupAttribute(const gl::VertexAttribute &attribute)
{
for (unsigned int element = 0; element < mCache.size(); element++)
{
if (mCache[element].type == attribute.mType &&
mCache[element].size == attribute.mSize &&
mCache[element].stride == attribute.stride() &&
mCache[element].normalized == attribute.mNormalized)
{
if (mCache[element].attributeOffset == attribute.mOffset % attribute.stride())
{
return mCache[element].streamOffset;
}
}
}
return -1;
}
bool StaticVertexBufferInterface::reserveSpace(unsigned int size)
{
unsigned int curSize = getBufferSize();
if (curSize == 0)
{
setBufferSize(size);
return true;
}
else if (curSize >= size)
{
return true;
}
else
{
UNREACHABLE(); // Static vertex buffers can't be resized
return false;
}
}
int StaticVertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances)
{
int attributeOffset = attrib.mOffset % attrib.stride();
VertexElement element = { attrib.mType, attrib.mSize, attrib.stride(), attrib.mNormalized, attributeOffset, getWritePosition() };
mCache.push_back(element);
return VertexBufferInterface::storeVertexAttributes(attrib, start, count, instances);
}
}
| C++ |
//
// 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.h: Defines a back-end specific class that hides the details of the
// implementation-specific renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER_H_
#define LIBGLESV2_RENDERER_RENDERER_H_
#include "libGLESv2/Uniform.h"
#include "libGLESv2/angletypes.h"
#if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL)
#define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3
#endif
const int versionWindowsVista = MAKEWORD(0x00, 0x06);
const int versionWindows7 = MAKEWORD(0x01, 0x06);
// Return the version of the operating system in a format suitable for ordering
// comparison.
inline int getComparableOSVersion()
{
DWORD version = GetVersion();
int majorVersion = LOBYTE(LOWORD(version));
int minorVersion = HIBYTE(LOWORD(version));
return MAKEWORD(minorVersion, majorVersion);
}
namespace egl
{
class Display;
}
namespace gl
{
class InfoLog;
class ProgramBinary;
class VertexAttribute;
class Buffer;
class Texture;
class Framebuffer;
}
namespace rx
{
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class VertexBuffer;
class IndexBuffer;
class QueryImpl;
class FenceImpl;
class BufferStorage;
class Blit;
struct TranslatedIndexData;
class ShaderExecutable;
class SwapChain;
class RenderTarget;
class Image;
class TextureStorage;
typedef void * ShaderBlob;
typedef void (*pCompileFunc)();
struct ConfigDesc
{
GLenum renderTargetFormat;
GLenum depthStencilFormat;
GLint multiSample;
bool fastConfig;
};
struct dx_VertexConstants
{
float depthRange[4];
float viewAdjust[4];
};
struct dx_PixelConstants
{
float depthRange[4];
float viewCoords[4];
float depthFront[4];
};
enum ShaderType
{
SHADER_VERTEX,
SHADER_PIXEL,
SHADER_GEOMETRY
};
class Renderer
{
public:
explicit Renderer(egl::Display *display);
virtual ~Renderer();
virtual EGLint initialize() = 0;
virtual bool resetDevice() = 0;
virtual int generateConfigs(ConfigDesc **configDescList) = 0;
virtual void deleteConfigs(ConfigDesc *configDescList) = 0;
virtual void sync(bool block) = 0;
virtual SwapChain *createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat) = 0;
virtual void setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &sampler) = 0;
virtual void setTexture(gl::SamplerType type, int index, gl::Texture *texture) = 0;
virtual void setRasterizerState(const gl::RasterizerState &rasterState) = 0;
virtual void setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask) = 0;
virtual void setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW) = 0;
virtual void setScissorRectangle(const gl::Rectangle &scissor, bool enabled) = 0;
virtual bool setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport) = 0;
virtual bool applyRenderTarget(gl::Framebuffer *frameBuffer) = 0;
virtual void applyShaders(gl::ProgramBinary *programBinary) = 0;
virtual void applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray) = 0;
virtual bool applyPrimitiveType(GLenum primitiveType, GLsizei elementCount) = 0;
virtual GLenum applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances) = 0;
virtual GLenum applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo) = 0;
virtual void drawArrays(GLenum mode, GLsizei count, GLsizei instances) = 0;
virtual void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances) = 0;
virtual void clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer) = 0;
virtual void markAllStateDirty() = 0;
// lost device
virtual void notifyDeviceLost() = 0;
virtual bool isDeviceLost() = 0;
virtual bool testDeviceLost(bool notify) = 0;
virtual bool testDeviceResettable() = 0;
// Renderer capabilities
virtual DWORD getAdapterVendor() const = 0;
virtual std::string getRendererDescription() const = 0;
virtual GUID getAdapterIdentifier() const = 0;
virtual bool getBGRATextureSupport() const = 0;
virtual bool getDXT1TextureSupport() = 0;
virtual bool getDXT3TextureSupport() = 0;
virtual bool getDXT5TextureSupport() = 0;
virtual bool getEventQuerySupport() = 0;
virtual bool getFloat32TextureSupport(bool *filtering, bool *renderable) = 0;
virtual bool getFloat16TextureSupport(bool *filtering, bool *renderable) = 0;
virtual bool getLuminanceTextureSupport() = 0;
virtual bool getLuminanceAlphaTextureSupport() = 0;
bool getVertexTextureSupport() const { return getMaxVertexTextureImageUnits() > 0; }
virtual unsigned int getMaxVertexTextureImageUnits() const = 0;
virtual unsigned int getMaxCombinedTextureImageUnits() const = 0;
virtual unsigned int getReservedVertexUniformVectors() const = 0;
virtual unsigned int getReservedFragmentUniformVectors() const = 0;
virtual unsigned int getMaxVertexUniformVectors() const = 0;
virtual unsigned int getMaxFragmentUniformVectors() const = 0;
virtual unsigned int getMaxVaryingVectors() const = 0;
virtual bool getNonPower2TextureSupport() const = 0;
virtual bool getDepthTextureSupport() const = 0;
virtual bool getOcclusionQuerySupport() const = 0;
virtual bool getInstancingSupport() const = 0;
virtual bool getTextureFilterAnisotropySupport() const = 0;
virtual float getTextureMaxAnisotropy() const = 0;
virtual bool getShareHandleSupport() const = 0;
virtual bool getDerivativeInstructionSupport() const = 0;
virtual bool getPostSubBufferSupport() const = 0;
virtual int getMajorShaderModel() const = 0;
virtual float getMaxPointSize() const = 0;
virtual int getMaxViewportDimension() const = 0;
virtual int getMaxTextureWidth() const = 0;
virtual int getMaxTextureHeight() const = 0;
virtual bool get32BitIndexSupport() const = 0;
virtual int getMinSwapInterval() const = 0;
virtual int getMaxSwapInterval() const = 0;
virtual GLsizei getMaxSupportedSamples() const = 0;
virtual unsigned int getMaxRenderTargets() const = 0;
// Pixel operations
virtual bool copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source) = 0;
virtual bool copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source) = 0;
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level) = 0;
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level) = 0;
virtual bool blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil) = 0;
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) = 0;
// RenderTarget creation
virtual RenderTarget *createRenderTarget(SwapChain *swapChain, bool depth) = 0;
virtual RenderTarget *createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth) = 0;
// Shader operations
virtual ShaderExecutable *loadExecutable(const void *function, size_t length, rx::ShaderType type) = 0;
virtual ShaderExecutable *compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type) = 0;
// Image operations
virtual Image *createImage() = 0;
virtual void generateMipmap(Image *dest, Image *source) = 0;
virtual TextureStorage *createTextureStorage2D(SwapChain *swapChain) = 0;
virtual TextureStorage *createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height) = 0;
virtual TextureStorage *createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size) = 0;
// Buffer creation
virtual VertexBuffer *createVertexBuffer() = 0;
virtual IndexBuffer *createIndexBuffer() = 0;
virtual BufferStorage *createBufferStorage() = 0;
// Query and Fence creation
virtual QueryImpl *createQuery(GLenum type) = 0;
virtual FenceImpl *createFence() = 0;
virtual bool getLUID(LUID *adapterLuid) const = 0;
protected:
bool initializeCompiler();
ShaderBlob *compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, UINT optimizationFlags, bool alternateFlags);
egl::Display *mDisplay;
private:
DISALLOW_COPY_AND_ASSIGN(Renderer);
HMODULE mD3dCompilerModule;
pCompileFunc mD3DCompileFunc;
};
}
#endif // LIBGLESV2_RENDERER_RENDERER_H_
| C++ |
//
// 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.h: Defines a back-end specific class for the D3D9 renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER9_H_
#define LIBGLESV2_RENDERER_RENDERER9_H_
#include "common/angleutils.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/renderer/ShaderCache.h"
#include "libGLESv2/renderer/VertexDeclarationCache.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/RenderTarget.h"
namespace gl
{
class Renderbuffer;
}
namespace rx
{
class VertexDataManager;
class IndexDataManager;
class StreamingIndexBufferInterface;
struct TranslatedAttribute;
class Renderer9 : public Renderer
{
public:
Renderer9(egl::Display *display, HDC hDc, bool softwareDevice);
virtual ~Renderer9();
static Renderer9 *makeRenderer9(Renderer *renderer);
virtual EGLint initialize();
virtual bool resetDevice();
virtual int generateConfigs(ConfigDesc **configDescList);
virtual void deleteConfigs(ConfigDesc *configDescList);
void startScene();
void endScene();
virtual void sync(bool block);
virtual SwapChain *createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat);
IDirect3DQuery9* allocateEventQuery();
void freeEventQuery(IDirect3DQuery9* query);
// resource creation
IDirect3DVertexShader9 *createVertexShader(const DWORD *function, size_t length);
IDirect3DPixelShader9 *createPixelShader(const DWORD *function, size_t length);
HRESULT createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer);
HRESULT createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer);
#if 0
void *createTexture2D();
void *createTextureCube();
void *createQuery();
void *createIndexBuffer();
void *createVertexbuffer();
// state setup
void applyShaders();
void applyConstants();
#endif
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 applyRenderTarget(gl::Framebuffer *frameBuffer);
virtual void applyShaders(gl::ProgramBinary *programBinary);
virtual void applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray);
virtual bool applyPrimitiveType(GLenum primitiveType, GLsizei elementCount);
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
IDirect3DDevice9 *getDevice() { return mDevice; }
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;
DWORD getCapsDeclTypes() const;
virtual int getMinSwapInterval() const;
virtual int getMaxSwapInterval() const;
virtual GLsizei getMaxSupportedSamples() const;
int getNearestSupportedSamples(D3DFORMAT format, int requested) const;
virtual unsigned int getMaxRenderTargets() const;
D3DFORMAT ConvertTextureInternalFormat(GLint internalformat);
// 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);
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();
// D3D9-renderer specific methods
bool boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest);
D3DPOOL getTexturePool(DWORD usage) const;
virtual bool getLUID(LUID *adapterLuid) const;
private:
DISALLOW_COPY_AND_ASSIGN(Renderer9);
void applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v);
void applyUniformniv(gl::Uniform *targetUniform, const GLint *v);
void applyUniformnbv(gl::Uniform *targetUniform, const GLint *v);
void drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer);
void drawIndexedPoints(GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer);
void getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray);
bool copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged);
gl::Renderbuffer *getNullColorbuffer(gl::Renderbuffer *depthbuffer);
D3DPOOL getBufferPool(DWORD usage) const;
HMODULE mD3d9Module;
HDC mDc;
void initializeDevice();
D3DPRESENT_PARAMETERS getDefaultPresentParameters();
void releaseDeviceResources();
UINT mAdapter;
D3DDEVTYPE mDeviceType;
bool mSoftwareDevice; // FIXME: Deprecate
IDirect3D9 *mD3d9; // Always valid after successful initialization.
IDirect3D9Ex *mD3d9Ex; // Might be null if D3D9Ex is not supported.
IDirect3DDevice9 *mDevice;
IDirect3DDevice9Ex *mDeviceEx; // Might be null if D3D9Ex is not supported.
Blit *mBlit;
HWND mDeviceWindow;
bool mDeviceLost;
D3DCAPS9 mDeviceCaps;
D3DADAPTER_IDENTIFIER9 mAdapterIdentifier;
D3DPRIMITIVETYPE mPrimitiveType;
int mPrimitiveCount;
GLsizei mRepeatDraw;
bool mSceneStarted;
bool mSupportsNonPower2Textures;
bool mSupportsTextureFilterAnisotropy;
int mMinSwapInterval;
int mMaxSwapInterval;
bool mOcclusionQuerySupport;
bool mEventQuerySupport;
bool mVertexTextureSupport;
bool mDepthTextureSupport;
bool mFloat32TextureSupport;
bool mFloat32FilterSupport;
bool mFloat32RenderSupport;
bool mFloat16TextureSupport;
bool mFloat16FilterSupport;
bool mFloat16RenderSupport;
bool mDXT1TextureSupport;
bool mDXT3TextureSupport;
bool mDXT5TextureSupport;
bool mLuminanceTextureSupport;
bool mLuminanceAlphaTextureSupport;
std::map<D3DFORMAT, bool *> mMultiSampleSupport;
GLsizei mMaxSupportedSamples;
// current render target states
unsigned int mAppliedRenderTargetSerial;
unsigned int mAppliedDepthbufferSerial;
unsigned int mAppliedStencilbufferSerial;
bool mDepthStencilInitialized;
bool mRenderTargetDescInitialized;
rx::RenderTarget::Desc mRenderTargetDesc;
unsigned int mCurStencilSize;
unsigned int mCurDepthSize;
IDirect3DStateBlock9 *mMaskedClearSavedState;
// previously set render states
bool mForceSetDepthStencilState;
gl::DepthStencilState mCurDepthStencilState;
int mCurStencilRef;
int mCurStencilBackRef;
bool mCurFrontFaceCCW;
bool mForceSetRasterState;
gl::RasterizerState mCurRasterState;
bool mForceSetScissor;
gl::Rectangle mCurScissor;
bool mScissorEnabled;
bool mForceSetViewport;
gl::Rectangle mCurViewport;
float mCurNear;
float mCurFar;
bool mForceSetBlendState;
gl::BlendState mCurBlendState;
gl::Color mCurBlendColor;
GLuint mCurSampleMask;
// 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];
unsigned int mAppliedIBSerial;
unsigned int mAppliedProgramBinarySerial;
rx::dx_VertexConstants mVertexConstants;
rx::dx_PixelConstants mPixelConstants;
bool mDxUniformsDirty;
// A pool of event queries that are currently unused.
std::vector<IDirect3DQuery9*> mEventQueryPool;
VertexShaderCache mVertexShaderCache;
PixelShaderCache mPixelShaderCache;
VertexDataManager *mVertexDataManager;
VertexDeclarationCache mVertexDeclarationCache;
IndexDataManager *mIndexDataManager;
StreamingIndexBufferInterface *mLineLoopIB;
enum { NUM_NULL_COLORBUFFER_CACHE_ENTRIES = 12 };
struct NullColorbufferCacheEntry
{
UINT lruCount;
int width;
int height;
gl::Renderbuffer *buffer;
} mNullColorbufferCache[NUM_NULL_COLORBUFFER_CACHE_ENTRIES];
UINT mMaxNullColorbufferLRU;
};
}
#endif // LIBGLESV2_RENDERER_RENDERER9_H_
| C++ |
//
// 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.h: Defines the rx::Image9 class, which acts as the interface to
// the actual underlying surfaces of a Texture.
#ifndef LIBGLESV2_RENDERER_IMAGE9_H_
#define LIBGLESV2_RENDERER_IMAGE9_H_
#include "libGLESv2/renderer/Image.h"
#include "common/debug.h"
namespace gl
{
class Framebuffer;
}
namespace rx
{
class Renderer;
class Renderer9;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class Image9 : public Image
{
public:
Image9();
~Image9();
static Image9 *makeImage9(Image *img);
static void generateMipmap(Image9 *dest, Image9 *source);
static void generateMip(IDirect3DSurface9 *destSurface, IDirect3DSurface9 *sourceSurface);
static void copyLockableSurfaces(IDirect3DSurface9 *dest, IDirect3DSurface9 *source);
virtual bool redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease);
virtual bool isRenderableFormat() const;
D3DFORMAT getD3DFormat() const;
virtual bool isDirty() const {return mSurface && mDirty;}
IDirect3DSurface9 *getSurface();
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);
virtual bool updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
virtual void loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input);
virtual void loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input);
virtual void copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source);
private:
DISALLOW_COPY_AND_ASSIGN(Image9);
void createSurface();
void setManagedSurface(IDirect3DSurface9 *surface);
bool updateSurface(IDirect3DSurface9 *dest, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
HRESULT lock(D3DLOCKED_RECT *lockedRect, const RECT *rect);
void unlock();
Renderer9 *mRenderer;
D3DPOOL mD3DPool; // can only be D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED since it needs to be lockable.
D3DFORMAT mD3DFormat;
IDirect3DSurface9 *mSurface;
};
}
#endif // LIBGLESV2_RENDERER_IMAGE9_H_
| C++ |
//
// 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.
#ifndef LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
#define LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
#include "libGLESv2/Constants.h"
#include "common/angleutils.h"
namespace gl
{
class VertexAttribute;
class ProgramBinary;
}
namespace rx
{
class BufferStorage;
class StreamingVertexBufferInterface;
class VertexBuffer;
class Renderer;
struct TranslatedAttribute
{
bool active;
const gl::VertexAttribute *attribute;
UINT offset;
UINT stride; // 0 means not to advance the read pointer at all
VertexBuffer *vertexBuffer;
BufferStorage *storage;
unsigned int serial;
unsigned int divisor;
};
class VertexDataManager
{
public:
VertexDataManager(rx::Renderer *renderer);
virtual ~VertexDataManager();
GLenum prepareVertexData(const gl::VertexAttribute attribs[], gl::ProgramBinary *programBinary, GLint start, GLsizei count, TranslatedAttribute *outAttribs, GLsizei instances);
private:
DISALLOW_COPY_AND_ASSIGN(VertexDataManager);
rx::Renderer *const mRenderer;
StreamingVertexBufferInterface *mStreamingBuffer;
float mCurrentValue[gl::MAX_VERTEX_ATTRIBS][4];
StreamingVertexBufferInterface *mCurrentValueBuffer[gl::MAX_VERTEX_ATTRIBS];
std::size_t mCurrentValueOffsets[gl::MAX_VERTEX_ATTRIBS];
};
}
#endif // LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
| C++ |
//
// 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.
//
// TextureStorage.h: Defines the abstract rx::TextureStorageInterface class and its concrete derived
// classes TextureStorageInterface2D and TextureStorageInterfaceCube, which act as the interface to the
// GPU-side texture.
#ifndef LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
#define LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
#include "common/debug.h"
namespace rx
{
class Renderer;
class SwapChain;
class RenderTarget;
class Blit;
class TextureStorage
{
public:
TextureStorage() {};
virtual ~TextureStorage() {};
virtual int getLodOffset() const = 0;
virtual bool isRenderTarget() const = 0;
virtual bool isManaged() const = 0;
virtual int levelCount() = 0;
virtual RenderTarget *getRenderTarget() = 0;
virtual RenderTarget *getRenderTarget(GLenum faceTarget) = 0;
virtual void generateMipmap(int level) = 0;
virtual void generateMipmap(int face, int level) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage);
};
class TextureStorageInterface
{
public:
TextureStorageInterface();
virtual ~TextureStorageInterface();
TextureStorage *getStorageInstance() { return mInstance; }
unsigned int getTextureSerial() const;
virtual unsigned int getRenderTargetSerial(GLenum target) const = 0;
virtual int getLodOffset() const;
virtual bool isRenderTarget() const;
virtual bool isManaged() const;
virtual int levelCount();
protected:
TextureStorage *mInstance;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterface);
const unsigned int mTextureSerial;
static unsigned int issueTextureSerial();
static unsigned int mCurrentTextureSerial;
};
class TextureStorageInterface2D : public TextureStorageInterface
{
public:
TextureStorageInterface2D(Renderer *renderer, SwapChain *swapchain);
TextureStorageInterface2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual ~TextureStorageInterface2D();
void generateMipmap(int level);
RenderTarget *getRenderTarget() const;
virtual unsigned int getRenderTargetSerial(GLenum target) const;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterface2D);
const unsigned int mRenderTargetSerial;
};
class TextureStorageInterfaceCube : public TextureStorageInterface
{
public:
TextureStorageInterfaceCube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
virtual ~TextureStorageInterfaceCube();
void generateMipmap(int face, int level);
RenderTarget *getRenderTarget(GLenum faceTarget) const;
virtual unsigned int getRenderTargetSerial(GLenum target) const;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterfaceCube);
const unsigned int mFirstRenderTargetSerial;
};
}
#endif // LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
| C++ |
#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.
//
// Image11.h: Implements the rx::Image11 class, which acts as the interface to
// the actual underlying resources of a Texture
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/Image11.h"
#include "libGLESv2/renderer/TextureStorage11.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/renderer/generatemip.h"
namespace rx
{
Image11::Image11()
{
mStagingTexture = NULL;
mRenderer = NULL;
mDXGIFormat = DXGI_FORMAT_UNKNOWN;
}
Image11::~Image11()
{
if (mStagingTexture)
{
mStagingTexture->Release();
}
}
Image11 *Image11::makeImage11(Image *img)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Image11*, img));
return static_cast<rx::Image11*>(img);
}
void Image11::generateMipmap(Image11 *dest, Image11 *src)
{
ASSERT(src->getDXGIFormat() == dest->getDXGIFormat());
ASSERT(src->getWidth() == 1 || src->getWidth() / 2 == dest->getWidth());
ASSERT(src->getHeight() == 1 || src->getHeight() / 2 == dest->getHeight());
D3D11_MAPPED_SUBRESOURCE destMapped, srcMapped;
dest->map(&destMapped);
src->map(&srcMapped);
const unsigned char *sourceData = reinterpret_cast<const unsigned char*>(srcMapped.pData);
unsigned char *destData = reinterpret_cast<unsigned char*>(destMapped.pData);
if (sourceData && destData)
{
switch (src->getDXGIFormat())
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM:
GenerateMip<R8G8B8A8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_A8_UNORM:
GenerateMip<A8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R8_UNORM:
GenerateMip<R8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
GenerateMip<A32B32G32R32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32B32_FLOAT:
GenerateMip<R32G32B32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
GenerateMip<A16B16G16R16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R8G8_UNORM:
GenerateMip<R8G8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16_FLOAT:
GenerateMip<R16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16G16_FLOAT:
GenerateMip<R16G16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32_FLOAT:
GenerateMip<R32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32_FLOAT:
GenerateMip<R32G32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
default:
UNREACHABLE();
break;
}
dest->unmap();
src->unmap();
}
dest->markDirty();
}
bool Image11::isDirty() const
{
return (mStagingTexture && mDirty);
}
bool Image11::updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
TextureStorage11_2D *storage11 = TextureStorage11_2D::makeTextureStorage11_2D(storage->getStorageInstance());
return storage11->updateSubresourceLevel(getStagingTexture(), getStagingSubresource(), level, 0, xoffset, yoffset, width, height);
}
bool Image11::updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
TextureStorage11_Cube *storage11 = TextureStorage11_Cube::makeTextureStorage11_Cube(storage->getStorageInstance());
return storage11->updateSubresourceLevel(getStagingTexture(), getStagingSubresource(), level, face, xoffset, yoffset, width, height);
}
bool Image11::redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease)
{
if (mWidth != width ||
mHeight != height ||
mInternalFormat != internalformat ||
forceRelease)
{
mRenderer = Renderer11::makeRenderer11(renderer);
mWidth = width;
mHeight = height;
mInternalFormat = internalformat;
// compute the d3d format that will be used
mDXGIFormat = gl_d3d11::ConvertTextureFormat(internalformat);
mActualFormat = d3d11_gl::ConvertTextureInternalFormat(mDXGIFormat);
if (mStagingTexture)
{
mStagingTexture->Release();
mStagingTexture = NULL;
}
return true;
}
return false;
}
bool Image11::isRenderableFormat() const
{
return TextureStorage11::IsTextureFormatRenderable(mDXGIFormat);
}
DXGI_FORMAT Image11::getDXGIFormat() const
{
// this should only happen if the image hasn't been redefined first
// which would be a bug by the caller
ASSERT(mDXGIFormat != DXGI_FORMAT_UNKNOWN);
return mDXGIFormat;
}
// Store the pixel rectangle designated by xoffset,yoffset,width,height with pixels stored as format/type at input
// into the target pixel rectangle.
void Image11::loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input)
{
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
if (FAILED(result))
{
ERR("Could not map image for loading.");
return;
}
GLsizei inputPitch = gl::ComputePitch(width, mInternalFormat, unpackAlignment);
size_t pixelSize = d3d11::ComputePixelSizeBits(mDXGIFormat) / 8;
void* offsetMappedData = (void*)((BYTE *)mappedImage.pData + (yoffset * mappedImage.RowPitch + xoffset * pixelSize));
switch (mInternalFormat)
{
case GL_ALPHA8_EXT:
loadAlphaDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE8_EXT:
loadLuminanceDataToNativeOrBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData, false);
break;
case GL_ALPHA32F_EXT:
loadAlphaFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE32F_EXT:
loadLuminanceFloatDataToRGB(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_ALPHA16F_EXT:
loadAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE16F_EXT:
loadLuminanceHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE8_ALPHA8_EXT:
loadLuminanceAlphaDataToNativeOrBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData, false);
break;
case GL_LUMINANCE_ALPHA32F_EXT:
loadLuminanceAlphaFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE_ALPHA16F_EXT:
loadLuminanceAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB8_OES:
loadRGBUByteDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB565:
loadRGB565DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA8_OES:
loadRGBAUByteDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA4:
loadRGBA4444DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB5_A1:
loadRGBA5551DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_BGRA8_EXT:
loadBGRADataToBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB32F_EXT:
loadRGBFloatDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB16F_EXT:
loadRGBHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA32F_EXT:
loadRGBAFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA16F_EXT:
loadRGBAHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
default: UNREACHABLE();
}
unmap();
}
void Image11::loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input)
{
ASSERT(xoffset % 4 == 0);
ASSERT(yoffset % 4 == 0);
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
if (FAILED(result))
{
ERR("Could not map image for loading.");
return;
}
// Size computation assumes a 4x4 block compressed texture format
size_t blockSize = d3d11::ComputeBlockSizeBits(mDXGIFormat) / 8;
void* offsetMappedData = (void*)((BYTE *)mappedImage.pData + ((yoffset / 4) * mappedImage.RowPitch + (xoffset / 4) * blockSize));
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*)offsetMappedData + i * mappedImage.RowPitch), (void*)((BYTE*)input + i * inputPitch), inputPitch);
}
unmap();
}
void Image11::copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source)
{
gl::Renderbuffer *colorbuffer = source->getReadColorbuffer();
if (colorbuffer && colorbuffer->getActualFormat() == (GLuint)mActualFormat)
{
// No conversion needed-- use copyback fastpath
ID3D11Texture2D *colorBufferTexture = NULL;
unsigned int subresourceIndex = 0;
if (mRenderer->getRenderTargetResource(colorbuffer, &subresourceIndex, &colorBufferTexture))
{
D3D11_TEXTURE2D_DESC textureDesc;
colorBufferTexture->GetDesc(&textureDesc);
ID3D11Device *device = mRenderer->getDevice();
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
ID3D11Texture2D* srcTex = NULL;
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = D3D11_USAGE_DEFAULT;
resolveDesc.BindFlags = 0;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
HRESULT result = device->CreateTexture2D(&resolveDesc, NULL, &srcTex);
if (FAILED(result))
{
ERR("Failed to create resolve texture for Image11::copy, HRESULT: 0x%X.", result);
return;
}
deviceContext->ResolveSubresource(srcTex, 0, colorBufferTexture, subresourceIndex, textureDesc.Format);
subresourceIndex = 0;
}
else
{
srcTex = colorBufferTexture;
srcTex->AddRef();
}
D3D11_BOX srcBox;
srcBox.left = x;
srcBox.right = x + width;
srcBox.top = y;
srcBox.bottom = y + height;
srcBox.front = 0;
srcBox.back = 1;
deviceContext->CopySubresourceRegion(mStagingTexture, 0, xoffset, yoffset, 0, srcTex, subresourceIndex, &srcBox);
srcTex->Release();
colorBufferTexture->Release();
}
}
else
{
// This format requires conversion, so we must copy the texture to staging and manually convert via readPixels
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
// determine the offset coordinate into the destination buffer
GLsizei rowOffset = gl::ComputePixelSize(mActualFormat) * xoffset;
void *dataOffset = static_cast<unsigned char*>(mappedImage.pData) + mappedImage.RowPitch * yoffset + rowOffset;
mRenderer->readPixels(source, x, y, width, height, gl::ExtractFormat(mInternalFormat),
gl::ExtractType(mInternalFormat), mappedImage.RowPitch, false, 4, dataOffset);
unmap();
}
}
ID3D11Texture2D *Image11::getStagingTexture()
{
createStagingTexture();
return mStagingTexture;
}
unsigned int Image11::getStagingSubresource()
{
createStagingTexture();
return mStagingSubresource;
}
void Image11::createStagingTexture()
{
if (mStagingTexture)
{
return;
}
ID3D11Texture2D *newTexture = NULL;
int lodOffset = 1;
const DXGI_FORMAT dxgiFormat = getDXGIFormat();
ASSERT(!d3d11::IsDepthStencilFormat(dxgiFormat)); // We should never get here for depth textures
if (mWidth != 0 && mHeight != 0)
{
GLsizei width = mWidth;
GLsizei height = mHeight;
// adjust size if needed for compressed textures
gl::MakeValidSize(false, d3d11::IsCompressed(dxgiFormat), &width, &height, &lodOffset);
ID3D11Device *device = mRenderer->getDevice();
D3D11_TEXTURE2D_DESC desc;
desc.Width = width;
desc.Height = height;
desc.MipLevels = lodOffset + 1;
desc.ArraySize = 1;
desc.Format = dxgiFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
HRESULT result = device->CreateTexture2D(&desc, NULL, &newTexture);
if (FAILED(result))
{
ASSERT(result == E_OUTOFMEMORY);
ERR("Creating image failed.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
mStagingTexture = newTexture;
mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
mDirty = false;
}
HRESULT Image11::map(D3D11_MAPPED_SUBRESOURCE *map)
{
createStagingTexture();
HRESULT result = E_FAIL;
if (mStagingTexture)
{
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
result = deviceContext->Map(mStagingTexture, mStagingSubresource, D3D11_MAP_WRITE, 0, map);
// this can fail if the device is removed (from TDR)
if (d3d11::isDeviceLostError(result))
{
mRenderer->notifyDeviceLost();
}
else if (SUCCEEDED(result))
{
mDirty = true;
}
}
return result;
}
void Image11::unmap()
{
if (mStagingTexture)
{
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
deviceContext->Unmap(mStagingTexture, mStagingSubresource);
}
}
}
| C++ |
//
// 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.
//
// ShaderExecutable11.h: Defines a D3D11-specific class to contain shader
// executable implementation details.
#ifndef LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
#define LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
#include "libGLESv2/renderer/ShaderExecutable.h"
namespace rx
{
class ShaderExecutable11 : public ShaderExecutable
{
public:
ShaderExecutable11(const void *function, size_t length, ID3D11PixelShader *executable);
ShaderExecutable11(const void *function, size_t length, ID3D11VertexShader *executable);
ShaderExecutable11(const void *function, size_t length, ID3D11GeometryShader *executable);
virtual ~ShaderExecutable11();
static ShaderExecutable11 *makeShaderExecutable11(ShaderExecutable *executable);
ID3D11PixelShader *getPixelShader() const;
ID3D11VertexShader *getVertexShader() const;
ID3D11GeometryShader *getGeometryShader() const;
ID3D11Buffer *getConstantBuffer(ID3D11Device *device, unsigned int registerCount);
private:
DISALLOW_COPY_AND_ASSIGN(ShaderExecutable11);
ID3D11PixelShader *mPixelExecutable;
ID3D11VertexShader *mVertexExecutable;
ID3D11GeometryShader *mGeometryExecutable;
ID3D11Buffer *mConstantBuffer;
};
}
#endif // LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
| C++ |
#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.
//
// Query9.cpp: Defines the rx::Query9 class which implements rx::QueryImpl.
#include "libGLESv2/renderer/Query9.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/Renderer9.h"
namespace rx
{
Query9::Query9(rx::Renderer9 *renderer, GLenum type) : QueryImpl(type)
{
mRenderer = renderer;
mQuery = NULL;
}
Query9::~Query9()
{
if (mQuery)
{
mQuery->Release();
mQuery = NULL;
}
}
void Query9::begin()
{
if (mQuery == NULL)
{
if (FAILED(mRenderer->getDevice()->CreateQuery(D3DQUERYTYPE_OCCLUSION, &mQuery)))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
HRESULT result = mQuery->Issue(D3DISSUE_BEGIN);
ASSERT(SUCCEEDED(result));
}
void Query9::end()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
HRESULT result = mQuery->Issue(D3DISSUE_END);
ASSERT(SUCCEEDED(result));
mStatus = GL_FALSE;
mResult = GL_FALSE;
}
GLuint Query9::getResult()
{
if (mQuery != NULL)
{
while (!testQuery())
{
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 (mRenderer->testDeviceLost(true))
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
}
}
return mResult;
}
GLboolean Query9::isResultAvailable()
{
if (mQuery != NULL)
{
testQuery();
}
return mStatus;
}
GLboolean Query9::testQuery()
{
if (mQuery != NULL && mStatus != GL_TRUE)
{
DWORD numPixels = 0;
HRESULT hres = mQuery->GetData(&numPixels, sizeof(DWORD), D3DGETDATA_FLUSH);
if (hres == 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:
ASSERT(false);
}
}
else if (d3d9::isDeviceLostError(hres))
{
mRenderer->notifyDeviceLost();
return gl::error(GL_OUT_OF_MEMORY, GL_TRUE);
}
return mStatus;
}
return GL_TRUE; // prevent blocking when query is null
}
}
| C++ |
//
// 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.h Defines the BufferStorage11 class.
#ifndef LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
#define LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
#include "libGLESv2/renderer/BufferStorage.h"
namespace rx
{
class Renderer11;
class BufferStorage11 : public BufferStorage
{
public:
explicit BufferStorage11(Renderer11 *renderer);
virtual ~BufferStorage11();
static BufferStorage11 *makeBufferStorage11(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;
virtual void markBufferUsage();
ID3D11Buffer *getBuffer() const;
private:
Renderer11 *mRenderer;
ID3D11Buffer *mStagingBuffer;
unsigned int mStagingBufferSize;
ID3D11Buffer *mBuffer;
unsigned int mBufferSize;
unsigned int mSize;
void *mResolvedData;
unsigned int mResolvedDataSize;
bool mResolvedDataValid;
unsigned int mReadUsageCount;
unsigned int mWriteUsageCount;
};
}
#endif // LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.