Create a vertex or fragment shader, given the source and type
163768
function(src, type) {
        var gl = this.context;
        var shader = gl.createShader(type);
        gl.shaderSource(shader, src);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            throw gl.getShaderInfoLog(shader);
        }
        return shader;
    }
459980
function createVertexBufferObjects(renderState) {
    if (m_geomData) {
      if (renderState) {
        m_context = renderState.m_context;
      }
      var numberOfSources = m_geomData.numberOfSources(),
          i, j, k, bufferId = null, keys, ks, numberOfPrimitives, data;

      for (i = 0; i < numberOfSources; i += 1) {
        bufferId = m_context.createBuffer();
        m_context.bindBuffer(vgl.GL.ARRAY_BUFFER, bufferId);
        data = m_geomData.source(i).data();
        if (!(data instanceof Float32Array)) {
          data = new Float32Array(data);
        }
        m_context.bufferData(vgl.GL.ARRAY_BUFFER, data,
                      m_dynamicDraw ? vgl.GL.DYNAMIC_DRAW :
                      vgl.GL.STATIC_DRAW);

        keys = m_geomData.source(i).keys();
        ks = [];

        for (j = 0; j < keys.length; j += 1) {
          ks.push(keys[j]);
        }

        m_bufferVertexAttributeMap[i] = ks;
        m_buffers[i] = bufferId;
      }

      numberOfPrimitives = m_geomData.numberOfPrimitives();
      for (k = 0; k < numberOfPrimitives; k += 1) {
        bufferId = m_context.createBuffer();
        m_context.bindBuffer(vgl.GL.ARRAY_BUFFER, bufferId);
        m_context.bufferData(vgl.GL.ARRAY_BUFFER,
          m_geomData.primitive(k).indices(), vgl.GL.STATIC_DRAW);
        m_buffers[i] = bufferId;
        i += 1;
      }

      m_glCompileTimestamp.modified();
    }
  }
582915
function getShader(gl, source, isVertex) {
  var shader = gl.createShader(isVertex ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);

  // See if it compiled successfully

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}
1000955
def paintGL(self):
        ''''''

        if self.post_processing:
            # Render to the first framebuffer
            glBindFramebuffer(GL_FRAMEBUFFER, self.fb0)
            glViewport(0, 0, self.width(), self.height())

            status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
            if (status != GL_FRAMEBUFFER_COMPLETE):
                reason = dict(GL_FRAMEBUFFER_UNDEFINED='UNDEFINED',
                              GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT='INCOMPLETE_ATTACHMENT',
                              GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT='INCOMPLETE_MISSING_ATTACHMENT',
                              GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER='INCOMPLETE_DRAW_BUFFER',
                              GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER='INCOMPLETE_READ_BUFFER',
                              GL_FRAMEBUFFER_UNSUPPORTED='UNSUPPORTED',
                          )[status]

                raise Exception('Framebuffer is not complete: {}'.format(reason))
        else:
            glBindFramebuffer(GL_FRAMEBUFFER, DEFAULT_FRAMEBUFFER)


        # Clear color take floats
        bg_r, bg_g, bg_b, bg_a = self.background_color
        glClearColor(bg_r/255, bg_g/255, bg_b/255, bg_a/255)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        proj = self.camera.projection
        cam = self.camera.matrix

        self.mvproj = np.dot(proj, cam)

        self.ldir = cam[:3, :3].T.dot(self.light_dir)



        # Draw World
        self.on_draw_world()

        # Iterate over all of the post processing effects
        if self.post_processing:
            if len(self.post_processing) > 1:
                newarg = self.textures.copy()

                # Ping-pong framebuffer rendering
                for i, pp in enumerate(self.post_processing[:-1]):
                    if i % 2:
                        outfb = self.fb1
                        outtex = self._extra_textures['fb1']
                    else:
                        outfb = self.fb2
                        outtex = self._extra_textures['fb2']

                    pp.render(outfb, newarg)

                    newarg['color'] = outtex

                self.post_processing[-1].render(DEFAULT_FRAMEBUFFER, newarg)

            else:
                self.post_processing[0].render(DEFAULT_FRAMEBUFFER, self.textures)

        # Draw the UI at the very last step
        self.on_draw_ui()
