cocos2d-js Shader系列2:在cc.Sprite上使用Shader(黑白、灰度、造旧效果)

在Sprite中使用Shader做特殊的颜色处理比较简单,只需要把Shader程序绑定到Sprite上即可:

sprite.shaderProgram = alphaTestShader;

Cocos2d内置了一些Shader,详细可以看代码:

其中,CCShaderCache缓存了一些Shader实例,而GLProgram则对gl的api做了简单的封装让接口更友好。

需要注意的是,使用GLProgram编译shader程序时,cocos2d会自动加入了一些参数。

    _compileShader: function (shader, type, source) { 
        if (!source || !shader) 
            return false; 
        //var preStr = (type == this._glContext.VERTEX_SHADER) ? "precision highp float;\n" : "precision mediump float;\n"; 
        source = "precision highp float;        \n" 
            + "uniform mat4 CC_PMatrix;         \n" 
            + "uniform mat4 CC_MVMatrix;        \n" 
            + "uniform mat4 CC_MVPMatrix;       \n" 
            + "uniform vec4 CC_Time;            \n" 
            + "uniform vec4 CC_SinTime;         \n" 
            + "uniform vec4 CC_CosTime;         \n" 
            + "uniform vec4 CC_Random01;        \n" 
            + "//CC INCLUDES END                \n" + source; 
        this._glContext.shaderSource(shader, source); 
        this._glContext.compileShader(shader); 
        var status = this._glContext.getShaderParameter(shader, this._glContext.COMPILE_STATUS); 
        if (!status) { 
            cc.log("cocos2d: ERROR: Failed to compile shader:\n" + this._glContext.getShaderSource(shader)); 
            if (type == this._glContext.VERTEX_SHADER) 
                cc.log("cocos2d: \n" + this.vertexShaderLog()); 
            else 
                cc.log("cocos2d: \n" + this.fragmentShaderLog()); 
        } 
        return ( status == 1 ); 
    }

另外,绑定到sprite之后,cocos2d会自动设置一些值,我们只需要事先做个绑定即可,而这个绑定操作,也是有友好封装的。具体可以顺藤摸瓜看代码。

                program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); 
                program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); 
                program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);

在sprite上做效果,无非就是一些颜色变换或者说是滤镜而已。由于cocos没有原生的滤镜,不像flash那么方便,那么我们就要自己动手丰衣足食了。

下边实现两个灰度和造旧sepia的效果,类似Flash的ShaderFilter一样。

(绿色球就是原图,上下2个小球分别用不同的sepia参数得到的造旧效果)

var sugar4 = Sugar.create(0,0,2); 
        sugar4.x = size.width/4; 
        sugar4.y = size.height/1.5; 
        this.addChild(sugar4); 
        sugar4.scale = 3; 
        var sugar = Sugar.create(0,0,2); 
        sugar.x = size.width/2; 
        sugar.y = size.height/2; 
        this.addChild(sugar); 
        sugar.scale = 3; 
        var sugar2 = Sugar.create(0,0,2); 
        sugar2.x = size.width/3; 
        sugar2.y = size.height/3; 
        this.addChild(sugar2); 
        sugar2.scale = 2; 
        var sugar3 = Sugar.create(0,0,2); 
        sugar3.x = size.width/3*2; 
        sugar3.y = size.height/3*2; 
        this.addChild(sugar3); 
        sugar3.scale = 2; 
        Filter.grayScale(sugar); 
        Filter.sepia(sugar2, 0.5); 
        Filter.sepia(sugar3, 0.9);

Filter类的代码:

