allocate OpenGL resources
962180
def init_gl(self):
        ""
        self.vr_system = openvr.init(openvr.VRApplication_Scene)
        w, h = self.vr_system.getRecommendedRenderTargetSize()
        self.left_fb = OpenVrFramebuffer(w, h, multisample=self.multisample)
        self.right_fb = OpenVrFramebuffer(w, h, multisample=self.multisample)
        self.compositor = openvr.VRCompositor()
        if self.compositor is None:
            raise Exception("Unable to create compositor") 
        self.left_fb.init_gl()
        self.right_fb.init_gl()
        # Compute projection matrix
        zNear = 0.2
        zFar = 500.0
        self.projection_left = numpy.asarray(matrixForOpenVrMatrix(self.vr_system.getProjectionMatrix(
                openvr.Eye_Left, 
                zNear, zFar)))
        self.projection_right = numpy.asarray(matrixForOpenVrMatrix(self.vr_system.getProjectionMatrix(
                openvr.Eye_Right, 
                zNear, zFar)))
        self.view_left = matrixForOpenVrMatrix(
            self.vr_system.getEyeToHeadTransform(openvr.Eye_Left)).I  # head_X_eye in Kane notation
        self.view_right = matrixForOpenVrMatrix(
            self.vr_system.getEyeToHeadTransform(openvr.Eye_Right)).I  # head_X_eye in Kane notation
        for actor in self:
            actor.init_gl()
181926
def glBufferData(target, data, usage):
    
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    res = _lib.glBufferData(target, size, data, usage)
590032
def send(self):
        

        for name, array in iteritems(self):

            shader_id = c_int(0)
            gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM, byref(shader_id))
            if shader_id.value == 0:
                raise UnboundLocalError("""Shader not bound to OpenGL context--uniform cannot be sent.
                ------------ Tip -------------
                with ratcave.default_shader:
                    mesh.draw()
                ------------------------------
                """)

            # Attach a shader location value to the array, for quick memory lookup. (gl calls are expensive, for some reason)
            try:
                loc, shader_id_for_array = array.loc
                if shader_id.value != shader_id_for_array:
                    raise Exception('Uniform location bound to a different shader')
            except (AttributeError, Exception) as e:
                array.loc = (gl.glGetUniformLocation(shader_id.value, name.encode('ascii')), shader_id.value)

            if array.ndim == 2:  # Assuming a 4x4 float32 matrix (common for graphics operations)
                try:
                    pointer = array.pointer
                except AttributeError:
                    array.pointer = array.ctypes.data_as(POINTER(c_float * 16)).contents
                    pointer = array.pointer
                gl.glUniformMatrix4fv(array.loc[0], 1, True, pointer)

            else:
                sendfun = self._sendfuns[array.dtype.kind][len(array) - 1]  # Find correct glUniform function
                sendfun(array.loc[0], *array)
1065136
def set_shaders(self, vert, frag):
        
        if not vert or not frag:
            raise ValueError('Vertex and fragment code must both be non-empty')
        
        # pre-process shader code for #include directives
        vert, frag = preprocess(vert), preprocess(frag)
        
        # Store source code, send it to glir, parse the code for variables
        self._shaders = vert, frag

        self._glir.command('SHADERS', self._id, vert, frag)
        # All current variables become pending variables again
        for key, val in self._user_variables.items():
            self._pending_variables[key] = val
        self._user_variables = {}
        # Parse code (and process pending variables)
        self._parse_variables_from_code()
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()
293038
public void setAllocatedResource(final AllocatedResource resource) {

		final Iterator<ExecutionVertex> it = this.vertices.iterator();
		while (it.hasNext()) {
			final ExecutionVertex vertex = it.next();
			vertex.setAllocatedResource(resource);
		}
	}
