Create a shader program
774580
function createShaderProgram(gl, shaders) {
  const program = gl.createProgram();

  for (let i = 0; i < shaders.length; i++) {
    gl.attachShader(program, shaders[i]);
  }

  gl.linkProgram(program);

  // Check the link status
  const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {
    // something went wrong with the link
    const lastError = gl.getProgramInfoLog(program);
    console.error('Error in program linking:', lastError);
    gl.deleteProgram(program);

    return null;
  }

  program.shaders = shaders;
  gl.useProgram(program);

  return program;
}
845981
function (shader) {
            if (this.activeShader !== shader) {
                this.flush();
                this.activeShader = shader;
                this.activeShader.bind();
                this.activeShader.uniforms.uProjectionMatrix = this.projectionMatrix.val;
            }
        }
1165689
function() {
		var gl = this.gl,
		      program = this.program;


		// initialize pixel textures
		this.bgTexture = createTexture( 0, "bgTexture" );
		this.spriteTexture = createTexture( 1, "spriteTexture" );
		this.prioTexture = createTexture( 2, "prioTexture" );

		// initialize palette texture
		this.paletteTexture = createTexture( 3, "paletteTexture" );
		gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 64, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, palette );

		function createTexture( index, name ) {
			var texture = gl.createTexture();
			gl.bindTexture(gl.TEXTURE_2D, texture);

			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

			gl.uniform1i(gl.getUniformLocation(program, name), index);

			return texture;
		}
	}
1357118
function LGraphTextureChannels() {
            this.addInput("Texture", "Texture");

            this.addOutput("R", "Texture");
            this.addOutput("G", "Texture");
            this.addOutput("B", "Texture");
            this.addOutput("A", "Texture");

            this.properties = { use_luminance: true };
            if (!LGraphTextureChannels._shader) {
                LGraphTextureChannels._shader = new GL.Shader(
                    Shader.SCREEN_VERTEX_SHADER,
                    LGraphTextureChannels.pixel_shader
                );
            }
        }
172196
def set_shaders(self, vert, frag):
        
        self._linked = False
        # Create temporary shader objects
        vert_handle = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        frag_handle = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        # For both vertex and fragment shader: set source, compile, check
        for code, handle, type_ in [(vert, vert_handle, 'vertex'),
                                    (frag, frag_handle, 'fragment')]:
            gl.glShaderSource(handle, code)
            gl.glCompileShader(handle)
            status = gl.glGetShaderParameter(handle, gl.GL_COMPILE_STATUS)
            if not status:
                errors = gl.glGetShaderInfoLog(handle)
                errormsg = self._get_error(code, errors, 4)
                raise RuntimeError("Shader compilation error in %s:\n%s" %
                                   (type_ + ' shader', errormsg))
        # Attach shaders
        gl.glAttachShader(self._handle, vert_handle)
        gl.glAttachShader(self._handle, frag_handle)
        # Link the program and check
        gl.glLinkProgram(self._handle)
        if not gl.glGetProgramParameter(self._handle, gl.GL_LINK_STATUS):
            raise RuntimeError('Program linking error:\n%s'
                               % gl.glGetProgramInfoLog(self._handle))
        # Now we can remove the shaders. We no longer need them and it
        # frees up precious GPU memory:
        # http://gamedev.stackexchange.com/questions/47910
        gl.glDetachShader(self._handle, vert_handle)
        gl.glDetachShader(self._handle, frag_handle)
        gl.glDeleteShader(vert_handle)
        gl.glDeleteShader(frag_handle)
        # Now we know what variables will be used by the program
        self._unset_variables = self._get_active_attributes_and_uniforms()
        self._handles = {}
        self._known_invalid = set()
        self._linked = True
