Cocos2d-lua 初識shader之三:模糊
阿新 • • 發佈:2019-02-05
原理:遍歷當前畫素點周圍的部分畫素點,累加它們的rgba,根據距離設定權重並相乘,最後再根據總權重獲取該總和的平均值,將該平均值設定為當前畫素點的顏色。
local vert = [[ attribute vec4 a_position; attribute vec2 a_texCoord; attribute vec4 a_color; #ifdef GL_ES varying lowp vec4 v_fragmentColor; varying mediump vec2 v_texCoord; #else varying vec4 v_fragmentColor; varying vec2 v_texCoord; #endif void main() { gl_Position = CC_PMatrix * a_position; v_fragmentColor = a_color; v_texCoord = a_texCoord; } ]] local frag = [[ #ifdef GL_ES precision mediump float; #endif varying vec4 v_fragmentColor; varying vec2 v_texCoord; uniform float limit; // 半徑 uniform vec2 my_size; // 紋理大小(寬和高),為了計算周圍各點的紋理座標,必須傳入它,因為紋理座標範圍是0~1 void main(void) { vec2 unit = 1.0 / my_size.xy; // 單位尺寸 float r = limit; float step = r / 2.0; // 步長 float totalWeight = 0.0; // 總權重 vec4 all = vec4(0); // 所有畫素點顏色之和 // 遍歷當前畫素點周圍的所有畫素點,將它們的顏色值相加 // 根據畫素點距離當前畫素點的距離設定權重 for(float i = -r; i < r; i += step) { for(float j = -r; j < r; j += step) { // 權重 float weight = (r - abs(i)) * (r - abs(j)); // 加上該畫素點顏色值*權重 all += texture2D(CC_Texture0, v_texCoord + vec2(i * unit.x, j * unit.y)) * weight; totalWeight += weight; } } // 設定當前畫素點的顏色為總顏色之和除以總權重 gl_FragColor = all / totalWeight; } ]] -- 1.建立glProgram local glProgram = cc.GLProgram:createWithByteArrays(vert, frag) -- 2.獲取glProgramState local glProgramState = cc.GLProgramState:getOrCreateWithGLProgram(glProgram) -- 3.設定屬性值 glProgramState:setUniformFloat("limit", 10) -- 4.獲取材質的尺寸。self.blur為Sprite local size = self.blur:getTexture():getContentSizeInPixels() glProgramState:setUniformVec2("my_size", cc.p(size.width, size.height)) self.blur:setGLProgram(glProgram) self.blur:setGLProgramState(glProgramState)
半徑小:
半徑大: