Commit c9dc3066 authored by wjf's avatar wjf

l

parent 9272db0e
...@@ -74,6 +74,13 @@ export function getRenderStyle() { ...@@ -74,6 +74,13 @@ export function getRenderStyle() {
return renderStyle return renderStyle
} }
/**
* 获取渲染canvas
*/
export function getRenderCanvas(){
return _canvas
}
/** /**
* 清空渲染上下文 * 清空渲染上下文
*/ */
......
...@@ -2,18 +2,18 @@ ...@@ -2,18 +2,18 @@
* Created by rockyl on 2018/11/5. * Created by rockyl on 2018/11/5.
*/ */
export {ScillaComponent} from "./ScillaComponent"; export { ScillaComponent } from "./ScillaComponent";
export {Entity} from './Entity' export { Entity } from './Entity'
export {Scene} from './Scene' export { Scene } from './Scene'
export {ScillaEvent} from './ScillaEvent' export { ScillaEvent } from './ScillaEvent'
// export {getContext, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut, ScaleMode} from './context/RenderContext'; // export {getContext, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut, ScaleMode} from './context/RenderContext';
export { getContext, getRenderStyle, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut } from './context/RenderContextGL'; export { getContext, getRenderStyle, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut, ScaleMode } from './context/RenderContextGL';
export {pagePosToCanvasPos, canvasPosToPagePos} from './context/InteractContext'; export { pagePosToCanvasPos, canvasPosToPagePos } from './context/InteractContext';
export * from './manager' export * from './manager'
export {default as Texture, createTexture} from './Texture' export { default as Texture, createTexture } from './Texture'
export * from './Sheet' export * from './Sheet'
export * from './FrameAnimation' export * from './FrameAnimation'
//导出webgl渲染器 //导出webgl渲染器
export {default as WebGLRenderer} from "./webgl/WebGLRenderer"; export { default as WebGLRenderer } from "./webgl/WebGLRenderer";
\ No newline at end of file \ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
/** /**
* Base for a common object renderer that can be used as a system renderer plugin. * Base for a common object renderer that can be used as a system renderer plugin.
* * 渲染器插件的基类
* @class * @class
*/ */
export default class ObjectRenderer { export default class ObjectRenderer {
......
This diff is collapsed.
...@@ -8,7 +8,7 @@ const BLEND_FUNC = 4; ...@@ -8,7 +8,7 @@ const BLEND_FUNC = 4;
/** /**
* A WebGL state machines * A WebGL state machines
* * 设置状态机状态管理类
* @class * @class
*/ */
export default class WebGLState { export default class WebGLState {
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @type {number} * @type {number}
*/ */
export const PI_2 = Math.PI * 2; export const PI_2 = Math.PI * 2;
...@@ -13,7 +12,6 @@ export const PI_2 = Math.PI * 2; ...@@ -13,7 +12,6 @@ export const PI_2 = Math.PI * 2;
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @type {number} * @type {number}
*/ */
export const RAD_TO_DEG = 180 / Math.PI; export const RAD_TO_DEG = 180 / Math.PI;
...@@ -23,7 +21,6 @@ export const RAD_TO_DEG = 180 / Math.PI; ...@@ -23,7 +21,6 @@ export const RAD_TO_DEG = 180 / Math.PI;
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @type {number} * @type {number}
*/ */
export const DEG_TO_RAD = Math.PI / 180; export const DEG_TO_RAD = Math.PI / 180;
...@@ -33,7 +30,7 @@ export const DEG_TO_RAD = Math.PI / 180; ...@@ -33,7 +30,7 @@ export const DEG_TO_RAD = Math.PI / 180;
* *
* @static * @static
* @constant * @constant
* @memberof PIXI * @memberof
* @name RENDERER_TYPE * @name RENDERER_TYPE
* @type {object} * @type {object}
* @property {number} UNKNOWN - Unknown render type. * @property {number} UNKNOWN - Unknown render type.
...@@ -54,7 +51,6 @@ export const RENDERER_TYPE = { ...@@ -54,7 +51,6 @@ export const RENDERER_TYPE = {
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @name BLEND_MODES * @name BLEND_MODES
* @type {object} * @type {object}
* @property {number} NORMAL * @property {number} NORMAL
...@@ -104,7 +100,6 @@ export const BLEND_MODES = { ...@@ -104,7 +100,6 @@ export const BLEND_MODES = {
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @name DRAW_MODES * @name DRAW_MODES
* @type {object} * @type {object}
* @property {number} POINTS * @property {number} POINTS
...@@ -133,7 +128,6 @@ export const DRAW_MODES = { ...@@ -133,7 +128,6 @@ export const DRAW_MODES = {
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @name SCALE_MODES * @name SCALE_MODES
* @type {object} * @type {object}
* @property {number} LINEAR Smooth scaling * @property {number} LINEAR Smooth scaling
...@@ -157,7 +151,6 @@ export const SCALE_MODES = { ...@@ -157,7 +151,6 @@ export const SCALE_MODES = {
* @static * @static
* @constant * @constant
* @name WRAP_MODES * @name WRAP_MODES
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} CLAMP - The textures uvs are clamped * @property {number} CLAMP - The textures uvs are clamped
* @property {number} REPEAT - The texture uvs tile and repeat * @property {number} REPEAT - The texture uvs tile and repeat
...@@ -172,7 +165,7 @@ export const WRAP_MODES = { ...@@ -172,7 +165,7 @@ export const WRAP_MODES = {
/** /**
* The gc modes that are supported by * The gc modes that are supported by
* *
* The {@link settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO * The {@link settings.GC_MODE} Garbage Collection mode for JS textures is AUTO
* If set to GC_MODE, the renderer will occasionally check textures usage. If they are not * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
* used for a specified period of time they will be removed from the GPU. They will of course * used for a specified period of time they will be removed from the GPU. They will of course
* be uploaded again when they are required. This is a silent behind the scenes process that * be uploaded again when they are required. This is a silent behind the scenes process that
...@@ -184,7 +177,6 @@ export const WRAP_MODES = { ...@@ -184,7 +177,6 @@ export const WRAP_MODES = {
* @static * @static
* @constant * @constant
* @name GC_MODES * @name GC_MODES
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} AUTO - Garbage collection will happen periodically automatically * @property {number} AUTO - Garbage collection will happen periodically automatically
* @property {number} MANUAL - Garbage collection will need to be called manually * @property {number} MANUAL - Garbage collection will need to be called manually
...@@ -199,7 +191,6 @@ export const GC_MODES = { ...@@ -199,7 +191,6 @@ export const GC_MODES = {
* *
* @static * @static
* @constant * @constant
* @memberof PIXI
* @type {RegExp|string} * @type {RegExp|string}
* @example `image.png` * @example `image.png`
*/ */
...@@ -212,7 +203,6 @@ export const URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; ...@@ -212,7 +203,6 @@ export const URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i;
* @static * @static
* @constant * @constant
* @name DATA_URI * @name DATA_URI
* @memberof PIXI
* @type {RegExp|string} * @type {RegExp|string}
* @example data:image/png;base64 * @example data:image/png;base64
*/ */
...@@ -224,7 +214,6 @@ export const DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+)) ...@@ -224,7 +214,6 @@ export const DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))
* @static * @static
* @constant * @constant
* @name SVG_SIZE * @name SVG_SIZE
* @memberof PIXI
* @type {RegExp|string} * @type {RegExp|string}
* @example <svg width="100" height="100"></svg> * @example <svg width="100" height="100"></svg>
*/ */
...@@ -236,7 +225,6 @@ export const SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px) ...@@ -236,7 +225,6 @@ export const SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)
* @static * @static
* @constant * @constant
* @name SHAPES * @name SHAPES
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} POLY Polygon * @property {number} POLY Polygon
* @property {number} RECT Rectangle * @property {number} RECT Rectangle
...@@ -258,7 +246,6 @@ export const SHAPES = { ...@@ -258,7 +246,6 @@ export const SHAPES = {
* @static * @static
* @constant * @constant
* @name PRECISION * @name PRECISION
* @memberof PIXI
* @type {object} * @type {object}
* @property {string} LOW='lowp' * @property {string} LOW='lowp'
* @property {string} MEDIUM='mediump' * @property {string} MEDIUM='mediump'
...@@ -276,7 +263,6 @@ export const PRECISION = { ...@@ -276,7 +263,6 @@ export const PRECISION = {
* @static * @static
* @constant * @constant
* @name TRANSFORM_MODE * @name TRANSFORM_MODE
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} STATIC * @property {number} STATIC
* @property {number} DYNAMIC * @property {number} DYNAMIC
...@@ -292,7 +278,6 @@ export const TRANSFORM_MODE = { ...@@ -292,7 +278,6 @@ export const TRANSFORM_MODE = {
* @static * @static
* @constant * @constant
* @name TEXT_GRADIENT * @name TEXT_GRADIENT
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} LINEAR_VERTICAL Vertical gradient * @property {number} LINEAR_VERTICAL Vertical gradient
* @property {number} LINEAR_HORIZONTAL Linear gradient * @property {number} LINEAR_HORIZONTAL Linear gradient
...@@ -303,14 +288,13 @@ export const TEXT_GRADIENT = { ...@@ -303,14 +288,13 @@ export const TEXT_GRADIENT = {
}; };
/** /**
* Represents the update priorities used by internal PIXI classes when registered with * Represents the update priorities used by internal classes when registered with
* the {@link ticker.Ticker} object. Higher priority items are updated first and lower * the {@link ticker.Ticker} object. Higher priority items are updated first and lower
* priority items, such as render, should go later. * priority items, such as render, should go later.
* *
* @static * @static
* @constant * @constant
* @name UPDATE_PRIORITY * @name UPDATE_PRIORITY
* @memberof PIXI
* @type {object} * @type {object}
* @property {number} INTERACTION=50 Highest priority, used for {@link interaction.InteractionManager} * @property {number} INTERACTION=50 Highest priority, used for {@link interaction.InteractionManager}
* @property {number} HIGH=25 High priority updating, {@link VideoBaseTexture} and {@link extras.AnimatedSprite} * @property {number} HIGH=25 High priority updating, {@link VideoBaseTexture} and {@link extras.AnimatedSprite}
......
/**
* 批处理用buffer数据
*/
export class BatchBuffer { export class BatchBuffer {
/**
* 顶点数据,类型化数组
* https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
*/
vertices: ArrayBuffer; vertices: ArrayBuffer;
/**
* 顶点的位置信息视图,浮点数
* View on the vertices as a Float32Array for positions
*/
float32View: Float32Array; float32View: Float32Array;
/**
* uv及颜色值的信息视图,整数
* View on the vertices as a Uint32Array for uvs
*/
uint32View: Uint32Array; uint32View: Uint32Array;
/**
* positions,uvs,colors暂时不用做单独记录
*/
positions: any; positions: any;
uvs: any; uvs: any;
colors: any; colors: any;
/** /**
* @param {number} size - The size of the buffer in bytes. * @param {number} size - The size of the buffer in bytes.
*/ */
constructor(size) { constructor(size: number) {
this.vertices = new ArrayBuffer(size); this.vertices = new ArrayBuffer(size);
/**
* View on the vertices as a Float32Array for positions
*
* @member {Float32Array}
*/
this.float32View = new Float32Array(this.vertices); this.float32View = new Float32Array(this.vertices);
/**
* View on the vertices as a Uint32Array for uvs
*
* @member {Float32Array}
*/
this.uint32View = new Uint32Array(this.vertices); this.uint32View = new Uint32Array(this.vertices);
} }
......
var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0);
/** /**
* Helper class to create a webGL buffer * 用于创建webGL buffer,顶点和索引专用
*
* @class * @class
* @memberof glCore * @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL rendering context * @param gl {WebGLRenderingContext} The current WebGL rendering context
...@@ -11,47 +10,56 @@ var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); ...@@ -11,47 +10,56 @@ var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0);
* @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/ */
export class GLBuffer { export class GLBuffer {
/**
* 当前上下文
* @member {WebGLRenderingContext}
*/
gl: any; gl: any;
/**
* The WebGL buffer, created upon instantiation
* @member {WebGLBuffer}
*/
buffer: any; buffer: any;
/**
* buffer类型
* 顶点或索引
* @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER}
*/
type: any; type: any;
/**
* The draw type of the buffer
* 绘制类型
* gl.STATIC_DRAW: 缓冲区的内容可能经常使用,而不会经常更改
* gl.DYNAMIC_DRAW: 缓冲区的内容可能经常被使用,并且经常更改
* gl.STREAM_DRAW: 缓冲区的内容可能不会经常使用,且不会经常更改
* @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/
drawType: any; drawType: any;
data: ArrayBuffer;
/**
* The data in the buffer, as a typed array
* 用来表示通用的、固定长度的原始二进制数据缓冲区。ArrayBuffer 不能直接操作,
* 而是要通过类型数组对象或 DataView 对象来操作,
* 它们会将缓冲区中的数据表示为特定的格式,并通过这些格式来读写缓冲区的内容。
* @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
*/
data;
/**
* 更新ID
*/
_updateID: number; _updateID: number;
constructor(gl, type?, data?, drawType?) { constructor(gl, type?, data?, drawType?) {
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl; this.gl = gl;
/**
* The WebGL buffer, created upon instantiation
*
* @member {WebGLBuffer}
*/
this.buffer = gl.createBuffer(); this.buffer = gl.createBuffer();
/**
* The type of the buffer
*
* @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER}
*/
this.type = type || gl.ARRAY_BUFFER; this.type = type || gl.ARRAY_BUFFER;
/**
* The draw type of the buffer
*
* @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/
this.drawType = drawType || gl.STATIC_DRAW; this.drawType = drawType || gl.STATIC_DRAW;
/**
* The data in the buffer, as a typed array
*
* @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
*/
this.data = EMPTY_ARRAY_BUFFER; this.data = EMPTY_ARRAY_BUFFER;
if (data) { if (data) {
...@@ -62,12 +70,13 @@ export class GLBuffer { ...@@ -62,12 +70,13 @@ export class GLBuffer {
}; };
/** /**
* 上传数据
* Uploads the buffer to the GPU * Uploads the buffer to the GPU
* @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload
* @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract
* @param dontBind {Boolean} whether to bind the buffer before uploading it * @param dontBind {Boolean} whether to bind the buffer before uploading it 是否不绑定buffer
*/ */
public upload(data, offset?, dontBind?) { public upload(data, offset?:number, dontBind?:boolean) {
// todo - needed? // todo - needed?
if (!dontBind) this.bind(); if (!dontBind) this.bind();
...@@ -85,9 +94,11 @@ export class GLBuffer { ...@@ -85,9 +94,11 @@ export class GLBuffer {
this.data = data; this.data = data;
}; };
/** /**
* Binds the buffer * Binds the buffer
* * 状态机接下来使用的buffer
*
*/ */
public bind() { public bind() {
var gl = this.gl; var gl = this.gl;
...@@ -100,10 +111,22 @@ export class GLBuffer { ...@@ -100,10 +111,22 @@ export class GLBuffer {
public destroy = function () { public destroy = function () {
this.gl.deleteBuffer(this.buffer); this.gl.deleteBuffer(this.buffer);
}; };
/**
* 创建顶点缓存
* @param gl
* @param data
* @param drawType
*/
public static createVertexBuffer(gl, data?, drawType?) { public static createVertexBuffer(gl, data?, drawType?) {
return new GLBuffer(gl, gl.ARRAY_BUFFER, data, drawType); return new GLBuffer(gl, gl.ARRAY_BUFFER, data, drawType);
}; };
/**
* 创建索引缓存
* @param gl
* @param data
* @param drawType
*/
public static createIndexBuffer(gl, data?, drawType?) { public static createIndexBuffer(gl, data?, drawType?) {
return new GLBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); return new GLBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType);
}; };
......
...@@ -3,6 +3,7 @@ import { GLTexture } from './GLTexture'; ...@@ -3,6 +3,7 @@ import { GLTexture } from './GLTexture';
/** /**
* Helper class to create a webGL Framebuffer * Helper class to create a webGL Framebuffer
* 帧缓存,暂时不使用,renderTarget里用,主要用于滤镜处理
* *
* @class * @class
* @memberof glCore * @memberof glCore
......
...@@ -7,7 +7,7 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec ...@@ -7,7 +7,7 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec
/** /**
* Helper class to create a webGL Shader * Helper class to create a webGL Shader
* * 创建webgl shader用,里面主要用到attributes和uniforms
* @class * @class
* @memberof glCore * @memberof glCore
* @param gl {WebGLRenderingContext} * @param gl {WebGLRenderingContext}
...@@ -17,17 +17,42 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec ...@@ -17,17 +17,42 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec
* @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1}
*/ */
export class GLShader { export class GLShader {
gl: any; /**
program: any; * The current WebGL rendering context
* @member {WebGLRenderingContext}
*/
gl: WebGLRenderingContext;
/**
* The shader program
* @member {WebGLProgram}
*/
program: WebGLProgram;
/**
* The attributes of the shader as an object containing the following properties
* {
* type,
* size,
* location,
* pointer
* }
* @member {Object}
*/
attributes: {}; attributes: {};
uniformData: {}; uniformData: {};
/**
* The uniforms of the shader as an object containing the following properties
* {
* gl,
* data
* }
* @member {Object}
*/
uniforms: { data: {}; }; uniforms: { data: {}; };
constructor(gl, vertexSrc, fragmentSrc, precision?, attributeLocations?) {
/** constructor(gl:WebGLRenderingContext, vertexSrc:string, fragmentSrc:string, precision?:string, attributeLocations?) {
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl; this.gl = gl;
if (precision) { if (precision) {
...@@ -35,44 +60,21 @@ export class GLShader { ...@@ -35,44 +60,21 @@ export class GLShader {
fragmentSrc = setPrecision(fragmentSrc, precision); fragmentSrc = setPrecision(fragmentSrc, precision);
} }
/**
* The shader program
*
* @member {WebGLProgram}
*/
// First compile the program.. // First compile the program..
this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations);
/**
* The attributes of the shader as an object containing the following properties
* {
* type,
* size,
* location,
* pointer
* }
* @member {Object}
*/
// next extract the attributes // next extract the attributes
this.attributes = extractAttributes(gl, this.program); this.attributes = extractAttributes(gl, this.program);
this.uniformData = extractUniforms(gl, this.program); this.uniformData = extractUniforms(gl, this.program);
/**
* The uniforms of the shader as an object containing the following properties
* {
* gl,
* data
* }
* @member {Object}
*/
this.uniforms = generateUniformAccessObject(gl, this.uniformData); this.uniforms = generateUniformAccessObject(gl, this.uniformData);
}; };
/** /**
* Uses this shader * Uses this shader
* * 状态机当前使用的shader
* @return {glCore.GLShader} Returns itself. * @return {glCore.GLShader} Returns itself.
*/ */
public bind() { public bind() {
......
/** /**
* Helper class to create a WebGL Texture * Helper class to create a WebGL Texture
* * 用于创建WebGL Texture
* @class * @class
* @memberof glCore * @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL context * @param gl {WebGLRenderingContext} The current WebGL context
...@@ -11,57 +11,53 @@ ...@@ -11,57 +11,53 @@
* @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE
*/ */
export class GLTexture { export class GLTexture {
gl: any; /**
texture: any; * 当前上下文
* The current WebGL rendering context
*/
gl: WebGLRenderingContext;
texture: WebGLTexture;
/**
* If mipmapping was used for this texture, enable and disable with enableMipmap()
* 是否对纹理进行存储缩小的各种尺寸纹理,比如原图1024*1024,存储512*512,256*256,128*128等一直到1*1;为了纹理的缩放时处理,是取相邻或线性插值
*/
mipmap: boolean; mipmap: boolean;
premultiplyAlpha: boolean; /**
width: any; * Set to true to enable pre-multiplied alpha
height: any; * 设置纹理预乘透明值,为true,https://blog.csdn.net/mydreamremindme/article/details/50817294
*/
premultiplyAlpha;
/**
* 纹理宽度
*/
width: number;
/**
* 纹理高度
*/
height: number;
/**
* {number} the pixel format of the texture. defaults to gl.RGBA
* 纹理格式,默认gl.RGBA 还有gl.RGB
*/
format: any; format: any;
/**
* {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE
* 纹理类型,默认gl.UNSIGNED_BYTE //https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/texImage2D
*/
type: any; type: any;
constructor(gl, width?, height?, format?, type?) { constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?, type?) {
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
this.gl = gl;
/**
* The WebGL texture
*
* @member {WebGLTexture}
*/
this.texture = gl.createTexture(); this.texture = gl.createTexture();
/**
* If mipmapping was used for this texture, enable and disable with enableMipmap()
*
* @member {Boolean}
*/
// some settings.. // some settings..
this.mipmap = false; this.mipmap = false;
/**
* Set to true to enable pre-multiplied alpha
*
* @member {Boolean}
*/
this.premultiplyAlpha = false; this.premultiplyAlpha = false;
/**
* The width of texture
*
* @member {Number}
*/
this.width = width || -1; this.width = width || -1;
/**
* The height of texture
*
* @member {Number}
*/
this.height = height || -1; this.height = height || -1;
/** /**
...@@ -77,17 +73,16 @@ export class GLTexture { ...@@ -77,17 +73,16 @@ export class GLTexture {
* @member {Number} * @member {Number}
*/ */
this.type = type || gl.UNSIGNED_BYTE; this.type = type || gl.UNSIGNED_BYTE;
}; };
/** /**
* Uploads this texture to the GPU * Uploads this texture to the GPU
* GPU存储纹理数据
* @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture
*/ */
public upload(source) { public upload(source) {
this.bind(); this.bind();
var gl = this.gl; var gl = this.gl;
...@@ -99,20 +94,22 @@ export class GLTexture { ...@@ -99,20 +94,22 @@ export class GLTexture {
var newHeight = source.videoHeight || source.height; var newHeight = source.videoHeight || source.height;
if (newHeight !== this.height || newWidth !== this.width) { if (newHeight !== this.height || newWidth !== this.width) {
//https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/texImage2D
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source);
} }
else { else {
//https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texSubImage2D
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source);
} }
// if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect.
this.width = newWidth; this.width = newWidth;
this.height = newHeight; this.height = newHeight;
}; };
/** /**
* Use a data source and uploads this texture to the GPU * Use a data source and uploads this texture to the GPU
* 数据类型的纹理
* @param data {TypedArray} the data to upload to the texture * @param data {TypedArray} the data to upload to the texture
* @param width {number} the new width of the texture * @param width {number} the new width of the texture
* @param height {number} the new height of the texture * @param height {number} the new height of the texture
...@@ -162,9 +159,10 @@ export class GLTexture { ...@@ -162,9 +159,10 @@ export class GLTexture {
/** /**
* Binds the texture * Binds the texture
* 绑定纹理,不传location表示不激活额外纹理,绑定的纹理位置与原状态相同
* @param location * @param location
*/ */
public bind(location?) { public bind(location?: number) {
var gl = this.gl; var gl = this.gl;
if (location !== undefined) { if (location !== undefined) {
...@@ -176,6 +174,7 @@ export class GLTexture { ...@@ -176,6 +174,7 @@ export class GLTexture {
/** /**
* Unbinds the texture * Unbinds the texture
* 解除纹理绑定,解除位置与原状态相同
*/ */
public unbind() { public unbind() {
var gl = this.gl; var gl = this.gl;
...@@ -184,8 +183,9 @@ export class GLTexture { ...@@ -184,8 +183,9 @@ export class GLTexture {
/** /**
* @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
* 缩小的纹理像素 按线性插值,还是按钮邻近原则
*/ */
public minFilter(linear) { public minFilter(linear: boolean) {
var gl = this.gl; var gl = this.gl;
this.bind(); this.bind();
...@@ -200,8 +200,9 @@ export class GLTexture { ...@@ -200,8 +200,9 @@ export class GLTexture {
/** /**
* @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
* 放大的纹理像素 按线性插值,还是按钮邻近原则
*/ */
public magFilter(linear) { public magFilter(linear: boolean) {
var gl = this.gl; var gl = this.gl;
this.bind(); this.bind();
...@@ -211,6 +212,7 @@ export class GLTexture { ...@@ -211,6 +212,7 @@ export class GLTexture {
/** /**
* Enables mipmapping * Enables mipmapping
* 生成缩小的纹理集,只能在图片宽高满足2的指数时使用
*/ */
public enableMipmap() { public enableMipmap() {
var gl = this.gl; var gl = this.gl;
...@@ -224,6 +226,7 @@ export class GLTexture { ...@@ -224,6 +226,7 @@ export class GLTexture {
/** /**
* Enables linear filtering * Enables linear filtering
* 设置线性
*/ */
public enableLinearScaling() { public enableLinearScaling() {
this.minFilter(true); this.minFilter(true);
...@@ -232,6 +235,7 @@ export class GLTexture { ...@@ -232,6 +235,7 @@ export class GLTexture {
/** /**
* Enables nearest neighbour interpolation * Enables nearest neighbour interpolation
* 设置邻近
*/ */
public enableNearestScaling() { public enableNearestScaling() {
this.minFilter(false); this.minFilter(false);
...@@ -240,6 +244,7 @@ export class GLTexture { ...@@ -240,6 +244,7 @@ export class GLTexture {
/** /**
* Enables clamping on the texture so WebGL will not repeat it * Enables clamping on the texture so WebGL will not repeat it
* 如果纹理不满足2的指数时必设,以边缘像素延申
*/ */
public enableWrapClamp() { public enableWrapClamp() {
var gl = this.gl; var gl = this.gl;
...@@ -252,6 +257,7 @@ export class GLTexture { ...@@ -252,6 +257,7 @@ export class GLTexture {
/** /**
* Enable tiling on the texture * Enable tiling on the texture
* 允许纹理重复,地砖模式
*/ */
public enableWrapRepeat() { public enableWrapRepeat() {
var gl = this.gl; var gl = this.gl;
...@@ -261,6 +267,9 @@ export class GLTexture { ...@@ -261,6 +267,9 @@ export class GLTexture {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
}; };
/**
* 镜像形式重复
*/
public enableWrapMirrorRepeat() { public enableWrapMirrorRepeat() {
var gl = this.gl; var gl = this.gl;
...@@ -281,16 +290,16 @@ export class GLTexture { ...@@ -281,16 +290,16 @@ export class GLTexture {
}; };
/** /**
* @static * 从图片数据创建纹理
* @param gl {WebGLRenderingContext} The current WebGL context * @static
* @param source {HTMLImageElement|ImageData} the source image of the texture * @param gl {WebGLRenderingContext} The current WebGL context
* @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha * @param source {HTMLImageElement|ImageData} the source image of the texture
*/ * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha
public static fromSource(gl, source, premultiplyAlpha?) { */
var texture = new GLTexture(gl); public static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData, premultiplyAlpha?: boolean) {
var texture: GLTexture = new GLTexture(gl);
texture.premultiplyAlpha = premultiplyAlpha || false; texture.premultiplyAlpha = premultiplyAlpha || false;
texture.upload(source); texture.upload(source);
return texture; return texture;
}; };
......
...@@ -2,12 +2,11 @@ ...@@ -2,12 +2,11 @@
/** /**
* A standard object to store the Uvs of a texture * A standard object to store the Uvs of a texture
* * 纹理的uv,暂时不处理纹理的旋转,不用GroupD8,
* @class * @class
* @private * @private
*/ */
export class TextureUvs export class TextureUvs {
{
x0: number; x0: number;
y0: number; y0: number;
x1: number; x1: number;
...@@ -16,12 +15,17 @@ export class TextureUvs ...@@ -16,12 +15,17 @@ export class TextureUvs
y2: number; y2: number;
x3: number; x3: number;
y3: number; y3: number;
/**
* 减少传入gpu的数据字节,所以转换成十六进制,
*/
uvsUint32: Uint32Array; uvsUint32: Uint32Array;
/** /**
* * 00.....10
* . .
* . .
* 01.....11
*/ */
constructor() constructor() {
{
this.x0 = 0; this.x0 = 0;
this.y0 = 0; this.y0 = 0;
...@@ -43,14 +47,13 @@ export class TextureUvs ...@@ -43,14 +47,13 @@ export class TextureUvs
/** /**
* Sets the texture Uvs based on the given frame information. * Sets the texture Uvs based on the given frame information.
* * 设置uv
* @private * @private
* @param {Rectangle} frame - The frame of the texture * @param {Rectangle} frame - The frame of the texture 小图
* @param {Rectangle} baseFrame - The base frame of the texture * @param {Rectangle} baseFrame - The base frame of the texture,大图
* @param {number} rotate - Rotation of frame, see {@link GroupD8} * @param {number} rotate - Rotation of frame, see {@link GroupD8}
*/ */
set(frame, baseFrame, rotate?) set(frame, baseFrame, rotate?) {
{
const tw = baseFrame.width; const tw = baseFrame.width;
const th = baseFrame.height; const th = baseFrame.height;
...@@ -82,17 +85,17 @@ export class TextureUvs ...@@ -82,17 +85,17 @@ export class TextureUvs
// } // }
// else // else
// { // {
this.x0 = frame.x / tw; this.x0 = frame.x / tw;
this.y0 = frame.y / th; this.y0 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw; this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th; this.y1 = frame.y / th;
this.x2 = (frame.x + frame.width) / tw; this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th; this.y2 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw; this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th; this.y3 = (frame.y + frame.height) / th;
// } // }
this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF); this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF);
......
...@@ -5,7 +5,7 @@ import { setVertexAttribArrays } from './setVertexAttribArrays'; ...@@ -5,7 +5,7 @@ import { setVertexAttribArrays } from './setVertexAttribArrays';
/** /**
* Helper class to work with WebGL VertexArrayObjects (vaos) * Helper class to work with WebGL VertexArrayObjects (vaos)
* Only works if WebGL extensions are enabled (they usually are) * Only works if WebGL extensions are enabled (they usually are)
* * 核心类VAOs
* @class * @class
* @memberof glCore * @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL rendering context * @param gl {WebGLRenderingContext} The current WebGL rendering context
...@@ -14,13 +14,29 @@ export class VertexArrayObject { ...@@ -14,13 +14,29 @@ export class VertexArrayObject {
nativeVaoExtension: any; nativeVaoExtension: any;
nativeState: any; nativeState: any;
nativeVao: any; nativeVao: any;
gl: any; /**
* 当前上下文
*/
gl: WebGLRenderingContext;
/**
* An array of attributes
* attributes数组
*/
attributes: any[]; attributes: any[];
/**
* 索引buffer
* @member {GLBuffer}
*/
indexBuffer: any; indexBuffer: any;
/**
* A boolean flag
*/
dirty: boolean; dirty: boolean;
constructor(gl, state) { constructor(gl: WebGLRenderingContext, state) {
this.nativeVaoExtension = null; this.nativeVaoExtension = null;
//不要求必须使用原生时,基本都支持扩展
if (!VertexArrayObject.FORCE_NATIVE) { if (!VertexArrayObject.FORCE_NATIVE) {
this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') ||
gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') ||
...@@ -41,35 +57,18 @@ export class VertexArrayObject { ...@@ -41,35 +57,18 @@ export class VertexArrayObject {
}; };
} }
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl; this.gl = gl;
/**
* An array of attributes
*
* @member {Array}
*/
this.attributes = []; this.attributes = [];
/**
* @member {glCore.GLBuffer}
*/
this.indexBuffer = null; this.indexBuffer = null;
/**
* A boolean flag
*
* @member {Boolean}
*/
this.dirty = false; this.dirty = false;
}; };
/** /**
* Binds the buffer * Binds the buffer
* 绑定数据
*/ */
public bind() { public bind() {
if (this.nativeVao) { if (this.nativeVao) {
...@@ -93,6 +92,7 @@ export class VertexArrayObject { ...@@ -93,6 +92,7 @@ export class VertexArrayObject {
/** /**
* Unbinds the buffer * Unbinds the buffer
* 解绑数据
*/ */
public unbind() { public unbind() {
if (this.nativeVao) { if (this.nativeVao) {
...@@ -104,6 +104,7 @@ export class VertexArrayObject { ...@@ -104,6 +104,7 @@ export class VertexArrayObject {
/** /**
* Uses this vao * Uses this vao
* 激活vao
*/ */
public activate() { public activate() {
...@@ -136,7 +137,7 @@ export class VertexArrayObject { ...@@ -136,7 +137,7 @@ export class VertexArrayObject {
}; };
/** /**
* * 添加attribute
* @param buffer {gl.GLBuffer} * @param buffer {gl.GLBuffer}
* @param attribute {*} * @param attribute {*}
* @param type {String} * @param type {String}
...@@ -162,7 +163,7 @@ export class VertexArrayObject { ...@@ -162,7 +163,7 @@ export class VertexArrayObject {
}; };
/** /**
* * 添加索引数据
* @param buffer {gl.GLBuffer} * @param buffer {gl.GLBuffer}
*/ */
public addIndex(buffer/*, options*/) { public addIndex(buffer/*, options*/) {
...@@ -175,6 +176,7 @@ export class VertexArrayObject { ...@@ -175,6 +176,7 @@ export class VertexArrayObject {
/** /**
* Unbinds this vao and disables it * Unbinds this vao and disables it
* 解绑废弃vao
*/ */
public clear() { public clear() {
// var gl = this.gl; // var gl = this.gl;
...@@ -192,17 +194,20 @@ export class VertexArrayObject { ...@@ -192,17 +194,20 @@ export class VertexArrayObject {
}; };
/** /**
* @param type {Number} * 执行绘制
* @param size {Number} * @param type {Number} gl.TRIANGLES\gl.TRIANGLE_STRIP等
* @param start {Number} * @param size {Number} 个数
* @param start {Number} 偏移
*/ */
public draw(type, size?, start?) { public draw(type, size?, start?) {
var gl = this.gl; var gl = this.gl;
if (this.indexBuffer) { if (this.indexBuffer) {
//有索引 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements
gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2);
} }
else { else {
//无索引 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawArrays
// TODO need a better way to calculate size.. // TODO need a better way to calculate size..
gl.drawArrays(type, start || 0, size || this.getSize()); gl.drawArrays(type, start || 0, size || this.getSize());
} }
......
...@@ -9,7 +9,12 @@ const fragTemplate = [ ...@@ -9,7 +9,12 @@ const fragTemplate = [
'}', '}',
].join('\n'); ].join('\n');
export function checkMaxIfStatmentsInShader(maxIfs, gl) { /**
* 检查最大纹理数是否合法
* @param maxIfs
* @param gl
*/
export function checkMaxIfStatmentsInShader(maxIfs:number, gl:WebGLRenderingContext) {
const createTempContext = !gl; const createTempContext = !gl;
// @if DEBUG // @if DEBUG
......
/** /**
* Helper class to create a webGL Context * Helper class to create a webGL Context
* * 创建webgl上下文
* @class
* @memberof glCore
* @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from
* @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes,
* see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available
......
/** /**
* Generic Mask Stack data structure * Generic Mask Stack data structure
* * 根据图片数量创建索引数组
* 0....1
* . . .
* . . .
* 3....2
* @function createIndicesForQuads * @function createIndicesForQuads
* @private * @private
* @param {number} size - Number of quads * @param {number} size - Number of quads
* @return {Uint16Array} indices * @return {Uint16Array} indices
*/ */
export function createIndicesForQuads(size) export function createIndicesForQuads(size:number)
{ {
// the total number of indices in our array, there are 6 points per quad. // the total number of indices in our array, there are 6 points per quad.
......
...@@ -8,7 +8,7 @@ const VSHADER_SOURCE = ...@@ -8,7 +8,7 @@ const VSHADER_SOURCE =
"attribute float aTextureId;" + "attribute float aTextureId;" +
"uniform mat3 projectionMatrix;" + "uniform mat3 projectionMatrix;" +
"uniform mat3 modelMatrix;" + // "uniform mat3 modelMatrix;" +
"varying vec2 vTextureCoord;" + "varying vec2 vTextureCoord;" +
"varying vec4 vColor;" + "varying vec4 vColor;" +
...@@ -21,6 +21,7 @@ const VSHADER_SOURCE = ...@@ -21,6 +21,7 @@ const VSHADER_SOURCE =
"vTextureId = aTextureId;" + "vTextureId = aTextureId;" +
"vColor = aColor;" + "vColor = aColor;" +
"}"; "}";
//片元着色器程序
const fragTemplate = [ const fragTemplate = [
'precision mediump float;', 'precision mediump float;',
'varying vec2 vTextureCoord;', 'varying vec2 vTextureCoord;',
...@@ -37,7 +38,11 @@ const fragTemplate = [ ...@@ -37,7 +38,11 @@ const fragTemplate = [
].join('\n'); ].join('\n');
/**
* 创建批处理专用着色器,核心,切换纹理
* @param gl
* @param maxTextures 最大纹理数
*/
export function generateMultiTextureShader(gl, maxTextures) { export function generateMultiTextureShader(gl, maxTextures) {
// const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); // const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8');
let fragmentSrc = fragTemplate; let fragmentSrc = fragTemplate;
......
...@@ -5,6 +5,7 @@ export { GLBuffer } from './GLBuffer'; ...@@ -5,6 +5,7 @@ export { GLBuffer } from './GLBuffer';
export { VertexArrayObject } from './VertexArrayObject'; export { VertexArrayObject } from './VertexArrayObject';
export { GLFramebuffer } from "./GLFramebuffer"; export { GLFramebuffer } from "./GLFramebuffer";
export { GLShader } from "./GLShader"; export { GLShader } from "./GLShader";
export { BatchBuffer } from "./BatchBuffer";
export { TextureUvs } from "./TextureUvs"; export { TextureUvs } from "./TextureUvs";
export { checkMaxIfStatmentsInShader } from "./checkMaxIfStatmentsInShader" export { checkMaxIfStatmentsInShader } from "./checkMaxIfStatmentsInShader"
// var GL_MAP = {}; // var GL_MAP = {};
/** /**
* 连接attribute变量与分配给它的缓冲区对象,两种方式,与顶点着色器通信核心方法
* @param gl {WebGLRenderingContext} The current WebGL context * @param gl {WebGLRenderingContext} The current WebGL context
* @param attribs {*} * @param attribs {*}
* @param state {*} * @param state {*}
......
/** /**
* @class * 编译着色器程序
* @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
* @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param vertexSrc The vertex shader source as an array of strings.顶点着色器
* @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param fragmentSrc The fragment shader source as an array of strings.片元着色器
* @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations
* @return {WebGLProgram} the shader program * @return {WebGLProgram} the shader program 返回着色器程序
*/ */
export function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations?) { export function compileProgram(gl:WebGLRenderingContext, vertexSrc:string, fragmentSrc:string, attributeLocations?) {
var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);
var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);
...@@ -50,6 +49,7 @@ export function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations?) ...@@ -50,6 +49,7 @@ export function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations?)
}; };
/** /**
* 创建shader
* @private * @private
* @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
* @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
......
...@@ -3,14 +3,14 @@ import { mapType } from './mapType'; ...@@ -3,14 +3,14 @@ import { mapType } from './mapType';
import { mapSize } from './mapSize'; import { mapSize } from './mapSize';
/** /**
* Extracts the attributes * Extracts the attributes获取attributes属性
* @class * @class
* @memberof glCore.shader * @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context * @param gl {WebGLRenderingContext} The current WebGL rendering context
* @param program {WebGLProgram} The shader program to get the attributes from * @param program {WebGLProgram} The shader program to get the attributes from
* @return attributes {Object} * @return attributes {Object}
*/ */
export function extractAttributes(gl, program) { export function extractAttributes(gl: WebGLRenderingContext, program: WebGLProgram) {
var attributes = {}; var attributes = {};
var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
......
...@@ -2,7 +2,7 @@ import { mapType } from './mapType'; ...@@ -2,7 +2,7 @@ import { mapType } from './mapType';
import { defaultValue } from './defaultValue'; import { defaultValue } from './defaultValue';
/** /**
* Extracts the uniforms * Extracts the uniforms 获取uniforms属性
* @class * @class
* @memberof glCore.shader * @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context * @param gl {WebGLRenderingContext} The current WebGL rendering context
......
/** /**
* Extracts the attributes * 使uniform能通过赋值直接和着色器程序通信
* @class * @class
* @memberof glCore.shader * @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context * @param gl {WebGLRenderingContext} The current WebGL rendering context
......
/** /**
* 给shader source设置precision
* Sets the float precision on the shader. If the precision is already present this function will do nothing * Sets the float precision on the shader. If the precision is already present this function will do nothing
* @param {string} src the shader source * @param {string} src the shader source
* @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'.
......
...@@ -2,13 +2,28 @@ ...@@ -2,13 +2,28 @@
// import AlphaMaskFilter from '../filters/spriteMask/SpriteMaskFilter'; // import AlphaMaskFilter from '../filters/spriteMask/SpriteMaskFilter';
/** /**
* @class * 遮罩管理器
*/ */
export default class MaskManager { export default class MaskManager {
/**
* 当前渲染器
*/
renderer: any; renderer: any;
/**
* 是否剪切
*/
scissor: boolean; scissor: boolean;
/**
* 剪切数据
*/
scissorData: any; scissorData: any;
/**
* 剪切对象
*/
scissorRenderTarget: any; scissorRenderTarget: any;
/**
* 是否允许剪切
*/
enableScissor: boolean; enableScissor: boolean;
/** /**
* @param {WebGLRenderer} renderer - The renderer this manager works for. * @param {WebGLRenderer} renderer - The renderer this manager works for.
...@@ -29,7 +44,7 @@ export default class MaskManager { ...@@ -29,7 +44,7 @@ export default class MaskManager {
/** /**
* Applies the Mask and adds it to the current filter stack. * Applies the Mask and adds it to the current filter stack.
* * 执行遮罩
* @param {DisplayObject} target - Display Object to push the mask to * @param {DisplayObject} target - Display Object to push the mask to
* @param {Sprite|Graphics} maskData - The masking data. * @param {Sprite|Graphics} maskData - The masking data.
*/ */
...@@ -62,7 +77,7 @@ export default class MaskManager { ...@@ -62,7 +77,7 @@ export default class MaskManager {
/** /**
* Removes the last mask from the mask stack and doesn't return it. * Removes the last mask from the mask stack and doesn't return it.
* * 移除遮罩
* @param {DisplayObject} target - Display Object to pop the mask from * @param {DisplayObject} target - Display Object to pop the mask from
* @param {Sprite|Graphics} maskData - The masking data. * @param {Sprite|Graphics} maskData - The masking data.
*/ */
...@@ -114,7 +129,7 @@ export default class MaskManager { ...@@ -114,7 +129,7 @@ export default class MaskManager {
/** /**
* Applies the Mask and adds it to the current filter stack. * Applies the Mask and adds it to the current filter stack.
* * 执行模板遮罩
* @param {Sprite|Graphics} maskData - The masking data. * @param {Sprite|Graphics} maskData - The masking data.
*/ */
pushStencilMask(maskData) { pushStencilMask(maskData) {
...@@ -124,7 +139,7 @@ export default class MaskManager { ...@@ -124,7 +139,7 @@ export default class MaskManager {
/** /**
* Removes the last filter from the filter stack and doesn't return it. * Removes the last filter from the filter stack and doesn't return it.
* * 移除模板遮罩
*/ */
popStencilMask(target, maskData) { popStencilMask(target, maskData) {
this.renderer.currentRenderer.stop(); this.renderer.currentRenderer.stop();
...@@ -132,7 +147,7 @@ export default class MaskManager { ...@@ -132,7 +147,7 @@ export default class MaskManager {
} }
/** /**
* * 执行剪切遮罩
* @param {DisplayObject} target - Display Object to push the mask to * @param {DisplayObject} target - Display Object to push the mask to
* @param {Graphics} maskData - The masking data. * @param {Graphics} maskData - The masking data.
*/ */
...@@ -160,8 +175,7 @@ export default class MaskManager { ...@@ -160,8 +175,7 @@ export default class MaskManager {
} }
/** /**
* * 移除剪切遮罩
*
*/ */
popScissorMask(target, maskData) { popScissorMask(target, maskData) {
// this.scissorRenderTarget = null; // this.scissorRenderTarget = null;
......
/** /**
* 模板缓存,实现遮罩
* @class * @class
*/ */
export default class StencilManager { export default class StencilManager {
/**
* 当前渲染器
*/
renderer: any; renderer: any;
/**
* 记录嵌套的遮罩数据
*/
stencilMaskStack: any; stencilMaskStack: any;
/** /**
* @param {WebGLRenderer} renderer - The renderer this manager works for. * @param {WebGLRenderer} renderer - The renderer this manager works for.
*/ */
...@@ -16,7 +24,7 @@ export default class StencilManager { ...@@ -16,7 +24,7 @@ export default class StencilManager {
/** /**
* Changes the mask stack that is used by this manager. * Changes the mask stack that is used by this manager.
* * 改变mask stack
* @param {Graphics[]} stencilMaskStack - The mask stack * @param {Graphics[]} stencilMaskStack - The mask stack
*/ */
setMaskStack(stencilMaskStack) { setMaskStack(stencilMaskStack) {
...@@ -34,7 +42,7 @@ export default class StencilManager { ...@@ -34,7 +42,7 @@ export default class StencilManager {
/** /**
* Applies the Mask and adds it to the current stencil stack. @alvin * Applies the Mask and adds it to the current stencil stack. @alvin
* * 应用遮罩
* @param {Graphics} graphics - The mask * @param {Graphics} graphics - The mask
*/ */
pushStencil(graphics) { pushStencil(graphics) {
...@@ -51,23 +59,29 @@ export default class StencilManager { ...@@ -51,23 +59,29 @@ export default class StencilManager {
this.stencilMaskStack.push(graphics); this.stencilMaskStack.push(graphics);
// Increment the refference stencil value where the new mask overlaps with the old ones.
if(graphics.maskVisible){ if(graphics.maskVisible){
//如果显示遮罩 //如果显示遮罩
gl.colorMask(true, true, true, true); gl.colorMask(true, true, true, true);
}else{ }else{
gl.colorMask(false, false, false, false); gl.colorMask(false, false, false, false);
} }
// Increment the refference stencil value where the new mask overlaps with the old ones.
// gl.colorMask(true, true, true, true); // gl.colorMask(true, true, true, true);
//设置模板检测规则,https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/stencilFunc
gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
//设置模板的绘制规则,模板检测未通过时,深度检测通过时,都通过时 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp
gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
//开始绘制遮罩数据
this.renderer.plugins.graphics.render(graphics); this.renderer.plugins.graphics.render(graphics);
//应用当前遮罩,后续绘制的东西都会有效
this._useCurrent(); this._useCurrent();
} }
/** /**
* Removes the last mask from the stencil stack. @alvin * Removes the last mask from the stencil stack. @alvin
* 移除模板数据,一步一步,考虑嵌套的遮罩。
*/ */
popStencil() { popStencil() {
this.renderer.setObjectRenderer(this.renderer.plugins.graphics); this.renderer.setObjectRenderer(this.renderer.plugins.graphics);
...@@ -93,6 +107,7 @@ export default class StencilManager { ...@@ -93,6 +107,7 @@ export default class StencilManager {
/** /**
* Setup renderer to use the current stencil data. * Setup renderer to use the current stencil data.
* 使用当前模板数据
*/ */
_useCurrent() { _useCurrent() {
const gl = this.renderer.gl; const gl = this.renderer.gl;
...@@ -104,7 +119,7 @@ export default class StencilManager { ...@@ -104,7 +119,7 @@ export default class StencilManager {
/** /**
* Fill 1s equal to the number of acitve stencil masks. * Fill 1s equal to the number of acitve stencil masks.
* * 计算用于与运算的二进制对比位
* @return {number} The bitwise mask. * @return {number} The bitwise mask.
*/ */
_getBitwiseMask() { _getBitwiseMask() {
......
...@@ -6,37 +6,31 @@ import removeItems from '../utils/removeItems'; ...@@ -6,37 +6,31 @@ import removeItems from '../utils/removeItems';
import {isPow2} from "../utils" import {isPow2} from "../utils"
/** /**
* Helper class to create a webGL Texture * Helper class to create a webGL Texture
* * 用于创建webGL Texture
* @class * @class
*/ */
export default class TextureManager { export default class TextureManager {
/**
* 当前渲染器的指向
*/
renderer: any; renderer: any;
/**
*
*/
gl: any; gl: any;
/**
* Track textures in the renderer so we can no longer listen to them on destruction.
* 纹理集
*/
_managedTextures: any[]; _managedTextures: any[];
/** /**
* @param {WebGLRenderer} renderer - A reference to the current renderer * @param {WebGLRenderer} renderer - A reference to the current renderer
*/ */
constructor(renderer) { constructor(renderer) {
/**
* A reference to the current renderer
*
* @member {PIXI.WebGLRenderer}
*/
this.renderer = renderer; this.renderer = renderer;
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = renderer.gl; this.gl = renderer.gl;
/**
* Track textures in the renderer so we can no longer listen to them on destruction.
*
* @member {Array<*>}
* @private
*/
this._managedTextures = []; this._managedTextures = [];
} }
...@@ -58,9 +52,9 @@ export default class TextureManager { ...@@ -58,9 +52,9 @@ export default class TextureManager {
/** /**
* Updates and/or Creates a WebGL texture for the renderer's context. * Updates and/or Creates a WebGL texture for the renderer's context.
* * 更新或创建一个WebGL texture ,主要方法
* @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update * @param {BaseTexture|Texture} texture - the texture to update 暂时主要是image
* @param {number} location - the location the texture will be bound to. * @param {number} location - the location the texture will be bound to.激活绑定纹理的位置
* @return {GLTexture} The gl texture. * @return {GLTexture} The gl texture.
*/ */
updateTexture(texture, location) { updateTexture(texture, location) {
...@@ -173,7 +167,7 @@ export default class TextureManager { ...@@ -173,7 +167,7 @@ export default class TextureManager {
/** /**
* Deletes the texture from WebGL * Deletes the texture from WebGL
* *
* @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy * @param {BaseTexture|Texture} texture - the texture to destroy
* @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
*/ */
destroyTexture(texture, skipRemove) { destroyTexture(texture, skipRemove) {
......
import ObjectRenderer from '../ObjectRenderer'; import ObjectRenderer from '../ObjectRenderer';
import WebGLRenderer from '../WebGLRenderer'; import WebGLRenderer from '../WebGLRenderer';
import createIndicesForQuads from '../utils/createIndicesForQuads'; import { createIndicesForQuads } from '../glCore/createIndicesForQuads';
import { generateMultiTextureShader } from '../utils/generateMultiTextureShader'; import { generateMultiTextureShader } from '../glCore/generateMultiTextureShader';
import { checkMaxIfStatmentsInShader } from '../glCore/checkMaxIfStatmentsInShader'; import { checkMaxIfStatmentsInShader } from '../glCore/checkMaxIfStatmentsInShader';
import { BatchBuffer } from '../glCore/BatchBuffer'; import { BatchBuffer } from '../glCore/BatchBuffer';
import settings from '../settings'; import settings from '../settings';
...@@ -16,21 +16,59 @@ let TEXTURE_TICK = 0; ...@@ -16,21 +16,59 @@ let TEXTURE_TICK = 0;
/** /**
* Renderer dedicated to drawing and batching sprites. * Renderer dedicated to drawing and batching sprites.
* * 批处理核心插件
* @class * @class
* @private * @private
* @extends ObjectRenderer * @extends ObjectRenderer
*/ */
export default class BatchRenderer extends ObjectRenderer { export default class BatchRenderer extends ObjectRenderer {
/**
* Number of values sent in the vertex buffer.
* aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5
* 顶点数据中的步长
*/
vertSize: number; vertSize: number;
/**
* The size of the vertex information in bytes.
* 顶点数据步长的字节长度 *4
*/
vertByteSize: number; vertByteSize: number;
/**
* The number of images in the SpriteRenderer before it flushes.
* 批处理最大值总数
*/
size: number; size: number;
/**
* 所有可能用到的2的指数的buffer
*/
buffers: any[]; buffers: any[];
/**
* Holds the indices of the geometry (quads) to draw
* 基于size设定的顶点索引
*/
indices: Uint16Array; indices: Uint16Array;
/**
* The default shaders that is used if a sprite doesn't have a more specific one.
* there is a shader for each number of textures that can be rendererd.
* These shaders will also be generated on the fly as required.
* @member {GLShader}
*/
shader: any; shader: any;
/**
* 当前下标
*/
currentIndex: number; currentIndex: number;
/**
* 批处理分组
*/
groups: any[]; groups: any[];
/**
* flush要处理的所有元素
*/
sprites: any[]; sprites: any[];
/**
* 顶点buffer
*/
vertexBuffers: any[]; vertexBuffers: any[];
vaos: any[]; vaos: any[];
vaoMax: number; vaoMax: number;
...@@ -46,49 +84,23 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -46,49 +84,23 @@ export default class BatchRenderer extends ObjectRenderer {
constructor(renderer) { constructor(renderer) {
super(renderer); super(renderer);
/**
* Number of values sent in the vertex buffer.
* aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5
*
* @member {number}
*/
this.vertSize = 5; this.vertSize = 5;
/**
* The size of the vertex information in bytes.
*
* @member {number}
*/
this.vertByteSize = this.vertSize * 4; this.vertByteSize = this.vertSize * 4;
/**
* The number of images in the SpriteRenderer before it flushes.
*
* @member {number}
*/
this.size = settings.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop this.size = settings.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop
// the total number of bytes in our batch // the total number of bytes in our batch
// let numVerts = this.size * 4 * this.vertByteSize; // let numVerts = this.size * 4 * this.vertByteSize;
//建立所有可能用到的2的指数的buffer
this.buffers = []; this.buffers = [];
for (let i = 1; i <= nextPow2(this.size); i *= 2) { for (let i = 1; i <= nextPow2(this.size); i *= 2) {
this.buffers.push(new BatchBuffer(i * 4 * this.vertByteSize)); this.buffers.push(new BatchBuffer(i * 4 * this.vertByteSize));
} }
/**
* Holds the indices of the geometry (quads) to draw
*
* @member {Uint16Array}
*/
this.indices = createIndicesForQuads(this.size); this.indices = createIndicesForQuads(this.size);
/**
* The default shaders that is used if a sprite doesn't have a more specific one.
* there is a shader for each number of textures that can be rendererd.
* These shaders will also be generated on the fly as required.
* @member {Shader[]}
*/
this.shader = null; this.shader = null;
this.currentIndex = 0; this.currentIndex = 0;
...@@ -111,7 +123,8 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -111,7 +123,8 @@ export default class BatchRenderer extends ObjectRenderer {
/** /**
* Sets up the renderer context and necessary buffers. * Sets up the renderer context and necessary buffers.
* * 之前父级会设置this.renderer.on('context', this.onContextChange, this);
* 从简,直接在renderer里设置
* @private * @private
*/ */
onContextChange() { onContextChange() {
...@@ -167,7 +180,7 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -167,7 +180,7 @@ export default class BatchRenderer extends ObjectRenderer {
/** /**
* Called before the renderer starts rendering. * Called before the renderer starts rendering.
* * 在每帧渲染开始前执行
*/ */
onPrerender() { onPrerender() {
this.vertexCount = 0; this.vertexCount = 0;
...@@ -175,7 +188,7 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -175,7 +188,7 @@ export default class BatchRenderer extends ObjectRenderer {
/** /**
* Renders the sprite object. * Renders the sprite object.
* * 记录每个元素
* @param {Sprite} sprite - the sprite to render when using this spritebatch * @param {Sprite} sprite - the sprite to render when using this spritebatch
*/ */
render(sprite) { render(sprite) {
...@@ -199,7 +212,7 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -199,7 +212,7 @@ export default class BatchRenderer extends ObjectRenderer {
/** /**
* Renders the content and empties the current batch. * Renders the content and empties the current batch.
* * 将记录的所有元素一次绘制
*/ */
flush() { flush() {
if (this.currentIndex === 0) { if (this.currentIndex === 0) {
...@@ -286,6 +299,7 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -286,6 +299,7 @@ export default class BatchRenderer extends ObjectRenderer {
currentTexture = nextTexture; currentTexture = nextTexture;
if (nextTexture._enabled !== TICK) { if (nextTexture._enabled !== TICK) {
//如果将超过最大纹理数,则跳到一个group
if (textureCount === MAX_TEXTURES) { if (textureCount === MAX_TEXTURES) {
TICK++; TICK++;
...@@ -386,7 +400,7 @@ export default class BatchRenderer extends ObjectRenderer { ...@@ -386,7 +400,7 @@ export default class BatchRenderer extends ObjectRenderer {
_tintRGB = (num >> 16) + (num & 0xff00) + ((num & 0xff) << 16); _tintRGB = (num >> 16) + (num & 0xff00) + ((num & 0xff) << 16);
} }
const alpha = Math.min(sprite.transform.renderAlpha*sprite.alpha, 1.0); const alpha = Math.min(sprite.transform.renderAlpha * sprite.alpha, 1.0);
// we dont call extra function if alpha is 1.0, that's faster // we dont call extra function if alpha is 1.0, that's faster
const argb = alpha < 1.0 /*&& nextTexture.premultipliedAlpha*/ ? premultiplyTint(/*sprite._tintRGB*/_tintRGB, alpha) const argb = alpha < 1.0 /*&& nextTexture.premultipliedAlpha*/ ? premultiplyTint(/*sprite._tintRGB*/_tintRGB, alpha)
: /*sprite._tintRGB*/_tintRGB + (alpha * 255 << 24); : /*sprite._tintRGB*/_tintRGB + (alpha * 255 << 24);
......
...@@ -9,15 +9,30 @@ import { GLBuffer, VertexArrayObject } from "../glCore" ...@@ -9,15 +9,30 @@ import { GLBuffer, VertexArrayObject } from "../glCore"
/** /**
* Renders the graphics object. * Renders the graphics object.
*暂时为遮罩处理用,shader和vao特定的 * 暂时为遮罩处理用,shader和vao特定的
* @class * @class
* @extends ObjectRenderer * @extends ObjectRenderer
*/ */
export default class GraphicsRenderer extends ObjectRenderer { export default class GraphicsRenderer extends ObjectRenderer {
/**
* 暂时不需要,存储数据
*/
graphicsDataPool: any[]; graphicsDataPool: any[];
/**
* 预置的着色器
*/
primitiveShader: any; primitiveShader: any;
/**
* 当前上下文
*/
gl: any; gl: any;
/**
*
*/
CONTEXT_UID: number; CONTEXT_UID: number;
/**
* 当前渲染器
*/
renderer: any; renderer: any;
buffer: GLBuffer; buffer: GLBuffer;
indexBuffer: GLBuffer; indexBuffer: GLBuffer;
......
...@@ -2,7 +2,7 @@ import Shader from './Shader'; ...@@ -2,7 +2,7 @@ import Shader from './Shader';
/** /**
* This shader is used to draw simple primitive shapes for {@link Graphics}. * This shader is used to draw simple primitive shapes for {@link Graphics}.
* * 为图形使用的着色器
* @class * @class
* @extends Shader * @extends Shader
*/ */
......
...@@ -25,7 +25,7 @@ function checkPrecision(src, def) ...@@ -25,7 +25,7 @@ function checkPrecision(src, def)
/** /**
* Wrapper class, webGL Shader * Wrapper class, webGL Shader
* Adds precision string if vertexSrc or fragmentSrc have no mention of it. * Adds precision string if vertexSrc or fragmentSrc have no mention of it.
* * 为了给着色器加精度
* @class * @class
* @extends GLShader * @extends GLShader
*/ */
......
/**
* 批处理buffer数据类
*/
export default class Buffer {
/**
* 顶点类型化数组
*/
vertices: ArrayBuffer;
/**
* View on the vertices as a Float32Array for positions
* @member {Float32Array}
*/
float32View: Float32Array;
/**
* View on the vertices as a Uint32Array for uvs
* @member {Uint32Array}
*/
uint32View: Uint32Array;
positions: any;
uvs: any;
colors: any;
/**
* @param {number} size - The size of the buffer in bytes.
*/
constructor(size) {
this.vertices = new ArrayBuffer(size);
this.float32View = new Float32Array(this.vertices);
this.uint32View = new Uint32Array(this.vertices);
}
/**
* Destroys the buffer.
*
*/
destroy() {
this.vertices = null;
this.positions = null;
this.uvs = null;
this.colors = null;
}
}
...@@ -5,6 +5,7 @@ import settings from '../settings'; ...@@ -5,6 +5,7 @@ import settings from '../settings';
import { GLFramebuffer,GLTexture } from '../glCore'; import { GLFramebuffer,GLTexture } from '../glCore';
import { getStageSize } from "../../../core/context/RenderContextGL" import { getStageSize } from "../../../core/context/RenderContextGL"
/** /**
* 渲染对象,暂时只用到root
* @class * @class
*/ */
export default class RenderTarget { export default class RenderTarget {
......
/**
* 检测ios设备,若是,则返回不能同帧上传同一buffer
*/
export default function canUploadSameBuffer() { export default function canUploadSameBuffer() {
// Uploading the same buffer multiple times in a single frame can cause perf issues. // Uploading the same buffer multiple times in a single frame can cause perf issues.
// Apparent on IOS so only check for that at the moment // Apparent on IOS so only check for that at the moment
......
/**
* Generic Mask Stack data structure
*
* @function createIndicesForQuads
* @private
* @param {number} size - Number of quads
* @return {Uint16Array} indices
*/
export default function createIndicesForQuads(size)
{
// the total number of indices in our array, there are 6 points per quad.
const totalIndices = size * 6;
const indices = new Uint16Array(totalIndices);
// fill the indices with the quads to draw
for (let i = 0, j = 0; i < totalIndices; i += 6, j += 4)
{
indices[i + 0] = j + 0;
indices[i + 1] = j + 1;
indices[i + 2] = j + 2;
indices[i + 3] = j + 0;
indices[i + 4] = j + 2;
indices[i + 5] = j + 3;
}
return indices;
}
import { GLShader } from '../glCore/GLShader';
//顶点着色器程序
const VSHADER_SOURCE =
" precision highp float;" +
"attribute vec2 aVertexPosition;" +
"attribute vec2 aTextureCoord;" +
"attribute vec4 aColor;" +
"attribute float aTextureId;" +
"uniform mat3 projectionMatrix;" +
// "uniform mat3 modelMatrix;" +
"varying vec2 vTextureCoord;" +
"varying vec4 vColor;" +
"varying float vTextureId;" +
"void main(void){" +
"gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
// "gl_Position = vec4((projectionMatrix *modelMatrix* vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
"vTextureCoord = aTextureCoord;" +
"vTextureId = aTextureId;" +
"vColor = aColor;" +
"}";
const fragTemplate = [
'precision mediump float;',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'varying float vTextureId;',
'uniform sampler2D uSamplers[%count%];',
'void main(void){',
'vec4 color;',
'float textureId = floor(vTextureId+0.5);',
'%forloop%',
'gl_FragColor = color * vColor;',
'}',
].join('\n');
export function generateMultiTextureShader(gl, maxTextures) {
// const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8');
let fragmentSrc = fragTemplate;
fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures);
fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures));
// console.log(fragmentSrc)
const shader = new GLShader(gl, VSHADER_SOURCE, fragmentSrc);
const sampleValues = [];
for (let i = 0; i < maxTextures; i++) {
sampleValues[i] = i;
}
shader.bind();
shader.uniforms["uSamplers"] = sampleValues;
// console.log(fragmentSrc)
return shader;
}
function generateSampleSrc(maxTextures) {
let src = '';
src += '\n';
src += '\n';
for (let i = 0; i < maxTextures; i++) {
if (i > 0) {
src += '\nelse ';
}
if (i < maxTextures - 1) {
src += `if(textureId == ${i}.0)`;
}
src += '\n{';
src += `\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`;
src += '\n}';
}
src += '\n';
src += '\n';
return src;
}
/** /**
* premultiplies tint * premultiplies tint
* * 颜色与透明度预先处理
* @memberof utils * @memberof utils
* @param {number} tint integet RGB * @param {number} tint integet RGB
* @param {number} alpha floating point alpha (0.0-1.0) * @param {number} alpha floating point alpha (0.0-1.0)
* @returns {number} tint multiplied by alpha * @returns {number} tint multiplied by alpha
*/ */
export function premultiplyTint(tint, alpha) { export function premultiplyTint(tint:number, alpha:number) {
if (alpha === 1.0) { if (alpha === 1.0) {
return (alpha * 255 << 24) + tint; return (alpha * 255 << 24) + tint;
} }
...@@ -23,7 +23,10 @@ export function premultiplyTint(tint, alpha) { ...@@ -23,7 +23,10 @@ export function premultiplyTint(tint, alpha) {
return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
} }
/**
* 求下一个最接近2的指数,数值
* @param v
*/
export function nextPow2(v) { export function nextPow2(v) {
v += v === 0; v += v === 0;
--v; --v;
...@@ -35,6 +38,10 @@ export function nextPow2(v) { ...@@ -35,6 +38,10 @@ export function nextPow2(v) {
return v + 1; return v + 1;
} }
/**
* 求2为底的对数
* @param v
*/
export function log2(v: number) { export function log2(v: number) {
var r, shift; var r, shift;
r = Number(v > 0xFFFF) << 4; v >>>= r; r = Number(v > 0xFFFF) << 4; v >>>= r;
...@@ -44,13 +51,17 @@ export function log2(v: number) { ...@@ -44,13 +51,17 @@ export function log2(v: number) {
return r | (v >> 1); return r | (v >> 1);
} }
/**
* 是否2的指数式
* @param v
*/
export function isPow2(v) { export function isPow2(v) {
return !(v & (v - 1)) && (!!v); return !(v & (v - 1)) && (!!v);
} }
/** /**
* Converts a hex color number to an [R, G, B] array * Converts a hex color number to an [R, G, B] array
* * 0xffffff转[R,G,B]
* @memberof utils * @memberof utils
* @function hex2rgb * @function hex2rgb
* @param {number} hex - The number to convert * @param {number} hex - The number to convert
......
import {Device} from './Device'; import {Device} from './Device';
/**
* 获取合适的最大纹理数量
* @param max
*/
export default function maxRecommendedTextures(max) export default function maxRecommendedTextures(max)
{ {
if (Device.tablet || Device.phone) if (Device.tablet || Device.phone)
......
/** /**
* Remove a range of items from an array * Remove a range of items from an array
* * 从数组移除一定范围下标的元素
* @function removeItems * @function removeItems
* @param {Array<*>} arr The target array * @param {Array<*>} arr The target array
* @param {number} startIdx The index to begin removing from (inclusive) * @param {number} startIdx The index to begin removing from (inclusive)
......
/**
* 检查gl是否有效,主要检查模板缓存是否可用
*/
export default function validateContext(gl) export default function validateContext(gl)
{ {
const attributes = gl.getContextAttributes(); const attributes = gl.getContextAttributes();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment