aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/gpu/gl
diff options
context:
space:
mode:
Diffstat (limited to 'src/gpu/gl')
-rw-r--r--src/gpu/gl/GrGLEffect.h2
-rw-r--r--src/gpu/gl/GrGLProgram.cpp9
-rw-r--r--src/gpu/gl/GrGLProgram.h8
-rw-r--r--src/gpu/gl/GrGLProgramDataManager.cpp10
-rw-r--r--src/gpu/gl/GrGLProgramDataManager.h6
-rw-r--r--src/gpu/gl/GrGLProgramDesc.cpp9
-rw-r--r--src/gpu/gl/GrGLProgramDesc.h9
-rw-r--r--src/gpu/gl/GrGLProgramEffects.cpp66
-rw-r--r--src/gpu/gl/GrGLProgramEffects.h54
-rw-r--r--src/gpu/gl/GrGLShaderBuilder.cpp1071
-rw-r--r--src/gpu/gl/GrGLVertexEffect.h8
-rw-r--r--src/gpu/gl/GrGpuGL.cpp1
-rw-r--r--src/gpu/gl/builders/GrGLFragmentShaderBuilder.cpp351
-rw-r--r--src/gpu/gl/builders/GrGLFragmentShaderBuilder.h118
-rw-r--r--src/gpu/gl/builders/GrGLGeometryShaderBuilder.cpp70
-rw-r--r--src/gpu/gl/builders/GrGLGeometryShaderBuilder.h32
-rw-r--r--src/gpu/gl/builders/GrGLProgramBuilder.cpp409
-rw-r--r--src/gpu/gl/builders/GrGLProgramBuilder.h (renamed from src/gpu/gl/GrGLShaderBuilder.h)253
-rw-r--r--src/gpu/gl/builders/GrGLSLPrettyPrint.cpp (renamed from src/gpu/gl/GrGLSLPrettyPrint.cpp)0
-rw-r--r--src/gpu/gl/builders/GrGLShaderBuilder.cpp155
-rw-r--r--src/gpu/gl/builders/GrGLShaderBuilder.h170
-rw-r--r--src/gpu/gl/builders/GrGLShaderStringBuilder.cpp85
-rw-r--r--src/gpu/gl/builders/GrGLShaderStringBuilder.h20
-rw-r--r--src/gpu/gl/builders/GrGLVertexShaderBuilder.cpp200
-rw-r--r--src/gpu/gl/builders/GrGLVertexShaderBuilder.h81
25 files changed, 1803 insertions, 1394 deletions
diff --git a/src/gpu/gl/GrGLEffect.h b/src/gpu/gl/GrGLEffect.h
index 18b3002edf..88aa4cdd1c 100644
--- a/src/gpu/gl/GrGLEffect.h
+++ b/src/gpu/gl/GrGLEffect.h
@@ -68,7 +68,7 @@ public:
GrGLEffect. These can be passed to the builder to emit texture
reads in the generated code.
*/
- virtual void emitCode(GrGLShaderBuilder* builder,
+ virtual void emitCode(GrGLProgramBuilder* builder,
const GrDrawEffect& drawEffect,
const GrEffectKey& key,
const char* outputColor,
diff --git a/src/gpu/gl/GrGLProgram.cpp b/src/gpu/gl/GrGLProgram.cpp
index d8c751d71d..d49d000fe3 100644
--- a/src/gpu/gl/GrGLProgram.cpp
+++ b/src/gpu/gl/GrGLProgram.cpp
@@ -24,13 +24,12 @@ GrGLProgram* GrGLProgram::Create(GrGpuGL* gpu,
const GrGLProgramDesc& desc,
const GrEffectStage* colorStages[],
const GrEffectStage* coverageStages[]) {
- SkAutoTDelete<GrGLShaderBuilder> builder;
+ SkAutoTDelete<GrGLProgramBuilder> builder;
if (desc.getHeader().fHasVertexCode ||!gpu->shouldUseFixedFunctionTexturing()) {
- builder.reset(SkNEW_ARGS(GrGLFullShaderBuilder, (gpu, desc)));
+ builder.reset(SkNEW_ARGS(GrGLFullProgramBuilder, (gpu, desc)));
} else {
- builder.reset(SkNEW_ARGS(GrGLFragmentOnlyShaderBuilder, (gpu, desc)));
+ builder.reset(SkNEW_ARGS(GrGLFragmentOnlyProgramBuilder, (gpu, desc)));
}
-
if (builder->genProgram(colorStages, coverageStages)) {
SkASSERT(0 != builder->getProgramID());
return SkNEW_ARGS(GrGLProgram, (gpu, desc, *builder));
@@ -40,7 +39,7 @@ GrGLProgram* GrGLProgram::Create(GrGpuGL* gpu,
GrGLProgram::GrGLProgram(GrGpuGL* gpu,
const GrGLProgramDesc& desc,
- const GrGLShaderBuilder& builder)
+ const GrGLProgramBuilder& builder)
: fColor(GrColor_ILLEGAL)
, fCoverage(GrColor_ILLEGAL)
, fDstCopyTexUnit(-1)
diff --git a/src/gpu/gl/GrGLProgram.h b/src/gpu/gl/GrGLProgram.h
index fb496856b4..7af55f10ee 100644
--- a/src/gpu/gl/GrGLProgram.h
+++ b/src/gpu/gl/GrGLProgram.h
@@ -9,10 +9,10 @@
#ifndef GrGLProgram_DEFINED
#define GrGLProgram_DEFINED
+#include "builders/GrGLProgramBuilder.h"
#include "GrDrawState.h"
#include "GrGLContext.h"
#include "GrGLProgramDesc.h"
-#include "GrGLShaderBuilder.h"
#include "GrGLSL.h"
#include "GrGLTexture.h"
#include "GrGLProgramDataManager.h"
@@ -22,7 +22,7 @@
class GrGLEffect;
class GrGLProgramEffects;
-class GrGLShaderBuilder;
+class GrGLProgramBuilder;
/**
* This class manages a GPU program and records per-program information.
@@ -37,7 +37,7 @@ class GrGLProgram : public SkRefCnt {
public:
SK_DECLARE_INST_COUNT(GrGLProgram)
- typedef GrGLShaderBuilder::BuiltinUniformHandles BuiltinUniformHandles;
+ typedef GrGLProgramBuilder::BuiltinUniformHandles BuiltinUniformHandles;
static GrGLProgram* Create(GrGpuGL* gpu,
const GrGLProgramDesc& desc,
@@ -167,7 +167,7 @@ private:
GrGLProgram(GrGpuGL*,
const GrGLProgramDesc&,
- const GrGLShaderBuilder&);
+ const GrGLProgramBuilder&);
// Sets the texture units for samplers.
void initSamplerUniforms();
diff --git a/src/gpu/gl/GrGLProgramDataManager.cpp b/src/gpu/gl/GrGLProgramDataManager.cpp
index c4c51933c7..eed9d1935d 100644
--- a/src/gpu/gl/GrGLProgramDataManager.cpp
+++ b/src/gpu/gl/GrGLProgramDataManager.cpp
@@ -5,7 +5,7 @@
* found in the LICENSE file.
*/
-#include "gl/GrGLShaderBuilder.h"
+#include "gl/builders/GrGLProgramBuilder.h"
#include "gl/GrGLProgram.h"
#include "gl/GrGLUniformHandle.h"
#include "gl/GrGpuGL.h"
@@ -17,13 +17,13 @@
GrGLProgramDataManager::GrGLProgramDataManager(GrGpuGL* gpu,
GrGLProgram*,
- const GrGLShaderBuilder& builder)
+ const GrGLProgramBuilder& builder)
: fGpu(gpu) {
int count = builder.getUniformInfos().count();
fUniforms.push_back_n(count);
for (int i = 0; i < count; i++) {
Uniform& uniform = fUniforms[i];
- const GrGLShaderBuilder::UniformInfo& builderUniform = builder.getUniformInfos()[i];
+ const GrGLProgramBuilder::UniformInfo& builderUniform = builder.getUniformInfos()[i];
SkASSERT(GrGLShaderVar::kNonArray == builderUniform.fVariable.getArrayCount() ||
builderUniform.fVariable.getArrayCount() > 0);
SkDEBUGCODE(
@@ -32,12 +32,12 @@ GrGLProgramDataManager::GrGLProgramDataManager(GrGpuGL* gpu,
);
// TODO: Move the Xoom uniform array in both FS and VS bug workaround here.
- if (GrGLShaderBuilder::kVertex_Visibility & builderUniform.fVisibility) {
+ if (GrGLProgramBuilder::kVertex_Visibility & builderUniform.fVisibility) {
uniform.fVSLocation = builderUniform.fLocation;
} else {
uniform.fVSLocation = kUnusedUniform;
}
- if (GrGLShaderBuilder::kFragment_Visibility & builderUniform.fVisibility) {
+ if (GrGLProgramBuilder::kFragment_Visibility & builderUniform.fVisibility) {
uniform.fFSLocation = builderUniform.fLocation;
} else {
uniform.fFSLocation = kUnusedUniform;
diff --git a/src/gpu/gl/GrGLProgramDataManager.h b/src/gpu/gl/GrGLProgramDataManager.h
index 8ef4a41fbc..3082f6f02b 100644
--- a/src/gpu/gl/GrGLProgramDataManager.h
+++ b/src/gpu/gl/GrGLProgramDataManager.h
@@ -17,7 +17,7 @@
class GrGpuGL;
class SkMatrix;
class GrGLProgram;
-class GrGLShaderBuilder;
+class GrGLProgramBuilder;
/** Manages the resources used by a shader program.
* The resources are objects the program uses to communicate with the
@@ -51,10 +51,10 @@ public:
int fValue;
friend class GrGLProgramDataManager; // For accessing toProgramDataIndex().
- friend class GrGLShaderBuilder; // For accessing toShaderBuilderIndex().
+ friend class GrGLProgramBuilder; // For accessing toShaderBuilderIndex().
};
- GrGLProgramDataManager(GrGpuGL*, GrGLProgram*, const GrGLShaderBuilder&);
+ GrGLProgramDataManager(GrGpuGL*, GrGLProgram*, const GrGLProgramBuilder&);
/** Functions for uploading uniform values. The varities ending in v can be used to upload to an
* array of uniforms. arrayCount must be <= the array count of the uniform.
diff --git a/src/gpu/gl/GrGLProgramDesc.cpp b/src/gpu/gl/GrGLProgramDesc.cpp
index e1a319104d..7cdbcd0efc 100644
--- a/src/gpu/gl/GrGLProgramDesc.cpp
+++ b/src/gpu/gl/GrGLProgramDesc.cpp
@@ -5,11 +5,11 @@
* found in the LICENSE file.
*/
+#include "gl/builders/GrGLProgramBuilder.h"
#include "GrGLProgramDesc.h"
#include "GrBackendEffectFactory.h"
#include "GrDrawEffect.h"
#include "GrEffect.h"
-#include "GrGLShaderBuilder.h"
#include "GrGpuGL.h"
#include "SkChecksum.h"
@@ -212,15 +212,16 @@ bool GrGLProgramDesc::Build(const GrDrawState& drawState,
if (NULL != dstCopy) {
dstCopyTexture = dstCopy->texture();
}
- header->fDstReadKey = GrGLShaderBuilder::KeyForDstRead(dstCopyTexture, gpu->glCaps());
+ header->fDstReadKey = GrGLFragmentShaderBuilder::KeyForDstRead(dstCopyTexture,
+ gpu->glCaps());
SkASSERT(0 != header->fDstReadKey);
} else {
header->fDstReadKey = 0;
}
if (readFragPosition) {
- header->fFragPosKey = GrGLShaderBuilder::KeyForFragmentPosition(drawState.getRenderTarget(),
- gpu->glCaps());
+ header->fFragPosKey = GrGLFragmentShaderBuilder::KeyForFragmentPosition(
+ drawState.getRenderTarget(), gpu->glCaps());
} else {
header->fFragPosKey = 0;
}
diff --git a/src/gpu/gl/GrGLProgramDesc.h b/src/gpu/gl/GrGLProgramDesc.h
index cccdee9ce2..e8925d0c5c 100644
--- a/src/gpu/gl/GrGLProgramDesc.h
+++ b/src/gpu/gl/GrGLProgramDesc.h
@@ -252,9 +252,12 @@ private:
// part of GrGLShaderBuilder that is used by effects so that this header doesn't need to be
// visible to GrGLEffects. Then make public accessors as necessary and remove friends.
friend class GrGLProgram;
- friend class GrGLShaderBuilder;
- friend class GrGLFullShaderBuilder;
- friend class GrGLFragmentOnlyShaderBuilder;
+ friend class GrGLProgramBuilder;
+ friend class GrGLFullProgramBuilder;
+ friend class GrGLFragmentOnlyProgramBuilder;
+ friend class GrGLVertexShaderBuilder;
+ friend class GrGLFragmentShaderBuilder;
+ friend class GrGLGeometryShaderBuilder;
};
#endif
diff --git a/src/gpu/gl/GrGLProgramEffects.cpp b/src/gpu/gl/GrGLProgramEffects.cpp
index 8ea77d05eb..efb64fe640 100644
--- a/src/gpu/gl/GrGLProgramEffects.cpp
+++ b/src/gpu/gl/GrGLProgramEffects.cpp
@@ -5,10 +5,10 @@
* found in the LICENSE file.
*/
+#include "gl/builders/GrGLProgramBuilder.h"
#include "GrGLProgramEffects.h"
#include "GrDrawEffect.h"
#include "gl/GrGLEffect.h"
-#include "gl/GrGLShaderBuilder.h"
#include "gl/GrGLVertexEffect.h"
#include "gl/GrGpuGL.h"
@@ -204,7 +204,7 @@ GrGLProgramEffects::~GrGLProgramEffects() {
}
}
-void GrGLProgramEffects::emitSamplers(GrGLShaderBuilder* builder,
+void GrGLProgramEffects::emitSamplers(GrGLProgramBuilder* builder,
const GrEffect* effect,
TextureSamplerArray* outSamplers) {
SkTArray<Sampler, true>& samplers = fSamplers.push_back();
@@ -213,7 +213,7 @@ void GrGLProgramEffects::emitSamplers(GrGLShaderBuilder* builder,
SkString name;
for (int t = 0; t < numTextures; ++t) {
name.printf("Sampler%d", t);
- samplers[t].fUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
+ samplers[t].fUniform = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
kSampler2D_GrSLType,
name.c_str());
SkNEW_APPEND_TO_TARRAY(outSamplers, TextureSampler,
@@ -250,7 +250,7 @@ void GrGLProgramEffects::bindTextures(GrGpuGL* gpu, const GrEffect* effect, int
////////////////////////////////////////////////////////////////////////////////
-void GrGLVertexProgramEffects::emitEffect(GrGLFullShaderBuilder* builder,
+void GrGLVertexProgramEffects::emitEffect(GrGLFullProgramBuilder* builder,
const GrEffectStage& stage,
const GrEffectKey& key,
const char* outColor,
@@ -261,7 +261,9 @@ void GrGLVertexProgramEffects::emitEffect(GrGLFullShaderBuilder* builder,
SkSTArray<2, TransformedCoords> coords(effect->numTransforms());
SkSTArray<4, TextureSampler> samplers(effect->numTextures());
- this->emitAttributes(builder, stage);
+ GrGLVertexShaderBuilder* vsBuilder = builder->getVertexShaderBuilder();
+ GrGLFragmentShaderBuilder* fsBuilder = builder->getFragmentShaderBuilder();
+ vsBuilder->emitAttributes(stage);
this->emitTransforms(builder, drawEffect, &coords);
this->emitSamplers(builder, effect, &samplers);
@@ -271,8 +273,8 @@ void GrGLVertexProgramEffects::emitEffect(GrGLFullShaderBuilder* builder,
// Enclose custom code in a block to avoid namespace conflicts
SkString openBrace;
openBrace.printf("\t{ // Stage %d: %s\n", stageIndex, glEffect->name());
- builder->vsCodeAppend(openBrace.c_str());
- builder->fsCodeAppend(openBrace.c_str());
+ fsBuilder->codeAppend(openBrace.c_str());
+ vsBuilder->codeAppend(openBrace.c_str());
if (glEffect->isVertexEffect()) {
GrGLVertexEffect* vertexEffect = static_cast<GrGLVertexEffect*>(glEffect);
@@ -281,25 +283,11 @@ void GrGLVertexProgramEffects::emitEffect(GrGLFullShaderBuilder* builder,
glEffect->emitCode(builder, drawEffect, key, outColor, inColor, coords, samplers);
}
- builder->vsCodeAppend("\t}\n");
- builder->fsCodeAppend("\t}\n");
+ vsBuilder->codeAppend("\t}\n");
+ fsBuilder->codeAppend("\t}\n");
}
-void GrGLVertexProgramEffects::emitAttributes(GrGLFullShaderBuilder* builder,
- const GrEffectStage& stage) {
- int numAttributes = stage.getVertexAttribIndexCount();
- const int* attributeIndices = stage.getVertexAttribIndices();
- for (int a = 0; a < numAttributes; ++a) {
- // TODO: Make addAttribute mangle the name.
- SkString attributeName("aAttr");
- attributeName.appendS32(attributeIndices[a]);
- builder->addEffectAttribute(attributeIndices[a],
- stage.getEffect()->vertexAttribType(a),
- attributeName);
- }
-}
-
-void GrGLVertexProgramEffects::emitTransforms(GrGLFullShaderBuilder* builder,
+void GrGLVertexProgramEffects::emitTransforms(GrGLFullProgramBuilder* builder,
const GrDrawEffect& drawEffect,
TransformedCoordsArray* outCoords) {
SkTArray<Transform, true>& transforms = fTransforms.push_back();
@@ -327,7 +315,7 @@ void GrGLVertexProgramEffects::emitTransforms(GrGLFullShaderBuilder* builder,
suffixedUniName.appendf("_%i", t);
uniName = suffixedUniName.c_str();
}
- transforms[t].fHandle = builder->addUniform(GrGLShaderBuilder::kVertex_Visibility,
+ transforms[t].fHandle = builder->addUniform(GrGLProgramBuilder::kVertex_Visibility,
kMat33f_GrSLType,
uniName,
&uniName);
@@ -341,18 +329,19 @@ void GrGLVertexProgramEffects::emitTransforms(GrGLFullShaderBuilder* builder,
}
const char* vsVaryingName;
const char* fsVaryingName;
+ GrGLVertexShaderBuilder* vsBuilder = builder->getVertexShaderBuilder();
builder->addVarying(varyingType, varyingName, &vsVaryingName, &fsVaryingName);
const GrGLShaderVar& coords = kPosition_GrCoordSet == get_source_coords(totalKey, t) ?
- builder->positionAttribute() :
- builder->localCoordsAttribute();
+ vsBuilder->positionAttribute() :
+ vsBuilder->localCoordsAttribute();
// varying = matrix * coords (logically)
SkASSERT(kVec2f_GrSLType == varyingType || kVec3f_GrSLType == varyingType);
if (kVec2f_GrSLType == varyingType) {
- builder->vsCodeAppendf("\t%s = (%s * vec3(%s, 1)).xy;\n",
+ vsBuilder->codeAppendf("\t%s = (%s * vec3(%s, 1)).xy;\n",
vsVaryingName, uniName, coords.c_str());
} else {
- builder->vsCodeAppendf("\t%s = %s * vec3(%s, 1);\n",
+ vsBuilder->codeAppendf("\t%s = %s * vec3(%s, 1);\n",
vsVaryingName, uniName, coords.c_str());
}
SkNEW_APPEND_TO_TARRAY(outCoords, TransformedCoords,
@@ -390,13 +379,13 @@ void GrGLVertexProgramEffects::setTransformData(const GrGLProgramDataManager& pr
}
}
-GrGLVertexProgramEffectsBuilder::GrGLVertexProgramEffectsBuilder(GrGLFullShaderBuilder* builder,
+GrGLVertexProgramEffectsBuilder::GrGLVertexProgramEffectsBuilder(GrGLFullProgramBuilder* builder,
int reserveCount)
: fBuilder(builder)
, fProgramEffects(SkNEW_ARGS(GrGLVertexProgramEffects,
- (reserveCount, fBuilder->hasExplicitLocalCoords()))) {
+ (reserveCount,
+ fBuilder->getVertexShaderBuilder()->hasExplicitLocalCoords()))) {
}
-
void GrGLVertexProgramEffectsBuilder::emitEffect(const GrEffectStage& stage,
const GrEffectKey& key,
const char* outColor,
@@ -408,7 +397,7 @@ void GrGLVertexProgramEffectsBuilder::emitEffect(const GrEffectStage& stage,
////////////////////////////////////////////////////////////////////////////////
-void GrGLPathTexGenProgramEffects::emitEffect(GrGLFragmentOnlyShaderBuilder* builder,
+void GrGLPathTexGenProgramEffects::emitEffect(GrGLFragmentOnlyProgramBuilder* builder,
const GrEffectStage& stage,
const GrEffectKey& key,
const char* outColor,
@@ -426,18 +415,19 @@ void GrGLPathTexGenProgramEffects::emitEffect(GrGLFragmentOnlyShaderBuilder* bui
GrGLEffect* glEffect = effect->getFactory().createGLInstance(drawEffect);
fGLEffects.push_back(glEffect);
+ GrGLFragmentShaderBuilder* fsBuilder = builder->getFragmentShaderBuilder();
// Enclose custom code in a block to avoid namespace conflicts
SkString openBrace;
openBrace.printf("\t{ // Stage %d: %s\n", stageIndex, glEffect->name());
- builder->fsCodeAppend(openBrace.c_str());
+ fsBuilder->codeAppend(openBrace.c_str());
SkASSERT(!glEffect->isVertexEffect());
glEffect->emitCode(builder, drawEffect, key, outColor, inColor, coords, samplers);
- builder->fsCodeAppend("\t}\n");
+ fsBuilder->codeAppend("\t}\n");
}
-void GrGLPathTexGenProgramEffects::setupPathTexGen(GrGLFragmentOnlyShaderBuilder* builder,
+void GrGLPathTexGenProgramEffects::setupPathTexGen(GrGLFragmentOnlyProgramBuilder* builder,
const GrDrawEffect& drawEffect,
TransformedCoordsArray* outCoords) {
int numTransforms = drawEffect.effect()->numTransforms();
@@ -499,12 +489,11 @@ void GrGLPathTexGenProgramEffects::setPathTexGenState(GrGpuGL* gpu,
}
GrGLPathTexGenProgramEffectsBuilder::GrGLPathTexGenProgramEffectsBuilder(
- GrGLFragmentOnlyShaderBuilder* builder,
+ GrGLFragmentOnlyProgramBuilder* builder,
int reserveCount)
: fBuilder(builder)
, fProgramEffects(SkNEW_ARGS(GrGLPathTexGenProgramEffects, (reserveCount))) {
}
-
void GrGLPathTexGenProgramEffectsBuilder::emitEffect(const GrEffectStage& stage,
const GrEffectKey& key,
const char* outColor,
@@ -513,3 +502,4 @@ void GrGLPathTexGenProgramEffectsBuilder::emitEffect(const GrEffectStage& stage,
SkASSERT(NULL != fProgramEffects.get());
fProgramEffects->emitEffect(fBuilder, stage, key, outColor, inColor, stageIndex);
}
+
diff --git a/src/gpu/gl/GrGLProgramEffects.h b/src/gpu/gl/GrGLProgramEffects.h
index 7ae925b69b..e4d84a013b 100644
--- a/src/gpu/gl/GrGLProgramEffects.h
+++ b/src/gpu/gl/GrGLProgramEffects.h
@@ -16,9 +16,9 @@
class GrEffect;
class GrEffectStage;
class GrGLVertexProgramEffectsBuilder;
-class GrGLShaderBuilder;
-class GrGLFullShaderBuilder;
-class GrGLFragmentOnlyShaderBuilder;
+class GrGLProgramBuilder;
+class GrGLFullProgramBuilder;
+class GrGLFragmentOnlyProgramBuilder;
/**
* This class encapsulates an array of GrGLEffects and their supporting data (coord transforms
@@ -54,6 +54,8 @@ public:
const GrGLProgramDataManager&,
const GrEffectStage* effectStages[]) = 0;
+ void addEffect(GrGLEffect* effect) { fGLEffects.push_back(effect); }
+
/**
* Passed to GrGLEffects so they can add transformed coordinates to their shader code.
*/
@@ -100,6 +102,7 @@ public:
typedef SkTArray<TextureSampler> TextureSamplerArray;
protected:
+
/**
* Helpers for GenEffectMetaKey.
*/
@@ -117,7 +120,7 @@ protected:
* appends the necessary data to the TextureSamplerArray* object so effects can add texture
* lookups to their code. This method is only meant to be called during the construction phase.
*/
- void emitSamplers(GrGLShaderBuilder*, const GrEffect*, TextureSamplerArray*);
+ void emitSamplers(GrGLProgramBuilder*, const GrEffect*, TextureSamplerArray*);
/**
* Helper for setData(). Binds all the textures for an effect.
@@ -134,6 +137,7 @@ protected:
SkTArray<SkSTArray<4, Sampler, true> > fSamplers;
private:
+ friend class GrGLFragmentO;
typedef SkRefCnt INHERITED;
};
@@ -143,7 +147,6 @@ private:
class GrGLProgramEffectsBuilder {
public:
virtual ~GrGLProgramEffectsBuilder() { }
-
/**
* Emits the effect's shader code, and stores the necessary uniforms internally.
*/
@@ -166,19 +169,17 @@ public:
const GrEffectStage* effectStages[]) SK_OVERRIDE;
private:
- friend class GrGLVertexProgramEffectsBuilder;
+ friend class GrGLFullProgramBuilder;
GrGLVertexProgramEffects(int reserveCount, bool explicitLocalCoords)
: INHERITED(reserveCount)
, fTransforms(reserveCount)
, fHasExplicitLocalCoords(explicitLocalCoords) {
}
-
/**
- * Helper for GrGLProgramEffectsBuilder::emitEfffect(). This method is meant to only be called
- * during the construction phase.
+ * This method is meant to only be called during the construction phase.
*/
- void emitEffect(GrGLFullShaderBuilder*,
+ void emitEffect(GrGLFullProgramBuilder*,
const GrEffectStage&,
const GrEffectKey&,
const char* outColor,
@@ -188,7 +189,7 @@ private:
/**
* Helper for emitEffect(). Emits any attributes an effect may have.
*/
- void emitAttributes(GrGLFullShaderBuilder*, const GrEffectStage&);
+ void emitAttributes(GrGLFullProgramBuilder*, const GrEffectStage&);
/**
* Helper for emitEffect(). Emits code to implement an effect's coord transforms in the VS.
@@ -197,7 +198,7 @@ private:
* of the varyings in the VS and FS as well their types are appended to the
* TransformedCoordsArray* object, which is in turn passed to the effect's emitCode() function.
*/
- void emitTransforms(GrGLFullShaderBuilder*,
+ void emitTransforms(GrGLFullProgramBuilder*,
const GrDrawEffect&,
TransformedCoordsArray*);
@@ -215,6 +216,8 @@ private:
SkTArray<SkSTArray<2, Transform, true> > fTransforms;
bool fHasExplicitLocalCoords;
+ friend class GrGLVertexProgramEffectsBuilder;
+
typedef GrGLProgramEffects INHERITED;
};
@@ -223,25 +226,21 @@ private:
*/
class GrGLVertexProgramEffectsBuilder : public GrGLProgramEffectsBuilder {
public:
- GrGLVertexProgramEffectsBuilder(GrGLFullShaderBuilder*, int reserveCount);
+ GrGLVertexProgramEffectsBuilder(GrGLFullProgramBuilder*, int reserveCount);
virtual ~GrGLVertexProgramEffectsBuilder() { }
-
virtual void emitEffect(const GrEffectStage&,
const GrEffectKey&,
const char* outColor,
const char* inColor,
int stageIndex) SK_OVERRIDE;
-
/**
* Finalizes the building process and returns the effect array. After this call, the builder
* becomes invalid.
*/
GrGLProgramEffects* finish() { return fProgramEffects.detach(); }
-
private:
- GrGLFullShaderBuilder* fBuilder;
+ GrGLFullProgramBuilder* fBuilder;
SkAutoTDelete<GrGLVertexProgramEffects> fProgramEffects;
-
typedef GrGLProgramEffectsBuilder INHERITED;
};
@@ -258,7 +257,7 @@ public:
const GrEffectStage* effectStages[]) SK_OVERRIDE;
private:
- friend class GrGLPathTexGenProgramEffectsBuilder;
+ friend class GrGLFragmentOnlyProgramBuilder;
GrGLPathTexGenProgramEffects(int reserveCount)
: INHERITED(reserveCount)
@@ -266,10 +265,9 @@ private:
}
/**
- * Helper for GrGLProgramEffectsBuilder::emitEfffect(). This method is meant to only be called
- * during the construction phase.
+ * This method is meant to only be called during the construction phase.
*/
- void emitEffect(GrGLFragmentOnlyShaderBuilder*,
+ void emitEffect(GrGLFragmentOnlyProgramBuilder*,
const GrEffectStage&,
const GrEffectKey&,
const char* outColor,
@@ -284,7 +282,7 @@ private:
* types are appended to the TransformedCoordsArray* object, which is in turn passed to the
* effect's emitCode() function.
*/
- void setupPathTexGen(GrGLFragmentOnlyShaderBuilder*,
+ void setupPathTexGen(GrGLFragmentOnlyProgramBuilder*,
const GrDrawEffect&,
TransformedCoordsArray*);
@@ -302,6 +300,7 @@ private:
SkTArray<Transforms> fTransforms;
+ friend class GrGLPathTexGenProgramEffectsBuilder;
typedef GrGLProgramEffects INHERITED;
};
@@ -310,26 +309,23 @@ private:
*/
class GrGLPathTexGenProgramEffectsBuilder : public GrGLProgramEffectsBuilder {
public:
- GrGLPathTexGenProgramEffectsBuilder(GrGLFragmentOnlyShaderBuilder*, int reserveCount);
+ GrGLPathTexGenProgramEffectsBuilder(GrGLFragmentOnlyProgramBuilder*, int reserveCount);
virtual ~GrGLPathTexGenProgramEffectsBuilder() { }
-
virtual void emitEffect(const GrEffectStage&,
const GrEffectKey&,
const char* outColor,
const char* inColor,
int stageIndex) SK_OVERRIDE;
-
/**
* Finalizes the building process and returns the effect array. After this call, the builder
* becomes invalid.
*/
GrGLProgramEffects* finish() { return fProgramEffects.detach(); }
-
private:
- GrGLFragmentOnlyShaderBuilder* fBuilder;
+ GrGLFragmentOnlyProgramBuilder* fBuilder;
SkAutoTDelete<GrGLPathTexGenProgramEffects> fProgramEffects;
-
typedef GrGLProgramEffectsBuilder INHERITED;
};
+
#endif
diff --git a/src/gpu/gl/GrGLShaderBuilder.cpp b/src/gpu/gl/GrGLShaderBuilder.cpp
deleted file mode 100644
index 9fffd26145..0000000000
--- a/src/gpu/gl/GrGLShaderBuilder.cpp
+++ /dev/null
@@ -1,1071 +0,0 @@
-/*
- * Copyright 2012 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "gl/GrGLShaderBuilder.h"
-#include "gl/GrGLProgram.h"
-#include "gl/GrGLSLPrettyPrint.h"
-#include "gl/GrGLUniformHandle.h"
-#include "GrCoordTransform.h"
-#include "GrDrawEffect.h"
-#include "GrGpuGL.h"
-#include "GrTexture.h"
-#include "SkRTConf.h"
-#include "SkTraceEvent.h"
-
-#define GL_CALL(X) GR_GL_CALL(this->gpu()->glInterface(), X)
-#define GL_CALL_RET(R, X) GR_GL_CALL_RET(this->gpu()->glInterface(), R, X)
-
-// number of each input/output type in a single allocation block
-static const int kVarsPerBlock = 8;
-
-// except FS outputs where we expect 2 at most.
-static const int kMaxFSOutputs = 2;
-
-// ES2 FS only guarantees mediump and lowp support
-static const GrGLShaderVar::Precision kDefaultFragmentPrecision = GrGLShaderVar::kMedium_Precision;
-
-typedef GrGLProgramDataManager::UniformHandle UniformHandle;
-
-SK_CONF_DECLARE(bool, c_PrintShaders, "gpu.printShaders", false,
- "Print the source code for all shaders generated.");
-
-///////////////////////////////////////////////////////////////////////////////
-
-namespace {
-
-inline const char* color_attribute_name() { return "aColor"; }
-inline const char* coverage_attribute_name() { return "aCoverage"; }
-inline const char* declared_color_output_name() { return "fsColorOut"; }
-inline const char* dual_source_output_name() { return "dualSourceOut"; }
-inline const char* sample_function_name(GrSLType type, GrGLSLGeneration glslGen) {
- if (kVec2f_GrSLType == type) {
- return glslGen >= k130_GrGLSLGeneration ? "texture" : "texture2D";
- } else {
- SkASSERT(kVec3f_GrSLType == type);
- return glslGen >= k130_GrGLSLGeneration ? "textureProj" : "texture2DProj";
- }
-}
-
-void append_texture_lookup(SkString* out,
- GrGpuGL* gpu,
- const char* samplerName,
- const char* coordName,
- uint32_t configComponentMask,
- const char* swizzle,
- GrSLType varyingType = kVec2f_GrSLType) {
- SkASSERT(NULL != coordName);
-
- out->appendf("%s(%s, %s)",
- sample_function_name(varyingType, gpu->glslGeneration()),
- samplerName,
- coordName);
-
- char mangledSwizzle[5];
-
- // The swizzling occurs using texture params instead of shader-mangling if ARB_texture_swizzle
- // is available.
- if (!gpu->glCaps().textureSwizzleSupport() &&
- (kA_GrColorComponentFlag == configComponentMask)) {
- char alphaChar = gpu->glCaps().textureRedSupport() ? 'r' : 'a';
- int i;
- for (i = 0; '\0' != swizzle[i]; ++i) {
- mangledSwizzle[i] = alphaChar;
- }
- mangledSwizzle[i] ='\0';
- swizzle = mangledSwizzle;
- }
- // For shader prettiness we omit the swizzle rather than appending ".rgba".
- if (memcmp(swizzle, "rgba", 4)) {
- out->appendf(".%s", swizzle);
- }
-}
-
-}
-
-static const char kDstCopyColorName[] = "_dstColor";
-
-///////////////////////////////////////////////////////////////////////////////
-
-bool GrGLShaderBuilder::genProgram(const GrEffectStage* colorStages[],
- const GrEffectStage* coverageStages[]) {
- const GrGLProgramDesc::KeyHeader& header = this->desc().getHeader();
-
- ///////////////////////////////////////////////////////////////////////////
- // emit code to read the dst copy texture, if necessary
- if (kNoDstRead_DstReadKey != header.fDstReadKey && !fGpu->glCaps().fbFetchSupport()) {
- bool topDown = SkToBool(kTopLeftOrigin_DstReadKeyBit & header.fDstReadKey);
- const char* dstCopyTopLeftName;
- const char* dstCopyCoordScaleName;
- const char* dstCopySamplerName;
- uint32_t configMask;
- if (SkToBool(kUseAlphaConfig_DstReadKeyBit & header.fDstReadKey)) {
- configMask = kA_GrColorComponentFlag;
- } else {
- configMask = kRGBA_GrColorComponentFlags;
- }
- fUniformHandles.fDstCopySamplerUni =
- this->addUniform(kFragment_Visibility, kSampler2D_GrSLType, "DstCopySampler",
- &dstCopySamplerName);
- fUniformHandles.fDstCopyTopLeftUni =
- this->addUniform(kFragment_Visibility, kVec2f_GrSLType, "DstCopyUpperLeft",
- &dstCopyTopLeftName);
- fUniformHandles.fDstCopyScaleUni =
- this->addUniform(kFragment_Visibility, kVec2f_GrSLType, "DstCopyCoordScale",
- &dstCopyCoordScaleName);
- const char* fragPos = this->fragmentPosition();
- this->fsCodeAppend("\t// Read color from copy of the destination.\n");
- this->fsCodeAppendf("\tvec2 _dstTexCoord = (%s.xy - %s) * %s;\n",
- fragPos, dstCopyTopLeftName, dstCopyCoordScaleName);
- if (!topDown) {
- this->fsCodeAppend("\t_dstTexCoord.y = 1.0 - _dstTexCoord.y;\n");
- }
- this->fsCodeAppendf("\tvec4 %s = ", kDstCopyColorName);
- append_texture_lookup(&fFSCode,
- fGpu,
- dstCopySamplerName,
- "_dstTexCoord",
- configMask,
- "rgba");
- this->fsCodeAppend(";\n\n");
- }
-
- ///////////////////////////////////////////////////////////////////////////
- // get the initial color and coverage to feed into the first effect in each effect chain
-
- GrGLSLExpr4 inputColor;
- GrGLSLExpr4 inputCoverage;
-
- if (GrGLProgramDesc::kUniform_ColorInput == header.fColorInput) {
- const char* name;
- fUniformHandles.fColorUni =
- this->addUniform(GrGLShaderBuilder::kFragment_Visibility, kVec4f_GrSLType, "Color",
- &name);
- inputColor = GrGLSLExpr4(name);
- }
-
- if (GrGLProgramDesc::kUniform_ColorInput == header.fCoverageInput) {
- const char* name;
- fUniformHandles.fCoverageUni =
- this->addUniform(GrGLShaderBuilder::kFragment_Visibility, kVec4f_GrSLType, "Coverage",
- &name);
- inputCoverage = GrGLSLExpr4(name);
- } else if (GrGLProgramDesc::kSolidWhite_ColorInput == header.fCoverageInput) {
- inputCoverage = GrGLSLExpr4(1);
- }
-
- if (k110_GrGLSLGeneration != fGpu->glslGeneration()) {
- fFSOutputs.push_back().set(kVec4f_GrSLType,
- GrGLShaderVar::kOut_TypeModifier,
- declared_color_output_name());
- fHasCustomColorOutput = true;
- }
-
- this->emitCodeBeforeEffects(&inputColor, &inputCoverage);
-
- ///////////////////////////////////////////////////////////////////////////
- // emit the per-effect code for both color and coverage effects
-
- GrGLProgramDesc::EffectKeyProvider colorKeyProvider(
- &this->desc(), GrGLProgramDesc::EffectKeyProvider::kColor_EffectType);
- fColorEffects.reset(this->createAndEmitEffects(colorStages,
- this->desc().numColorEffects(),
- colorKeyProvider,
- &inputColor));
-
- GrGLProgramDesc::EffectKeyProvider coverageKeyProvider(
- &this->desc(), GrGLProgramDesc::EffectKeyProvider::kCoverage_EffectType);
- fCoverageEffects.reset(this->createAndEmitEffects(coverageStages,
- this->desc().numCoverageEffects(),
- coverageKeyProvider,
- &inputCoverage));
-
- this->emitCodeAfterEffects();
-
- ///////////////////////////////////////////////////////////////////////////
- // write the secondary color output if necessary
- if (GrGLProgramDesc::CoverageOutputUsesSecondaryOutput(header.fCoverageOutput)) {
- const char* secondaryOutputName = this->enableSecondaryOutput();
-
- // default coeff to ones for kCoverage_DualSrcOutput
- GrGLSLExpr4 coeff(1);
- if (GrGLProgramDesc::kSecondaryCoverageISA_CoverageOutput == header.fCoverageOutput) {
- // Get (1-A) into coeff
- coeff = GrGLSLExpr4::VectorCast(GrGLSLExpr1(1) - inputColor.a());
- } else if (GrGLProgramDesc::kSecondaryCoverageISC_CoverageOutput ==
- header.fCoverageOutput){
- // Get (1-RGBA) into coeff
- coeff = GrGLSLExpr4(1) - inputColor;
- }
- // Get coeff * coverage into modulate and then write that to the dual source output.
- this->fsCodeAppendf("\t%s = %s;\n", secondaryOutputName, (coeff * inputCoverage).c_str());
- }
-
- ///////////////////////////////////////////////////////////////////////////
- // combine color and coverage as frag color
-
- // Get "color * coverage" into fragColor
- GrGLSLExpr4 fragColor = inputColor * inputCoverage;
- // Now tack on "+(1-coverage)dst onto the frag color if we were asked to do so.
- if (GrGLProgramDesc::kCombineWithDst_CoverageOutput == header.fCoverageOutput) {
- GrGLSLExpr4 dstCoeff = GrGLSLExpr4(1) - inputCoverage;
-
- GrGLSLExpr4 dstContribution = dstCoeff * GrGLSLExpr4(this->dstColor());
-
- fragColor = fragColor + dstContribution;
- }
- this->fsCodeAppendf("\t%s = %s;\n", this->getColorOutputName(), fragColor.c_str());
-
- if (!this->finish()) {
- return false;
- }
-
- return true;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-GrGLShaderBuilder::GrGLShaderBuilder(GrGpuGL* gpu,
- const GrGLProgramDesc& desc)
- : fHasVertexShader(false)
- , fTexCoordSetCnt(0)
- , fProgramID(0)
- , fDesc(desc)
- , fGpu(gpu)
- , fFSFeaturesAddedMask(0)
- , fFSInputs(kVarsPerBlock)
- , fFSOutputs(kMaxFSOutputs)
- , fUniforms(kVarsPerBlock)
- , fSetupFragPosition(false)
- , fTopLeftFragPosRead(kTopLeftFragPosRead_FragPosKey == desc.getHeader().fFragPosKey)
- , fHasCustomColorOutput(false)
- , fHasSecondaryOutput(false) {
-}
-
-bool GrGLShaderBuilder::enableFeature(GLSLFeature feature) {
- switch (feature) {
- case kStandardDerivatives_GLSLFeature:
- if (!fGpu->glCaps().shaderDerivativeSupport()) {
- return false;
- }
- if (kGLES_GrGLStandard == fGpu->glStandard()) {
- this->addFSFeature(1 << kStandardDerivatives_GLSLFeature,
- "GL_OES_standard_derivatives");
- }
- return true;
- default:
- SkFAIL("Unexpected GLSLFeature requested.");
- return false;
- }
-}
-
-void GrGLShaderBuilder::addFSFeature(uint32_t featureBit, const char* extensionName) {
- if (!(featureBit & fFSFeaturesAddedMask)) {
- fFSExtensions.appendf("#extension %s: require\n", extensionName);
- fFSFeaturesAddedMask |= featureBit;
- }
-}
-
-void GrGLShaderBuilder::nameVariable(SkString* out, char prefix, const char* name) {
- if ('\0' == prefix) {
- *out = name;
- } else {
- out->printf("%c%s", prefix, name);
- }
- if (fCodeStage.inStageCode()) {
- if (out->endsWith('_')) {
- // Names containing "__" are reserved.
- out->append("x");
- }
- out->appendf("_Stage%d", fCodeStage.stageIndex());
- }
-}
-
-const char* GrGLShaderBuilder::dstColor() {
- if (fCodeStage.inStageCode()) {
- const GrEffect* effect = fCodeStage.effectStage()->getEffect();
- if (!effect->willReadDstColor()) {
- SkDEBUGFAIL("GrGLEffect asked for dst color but its generating GrEffect "
- "did not request access.");
- return "";
- }
- }
-
- if (fGpu->glCaps().fbFetchSupport()) {
- this->addFSFeature(1 << (kLastGLSLPrivateFeature + 1),
- fGpu->glCaps().fbFetchExtensionString());
- return fGpu->glCaps().fbFetchColorName();
- } else if (fUniformHandles.fDstCopySamplerUni.isValid()) {
- return kDstCopyColorName;
- } else {
- return "";
- }
-}
-
-void GrGLShaderBuilder::appendTextureLookup(SkString* out,
- const GrGLShaderBuilder::TextureSampler& sampler,
- const char* coordName,
- GrSLType varyingType) const {
- append_texture_lookup(out,
- fGpu,
- this->getUniformCStr(sampler.samplerUniform()),
- coordName,
- sampler.configComponentMask(),
- sampler.swizzle(),
- varyingType);
-}
-
-void GrGLShaderBuilder::fsAppendTextureLookup(const GrGLShaderBuilder::TextureSampler& sampler,
- const char* coordName,
- GrSLType varyingType) {
- this->appendTextureLookup(&fFSCode, sampler, coordName, varyingType);
-}
-
-void GrGLShaderBuilder::fsAppendTextureLookupAndModulate(
- const char* modulation,
- const GrGLShaderBuilder::TextureSampler& sampler,
- const char* coordName,
- GrSLType varyingType) {
- SkString lookup;
- this->appendTextureLookup(&lookup, sampler, coordName, varyingType);
- fFSCode.append((GrGLSLExpr4(modulation) * GrGLSLExpr4(lookup)).c_str());
-}
-
-GrGLShaderBuilder::DstReadKey GrGLShaderBuilder::KeyForDstRead(const GrTexture* dstCopy,
- const GrGLCaps& caps) {
- uint32_t key = kYesDstRead_DstReadKeyBit;
- if (caps.fbFetchSupport()) {
- return key;
- }
- SkASSERT(NULL != dstCopy);
- if (!caps.textureSwizzleSupport() && GrPixelConfigIsAlphaOnly(dstCopy->config())) {
- // The fact that the config is alpha-only must be considered when generating code.
- key |= kUseAlphaConfig_DstReadKeyBit;
- }
- if (kTopLeft_GrSurfaceOrigin == dstCopy->origin()) {
- key |= kTopLeftOrigin_DstReadKeyBit;
- }
- SkASSERT(static_cast<DstReadKey>(key) == key);
- return static_cast<DstReadKey>(key);
-}
-
-GrGLShaderBuilder::FragPosKey GrGLShaderBuilder::KeyForFragmentPosition(const GrRenderTarget* dst,
- const GrGLCaps&) {
- if (kTopLeft_GrSurfaceOrigin == dst->origin()) {
- return kTopLeftFragPosRead_FragPosKey;
- } else {
- return kBottomLeftFragPosRead_FragPosKey;
- }
-}
-
-
-const GrGLenum* GrGLShaderBuilder::GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps) {
- if (caps.textureSwizzleSupport() && GrPixelConfigIsAlphaOnly(config)) {
- if (caps.textureRedSupport()) {
- static const GrGLenum gRedSmear[] = { GR_GL_RED, GR_GL_RED, GR_GL_RED, GR_GL_RED };
- return gRedSmear;
- } else {
- static const GrGLenum gAlphaSmear[] = { GR_GL_ALPHA, GR_GL_ALPHA,
- GR_GL_ALPHA, GR_GL_ALPHA };
- return gAlphaSmear;
- }
- } else {
- static const GrGLenum gStraight[] = { GR_GL_RED, GR_GL_GREEN, GR_GL_BLUE, GR_GL_ALPHA };
- return gStraight;
- }
-}
-
-GrGLProgramDataManager::UniformHandle GrGLShaderBuilder::addUniformArray(uint32_t visibility,
- GrSLType type,
- const char* name,
- int count,
- const char** outName) {
- SkASSERT(name && strlen(name));
- SkDEBUGCODE(static const uint32_t kVisibilityMask = kVertex_Visibility | kFragment_Visibility);
- SkASSERT(0 == (~kVisibilityMask & visibility));
- SkASSERT(0 != visibility);
-
- UniformInfo& uni = fUniforms.push_back();
- uni.fVariable.setType(type);
- uni.fVariable.setTypeModifier(GrGLShaderVar::kUniform_TypeModifier);
- this->nameVariable(uni.fVariable.accessName(), 'u', name);
- uni.fVariable.setArrayCount(count);
- uni.fVisibility = visibility;
-
- // If it is visible in both the VS and FS, the precision must match.
- // We declare a default FS precision, but not a default VS. So set the var
- // to use the default FS precision.
- if ((kVertex_Visibility | kFragment_Visibility) == visibility) {
- // the fragment and vertex precisions must match
- uni.fVariable.setPrecision(kDefaultFragmentPrecision);
- }
-
- if (NULL != outName) {
- *outName = uni.fVariable.c_str();
- }
- return GrGLProgramDataManager::UniformHandle::CreateFromUniformIndex(fUniforms.count() - 1);
-}
-
-SkString GrGLShaderBuilder::ensureFSCoords2D(const TransformedCoordsArray& coords, int index) {
- if (kVec3f_GrSLType != coords[index].type()) {
- SkASSERT(kVec2f_GrSLType == coords[index].type());
- return coords[index].getName();
- }
-
- SkString coords2D("coords2D");
- if (0 != index) {
- coords2D.appendf("_%i", index);
- }
- this->fsCodeAppendf("\tvec2 %s = %s.xy / %s.z;",
- coords2D.c_str(), coords[index].c_str(), coords[index].c_str());
- return coords2D;
-}
-
-const char* GrGLShaderBuilder::fragmentPosition() {
- if (fCodeStage.inStageCode()) {
- const GrEffect* effect = fCodeStage.effectStage()->getEffect();
- if (!effect->willReadFragmentPosition()) {
- SkDEBUGFAIL("GrGLEffect asked for frag position but its generating GrEffect "
- "did not request access.");
- return "";
- }
- }
- // We only declare "gl_FragCoord" when we're in the case where we want to use layout qualifiers
- // to reverse y. Otherwise it isn't necessary and whether the "in" qualifier appears in the
- // declaration varies in earlier GLSL specs. So it is simpler to omit it.
- if (fTopLeftFragPosRead) {
- fSetupFragPosition = true;
- return "gl_FragCoord";
- } else if (fGpu->glCaps().fragCoordConventionsSupport()) {
- if (!fSetupFragPosition) {
- if (fGpu->glslGeneration() < k150_GrGLSLGeneration) {
- this->addFSFeature(1 << kFragCoordConventions_GLSLPrivateFeature,
- "GL_ARB_fragment_coord_conventions");
- }
- fFSInputs.push_back().set(kVec4f_GrSLType,
- GrGLShaderVar::kIn_TypeModifier,
- "gl_FragCoord",
- GrGLShaderVar::kDefault_Precision,
- GrGLShaderVar::kUpperLeft_Origin);
- fSetupFragPosition = true;
- }
- return "gl_FragCoord";
- } else {
- static const char* kCoordName = "fragCoordYDown";
- if (!fSetupFragPosition) {
- // temporarily change the stage index because we're inserting non-stage code.
- CodeStage::AutoStageRestore csar(&fCodeStage, NULL);
-
- SkASSERT(!fUniformHandles.fRTHeightUni.isValid());
- const char* rtHeightName;
-
- fUniformHandles.fRTHeightUni =
- this->addUniform(kFragment_Visibility, kFloat_GrSLType, "RTHeight", &rtHeightName);
-
- // Using glFragCoord.zw for the last two components tickles an Adreno driver bug that
- // causes programs to fail to link. Making this function return a vec2() didn't fix the
- // problem but using 1.0 for the last two components does.
- this->fFSCode.prependf("\tvec4 %s = vec4(gl_FragCoord.x, %s - gl_FragCoord.y, 1.0, "
- "1.0);\n", kCoordName, rtHeightName);
- fSetupFragPosition = true;
- }
- SkASSERT(fUniformHandles.fRTHeightUni.isValid());
- return kCoordName;
- }
-}
-
-void GrGLShaderBuilder::fsEmitFunction(GrSLType returnType,
- const char* name,
- int argCnt,
- const GrGLShaderVar* args,
- const char* body,
- SkString* outName) {
- fFSFunctions.append(GrGLSLTypeString(returnType));
- this->nameVariable(outName, '\0', name);
- fFSFunctions.appendf(" %s", outName->c_str());
- fFSFunctions.append("(");
- for (int i = 0; i < argCnt; ++i) {
- args[i].appendDecl(this->ctxInfo(), &fFSFunctions);
- if (i < argCnt - 1) {
- fFSFunctions.append(", ");
- }
- }
- fFSFunctions.append(") {\n");
- fFSFunctions.append(body);
- fFSFunctions.append("}\n\n");
-}
-
-namespace {
-
-inline void append_default_precision_qualifier(GrGLShaderVar::Precision p,
- GrGLStandard standard,
- SkString* str) {
- // Desktop GLSL has added precision qualifiers but they don't do anything.
- if (kGLES_GrGLStandard == standard) {
- switch (p) {
- case GrGLShaderVar::kHigh_Precision:
- str->append("precision highp float;\n");
- break;
- case GrGLShaderVar::kMedium_Precision:
- str->append("precision mediump float;\n");
- break;
- case GrGLShaderVar::kLow_Precision:
- str->append("precision lowp float;\n");
- break;
- case GrGLShaderVar::kDefault_Precision:
- SkFAIL("Default precision now allowed.");
- default:
- SkFAIL("Unknown precision value.");
- }
- }
-}
-}
-
-void GrGLShaderBuilder::appendDecls(const VarArray& vars, SkString* out) const {
- for (int i = 0; i < vars.count(); ++i) {
- vars[i].appendDecl(this->ctxInfo(), out);
- out->append(";\n");
- }
-}
-
-void GrGLShaderBuilder::appendUniformDecls(ShaderVisibility visibility,
- SkString* out) const {
- for (int i = 0; i < fUniforms.count(); ++i) {
- if (fUniforms[i].fVisibility & visibility) {
- fUniforms[i].fVariable.appendDecl(this->ctxInfo(), out);
- out->append(";\n");
- }
- }
-}
-
-void GrGLShaderBuilder::createAndEmitEffects(GrGLProgramEffectsBuilder* programEffectsBuilder,
- const GrEffectStage* effectStages[],
- int effectCnt,
- const GrGLProgramDesc::EffectKeyProvider& keyProvider,
- GrGLSLExpr4* fsInOutColor) {
- bool effectEmitted = false;
-
- GrGLSLExpr4 inColor = *fsInOutColor;
- GrGLSLExpr4 outColor;
-
- for (int e = 0; e < effectCnt; ++e) {
- SkASSERT(NULL != effectStages[e] && NULL != effectStages[e]->getEffect());
- const GrEffectStage& stage = *effectStages[e];
-
- CodeStage::AutoStageRestore csar(&fCodeStage, &stage);
-
- if (inColor.isZeros()) {
- SkString inColorName;
-
- // Effects have no way to communicate zeros, they treat an empty string as ones.
- this->nameVariable(&inColorName, '\0', "input");
- this->fsCodeAppendf("\tvec4 %s = %s;\n", inColorName.c_str(), inColor.c_str());
- inColor = inColorName;
- }
-
- // create var to hold stage result
- SkString outColorName;
- this->nameVariable(&outColorName, '\0', "output");
- this->fsCodeAppendf("\tvec4 %s;\n", outColorName.c_str());
- outColor = outColorName;
-
-
- programEffectsBuilder->emitEffect(stage,
- keyProvider.get(e),
- outColor.c_str(),
- inColor.isOnes() ? NULL : inColor.c_str(),
- fCodeStage.stageIndex());
-
- inColor = outColor;
- effectEmitted = true;
- }
-
- if (effectEmitted) {
- *fsInOutColor = outColor;
- }
-}
-
-const char* GrGLShaderBuilder::getColorOutputName() const {
- return fHasCustomColorOutput ? declared_color_output_name() : "gl_FragColor";
-}
-
-const char* GrGLShaderBuilder::enableSecondaryOutput() {
- if (!fHasSecondaryOutput) {
- fFSOutputs.push_back().set(kVec4f_GrSLType,
- GrGLShaderVar::kOut_TypeModifier,
- dual_source_output_name());
- fHasSecondaryOutput = true;
- }
- return dual_source_output_name();
-}
-
-bool GrGLShaderBuilder::finish() {
- SkASSERT(0 == fProgramID);
- GL_CALL_RET(fProgramID, CreateProgram());
- if (!fProgramID) {
- return false;
- }
-
- SkTDArray<GrGLuint> shadersToDelete;
-
- if (!this->compileAndAttachShaders(fProgramID, &shadersToDelete)) {
- GL_CALL(DeleteProgram(fProgramID));
- return false;
- }
-
- this->bindProgramLocations(fProgramID);
-
- GL_CALL(LinkProgram(fProgramID));
-
- // Calling GetProgramiv is expensive in Chromium. Assume success in release builds.
- bool checkLinked = !fGpu->ctxInfo().isChromium();
-#ifdef SK_DEBUG
- checkLinked = true;
-#endif
- if (checkLinked) {
- GrGLint linked = GR_GL_INIT_ZERO;
- GL_CALL(GetProgramiv(fProgramID, GR_GL_LINK_STATUS, &linked));
- if (!linked) {
- GrGLint infoLen = GR_GL_INIT_ZERO;
- GL_CALL(GetProgramiv(fProgramID, GR_GL_INFO_LOG_LENGTH, &infoLen));
- SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
- if (infoLen > 0) {
- // retrieve length even though we don't need it to workaround
- // bug in chrome cmd buffer param validation.
- GrGLsizei length = GR_GL_INIT_ZERO;
- GL_CALL(GetProgramInfoLog(fProgramID,
- infoLen+1,
- &length,
- (char*)log.get()));
- GrPrintf((char*)log.get());
- }
- SkDEBUGFAIL("Error linking program");
- GL_CALL(DeleteProgram(fProgramID));
- fProgramID = 0;
- return false;
- }
- }
-
- this->resolveProgramLocations(fProgramID);
-
- for (int i = 0; i < shadersToDelete.count(); ++i) {
- GL_CALL(DeleteShader(shadersToDelete[i]));
- }
-
- return true;
-}
-
-// Compiles a GL shader and attaches it to a program. Returns the shader ID if
-// successful, or 0 if not.
-static GrGLuint attach_shader(const GrGLContext& glCtx,
- GrGLuint programId,
- GrGLenum type,
- const SkString& shaderSrc) {
- const GrGLInterface* gli = glCtx.interface();
-
- GrGLuint shaderId;
- GR_GL_CALL_RET(gli, shaderId, CreateShader(type));
- if (0 == shaderId) {
- return 0;
- }
-
-#ifdef SK_DEBUG
- SkString prettySource = GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, false);
- const GrGLchar* sourceStr = prettySource.c_str();
- GrGLint sourceLength = static_cast<GrGLint>(prettySource.size());
-#else
- GrGLint sourceLength = static_cast<GrGLint>(shaderSrc.size());
- const GrGLchar* sourceStr = shaderSrc.c_str();
-#endif
- GR_GL_CALL(gli, ShaderSource(shaderId, 1, &sourceStr, &sourceLength));
- GR_GL_CALL(gli, CompileShader(shaderId));
-
- // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.
- bool checkCompiled = !glCtx.isChromium();
-#ifdef SK_DEBUG
- checkCompiled = true;
-#endif
- if (checkCompiled) {
- GrGLint compiled = GR_GL_INIT_ZERO;
- GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));
-
- if (!compiled) {
- GrGLint infoLen = GR_GL_INIT_ZERO;
- GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));
- SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
- if (infoLen > 0) {
- // retrieve length even though we don't need it to workaround bug in Chromium cmd
- // buffer param validation.
- GrGLsizei length = GR_GL_INIT_ZERO;
- GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1,
- &length, (char*)log.get()));
- GrPrintf(GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, true).c_str());
- GrPrintf("\n%s", log.get());
- }
- SkDEBUGFAIL("Shader compilation failed!");
- GR_GL_CALL(gli, DeleteShader(shaderId));
- return 0;
- }
- }
-
- TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader",
- TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderSrc.c_str()));
- if (c_PrintShaders) {
- GrPrintf(GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, true).c_str());
- GrPrintf("\n");
- }
-
- // Attach the shader, but defer deletion until after we have linked the program.
- // This works around a bug in the Android emulator's GLES2 wrapper which
- // will immediately delete the shader object and free its memory even though it's
- // attached to a program, which then causes glLinkProgram to fail.
- GR_GL_CALL(gli, AttachShader(programId, shaderId));
-
- return shaderId;
-}
-
-bool GrGLShaderBuilder::compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) const {
- SkString fragShaderSrc(GrGetGLSLVersionDecl(this->ctxInfo()));
- fragShaderSrc.append(fFSExtensions);
- append_default_precision_qualifier(kDefaultFragmentPrecision,
- fGpu->glStandard(),
- &fragShaderSrc);
- this->appendUniformDecls(kFragment_Visibility, &fragShaderSrc);
- this->appendDecls(fFSInputs, &fragShaderSrc);
- // We shouldn't have declared outputs on 1.10
- SkASSERT(k110_GrGLSLGeneration != fGpu->glslGeneration() || fFSOutputs.empty());
- this->appendDecls(fFSOutputs, &fragShaderSrc);
- fragShaderSrc.append(fFSFunctions);
- fragShaderSrc.append("void main() {\n");
- fragShaderSrc.append(fFSCode);
- fragShaderSrc.append("}\n");
-
- GrGLuint fragShaderId = attach_shader(fGpu->glContext(), programId, GR_GL_FRAGMENT_SHADER, fragShaderSrc);
- if (!fragShaderId) {
- return false;
- }
-
- *shaderIds->append() = fragShaderId;
-
- return true;
-}
-
-void GrGLShaderBuilder::bindProgramLocations(GrGLuint programId) {
- if (fHasCustomColorOutput) {
- GL_CALL(BindFragDataLocation(programId, 0, declared_color_output_name()));
- }
- if (fHasSecondaryOutput) {
- GL_CALL(BindFragDataLocationIndexed(programId, 0, 1, dual_source_output_name()));
- }
- // skbug.com/2056
- bool usingBindUniform = fGpu->glInterface()->fFunctions.fBindUniformLocation != NULL;
- if (usingBindUniform) {
- int count = fUniforms.count();
- for (int i = 0; i < count; ++i) {
- GL_CALL(BindUniformLocation(programId, i, fUniforms[i].fVariable.c_str()));
- fUniforms[i].fLocation = i;
- }
- }
-}
-
-void GrGLShaderBuilder::resolveProgramLocations(GrGLuint programId) {
- bool usingBindUniform = fGpu->glInterface()->fFunctions.fBindUniformLocation != NULL;
- if (!usingBindUniform) {
- int count = fUniforms.count();
- for (int i = 0; i < count; ++i) {
- GrGLint location;
- GL_CALL_RET(location,
- GetUniformLocation(programId, fUniforms[i].fVariable.c_str()));
- fUniforms[i].fLocation = location;
- }
- }
-}
-
-const GrGLContextInfo& GrGLShaderBuilder::ctxInfo() const {
- return fGpu->ctxInfo();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-GrGLFullShaderBuilder::GrGLFullShaderBuilder(GrGpuGL* gpu,
- const GrGLProgramDesc& desc)
- : INHERITED(gpu, desc)
- , fVSAttrs(kVarsPerBlock)
- , fVSOutputs(kVarsPerBlock)
- , fGSInputs(kVarsPerBlock)
- , fGSOutputs(kVarsPerBlock) {
-}
-
-void GrGLFullShaderBuilder::emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) {
- const GrGLProgramDesc::KeyHeader& header = this->desc().getHeader();
-
- fHasVertexShader = true;
-
- fPositionVar = &fVSAttrs.push_back();
- fPositionVar->set(kVec2f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, "aPosition");
- if (-1 != header.fLocalCoordAttributeIndex) {
- fLocalCoordsVar = &fVSAttrs.push_back();
- fLocalCoordsVar->set(kVec2f_GrSLType,
- GrGLShaderVar::kAttribute_TypeModifier,
- "aLocalCoords");
- } else {
- fLocalCoordsVar = fPositionVar;
- }
-
- const char* viewMName;
- fUniformHandles.fViewMatrixUni =
- this->addUniform(GrGLShaderBuilder::kVertex_Visibility, kMat33f_GrSLType, "ViewM",
- &viewMName);
-
- // Transform the position into Skia's device coords.
- this->vsCodeAppendf("\tvec3 pos3 = %s * vec3(%s, 1);\n",
- viewMName, fPositionVar->c_str());
-
- // we output point size in the GS if present
- if (header.fEmitsPointSize
-#if GR_GL_EXPERIMENTAL_GS
- && !header.fExperimentalGS
-#endif
- ) {
- this->vsCodeAppend("\tgl_PointSize = 1.0;\n");
- }
-
- if (GrGLProgramDesc::kAttribute_ColorInput == header.fColorInput) {
- this->addAttribute(kVec4f_GrSLType, color_attribute_name());
- const char *vsName, *fsName;
- this->addVarying(kVec4f_GrSLType, "Color", &vsName, &fsName);
- this->vsCodeAppendf("\t%s = %s;\n", vsName, color_attribute_name());
- *color = fsName;
- }
-
- if (GrGLProgramDesc::kAttribute_ColorInput == header.fCoverageInput) {
- this->addAttribute(kVec4f_GrSLType, coverage_attribute_name());
- const char *vsName, *fsName;
- this->addVarying(kVec4f_GrSLType, "Coverage", &vsName, &fsName);
- this->vsCodeAppendf("\t%s = %s;\n", vsName, coverage_attribute_name());
- *coverage = fsName;
- }
-}
-
-void GrGLFullShaderBuilder::emitCodeAfterEffects() {
- const char* rtAdjustName;
- fUniformHandles.fRTAdjustmentUni =
- this->addUniform(GrGLShaderBuilder::kVertex_Visibility, kVec4f_GrSLType, "rtAdjustment",
- &rtAdjustName);
-
- // Transform from Skia's device coords to GL's normalized device coords.
- this->vsCodeAppendf(
- "\tgl_Position = vec4(dot(pos3.xz, %s.xy), dot(pos3.yz, %s.zw), 0, pos3.z);\n",
- rtAdjustName, rtAdjustName);
-}
-
-bool GrGLFullShaderBuilder::addAttribute(GrSLType type, const char* name) {
- for (int i = 0; i < fVSAttrs.count(); ++i) {
- const GrGLShaderVar& attr = fVSAttrs[i];
- // if attribute already added, don't add it again
- if (attr.getName().equals(name)) {
- SkASSERT(attr.getType() == type);
- return false;
- }
- }
- fVSAttrs.push_back().set(type,
- GrGLShaderVar::kAttribute_TypeModifier,
- name);
- return true;
-}
-
-bool GrGLFullShaderBuilder::addEffectAttribute(int attributeIndex,
- GrSLType type,
- const SkString& name) {
- if (!this->addAttribute(type, name.c_str())) {
- return false;
- }
-
- fEffectAttributes.push_back().set(attributeIndex, name);
- return true;
-}
-
-void GrGLFullShaderBuilder::addVarying(GrSLType type,
- const char* name,
- const char** vsOutName,
- const char** fsInName) {
- fVSOutputs.push_back();
- fVSOutputs.back().setType(type);
- fVSOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
- this->nameVariable(fVSOutputs.back().accessName(), 'v', name);
-
- if (vsOutName) {
- *vsOutName = fVSOutputs.back().getName().c_str();
- }
- // input to FS comes either from VS or GS
- const SkString* fsName;
-#if GR_GL_EXPERIMENTAL_GS
- if (this->desc().getHeader().fExperimentalGS) {
- // if we have a GS take each varying in as an array
- // and output as non-array.
- fGSInputs.push_back();
- fGSInputs.back().setType(type);
- fGSInputs.back().setTypeModifier(GrGLShaderVar::kVaryingIn_TypeModifier);
- fGSInputs.back().setUnsizedArray();
- *fGSInputs.back().accessName() = fVSOutputs.back().getName();
- fGSOutputs.push_back();
- fGSOutputs.back().setType(type);
- fGSOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
- this->nameVariable(fGSOutputs.back().accessName(), 'g', name);
- fsName = fGSOutputs.back().accessName();
- } else
-#endif
- {
- fsName = fVSOutputs.back().accessName();
- }
- this->fsInputAppend().set(type, GrGLShaderVar::kVaryingIn_TypeModifier, *fsName);
- if (fsInName) {
- *fsInName = fsName->c_str();
- }
-}
-
-const SkString* GrGLFullShaderBuilder::getEffectAttributeName(int attributeIndex) const {
- const AttributePair* attribEnd = fEffectAttributes.end();
- for (const AttributePair* attrib = fEffectAttributes.begin(); attrib != attribEnd; ++attrib) {
- if (attrib->fIndex == attributeIndex) {
- return &attrib->fName;
- }
- }
-
- return NULL;
-}
-
-GrGLProgramEffects* GrGLFullShaderBuilder::createAndEmitEffects(
- const GrEffectStage* effectStages[],
- int effectCnt,
- const GrGLProgramDesc::EffectKeyProvider& keyProvider,
- GrGLSLExpr4* inOutFSColor) {
-
- GrGLVertexProgramEffectsBuilder programEffectsBuilder(this, effectCnt);
- this->INHERITED::createAndEmitEffects(&programEffectsBuilder,
- effectStages,
- effectCnt,
- keyProvider,
- inOutFSColor);
- return programEffectsBuilder.finish();
-}
-
-bool GrGLFullShaderBuilder::compileAndAttachShaders(GrGLuint programId,
- SkTDArray<GrGLuint>* shaderIds) const {
- const GrGLContext& glCtx = this->gpu()->glContext();
- SkString vertShaderSrc(GrGetGLSLVersionDecl(this->ctxInfo()));
- this->appendUniformDecls(kVertex_Visibility, &vertShaderSrc);
- this->appendDecls(fVSAttrs, &vertShaderSrc);
- this->appendDecls(fVSOutputs, &vertShaderSrc);
- vertShaderSrc.append("void main() {\n");
- vertShaderSrc.append(fVSCode);
- vertShaderSrc.append("}\n");
- GrGLuint vertShaderId = attach_shader(glCtx, programId, GR_GL_VERTEX_SHADER, vertShaderSrc);
- if (!vertShaderId) {
- return false;
- }
- *shaderIds->append() = vertShaderId;
-
-#if GR_GL_EXPERIMENTAL_GS
- if (this->desc().getHeader().fExperimentalGS) {
- SkASSERT(this->ctxInfo().glslGeneration() >= k150_GrGLSLGeneration);
- SkString geomShaderSrc(GrGetGLSLVersionDecl(this->ctxInfo()));
- geomShaderSrc.append("layout(triangles) in;\n"
- "layout(triangle_strip, max_vertices = 6) out;\n");
- this->appendDecls(fGSInputs, &geomShaderSrc);
- this->appendDecls(fGSOutputs, &geomShaderSrc);
- geomShaderSrc.append("void main() {\n");
- geomShaderSrc.append("\tfor (int i = 0; i < 3; ++i) {\n"
- "\t\tgl_Position = gl_in[i].gl_Position;\n");
- if (this->desc().getHeader().fEmitsPointSize) {
- geomShaderSrc.append("\t\tgl_PointSize = 1.0;\n");
- }
- SkASSERT(fGSInputs.count() == fGSOutputs.count());
- for (int i = 0; i < fGSInputs.count(); ++i) {
- geomShaderSrc.appendf("\t\t%s = %s[i];\n",
- fGSOutputs[i].getName().c_str(),
- fGSInputs[i].getName().c_str());
- }
- geomShaderSrc.append("\t\tEmitVertex();\n"
- "\t}\n"
- "\tEndPrimitive();\n");
- geomShaderSrc.append("}\n");
- GrGLuint geomShaderId = attach_shader(glCtx, programId, GR_GL_GEOMETRY_SHADER, geomShaderSrc);
- if (!geomShaderId) {
- return false;
- }
- *shaderIds->append() = geomShaderId;
- }
-#endif
-
- return this->INHERITED::compileAndAttachShaders(programId, shaderIds);
-}
-
-void GrGLFullShaderBuilder::bindProgramLocations(GrGLuint programId) {
- this->INHERITED::bindProgramLocations(programId);
-
- const GrGLProgramDesc::KeyHeader& header = this->desc().getHeader();
-
- // Bind the attrib locations to same values for all shaders
- SkASSERT(-1 != header.fPositionAttributeIndex);
- GL_CALL(BindAttribLocation(programId,
- header.fPositionAttributeIndex,
- fPositionVar->c_str()));
- if (-1 != header.fLocalCoordAttributeIndex) {
- GL_CALL(BindAttribLocation(programId,
- header.fLocalCoordAttributeIndex,
- fLocalCoordsVar->c_str()));
- }
- if (-1 != header.fColorAttributeIndex) {
- GL_CALL(BindAttribLocation(programId,
- header.fColorAttributeIndex,
- color_attribute_name()));
- }
- if (-1 != header.fCoverageAttributeIndex) {
- GL_CALL(BindAttribLocation(programId,
- header.fCoverageAttributeIndex,
- coverage_attribute_name()));
- }
-
- const AttributePair* attribEnd = fEffectAttributes.end();
- for (const AttributePair* attrib = fEffectAttributes.begin(); attrib != attribEnd; ++attrib) {
- GL_CALL(BindAttribLocation(programId, attrib->fIndex, attrib->fName.c_str()));
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-GrGLFragmentOnlyShaderBuilder::GrGLFragmentOnlyShaderBuilder(GrGpuGL* gpu,
- const GrGLProgramDesc& desc)
- : INHERITED(gpu, desc) {
- SkASSERT(!desc.getHeader().fHasVertexCode);
- SkASSERT(gpu->glCaps().pathRenderingSupport());
- SkASSERT(GrGLProgramDesc::kAttribute_ColorInput != desc.getHeader().fColorInput);
- SkASSERT(GrGLProgramDesc::kAttribute_ColorInput != desc.getHeader().fCoverageInput);
-}
-
-int GrGLFragmentOnlyShaderBuilder::addTexCoordSets(int count) {
- int firstFreeCoordSet = fTexCoordSetCnt;
- fTexCoordSetCnt += count;
- SkASSERT(gpu()->glCaps().maxFixedFunctionTextureCoords() >= fTexCoordSetCnt);
- return firstFreeCoordSet;
-}
-
-GrGLProgramEffects* GrGLFragmentOnlyShaderBuilder::createAndEmitEffects(
- const GrEffectStage* effectStages[],
- int effectCnt,
- const GrGLProgramDesc::EffectKeyProvider& keyProvider,
- GrGLSLExpr4* inOutFSColor) {
-
- GrGLPathTexGenProgramEffectsBuilder pathTexGenEffectsBuilder(this,
- effectCnt);
- this->INHERITED::createAndEmitEffects(&pathTexGenEffectsBuilder,
- effectStages,
- effectCnt,
- keyProvider,
- inOutFSColor);
- return pathTexGenEffectsBuilder.finish();
-}
diff --git a/src/gpu/gl/GrGLVertexEffect.h b/src/gpu/gl/GrGLVertexEffect.h
index eba1fbe795..2e82fbc4d7 100644
--- a/src/gpu/gl/GrGLVertexEffect.h
+++ b/src/gpu/gl/GrGLVertexEffect.h
@@ -24,27 +24,27 @@ public:
* This is similar to emitCode() in the base class, except it takes a full shader builder.
* This allows the effect subclass to emit vertex code.
*/
- virtual void emitCode(GrGLFullShaderBuilder* builder,
+ virtual void emitCode(GrGLFullProgramBuilder* builder,
const GrDrawEffect& drawEffect,
const GrEffectKey& key,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) = 0;
-
/**
* Provide a default override for base class's emitCode() function.
*/
- virtual void emitCode(GrGLShaderBuilder* builder,
+ virtual void emitCode(GrGLProgramBuilder* builder,
const GrDrawEffect& drawEffect,
const GrEffectKey& key,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) SK_OVERRIDE {
- SkFAIL("GrGLVertexEffect requires GrGLFullShaderBuilder* overload for emitCode().");
+ SkFAIL("GrGLVertexEffect requires GrGLFullProgramBuilder* overload for emitCode().");
}
+
private:
typedef GrGLEffect INHERITED;
};
diff --git a/src/gpu/gl/GrGpuGL.cpp b/src/gpu/gl/GrGpuGL.cpp
index 418f591301..3c22d17b64 100644
--- a/src/gpu/gl/GrGpuGL.cpp
+++ b/src/gpu/gl/GrGpuGL.cpp
@@ -8,7 +8,6 @@
#include "GrGpuGL.h"
#include "GrGLStencilBuffer.h"
-#include "GrGLShaderBuilder.h"
#include "GrTemplates.h"
#include "GrTypes.h"
#include "SkStrokeRec.h"
diff --git a/src/gpu/gl/builders/GrGLFragmentShaderBuilder.cpp b/src/gpu/gl/builders/GrGLFragmentShaderBuilder.cpp
new file mode 100644
index 0000000000..d216a18c25
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLFragmentShaderBuilder.cpp
@@ -0,0 +1,351 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrGLFragmentShaderBuilder.h"
+#include "GrGLShaderStringBuilder.h"
+#include "GrGLProgramBuilder.h"
+#include "../GrGpuGL.h"
+
+namespace {
+#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)
+#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)
+// ES2 FS only guarantees mediump and lowp support
+static const GrGLShaderVar::Precision kDefaultFragmentPrecision = GrGLShaderVar::kMedium_Precision;
+static const char kDstCopyColorName[] = "_dstColor";
+inline const char* declared_color_output_name() { return "fsColorOut"; }
+inline const char* dual_source_output_name() { return "dualSourceOut"; }
+inline void append_default_precision_qualifier(GrGLShaderVar::Precision p,
+ GrGLStandard standard,
+ SkString* str) {
+ // Desktop GLSL has added precision qualifiers but they don't do anything.
+ if (kGLES_GrGLStandard == standard) {
+ switch (p) {
+ case GrGLShaderVar::kHigh_Precision:
+ str->append("precision highp float;\n");
+ break;
+ case GrGLShaderVar::kMedium_Precision:
+ str->append("precision mediump float;\n");
+ break;
+ case GrGLShaderVar::kLow_Precision:
+ str->append("precision lowp float;\n");
+ break;
+ case GrGLShaderVar::kDefault_Precision:
+ SkFAIL("Default precision now allowed.");
+ default:
+ SkFAIL("Unknown precision value.");
+ }
+ }
+}
+}
+
+GrGLFragmentShaderBuilder::DstReadKey GrGLFragmentShaderBuilder::KeyForDstRead(
+ const GrTexture* dstCopy, const GrGLCaps& caps) {
+ uint32_t key = kYesDstRead_DstReadKeyBit;
+ if (caps.fbFetchSupport()) {
+ return key;
+ }
+ SkASSERT(NULL != dstCopy);
+ if (!caps.textureSwizzleSupport() && GrPixelConfigIsAlphaOnly(dstCopy->config())) {
+ // The fact that the config is alpha-only must be considered when generating code.
+ key |= kUseAlphaConfig_DstReadKeyBit;
+ }
+ if (kTopLeft_GrSurfaceOrigin == dstCopy->origin()) {
+ key |= kTopLeftOrigin_DstReadKeyBit;
+ }
+ SkASSERT(static_cast<DstReadKey>(key) == key);
+ return static_cast<DstReadKey>(key);
+}
+
+GrGLFragmentShaderBuilder::FragPosKey GrGLFragmentShaderBuilder::KeyForFragmentPosition(
+ const GrRenderTarget* dst, const GrGLCaps&) {
+ if (kTopLeft_GrSurfaceOrigin == dst->origin()) {
+ return kTopLeftFragPosRead_FragPosKey;
+ } else {
+ return kBottomLeftFragPosRead_FragPosKey;
+ }
+}
+
+GrGLFragmentShaderBuilder::GrGLFragmentShaderBuilder(GrGLProgramBuilder* program,
+ const GrGLProgramDesc& desc)
+ : INHERITED(program)
+ , fHasCustomColorOutput(false)
+ , fHasSecondaryOutput(false)
+ , fSetupFragPosition(false)
+ , fTopLeftFragPosRead(kTopLeftFragPosRead_FragPosKey == desc.getHeader().fFragPosKey){
+}
+
+const char* GrGLFragmentShaderBuilder::dstColor() {
+ if (fProgramBuilder->fCodeStage.inStageCode()) {
+ const GrEffect* effect = fProgramBuilder->fCodeStage.effectStage()->getEffect();
+ if (!effect->willReadDstColor()) {
+ SkDEBUGFAIL("GrGLEffect asked for dst color but its generating GrEffect "
+ "did not request access.");
+ return "";
+ }
+ }
+
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ if (gpu->glCaps().fbFetchSupport()) {
+ this->addFeature(1 << (GrGLFragmentShaderBuilder::kLastGLSLPrivateFeature + 1),
+ gpu->glCaps().fbFetchExtensionString());
+ return gpu->glCaps().fbFetchColorName();
+ } else if (fProgramBuilder->fUniformHandles.fDstCopySamplerUni.isValid()) {
+ return kDstCopyColorName;
+ } else {
+ return "";
+ }
+}
+
+bool GrGLFragmentShaderBuilder::enableFeature(GLSLFeature feature) {
+ switch (feature) {
+ case kStandardDerivatives_GLSLFeature: {
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ if (!gpu->glCaps().shaderDerivativeSupport()) {
+ return false;
+ }
+ if (kGLES_GrGLStandard == gpu->glStandard()) {
+ this->addFeature(1 << kStandardDerivatives_GLSLFeature,
+ "GL_OES_standard_derivatives");
+ }
+ return true;
+ }
+ default:
+ SkFAIL("Unexpected GLSLFeature requested.");
+ return false;
+ }
+}
+
+SkString GrGLFragmentShaderBuilder::ensureFSCoords2D(const TransformedCoordsArray& coords, int index) {
+ if (kVec3f_GrSLType != coords[index].type()) {
+ SkASSERT(kVec2f_GrSLType == coords[index].type());
+ return coords[index].getName();
+ }
+
+ SkString coords2D("coords2D");
+ if (0 != index) {
+ coords2D.appendf("_%i", index);
+ }
+ this->codeAppendf("\tvec2 %s = %s.xy / %s.z;",
+ coords2D.c_str(), coords[index].c_str(), coords[index].c_str());
+ return coords2D;
+}
+
+const char* GrGLFragmentShaderBuilder::fragmentPosition() {
+ GrGLProgramBuilder::CodeStage* cs = &fProgramBuilder->fCodeStage;
+ if (cs->inStageCode()) {
+ const GrEffect* effect = cs->effectStage()->getEffect();
+ if (!effect->willReadFragmentPosition()) {
+ SkDEBUGFAIL("GrGLEffect asked for frag position but its generating GrEffect "
+ "did not request access.");
+ return "";
+ }
+ }
+
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ // We only declare "gl_FragCoord" when we're in the case where we want to use layout qualifiers
+ // to reverse y. Otherwise it isn't necessary and whether the "in" qualifier appears in the
+ // declaration varies in earlier GLSL specs. So it is simpler to omit it.
+ if (fTopLeftFragPosRead) {
+ fSetupFragPosition = true;
+ return "gl_FragCoord";
+ } else if (gpu->glCaps().fragCoordConventionsSupport()) {
+ if (!fSetupFragPosition) {
+ if (gpu->glslGeneration() < k150_GrGLSLGeneration) {
+ this->addFeature(1 << kFragCoordConventions_GLSLPrivateFeature,
+ "GL_ARB_fragment_coord_conventions");
+ }
+ fInputs.push_back().set(kVec4f_GrSLType,
+ GrGLShaderVar::kIn_TypeModifier,
+ "gl_FragCoord",
+ GrGLShaderVar::kDefault_Precision,
+ GrGLShaderVar::kUpperLeft_Origin);
+ fSetupFragPosition = true;
+ }
+ return "gl_FragCoord";
+ } else {
+ static const char* kCoordName = "fragCoordYDown";
+ if (!fSetupFragPosition) {
+ // temporarily change the stage index because we're inserting non-stage code.
+ GrGLProgramBuilder::CodeStage::AutoStageRestore csar(cs, NULL);
+
+ SkASSERT(!fProgramBuilder->fUniformHandles.fRTHeightUni.isValid());
+ const char* rtHeightName;
+
+ fProgramBuilder->fUniformHandles.fRTHeightUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kFloat_GrSLType,
+ "RTHeight",
+ &rtHeightName);
+
+ // Using glFragCoord.zw for the last two components tickles an Adreno driver bug that
+ // causes programs to fail to link. Making this function return a vec2() didn't fix the
+ // problem but using 1.0 for the last two components does.
+ this->codePrependf("\tvec4 %s = vec4(gl_FragCoord.x, %s - gl_FragCoord.y, 1.0, "
+ "1.0);\n", kCoordName, rtHeightName);
+ fSetupFragPosition = true;
+ }
+ SkASSERT(fProgramBuilder->fUniformHandles.fRTHeightUni.isValid());
+ return kCoordName;
+ }
+}
+
+void GrGLFragmentShaderBuilder::addVarying(GrSLType type,
+ const char* name,
+ const char** fsInName) {
+ fInputs.push_back().set(type, GrGLShaderVar::kVaryingIn_TypeModifier, name);
+ if (fsInName) {
+ *fsInName = name;
+ }
+}
+
+void GrGLFragmentShaderBuilder::bindProgramLocations(GrGLuint programId) {
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ if (fHasCustomColorOutput) {
+ GL_CALL(BindFragDataLocation(programId, 0, declared_color_output_name()));
+ }
+ if (fHasSecondaryOutput) {
+ GL_CALL(BindFragDataLocationIndexed(programId, 0, 1, dual_source_output_name()));
+ }
+}
+
+bool GrGLFragmentShaderBuilder::compileAndAttachShaders(GrGLuint programId,
+ SkTDArray<GrGLuint>* shaderIds) const {
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ SkString fragShaderSrc(GrGetGLSLVersionDecl(gpu->ctxInfo()));
+ fragShaderSrc.append(fExtensions);
+ append_default_precision_qualifier(kDefaultFragmentPrecision,
+ gpu->glStandard(),
+ &fragShaderSrc);
+ fProgramBuilder->appendUniformDecls(GrGLProgramBuilder::kFragment_Visibility, &fragShaderSrc);
+ fProgramBuilder->appendDecls(fInputs, &fragShaderSrc);
+ // We shouldn't have declared outputs on 1.10
+ SkASSERT(k110_GrGLSLGeneration != gpu->glslGeneration() || fOutputs.empty());
+ fProgramBuilder->appendDecls(fOutputs, &fragShaderSrc);
+ fragShaderSrc.append(fFunctions);
+ fragShaderSrc.append("void main() {\n");
+ fragShaderSrc.append(fCode);
+ fragShaderSrc.append("}\n");
+
+ GrGLuint fragShaderId = GrGLCompileAndAttachShader(gpu->glContext(),
+ programId, GR_GL_FRAGMENT_SHADER, fragShaderSrc);
+ if (!fragShaderId) {
+ return false;
+ }
+
+ *shaderIds->append() = fragShaderId;
+
+ return true;
+}
+
+void GrGLFragmentShaderBuilder::emitCodeBeforeEffects() {
+ const GrGLProgramDesc::KeyHeader& header = fProgramBuilder->desc().getHeader();
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+
+ ///////////////////////////////////////////////////////////////////////////
+ // emit code to read the dst copy texture, if necessary
+ if (kNoDstRead_DstReadKey != header.fDstReadKey && !gpu->glCaps().fbFetchSupport()) {
+ bool topDown = SkToBool(kTopLeftOrigin_DstReadKeyBit & header.fDstReadKey);
+ const char* dstCopyTopLeftName;
+ const char* dstCopyCoordScaleName;
+ const char* dstCopySamplerName;
+ uint32_t configMask;
+ if (SkToBool(kUseAlphaConfig_DstReadKeyBit & header.fDstReadKey)) {
+ configMask = kA_GrColorComponentFlag;
+ } else {
+ configMask = kRGBA_GrColorComponentFlags;
+ }
+ fProgramBuilder->fUniformHandles.fDstCopySamplerUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kSampler2D_GrSLType,
+ "DstCopySampler",
+ &dstCopySamplerName);
+ fProgramBuilder->fUniformHandles.fDstCopyTopLeftUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec2f_GrSLType,
+ "DstCopyUpperLeft",
+ &dstCopyTopLeftName);
+ fProgramBuilder->fUniformHandles.fDstCopyScaleUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec2f_GrSLType,
+ "DstCopyCoordScale",
+ &dstCopyCoordScaleName);
+ const char* fragPos = fragmentPosition();
+
+ this->codeAppend("// Read color from copy of the destination.\n");
+ this->codeAppendf("vec2 _dstTexCoord = (%s.xy - %s) * %s;",
+ fragPos, dstCopyTopLeftName, dstCopyCoordScaleName);
+ if (!topDown) {
+ this->codeAppend("_dstTexCoord.y = 1.0 - _dstTexCoord.y;");
+ }
+ this->codeAppendf("vec4 %s = ", kDstCopyColorName);
+ this->appendTextureLookup(dstCopySamplerName,
+ "_dstTexCoord",
+ configMask,
+ "rgba");
+ this->codeAppend(";");
+ }
+
+ if (k110_GrGLSLGeneration != gpu->glslGeneration()) {
+ fOutputs.push_back().set(kVec4f_GrSLType,
+ GrGLShaderVar::kOut_TypeModifier,
+ declared_color_output_name());
+ fHasCustomColorOutput = true;
+ }
+}
+
+void GrGLFragmentShaderBuilder::emitCodeAfterEffects(const GrGLSLExpr4& inputColor, const GrGLSLExpr4& inputCoverage) {
+ const GrGLProgramDesc::KeyHeader& header = fProgramBuilder->desc().getHeader();
+
+ ///////////////////////////////////////////////////////////////////////////
+ // write the secondary color output if necessary
+ if (GrGLProgramDesc::CoverageOutputUsesSecondaryOutput(header.fCoverageOutput)) {
+ const char* secondaryOutputName = this->enableSecondaryOutput();
+
+ // default coeff to ones for kCoverage_DualSrcOutput
+ GrGLSLExpr4 coeff(1);
+ if (GrGLProgramDesc::kSecondaryCoverageISA_CoverageOutput == header.fCoverageOutput) {
+ // Get (1-A) into coeff
+ coeff = GrGLSLExpr4::VectorCast(GrGLSLExpr1(1) - inputColor.a());
+ } else if (GrGLProgramDesc::kSecondaryCoverageISC_CoverageOutput ==
+ header.fCoverageOutput){
+ // Get (1-RGBA) into coeff
+ coeff = GrGLSLExpr4(1) - inputColor;
+ }
+ // Get coeff * coverage into modulate and then write that to the dual source output.
+ codeAppendf("\t%s = %s;\n", secondaryOutputName, (coeff * inputCoverage).c_str());
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // combine color and coverage as frag color
+
+ // Get "color * coverage" into fragColor
+ GrGLSLExpr4 fragColor = inputColor * inputCoverage;
+ // Now tack on "+(1-coverage)dst onto the frag color if we were asked to do so.
+ if (GrGLProgramDesc::kCombineWithDst_CoverageOutput == header.fCoverageOutput) {
+ GrGLSLExpr4 dstCoeff = GrGLSLExpr4(1) - inputCoverage;
+
+ GrGLSLExpr4 dstContribution = dstCoeff * GrGLSLExpr4(dstColor());
+
+ fragColor = fragColor + dstContribution;
+ }
+ codeAppendf("\t%s = %s;\n", this->getColorOutputName(), fragColor.c_str());
+}
+
+const char* GrGLFragmentShaderBuilder::enableSecondaryOutput() {
+ if (!fHasSecondaryOutput) {
+ fOutputs.push_back().set(kVec4f_GrSLType,
+ GrGLShaderVar::kOut_TypeModifier,
+ dual_source_output_name());
+ fHasSecondaryOutput = true;
+ }
+ return dual_source_output_name();
+}
+
+const char* GrGLFragmentShaderBuilder::getColorOutputName() const {
+ return fHasCustomColorOutput ? declared_color_output_name() : "gl_FragColor";
+}
+
diff --git a/src/gpu/gl/builders/GrGLFragmentShaderBuilder.h b/src/gpu/gl/builders/GrGLFragmentShaderBuilder.h
new file mode 100644
index 0000000000..0f700bd94d
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLFragmentShaderBuilder.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef GrGLFragmentShaderBuilder_DEFINED
+#define GrGLFragmentShaderBuilder_DEFINED
+#include "GrGLShaderBuilder.h"
+
+class GrGLProgramBuilder;
+
+class GrGLFragmentShaderBuilder : public GrGLShaderBuilder {
+public:
+ typedef uint8_t DstReadKey;
+ typedef uint8_t FragPosKey;
+
+ /** Returns a key for adding code to read the copy-of-dst color in service of effects that
+ require reading the dst. It must not return 0 because 0 indicates that there is no dst
+ copy read at all (in which case this function should not be called). */
+ static DstReadKey KeyForDstRead(const GrTexture* dstCopy, const GrGLCaps&);
+
+ /** Returns a key for reading the fragment location. This should only be called if there is an
+ effect that will requires the fragment position. If the fragment position is not required,
+ the key is 0. */
+ static FragPosKey KeyForFragmentPosition(const GrRenderTarget* dst, const GrGLCaps&);
+
+ GrGLFragmentShaderBuilder(GrGLProgramBuilder* program, const GrGLProgramDesc& desc);
+
+ /** Returns the variable name that holds the color of the destination pixel. This may be NULL if
+ no effect advertised that it will read the destination. */
+ const char* dstColor();
+
+ /**
+ * Use of these features may require a GLSL extension to be enabled. Shaders may not compile
+ * if code is added that uses one of these features without calling enableFeature()
+ */
+ enum GLSLFeature {
+ kStandardDerivatives_GLSLFeature = 0,
+ kLastGLSLFeature = kStandardDerivatives_GLSLFeature
+ };
+
+ /**
+ * If the feature is supported then true is returned and any necessary #extension declarations
+ * are added to the shaders. If the feature is not supported then false will be returned.
+ */
+ bool enableFeature(GLSLFeature);
+
+ /**
+ * This returns a variable name to access the 2D, perspective correct version of the coords in
+ * the fragment shader. If the coordinates at index are 3-dimensional, it immediately emits a
+ * perspective divide into the fragment shader (xy / z) to convert them to 2D.
+ */
+ SkString ensureFSCoords2D(const TransformedCoordsArray& coords, int index);
+
+
+ /** Returns a variable name that represents the position of the fragment in the FS. The position
+ is in device space (e.g. 0,0 is the top left and pixel centers are at half-integers). */
+ const char* fragmentPosition();
+
+private:
+ /*
+ * An internal call for GrGLFullProgramBuilder to use to add varyings to the vertex shader
+ */
+ void addVarying(GrSLType type,
+ const char* name,
+ const char** fsInName);
+
+ /*
+ * Private functions used by GrGLProgramBuilder for compilation
+ */
+ void bindProgramLocations(GrGLuint programId);
+ bool compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) const;
+ void emitCodeBeforeEffects();
+ void emitCodeAfterEffects(const GrGLSLExpr4& inputColor, const GrGLSLExpr4& inputCoverage);
+
+ /** Enables using the secondary color output and returns the name of the var in which it is
+ to be stored */
+ const char* enableSecondaryOutput();
+
+ /** Gets the name of the primary color output. */
+ const char* getColorOutputName() const;
+
+ /**
+ * Features that should only be enabled by GrGLFragmentShaderBuilder itself.
+ */
+ enum GLSLPrivateFeature {
+ kFragCoordConventions_GLSLPrivateFeature = kLastGLSLFeature + 1,
+ kLastGLSLPrivateFeature = kFragCoordConventions_GLSLPrivateFeature
+ };
+
+ // Interpretation of DstReadKey when generating code
+ enum {
+ kNoDstRead_DstReadKey = 0,
+ kYesDstRead_DstReadKeyBit = 0x1, // Set if we do a dst-copy-read.
+ kUseAlphaConfig_DstReadKeyBit = 0x2, // Set if dst-copy config is alpha only.
+ kTopLeftOrigin_DstReadKeyBit = 0x4, // Set if dst-copy origin is top-left.
+ };
+
+ enum {
+ kNoFragPosRead_FragPosKey = 0, // The fragment positition will not be needed.
+ kTopLeftFragPosRead_FragPosKey = 0x1,// Read frag pos relative to top-left.
+ kBottomLeftFragPosRead_FragPosKey = 0x2,// Read frag pos relative to bottom-left.
+ };
+
+ bool fHasCustomColorOutput;
+ bool fHasSecondaryOutput;
+ bool fSetupFragPosition;
+ bool fTopLeftFragPosRead;
+
+ friend class GrGLProgramBuilder;
+ friend class GrGLFullProgramBuilder;
+
+ typedef GrGLShaderBuilder INHERITED;
+};
+
+#endif
diff --git a/src/gpu/gl/builders/GrGLGeometryShaderBuilder.cpp b/src/gpu/gl/builders/GrGLGeometryShaderBuilder.cpp
new file mode 100644
index 0000000000..6cdf2f93e0
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLGeometryShaderBuilder.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrGLGeometryShaderBuilder.h"
+#include "GrGLShaderStringBuilder.h"
+#include "GrGLProgramBuilder.h"
+#include "../GrGpuGL.h"
+
+GrGLGeometryShaderBuilder::GrGLGeometryShaderBuilder(GrGLFullProgramBuilder* program)
+ : INHERITED(program) {
+
+}
+
+void GrGLGeometryShaderBuilder::addVarying(GrSLType type,
+ const char* name,
+ const char** gsOutName) {
+ // if we have a GS take each varying in as an array
+ // and output as non-array.
+ fInputs.push_back();
+ fInputs.back().setType(type);
+ fInputs.back().setTypeModifier(GrGLShaderVar::kVaryingIn_TypeModifier);
+ fInputs.back().setUnsizedArray();
+ *fInputs.back().accessName() = name;
+ fOutputs.push_back();
+ fOutputs.back().setType(type);
+ fOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
+ fProgramBuilder->nameVariable(fOutputs.back().accessName(), 'g', name);
+ if (gsOutName) {
+ *gsOutName = fOutputs.back().getName().c_str();
+ }
+}
+
+
+bool GrGLGeometryShaderBuilder::compileAndAttachShaders(GrGLuint programId,
+ SkTDArray<GrGLuint>* shaderIds) const {
+ const GrGLContext& glCtx = fProgramBuilder->gpu()->glContext();
+ SkASSERT(fProgramBuilder->ctxInfo().glslGeneration() >= k150_GrGLSLGeneration);
+ SkString geomShaderSrc(GrGetGLSLVersionDecl(fProgramBuilder->ctxInfo()));
+ geomShaderSrc.append("layout(triangles) in;\n"
+ "layout(triangle_strip, max_vertices = 6) out;\n");
+ fProgramBuilder->appendDecls(fInputs, &geomShaderSrc);
+ fProgramBuilder->appendDecls(fOutputs, &geomShaderSrc);
+ geomShaderSrc.append("void main() {\n");
+ geomShaderSrc.append("\tfor (int i = 0; i < 3; ++i) {\n"
+ "\t\tgl_Position = gl_in[i].gl_Position;\n");
+ if (fProgramBuilder->desc().getHeader().fEmitsPointSize) {
+ geomShaderSrc.append("\t\tgl_PointSize = 1.0;\n");
+ }
+ SkASSERT(fInputs.count() == fOutputs.count());
+ for (int i = 0; i < fInputs.count(); ++i) {
+ geomShaderSrc.appendf("\t\t%s = %s[i];\n",
+ fOutputs[i].getName().c_str(),
+ fInputs[i].getName().c_str());
+ }
+ geomShaderSrc.append("\t\tEmitVertex();\n"
+ "\t}\n"
+ "\tEndPrimitive();\n");
+ geomShaderSrc.append("}\n");
+ GrGLuint geomShaderId =
+ GrGLCompileAndAttachShader(glCtx, programId, GR_GL_GEOMETRY_SHADER, geomShaderSrc);
+ if (!geomShaderId) {
+ return false;
+ }
+ *shaderIds->append() = geomShaderId;
+ return true;
+}
diff --git a/src/gpu/gl/builders/GrGLGeometryShaderBuilder.h b/src/gpu/gl/builders/GrGLGeometryShaderBuilder.h
new file mode 100644
index 0000000000..833d31774f
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLGeometryShaderBuilder.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef GrGLGeometryShaderBuilder_DEFINED
+#define GrGLGeometryShaderBuilder_DEFINED
+
+#include "GrGLShaderBuilder.h"
+
+class GrGLProgramBuilder;
+
+class GrGLGeometryShaderBuilder : public GrGLFullShaderBuilder {
+public:
+ GrGLGeometryShaderBuilder(GrGLFullProgramBuilder* program);
+private:
+ /*
+ * an internal call for GrGLFullProgramBuilder to add varyings
+ */
+ void addVarying(GrSLType type,
+ const char* name,
+ const char** gsOutName);
+
+ bool compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) const;
+
+ friend class GrGLFullProgramBuilder;
+ typedef GrGLFullShaderBuilder INHERITED;
+};
+
+#endif
diff --git a/src/gpu/gl/builders/GrGLProgramBuilder.cpp b/src/gpu/gl/builders/GrGLProgramBuilder.cpp
new file mode 100644
index 0000000000..f4ee32b48d
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLProgramBuilder.cpp
@@ -0,0 +1,409 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "gl/GrGLProgram.h"
+#include "gl/GrGLSLPrettyPrint.h"
+#include "gl/GrGLUniformHandle.h"
+#include "GrCoordTransform.h"
+#include "GrDrawEffect.h"
+#include "../GrGpuGL.h"
+#include "GrGLFragmentShaderBuilder.h"
+#include "GrGLProgramBuilder.h"
+#include "GrTexture.h"
+#include "GrGLVertexShaderBuilder.h"
+#include "SkRTConf.h"
+#include "SkTraceEvent.h"
+
+namespace {
+#define GL_CALL(X) GR_GL_CALL(this->gpu()->glInterface(), X)
+#define GL_CALL_RET(R, X) GR_GL_CALL_RET(this->gpu()->glInterface(), R, X)
+
+// number of each input/output type in a single allocation block
+static const int kVarsPerBlock = 8;
+
+// ES2 FS only guarantees mediump and lowp support
+static const GrGLShaderVar::Precision kDefaultFragmentPrecision = GrGLShaderVar::kMedium_Precision;
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+bool GrGLProgramBuilder::genProgram(const GrEffectStage* colorStages[],
+ const GrEffectStage* coverageStages[]) {
+ const GrGLProgramDesc::KeyHeader& header = this->desc().getHeader();
+
+ fFS.emitCodeBeforeEffects();
+
+ ///////////////////////////////////////////////////////////////////////////
+ // get the initial color and coverage to feed into the first effect in each effect chain
+
+ GrGLSLExpr4 inputColor;
+ GrGLSLExpr4 inputCoverage;
+
+ if (GrGLProgramDesc::kUniform_ColorInput == header.fColorInput) {
+ const char* name;
+ fUniformHandles.fColorUni =
+ this->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec4f_GrSLType,
+ "Color",
+ &name);
+ inputColor = GrGLSLExpr4(name);
+ }
+
+ if (GrGLProgramDesc::kUniform_ColorInput == header.fCoverageInput) {
+ const char* name;
+ fUniformHandles.fCoverageUni =
+ this->addUniform(GrGLProgramBuilder::kFragment_Visibility,
+ kVec4f_GrSLType,
+ "Coverage",
+ &name);
+ inputCoverage = GrGLSLExpr4(name);
+ } else if (GrGLProgramDesc::kSolidWhite_ColorInput == header.fCoverageInput) {
+ inputCoverage = GrGLSLExpr4(1);
+ }
+
+ this->emitCodeBeforeEffects(&inputColor, &inputCoverage);
+
+ ///////////////////////////////////////////////////////////////////////////
+ // emit the per-effect code for both color and coverage effects
+
+ GrGLProgramDesc::EffectKeyProvider colorKeyProvider(
+ &this->desc(), GrGLProgramDesc::EffectKeyProvider::kColor_EffectType);
+ fColorEffects.reset(this->createAndEmitEffects(colorStages,
+ this->desc().numColorEffects(),
+ colorKeyProvider,
+ &inputColor));
+
+ GrGLProgramDesc::EffectKeyProvider coverageKeyProvider(
+ &this->desc(), GrGLProgramDesc::EffectKeyProvider::kCoverage_EffectType);
+ fCoverageEffects.reset(this->createAndEmitEffects(coverageStages,
+ this->desc().numCoverageEffects(),
+ coverageKeyProvider,
+ &inputCoverage));
+
+ this->emitCodeAfterEffects();
+
+ fFS.emitCodeAfterEffects(inputColor, inputCoverage);
+
+ if (!this->finish()) {
+ return false;
+ }
+
+ return true;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+GrGLProgramBuilder::GrGLProgramBuilder(GrGpuGL* gpu,
+ const GrGLProgramDesc& desc)
+ : fFragOnly(!desc.getHeader().fHasVertexCode && gpu->shouldUseFixedFunctionTexturing())
+ , fTexCoordSetCnt(0)
+ , fProgramID(0)
+ , fFS(this, desc)
+ , fDesc(desc)
+ , fGpu(gpu)
+ , fUniforms(kVarsPerBlock) {
+}
+
+void GrGLProgramBuilder::nameVariable(SkString* out, char prefix, const char* name) {
+ if ('\0' == prefix) {
+ *out = name;
+ } else {
+ out->printf("%c%s", prefix, name);
+ }
+ if (fCodeStage.inStageCode()) {
+ if (out->endsWith('_')) {
+ // Names containing "__" are reserved.
+ out->append("x");
+ }
+ out->appendf("_Stage%d", fCodeStage.stageIndex());
+ }
+}
+
+GrGLProgramDataManager::UniformHandle GrGLProgramBuilder::addUniformArray(uint32_t visibility,
+ GrSLType type,
+ const char* name,
+ int count,
+ const char** outName) {
+ SkASSERT(name && strlen(name));
+ SkDEBUGCODE(static const uint32_t kVisibilityMask = kVertex_Visibility | kFragment_Visibility);
+ SkASSERT(0 == (~kVisibilityMask & visibility));
+ SkASSERT(0 != visibility);
+
+ UniformInfo& uni = fUniforms.push_back();
+ uni.fVariable.setType(type);
+ uni.fVariable.setTypeModifier(GrGLShaderVar::kUniform_TypeModifier);
+ this->nameVariable(uni.fVariable.accessName(), 'u', name);
+ uni.fVariable.setArrayCount(count);
+ uni.fVisibility = visibility;
+
+ // If it is visible in both the VS and FS, the precision must match.
+ // We declare a default FS precision, but not a default VS. So set the var
+ // to use the default FS precision.
+ if ((kVertex_Visibility | kFragment_Visibility) == visibility) {
+ // the fragment and vertex precisions must match
+ uni.fVariable.setPrecision(kDefaultFragmentPrecision);
+ }
+
+ if (NULL != outName) {
+ *outName = uni.fVariable.c_str();
+ }
+ return GrGLProgramDataManager::UniformHandle::CreateFromUniformIndex(fUniforms.count() - 1);
+}
+
+void GrGLProgramBuilder::appendDecls(const VarArray& vars, SkString* out) const {
+ for (int i = 0; i < vars.count(); ++i) {
+ vars[i].appendDecl(this->ctxInfo(), out);
+ out->append(";\n");
+ }
+}
+
+void GrGLProgramBuilder::appendUniformDecls(ShaderVisibility visibility,
+ SkString* out) const {
+ for (int i = 0; i < fUniforms.count(); ++i) {
+ if (fUniforms[i].fVisibility & visibility) {
+ fUniforms[i].fVariable.appendDecl(this->ctxInfo(), out);
+ out->append(";\n");
+ }
+ }
+}
+
+void GrGLProgramBuilder::createAndEmitEffects(GrGLProgramEffectsBuilder* programEffectsBuilder,
+ const GrEffectStage* effectStages[],
+ int effectCnt,
+ const GrGLProgramDesc::EffectKeyProvider& keyProvider,
+ GrGLSLExpr4* fsInOutColor) {
+ bool effectEmitted = false;
+
+ GrGLSLExpr4 inColor = *fsInOutColor;
+ GrGLSLExpr4 outColor;
+
+ for (int e = 0; e < effectCnt; ++e) {
+ SkASSERT(NULL != effectStages[e] && NULL != effectStages[e]->getEffect());
+ const GrEffectStage& stage = *effectStages[e];
+
+ CodeStage::AutoStageRestore csar(&fCodeStage, &stage);
+
+ if (inColor.isZeros()) {
+ SkString inColorName;
+
+ // Effects have no way to communicate zeros, they treat an empty string as ones.
+ this->nameVariable(&inColorName, '\0', "input");
+ fFS.codeAppendf("\tvec4 %s = %s;\n", inColorName.c_str(), inColor.c_str());
+ inColor = inColorName;
+ }
+
+ // create var to hold stage result
+ SkString outColorName;
+ this->nameVariable(&outColorName, '\0', "output");
+ fFS.codeAppendf("\tvec4 %s;\n", outColorName.c_str());
+ outColor = outColorName;
+
+
+ programEffectsBuilder->emitEffect(stage,
+ keyProvider.get(e),
+ outColor.c_str(),
+ inColor.isOnes() ? NULL : inColor.c_str(),
+ fCodeStage.stageIndex());
+
+ inColor = outColor;
+ effectEmitted = true;
+ }
+
+ if (effectEmitted) {
+ *fsInOutColor = outColor;
+ }
+}
+
+bool GrGLProgramBuilder::finish() {
+ SkASSERT(0 == fProgramID);
+ GL_CALL_RET(fProgramID, CreateProgram());
+ if (!fProgramID) {
+ return false;
+ }
+
+ SkTDArray<GrGLuint> shadersToDelete;
+
+ if (!this->compileAndAttachShaders(fProgramID, &shadersToDelete)) {
+ GL_CALL(DeleteProgram(fProgramID));
+ return false;
+ }
+
+ this->bindProgramLocations(fProgramID);
+
+ GL_CALL(LinkProgram(fProgramID));
+
+ // Calling GetProgramiv is expensive in Chromium. Assume success in release builds.
+ bool checkLinked = !fGpu->ctxInfo().isChromium();
+#ifdef SK_DEBUG
+ checkLinked = true;
+#endif
+ if (checkLinked) {
+ GrGLint linked = GR_GL_INIT_ZERO;
+ GL_CALL(GetProgramiv(fProgramID, GR_GL_LINK_STATUS, &linked));
+ if (!linked) {
+ GrGLint infoLen = GR_GL_INIT_ZERO;
+ GL_CALL(GetProgramiv(fProgramID, GR_GL_INFO_LOG_LENGTH, &infoLen));
+ SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
+ if (infoLen > 0) {
+ // retrieve length even though we don't need it to workaround
+ // bug in chrome cmd buffer param validation.
+ GrGLsizei length = GR_GL_INIT_ZERO;
+ GL_CALL(GetProgramInfoLog(fProgramID,
+ infoLen+1,
+ &length,
+ (char*)log.get()));
+ GrPrintf((char*)log.get());
+ }
+ SkDEBUGFAIL("Error linking program");
+ GL_CALL(DeleteProgram(fProgramID));
+ fProgramID = 0;
+ return false;
+ }
+ }
+
+ this->resolveProgramLocations(fProgramID);
+
+ for (int i = 0; i < shadersToDelete.count(); ++i) {
+ GL_CALL(DeleteShader(shadersToDelete[i]));
+ }
+
+ return true;
+}
+
+bool GrGLProgramBuilder::compileAndAttachShaders(GrGLuint programId,
+ SkTDArray<GrGLuint>* shaderIds) const {
+ return fFS.compileAndAttachShaders(programId, shaderIds);
+}
+
+void GrGLProgramBuilder::bindProgramLocations(GrGLuint programId) {
+ fFS.bindProgramLocations(programId);
+
+ // skbug.com/2056
+ bool usingBindUniform = fGpu->glInterface()->fFunctions.fBindUniformLocation != NULL;
+ if (usingBindUniform) {
+ int count = fUniforms.count();
+ for (int i = 0; i < count; ++i) {
+ GL_CALL(BindUniformLocation(programId, i, fUniforms[i].fVariable.c_str()));
+ fUniforms[i].fLocation = i;
+ }
+ }
+}
+
+void GrGLProgramBuilder::resolveProgramLocations(GrGLuint programId) {
+ bool usingBindUniform = fGpu->glInterface()->fFunctions.fBindUniformLocation != NULL;
+ if (!usingBindUniform) {
+ int count = fUniforms.count();
+ for (int i = 0; i < count; ++i) {
+ GrGLint location;
+ GL_CALL_RET(location,
+ GetUniformLocation(programId, fUniforms[i].fVariable.c_str()));
+ fUniforms[i].fLocation = location;
+ }
+ }
+}
+
+const GrGLContextInfo& GrGLProgramBuilder::ctxInfo() const {
+ return fGpu->ctxInfo();
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+GrGLFullProgramBuilder::GrGLFullProgramBuilder(GrGpuGL* gpu,
+ const GrGLProgramDesc& desc)
+ : INHERITED(gpu, desc)
+ , fGS(this)
+ , fVS(this) {
+}
+
+void GrGLFullProgramBuilder::emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) {
+ fVS.emitCodeBeforeEffects(color, coverage);
+}
+
+void GrGLFullProgramBuilder::emitCodeAfterEffects() {
+ fVS.emitCodeAfterEffects();
+}
+
+void GrGLFullProgramBuilder::addVarying(GrSLType type,
+ const char* name,
+ const char** vsOutName,
+ const char** fsInName) {
+ fVS.addVarying(type, name, vsOutName);
+
+ SkString* fsInputName = fVS.fOutputs.back().accessName();
+
+#if GR_GL_EXPERIMENTAL_GS
+ if (desc().getHeader().fExperimentalGS) {
+ // TODO let the caller use these names
+ fGS.addVarying(type, fsInputName->c_str(), NULL);
+ fsInputName = fGS.fOutputs.back().accessName();
+ }
+#endif
+ fFS.addVarying(type, fsInputName->c_str(), fsInName);
+}
+
+GrGLProgramEffects* GrGLFullProgramBuilder::createAndEmitEffects(
+ const GrEffectStage* effectStages[],
+ int effectCnt,
+ const GrGLProgramDesc::EffectKeyProvider& keyProvider,
+ GrGLSLExpr4* inOutFSColor) {
+
+ GrGLVertexProgramEffectsBuilder programEffectsBuilder(this, effectCnt);
+ this->INHERITED::createAndEmitEffects(&programEffectsBuilder,
+ effectStages,
+ effectCnt,
+ keyProvider,
+ inOutFSColor);
+ return programEffectsBuilder.finish();
+}
+
+bool GrGLFullProgramBuilder::compileAndAttachShaders(GrGLuint programId,
+ SkTDArray<GrGLuint>* shaderIds) const {
+ return INHERITED::compileAndAttachShaders(programId, shaderIds)
+ && fVS.compileAndAttachShaders(programId, shaderIds)
+#if GR_GL_EXPERIMENTAL_GS
+ && (!desc().getHeader().fExperimentalGS
+ || fGS.compileAndAttachShaders(programId, shaderIds))
+#endif
+ ;
+}
+
+void GrGLFullProgramBuilder::bindProgramLocations(GrGLuint programId) {
+ fVS.bindProgramLocations(programId);
+ INHERITED::bindProgramLocations(programId);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+GrGLFragmentOnlyProgramBuilder::GrGLFragmentOnlyProgramBuilder(GrGpuGL* gpu,
+ const GrGLProgramDesc& desc)
+ : INHERITED(gpu, desc) {
+ SkASSERT(!desc.getHeader().fHasVertexCode);
+ SkASSERT(gpu->glCaps().pathRenderingSupport());
+ SkASSERT(GrGLProgramDesc::kAttribute_ColorInput != desc.getHeader().fColorInput);
+ SkASSERT(GrGLProgramDesc::kAttribute_ColorInput != desc.getHeader().fCoverageInput);
+}
+
+int GrGLFragmentOnlyProgramBuilder::addTexCoordSets(int count) {
+ int firstFreeCoordSet = fTexCoordSetCnt;
+ fTexCoordSetCnt += count;
+ SkASSERT(gpu()->glCaps().maxFixedFunctionTextureCoords() >= fTexCoordSetCnt);
+ return firstFreeCoordSet;
+}
+
+GrGLProgramEffects* GrGLFragmentOnlyProgramBuilder::createAndEmitEffects(
+ const GrEffectStage* effectStages[], int effectCnt,
+ const GrGLProgramDesc::EffectKeyProvider& keyProvider, GrGLSLExpr4* inOutFSColor) {
+
+ GrGLPathTexGenProgramEffectsBuilder pathTexGenEffectsBuilder(this,
+ effectCnt);
+ this->INHERITED::createAndEmitEffects(&pathTexGenEffectsBuilder,
+ effectStages,
+ effectCnt,
+ keyProvider,
+ inOutFSColor);
+ return pathTexGenEffectsBuilder.finish();
+}
diff --git a/src/gpu/gl/GrGLShaderBuilder.h b/src/gpu/gl/builders/GrGLProgramBuilder.h
index 2a14a1f625..09f7eba511 100644
--- a/src/gpu/gl/GrGLShaderBuilder.h
+++ b/src/gpu/gl/builders/GrGLProgramBuilder.h
@@ -1,17 +1,20 @@
/*
- * Copyright 2012 Google Inc.
+ * Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
-#ifndef GrGLShaderBuilder_DEFINED
-#define GrGLShaderBuilder_DEFINED
+#ifndef GrGLProgramBuilder_DEFINED
+#define GrGLProgramBuilder_DEFINED
#include "GrAllocator.h"
#include "GrBackendEffectFactory.h"
#include "GrColor.h"
#include "GrEffect.h"
+#include "GrGLFragmentShaderBuilder.h"
+#include "GrGLGeometryShaderBuilder.h"
+#include "GrGLVertexShaderBuilder.h"
#include "SkTypes.h"
#include "gl/GrGLProgramDesc.h"
#include "gl/GrGLProgramEffects.h"
@@ -28,12 +31,8 @@ class GrGLProgramDesc;
Contains all the incremental state of a shader as it is being built,as well as helpers to
manipulate that state.
*/
-class GrGLShaderBuilder {
+class GrGLProgramBuilder {
public:
- typedef GrTAllocator<GrGLShaderVar> VarArray;
- typedef GrGLProgramEffects::TextureSampler TextureSampler;
- typedef GrGLProgramEffects::TransformedCoordsArray TransformedCoordsArray;
-
enum ShaderVisibility {
kVertex_Visibility = 0x1,
kGeometry_Visibility = 0x2,
@@ -89,87 +88,11 @@ public:
return fUniformHandles;
}
GrGLuint getProgramID() const { SkASSERT(fProgramID); return fProgramID; }
- bool hasVertexShader() const { SkASSERT(fProgramID); return fHasVertexShader; }
+ bool hasVertexShader() const { SkASSERT(fProgramID); return !fFragOnly; }
int getTexCoordSetCount() const { SkASSERT(fProgramID); return fTexCoordSetCnt; }
const UniformInfoArray& getUniformInfos() const { return fUniforms; }
- virtual ~GrGLShaderBuilder() {}
-
- /**
- * Use of these features may require a GLSL extension to be enabled. Shaders may not compile
- * if code is added that uses one of these features without calling enableFeature()
- */
- enum GLSLFeature {
- kStandardDerivatives_GLSLFeature = 0,
-
- kLastGLSLFeature = kStandardDerivatives_GLSLFeature
- };
-
- /**
- * If the feature is supported then true is returned and any necessary #extension declarations
- * are added to the shaders. If the feature is not supported then false will be returned.
- */
- bool enableFeature(GLSLFeature);
-
- /**
- * Called by GrGLEffects to add code the fragment shader.
- */
- void fsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
- va_list args;
- va_start(args, format);
- fFSCode.appendVAList(format, args);
- va_end(args);
- }
-
- void fsCodeAppend(const char* str) { fFSCode.append(str); }
-
- /** Appends a 2D texture sample with projection if necessary. coordType must either be Vec2f or
- Vec3f. The latter is interpreted as projective texture coords. The vec length and swizzle
- order of the result depends on the GrTextureAccess associated with the TextureSampler. */
- void appendTextureLookup(SkString* out,
- const TextureSampler&,
- const char* coordName,
- GrSLType coordType = kVec2f_GrSLType) const;
-
- /** Version of above that appends the result to the fragment shader code instead.*/
- void fsAppendTextureLookup(const TextureSampler&,
- const char* coordName,
- GrSLType coordType = kVec2f_GrSLType);
-
-
- /** Does the work of appendTextureLookup and modulates the result by modulation. The result is
- always a vec4. modulation and the swizzle specified by TextureSampler must both be vec4 or
- float. If modulation is "" or NULL it this function acts as though appendTextureLookup were
- called. */
- void fsAppendTextureLookupAndModulate(const char* modulation,
- const TextureSampler&,
- const char* coordName,
- GrSLType coordType = kVec2f_GrSLType);
-
- /** Emits a helper function outside of main() in the fragment shader. */
- void fsEmitFunction(GrSLType returnType,
- const char* name,
- int argCnt,
- const GrGLShaderVar* args,
- const char* body,
- SkString* outName);
-
- typedef uint8_t DstReadKey;
- typedef uint8_t FragPosKey;
-
- /** Returns a key for adding code to read the copy-of-dst color in service of effects that
- require reading the dst. It must not return 0 because 0 indicates that there is no dst
- copy read at all (in which case this function should not be called). */
- static DstReadKey KeyForDstRead(const GrTexture* dstCopy, const GrGLCaps&);
-
- /** Returns a key for reading the fragment location. This should only be called if there is an
- effect that will requires the fragment position. If the fragment position is not required,
- the key is 0. */
- static FragPosKey KeyForFragmentPosition(const GrRenderTarget* dst, const GrGLCaps&);
-
- /** If texture swizzling is available using tex parameters then it is preferred over mangling
- the generated shader code. This potentially allows greater reuse of cached shaders. */
- static const GrGLenum* GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps);
+ virtual ~GrGLProgramBuilder() {}
/** Add a uniform variable to the current program, that has visibility in one or more shaders.
visibility is a bitfield of ShaderVisibility values indicating from which shaders the
@@ -200,52 +123,18 @@ public:
return this->getUniformVariable(u).c_str();
}
- /**
- * This returns a variable name to access the 2D, perspective correct version of the coords in
- * the fragment shader. If the coordinates at index are 3-dimensional, it immediately emits a
- * perspective divide into the fragment shader (xy / z) to convert them to 2D.
- */
- SkString ensureFSCoords2D(const TransformedCoordsArray&, int index);
-
- /** Returns a variable name that represents the position of the fragment in the FS. The position
- is in device space (e.g. 0,0 is the top left and pixel centers are at half-integers). */
- const char* fragmentPosition();
-
- /** Returns the variable name that holds the color of the destination pixel. This may be NULL if
- no effect advertised that it will read the destination. */
- const char* dstColor();
-
const GrGLContextInfo& ctxInfo() const;
- /**
- * Helper for begining and ending a block in the fragment code. TODO: Make GrGLShaderBuilder
- * aware of all blocks and turn single \t's into the correct number of tabs (or spaces) so that
- * our shaders print pretty without effect writers tracking indentation.
- */
- class FSBlock {
- public:
- FSBlock(GrGLShaderBuilder* builder) : fBuilder(builder) {
- SkASSERT(NULL != builder);
- fBuilder->fsCodeAppend("\t{\n");
- }
-
- ~FSBlock() {
- fBuilder->fsCodeAppend("\t}\n");
- }
- private:
- GrGLShaderBuilder* fBuilder;
- };
+ GrGLFragmentShaderBuilder* getFragmentShaderBuilder() { return &fFS; }
protected:
- GrGLShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
+ typedef GrTAllocator<GrGLShaderVar> VarArray;
+ GrGLProgramBuilder(GrGpuGL*, const GrGLProgramDesc&);
GrGpuGL* gpu() const { return fGpu; }
const GrGLProgramDesc& desc() const { return fDesc; }
- /** Add input/output variable declarations (i.e. 'varying') to the fragment shader. */
- GrGLShaderVar& fsInputAppend() { return fFSInputs.push_back(); }
-
// Helper for emitEffects().
void createAndEmitEffects(GrGLProgramEffectsBuilder*,
const GrEffectStage* effectStages[],
@@ -269,9 +158,10 @@ protected:
SkAutoTUnref<GrGLProgramEffects> fColorEffects;
SkAutoTUnref<GrGLProgramEffects> fCoverageEffects;
BuiltinUniformHandles fUniformHandles;
- bool fHasVertexShader;
+ bool fFragOnly;
int fTexCoordSetCnt;
GrGLuint fProgramID;
+ GrGLFragmentShaderBuilder fFS;
private:
class CodeStage : SkNoncopyable {
public:
@@ -351,84 +241,27 @@ private:
*/
virtual void emitCodeAfterEffects() = 0;
- /** Enables using the secondary color output and returns the name of the var in which it is
- to be stored */
- const char* enableSecondaryOutput();
- /** Gets the name of the primary color output. */
- const char* getColorOutputName() const;
-
/**
* Compiles all the shaders, links them into a program, and writes the program id to the output
* struct.
**/
bool finish();
- /**
- * Features that should only be enabled by GrGLShaderBuilder itself.
- */
- enum GLSLPrivateFeature {
- kFragCoordConventions_GLSLPrivateFeature = kLastGLSLFeature + 1,
- kLastGLSLPrivateFeature = kFragCoordConventions_GLSLPrivateFeature
- };
- bool enablePrivateFeature(GLSLPrivateFeature);
-
- // If we ever have VS/GS features we can expand this to take a bitmask of ShaderVisibility and
- // track the enables separately for each shader.
- void addFSFeature(uint32_t featureBit, const char* extensionName);
-
- // Interpretation of DstReadKey when generating code
- enum {
- kNoDstRead_DstReadKey = 0,
- kYesDstRead_DstReadKeyBit = 0x1, // Set if we do a dst-copy-read.
- kUseAlphaConfig_DstReadKeyBit = 0x2, // Set if dst-copy config is alpha only.
- kTopLeftOrigin_DstReadKeyBit = 0x4, // Set if dst-copy origin is top-left.
- };
-
- enum {
- kNoFragPosRead_FragPosKey = 0, // The fragment positition will not be needed.
- kTopLeftFragPosRead_FragPosKey = 0x1,// Read frag pos relative to top-left.
- kBottomLeftFragPosRead_FragPosKey = 0x2,// Read frag pos relative to bottom-left.
- };
-
const GrGLProgramDesc& fDesc;
GrGpuGL* fGpu;
- uint32_t fFSFeaturesAddedMask;
- SkString fFSFunctions;
- SkString fFSExtensions;
- VarArray fFSInputs;
- VarArray fFSOutputs;
UniformInfoArray fUniforms;
- SkString fFSCode;
-
- bool fSetupFragPosition;
- bool fTopLeftFragPosRead;
-
- bool fHasCustomColorOutput;
- bool fHasSecondaryOutput;
+ friend class GrGLShaderBuilder;
+ friend class GrGLVertexShaderBuilder;
+ friend class GrGLFragmentShaderBuilder;
+ friend class GrGLGeometryShaderBuilder;
};
////////////////////////////////////////////////////////////////////////////////
-class GrGLFullShaderBuilder : public GrGLShaderBuilder {
+class GrGLFullProgramBuilder : public GrGLProgramBuilder {
public:
- GrGLFullShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
-
- /**
- * Called by GrGLEffects to add code to one of the shaders.
- */
- void vsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
- va_list args;
- va_start(args, format);
- fVSCode.appendVAList(format, args);
- va_end(args);
- }
-
- void vsCodeAppend(const char* str) { fVSCode.append(str); }
-
- /** Add a vertex attribute to the current program that is passed in from the vertex data.
- Returns false if the attribute was already there, true otherwise. */
- bool addAttribute(GrSLType type, const char* name);
+ GrGLFullProgramBuilder(GrGpuGL*, const GrGLProgramDesc&);
/** Add a varying variable to the current program to pass values between vertex and fragment
shaders. If the last two parameters are non-NULL, they are filled in with the name
@@ -438,23 +271,7 @@ public:
const char** vsOutName = NULL,
const char** fsInName = NULL);
- /** Returns a vertex attribute that represents the vertex position in the VS. This is the
- pre-matrix position and is commonly used by effects to compute texture coords via a matrix.
- */
- const GrGLShaderVar& positionAttribute() const { return *fPositionVar; }
-
- /** Returns a vertex attribute that represents the local coords in the VS. This may be the same
- as positionAttribute() or it may not be. It depends upon whether the rendering code
- specified explicit local coords or not in the GrDrawState. */
- const GrGLShaderVar& localCoordsAttribute() const { return *fLocalCoordsVar; }
-
- /**
- * Are explicit local coordinates provided as input to the vertex shader.
- */
- bool hasExplicitLocalCoords() const { return (fLocalCoordsVar != fPositionVar); }
-
- bool addEffectAttribute(int attributeIndex, GrSLType type, const SkString& name);
- const SkString* getEffectAttributeName(int attributeIndex) const;
+ GrGLVertexShaderBuilder* getVertexShaderBuilder() { return &fVS; }
private:
virtual void emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) SK_OVERRIDE;
@@ -471,33 +288,17 @@ private:
virtual void bindProgramLocations(GrGLuint programId) SK_OVERRIDE;
- VarArray fVSAttrs;
- VarArray fVSOutputs;
- VarArray fGSInputs;
- VarArray fGSOutputs;
-
- SkString fVSCode;
-
- struct AttributePair {
- void set(int index, const SkString& name) {
- fIndex = index; fName = name;
- }
- int fIndex;
- SkString fName;
- };
- SkSTArray<10, AttributePair, true> fEffectAttributes;
-
- GrGLShaderVar* fPositionVar;
- GrGLShaderVar* fLocalCoordsVar;
+ GrGLGeometryShaderBuilder fGS;
+ GrGLVertexShaderBuilder fVS;
- typedef GrGLShaderBuilder INHERITED;
+ typedef GrGLProgramBuilder INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
-class GrGLFragmentOnlyShaderBuilder : public GrGLShaderBuilder {
+class GrGLFragmentOnlyProgramBuilder : public GrGLProgramBuilder {
public:
- GrGLFragmentOnlyShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
+ GrGLFragmentOnlyProgramBuilder(GrGpuGL*, const GrGLProgramDesc&);
int addTexCoordSets(int count);
@@ -511,7 +312,7 @@ private:
virtual void emitCodeAfterEffects() SK_OVERRIDE {}
- typedef GrGLShaderBuilder INHERITED;
+ typedef GrGLProgramBuilder INHERITED;
};
#endif
diff --git a/src/gpu/gl/GrGLSLPrettyPrint.cpp b/src/gpu/gl/builders/GrGLSLPrettyPrint.cpp
index 27f4b44e66..27f4b44e66 100644
--- a/src/gpu/gl/GrGLSLPrettyPrint.cpp
+++ b/src/gpu/gl/builders/GrGLSLPrettyPrint.cpp
diff --git a/src/gpu/gl/builders/GrGLShaderBuilder.cpp b/src/gpu/gl/builders/GrGLShaderBuilder.cpp
new file mode 100644
index 0000000000..4dea142632
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLShaderBuilder.cpp
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrGLShaderBuilder.h"
+#include "GrGLProgramBuilder.h"
+#include "../GrGpuGL.h"
+#include "../GrGLShaderVar.h"
+
+namespace {
+inline const char* sample_function_name(GrSLType type, GrGLSLGeneration glslGen) {
+ if (kVec2f_GrSLType == type) {
+ return glslGen >= k130_GrGLSLGeneration ? "texture" : "texture2D";
+ } else {
+ SkASSERT(kVec3f_GrSLType == type);
+ return glslGen >= k130_GrGLSLGeneration ? "textureProj" : "texture2DProj";
+ }
+}
+void append_texture_lookup(SkString* out,
+ GrGpuGL* gpu,
+ const char* samplerName,
+ const char* coordName,
+ uint32_t configComponentMask,
+ const char* swizzle,
+ GrSLType varyingType = kVec2f_GrSLType) {
+ SkASSERT(NULL != coordName);
+
+ out->appendf("%s(%s, %s)",
+ sample_function_name(varyingType, gpu->glslGeneration()),
+ samplerName,
+ coordName);
+
+ char mangledSwizzle[5];
+
+ // The swizzling occurs using texture params instead of shader-mangling if ARB_texture_swizzle
+ // is available.
+ if (!gpu->glCaps().textureSwizzleSupport() &&
+ (kA_GrColorComponentFlag == configComponentMask)) {
+ char alphaChar = gpu->glCaps().textureRedSupport() ? 'r' : 'a';
+ int i;
+ for (i = 0; '\0' != swizzle[i]; ++i) {
+ mangledSwizzle[i] = alphaChar;
+ }
+ mangledSwizzle[i] ='\0';
+ swizzle = mangledSwizzle;
+ }
+ // For shader prettiness we omit the swizzle rather than appending ".rgba".
+ if (memcmp(swizzle, "rgba", 4)) {
+ out->appendf(".%s", swizzle);
+ }
+}
+static const int kVarsPerBlock = 8;
+}
+
+GrGLShaderBuilder::GrGLShaderBuilder(GrGLProgramBuilder* program)
+ : fProgramBuilder(program)
+ , fInputs(kVarsPerBlock)
+ , fOutputs(kVarsPerBlock)
+ , fFeaturesAddedMask(0) {
+}
+
+void GrGLShaderBuilder::emitFunction(GrSLType returnType,
+ const char* name,
+ int argCnt,
+ const GrGLShaderVar* args,
+ const char* body,
+ SkString* outName) {
+ fFunctions.append(GrGLSLTypeString(returnType));
+ fProgramBuilder->nameVariable(outName, '\0', name);
+ fFunctions.appendf(" %s", outName->c_str());
+ fFunctions.append("(");
+ const GrGLContextInfo& ctxInfo = fProgramBuilder->gpu()->ctxInfo();
+ for (int i = 0; i < argCnt; ++i) {
+ args[i].appendDecl(ctxInfo, &fFunctions);
+ if (i < argCnt - 1) {
+ fFunctions.append(", ");
+ }
+ }
+ fFunctions.append(") {\n");
+ fFunctions.append(body);
+ fFunctions.append("}\n\n");
+}
+
+void GrGLShaderBuilder::appendTextureLookup(SkString* out,
+ const TextureSampler& sampler,
+ const char* coordName,
+ GrSLType varyingType) const {
+ append_texture_lookup(out,
+ fProgramBuilder->gpu(),
+ fProgramBuilder->getUniformCStr(sampler.samplerUniform()),
+ coordName,
+ sampler.configComponentMask(),
+ sampler.swizzle(),
+ varyingType);
+}
+
+void GrGLShaderBuilder::appendTextureLookup(const TextureSampler& sampler,
+ const char* coordName,
+ GrSLType varyingType) {
+ this->appendTextureLookup(&fCode, sampler, coordName, varyingType);
+}
+
+void GrGLShaderBuilder::appendTextureLookupAndModulate(const char* modulation,
+ const TextureSampler& sampler,
+ const char* coordName,
+ GrSLType varyingType) {
+ SkString lookup;
+ this->appendTextureLookup(&lookup, sampler, coordName, varyingType);
+ this->codeAppend((GrGLSLExpr4(modulation) * GrGLSLExpr4(lookup)).c_str());
+}
+
+
+const GrGLenum* GrGLShaderBuilder::GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps) {
+ if (caps.textureSwizzleSupport() && GrPixelConfigIsAlphaOnly(config)) {
+ if (caps.textureRedSupport()) {
+ static const GrGLenum gRedSmear[] = { GR_GL_RED, GR_GL_RED, GR_GL_RED, GR_GL_RED };
+ return gRedSmear;
+ } else {
+ static const GrGLenum gAlphaSmear[] = { GR_GL_ALPHA, GR_GL_ALPHA,
+ GR_GL_ALPHA, GR_GL_ALPHA };
+ return gAlphaSmear;
+ }
+ } else {
+ static const GrGLenum gStraight[] = { GR_GL_RED, GR_GL_GREEN, GR_GL_BLUE, GR_GL_ALPHA };
+ return gStraight;
+ }
+}
+
+void GrGLShaderBuilder::addFeature(uint32_t featureBit, const char* extensionName) {
+ if (!(featureBit & fFeaturesAddedMask)) {
+ fExtensions.appendf("#extension %s: require\n", extensionName);
+ fFeaturesAddedMask |= featureBit;
+ }
+}
+
+void GrGLShaderBuilder::appendTextureLookup(const char* samplerName,
+ const char* coordName,
+ uint32_t configComponentMask,
+ const char* swizzle) {
+ append_texture_lookup(&fCode,
+ fProgramBuilder->gpu(),
+ samplerName,
+ coordName,
+ configComponentMask,
+ swizzle,
+ kVec2f_GrSLType);
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+GrGLFullShaderBuilder::GrGLFullShaderBuilder(GrGLFullProgramBuilder* program)
+ : INHERITED(program)
+ , fFullProgramBuilder(program) {}
diff --git a/src/gpu/gl/builders/GrGLShaderBuilder.h b/src/gpu/gl/builders/GrGLShaderBuilder.h
new file mode 100644
index 0000000000..1d0fa6a790
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLShaderBuilder.h
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef GrGLShaderBuilder_DEFINED
+#define GrGLShaderBuilder_DEFINED
+
+#include "gl/GrGLProgramDesc.h"
+#include "gl/GrGLProgramEffects.h"
+#include "gl/GrGLSL.h"
+#include "gl/GrGLProgramDataManager.h"
+#include "GrAllocator.h"
+#include "GrBackendEffectFactory.h"
+#include "GrColor.h"
+#include "GrEffect.h"
+#include "SkTypes.h"
+
+#include <stdarg.h>
+
+class GrGLContextInfo;
+class GrEffectStage;
+class GrGLProgramDesc;
+class GrGLProgramBuilder;
+class GrGLFullProgramBuilder;
+
+/**
+ base class for all shaders builders
+*/
+class GrGLShaderBuilder {
+public:
+ typedef GrGLProgramEffects::TransformedCoordsArray TransformedCoordsArray;
+ typedef GrGLProgramEffects::TextureSampler TextureSampler;
+ GrGLShaderBuilder(GrGLProgramBuilder* program);
+
+ void addInput(GrGLShaderVar i) { fInputs.push_back(i); }
+ void addOutput(GrGLShaderVar i) { fOutputs.push_back(i); }
+
+ /*
+ * We put texture lookups in the base class because it is TECHNICALLY possible to do texture
+ * lookups in any kind of shader. However, for the time being using these calls on non-fragment
+ * shaders will result in a shader compilation error as texture sampler uniforms are only
+ * visible to the fragment shader. It would not be hard to change this behavior, if someone
+ * actually wants to do texture lookups in a non-fragment shader
+ *
+ * TODO if append texture lookup is used on a non-fragment shader, sampler uniforms should be
+ * made visible to that shaders
+ */
+ /** Appends a 2D texture sample with projection if necessary. coordType must either be Vec2f or
+ Vec3f. The latter is interpreted as projective texture coords. The vec length and swizzle
+ order of the result depends on the GrTextureAccess associated with the TextureSampler. */
+ void appendTextureLookup(SkString* out,
+ const TextureSampler&,
+ const char* coordName,
+ GrSLType coordType = kVec2f_GrSLType) const;
+
+ /** Version of above that appends the result to the fragment shader code instead.*/
+ void appendTextureLookup(const TextureSampler&,
+ const char* coordName,
+ GrSLType coordType = kVec2f_GrSLType);
+
+
+ /** Does the work of appendTextureLookup and modulates the result by modulation. The result is
+ always a vec4. modulation and the swizzle specified by TextureSampler must both be vec4 or
+ float. If modulation is "" or NULL it this function acts as though appendTextureLookup were
+ called. */
+ void appendTextureLookupAndModulate(const char* modulation,
+ const TextureSampler&,
+ const char* coordName,
+ GrSLType coordType = kVec2f_GrSLType);
+
+ /** If texture swizzling is available using tex parameters then it is preferred over mangling
+ the generated shader code. This potentially allows greater reuse of cached shaders. */
+ static const GrGLenum* GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps);
+
+ /**
+ * Called by GrGLEffects to add code to one of the shaders.
+ */
+ void codeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
+ va_list args;
+ va_start(args, format);
+ fCode.appendVAList(format, args);
+ va_end(args);
+ }
+
+ void codeAppend(const char* str) { fCode.append(str); }
+
+ void codePrependf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
+ va_list args;
+ va_start(args, format);
+ fCode.prependVAList(format, args);
+ va_end(args);
+ }
+
+ /** Emits a helper function outside of main() in the fragment shader. */
+ void emitFunction(GrSLType returnType,
+ const char* name,
+ int argCnt,
+ const GrGLShaderVar* args,
+ const char* body,
+ SkString* outName);
+
+ /*
+ * Get parent builder for adding uniforms
+ */
+ GrGLProgramBuilder* getProgramBuilder() { return fProgramBuilder; }
+
+ /**
+ * Helper for begining and ending a block in the fragment code.
+ */
+ class ShaderBlock {
+ public:
+ ShaderBlock(GrGLShaderBuilder* builder) : fBuilder(builder) {
+ SkASSERT(NULL != builder);
+ fBuilder->codeAppend("{");
+ }
+
+ ~ShaderBlock() {
+ fBuilder->codeAppend("}");
+ }
+ private:
+ GrGLShaderBuilder* fBuilder;
+ };
+protected:
+
+ /*
+ * this super low level function is just for use internally to builders
+ */
+ void appendTextureLookup(const char* samplerName,
+ const char* coordName,
+ uint32_t configComponentMask,
+ const char* swizzle);
+
+ /*
+ * A general function which enables an extension in a shader if the feature bit is not present
+ */
+ void addFeature(uint32_t featureBit, const char* extensionName);
+
+ typedef GrTAllocator<GrGLShaderVar> VarArray;
+
+ GrGLProgramBuilder* fProgramBuilder;
+
+ SkString fCode;
+ SkString fFunctions;
+ SkString fExtensions;
+
+ VarArray fInputs;
+ VarArray fOutputs;
+ uint32_t fFeaturesAddedMask;
+};
+
+
+/*
+ * Full Shader builder is the base class for shaders which are only accessible through full program
+ * builder, ie vertex, geometry, and later TCU / TES. Using this base class, they can access the
+ * full program builder functionality through the full program pointer
+ */
+class GrGLFullShaderBuilder : public GrGLShaderBuilder {
+public:
+ GrGLFullShaderBuilder(GrGLFullProgramBuilder* program);
+
+ GrGLFullProgramBuilder* fullProgramBuilder() { return fFullProgramBuilder; }
+protected:
+ GrGLFullProgramBuilder* fFullProgramBuilder;
+private:
+ typedef GrGLShaderBuilder INHERITED;
+};
+#endif
diff --git a/src/gpu/gl/builders/GrGLShaderStringBuilder.cpp b/src/gpu/gl/builders/GrGLShaderStringBuilder.cpp
new file mode 100644
index 0000000000..dff8c7e684
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLShaderStringBuilder.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrGLShaderStringBuilder.h"
+#include "../GrGpuGL.h"
+#include "gl/GrGLSLPrettyPrint.h"
+#include "SkRTConf.h"
+#include "SkTraceEvent.h"
+
+#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)
+#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)
+
+SK_CONF_DECLARE(bool, c_PrintShaders, "gpu.printShaders", false,
+ "Print the source code for all shaders generated.");
+
+GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,
+ GrGLuint programId,
+ GrGLenum type,
+ const SkString& shaderSrc) {
+ const GrGLInterface* gli = glCtx.interface();
+
+ GrGLuint shaderId;
+ GR_GL_CALL_RET(gli, shaderId, CreateShader(type));
+ if (0 == shaderId) {
+ return 0;
+ }
+
+ #ifdef SK_DEBUG
+ SkString prettySource = GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, false);
+ const GrGLchar* sourceStr = prettySource.c_str();
+ GrGLint sourceLength = static_cast<GrGLint>(prettySource.size());
+ #else
+ GrGLint sourceLength = static_cast<GrGLint>(shaderSrc.size());
+ const GrGLchar* sourceStr = shaderSrc.c_str();
+ #endif
+ GR_GL_CALL(gli, ShaderSource(shaderId, 1, &sourceStr, &sourceLength));
+ GR_GL_CALL(gli, CompileShader(shaderId));
+
+ // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.
+ bool checkCompiled = !glCtx.isChromium();
+ #ifdef SK_DEBUG
+ checkCompiled = true;
+ #endif
+ if (checkCompiled) {
+ GrGLint compiled = GR_GL_INIT_ZERO;
+ GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));
+
+ if (!compiled) {
+ GrGLint infoLen = GR_GL_INIT_ZERO;
+ GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));
+ SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
+ if (infoLen > 0) {
+ // retrieve length even though we don't need it to workaround bug in Chromium cmd
+ // buffer param validation.
+ GrGLsizei length = GR_GL_INIT_ZERO;
+ GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1,
+ &length, (char*)log.get()));
+ GrPrintf(GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, true).c_str());
+ GrPrintf("\n%s", log.get());
+ }
+ SkDEBUGFAIL("Shader compilation failed!");
+ GR_GL_CALL(gli, DeleteShader(shaderId));
+ return 0;
+ }
+ }
+
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader",
+ TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderSrc.c_str()));
+ if (c_PrintShaders) {
+ GrPrintf(GrGLSLPrettyPrint::PrettyPrintGLSL(shaderSrc, true).c_str());
+ GrPrintf("\n");
+ }
+
+ // Attach the shader, but defer deletion until after we have linked the program.
+ // This works around a bug in the Android emulator's GLES2 wrapper which
+ // will immediately delete the shader object and free its memory even though it's
+ // attached to a program, which then causes glLinkProgram to fail.
+ GR_GL_CALL(gli, AttachShader(programId, shaderId));
+
+ return shaderId;
+}
diff --git a/src/gpu/gl/builders/GrGLShaderStringBuilder.h b/src/gpu/gl/builders/GrGLShaderStringBuilder.h
new file mode 100644
index 0000000000..8c18fa570a
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLShaderStringBuilder.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef GrGLShaderStringBuilder_DEFINED
+#define GrGLShaderStringBuilder_DEFINED
+
+#include "GrAllocator.h"
+#include "gl/GrGLContext.h"
+#include "SkTypes.h"
+
+GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,
+ GrGLuint programId,
+ GrGLenum type,
+ const SkString& shaderSrc);
+
+#endif
diff --git a/src/gpu/gl/builders/GrGLVertexShaderBuilder.cpp b/src/gpu/gl/builders/GrGLVertexShaderBuilder.cpp
new file mode 100644
index 0000000000..6abc085706
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLVertexShaderBuilder.cpp
@@ -0,0 +1,200 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrGLVertexShaderBuilder.h"
+#include "GrGLProgramBuilder.h"
+#include "GrGLShaderStringBuilder.h"
+#include "../GrGpuGL.h"
+
+#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)
+#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)
+
+namespace {
+inline const char* color_attribute_name() { return "aColor"; }
+inline const char* coverage_attribute_name() { return "aCoverage"; }
+}
+
+GrGLVertexShaderBuilder::GrGLVertexShaderBuilder(GrGLFullProgramBuilder* program)
+ : INHERITED(program)
+ , fPositionVar(NULL)
+ , fLocalCoordsVar(NULL) {
+}
+bool GrGLVertexShaderBuilder::addAttribute(GrSLType type, const char* name) {
+ for (int i = 0; i < fInputs.count(); ++i) {
+ const GrGLShaderVar& attr = fInputs[i];
+ // if attribute already added, don't add it again
+ if (attr.getName().equals(name)) {
+ return false;
+ }
+ }
+ fInputs.push_back().set(type, GrGLShaderVar::kAttribute_TypeModifier, name);
+ return true;
+}
+
+bool GrGLVertexShaderBuilder::addEffectAttribute(int attributeIndex,
+ GrSLType type,
+ const SkString& name) {
+ if (!this->addAttribute(type, name.c_str())) {
+ return false;
+ }
+
+ fEffectAttributes.push_back().set(attributeIndex, name);
+ return true;
+}
+
+void GrGLVertexShaderBuilder::emitAttributes(const GrEffectStage& stage) {
+ int numAttributes = stage.getVertexAttribIndexCount();
+ const int* attributeIndices = stage.getVertexAttribIndices();
+ for (int a = 0; a < numAttributes; ++a) {
+ // TODO: Make addAttribute mangle the name.
+ SkString attributeName("aAttr");
+ attributeName.appendS32(attributeIndices[a]);
+ this->addEffectAttribute(attributeIndices[a],
+ stage.getEffect()->vertexAttribType(a),
+ attributeName);
+ }
+}
+
+const SkString* GrGLVertexShaderBuilder::getEffectAttributeName(int attributeIndex) const {
+ const AttributePair* attribEnd = fEffectAttributes.end();
+ for (const AttributePair* attrib = fEffectAttributes.begin(); attrib != attribEnd; ++attrib) {
+ if (attrib->fIndex == attributeIndex) {
+ return &attrib->fName;
+ }
+ }
+
+ return NULL;
+}
+
+void GrGLVertexShaderBuilder::addVarying(GrSLType type, const char* name, const char** vsOutName) {
+ fOutputs.push_back();
+ fOutputs.back().setType(type);
+ fOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
+ fProgramBuilder->nameVariable(fOutputs.back().accessName(), 'v', name);
+
+ if (vsOutName) {
+ *vsOutName = fOutputs.back().getName().c_str();
+ }
+}
+
+
+void GrGLVertexShaderBuilder::bindProgramLocations(GrGLuint programId) {
+ const GrGLProgramDesc::KeyHeader& header = fProgramBuilder->desc().getHeader();
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+
+ // Bind the attrib locations to same values for all shaders
+ SkASSERT(-1 != header.fPositionAttributeIndex);
+ GL_CALL(BindAttribLocation(programId,
+ header.fPositionAttributeIndex,
+ fPositionVar->c_str()));
+ if (-1 != header.fLocalCoordAttributeIndex) {
+ GL_CALL(BindAttribLocation(programId,
+ header.fLocalCoordAttributeIndex,
+ fLocalCoordsVar->c_str()));
+ }
+ if (-1 != header.fColorAttributeIndex) {
+ GL_CALL(BindAttribLocation(programId,
+ header.fColorAttributeIndex,
+ color_attribute_name()));
+ }
+ if (-1 != header.fCoverageAttributeIndex) {
+ GL_CALL(BindAttribLocation(programId,
+ header.fCoverageAttributeIndex,
+ coverage_attribute_name()));
+ }
+
+ const AttributePair* attribEnd = fEffectAttributes.end();
+ for (const AttributePair* attrib = fEffectAttributes.begin(); attrib != attribEnd; ++attrib) {
+ GL_CALL(BindAttribLocation(programId, attrib->fIndex, attrib->fName.c_str()));
+ }
+}
+
+bool GrGLVertexShaderBuilder::compileAndAttachShaders(GrGLuint programId,
+ SkTDArray<GrGLuint>* shaderIds) const {
+ GrGpuGL* gpu = fProgramBuilder->gpu();
+ const GrGLContext& glCtx = gpu->glContext();
+ const GrGLContextInfo& ctxInfo = gpu->ctxInfo();
+ SkString vertShaderSrc(GrGetGLSLVersionDecl(ctxInfo));
+ fProgramBuilder->appendUniformDecls(GrGLProgramBuilder::kVertex_Visibility, &vertShaderSrc);
+ fProgramBuilder->appendDecls(fInputs, &vertShaderSrc);
+ fProgramBuilder->appendDecls(fOutputs, &vertShaderSrc);
+ vertShaderSrc.append("void main() {\n");
+ vertShaderSrc.append(fCode);
+ vertShaderSrc.append("}\n");
+ GrGLuint vertShaderId = GrGLCompileAndAttachShader(glCtx, programId,
+ GR_GL_VERTEX_SHADER, vertShaderSrc);
+ if (!vertShaderId) {
+ return false;
+ }
+ *shaderIds->append() = vertShaderId;
+ return true;
+}
+
+void GrGLVertexShaderBuilder::emitCodeAfterEffects() {
+ const char* rtAdjustName;
+ fProgramBuilder->fUniformHandles.fRTAdjustmentUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kVertex_Visibility,
+ kVec4f_GrSLType,
+ "rtAdjustment",
+ &rtAdjustName);
+
+ // Transform from Skia's device coords to GL's normalized device coords.
+ this->codeAppendf(
+ "\tgl_Position = vec4(dot(pos3.xz, %s.xy), dot(pos3.yz, %s.zw), 0, pos3.z);\n",
+ rtAdjustName, rtAdjustName);
+}
+
+void GrGLVertexShaderBuilder::emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) {
+ const GrGLProgramDesc::KeyHeader& header = fProgramBuilder->desc().getHeader();
+
+ fPositionVar = &fInputs.push_back();
+ fPositionVar->set(kVec2f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, "aPosition");
+ if (-1 != header.fLocalCoordAttributeIndex) {
+ fLocalCoordsVar = &fInputs.push_back();
+ fLocalCoordsVar->set(kVec2f_GrSLType,
+ GrGLShaderVar::kAttribute_TypeModifier,
+ "aLocalCoords");
+ } else {
+ fLocalCoordsVar = fPositionVar;
+ }
+
+ const char* viewMName;
+ fProgramBuilder->fUniformHandles.fViewMatrixUni =
+ fProgramBuilder->addUniform(GrGLProgramBuilder::kVertex_Visibility,
+ kMat33f_GrSLType,
+ "ViewM",
+ &viewMName);
+
+ // Transform the position into Skia's device coords.
+ this->codeAppendf("\tvec3 pos3 = %s * vec3(%s, 1);\n",
+ viewMName, fPositionVar->c_str());
+
+ // we output point size in the GS if present
+ if (header.fEmitsPointSize
+#if GR_GL_EXPERIMENTAL_GS
+ && !header.fExperimentalGS
+#endif
+ ) {
+ this->codeAppend("\tgl_PointSize = 1.0;\n");
+ }
+
+ if (GrGLProgramDesc::kAttribute_ColorInput == header.fColorInput) {
+ this->addAttribute(kVec4f_GrSLType, color_attribute_name());
+ const char *vsName, *fsName;
+ fFullProgramBuilder->addVarying(kVec4f_GrSLType, "Color", &vsName, &fsName);
+ this->codeAppendf("\t%s = %s;\n", vsName, color_attribute_name());
+ *color = fsName;
+ }
+
+ if (GrGLProgramDesc::kAttribute_ColorInput == header.fCoverageInput) {
+ this->addAttribute(kVec4f_GrSLType, coverage_attribute_name());
+ const char *vsName, *fsName;
+ fFullProgramBuilder->addVarying(kVec4f_GrSLType, "Coverage", &vsName, &fsName);
+ this->codeAppendf("\t%s = %s;\n", vsName, coverage_attribute_name());
+ *coverage = fsName;
+ }
+}
diff --git a/src/gpu/gl/builders/GrGLVertexShaderBuilder.h b/src/gpu/gl/builders/GrGLVertexShaderBuilder.h
new file mode 100644
index 0000000000..c576f57882
--- /dev/null
+++ b/src/gpu/gl/builders/GrGLVertexShaderBuilder.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef GrGLVertexShader_DEFINED
+#define GrGLVertexShader_DEFINED
+#include "GrGLShaderBuilder.h"
+
+class GrGLProgramBuilder;
+
+class GrGLVertexShaderBuilder : public GrGLFullShaderBuilder {
+public:
+ GrGLVertexShaderBuilder(GrGLFullProgramBuilder* program);
+
+ /*
+ * Add attribute will push a new attribute onto the end. It will also assert if there is
+ * a duplicate attribute
+ */
+ bool addAttribute(GrSLType type, const char* name);
+
+ bool addEffectAttribute(int attributeIndex, GrSLType type, const SkString& name);
+
+ /*
+ * this call is only for GrGLProgramEffects' internal use
+ */
+ void emitAttributes(const GrEffectStage& stage);
+
+ /**
+ * Are explicit local coordinates provided as input to the vertex shader.
+ */
+ bool hasExplicitLocalCoords() const { return (fLocalCoordsVar != fPositionVar); }
+
+ const SkString* getEffectAttributeName(int attributeIndex) const;
+
+ /** Returns a vertex attribute that represents the local coords in the VS. This may be the same
+ as positionAttribute() or it may not be. It depends upon whether the rendering code
+ specified explicit local coords or not in the GrDrawState. */
+ const GrGLShaderVar& localCoordsAttribute() const { return *fLocalCoordsVar; }
+
+ /** Returns a vertex attribute that represents the vertex position in the VS. This is the
+ pre-matrix position and is commonly used by effects to compute texture coords via a matrix.
+ */
+ const GrGLShaderVar& positionAttribute() const { return *fPositionVar; }
+
+private:
+ /*
+ * Internal call for GrGLFullProgramBuilder.addVarying
+ */
+ void addVarying(GrSLType type,
+ const char* name,
+ const char** vsOutName);
+
+ /*
+ * private helpers for compilation by GrGLProgramBuilder
+ */
+ void bindProgramLocations(GrGLuint programId);
+ bool compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) const;
+ void emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage);
+ void emitCodeAfterEffects();
+
+ struct AttributePair {
+ void set(int index, const SkString& name) {
+ fIndex = index; fName = name;
+ }
+ int fIndex;
+ SkString fName;
+ };
+
+ SkSTArray<10, AttributePair, true> fEffectAttributes;
+ GrGLShaderVar* fPositionVar;
+ GrGLShaderVar* fLocalCoordsVar;
+
+ friend class GrGLFullProgramBuilder;
+
+ typedef GrGLFullShaderBuilder INHERITED;
+};
+
+#endif