850391
protected function allocateColors()
    {
        // allocate bg color first for imagecreate
        $this->gdbgcolor = imagecolorallocate($this->im,
                                              $this->image_bg_color->r,
                                              $this->image_bg_color->g,
                                              $this->image_bg_color->b);

        $alpha = intval($this->text_transparency_percentage / 100 * 127);

        if ($this->use_transparent_text == true) {
            $this->gdtextcolor = imagecolorallocatealpha($this->im,
                                                         $this->text_color->r,
                                                         $this->text_color->g,
                                                         $this->text_color->b,
                                                         $alpha);
            $this->gdlinecolor = imagecolorallocatealpha($this->im,
                                                         $this->line_color->r,
                                                         $this->line_color->g,
                                                         $this->line_color->b,
                                                         $alpha);
            $this->gdnoisecolor = imagecolorallocatealpha($this->im,
                                                          $this->noise_color->r,
                                                          $this->noise_color->g,
                                                          $this->noise_color->b,
                                                          $alpha);
        } else {
            $this->gdtextcolor = imagecolorallocate($this->im,
                                                    $this->text_color->r,
                                                    $this->text_color->g,
                                                    $this->text_color->b);
            $this->gdlinecolor = imagecolorallocate($this->im,
                                                    $this->line_color->r,
                                                    $this->line_color->g,
                                                    $this->line_color->b);
            $this->gdnoisecolor = imagecolorallocate($this->im,
                                                          $this->noise_color->r,
                                                          $this->noise_color->g,
                                                          $this->noise_color->b);
        }

        $this->gdsignaturecolor = imagecolorallocate($this->im,
                                                     $this->signature_color->r,
                                                     $this->signature_color->g,
                                                     $this->signature_color->b);

    }
1025619
function InitShaders (gl, opts) {
  var numJoints = opts.numJoints

  var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
  var vertexShader = gl.createShader(gl.VERTEX_SHADER)

  gl.shaderSource(fragmentShader, fragment)
  gl.compileShader(fragmentShader)

  gl.shaderSource(vertexShader, vertex)
  gl.compileShader(vertexShader)

  var shaderProgram = gl.createProgram()
  gl.attachShader(shaderProgram, fragmentShader)
  gl.attachShader(shaderProgram, vertexShader)
  gl.linkProgram(shaderProgram)
  gl.useProgram(shaderProgram)

  var vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition')
  gl.enableVertexAttribArray(vertexPositionAttribute)

  var vertexNormalAttribute = gl.getAttribLocation(shaderProgram, 'aVertexNormal')
  gl.enableVertexAttribArray(vertexNormalAttribute)

  var jointIndexAttribute = gl.getAttribLocation(shaderProgram, 'aJointIndex')
  gl.enableVertexAttribArray(jointIndexAttribute)

  var jointWeightAttribute = gl.getAttribLocation(shaderProgram, 'aJointWeight')
  gl.enableVertexAttribArray(jointWeightAttribute)

  var shaderObj = {
    ambientColorUniform: gl.getUniformLocation(shaderProgram, 'uAmbientColor'),
    lightingDirectionUniform: gl.getUniformLocation(shaderProgram, 'uLightingDirection'),
    directionalColorUniform: gl.getUniformLocation(shaderProgram, 'uDirectionalColor'),
    program: shaderProgram,
    vertexPositionAttribute: vertexPositionAttribute,
    vertexNormalAttribute: vertexNormalAttribute,
    jointIndexAttribute: jointIndexAttribute,
    jointWeightAttribute: jointWeightAttribute,
    samplerUniform: gl.getUniformLocation(shaderProgram, 'uSampler'),
    pMatrixUniform: gl.getUniformLocation(shaderProgram, 'uPMatrix'),
    mvMatrixUniform: gl.getUniformLocation(shaderProgram, 'uMVMatrix')
  }

  for (var jointNum = 0; jointNum < numJoints; jointNum++) {
    shaderObj['boneMatrix' + jointNum] = gl.getUniformLocation(shaderProgram, 'boneMatrices[' + jointNum + ']')
    // Split our dual quaternion into two vec4's since we can't use mat2x4 in WebGL
    shaderObj['boneRotQuaternion' + jointNum] = gl.getUniformLocation(shaderProgram, 'boneRotQuaternions[' + jointNum + ']')
    shaderObj['boneTransQuaternion' + jointNum] = gl.getUniformLocation(shaderProgram, 'boneTransQuaternions[' + jointNum + ']')
  }

  return shaderObj
}
1366570
function() {
		var gl = this.gl;

		var fragmentShaderSource = [
			"precision mediump float;",
			"uniform sampler2D bgTexture;",
			"uniform sampler2D spriteTexture;",
			"uniform sampler2D prioTexture;",
			"uniform sampler2D paletteTexture;",
			"uniform vec4 bgColor;",
			"varying vec2 texCoord;",

			"void main(void) {",
				"float bgIndex = texture2D(bgTexture, texCoord).r;",
				"float spriteIndex = texture2D(spriteTexture, texCoord).r;",
				"float prioIndex = texture2D(prioTexture, texCoord).r;",
				"float colorIndex = ((spriteIndex > 0.0 && (prioIndex == 0.0 || bgIndex == 0.0)) ? spriteIndex : bgIndex);",
				"vec4 color = texture2D(paletteTexture, vec2( colorIndex * 4.0 + 0.0078, 0.5));", // 0.0078 == ( 0.5 * 3 / 192 ) === ( 0.5 * [RGB colors] / [palette width] )
				"if ( colorIndex > 0.0 ) {",
					"gl_FragColor = color;",
				"} else {",
					"gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);",
					"gl_FragColor = bgColor;",
				"}",
			"}"
		].join("\n");

		var vertexShaderSource = [
			"attribute vec2 vertCoord;",
			"varying vec2 texCoord;",

			"void main() {",
				"gl_Position = vec4(vertCoord, 0, 1);",
				"texCoord = vec2( 0.5 * ( vertCoord.x + 1.0 ), 0.5 * (1.0 - vertCoord.y));",
			"}"
		].join("");

		this.fragmentShader = compileShader( gl.FRAGMENT_SHADER, fragmentShaderSource );
		this.vertexShader = compileShader( gl.VERTEX_SHADER, vertexShaderSource );

		function compileShader( shaderType, shaderSource ) {
			var shader = gl.createShader( shaderType );
			gl.shaderSource( shader, shaderSource );
			gl.compileShader( shader );

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

			return shader;
		}
	}
