DDS Texture Extension

Specification:
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
973482
function GLTFTextureDDSExtension() {

		if ( ! THREE.DDSLoader ) {

			throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );

		}

		this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
		this.ddsLoader = new THREE.DDSLoader();

	}
443937
def dd2dms(dd):
    
    n = dd < 0
    dd = abs(dd)
    m,s = divmod(dd*3600,60)
    d,m = divmod(m,60)
    if n:
        d = -d
    return d,m,s
772798
function getter_THREE_SpriteMaterial(inst) {
	return [
		inst.name,
		inst.side,
		inst.opacity,
		inst.blending,
		inst.blendSrc,
		inst.blendDst,
		inst.blendEquation,
		inst.depthFunc,
		inst.polygonOffsetFactor,
		inst.polygonOffsetUnits,
		inst.alphaTest,
		inst.overdraw,
		inst.blendSrcAlpha,
		inst.blendDstAlpha,
		inst.blendEquationAlpha,
		inst.transparent,
		inst.depthTest,
		inst.depthWrite,
		inst.colorWrite,
		inst.polygonOffset,
		inst.visible,
		inst.precision,
		inst.color,
		inst.map,
		inst.rotation,
		inst.fog];
}
1179532
public static void checkDepthRenderableTexture2D(
    final JCGLTextureFormat t)
    throws JCGLExceptionFormatError
  {
    if (!isDepthRenderable(t)) {
      final String m = String.format(
        "Format %s is not depth-renderable for 2D textures", t);
      assert m != null;
      throw new JCGLExceptionFormatError(m);
    }
  }
500253
function LGraphTextureScaleOffset() {
            this.addInput("in", "Texture");
            this.addInput("scale", "vec2");
            this.addInput("offset", "vec2");
            this.addOutput("out", "Texture");
            this.properties = {
                offset: vec2.fromValues(0, 0),
                scale: vec2.fromValues(1, 1),
                precision: LGraphTexture.DEFAULT
            };
        }
1374781
def texture_formats(self):
        """"""
        info = self._get_renderer_info()
        return {PixelFormat(info.texture_formats[i]) for i in range(info.num_texture_formats)}
643641
def ddtodms(self, dd):
        """"""
        negative = dd < 0
        dd = abs(dd)
        minutes,seconds = divmod(dd*3600,60)
        degrees,minutes = divmod(minutes,60)
        if negative:
            if degrees > 0:
                degrees = -degrees
            elif minutes > 0:
                minutes = -minutes
            else:
                seconds = -seconds
        return (degrees,minutes,seconds)
776846
function(unit) {
    gl.activeTexture(gl.TEXTURE0 + (unit || 0));
    gl.bindTexture(gl.TEXTURE_2D, null);
  }
158225
def access(self):
        """"""
        access = ffi.new('int *')
        check_int_err(lib.SDL_QueryTexture(self._ptr, ffi.NULL, access, ffi.NULL, ffi.NULL))
        return TextureAccess(access[0])
