LayaBox引擎源碼閱讀筆記(二、從入口函數開始學習)

上篇博客已經把Laya整個框架梳理了一遍,本編博客我們就開始從Laya的入口學起。

  如果我們需要跑起來我們的工程,首先需要將工程編譯,Laya默認採用的是Gulp進行編譯,配置文件寫在了gulpfile.js

如果有同學對於Gulp感興趣可以去百度查相關資料,掌握幾個自動化編譯工具我認爲還是很重要的東西。

  我們工程的入口函數一般爲Main.ts,這裏面不光會處理我們自己的邏輯初始化,也會初始化Laya在我們工程上需要的東西。

在初始化後Laya中的瀏覽器代理Browser會去監聽瀏覽器的幀循環函數,這裏就是我們程序的主要更新源頭了

Browser.window.requestAnimationFrame(loop);
function loop(stamp){
    Laya.stage._loop();
    Browser.window.requestAnimationFrame(loop);
}

所有幀處理邏輯都集中在Laya.stage._loop函數之中而這個循環主要就是調用Stage中的render函數,這個函數處理了當前幀所有的邏輯與渲染提交。

var __proto=Stage.prototype;
/**@inheritDoc */
__proto.render=function(context,x,y){
	//1.解析獲得當前更新模式:sleep mouse fast三種模式	
	if (this._frameRate==="sleep"){
		var now=Browser.now();
		if (now-this._frameStartTime >=1000)this._frameStartTime=now;
		else return;
	}
	//2.renderCount渲染累計
	this._renderCount++;
	//3.stage不顯示 只更新邏輯
	if (!this._visible){
		if (this._renderCount % 5===0){
			CallLater.I._update();
			Stat.loopCount++;
			Laya.systemTimer._update();
			Laya.startTimer._update();
			Laya.physicsTimer._update();
			Laya.updateTimer._update();
			Laya.lateTimer._update();
			Laya.timer._update();
		}
		return;
	}
	this._frameStartTime=Browser.now();
	var frameMode=this._frameRate==="mouse" ? (((this._frameStartTime-this._mouseMoveTime)< 2000)? "fast" :"slow"):this._frameRate;
	var isFastMode=(frameMode!=="slow");
	var isDoubleLoop=(this._renderCount % 2===0);
	Stat.renderSlow=!isFastMode;
	//4.本次需要更新渲染就清空context
	if (isFastMode || isDoubleLoop){
		CallLater.I._update();
		Stat.loopCount++;
		if (!Render.isConchApp){
			if (Render.isWebGL && this.renderingEnabled){
				context.clear();
				_super.prototype.render.call(this,context,x,y);
				Stat._show && Stat._sp && Stat._sp.render(context,x,y);
			}
		}
	}
	//5.渲染,重置顏色 再將指令flush
	if (this.renderingEnabled && (isFastMode || !isDoubleLoop)){
		if (Render.isWebGL){
			RunDriver.clear(this._bgColor);
			context.flush();
			VectorGraphManager.instance && VectorGraphManager.getInstance().endDispose();
			}else {
			RunDriver.clear(this._bgColor);
			_super.prototype.render.call(this,context,x,y);
			Stat._show && Stat._sp && Stat._sp.render(context,x,y);
			if (Render.isConchApp)context.gl.commit();
		}
	}
	//6.更新邏輯
	Laya.systemTimer._update();
	Laya.startTimer._update();
	Laya.physicsTimer._update();
	Laya.updateTimer._update();
	Laya.lateTimer._update();
	Laya.timer._update();
}

從上面代碼可以看出更新主要分三步:清空畫布——提交渲染——更新邏輯

這裏的context是Stage持有的內容對象,在沒有啓用WebGL的情況下該對象爲CanvasRenderingContext2D實例,如果啓用WebGL後這個對象爲WebGLContext2D對象,x,y默認爲0,0 

在Laya2.0的index.html中一開始是不存在canvas標籤的,是在初始化時append上去的。

Render._mainCanvas.source.id = "layaCanvas";
Render._mainCanvas.source.width = width;
Render._mainCanvas.source.height = height;
if(laya.renders.Render.isConchApp){
	Browser.document.body.appendChild(Render._mainCanvas.source);
}else{
	Browser.container.appendChild(Render._mainCanvas.source);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章