954278
function () {
            if (this.length) {
                var gl = this.gl;

                // Copy data into stream buffer
                var len = this.length * ELEMENT_SIZE * ELEMENTS_PER_QUAD;
                gl.bufferData(
                    gl.ARRAY_BUFFER,
                    this.stream.subarray(0, len),
                    gl.STREAM_DRAW
                );

                // Draw the stream buffer
                gl.drawElements(
                    gl.TRIANGLES,
                    this.length * INDICES_PER_QUAD,
                    gl.UNSIGNED_SHORT,
                    0
                );

                this.sbIndex = 0;
                this.length = 0;
            }
        }
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;
	}
995093
def bind(self):
        """"""
        # This is called simply to deal with anything that might be currently bound (for example, Pyglet objects),
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)

        # Store current viewport size for later
        self._old_viewport = get_viewport()

        # Bind the FBO, and change the viewport to fit its texture.
        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, self.id)  # Rendering off-screen
        gl.glViewport(0, 0, self.texture.width, self.texture.height)
364711
def allocate(n, dtype=numpy.float32):
    
    return drv.pagelocked_empty(int(n), dtype, order='C', mem_flags=drv.host_alloc_flags.PORTABLE)
873912
function GPU() {
      var _this;

      var ua = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var cssFlagsPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'gpu';

      _classCallCheck(this, GPU);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(GPU).call(this, ua, flags, cssFlagsPrefix));

      _this._createTestElements();

      _this.webGLVendor = _this._info.webGLVendor;
      _this.webGLRenderer = _this._info.webGLRenderer;
      _this.vendor = _this._info.vendor;
      _this.model = _this._info.model;
      _this.renderer = _this._info.renderer;
      return _this;
    }
819239
def allocate(self):
        """"""
        network_name = None

        self._hypervisor = libvirt.open(
            self.configuration.get('hypervisor', 'lxc:///'))

        if 'network' in self.configuration:
            self._network = network.create(self._hypervisor, self.identifier,
                                           self.configuration['network'])
            network_name = self._network.name()

        self._domain = domain_create(self._hypervisor, self.identifier,
                                     self.configuration['domain'],
                                     network_name=network_name)
        if self._network is None:
            self._network = network.lookup(self._domain)
118960
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.setTexture2D( v[ i ] || emptyTexture, units[ i ] );

			}

		}
191843
def _setup_resources():
    
    target_procs = 10240
    cur_proc, max_proc = resource.getrlimit(resource.RLIMIT_NPROC)
    target_proc = min(max_proc, target_procs) if max_proc > 0 else target_procs
    resource.setrlimit(resource.RLIMIT_NPROC, (max(cur_proc, target_proc), max_proc))
    cur_hdls, max_hdls = resource.getrlimit(resource.RLIMIT_NOFILE)
    target_hdls = min(max_hdls, target_procs) if max_hdls > 0 else target_procs
    resource.setrlimit(resource.RLIMIT_NOFILE, (max(cur_hdls, target_hdls), max_hdls))