/** 
* Created by kenkozheng on 2014/11/4. 
*/ 
/** 
* 只能用于控制Sprite的色调等,目标是实现类似Flash的内置基本滤镜 
* 静态类 
*/ 
var Filter = { 
    DEFAULT_VERTEX_SHADER: 
        "attribute vec4 a_position; \n" 
        + "attribute vec2 a_texCoord; \n" 
        + "varying mediump vec2 v_texCoord; \n" 
        + "void main() \n" 
        + "{ \n" 
        + "    gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;  \n" 
        + "    v_texCoord = a_texCoord; \n" 
        + "}", 
    GRAY_SCALE_FRAGMENT_SHADER: 
        "varying vec2 v_texCoord;   \n" 
        + "uniform sampler2D CC_Texture0; \n" 
        + "void main() \n" 
        + "{  \n" 
        + "    vec4 texColor = texture2D(CC_Texture0, v_texCoord);  \n" 
        + "    float gray = texColor.r * 0.299 + texColor.g * 0.587 + texColor.b * 0.114; \n" 
        + "    gl_FragColor = vec4(gray, gray, gray, texColor.a);  \n" 
        + "}", 
    SEPIA_FRAGMENT_SHADER: 
        "varying vec2 v_texCoord;   \n" 
        + "uniform sampler2D CC_Texture0; \n" 
        + "uniform float u_degree; \n" 
        + "void main() \n" 
        + "{  \n" 
        + "    vec4 texColor = texture2D(CC_Texture0, v_texCoord);  \n" 
        + "    float r = texColor.r * 0.393 + texColor.g * 0.769 + texColor.b * 0.189; \n" 
        + "    float g = texColor.r * 0.349 + texColor.g * 0.686 + texColor.b * 0.168; \n" 
        + "    float b = texColor.r * 0.272 + texColor.g * 0.534 + texColor.b * 0.131; \n" 
        + "    gl_FragColor = mix(texColor, vec4(r, g, b, texColor.a), u_degree);  \n" 
        + "}", 
    programs:{}, 
    /** 
     * 灰度 
     * @param sprite 
     */ 
    grayScale: function (sprite) { 
        var program = Filter.programs["grayScale"]; 
        if(!program){ 
            program = new cc.GLProgram(); 
            program.initWithVertexShaderByteArray(Filter.DEFAULT_VERTEX_SHADER, Filter.GRAY_SCALE_FRAGMENT_SHADER); 
            program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);        //cocos会做初始化的工作 
            program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); 
            program.link(); 
            program.updateUniforms(); 
            Filter.programs["grayScale"] = program; 
        } 
        gl.useProgram(program.getProgram()); 
        sprite.shaderProgram = program; 
    }, 
    /** 
     * 造旧 
     * @param sprite 
     * @param degree 旧的程度 0~1 
     */ 
    sepia: function (sprite, degree) { 
        var program = Filter.programs["sepia"+degree]; 
        if(!program){ 
            program = new cc.GLProgram(); 
            program.initWithVertexShaderByteArray(Filter.DEFAULT_VERTEX_SHADER, Filter.SEPIA_FRAGMENT_SHADER); 
            program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);        //cocos会做初始化的工作 
            program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); 
            program.link(); 
            program.updateUniforms(); 
            var degreeLocation = program.getUniformLocationForName("u_degree"); 
            program.setUniformLocationF32(degreeLocation, degree); 
            Filter.programs["sepia"+degree] = program; 
        } 
        gl.useProgram(program.getProgram()); 
        sprite.shaderProgram = program; 
    } 
};

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏wym

手把手教你写linux系统下贪吃蛇(一)

typedef struct snakeBodynode { int x; int y;                    //x,y是坐标 stru...

962
来自专栏GIS讲堂

geotools获取给定点的DEM高程值

1、在web端绘制一条曲线; 2、获取各节点处的高程值; 3、根据高程值绘制高程堆积图。

1085
来自专栏码匠的流水账

聊聊storm的IEventLogger

storm-2.0.0/storm-client/src/jvm/org/apache/storm/metric/IEventLogger.java

1193
来自专栏阿炬.NET

使用wepy开发微信小程序01——常用的组件

1425
来自专栏Java学习网

Java实现把整数转换为英语单词的方法,实用代码

一个非负整数转换为英文单词表示。 例如: 123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand...

2379
来自专栏码匠的流水账

FluxSink实例及解析

reactor-core-3.1.3.RELEASE-sources.jar!/reactor/core/publisher/FluxSink.java

812
来自专栏高性能服务器开发

(三)dict哈希结构2

dict.c; /* Hash Tables Implementation. * * This file implements in memory ha...

2689
来自专栏计算机视觉与深度学习基础

Leetcode 题目列表(难度、出现频率、知识点)

不全,但好像没看到有更好的版本,刷前132题暂时凑合着用吧! 转载自:LeetCode Question Difficulty Distribution ?...

3606
来自专栏听雨堂

VB6对滚轮的支持

        我需要对Mapx控件支持鼠标滚轮,找了一个可以使用的代码,来自         http://blog.csdn.net/areful/arch...

19310
来自专栏YG小书屋

orc文件格式对常用系统的支持

763

扫码关注云+社区