Monkey-patch pyopengl to fix a bug in glBufferSubData.
514252
def _patch():
    
    import sys
    from OpenGL import GL
    if sys.version_info > (3,):
        buffersubdatafunc = GL.glBufferSubData
        if hasattr(buffersubdatafunc, 'wrapperFunction'):
            buffersubdatafunc = buffersubdatafunc.wrapperFunction
        _m = sys.modules[buffersubdatafunc.__module__]
        _m.long = int
    
    # Fix missing enum
    try:
        from OpenGL.GL.VERSION import GL_2_0
        GL_2_0.GL_OBJECT_SHADER_SOURCE_LENGTH = GL_2_0.GL_SHADER_SOURCE_LENGTH
    except Exception:
        pass
1322737
function(initial_csg) {
    var csg = initial_csg.canonicalized();
    var mesh = new GL.Mesh({ normals: true, colors: true });
    var meshes = [ mesh ];
    var vertexTag2Index = {};
    var vertices = [];
    var colors = [];
    var triangles = [];
    // set to true if we want to use interpolated vertex normals
    // this creates nice round spheres but does not represent the shape of
    // the actual model
    var smoothlighting = this.solid.smooth;
    var polygons = csg.toPolygons();
    var numpolygons = polygons.length;
    for(var j = 0; j < numpolygons; j++) {
      var polygon = polygons[j];
      var color = this.solid.color;  // default color
  
      if(polygon.shared && polygon.shared.color) {
        color = polygon.shared.color;
      } else if(polygon.color) {
        color = polygon.color;
      }

      if (color.length < 4)
        color.push(1.); //opaque

      var indices = polygon.vertices.map(function(vertex) {
        var vertextag = vertex.getTag();
        var vertexindex = vertexTag2Index[vertextag];
        var prevcolor = colors[vertexindex];
        if(smoothlighting && (vertextag in vertexTag2Index) &&
          (prevcolor[0] == color[0]) &&
          (prevcolor[1] == color[1]) &&
          (prevcolor[2] == color[2])
        ) {
          vertexindex = vertexTag2Index[vertextag];
        } else {
          vertexindex = vertices.length;
          vertexTag2Index[vertextag] = vertexindex;
          vertices.push([vertex.pos.x, vertex.pos.y, vertex.pos.z]);
          colors.push(color);
        }
        return vertexindex;
      });
      for (var i = 2; i < indices.length; i++) {
        triangles.push([indices[0], indices[i - 1], indices[i]]);
      }
      // if too many vertices, start a new mesh;
      if (vertices.length > 65000) {
        // finalize the old mesh
        mesh.triangles = triangles;
        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.computeWireframe();
        mesh.computeNormals();

        if ( mesh.vertices.length ) {
          meshes.push(mesh);
        }

        // start a new mesh
        mesh = new GL.Mesh({ normals: true, colors: true });
        triangles = [];
        colors = [];
        vertices = [];
      }
    }
    // finalize last mesh
    mesh.triangles = triangles;
    mesh.vertices = vertices;
    mesh.colors = colors;
    mesh.computeWireframe();
    mesh.computeNormals();

    if ( mesh.vertices.length ) {
      meshes.push(mesh);
    }

    return meshes;
  }
1091062
function _gpfFuncImpl (params, source) {
    _gpfAssert(typeof source === "string" && source.length, "Source expected (or use _gpfEmptyFunc)");
    /*#ifdef(DEBUG)*/
    try {
        /*#endif*/
        return _gpfFuncUnsafe(params, source);
        /*#ifdef(DEBUG)*/
    } catch (e) {
        throw _gpfFuncImplDocumentError(e, params, source);
    }
    /*#endif*/
}
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)
252937
function( gl, v, renderer ) {

			var n = v.length,
				units = allocTexUnits( renderer, n );

			gl.uniform1iv( this.addr, units );

			for ( var i = 0; i !== n; ++ i ) {

				renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );

			}

		}