1003154
def main():
    '''
        
    '''

    print('GLWindow:', GLWindow.__version__)
    print('Python:', sys.version)
    print('Platform:', sys.platform)

    wnd = GLWindow.create_window((480, 480), title='GLWindow Sample')
    wnd.vsync = False

    ctx = ModernGL.create_context()

    prog = ctx.program([
        ctx.vertex_shader('''
            #version 330
            in vec2 vert;
            in vec4 vert_color;
            out vec4 frag_color;
            uniform vec2 scale;
            uniform float rotation;
            void main() {
                frag_color = vert_color;
                float r = rotation * (0.5 + gl_InstanceID * 0.05);
                mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
            }
        '''),
        ctx.fragment_shader('''
            #version 330
            in vec4 frag_color;
            out vec4 color;
            void main() {
                color = vec4(frag_color);
            }
        '''),
    ])

    scale = prog.uniforms['scale']
    rotation = prog.uniforms['rotation']

    vbo = ctx.buffer(struct.pack(
        '18f',
        1.0, 0.0, 1.0, 0.0, 0.0, 0.5,
        -0.5, 0.86, 0.0, 1.0, 0.0, 0.5,
        -0.5, -0.86, 0.0, 0.0, 1.0, 0.5,
    ))

    vao = ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

    while wnd.update():
        wnd.clear(0.95, 0.95, 0.95)

        width, height = wnd.size
        scale.value = (height / width * 0.75, 0.75)
        ctx.viewport = wnd.viewport
        ctx.enable(ModernGL.BLEND)
        rotation.value = wnd.time
        vao.render(instances=10)
181548
function LGraphTextureLUT() {
            this.addInput("Texture", "Texture");
            this.addInput("LUT", "Texture");
            this.addInput("Intensity", "number");
            this.addOutput("", "Texture");
            this.properties = {
                intensity: 1,
                precision: LGraphTexture.DEFAULT,
                texture: null
            };

            if (!LGraphTextureLUT._shader) {
                LGraphTextureLUT._shader = new GL.Shader(
                    Shader.SCREEN_VERTEX_SHADER,
                    LGraphTextureLUT.pixel_shader
                );
            }
        }
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;
	}
1268612
function createShader(
    gl
  , vertSource
  , fragSource
  , uniforms
  , attributes) {
  
  //Compile vertex shader
  var vertShader = gl.createShader(gl.VERTEX_SHADER)
  gl.shaderSource(vertShader, vertSource)
  gl.compileShader(vertShader)
  if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
    var errLog = gl.getShaderInfoLog(vertShader)
    console.error('gl-shader: Error compling vertex shader:', errLog)
    throw new Error('gl-shader: Error compiling vertex shader:' + errLog)
  }
  
  //Compile fragment shader
  var fragShader = gl.createShader(gl.FRAGMENT_SHADER)
  gl.shaderSource(fragShader, fragSource)
  gl.compileShader(fragShader)
  if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
    var errLog = gl.getShaderInfoLog(fragShader)
    console.error('gl-shader: Error compiling fragment shader:', errLog)
    throw new Error('gl-shader: Error compiling fragment shader:' + errLog)
  }
  
  //Link program
  var program = gl.createProgram()
  gl.attachShader(program, fragShader)
  gl.attachShader(program, vertShader)

  //Optional default attriubte locations
  attributes.forEach(function(a) {
    if (typeof a.location === 'number') 
      gl.bindAttribLocation(program, a.location, a.name)
  })

  gl.linkProgram(program)
  if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    var errLog = gl.getProgramInfoLog(program)
    console.error('gl-shader: Error linking shader program:', errLog)
    throw new Error('gl-shader: Error linking shader program:' + errLog)
  }
  
  //Return final linked shader object
  var shader = new Shader(
    gl,
    program,
    vertShader,
    fragShader
  )
  shader.updateExports(uniforms, attributes)

  return shader
}
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 )
777187
function glsl () {
  return {
    transform(glsl, id) {
      if (/\.glsl$/.test(id) === false) return
			// remove comments and fix new line chars
      var shaderAsText = glsl
        .replace(/[ \t]*\/\/.*\n/g, '') // remove //
        .replace(/[ \t]*\/\*[\s\S]*?\*\//g, '') // remove /* */
        .replace(/\n{2,}/g, '\n') // # \n+ to \n
      //
      var shaderAsBase64 = 'data:text/plain;base64,' + new Buffer(shaderAsText).toString('base64')
			//
      var moduleApi = { text: shaderAsText, base64: shaderAsBase64 }
      // add module wrapper
			var code = 'export default ' + JSON.stringify(moduleApi) + ';'
      return {
        code: code,
        map: {mappings: ''}
      }
    }
  }
}
1252810
function VertexArray(gl, numVerts, float32Allocator)  {
  VertexArrayBase.call(this, gl, numVerts, float32Allocator);
  this._numVerts = 0;
  this._primitiveType = this._gl.LINES;
}
364171
void draw(GLShader shader, InternalTransform xform, int tint,
            float dx, float dy, float dw, float dh) {
    draw(shader, xform, tint, dx, dy, dw, dh,
         0, 0, (repeatX ? dw : width()), (repeatY ? dh : height()));
  }
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;
}
447561
private void drawTriangle(ShaderBuffer out1, float x1, float y1, float z1, float w1,
                              ShaderBuffer out2, float x2, float y2, float z2, float w2,
                              ShaderBuffer out3, float x3, float y3, float z3, float w3,
                              ShaderImplementation fragmentShader, ShaderBuffer fragmentIn, ShaderBuffer fragmentOut) {
        // (28).(4) (in bits) fixed-point coordinates
        final int fy1 = Math.round(y1 * 16);
        final int fy2 = Math.round(y2 * 16);
        final int fy3 = Math.round(y3 * 16);
        final int fx1 = Math.round(x1 * 16);
        final int fx2 = Math.round(x2 * 16);
        final int fx3 = Math.round(x3 * 16);
        // Deltas
        final int dx12 = fx1 - fx2;
        final int dx23 = fx2 - fx3;
        final int dx31 = fx3 - fx1;
        final int dy12 = fy1 - fy2;
        final int dy23 = fy2 - fy3;
        final int dy31 = fy3 - fy1;
        // Fixed-point deltas
        final int fdx12 = dx12 << 4;
        final int fdx23 = dx23 << 4;
        final int fdx31 = dx31 << 4;
        final int fdy12 = dy12 << 4;
        final int fdy23 = dy23 << 4;
        final int fdy31 = dy31 << 4;
        // Block size, standard 8x8 (must be power of two), here 2^3
        final int block = 1 << 3;
        // Bounding rectangle, start in the corner of the 8x8 block
        final int minX = Math.min(fx1, Math.min(fx2, fx3)) + 0xf >> 4 & ~(block - 1);
        final int maxX = Math.max(fx1, Math.max(fx2, fx3)) + 0xf >> 4;
        final int minY = Math.min(fy1, Math.min(fy2, fy3)) + 0xf >> 4 & ~(block - 1);
        final int maxY = Math.max(fy1, Math.max(fy2, fy3)) + 0xf >> 4;
        // Determinant of deltas to compute the normalized barycentric coordinates for interpolation
        final float det = dx23 * dy12 - dy23 * dx12;
        // Barycentric coordinates
        int c1 = dy12 * fx1 - dx12 * fy1;
        int c2 = dy23 * fx2 - dx23 * fy2;
        int c3 = dy31 * fx3 - dx31 * fy3;
        // Correct for fill convention
        if (dy12 < 0 || dy12 == 0 && dx12 > 0) {
            c1++;
        }
        if (dy23 < 0 || dy23 == 0 && dx23 > 0) {
            c2++;
        }
        if (dy31 < 0 || dy31 == 0 && dx31 > 0) {
            c3++;
        }
        // Loop through blocks
        for (int by = minY; by < maxY; by += block) {
            for (int bx = minX; bx < maxX; bx += block) {
                // Corners of block
                final int bx0 = bx << 4;
                final int bx1 = bx + block - 1 << 4;
                final int by0 = by << 4;
                final int by1 = by + block - 1 << 4;
                // Evaluate half-space functions
                final boolean a00 = c1 + dx12 * by0 - dy12 * bx0 <= 0;
                final boolean a10 = c1 + dx12 * by0 - dy12 * bx1 <= 0;
                final boolean a01 = c1 + dx12 * by1 - dy12 * bx0 <= 0;
                final boolean a11 = c1 + dx12 * by1 - dy12 * bx1 <= 0;
                final boolean b00 = c2 + dx23 * by0 - dy23 * bx0 <= 0;
                final boolean b10 = c2 + dx23 * by0 - dy23 * bx1 <= 0;
                final boolean b01 = c2 + dx23 * by1 - dy23 * bx0 <= 0;
                final boolean b11 = c2 + dx23 * by1 - dy23 * bx1 <= 0;
                final boolean c00 = c3 + dx31 * by0 - dy31 * bx0 <= 0;
                final boolean c10 = c3 + dx31 * by0 - dy31 * bx1 <= 0;
                final boolean c01 = c3 + dx31 * by1 - dy31 * bx0 <= 0;
                final boolean c11 = c3 + dx31 * by1 - dy31 * bx1 <= 0;
                // Skip the block when outside an edge
                if (a00 && a10 && a01 && a11 || b00 && b10 && b01 && b11 || c00 && c10 && c01 && c11) {
                    continue;
                }
                // Compute the barycentric coordinates
                int cy1 = c1 + dx12 * by0 - dy12 * bx0;
                int cy2 = c2 + dx23 * by0 - dy23 * bx0;
                int cy3 = c3 + dx31 * by0 - dy31 * bx0;
                // Iterate the block
                for (int y = by; y < by + block; y++) {
                    int cx1 = cy1;
                    int cx2 = cy2;
                    int cx3 = cy3;
                    for (int x = bx; x < bx + block; x++) {
                        // Only draw pixels inside the triangle
                        if (cx1 > 0 && cx2 > 0 && cx3 > 0) {
                            // Compute the normalized barycentric coordinates
                            final float t = cx1 / det;
                            final float r = cx2 / det;
                            final float s = 1 - t - r;
                            // Lerp the rest of the data using the barycentric coordinates
                            final float z = SoftwareUtil.baryLerp(z1, z2, z3, r, s, t);
                            final float w = SoftwareUtil.baryLerp(w1, w2, w3, r, s, t);
                            fragmentIn.clear();
                            fragmentIn.writeRaw(Float.floatToIntBits(x));
                            fragmentIn.writeRaw(Float.floatToIntBits(y));
                            fragmentIn.writeRaw(Float.floatToIntBits(z));
                            fragmentIn.writeRaw(Float.floatToIntBits(w));
                            out1.position(4);
                            out2.position(4);
                            out3.position(4);
                            SoftwareUtil.baryLerp(out1, out2, out3, r, s, t, 1, fragmentIn);
                            fragmentIn.flip();
                            // Shade and write the fragment
                            writeFragment(fragmentShader, fragmentIn, fragmentOut, x, y, z);
                        }
                        cx1 -= fdy12;
                        cx2 -= fdy23;
                        cx3 -= fdy31;
                    }
                    cy1 += fdx12;
                    cy2 += fdx23;
                    cy3 += fdx31;
                }
            }
        }
    }
1235062
def _load_shader(filename):
    """"""
    curdir = op.dirname(op.realpath(__file__))
    glsl_path = op.join(curdir, 'glsl')
    path = op.join(glsl_path, filename)
    with open(path, 'r') as f:
        return f.read()
705441
def bInit( self, vrModel, vrDiffuseTexture ):
        ""
        # create and bind a VAO to hold state for this model
        self.m_glVertArray = glGenVertexArrays(1)
        glBindVertexArray( self.m_glVertArray )
        # Populate a vertex buffer
        self.m_glVertBuffer = glGenBuffers(1)
        glBindBuffer( GL_ARRAY_BUFFER, self.m_glVertBuffer )
        glBufferData( GL_ARRAY_BUFFER, sizeof( openvr.RenderModel_Vertex_t ) * vrModel.unVertexCount, vrModel.rVertexData, GL_STATIC_DRAW )
        # Identify the components in the vertex buffer
        glEnableVertexAttribArray( 0 )
        glVertexAttribPointer( 0, 3, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.vPosition.offset )
        glEnableVertexAttribArray( 1 )
        glVertexAttribPointer( 1, 3, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.vNormal.offset )
        glEnableVertexAttribArray( 2 )
        glVertexAttribPointer( 2, 2, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.rfTextureCoord.offset )
        # Create and populate the index buffer
        self.m_glIndexBuffer = glGenBuffers(1)
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, self.m_glIndexBuffer )
        glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( ctypes.c_uint16 ) * vrModel.unTriangleCount * 3, vrModel.rIndexData, GL_STATIC_DRAW )
        glBindVertexArray( 0 )
        # create and populate the texture
        self.m_glTexture = glGenTextures(1)
        glBindTexture( GL_TEXTURE_2D, self.m_glTexture )
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, vrDiffuseTexture.unWidth, vrDiffuseTexture.unHeight,
            0, GL_RGBA, GL_UNSIGNED_BYTE, vrDiffuseTexture.rubTextureMapData )
        # If this renders black ask McJohn what's wrong.
        glGenerateMipmap(GL_TEXTURE_2D)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR )
        fLargest = glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT )
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest )
        glBindTexture( GL_TEXTURE_2D, 0 )
        self.m_unVertexCount = vrModel.unTriangleCount * 3
        return True
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;
}