67200
def _render_edf(self, orig_tex):
        """"""
        # Set up the necessary textures
        sdf_size = orig_tex.shape[:2]

        comp_texs = []
        for _ in range(2):
            tex = Texture2D(sdf_size + (4,), format='rgba',
                            interpolation='nearest', wrapping='clamp_to_edge')
            comp_texs.append(tex)
        self.fbo_to[0].color_buffer = comp_texs[0]
        self.fbo_to[1].color_buffer = comp_texs[1]
        for program in self.programs[1:]:  # program_seed does not need this
            program['u_texh'], program['u_texw'] = sdf_size

        # Do the rendering
        last_rend = 0
        with self.fbo_to[last_rend]:
            set_viewport(0, 0, sdf_size[1], sdf_size[0])
            self.program_seed['u_texture'] = orig_tex
            self.program_seed.draw('triangle_strip')
        stepsize = (np.array(sdf_size) // 2).max()
        while stepsize > 0:
            self.program_flood['u_step'] = stepsize
            self.program_flood['u_texture'] = comp_texs[last_rend]
            last_rend = 1 if last_rend == 0 else 0
            with self.fbo_to[last_rend]:
                set_viewport(0, 0, sdf_size[1], sdf_size[0])
                self.program_flood.draw('triangle_strip')
            stepsize //= 2
        return comp_texs[last_rend]
44525
def draw(self):
        ""
        glBindVertexArray( self.m_glVertArray )
        glActiveTexture( GL_TEXTURE0 )
        glBindTexture( GL_TEXTURE_2D, self.m_glTexture )
        glDrawElements( GL_TRIANGLES, self.m_unVertexCount, GL_UNSIGNED_SHORT, 0 )
        glBindVertexArray( 0 )
1102892
function compileShader( gl, shader, code ){
  gl.shaderSource( shader, code );
  gl.compileShader( shader );

  if (Program.debug && !gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    warn( gl.getShaderInfoLog(shader) );
    warn( formatCode( code ) );
    return false;
  }

  return true;
}
571610
def createAllShaders(self):
        ""
        self.m_unSceneProgramID = self.compileGLShader( 
            "Scene",
            # Vertex Shader
            dedent("""\
            #version 410
            uniform mat4 matrix;
            layout(location = 0) in vec4 position;
            layout(location = 1) in vec2 v2UVcoordsIn;
            layout(location = 2) in vec3 v3NormalIn;
            out vec2 v2UVcoords;
            void main()
            {
                v2UVcoords = v2UVcoordsIn;
                gl_Position = matrix * position;
            }
            """),
            # Fragment Shader
            dedent("""\
            #version 410 core
            uniform sampler2D mytexture;
            in vec2 v2UVcoords;
            out vec4 outputColor;
            void main()
            {
               outputColor = texture(mytexture, v2UVcoords);
            }
            """)
            )
        self.m_nSceneMatrixLocation = glGetUniformLocation( self.m_unSceneProgramID, "matrix" )
        if self.m_nSceneMatrixLocation == -1:
            dprintf( "Unable to find matrix uniform in scene shader\n" )
            return False
        self.m_unControllerTransformProgramID = self.compileGLShader(
            "Controller",
            # vertex shader
            dedent("""\
            #version 410
            uniform mat4 matrix;
            layout(location = 0) in vec4 position;
            layout(location = 1) in vec3 v3ColorIn;
            out vec4 v4Color;
            void main()
            {
                v4Color.xyz = v3ColorIn;
                v4Color.a = 1.0;
                gl_Position = matrix * position;
            }
            """),
            # fragment shader
            dedent("""\
            #version 410
            in vec4 v4Color;
            out vec4 outputColor;
            void main()
            {
               outputColor = v4Color;
            }
            """) )
        self.m_nControllerMatrixLocation = glGetUniformLocation( self.m_unControllerTransformProgramID, "matrix" )
        if self.m_nControllerMatrixLocation == -1:
            dprintf( "Unable to find matrix uniform in controller shader\n" )
            return False
        self.m_unRenderModelProgramID = self.compileGLShader( 
            "render model",
            # vertex shader
            dedent("""\
            #version 410
            uniform mat4 matrix;
            layout(location = 0) in vec4 position;
            layout(location = 1) in vec3 v3NormalIn;
            layout(location = 2) in vec2 v2TexCoordsIn;
            out vec2 v2TexCoord;
            void main()
            {
                v2TexCoord = v2TexCoordsIn;
                gl_Position = matrix * vec4(position.xyz, 1);
            }
            """),
            #fragment shader
            dedent("""\
            #version 410 core
            uniform sampler2D diffuse;
            in vec2 v2TexCoord;
            out vec4 outputColor;
            void main()
            {
               outputColor = texture( diffuse, v2TexCoord);
            }
            """) )
        self.m_nRenderModelMatrixLocation = glGetUniformLocation( self.m_unRenderModelProgramID, "matrix" )
        if self.m_nRenderModelMatrixLocation == -1:
            dprintf( "Unable to find matrix uniform in render model shader\n" )
            return False
        self.m_unLensProgramID = self.compileGLShader(
            "Distortion",
            # vertex shader
            dedent("""\
            #version 410 core
            layout(location = 0) in vec4 position;
            layout(location = 1) in vec2 v2UVredIn;
            layout(location = 2) in vec2 v2UVGreenIn;
            layout(location = 3) in vec2 v2UVblueIn;
            noperspective  out vec2 v2UVred;
            noperspective  out vec2 v2UVgreen;
            noperspective  out vec2 v2UVblue;
            void main()
            {
                v2UVred = v2UVredIn;
                v2UVgreen = v2UVGreenIn;
                v2UVblue = v2UVblueIn;
                gl_Position = position;
            }
            """),
            # fragment shader
            dedent("""\
            #version 410 core
            uniform sampler2D mytexture;
    
            noperspective  in vec2 v2UVred;
            noperspective  in vec2 v2UVgreen;
            noperspective  in vec2 v2UVblue;
    
            out vec4 outputColor;
    
            void main()
            {
                float fBoundsCheck = ( 
                    (dot( vec2( lessThan( v2UVgreen.xy, vec2(0.05, 0.05)) ), vec2(1.0, 1.0))
                    + dot( vec2( greaterThan( v2UVgreen.xy, vec2( 0.95, 0.95)) ), vec2(1.0, 1.0))) 
                    );
                if( fBoundsCheck > 1.0 ) {
                    outputColor = vec4( 0, 0, 0, 1.0 ); 
                } 
                else {
                    float red = texture(mytexture, v2UVred).x;
                    float green = texture(mytexture, v2UVgreen).y;
                    float blue = texture(mytexture, v2UVblue).z;
                    outputColor = vec4( red, green, blue, 1.0  ); 
                }
            }
            """) )
        return self.m_unSceneProgramID != 0 and self.m_unControllerTransformProgramID != 0 and self.m_unRenderModelProgramID != 0 and self.m_unLensProgramID != 0
464335
private static int createShaders() throws IOException {

        // load and compile the vertex shader.
        String vertexShaderCode = IOUtils.toString(
                ClassLoader.getSystemResourceAsStream("vertexShader.glsl"));
        int vertexShaderId = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
        glShaderSourceARB(vertexShaderId, vertexShaderCode);
        glCompileShaderARB(vertexShaderId);
        printLogInfo(vertexShaderId);

        // load and compile the fragment shader.
        String fragmentShaderCode = IOUtils.toString(
                ClassLoader.getSystemResourceAsStream("fragmentShader.glsl"));
        int fragmentShaderId = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
        glShaderSourceARB(fragmentShaderId, fragmentShaderCode);
        glCompileShaderARB(fragmentShaderId);
        printLogInfo(fragmentShaderId);

        // combine the two into a program.
        int programId = ARBShaderObjects.glCreateProgramObjectARB();
        glAttachObjectARB(programId, vertexShaderId);
        glAttachObjectARB(programId, fragmentShaderId);
        glValidateProgramARB(programId);
        glLinkProgramARB(programId);
        printLogInfo(programId);

        return programId;
    }
1004847
function (shaderType, symbol, val) {
        var vertexDefines = this.vertexDefines;
        var fragmentDefines = this.fragmentDefines;
        if (shaderType !== 'vertex' && shaderType !== 'fragment' && shaderType !== 'both'
            && arguments.length < 3
        ) {
            // shaderType default to be 'both'
            val = symbol;
            symbol = shaderType;
            shaderType = 'both';
        }
        val = val != null ? val : null;
        if (shaderType === 'vertex' || shaderType === 'both') {
            if (vertexDefines[symbol] !== val) {
                vertexDefines[symbol] = val;
                // Mark as dirty
                this._programKey = '';
            }
        }
        if (shaderType === 'fragment' || shaderType === 'both') {
            if (fragmentDefines[symbol] !== val) {
                fragmentDefines[symbol] = val;
                if (shaderType !== 'both') {
                    this._programKey = '';
                }
            }
        }
    }
1287564
function() {
		var gl = this.gl;

		var program = gl.createProgram();
		gl.attachShader( program, this.vertexShader );
		gl.attachShader( program, this.fragmentShader );
		gl.linkProgram( program );	
		gl.useProgram( program );

		this.program = program;
	}
204124
def shade_jar(self, shading_rules, jar_path):
    
    self.context.log.debug('Shading {}.'.format(jar_path))
    with temporary_dir() as tempdir:
      output_jar = os.path.join(tempdir, os.path.basename(jar_path))
      with self.shader.binary_shader_for_rules(output_jar, jar_path, shading_rules) as shade_runner:
        result = execute_runner(shade_runner, workunit_factory=self.context.new_workunit,
                                workunit_name='jarjar')
        if result != 0:
          raise TaskError('Shading tool failed to shade {0} (error code {1})'.format(jar_path,
                                                                                     result))
        if not os.path.exists(output_jar):
          raise TaskError('Shading tool returned success for {0}, but '
                          'the output jar was not found at {1}'.format(jar_path, output_jar))
        atomic_copy(output_jar, jar_path)
        return jar_path
7223
function transformShader(shaderContent, variableDict, config) {
  let match = null;
  let unrolledContents = null;
  let shaderString = shaderContent;

  // First do all the variable replacements
  Object.keys(variableDict).forEach((vname) => {
    const value = variableDict[vname];
    const r = new RegExp(`\\$\\{${vname}\\}`, 'g');
    shaderString = shaderString.replace(r, value);
  });

  // Now check if any loops need to be inlined
  if (config.inlineLoops) {
    const loopRegex = /\/\/@INLINE_LOOP([\s\S]+?)(?=\/\/@INLINE_LOOP)\/\/@INLINE_LOOP/;

    match = shaderString.match(loopRegex);
    while (match) {
      const capture = match[1];
      /* eslint-disable no-useless-escape */
      const infoRegex = /^\s*\(([^\),]+)\s*,\s*([^\),]+)\s*,\s*([^\)]+)\)/;
      const infoRegexMatch = capture.match(infoRegex);
      const loopVariableName = infoRegexMatch[1];
      const loopMin = infoRegexMatch[2];
      const loopCount = infoRegexMatch[3];
      const forLoop = capture.replace(infoRegex, '');
      const loopContentsRegex = /^\s*[^\{]+\{([\s\S]+?)\s*\}\s*$/;
      /* eslint-enable no-useless-escape */
      const forLoopMatch = forLoop.match(loopContentsRegex);
      const loopBody = forLoopMatch[1];
      const loopBodyReplacer = new RegExp(loopVariableName, 'g');

      unrolledContents = '';
      for (let i = loopMin; i < loopCount; ++i) {
        unrolledContents += loopBody.replace(loopBodyReplacer, i);
        unrolledContents += '\n';
      }

      shaderString = shaderString.replace(loopRegex, unrolledContents);
      match = shaderString.match(loopRegex);
    }
  }

  if (config.debug) {
    console.log('Transformed shader string:');
    console.log(shaderString);
  }

  return shaderString;
}
868671
function createUniformWrapper(gl, program, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function('gl', 'prog', 'locations', 
      'return function(){return gl.getUniform(prog,locations[' + index + '])}') 
    return proc(gl, program, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new Error('gl-shader: Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'prog', 'locations', code.join('\n'))
    return proc(gl, program, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return dup(d, false)
          }
          return dup(d)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return dup([d,d])
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}
111501
function () {
            this.sbIndex = 0;
            this.length = 0;

            var samplers = [];

            // WebGL context
            this.gl = this.renderer.gl;

            this.flush();

            this.setProjection(this.gl.canvas.width, this.gl.canvas.height);

            this.setViewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);

            // Initialize clear color
            this.gl.clearColor(0.0, 0.0, 0.0, 1.0);

            for (var i = 0; i < this.maxTextures; i++) {
                this.units[i] = false;
                samplers[i] = i;
            }
            // set the quad shader as the default program
            this.useShader(this.quadShader);
            this.quadShader.uniforms.uSampler = samplers;
        }
856248
function createGLResources(gl, glConfig) {
  const resources = {
    gl,
    buffers: {},
    textures: {},
    framebuffers: {},
    programs: {},
  };
  const buffers = glConfig.resources.buffers || [];
  const textures = glConfig.resources.textures || [];
  const framebuffers = glConfig.resources.framebuffers || [];

  // Create Buffer
  buffers.forEach((buffer) => {
    const glBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW);
    resources.buffers[buffer.id] = glBuffer;
  });

  // Create Texture
  textures.forEach((texture) => {
    const glTexture = gl.createTexture();
    const pixelStore = texture.pixelStore || [];
    const texParameter = texture.texParameter || [];

    gl.bindTexture(gl.TEXTURE_2D, glTexture);

    pixelStore.forEach((option) => {
      gl.pixelStorei(gl[option[0]], option[1]);
    });

    texParameter.forEach((option) => {
      gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]);
    });

    resources.textures[texture.id] = glTexture;
  });

  // Create Framebuffer
  framebuffers.forEach((framebuffer) => {
    const glFramebuffer = gl.createFramebuffer();
    glFramebuffer.width = framebuffer.width;
    glFramebuffer.height = framebuffer.height;

    resources.framebuffers[framebuffer.id] = glFramebuffer;
  });

  // Create programs
  Object.keys(glConfig.programs).forEach((programName) => {
    buildShaderProgram(gl, programName, glConfig, resources);
  });

  // Add destroy function
  resources.destroy = () => {
    freeGLResources(resources);
  };

  return resources;
}