298906
function updateFieldColorBuffer(lut, fieldData, buf) {
  // var buf = new Float32Array(fieldData.length * 3);
  for (let i = 0; i < fieldData.length; ++i) {
    const idx = i * 3,
      color = lut.getColor(fieldData[i]);
    buf[idx] = color[0];
    buf[idx + 1] = color[1];
    buf[idx + 2] = color[2];
  }
  return buf;
}
1278705
function fixOldGradient (args, gradient) {
	const type = args[0][0];
	let colorStops = [];
	let from;
	let to;

	// 将参数中的`color-stop`,`from`,`to`三种信息剔除出args并单独存放，剩下的存起来
	args = args.slice(1).filter((arg) => {
		const fnName = arg.value;
		if (fnName === "from") {
			from = arg;
		} else if (fnName === "to") {
			to = arg;
		} else if (fnName === "color-stop") {
			colorStops.push(arg);
		} else {
			return true;
		}
		return false;
	});

	if (from) {
		// 将from信息放入colorStops头部
		colorStops.unshift(from);
	}
	if (to) {
		// 将from信息放入colorStops尾部
		colorStops.push(to);
	}

	// 将数组colorStops中的元素都转换为标准形式
	colorStops = colorStops.map((colorStop, i) => {
		// 获取colorStop的参数
		colorStop = colorStop.nodes;
		// 如果不知一个参数
		if (colorStop.length > 1) {
			// 计算位置信息的浏览器默认值
			const posVal = i * 100 / (colorStops.length - 1);
			colorStop = colorStop.filter((val) => {
				// 如果位置信息与浏览器默认值相同，去除它
				return parseFloat(val) !== posVal;
			});

			if (colorStop.length > 1) {
				// 参数重新排列，位置信息放在后面，以便符合新语法
				colorStop.sort((word) => {
					return isNaN(parseFloat(word)) ? -1 : 1;
				});
			}
		}
		return colorStop;
	});

	if (type === "radial") {
		// 按照圆形渐变语法处理剩下的参数
		args = fixOldRadialGradient(args);
	} else {
		// 按照线性渐变语法处理剩下的参数
		args = fixOldLinearGradient(args);
	}

	if (args && args.length) {
		// 将`fixOldRadialGradient`或`fixOldLinearGradient`的返回结果插入colorStops
		colorStops.unshift(args);
	}
	// 将css属性名名称转换为标准的
	gradient.value = type + "-gradient";
	return colorStops;
}
167848
def compress_monkey_patch():
    
    from compressor.templatetags import compress as compress_tags
    from compressor import base as compress_base

    compress_base.Compressor.filter_input = filter_input
    compress_base.Compressor.output = output
    compress_base.Compressor.hunks = hunks
    compress_base.Compressor.precompile = precompile

    compress_tags.CompressorMixin.render_compressed = render_compressed

    from django_pyscss import compressor as pyscss_compressor

    pyscss_compressor.DjangoScssFilter.input = input
