splash screen webgl impl (#6058)

* splash screen webgl impl

* rename initRenderer2 to initRenderer
This commit is contained in:
jiaxin.lai
2020-01-08 19:09:14 +08:00
committed by pandamicro
parent fe92dfe151
commit 24102ee8cc
3 changed files with 424 additions and 55 deletions
+61 -54
View File
@@ -621,13 +621,12 @@ export class Game extends EventTarget {
this._rendererInitialized = true;
this.emit(Game.EVENT_RENDERER_INITED);
if (cc.internal.SplashScreen) {
// Start splash screen
cc.internal.SplashScreen.instance.main(this._gfxDevice);
cc.internal.SplashScreen.instance.setOnFinish(cb);
cc.internal.SplashScreen.instance.loadFinish = true;
if (!CC_EDITOR && !CC_PREVIEW && cc.internal.SplashScreenWebgl) {
cc.internal.SplashScreenWebgl.instance.setOnFinish(cb);
cc.internal.SplashScreenWebgl.instance.loadFinish = true;
} else {
cb && cb();
}
else if (cb) { cb(); }
});
}
@@ -783,62 +782,70 @@ export class Game extends EventTarget {
}
}
const el = this.config.id;
let width: any;
let height: any;
// TODO: adapter for editor & preview
let localCanvas: HTMLCanvasElement;
let localContainer: HTMLElement;
if (CC_EDITOR || CC_PREVIEW) {
const el = this.config.id;
let width: any;
let height: any;
let localContainer: HTMLElement;
if (CC_JSB) {
this.container = localContainer = document.createElement<'div'>('div');
this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode;
if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) {
localCanvas = window.sharedCanvas || wx.getSharedCanvas();
}
else if (CC_JSB) {
localCanvas = window.__canvas;
if (CC_JSB) {
this.container = localContainer = document.createElement<'div'>('div');
this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode;
if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) {
localCanvas = window.sharedCanvas || wx.getSharedCanvas();
}
else if (CC_JSB) {
localCanvas = window.__canvas;
}
else {
localCanvas = window.canvas;
}
this.canvas = localCanvas;
}
else {
localCanvas = window.canvas;
}
this.canvas = localCanvas;
}
else {
const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)));
if (!element) {
throw new Error(debug.getError(200));
}
if (element.tagName === 'CANVAS') {
width = (element as HTMLCanvasElement).width;
height = (element as HTMLCanvasElement).height;
// it is already a canvas, we wrap it around with a div
this.canvas = localCanvas = (element as HTMLCanvasElement);
this.container = localContainer = document.createElement<'div'>('div');
if (localCanvas && localCanvas.parentNode) {
localCanvas.parentNode.insertBefore(localContainer, localCanvas);
const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)));
if (!element) {
throw new Error(debug.getError(200));
}
} else {
// we must make a new canvas and place into this element
if (element.tagName !== 'DIV') {
debug.warnID(3819);
if (element.tagName === 'CANVAS') {
width = (element as HTMLCanvasElement).width;
height = (element as HTMLCanvasElement).height;
// it is already a canvas, we wrap it around with a div
this.canvas = localCanvas = (element as HTMLCanvasElement);
this.container = localContainer = document.createElement<'div'>('div');
if (localCanvas && localCanvas.parentNode) {
localCanvas.parentNode.insertBefore(localContainer, localCanvas);
}
} else {
// we must make a new canvas and place into this element
if (element.tagName !== 'DIV') {
debug.warnID(3819);
}
width = element.clientWidth;
height = element.clientHeight;
this.canvas = localCanvas = document.createElement('canvas');
this.container = localContainer = document.createElement<'div'>('div');
element.appendChild(localContainer);
}
width = element.clientWidth;
height = element.clientHeight;
localContainer.setAttribute('id', 'Cocos3dGameContainer');
localContainer.appendChild(localCanvas!);
this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode;
this.canvas = localCanvas = document.createElement('canvas');
this.container = localContainer = document.createElement<'div'>('div');
element.appendChild(localContainer);
addClass(localCanvas!, 'gameCanvas');
localCanvas.setAttribute('width', width || '480');
localCanvas.setAttribute('height', height || '320');
localCanvas.setAttribute('tabindex', '99');
}
localContainer.setAttribute('id', 'Cocos3dGameContainer');
localContainer.appendChild(localCanvas!);
this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode;
addClass(localCanvas!, 'gameCanvas');
localCanvas.setAttribute('width', width || '480');
localCanvas.setAttribute('height', height || '320');
localCanvas.setAttribute('tabindex', '99');
} else {
this.canvas = (this.config as any).adapter.canvas;
this.frame = (this.config as any).adapter.frame;
this.container = (this.config as any).adapter.container;
localCanvas = this.canvas as HTMLCanvasElement;
}
this._determineRenderType();
+2 -1
View File
@@ -60,4 +60,5 @@ import './primitive';
export * from './utils/profiler/profiler';
import './deprecated';
import './splash-image';
// import './splash-image';
import './splash-screen-webgl';
+361
View File
@@ -0,0 +1,361 @@
import { IGFXColor } from "./gfx";
import { clamp01 } from "./math";
import { easing } from "./animation";
type SplashEffectType = 'none' | 'Fade-InOut';
interface ISplashSetting {
readonly totalTime: number;
readonly base64src: string;
readonly effect: SplashEffectType;
readonly clearColor: IGFXColor;
readonly displayRatio: number;
readonly displayWatermark: boolean;
}
function createShader (gl: WebGLRenderingContext, type: number, source: string) {
let shader = gl.createShader(type);
if (!shader) {
console.error('create shader error', source);
return;
}
gl.shaderSource(shader, source);
gl.compileShader(shader);
let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (success) {
return shader;
} else {
console.error('compile shader error', shader);
console.log(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
}
}
function createProgram (gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader) {
let program = gl.createProgram();
if (!program) {
console.error('create program error');
return;
}
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
let success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success) {
return program;
} else {
console.error('link program error', success);
console.log(gl.getProgramInfoLog(program));
gl.deleteProgram(program);
}
}
const vs = "precision mediump float;attribute vec2 a_position;attribute vec2 a_texCoord;uniform vec2 u_resolution;uniform mat3 u_worldMat;varying vec2 v_texCoord;void main() {vec3 wpos = u_worldMat * vec3(a_position, 1.0);vec2 clipSpace = wpos.xy / u_resolution * 2.0 - 1.0;gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);v_texCoord = a_texCoord;}";
const fs = "precision mediump float;uniform float u_alpha;uniform sampler2D u_image;varying vec2 v_texCoord;void main(){gl_FragColor = texture2D(u_image,v_texCoord);gl_FragColor.xyz *= clamp(u_alpha, 0.0, 1.0);}";
export class SplashScreenWebgl {
private gl!: WebGLRenderingContext;
private program!: WebGLProgram;
private vertexShader!: WebGLShader;
private fragmentShader!: WebGLShader;
private positionBuffer!: WebGLBuffer;
private texcoordBuffer!: WebGLBuffer;
private textureLogo!: WebGLTexture;
private textureText!: WebGLTexture;
private logoImage = new Image();
private textImage: HTMLCanvasElement = document.createElement('canvas');
private vertices = new Float32Array([-1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1]);
private texcoords = new Float32Array([0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1]);
private logoMat33 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
private textMat33 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
private setting!: ISplashSetting;
private callBack: Function | null = null;
private cancelAnimate = false;
private handle = -1;
private startTime = -1;
private _isStart = false;
private _directCall = false;
private _splashFinish = false;
private _loadFinish = false;
public set loadFinish (v: boolean) {
this._loadFinish = v;
this._tryToStart();
}
private set splashFinish (v: boolean) {
this._splashFinish = v;
this._tryToStart();
}
private _tryToStart () {
if (this._splashFinish && this._loadFinish) {
if (this.callBack) {
this.cancelAnimate = true;
cancelAnimationFrame(this.handle);
this.destroy();
this.callBack();
}
}
}
public setOnFinish (cb: Function) {
if ((!this._isStart || this._directCall) && cb) {
delete SplashScreenWebgl._ins;
return cb();
}
this.callBack = cb;
}
public main (canvas: HTMLCanvasElement) {
if (window._CCSettings && window._CCSettings.splashScreen) {
this.setting = window._CCSettings.splashScreen;
(this.setting.totalTime as number) = this.setting.totalTime != null ? this.setting.totalTime : 3000;
(this.setting.base64src as string) = this.setting.base64src != null ? this.setting.base64src : '';
(this.setting.effect as SplashEffectType) = this.setting.effect != null ? this.setting.effect : 'Fade-InOut';
(this.setting.clearColor as IGFXColor) = this.setting.clearColor != null ? this.setting.clearColor : { r: 0.88, g: 0.88, b: 0.88, a: 1.0 };
(this.setting.displayRatio as number) = this.setting.displayRatio != null ? this.setting.displayRatio : 0.4;
(this.setting.displayWatermark as boolean) = this.setting.displayWatermark != null ? this.setting.displayWatermark : true;
} else {
this.setting = {
totalTime: 3000,
base64src: '',
effect: 'Fade-InOut',
clearColor: { r: 0.88, g: 0.88, b: 0.88, a: 1.0 },
displayRatio: 0.4,
displayWatermark: true
};
}
if (canvas == null || this.setting.base64src == '' || this.setting.totalTime <= 0) {
if (this.callBack) { this.callBack(); }
this.callBack = null;
(this.setting as any) = null;
this._directCall = true;
return;
} else {
const gl = canvas.getContext('webgl');
const gl2 = canvas.getContext('webgl2');
if (gl == null && gl2 == null) {
return console.error("this device does not support webgl");
} else {
if (gl != null) this.gl = gl;
if (gl2 != null) this.gl = gl2;
}
const textImage = this.textImage;
textImage.width = 300;
textImage.height = 30;
textImage.style.width = `${textImage.width}`;
textImage.style.height = `${textImage.height}`;
const ctx = textImage.getContext('2d')!;
ctx.font = `${18}px Arial`
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
ctx.fillStyle = '`#424242`';
ctx.fillText("Powered by Cocos Creator 3D", 30, 8);
this.logoImage.onload = this.init.bind(this);
this.logoImage.src = this.setting.base64src;
this._isStart = true;
}
}
private init () {
this.initMatrix();
this.initProgram();
this.initBuffer();
this.initTexture();
this.initState();
const that = this;
const animate = (time: number) => {
if (this.cancelAnimate) { return; }
that.frame(time);
requestAnimationFrame(animate);
}
this.handle = requestAnimationFrame(animate);
}
private initMatrix () {
const screenWidth = this.gl.canvas.width;
const screenHeight = this.gl.canvas.height;
const displayRatio = this.setting.displayRatio;
let logoW = this.logoImage.width / 2;
let logoH = this.logoImage.height / 2;
let textW = this.textImage.width / 2;
let textH = this.textImage.height / 2;
if (screenWidth < screenHeight) {
logoW = screenWidth / 2 * displayRatio;
logoH = logoW / (this.logoImage.width / this.logoImage.height);
textW = screenWidth / 2 * 0.5;
textH = textW / (this.textImage.width / this.textImage.height);
} else {
logoW = screenHeight / 2 * displayRatio;
logoH = logoW / (this.logoImage.width / this.logoImage.height);
textW = screenHeight / 2 * 0.5;
textH = textW / (this.textImage.width / this.textImage.height);
}
this.logoMat33[0] = logoW;
this.logoMat33[4] = logoH;
this.logoMat33[6] = screenWidth / 2;
this.logoMat33[7] = screenHeight / 2;
this.textMat33[0] = textW;
this.textMat33[4] = textH;
this.textMat33[6] = screenWidth / 2;
this.textMat33[7] = screenHeight * 0.9;
}
private initProgram () {
const gl = this.gl;
this.vertexShader = createShader(gl, gl.VERTEX_SHADER, vs)!;
this.fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fs)!;
this.program = createProgram(gl, this.vertexShader, this.fragmentShader)!;
}
private initBuffer () {
const gl = this.gl;
gl.useProgram(this.program);
this.positionBuffer = gl.createBuffer() as WebGLBuffer;
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW);
this.texcoordBuffer = gl.createBuffer() as WebGLBuffer;
gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.texcoords, gl.STATIC_DRAW);
var positionLocation = gl.getAttribLocation(this.program, "a_position");
gl.enableVertexAttribArray(positionLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
// Tell the position attribute how to get data out of positionBuffer (ARRAY_BUFFER)
var size = 2; // 2 components per iteration
var type = gl.FLOAT; // the data is 32bit floats
var normalize = false; // don't normalize the data
var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position
var offset = 0; // start at the beginning of the buffer
gl.vertexAttribPointer(positionLocation, size, type, normalize, stride, offset);
var texcoordLocation = gl.getAttribLocation(this.program, "a_texCoord");
gl.enableVertexAttribArray(texcoordLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer);
var size = 2; // 2 components per iteration
var type = gl.FLOAT; // the data is 32bit floats
var normalize = false; // don't normalize the data
var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position
var offset = 0; // start at the beginning of the buffer
gl.vertexAttribPointer(texcoordLocation, size, type, normalize, stride, offset);
}
private initTexture () {
const gl = this.gl;
this.textureLogo = gl.createTexture() as WebGLTexture;
gl.bindTexture(gl.TEXTURE_2D, this.textureLogo);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.logoImage);
this.textureText = gl.createTexture() as WebGLTexture;
gl.bindTexture(gl.TEXTURE_2D, this.textureText);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.textImage);
}
private initState () {
const gl = this.gl;
gl.useProgram(this.program);
var resolutionLocation = gl.getUniformLocation(this.program, "u_resolution");
gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}
private frame (time: number) {
const gl = this.gl;
const program = this.program;
const textureLogo = this.textureLogo;
const textureText = this.textureText;
const clearColor = this.setting.clearColor;
const logoMat33 = this.logoMat33;
const textMat33 = this.textMat33;
if (this.startTime < 0) { this.startTime = time; }
const elapsedTime = time - this.startTime;
const precent = clamp01(elapsedTime / this.setting.totalTime);
const alpha = easing.cubicOut(precent);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a);
gl.depthMask(true);
gl.clearDepth(1);
gl.clearStencil(0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.useProgram(this.program);
let location = gl.getUniformLocation(program, "u_alpha");
gl.uniform1f(location, alpha);
location = gl.getUniformLocation(program, "u_worldMat");
gl.uniformMatrix3fv(location, false, logoMat33);
gl.bindTexture(gl.TEXTURE_2D, textureLogo);
gl.drawArrays(gl.TRIANGLES, 0, 6);
if (this.setting.displayWatermark) {
gl.uniformMatrix3fv(location, false, textMat33);
gl.bindTexture(gl.TEXTURE_2D, textureText);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
if (elapsedTime > this.setting.totalTime) {
this.splashFinish = true;
}
}
private destroy () {
delete SplashScreenWebgl._ins;
this.gl.deleteProgram(this.program);
this.gl.deleteShader(this.vertexShader);
this.gl.deleteShader(this.fragmentShader);
this.gl.deleteBuffer(this.positionBuffer);
this.gl.deleteBuffer(this.texcoordBuffer);
this.gl.deleteTexture(this.textureLogo);
this.gl.deleteTexture(this.textureText);
}
private static _ins: SplashScreenWebgl;
public static get instance () {
if (SplashScreenWebgl._ins == null) {
SplashScreenWebgl._ins = new SplashScreenWebgl();
}
return SplashScreenWebgl._ins;
}
private constructor () { };
}
cc.internal.SplashScreenWebgl = SplashScreenWebgl;