GithubHelp home page GithubHelp logo

pixijs / pixi-compressed-textures Goto Github PK

View Code? Open in Web Editor NEW
92.0 11.0 24.0 1.74 MB

Compressed textures and retina support for pixijs. Loader can choose textures depends on platform and rendering mode.

License: MIT License

JavaScript 1.90% TypeScript 98.10%

pixi-compressed-textures's Introduction

pixi-compressed-textures

Compressed textures and retina support for pixi v5. Loader can choose textures depends on platform and rendering mode.

You can use previous version with PixiJS v4 - v4.x branch npm version 1.1.8

Supports DDS (S3TC DXT1-3-5, ATC, ATCA/ATC explicit, ATCI/ATC interpolated), PVR (PVRTC, ETC1, S3TC DXT1-3-5, PVRTC 2-4bpp RGB-RGBA), ASTC (all blocks size) 2D LDR preset

Supports advanced DXT compression crunch

Minimum demo

Pretty easy to hack parser into your loader.

let loader = new PIXI.Loader();
loader.add('building', 'building.dds');
loader.load(function(loader, resources) {
    let sprite = new PIXI.Sprite(resources['building'].texture);
});

However if somehow pixi-compressed-textures was initialized after creation of loader, add a ImageParser to it:

loader.use(PIXI.compressedTextures.ImageParser.use);

Full example

If your app has no detection of supported formats it is not ready for production.

This example shows how to handle multiple resolutions and multiple image formats for single images and for atlases.

const app = new PIXI.Application({ resolution: window.devicePixelRatio || 1 });
document.body.appendChild(app.view);

// use empty array if you dont want to use detect feature
const extensions = PIXI.compressedTextures.detectExtensions(app.renderer);
const loader = app.loader;

loader.pre(PIXI.compressedTextures.extensionChooser(extensions));
// use @2x texture if resolution is 2, use dds format if its windows
const textureOptions1 = { metadata: { choice: ['@2x.png', '.dds', '@2x.dds'] } };
// use dds format if its windows but dont care for retina
const textureOptions2 = { metadata: { choice: ['.dds'] } };
// while loading atlas, choose resolution for atlas and choose format for image
const atlasOptions = { metadata: { choice: ['@2x.json', '@1x.json'], imageMetadata: { choice: ['.dds'] } } };

loader.add('building1', 'examples/assets/pixi-compressed-textures/building1.png', textureOptions1)
    .add('building2', 'examples/assets/pixi-compressed-textures/building2.png', textureOptions2)
    // will be swapped to @1xб because @1x is always detected and we've specified it in atlasOptions
    // look up `detectExtensions` code, params and output
    .add('atlas1', 'examples/assets/pixi-compressed-textures/buildings.json', atlasOptions)
    .load((loaderInstance, resources) => {
        const spr1 = new PIXI.Sprite(resources.building1.texture);
        const spr2 = new PIXI.Sprite(resources.building2.texture);
        const spr3 = PIXI.Sprite.from('goldmine_10_5.png');
        const spr4 = PIXI.Sprite.from('wind_extractor_10.png');
        spr1.y = spr3.y = 150;
        spr2.y = spr4.y = 350;
        spr1.x = spr2.x = 250;
        spr3.x = spr4.x = 450;
        app.stage.addChild(spr1, spr2, spr3, spr4);
    });

Fixing it in cache

To fix url names in cache your have to add one extra loader plugin: extensionFixer.

It should be added after all other image-related plugins.

That way in the example above, image will appear under name examples/assets/pixi-compressed-textures/building1.png and not examples/assets/pixi-compressed-textures/building1.dds.

loader.use(PIXI.compressedTextures.ExtensionFixer.use);

Using crunch

To use crunch you have to manually add lib/crn_decomp.js to your build.

We cant help you with adding it in webpack or browserify or angular, its your job.

Using BASIS

Basis format disabled by default and require transcoder. Transcoder may be got from: https://github.com/BinomialLLC/basis_universal/tree/master/webgl/transcoder

This lib can't include transcoder because transcoder use wasm and is heavy (greater then 300kb) at the moment.

For using BASIS, you can bind transcoder to load, it register .basis to loader automatically.

Simple way:

BASIS().then(Module => {

    const { BasisFile, initializeBasis } = Module;
    
    // run module
    initializeBasis();
    
    // init for getting `compressedExtensions`
    app.renderer.texture.initCompressed();

    // get supported extensions
    const supp = app.renderer.texture.compressedExtensions;
    
    // bind transcoder to loader with specific extensions
    PIXI.compressedTextures.BASISLoader.bindTranscoder(BasisFile, supp);
});

Worker:

Because BASIS is synchronous then it transcode a RGB texture of 1024x1024 pixels ~30ms in main thread. Using it in Worker is the rightest way.

WorkedBASISLoader uses workers for transcoding. There are few API for it:

WorkedBASISLoader.loadAndRunTranscoder(options: 
    {
        path: string, // path to worker source `basis_transcoder.js` and `basis_transcoder.wasm`
        ext: any, //extensions from `app.renderer.texture.compressedExtensions`
        threads: number //workers count
    }) : Promise<void>