652201
function showGlInfo(gl) {
  const vertexUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  const fragmentUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  const combinedUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  console.log('vertex texture image units:', vertexUnits);
  console.log('fragment texture image units:', fragmentUnits);
  console.log('combined texture image units:', combinedUnits);
}
609958
function makePointsProgram(gl, data) {
  let vertexProgram = vertexProgramCache.get(gl)
  if (!vertexProgram) {
    let vertexShader = gl_utils.compile(gl, gl.VERTEX_SHADER, vertexShaderSrc);
    let fragmentShader = gl_utils.compile(gl, gl.FRAGMENT_SHADER, fragmentShaderSrc);
    vertexProgram = gl_utils.link(gl, vertexShader, fragmentShader);
    vertexProgramCache.set(gl, vertexProgram);
  }

  let locations = gl_utils.getLocations(gl, vertexProgram);

  var buffer = gl.createBuffer();
  if (!buffer) throw new Error('failed to create a nodesBuffer');
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data.byteLength, gl.DYNAMIC_DRAW);

  var pointTexture = createCircleTexture(gl);

  var api = {
    draw,
    updateData,
    dispose
  };
  return api;

  function updateData(newData) {
    data = newData;
  }

  function dispose() {
    // For some reason disposing the buffer results in unbindable
    // buffer for the lines program (that is created after this scene is disposed).
    // gl.deleteBuffer(buffer);
    gl.deleteProgram(vertexProgram);
    gl.deleteTexture(pointTexture);
    vertexProgramCache.delete(gl);
  }

  function draw(transform, screen, count) {
    gl.useProgram(vertexProgram);

    var bpe = data.BYTES_PER_ELEMENT;

    if (transform) {
      gl.uniformMatrix4fv(locations.uniforms.uTransform, false, transform.getArray());
    }
    gl.uniform2f(locations.uniforms.uScreenSize, screen.width, screen.height);
    gl.bindTexture(gl.TEXTURE_2D, pointTexture);

    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);

    gl.vertexAttribPointer(locations.attributes.aPosition, 2, gl.FLOAT, false, bpe * 6, 0)
    gl.enableVertexAttribArray(locations.attributes.aPosition)

    gl.vertexAttribPointer(locations.attributes.aPointSize, 1, gl.FLOAT, false, bpe * 6, 2 * bpe)
    gl.enableVertexAttribArray(locations.attributes.aPointSize)

    gl.vertexAttribPointer(locations.attributes.aColor, 3, gl.FLOAT, false, bpe * 6, 3 * bpe)
    gl.enableVertexAttribArray(locations.attributes.aColor);
    gl.drawArrays(gl.POINTS, 0, count);
  }
}
1116220
function checkWebGlSupported() {
  var canvas = document.createElement('canvas');
  var gl = canvas.getContext && (canvas.getContext('webgl') ||
                                 canvas.getContext('experimental-webgl'));
  return !!gl;
}
171693
def clear(options = {})
      options = {
          color: [0.0, 0.0, 0.0, 0.0],
      }.merge! options

      color = options[:color]
      color = color.to_opengl if color.is_a? Gosu::Color

      Gl.glBindFramebufferEXT Gl::GL_FRAMEBUFFER_EXT, fbo_id unless rendering?

      Gl.glDisable Gl::GL_BLEND # Need to replace the alpha too.
      Gl.glClearColor(*color)
      Gl.glClear Gl::GL_COLOR_BUFFER_BIT | Gl::GL_DEPTH_BUFFER_BIT
      Gl.glEnable Gl::GL_BLEND

      Gl.glBindFramebufferEXT Gl::GL_FRAMEBUFFER_EXT, 0 unless rendering?

      nil
    end
868627
def update_gl_state(self, *args, **kwargs):
        
        for v in self._subvisuals:
            v.update_gl_state(*args, **kwargs)
532271
function update (opt) {
    // remove old shaders
    disposeShaders()

    var quiet = opt.quiet
    var attributeBindings = opt.attributes

    var vertSrc = opt.vertex || defaultVertex
    var fragSrc = opt.fragment || defaultFragment

    // re-compile source
    vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertSrc, quiet, name)
    fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc, quiet, name)

    // re-link
    var shaders = [ vertexShader, fragmentShader ]
    linkShaders(gl, program, shaders, attributeBindings, quiet, name)

    // extract uniforms and attributes
    types = extract(gl, program)

    // allow user to inject some dummy uniforms
    if (opt.uniforms) {
      var inactiveUniforms = []
      opt.uniforms.forEach(function (uniform) {
        if (indexOfName(types.uniforms, uniform.name) === -1) {
          inactiveUniforms.push(uniform)
          types.uniforms.push({ name: uniform.name, type: uniform.type })
        }
      })

      // provide UX for inactive uniforms...? TBD
      if (!quiet && inactiveUniforms.length > 0) {
        var shaderName = name ? (' (' + name + ')') : ''
        console.warn('Inactive uniforms in shader' + shaderName + ': '
          + inactiveUniforms
            .map(function (x) { return x.name })
            .join(', '))
      }
    }

    // normalize sort order by name across Chrome / FF
    types.uniforms.sort(compareString)
    types.attributes.sort(compareString)

    // provide optimized getters/setters
    uniforms = reflect(types.uniforms, function (uniform, index) {
      return makeUniformProp(uniform, index)
    })

    // provide attribute locations and type
    // (GLSL ES does not support array/struct attributes)
    attributes = types.attributes.reduce(function (struct, attrib) {
      var name = attrib.name
      struct[name] = {
        size: dimension(attrib.type),
        type: attrib.type,
        location: gl.getAttribLocation(program, name)
      }
      return struct
    }, {})
  }