1057562
function RGBSplitFilter()
{
    core.AbstractFilter.call(this,
        // vertex shader
        null,
        // fragment shader
        fs.readFileSync(__dirname + '/rgbSplit.frag', 'utf8'),
        // custom uniforms
        {
            red:        { type: 'v2', value: { x: 20, y: 20 } },
            green:      { type: 'v2', value: { x: -20, y: 20 } },
            blue:       { type: 'v2', value: { x: 20, y: -20 } },
            dimensions: { type: '4fv', value: [0, 0, 0, 0] }
        }
    );
}
607430
function dsTextureConfig( gl , stencil ){
  if( stencil ){
    // DEPTH_STENCIL | DEPTH24_STENCIL8 | UNSIGNED_INT_24_8_WEBGL
    return {format: 0x84F9, type : 0x84FA, internal : gl.DEPTH24_STENCIL8 };
  } 
  // DEPTH_COMPONENT | DEPTH_COMPONENT24 | UNSIGNED_INT
  return {format: 0x1902, type : 0x1405, internal : gl.DEPTH_COMPONENT24 };
}
575004
def _sprite_map(g, **kwargs):
    
    g = StringValue(g).value

    if not Image:
        raise Exception("Images manipulation require PIL")

    if g in sprite_maps:
        sprite_maps[glob]['*'] = datetime.datetime.now()
    elif '..' not in g:  # Protect against going to prohibited places...
        vertical = (kwargs.get('direction', 'vertical') == 'vertical')
        offset_x = NumberValue(kwargs.get('offset_x', 0))
        offset_y = NumberValue(kwargs.get('offset_y', 0))
        repeat = StringValue(kwargs.get('repeat', 'no-repeat'))
        position = NumberValue(kwargs.get('position', 0))
        dst_color = kwargs.get('dst_color')
        src_color = kwargs.get('src_color')
        if position and position > -1 and position < 1:
            position.units = {'%': _units_weights.get('%', 1), '_': '%'}
        spacing = kwargs.get('spacing', 0)
        if isinstance(spacing, ListValue):
            spacing = [int(NumberValue(v).value) for n, v in spacing.items()]
        else:
            spacing = [int(NumberValue(spacing).value)]
        spacing = (spacing * 4)[:4]

        if callable(STATIC_ROOT):
            rfiles = files = sorted(STATIC_ROOT(g))
        else:
            glob_path = os.path.join(STATIC_ROOT, g)
            files = glob.glob(glob_path)
            files = sorted((f, None) for f in files)
            rfiles = [(f[len(STATIC_ROOT):], s) for f, s in files]

        if not files:
            log.error("Nothing found at '%s'", glob_path)
            return StringValue(None)

        times = []
        for file, storage in files:
            try:
                d_obj = storage.modified_time(file)
                times.append(int(time.mktime(d_obj.timetuple())))
            except:
                times.append(int(os.path.getmtime(file)))

        map_name = os.path.normpath(
            os.path.dirname(g)).replace('\\', '_').replace('/', '_')
        key = list(zip(*files)[0]) + times + [repr(kwargs)]
        key = map_name + '-' + base64.urlsafe_b64encode(
            hashlib.md5(repr(key)).digest()).rstrip('=').replace('-', '_')
        asset_file = key + '.png'
        asset_path = os.path.join(ASSETS_ROOT, asset_file)

        if os.path.exists(asset_path + '.cache'):
            asset, map, sizes = pickle.load(open(asset_path + '.cache'))
            sprite_maps[asset] = map
        else:
            images = tuple(Image.open(storage.open(file)) if storage is not None else Image.open(file) for file, storage in files)
            names = tuple(os.path.splitext(
                os.path.basename(file))[0] for file, storage in files)
            positions = []
            spacings = []
            tot_spacings = []
            for name in names:
                name = name.replace('-', '_')
                _position = kwargs.get(name + '_position')
                if _position is None:
                    _position = position
                else:
                    _position = NumberValue(_position)
                    if _position and _position > -1 and _position < 1:
                        _position.units = {'%':
                                           _units_weights.get('%', 1), '_': '%'}
                positions.append(_position)
                _spacing = kwargs.get(name + '_spacing')
                if _spacing is None:
                    _spacing = spacing
                else:
                    if isinstance(_spacing, ListValue):
                        _spacing = [int(NumberValue(
                            v).value) for n, v in _spacing.items()]
                    else:
                        _spacing = [int(NumberValue(_spacing).value)]
                    _spacing = (_spacing * 4)[:4]
                spacings.append(_spacing)
                if _position and _position.unit != '%':
                    if vertical:
                        if _position > 0:
                            tot_spacings.append((_spacing[0], _spacing[
                                1], _spacing[2], _spacing[3] + _position))
                    else:
                        if _position > 0:
                            tot_spacings.append((_spacing[0] + _position,
                                                 _spacing[1], _spacing[2], _spacing[3]))
                else:
                    tot_spacings.append(_spacing)
            sizes = tuple(image.size for image in images)

            _spacings = zip(*tot_spacings)
            if vertical:
                width = max(
                    zip(*sizes)[0]) + max(_spacings[1]) + max(_spacings[3])
                height = sum(
                    zip(*sizes)[1]) + sum(_spacings[0]) + sum(_spacings[2])
            else:
                width = sum(
                    zip(*sizes)[0]) + sum(_spacings[1]) + sum(_spacings[3])
                height = max(
                    zip(*sizes)[1]) + max(_spacings[0]) + max(_spacings[2])

            new_image = Image.new(
                mode='RGBA',
                size=(width, height),
                color=(0, 0, 0, 0)
            )

            offsets_x = []
            offsets_y = []
            offset = 0
            for i, image in enumerate(images):
                spacing = spacings[i]
                position = positions[i]
                if vertical:
                    if position and position.unit == '%':
                        x = width * position.value - \
                            (spacing[3] + sizes[i][1] + spacing[1])
                    elif position.value < 0:
                        x = width + position.value - \
                            (spacing[3] + sizes[i][1] + spacing[1])
                    else:
                        x = position.value
                    offset += spacing[0]
                    new_image.paste(image, (int(x + spacing[3]), offset))
                    offsets_x.append(x)
                    offsets_y.append(offset - spacing[0])
                    offset += sizes[i][1] + spacing[2]
                else:
                    if position and position.unit == '%':
                        y = height * position.value - \
                            (spacing[0] + sizes[i][1] + spacing[2])
                    elif position.value < 0:
                        y = height + position.value - \
                            (spacing[0] + sizes[i][1] + spacing[2])
                    else:
                        y = position.value
                    offset += spacing[3]
                    new_image.paste(image, (offset, int(y + spacing[0])))
                    offsets_x.append(offset - spacing[3])
                    offsets_y.append(y)
                    offset += sizes[i][0] + spacing[1]

            if dst_color:
                src_color = ColorValue(
                    src_color).value[:3] if src_color else (0, 0, 0)
                dst_color = list(ColorValue(dst_color).value[:3])
                pixdata = new_image.load()
                for y in xrange(new_image.size[1]):
                    for x in xrange(new_image.size[0]):
                        if pixdata[x, y][:3] == src_color:
                            pixdata[x,
                                    y] = tuple(dst_color + [pixdata[x, y][3]])

            try:
                new_image.save(asset_path)
            except IOError:
                log.exception("Error while saving image")
            filetime = int(time.mktime(datetime.datetime.now().timetuple()))

            url = '%s%s?_=%s' % (ASSETS_URL, asset_file, filetime)
            asset = 'url("%s") %s' % (escape(url), repeat)
            # Use the sorted list to remove older elements (keep only 500
            # objects):
            if len(sprite_maps) > 1000:
                for a in sorted(sprite_maps, key=lambda a: sprite_maps[a]['*'], reverse=True)[500:]:
                    del sprite_maps[a]
            # Add the new object:
            map = dict(zip(names, zip(sizes, rfiles, offsets_x, offsets_y)))
            map['*'] = datetime.datetime.now()
            map['*f*'] = asset_file
            map['*k*'] = key
            map['*n*'] = map_name
            map['*t*'] = filetime
            pickle.dump((asset, map, zip(files, sizes)), open(
                asset_path + '.cache', 'w'))
            sprite_maps[asset] = map
        for file, size in sizes:
            sprite_images[file] = size
    ret = StringValue(asset)
    return ret