WorkedBASISLoader.runTranscoder(options: 
    {
        jsSource: string, // text of jsFile
        wasmSource: ArrayBuffer, // buffer of wasm file
        threads: number,
        ext: any
    }): Promise<void>`

Note: wasmSource is transferred to workers for faster initialisation.

You must call 1 or 2 before loading of .basis files .

Ex:

app.renderer.texture.initCompressed();

// get supported extensions
const ext = app.renderer.texture.compressedExtensions;
const WBL = PIXI.compressedTextures.WorkedBASISLoader;
const pathToTranscoder = "/path/to/trancoder";

WBL.loadAndRunTranscoder({path : pathToTranscoder, ext: ext, threads : 2})
.then(() => {
    // BASIS transcoder is loaded, you can start loading .basis files
});

Note about atlases

PIXI recognizes resolution of atlas by suffix (@1x, @2x, ... )

If you dont specify that, resolution of the atlas will be taken from "meta.scale" which in our example is 1 and 0.5 instead of 2 and 1. It will shrink everything!

Browserify / WebPack / Angular

If you use browserify or Webpack you can use pixi-textures like this:

import * as PIXI from "pixi.js';
window.PIXI = PIXI;
import "pixi-compressed-textures"; //or require("pixi-compressed-textures")
// textureParser will form list of allowed extensions based on renderer.
loader.pre(PIXI.compressedTextures.extensionChooser(PIXI.compressedTextures.detectExtensions(renderer)));

Building

You will need to have node

Then you can install dependencies and build:

npm i
npm run build

That will output the built distributables to ./dist.

pixi-compressed-textures's People

Contributors

adasek avatar andrewstart avatar elizavetta avatar exponenta avatar gatsinski avatar inspector-ambitious avatar ivanpopelyshev avatar mbittarelli-jibo avatar mems avatar nikolayh avatar staff0rd avatar zprodev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pixi-compressed-textures's Issues

Not working with PIXI v5.1.1

Problem starts @ line

CompressedTextureManager.prototype = Object.create(WebGLManager.prototype);

Error : WebGLManager undefined

Pixi v6 Deprecated methods

I'd be happy to submit a PR if that's the case.

PIXI.systems.Resource --> PIXI.ResourceDeprecated
PIXI.resources.TextureSystem --> PIXI.TextureSystemDeprecated

image

KTX support?

Using Babylon.js where I can use KTX. Is there any thought about including this in Pixi.js?

pixi-compressed-textures TypeScript Definition

Is it possible to get somewhere, somehow typescript definition to pixi-compressed-texuters (d.ts)?
Maybe someone already made it?
Thanks for your attention.
I’m looking forward to your reply.

404 not found - demo example 3 console errors

Errors on the console:

There is no futher information.

Original is in the TypeScript Project: #158 but I believe it is the implementation.

pixi-compressed-textures.js:100 Uncaught `ReferenceError:` src is not defined
at CompressedImage.loadFromArrayBuffer (pixi-compressed-textures.js:100)
at pixi-compressed-textures.js:514
at MiniSignal.dispatch (mini-signals.js:93)
at Resource.complete (Resource.js:364)
at Resource.abort (Resource.js:402)
at Resource._onError (Resource.js:673)

/examples/required/assets/compressed/buildings.json Failed to load resource: the server responded with a status of 404 (Not Found)

pixi-compressed-textures.js:100 Uncaught ReferenceError: src is not defined
at CompressedImage.loadFromArrayBuffer (pixi-compressed-textures.js:100)
at pixi-compressed-textures.js:514
at MiniSignal.dispatch (mini-signals.js:93)
at Resource.complete (Resource.js:364)
at Resource.abort (Resource.js:402)
at Resource._onError (Resource.js:673)

Unable to load etc1 (pvr) texture

I'm trying to use compressed textures in mobile application. and i'm unable to load etc1 texture, i'm getting those warnings and a black square:
WebGL: INVALID_ENUM: compressedTexImage2D: invalid format
CompressedImage.generateWebGLTexture @ pixi-compressed-textures.js:22303
[.Offscreen-For-WebGL-0xdd8fe800]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering.

this is the code i'm using:

var extensions = PIXI.compressedTextures.detectExtensions(app.renderer);
var loader = new PIXI.loaders.Loader();
loader.pre(PIXI.compressedTextures.imageParser());
loader.add('shannon', 'data/shannon-etc1.pvr');
loader.load(function(loader, resources) {
    var sprite = new PIXI.Sprite(resources['shannon'].texture);
    app.stage.addChild(sprite);
});

and the pvr file is taken from this site, witch shows pvr (etc1) just fine on my tablet

Documentation enhancements

Thanks for this plugin.
I found few things didn't mentioned in the documentation.

  1. The order is important inside metadata.choice (at least for the choosing resolution).
    So it is matter to have it in a right order. From less resolution to highest.
    Correct:
    metadata: {
    choice: ["@1x.json", "@2x.json"]
    }
    Incorrect:
    metadata: {
    choice: ["@2x.json", "@1x.json"]
    }
    in a second way it will load 1x for resolution 2.
  2. If you are using detectExtensions method, you have to use suffix "@1x" ("@2x" etc), you cannot use "@x1", "@x2" etc.

premultipliedAlpha not work

gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); not work for gl.compressedTexImage2D(),is there something we can do? or we can only use premultipliedAlpha texture make by texturetools?

how can i make a line clickable?

let shapes = new PIXI.Graphics(); shapes.lineStyle(1 / scale, 0x4169e1, 1); shapes.moveTo(Apoints[0], Apoints[1]); shapes.lineTo(Bpoints[0], Bpoints[1]); shapes.isRobot = true; app.stage.addChild(shapes); shapes.on("pointerdown", function (e) { alert(111) });
i tried to make a line clickable, but failed, help!

Module not found: Error: Can't resolve 'fs'

I've installed this package via npm (npm install --save pixi-compressed-textures) and tried to include it in my project as per the suggested steps for Browserify (I'm actually using webpack.)

I've included it as follows:

import * as PIXI from 'pixi.js';
import TEX from 'pixi-compressed-textures';

I'm getting the following error:

ERROR in ./node_modules/pixi-compressed-textures/lib/crn_decomp.js
Module not found: Error: Can't resolve 'fs' in '/path/to/node_modules/pixi-compressed-textures/lib'

Is this plugin intended to be run in the browser? Am I missing something?

Any help would be appreciated. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.