27358
function FrameBuffer(gl, width, height, options) {
		var frameBuffer,
			renderBuffer,
			tex,
			status,
			useFloat = options === true ? options : (options && options.useFloat);

		useFloat = false;//useFloat && !!gl.getExtension("OES_texture_float"); //useFloat is not ready!
		if (useFloat) {
			this.type = gl.FLOAT;
		} else {
			this.type = gl.UNSIGNED_BYTE;
		}

		frameBuffer = gl.createFramebuffer();
		gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);

		if (options && options.texture) {
			this.texture = options.texture;
			gl.bindTexture(gl.TEXTURE_2D, this.texture);
			this.ownTexture = false;
		} else {
			this.texture = gl.createTexture();
			gl.bindTexture(gl.TEXTURE_2D, this.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);
			this.ownTexture = true;
		}

		try {
			if (this.type === gl.FLOAT) {
				tex = new Float32Array(width * height * 4);
				gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, tex);
			} else {
				gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
				this.type = gl.UNSIGNED_BYTE;
			}
		} catch (e) {
			// Null rejected
			this.type = gl.UNSIGNED_BYTE;
			tex = new Uint8Array(width * height * 4);
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, tex);
		}

		renderBuffer = gl.createRenderbuffer();
		gl.bindRenderbuffer(gl.RENDERBUFFER, renderBuffer);
		gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
		gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderBuffer);

		gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);

		status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);

		if (status === gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT) {
			throw('Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
		}

		if (status === gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
			throw('Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
		}

		if (status === gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS) {
			throw('Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
		}

		if (status === gl.FRAMEBUFFER_UNSUPPORTED) {
			throw('Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED');
		}

		if (status !== gl.FRAMEBUFFER_COMPLETE) {
			throw('Incomplete framebuffer: ' + status);
		}

		//clean up
		gl.bindTexture(gl.TEXTURE_2D, null);
		gl.bindRenderbuffer(gl.RENDERBUFFER, null);
		gl.bindFramebuffer(gl.FRAMEBUFFER, null);

		this.gl = gl;
		this.frameBuffer = frameBuffer;
		this.renderBuffer = renderBuffer;
		this.width = width;
		this.height = height;
	}
200188
def _update(self):
        

        if self._vertices_buffer is not None:
            self._vertices_buffer.delete()
        self._vertices_buffer = VertexBuffer(self._vertices_list.data)

        if self.itype is not None:
            if self._indices_buffer is not None:
                self._indices_buffer.delete()
            self._indices_buffer = IndexBuffer(self._indices_list.data)

        if self.utype is not None:
            if self._uniforms_texture is not None:
                self._uniforms_texture.delete()

            # We take the whole array (_data), not the data one
            texture = self._uniforms_list._data.view(np.float32)
            size = len(texture) / self._uniforms_float_count
            shape = self._compute_texture_shape(size)

            # shape[2] = float count is only used in vertex shader code
            texture = texture.reshape(shape[0], shape[1], 4)
            self._uniforms_texture = Texture2D(texture)
            self._uniforms_texture.data = texture
            self._uniforms_texture.interpolation = 'nearest'

        if len(self._programs):
            for program in self._programs:
                program.bind(self._vertices_buffer)
                if self._uniforms_list is not None:
                    program["uniforms"] = self._uniforms_texture
                    program["uniforms_shape"] = self._ushape
203528
def getMirrorTextureGL(self, eEye):
        """"""

        fn = self.function_table.getMirrorTextureGL
        pglTextureId = glUInt_t()
        pglSharedTextureHandle = glSharedTextureHandle_t()
        result = fn(eEye, byref(pglTextureId), byref(pglSharedTextureHandle))
        return result, pglTextureId, pglSharedTextureHandle