732099
function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {

		var glFormat = utils.convert( renderTarget.texture.format );
		var glType = utils.convert( renderTarget.texture.type );
		var glInternalFormat = getInternalFormat( glFormat, glType );
		state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
		_gl.bindFramebuffer( 36160, framebuffer );
		_gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( 36160, null );

	}
198211
def capture
      Gl.glBindTexture Gl::GL_TEXTURE_2D, id
      Gl.glCopyTexImage2D Gl::GL_TEXTURE_2D, 0, Gl::GL_RGBA8, 0, 0, width, height, 0
      self
    end
231129
function getTextureFromData(gl, data, opts) {
  if (data instanceof Texture2D) {
    return data;
  }
  return new Texture2D(gl, Object.assign({data}, opts));
}
114034
def mem_ds(res, extent, srs=None, dtype=gdal.GDT_Float32):
    
    #These round down to int
    #dst_ns = int((extent[2] - extent[0])/res)
    #dst_nl = int((extent[3] - extent[1])/res)
    #This should pad by 1 pixel, but not if extent and res were calculated together to give whole int
    dst_ns = int((extent[2] - extent[0])/res + 0.99)
    dst_nl = int((extent[3] - extent[1])/res + 0.99)
    m_ds = gdal.GetDriverByName('MEM').Create('', dst_ns, dst_nl, 1, dtype)
    m_gt = [extent[0], res, 0, extent[3], 0, -res]
    m_ds.SetGeoTransform(m_gt)
    if srs is not None:
        m_ds.SetProjection(srs.ExportToWkt())
    return m_ds
777335
function (texture) {
        var pixels = texture.pixels;
        var width = texture.width;
        var height = texture.height;

        function fetchPixel(x, y, rg) {
            x = Math.max(Math.min(x, width - 1), 0);
            y = Math.max(Math.min(y, height - 1), 0);
            var idx = (y * (width - 1) + x) * 4;
            if (pixels[idx + 3] === 0) {
                return false;
            }
            rg[0] = pixels[idx];
            rg[1] = pixels[idx + 1];
            return true;
        }

        function addPixel(a, b, out) {
            out[0] = a[0] + b[0];
            out[1] = a[1] + b[1];
        }

        var center = [], left = [], right = [], top = [], bottom = [];
        var weight = 0;
        for (var y = 0; y < height; y++) {
            for (var x = 0; x < width; x++) {
                var idx = (y * (width - 1) + x) * 4;
                if (pixels[idx + 3] === 0) {
                    weight = center[0] = center[1] = 0;
                    if (fetchPixel(x - 1, y, left)) {
                        weight++; addPixel(left, center, center);
                    }
                    if (fetchPixel(x + 1, y, right)) {
                        weight++; addPixel(right, center, center);
                    }
                    if (fetchPixel(x, y - 1, top)) {
                        weight++; addPixel(top, center, center);
                    }
                    if (fetchPixel(x, y + 1, bottom)) {
                        weight++; addPixel(bottom, center, center);
                    }
                    center[0] /= weight;
                    center[1] /= weight;
                    // PENDING If overwrite. bilinear interpolation.
                    pixels[idx] = center[0];
                    pixels[idx + 1] = center[1];
                }
                pixels[idx + 3] = 1;
            }
        }
    }