2022-09-20 15:50:01 +00:00
const i18n = require ( 'LanguageData' ) ;
i18n . init ( window . language ) ; // languageID should be equal to the one we input in New Language ID input field
2022-09-23 08:42:44 +00:00
const collisions = require ( './modules/Collisions' ) ;
2022-09-24 04:01:50 +00:00
const RingBuffer = require ( './RingBuffer' ) ;
2022-09-23 08:42:44 +00:00
2022-09-20 15:50:01 +00:00
window . ALL _MAP _STATES = {
VISUAL : 0 , // For free dragging & zooming.
EDITING _BELONGING : 1 ,
SHOWING _MODAL _POPUP : 2 ,
} ;
window . ALL _BATTLE _STATES = {
WAITING : 0 ,
IN _BATTLE : 1 ,
IN _SETTLEMENT : 2 ,
IN _DISMISSAL : 3 ,
} ;
window . MAGIC _ROOM _DOWNSYNC _FRAME _ID = {
2022-09-24 04:01:50 +00:00
BATTLE _READY _TO _START : - 1 ,
2022-10-01 15:54:48 +00:00
BATTLE _START : 0
2022-09-20 15:50:01 +00:00
} ;
cc . Class ( {
extends : cc . Component ,
properties : {
canvasNode : {
type : cc . Node ,
default : null ,
} ,
tiledAnimPrefab : {
type : cc . Prefab ,
default : null ,
} ,
player1Prefab : {
type : cc . Prefab ,
default : null ,
} ,
player2Prefab : {
type : cc . Prefab ,
default : null ,
} ,
treasurePrefab : {
type : cc . Prefab ,
default : null ,
} ,
trapPrefab : {
type : cc . Prefab ,
default : null ,
} ,
speedShoePrefab : {
type : cc . Prefab ,
default : null ,
} ,
polygonBoundaryBarrierPrefab : {
type : cc . Prefab ,
default : null ,
} ,
keyboardInputControllerNode : {
type : cc . Node ,
default : null
} ,
joystickInputControllerNode : {
type : cc . Node ,
default : null
} ,
confirmLogoutPrefab : {
type : cc . Prefab ,
default : null
} ,
simplePressToGoDialogPrefab : {
type : cc . Prefab ,
default : null
} ,
boundRoomIdLabel : {
type : cc . Label ,
default : null
} ,
countdownLabel : {
type : cc . Label ,
default : null
} ,
trapBulletPrefab : {
type : cc . Prefab ,
default : null
} ,
resultPanelPrefab : {
type : cc . Prefab ,
default : null
} ,
gameRulePrefab : {
type : cc . Prefab ,
default : null
} ,
findingPlayerPrefab : {
type : cc . Prefab ,
default : null
} ,
countdownToBeginGamePrefab : {
type : cc . Prefab ,
default : null
} ,
playersInfoPrefab : {
type : cc . Prefab ,
default : null
} ,
guardTowerPrefab : {
type : cc . Prefab ,
default : null
} ,
forceBigEndianFloatingNumDecoding : {
default : false ,
} ,
backgroundMapTiledIns : {
type : cc . TiledMap ,
default : null
} ,
2022-09-21 09:22:34 +00:00
rollbackEstimatedDt : {
type : cc . Float ,
default : 1.0 / 60
} ,
2022-10-01 15:54:48 +00:00
rollbackEstimatedDtMillis : {
type : cc . Float ,
default : 1000.0 / 60
} ,
rollbackEstimatedDtToleranceMillis : {
2022-10-01 12:45:38 +00:00
type : cc . Float ,
2022-10-01 15:54:48 +00:00
default : 1.0 / 60
2022-10-01 12:45:38 +00:00
} ,
2022-09-24 04:01:50 +00:00
maxChasingRenderFramesPerUpdate : {
type : cc . Integer ,
2022-09-26 03:16:18 +00:00
default : 10
2022-09-21 15:59:05 +00:00
} ,
2022-09-20 15:50:01 +00:00
} ,
_inputFrameIdDebuggable ( inputFrameId ) {
return ( 0 == inputFrameId % 10 ) ;
} ,
2022-09-24 04:01:50 +00:00
_dumpToRenderCache : function ( roomDownsyncFrame ) {
2022-09-20 15:50:01 +00:00
const self = this ;
2022-09-24 04:01:50 +00:00
const minToKeepRenderFrameId = self . lastAllConfirmedRenderFrameId ;
2022-09-26 02:36:46 +00:00
while ( 0 < self . recentRenderCache . cnt && self . recentRenderCache . stFrameId < minToKeepRenderFrameId ) {
2022-09-24 04:01:50 +00:00
self . recentRenderCache . pop ( ) ;
2022-09-22 09:09:49 +00:00
}
2022-09-26 02:36:46 +00:00
if ( self . recentRenderCache . stFrameId < minToKeepRenderFrameId ) {
console . warn ( "Weird dumping of RENDER frame: self.renderFrame=" , self . renderFrame , ", self.recentInputCache=" , self . _stringifyRecentInputCache ( false ) , ", self.recentRenderCache=" , self . _stringifyRecentRenderCache ( false ) , ", self.lastAllConfirmedRenderFrameId=" , self . lastAllConfirmedRenderFrameId , ", self.lastAllConfirmedInputFrameId=" , self . lastAllConfirmedInputFrameId ) ;
}
2022-09-24 04:01:50 +00:00
const existing = self . recentRenderCache . getByFrameId ( roomDownsyncFrame . id ) ;
if ( null != existing ) {
existing . players = roomDownsyncFrame . players ;
existing . sentAt = roomDownsyncFrame . sentAt ;
existing . countdownNanos = roomDownsyncFrame . countdownNanos ;
existing . treasures = roomDownsyncFrame . treasures ;
existing . bullets = roomDownsyncFrame . bullets ;
existing . speedShoes = roomDownsyncFrame . speedShoes ;
existing . guardTowers = roomDownsyncFrame . guardTowers ;
existing . playerMetas = roomDownsyncFrame . playerMetas ;
} else {
self . recentRenderCache . put ( roomDownsyncFrame ) ;
2022-09-20 15:50:01 +00:00
}
} ,
_dumpToInputCache : function ( inputFrameDownsync ) {
const self = this ;
2022-09-26 02:36:46 +00:00
let minToKeepInputFrameId = self . _convertToInputFrameId ( self . lastAllConfirmedRenderFrameId , self . inputDelayFrames ) ; // [WARNING] This could be different from "self.lastAllConfirmedInputFrameId". We'd like to keep the corresponding inputFrame for "self.lastAllConfirmedRenderFrameId" such that a rollback could place "self.chaserRenderFrameId = self.lastAllConfirmedRenderFrameId" for the worst case incorrect prediction.
if ( minToKeepInputFrameId > self . lastAllConfirmedInputFrameId ) minToKeepInputFrameId = self . lastAllConfirmedInputFrameId ;
while ( 0 < self . recentInputCache . cnt && self . recentInputCache . stFrameId < minToKeepInputFrameId ) {
2022-09-24 04:01:50 +00:00
self . recentInputCache . pop ( ) ;
2022-09-22 09:09:49 +00:00
}
2022-09-26 02:36:46 +00:00
if ( self . recentInputCache . stFrameId < minToKeepInputFrameId ) {
console . warn ( "Weird dumping of INPUT frame: self.renderFrame=" , self . renderFrame , ", self.recentInputCache=" , self . _stringifyRecentInputCache ( false ) , ", self.recentRenderCache=" , self . _stringifyRecentRenderCache ( false ) , ", self.lastAllConfirmedRenderFrameId=" , self . lastAllConfirmedRenderFrameId , ", self.lastAllConfirmedInputFrameId=" , self . lastAllConfirmedInputFrameId ) ;
}
2022-09-24 04:01:50 +00:00
const existing = self . recentInputCache . getByFrameId ( inputFrameDownsync . inputFrameId ) ;
if ( null != existing ) {
existing . inputList = inputFrameDownsync . inputList ;
existing . confirmedList = inputFrameDownsync . confirmedList ;
} else {
self . recentInputCache . put ( inputFrameDownsync ) ;
2022-09-20 15:50:01 +00:00
}
} ,
_convertToInputFrameId ( renderFrameId , inputDelayFrames ) {
if ( renderFrameId < inputDelayFrames ) return 0 ;
2022-09-21 15:59:05 +00:00
return ( ( renderFrameId - inputDelayFrames ) >> this . inputScaleFrames ) ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-29 04:21:04 +00:00
_convertToFirstUsedRenderFrameId ( inputFrameId , inputDelayFrames ) {
2022-09-21 15:59:05 +00:00
return ( ( inputFrameId << this . inputScaleFrames ) + inputDelayFrames ) ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-29 04:21:04 +00:00
shouldGenerateInputFrameUpsync ( renderFrameId ) {
2022-09-24 04:01:50 +00:00
return ( ( renderFrameId & ( ( 1 << this . inputScaleFrames ) - 1 ) ) == 0 ) ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
_allConfirmed ( confirmedList ) {
return ( confirmedList + 1 ) == ( 1 << this . playerRichInfoDict . size ) ;
} ,
2022-09-20 15:50:01 +00:00
_generateInputFrameUpsync ( inputFrameId ) {
2022-09-24 04:01:50 +00:00
const self = this ;
2022-09-20 15:50:01 +00:00
if (
2022-09-24 04:01:50 +00:00
null == self . ctrl ||
null == self . selfPlayerInfo
2022-09-20 15:50:01 +00:00
) {
return [ null , null ] ;
}
2022-09-24 04:01:50 +00:00
const joinIndex = self . selfPlayerInfo . joinIndex ;
const discreteDir = self . ctrl . getDiscretizedDirection ( ) ;
const previousInputFrameDownsyncWithPrediction = self . getCachedInputFrameDownsyncWithPrediction ( inputFrameId ) ;
const prefabbedInputList = ( null == previousInputFrameDownsyncWithPrediction ? new Array ( self . playerRichInfoDict . size ) . fill ( 0 ) : previousInputFrameDownsyncWithPrediction . inputList . slice ( ) ) ;
prefabbedInputList [ ( joinIndex - 1 ) ] = discreteDir . encodedIdx ;
const prefabbedInputFrameDownsync = {
inputFrameId : inputFrameId ,
inputList : prefabbedInputList ,
confirmedList : ( 1 << ( self . selfPlayerInfo . joinIndex - 1 ) )
2022-09-20 15:50:01 +00:00
} ;
2022-09-24 04:01:50 +00:00
self . _dumpToInputCache ( prefabbedInputFrameDownsync ) ; // A prefabbed inputFrame, would certainly be adding a new inputFrame to the cache, because server only downsyncs "all-confirmed inputFrames"
2022-09-20 15:50:01 +00:00
2022-09-24 04:01:50 +00:00
const previousSelfInput = ( null == previousInputFrameDownsyncWithPrediction ? null : previousInputFrameDownsyncWithPrediction . inputList [ joinIndex - 1 ] ) ;
return [ previousSelfInput , discreteDir . encodedIdx ] ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
shouldSendInputFrameUpsyncBatch ( prevSelfInput , currSelfInput , lastUpsyncInputFrameId , currInputFrameId ) {
2022-09-20 15:50:01 +00:00
/ *
2022-10-01 07:14:05 +00:00
For a 2 - player - battle , this "shouldUpsyncForEarlyAllConfirmedOnBackend" can be omitted , however for more players in a same battle , to avoid a "long time non-moving player" jamming the downsync of other moving players , we should use this flag .
When backend implements the "force confirmation" feature , we can have "false == shouldUpsyncForEarlyAllConfirmedOnBackend" all the time as well !
2022-09-20 15:50:01 +00:00
* /
if ( null == currSelfInput ) return false ;
2022-10-01 07:14:05 +00:00
const shouldUpsyncForEarlyAllConfirmedOnBackend = ( currInputFrameId - lastUpsyncInputFrameId >= this . inputFrameUpsyncDelayTolerance ) ;
return shouldUpsyncForEarlyAllConfirmedOnBackend || ( prevSelfInput != currSelfInput ) ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
sendInputFrameUpsyncBatch ( inputFrameId ) {
2022-09-20 15:50:01 +00:00
// [WARNING] Why not just send the latest input? Because different player would have a different "inputFrameId" of changing its last input, and that could make the server not recognizing any "all-confirmed inputFrame"!
2022-09-24 04:01:50 +00:00
const self = this ;
2022-09-20 15:50:01 +00:00
let inputFrameUpsyncBatch = [ ] ;
2022-09-24 04:01:50 +00:00
for ( let i = self . lastUpsyncInputFrameId + 1 ; i <= inputFrameId ; ++ i ) {
const inputFrameDownsync = self . recentInputCache . getByFrameId ( i ) ;
if ( null == inputFrameDownsync ) {
console . warn ( "sendInputFrameUpsyncBatch: recentInputCache is NOT having inputFrameId=" , i , "; recentInputCache=" , self . _stringifyRecentInputCache ( false ) ) ;
} else {
const inputFrameUpsync = {
inputFrameId : i ,
encodedDir : inputFrameDownsync . inputList [ self . selfPlayerInfo . joinIndex - 1 ] ,
} ;
inputFrameUpsyncBatch . push ( inputFrameUpsync ) ;
}
2022-09-20 15:50:01 +00:00
}
const reqData = window . WsReq . encode ( {
msgId : Date . now ( ) ,
2022-09-24 04:01:50 +00:00
playerId : self . selfPlayerInfo . id ,
2022-09-20 15:50:01 +00:00
act : window . UPSYNC _MSG _ACT _PLAYER _CMD ,
2022-09-24 04:01:50 +00:00
joinIndex : self . selfPlayerInfo . joinIndex ,
ackingFrameId : self . lastAllConfirmedRenderFrameId ,
ackingInputFrameId : self . lastAllConfirmedInputFrameId ,
2022-09-20 15:50:01 +00:00
inputFrameUpsyncBatch : inputFrameUpsyncBatch ,
} ) . finish ( ) ;
window . sendSafely ( reqData ) ;
2022-09-24 04:01:50 +00:00
self . lastUpsyncInputFrameId = inputFrameId ;
2022-09-20 15:50:01 +00:00
} ,
onEnable ( ) {
cc . log ( "+++++++ Map onEnable()" ) ;
} ,
onDisable ( ) {
cc . log ( "+++++++ Map onDisable()" ) ;
} ,
onDestroy ( ) {
const self = this ;
console . warn ( "+++++++ Map onDestroy()" ) ;
if ( null == self . battleState || ALL _BATTLE _STATES . WAITING == self . battleState ) {
window . clearBoundRoomIdInBothVolatileAndPersistentStorage ( ) ;
}
if ( null != window . handleRoomDownsyncFrame ) {
window . handleRoomDownsyncFrame = null ;
}
if ( null != window . handleInputFrameDownsyncBatch ) {
window . handleInputFrameDownsyncBatch = null ;
}
if ( null != window . handleBattleColliderInfo ) {
window . handleBattleColliderInfo = null ;
}
if ( null != window . handleClientSessionCloseOrError ) {
window . handleClientSessionCloseOrError = null ;
}
} ,
popupSimplePressToGo ( labelString , hideYesButton ) {
const self = this ;
self . state = ALL _MAP _STATES . SHOWING _MODAL _POPUP ;
const canvasNode = self . canvasNode ;
const simplePressToGoDialogNode = cc . instantiate ( self . simplePressToGoDialogPrefab ) ;
simplePressToGoDialogNode . setPosition ( cc . v2 ( 0 , 0 ) ) ;
simplePressToGoDialogNode . setScale ( 1 / canvasNode . scale ) ;
const simplePressToGoDialogScriptIns = simplePressToGoDialogNode . getComponent ( "SimplePressToGoDialog" ) ;
const yesButton = simplePressToGoDialogNode . getChildByName ( "Yes" ) ;
const postDismissalByYes = ( ) => {
self . transitToState ( ALL _MAP _STATES . VISUAL ) ;
canvasNode . removeChild ( simplePressToGoDialogNode ) ;
}
simplePressToGoDialogNode . getChildByName ( "Hint" ) . getComponent ( cc . Label ) . string = labelString ;
yesButton . once ( "click" , simplePressToGoDialogScriptIns . dismissDialog . bind ( simplePressToGoDialogScriptIns , postDismissalByYes ) ) ;
yesButton . getChildByName ( "Label" ) . getComponent ( cc . Label ) . string = "OK" ;
if ( true == hideYesButton ) {
yesButton . active = false ;
}
self . transitToState ( ALL _MAP _STATES . SHOWING _MODAL _POPUP ) ;
safelyAddChild ( self . widgetsAboveAllNode , simplePressToGoDialogNode ) ;
setLocalZOrder ( simplePressToGoDialogNode , 20 ) ;
return simplePressToGoDialogNode ;
} ,
alertForGoingBackToLoginScene ( labelString , mapIns , shouldRetainBoundRoomIdInBothVolatileAndPersistentStorage ) {
const millisToGo = 3000 ;
mapIns . popupSimplePressToGo ( cc . js . formatStr ( "%s will logout in %s seconds." , labelString , millisToGo / 1000 ) ) ;
setTimeout ( ( ) => {
mapIns . logout ( false , shouldRetainBoundRoomIdInBothVolatileAndPersistentStorage ) ;
} , millisToGo ) ;
} ,
_resetCurrentMatch ( ) {
const self = this ;
const mapNode = self . node ;
const canvasNode = mapNode . parent ;
self . countdownLabel . string = "" ;
self . countdownNanos = null ;
// Clearing previous info of all players. [BEGINS]
2022-09-24 04:01:50 +00:00
self . collisionPlayerIndexPrefix = ( 1 << 17 ) ; // For tracking the movements of players
2022-09-22 04:45:17 +00:00
if ( null != self . playerRichInfoDict ) {
self . playerRichInfoDict . forEach ( ( playerRichInfo , playerId ) => {
if ( playerRichInfo . node . parent ) {
playerRichInfo . node . parent . removeChild ( playerRichInfo . node ) ;
2022-09-20 15:50:01 +00:00
}
2022-09-22 04:45:17 +00:00
} ) ;
}
self . playerRichInfoDict = new Map ( ) ;
2022-09-20 15:50:01 +00:00
// Clearing previous info of all players. [ENDS]
self . renderFrameId = 0 ; // After battle started
2022-09-24 04:01:50 +00:00
self . lastAllConfirmedRenderFrameId = - 1 ;
self . lastAllConfirmedInputFrameId = - 1 ;
self . chaserRenderFrameId = - 1 ; // at any moment, "lastAllConfirmedRenderFrameId <= chaserRenderFrameId <= renderFrameId", but "chaserRenderFrameId" would fluctuate according to "handleInputFrameDownsyncBatch"
2022-10-01 15:54:48 +00:00
self . inputDelayFrames = 4 ;
2022-09-22 09:09:49 +00:00
self . inputScaleFrames = 2 ;
2022-09-20 15:50:01 +00:00
self . lastUpsyncInputFrameId = - 1 ;
2022-09-22 09:09:49 +00:00
self . inputFrameUpsyncDelayTolerance = 2 ;
2022-09-20 15:50:01 +00:00
2022-09-24 04:01:50 +00:00
self . recentRenderCache = new RingBuffer ( 1024 ) ;
2022-09-20 15:50:01 +00:00
self . selfPlayerInfo = null ; // This field is kept for distinguishing "self" and "others".
2022-09-24 04:01:50 +00:00
self . recentInputCache = new RingBuffer ( 1024 ) ;
2022-09-23 08:42:44 +00:00
self . latestCollisionSys = new collisions . Collisions ( ) ;
self . chaserCollisionSys = new collisions . Collisions ( ) ;
2022-09-24 04:01:50 +00:00
self . collisionBarrierIndexPrefix = ( 1 << 16 ) ; // For tracking the movements of barriers, though not yet actually used
self . latestCollisionSysMap = new Map ( ) ;
self . chaserCollisionSysMap = new Map ( ) ;
2022-09-21 15:59:05 +00:00
2022-09-20 15:50:01 +00:00
self . transitToState ( ALL _MAP _STATES . VISUAL ) ;
self . battleState = ALL _BATTLE _STATES . WAITING ;
if ( self . findingPlayerNode ) {
const findingPlayerScriptIns = self . findingPlayerNode . getComponent ( "FindingPlayer" ) ;
findingPlayerScriptIns . init ( ) ;
}
safelyAddChild ( self . widgetsAboveAllNode , self . playersInfoNode ) ;
safelyAddChild ( self . widgetsAboveAllNode , self . findingPlayerNode ) ;
} ,
onLoad ( ) {
const self = this ;
window . mapIns = self ;
window . forceBigEndianFloatingNumDecoding = self . forceBigEndianFloatingNumDecoding ;
console . warn ( "+++++++ Map onLoad()" ) ;
window . handleClientSessionCloseOrError = function ( ) {
console . warn ( '+++++++ Common handleClientSessionCloseOrError()' ) ;
if ( ALL _BATTLE _STATES . IN _SETTLEMENT == self . battleState ) { //如果是游戏时间结束引起的断连
console . log ( "游戏结束引起的断连, 不需要回到登录页面" ) ;
} else {
console . warn ( "意外断连,即将回到登录页面" ) ;
window . clearLocalStorageAndBackToLoginScene ( true ) ;
}
} ;
const mapNode = self . node ;
const canvasNode = mapNode . parent ;
2022-09-23 08:42:44 +00:00
cc . director . getCollisionManager ( ) . enabled = false ;
2022-09-20 15:50:01 +00:00
// self.musicEffectManagerScriptIns = self.node.getComponent("MusicEffectManager");
self . musicEffectManagerScriptIns = null ;
/** Init required prefab started. */
self . confirmLogoutNode = cc . instantiate ( self . confirmLogoutPrefab ) ;
self . confirmLogoutNode . getComponent ( "ConfirmLogout" ) . mapNode = self . node ;
// Initializes Result panel.
self . resultPanelNode = cc . instantiate ( self . resultPanelPrefab ) ;
self . resultPanelNode . width = self . canvasNode . width ;
self . resultPanelNode . height = self . canvasNode . height ;
const resultPanelScriptIns = self . resultPanelNode . getComponent ( "ResultPanel" ) ;
resultPanelScriptIns . mapScriptIns = self ;
resultPanelScriptIns . onAgainClicked = ( ) => {
self . battleState = ALL _BATTLE _STATES . WAITING ;
window . clearBoundRoomIdInBothVolatileAndPersistentStorage ( ) ;
window . initPersistentSessionClient ( self . initAfterWSConnected , null /* Deliberately NOT passing in any `expectedRoomId`. -- YFLu */ ) ;
} ;
resultPanelScriptIns . onCloseDelegate = ( ) => {
} ;
self . gameRuleNode = cc . instantiate ( self . gameRulePrefab ) ;
self . gameRuleNode . width = self . canvasNode . width ;
self . gameRuleNode . height = self . canvasNode . height ;
self . gameRuleScriptIns = self . gameRuleNode . getComponent ( "GameRule" ) ;
self . gameRuleScriptIns . mapNode = self . node ;
self . findingPlayerNode = cc . instantiate ( self . findingPlayerPrefab ) ;
self . findingPlayerNode . width = self . canvasNode . width ;
self . findingPlayerNode . height = self . canvasNode . height ;
const findingPlayerScriptIns = self . findingPlayerNode . getComponent ( "FindingPlayer" ) ;
findingPlayerScriptIns . init ( ) ;
self . playersInfoNode = cc . instantiate ( self . playersInfoPrefab ) ;
self . countdownToBeginGameNode = cc . instantiate ( self . countdownToBeginGamePrefab ) ;
self . countdownToBeginGameNode . width = self . canvasNode . width ;
self . countdownToBeginGameNode . height = self . canvasNode . height ;
self . mainCameraNode = canvasNode . getChildByName ( "Main Camera" ) ;
self . mainCamera = self . mainCameraNode . getComponent ( cc . Camera ) ;
for ( let child of self . mainCameraNode . children ) {
child . setScale ( 1 / self . mainCamera . zoomRatio ) ;
}
self . widgetsAboveAllNode = self . mainCameraNode . getChildByName ( "WidgetsAboveAll" ) ;
self . mainCameraNode . setPosition ( cc . v2 ( ) ) ;
/** Init required prefab ended. */
self . clientUpsyncFps = 60 ;
window . handleBattleColliderInfo = function ( parsedBattleColliderInfo ) {
self . battleColliderInfo = parsedBattleColliderInfo ;
const tiledMapIns = self . node . getComponent ( cc . TiledMap ) ;
const fullPathOfTmxFile = cc . js . formatStr ( "map/%s/map" , parsedBattleColliderInfo . stageName ) ;
cc . loader . loadRes ( fullPathOfTmxFile , cc . TiledMapAsset , ( err , tmxAsset ) => {
if ( null != err ) {
console . error ( err ) ;
return ;
}
/ *
[ WARNING ]
- The order of the following statements is important , because we should have finished "_resetCurrentMatch" before the first "RoomDownsyncFrame" .
2022-09-24 04:01:50 +00:00
- It ' s important to assign new "tmxAsset" before "extractBoundaryObjects" , to ensure that the correct tilesets are used .
2022-09-20 15:50:01 +00:00
- To ensure clearance , put destruction of the "cc.TiledMap" component preceding that of "mapNode.destroyAllChildren()" .
* /
tiledMapIns . tmxAsset = null ;
mapNode . removeAllChildren ( ) ;
self . _resetCurrentMatch ( ) ;
tiledMapIns . tmxAsset = tmxAsset ;
const newMapSize = tiledMapIns . getMapSize ( ) ;
const newTileSize = tiledMapIns . getTileSize ( ) ;
self . node . setContentSize ( newMapSize . width * newTileSize . width , newMapSize . height * newTileSize . height ) ;
self . node . setPosition ( cc . v2 ( 0 , 0 ) ) ;
/ *
* Deliberately hiding "ImageLayer" s . This dirty fix is specific to "CocosCreator v2.2.1" , where it got back the rendering capability of "ImageLayer of Tiled" , yet made incorrectly . In this game our "markers of ImageLayers" are rendered by dedicated prefabs with associated colliders .
*
* -- YFLu , 2020 - 01 - 23
* /
const existingImageLayers = tiledMapIns . getObjectGroups ( ) ;
for ( let singleImageLayer of existingImageLayers ) {
singleImageLayer . node . opacity = 0 ;
}
2022-09-24 04:01:50 +00:00
let barrierIdCounter = 0 ;
2022-09-20 15:50:01 +00:00
const boundaryObjs = tileCollisionManager . extractBoundaryObjects ( self . node ) ;
2022-09-24 04:01:50 +00:00
for ( let boundaryObj of boundaryObjs . barriers ) {
const x0 = boundaryObj [ 0 ] . x , y0 = boundaryObj [ 0 ] . y ;
let pts = [ ] ;
// TODO: Simplify this redundant coordinate conversion within "extractBoundaryObjects", but since this routine is only called once per battle, not urgent.
for ( let i = 0 ; i < boundaryObj . length ; ++ i ) {
pts . push ( [ boundaryObj [ i ] . x - x0 , boundaryObj [ i ] . y - y0 ] ) ;
}
const newBarrierLatest = self . latestCollisionSys . createPolygon ( x0 , y0 , pts ) ;
const newBarrierChaser = self . chaserCollisionSys . createPolygon ( x0 , y0 , pts ) ;
++ barrierIdCounter ;
const collisionBarrierIndex = ( self . collisionBarrierIndexPrefix + barrierIdCounter ) ;
self . latestCollisionSysMap . set ( collisionBarrierIndex , newBarrierLatest ) ;
self . chaserCollisionSysMap . set ( collisionBarrierIndex , newBarrierChaser ) ;
}
2022-09-20 15:50:01 +00:00
self . selfPlayerInfo = JSON . parse ( cc . sys . localStorage . getItem ( 'selfPlayer' ) ) ;
Object . assign ( self . selfPlayerInfo , {
id : self . selfPlayerInfo . playerId
} ) ;
const fullPathOfBackgroundMapTmxFile = cc . js . formatStr ( "map/%s/BackgroundMap/map" , parsedBattleColliderInfo . stageName ) ;
cc . loader . loadRes ( fullPathOfBackgroundMapTmxFile , cc . TiledMapAsset , ( err , backgroundMapTmxAsset ) => {
if ( null != err ) {
console . error ( err ) ;
return ;
}
self . backgroundMapTiledIns . tmxAsset = null ;
self . backgroundMapTiledIns . node . removeAllChildren ( ) ;
self . backgroundMapTiledIns . tmxAsset = backgroundMapTmxAsset ;
const newBackgroundMapSize = self . backgroundMapTiledIns . getMapSize ( ) ;
const newBackgroundMapTileSize = self . backgroundMapTiledIns . getTileSize ( ) ;
self . backgroundMapTiledIns . node . setContentSize ( newBackgroundMapSize . width * newBackgroundMapTileSize . width , newBackgroundMapSize . height * newBackgroundMapTileSize . height ) ;
self . backgroundMapTiledIns . node . setPosition ( cc . v2 ( 0 , 0 ) ) ;
const reqData = window . WsReq . encode ( {
msgId : Date . now ( ) ,
act : window . UPSYNC _MSG _ACT _PLAYER _COLLIDER _ACK ,
} ) . finish ( ) ;
window . sendSafely ( reqData ) ;
} ) ;
} ) ;
} ;
self . initAfterWSConnected = ( ) => {
const self = window . mapIns ;
self . hideGameRuleNode ( ) ;
self . transitToState ( ALL _MAP _STATES . WAITING ) ;
self . _inputControlEnabled = false ;
2022-09-26 02:36:46 +00:00
let findingPlayerScriptIns = self . findingPlayerNode . getComponent ( "FindingPlayer" ) ;
2022-10-01 15:54:48 +00:00
window . handlePlayerAdded = function ( rdf ) {
// Update the "finding player" GUI and show it if not previously present
if ( ! self . findingPlayerNode . parent ) {
self . showPopupInCanvas ( self . findingPlayerNode ) ;
2022-09-20 15:50:01 +00:00
}
2022-10-01 15:54:48 +00:00
findingPlayerScriptIns . updatePlayersInfo ( rdf . playerMetas ) ;
} ;
2022-09-26 02:36:46 +00:00
2022-10-01 15:54:48 +00:00
window . handleRoomDownsyncFrame = function ( rdf ) {
2022-09-26 02:36:46 +00:00
const frameId = rdf . id ;
2022-09-20 15:50:01 +00:00
// Right upon establishment of the "PersistentSessionClient", we should receive an initial signal "BattleColliderInfo" earlier than any "RoomDownsyncFrame" containing "PlayerMeta" data.
2022-10-01 15:54:48 +00:00
switch ( frameId ) {
2022-09-24 04:01:50 +00:00
case window . MAGIC _ROOM _DOWNSYNC _FRAME _ID . BATTLE _READY _TO _START :
2022-09-26 02:36:46 +00:00
self . onBattleReadyToStart ( rdf . playerMetas , false ) ;
2022-09-24 04:01:50 +00:00
return ;
case window . MAGIC _ROOM _DOWNSYNC _FRAME _ID . BATTLE _START :
2022-10-01 07:14:05 +00:00
self . onBattleStartedOrResynced ( rdf ) ;
2022-09-24 04:01:50 +00:00
return ;
2022-09-20 15:50:01 +00:00
}
// TODO: Inject a NetworkDoctor as introduced in https://app.yinxiang.com/shard/s61/nl/13267014/5c575124-01db-419b-9c02-ec81f78c6ddc/.
} ;
window . handleInputFrameDownsyncBatch = function ( batch ) {
if ( ALL _BATTLE _STATES . IN _BATTLE != self . battleState
&& ALL _BATTLE _STATES . IN _SETTLEMENT != self . battleState ) {
return ;
}
2022-09-24 04:01:50 +00:00
// console.log("Received inputFrameDownsyncBatch=", batch, ", now correspondingLastLocalInputFrame=", self.recentInputCache.getByFrameId(batch[batch.length-1].inputFrameId));
2022-09-21 09:22:34 +00:00
let firstPredictedYetIncorrectInputFrameId = null ;
let firstPredictedYetIncorrectInputFrameJoinIndex = null ;
2022-09-20 15:50:01 +00:00
for ( let k in batch ) {
const inputFrameDownsync = batch [ k ] ;
const inputFrameDownsyncId = inputFrameDownsync . inputFrameId ;
2022-09-24 04:01:50 +00:00
const localInputFrame = self . recentInputCache . getByFrameId ( inputFrameDownsyncId ) ;
2022-09-20 15:50:01 +00:00
if ( null == localInputFrame ) {
console . warn ( "handleInputFrameDownsyncBatch: recentInputCache is NOT having inputFrameDownsyncId=" , inputFrameDownsyncId , "; now recentInputCache=" , self . _stringifyRecentInputCache ( false ) ) ;
} else {
2022-09-21 09:22:34 +00:00
if ( null == firstPredictedYetIncorrectInputFrameId ) {
2022-09-20 15:50:01 +00:00
for ( let i in localInputFrame . inputList ) {
if ( localInputFrame . inputList [ i ] != inputFrameDownsync . inputList [ i ] ) {
firstPredictedYetIncorrectInputFrameId = inputFrameDownsyncId ;
firstPredictedYetIncorrectInputFrameJoinIndex = ( parseInt ( i ) + 1 ) ;
break ;
}
}
}
}
2022-09-24 04:01:50 +00:00
self . lastAllConfirmedInputFrameId = inputFrameDownsyncId ;
2022-09-20 15:50:01 +00:00
self . _dumpToInputCache ( inputFrameDownsync ) ;
}
2022-09-21 09:22:34 +00:00
if ( null != firstPredictedYetIncorrectInputFrameId ) {
2022-09-20 15:50:01 +00:00
const inputFrameId1 = firstPredictedYetIncorrectInputFrameId ;
2022-09-29 04:21:04 +00:00
const renderFrameId1 = self . _convertToFirstUsedRenderFrameId ( inputFrameId1 , self . inputDelayFrames ) ; // a.k.a. "firstRenderFrameIdUsingIncorrectInputFrameId"
2022-09-25 12:48:09 +00:00
if ( renderFrameId1 < self . renderFrameId ) {
2022-09-24 04:01:50 +00:00
/ *
A typical case is as follows .
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2022-09-25 12:48:09 +00:00
[ self . lastAllConfirmedRenderFrameId ] : 22
2022-09-24 04:01:50 +00:00
2022-09-25 12:48:09 +00:00
< renderFrameId1 > : 36
2022-09-24 04:01:50 +00:00
2022-09-21 15:59:05 +00:00
2022-09-25 12:48:09 +00:00
< self . chaserRenderFrameId > : 62
2022-09-24 04:01:50 +00:00
2022-09-25 12:48:09 +00:00
[ self . renderFrameId ] : 64
2022-09-24 04:01:50 +00:00
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
* /
2022-09-25 12:48:09 +00:00
if ( renderFrameId1 < self . chaserRenderFrameId ) {
2022-09-25 15:21:12 +00:00
// The actual rollback-and-chase would later be executed in update(dt).
2022-09-25 12:48:09 +00:00
console . warn ( "Mismatched input detected, resetting chaserRenderFrameId: inputFrameId1:" , inputFrameId1 , ", renderFrameId1:" , renderFrameId1 , ", chaserRenderFrameId before reset: " , self . chaserRenderFrameId ) ;
self . chaserRenderFrameId = renderFrameId1 ;
} else {
// Deliberately left blank, chasing is ongoing.
}
2022-09-20 15:50:01 +00:00
} else {
2022-09-25 12:48:09 +00:00
// No need to rollback when "renderFrameId1 == self.renderFrameId", because the "corresponding delayedInputFrame for renderFrameId2" is NOT YET EXECUTED BY NOW, it just went through "++self.renderFrameId" in "update(dt)" and javascript-runtime is mostly single-threaded in our programmable range.
2022-09-20 15:50:01 +00:00
}
}
} ;
}
// The player is now viewing "self.gameRuleNode" with button(s) to start an actual battle. -- YFLu
const expectedRoomId = window . getExpectedRoomIdSync ( ) ;
const boundRoomId = window . getBoundRoomIdFromPersistentStorage ( ) ;
console . warn ( "Map.onLoad, expectedRoomId == " , expectedRoomId , ", boundRoomId == " , boundRoomId ) ;
if ( null != expectedRoomId ) {
self . disableGameRuleNode ( ) ;
// The player is now possibly viewing "self.gameRuleNode" with no button, and should wait for `self.initAfterWSConnected` to be called.
self . battleState = ALL _BATTLE _STATES . WAITING ;
window . initPersistentSessionClient ( self . initAfterWSConnected , expectedRoomId ) ;
} else if ( null != boundRoomId ) {
self . disableGameRuleNode ( ) ;
self . battleState = ALL _BATTLE _STATES . WAITING ;
window . initPersistentSessionClient ( self . initAfterWSConnected , expectedRoomId ) ;
} else {
self . showPopupInCanvas ( self . gameRuleNode ) ;
// Deliberately left blank. -- YFLu
}
} ,
disableGameRuleNode ( ) {
const self = window . mapIns ;
if ( null == self . gameRuleNode ) {
return ;
}
if ( null == self . gameRuleScriptIns ) {
return ;
}
if ( null == self . gameRuleScriptIns . modeButton ) {
return ;
}
self . gameRuleScriptIns . modeButton . active = false ;
} ,
hideGameRuleNode ( ) {
const self = window . mapIns ;
if ( null == self . gameRuleNode ) {
return ;
}
self . gameRuleNode . active = false ;
} ,
enableInputControls ( ) {
this . _inputControlEnabled = true ;
} ,
disableInputControls ( ) {
this . _inputControlEnabled = false ;
} ,
2022-10-01 07:14:05 +00:00
onBattleStartedOrResynced ( rdf ) {
2022-09-21 04:21:36 +00:00
// This function is also applicable to "re-joining".
2022-10-01 07:14:05 +00:00
console . log ( 'On battle started or resynced! renderFrameId=' , rdf . id ) ;
2022-09-20 15:50:01 +00:00
const self = window . mapIns ;
2022-10-01 07:14:05 +00:00
self . renderFrameId = rdf . id ;
self . lastAllConfirmedRenderFrameId = rdf . id ;
self . chaserRenderFrameId = rdf . id ;
2022-09-26 02:36:46 +00:00
const players = rdf . players ;
const playerMetas = rdf . playerMetas ;
self . _initPlayerRichInfoDict ( players , playerMetas ) ;
// Show the top status indicators for IN_BATTLE
const playersInfoScriptIns = self . playersInfoNode . getComponent ( "PlayersInfo" ) ;
for ( let i in playerMetas ) {
const playerMeta = playerMetas [ i ] ;
playersInfoScriptIns . updateData ( playerMeta ) ;
}
2022-09-21 04:21:36 +00:00
if ( null != rdf . countdownNanos ) {
self . countdownNanos = rdf . countdownNanos ;
}
2022-09-20 15:50:01 +00:00
if ( null != self . musicEffectManagerScriptIns ) {
self . musicEffectManagerScriptIns . playBGM ( ) ;
}
const canvasNode = self . canvasNode ;
self . ctrl = canvasNode . getComponent ( "TouchEventsManager" ) ;
self . enableInputControls ( ) ;
if ( self . countdownToBeginGameNode . parent ) {
self . countdownToBeginGameNode . parent . removeChild ( self . countdownToBeginGameNode ) ;
}
self . transitToState ( ALL _MAP _STATES . VISUAL ) ;
2022-09-24 04:01:50 +00:00
self . applyRoomDownsyncFrameDynamics ( rdf ) ;
self . _dumpToRenderCache ( rdf ) ;
2022-09-21 04:21:36 +00:00
self . battleState = ALL _BATTLE _STATES . IN _BATTLE ; // Starts the increment of "self.renderFrameId" in "self.update(dt)"
2022-10-01 15:54:48 +00:00
self . lastRenderFrameIdTriggeredAt = performance . now ( ) ;
2022-09-25 12:48:09 +00:00
if ( null != window . boundRoomId ) {
self . boundRoomIdLabel . string = window . boundRoomId ;
}
2022-09-20 15:50:01 +00:00
} ,
logBattleStats ( ) {
const self = this ;
let s = [ ] ;
2022-09-24 04:01:50 +00:00
s . push ( "Battle stats: lastUpsyncInputFrameId=" + self . lastUpsyncInputFrameId + ", lastAllConfirmedInputFrameId=" + self . lastAllConfirmedInputFrameId ) ;
2022-09-22 09:09:49 +00:00
2022-09-25 12:48:09 +00:00
for ( let i = self . recentInputCache . stFrameId ; i < self . recentInputCache . edFrameId ; ++ i ) {
const inputFrameDownsync = self . recentInputCache . getByFrameId ( i ) ;
2022-09-22 09:09:49 +00:00
s . push ( JSON . stringify ( inputFrameDownsync ) ) ;
2022-09-25 12:48:09 +00:00
}
2022-09-20 15:50:01 +00:00
console . log ( s . join ( '\n' ) ) ;
} ,
onBattleStopped ( ) {
const self = this ;
self . countdownNanos = null ;
self . logBattleStats ( ) ;
if ( self . musicEffectManagerScriptIns ) {
self . musicEffectManagerScriptIns . stopAllMusic ( ) ;
}
const canvasNode = self . canvasNode ;
const resultPanelNode = self . resultPanelNode ;
const resultPanelScriptIns = resultPanelNode . getComponent ( "ResultPanel" ) ;
resultPanelScriptIns . showPlayerInfo ( self . playerRichInfoDict ) ;
window . clearBoundRoomIdInBothVolatileAndPersistentStorage ( ) ;
self . battleState = ALL _BATTLE _STATES . IN _SETTLEMENT ;
self . showPopupInCanvas ( resultPanelNode ) ;
// Clear player info
self . playersInfoNode . getComponent ( "PlayersInfo" ) . clearInfo ( ) ;
} ,
spawnPlayerNode ( joinIndex , x , y ) {
2022-09-24 04:01:50 +00:00
const self = this ;
const newPlayerNode = 1 == joinIndex ? cc . instantiate ( self . player1Prefab ) : cc . instantiate ( self . player2Prefab ) ; // hardcoded for now, car color determined solely by joinIndex
2022-09-20 15:50:01 +00:00
newPlayerNode . setPosition ( cc . v2 ( x , y ) ) ;
2022-09-24 04:01:50 +00:00
newPlayerNode . getComponent ( "SelfPlayer" ) . mapNode = self . node ;
const currentSelfColliderCircle = newPlayerNode . getComponent ( cc . CircleCollider ) ;
2022-09-20 15:50:01 +00:00
2022-09-26 03:16:18 +00:00
const newPlayerColliderLatest = self . latestCollisionSys . createCircle ( x , y , currentSelfColliderCircle . radius ) ;
const newPlayerColliderChaser = self . chaserCollisionSys . createCircle ( x , y , currentSelfColliderCircle . radius ) ;
2022-09-24 04:01:50 +00:00
const collisionPlayerIndex = self . collisionPlayerIndexPrefix + joinIndex ;
self . latestCollisionSysMap . set ( collisionPlayerIndex , newPlayerColliderLatest ) ;
self . chaserCollisionSysMap . set ( collisionPlayerIndex , newPlayerColliderChaser ) ;
safelyAddChild ( self . node , newPlayerNode ) ;
2022-09-20 15:50:01 +00:00
setLocalZOrder ( newPlayerNode , 5 ) ;
newPlayerNode . active = true ;
const playerScriptIns = newPlayerNode . getComponent ( "SelfPlayer" ) ;
playerScriptIns . scheduleNewDirection ( { dx : 0 , dy : 0 } , true ) ;
return [ newPlayerNode , playerScriptIns ] ;
} ,
update ( dt ) {
const self = this ;
2022-09-25 12:48:09 +00:00
if ( ALL _BATTLE _STATES . IN _BATTLE == self . battleState ) {
2022-10-01 15:54:48 +00:00
const elapsedMillisSinceLastFrameIdTriggered = performance . now ( ) - self . lastRenderFrameIdTriggeredAt ;
if ( elapsedMillisSinceLastFrameIdTriggered < ( self . rollbackEstimatedDtMillis ) ) {
// console.debug("Avoiding too fast frame@renderFrameId=", self.renderFrameId, ": elapsedMillisSinceLastFrameIdTriggered=", elapsedMillisSinceLastFrameIdTriggered);
2022-10-01 12:45:38 +00:00
return ;
}
2022-09-25 12:48:09 +00:00
try {
2022-10-01 12:45:38 +00:00
let st = performance . now ( ) ;
2022-09-25 12:48:09 +00:00
let prevSelfInput = null , currSelfInput = null ;
const noDelayInputFrameId = self . _convertToInputFrameId ( self . renderFrameId , 0 ) ; // It's important that "inputDelayFrames == 0" here
2022-09-29 04:21:04 +00:00
if ( self . shouldGenerateInputFrameUpsync ( self . renderFrameId ) ) {
2022-09-25 12:48:09 +00:00
const prevAndCurrInputs = self . _generateInputFrameUpsync ( noDelayInputFrameId ) ;
prevSelfInput = prevAndCurrInputs [ 0 ] ;
currSelfInput = prevAndCurrInputs [ 1 ] ;
}
2022-09-24 04:01:50 +00:00
2022-09-25 12:48:09 +00:00
let t0 = performance . now ( ) ;
if ( self . shouldSendInputFrameUpsyncBatch ( prevSelfInput , currSelfInput , self . lastUpsyncInputFrameId , noDelayInputFrameId ) ) {
// TODO: Is the following statement run asynchronously in an implicit manner? Should I explicitly run it asynchronously?
self . sendInputFrameUpsyncBatch ( noDelayInputFrameId ) ;
}
let t1 = performance . now ( ) ;
2022-09-25 15:21:12 +00:00
// Use "fractional-frame-chasing" to guarantee that "self.update(dt)" is not jammed by a "large range of frame-chasing". See `<proj-root>/ConcerningEdgeCases.md` for the motivation.
2022-09-25 12:48:09 +00:00
const prevChaserRenderFrameId = self . chaserRenderFrameId ;
let nextChaserRenderFrameId = ( prevChaserRenderFrameId + self . maxChasingRenderFramesPerUpdate ) ;
if ( nextChaserRenderFrameId > self . renderFrameId ) nextChaserRenderFrameId = self . renderFrameId ;
2022-09-25 15:21:12 +00:00
self . rollbackAndChase ( prevChaserRenderFrameId , nextChaserRenderFrameId , self . chaserCollisionSys , self . chaserCollisionSysMap ) ;
2022-09-25 12:48:09 +00:00
self . chaserRenderFrameId = nextChaserRenderFrameId ; // Move the cursor "self.chaserRenderFrameId", keep in mind that "self.chaserRenderFrameId" is not monotonic!
let t2 = performance . now ( ) ;
2022-09-25 15:21:12 +00:00
// Inside "self.rollbackAndChase", the "self.latestCollisionSys" is ALWAYS ROLLED BACK to "self.recentRenderCache.get(self.renderFrameId)" before being applied dynamics from corresponding inputFrameDownsync, REGARDLESS OF whether or not "self.chaserRenderFrameId == self.renderFrameId" now.
const rdf = self . rollbackAndChase ( self . renderFrameId , self . renderFrameId + 1 , self . latestCollisionSys , self . latestCollisionSysMap ) ;
2022-09-25 12:48:09 +00:00
self . applyRoomDownsyncFrameDynamics ( rdf ) ;
let t3 = performance . now ( ) ;
} catch ( err ) {
console . error ( "Error during Map.update" , err ) ;
} finally {
// Update countdown
if ( null != self . countdownNanos ) {
self . countdownNanos -= self . rollbackEstimatedDt * 1000000000 ;
if ( self . countdownNanos <= 0 ) {
self . onBattleStopped ( self . playerRichInfoDict ) ;
return ;
}
2022-09-20 15:50:01 +00:00
2022-09-25 12:48:09 +00:00
const countdownSeconds = parseInt ( self . countdownNanos / 1000000000 ) ;
if ( isNaN ( countdownSeconds ) ) {
console . warn ( ` countdownSeconds is NaN for countdownNanos == ${ self . countdownNanos } . ` ) ;
}
self . countdownLabel . string = countdownSeconds ;
2022-09-20 15:50:01 +00:00
}
2022-09-25 12:48:09 +00:00
++ self . renderFrameId ; // [WARNING] It's important to increment the renderFrameId AFTER all the operations above!!!
2022-10-01 15:54:48 +00:00
self . lastRenderFrameIdTriggeredAt = performance . now ( ) ;
2022-09-20 15:50:01 +00:00
}
}
} ,
transitToState ( s ) {
const self = this ;
self . state = s ;
} ,
logout ( byClick /* The case where this param is "true" will be triggered within `ConfirmLogout.js`.*/ , shouldRetainBoundRoomIdInBothVolatileAndPersistentStorage ) {
const self = this ;
const localClearance = ( ) => {
window . clearLocalStorageAndBackToLoginScene ( shouldRetainBoundRoomIdInBothVolatileAndPersistentStorage ) ;
}
const selfPlayerStr = cc . sys . localStorage . getItem ( "selfPlayer" ) ;
if ( null == selfPlayerStr ) {
localClearance ( ) ;
return ;
}
const selfPlayerInfo = JSON . parse ( selfPlayerStr ) ;
try {
NetworkUtils . ajax ( {
url : backendAddress . PROTOCOL + '://' + backendAddress . HOST + ':' + backendAddress . PORT + constants . ROUTE _PATH . API + constants . ROUTE _PATH . PLAYER + constants . ROUTE _PATH . VERSION + constants . ROUTE _PATH . INT _AUTH _TOKEN + constants . ROUTE _PATH . LOGOUT ,
type : "POST" ,
data : { intAuthToken : selfPlayerInfo . intAuthToken } ,
success : function ( res ) {
if ( res . ret != constants . RET _CODE . OK ) {
console . log ( "Logout failed: " , res ) ;
}
localClearance ( ) ;
} ,
error : function ( xhr , status , errMsg ) {
localClearance ( ) ;
} ,
timeout : function ( ) {
localClearance ( ) ;
}
} ) ;
} catch ( e ) { } finally {
// For Safari (both desktop and mobile).
localClearance ( ) ;
}
} ,
onLogoutClicked ( evt ) {
const self = this ;
self . showPopupInCanvas ( self . confirmLogoutNode ) ;
} ,
onLogoutConfirmationDismissed ( ) {
const self = this ;
self . transitToState ( ALL _MAP _STATES . VISUAL ) ;
const canvasNode = self . canvasNode ;
canvasNode . removeChild ( self . confirmLogoutNode ) ;
self . enableInputControls ( ) ;
} ,
onGameRule1v1ModeClicked ( evt , cb ) {
const self = this ;
self . battleState = ALL _BATTLE _STATES . WAITING ;
window . initPersistentSessionClient ( self . initAfterWSConnected , null /* Deliberately NOT passing in any `expectedRoomId`. -- YFLu */ ) ;
self . hideGameRuleNode ( ) ;
} ,
showPopupInCanvas ( toShowNode ) {
const self = this ;
self . disableInputControls ( ) ;
self . transitToState ( ALL _MAP _STATES . SHOWING _MODAL _POPUP ) ;
safelyAddChild ( self . widgetsAboveAllNode , toShowNode ) ;
setLocalZOrder ( toShowNode , 10 ) ;
} ,
2022-09-26 02:36:46 +00:00
onBattleReadyToStart ( playerMetas , isSelfRejoining ) {
console . log ( "Calling `onBattleReadyToStart` with:" , playerMetas ) ;
2022-09-20 15:50:01 +00:00
const self = this ;
const findingPlayerScriptIns = self . findingPlayerNode . getComponent ( "FindingPlayer" ) ;
2022-09-26 02:36:46 +00:00
findingPlayerScriptIns . hideExitButton ( ) ;
2022-09-20 15:50:01 +00:00
findingPlayerScriptIns . updatePlayersInfo ( playerMetas ) ;
2022-09-26 02:36:46 +00:00
const hideFindingPlayersGUI = function ( ) {
if ( null == self . findingPlayerNode . parent ) return ;
self . findingPlayerNode . parent . removeChild ( self . findingPlayerNode ) ;
} ;
if ( true == isSelfRejoining ) {
hideFindingPlayersGUI ( ) ;
} else {
// Delay to hide the "finding player" GUI, then show a countdown clock
window . setTimeout ( ( ) => {
hideFindingPlayersGUI ( ) ;
const countDownScriptIns = self . countdownToBeginGameNode . getComponent ( "CountdownToBeginGame" ) ;
countDownScriptIns . setData ( ) ;
self . showPopupInCanvas ( self . countdownToBeginGameNode ) ;
} , 1500 ) ;
}
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
_createRoomDownsyncFrameLocally ( renderFrameId , collisionSys , collisionSysMap ) {
2022-09-20 15:50:01 +00:00
const self = this ;
2022-09-24 04:01:50 +00:00
const prevRenderFrameId = renderFrameId - 1 ;
2022-09-29 04:21:04 +00:00
const inputFrameAppliedOnPrevRenderFrame = (
2022-09-24 04:01:50 +00:00
0 > prevRenderFrameId
?
null
:
self . getCachedInputFrameDownsyncWithPrediction ( self . _convertToInputFrameId ( prevRenderFrameId , self . inputDelayFrames ) )
) ;
// TODO: Find a better way to assign speeds instead of using "speedRefRenderFrameId".
const speedRefRenderFrameId = prevRenderFrameId ;
const speedRefRenderFrame = (
2022-09-29 04:21:04 +00:00
0 > speedRefRenderFrameId
2022-09-24 04:01:50 +00:00
?
null
:
2022-09-29 04:21:04 +00:00
self . recentRenderCache . getByFrameId ( speedRefRenderFrameId )
2022-09-24 04:01:50 +00:00
) ;
2022-09-20 15:50:01 +00:00
const rdf = {
2022-09-24 04:01:50 +00:00
id : renderFrameId ,
refFrameId : renderFrameId ,
players : { }
2022-09-20 15:50:01 +00:00
} ;
2022-09-22 04:45:17 +00:00
self . playerRichInfoDict . forEach ( ( playerRichInfo , playerId ) => {
2022-09-20 15:50:01 +00:00
const joinIndex = playerRichInfo . joinIndex ;
2022-09-24 04:01:50 +00:00
const collisionPlayerIndex = self . collisionPlayerIndexPrefix + joinIndex ;
const playerCollider = collisionSysMap . get ( collisionPlayerIndex ) ;
2022-09-20 15:50:01 +00:00
rdf . players [ playerRichInfo . id ] = {
id : playerRichInfo . id ,
2022-09-24 04:01:50 +00:00
x : playerCollider . x ,
y : playerCollider . y ,
2022-09-29 04:21:04 +00:00
dir : self . ctrl . decodeDirection ( null == inputFrameAppliedOnPrevRenderFrame ? 0 : inputFrameAppliedOnPrevRenderFrame . inputList [ joinIndex - 1 ] ) ,
2022-09-24 04:01:50 +00:00
speed : ( null == speedRefRenderFrame ? playerRichInfo . speed : speedRefRenderFrame . players [ playerRichInfo . id ] . speed ) ,
2022-09-20 15:50:01 +00:00
joinIndex : joinIndex
} ;
2022-09-22 04:45:17 +00:00
} ) ;
2022-09-24 04:01:50 +00:00
if (
2022-09-29 04:21:04 +00:00
null != inputFrameAppliedOnPrevRenderFrame && self . _allConfirmed ( inputFrameAppliedOnPrevRenderFrame . confirmedList )
2022-09-24 04:01:50 +00:00
&&
self . lastAllConfirmedRenderFrameId >= prevRenderFrameId
&&
rdf . id > self . lastAllConfirmedRenderFrameId
) {
self . lastAllConfirmedRenderFrameId = rdf . id ;
}
self . _dumpToRenderCache ( rdf ) ;
2022-09-21 09:22:34 +00:00
return rdf ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
applyRoomDownsyncFrameDynamics ( rdf ) {
2022-09-20 15:50:01 +00:00
const self = this ;
2022-09-22 04:45:17 +00:00
self . playerRichInfoDict . forEach ( ( playerRichInfo , playerId ) => {
2022-09-20 15:50:01 +00:00
const immediatePlayerInfo = rdf . players [ playerId ] ;
playerRichInfo . node . setPosition ( immediatePlayerInfo . x , immediatePlayerInfo . y ) ;
playerRichInfo . scriptIns . scheduleNewDirection ( immediatePlayerInfo . dir , true ) ;
playerRichInfo . scriptIns . updateSpeed ( immediatePlayerInfo . speed ) ;
2022-09-22 04:45:17 +00:00
} ) ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-24 04:01:50 +00:00
getCachedInputFrameDownsyncWithPrediction ( inputFrameId ) {
2022-09-22 04:45:17 +00:00
const self = this ;
2022-09-24 04:01:50 +00:00
let inputFrameDownsync = self . recentInputCache . getByFrameId ( inputFrameId ) ;
2022-09-25 12:48:09 +00:00
if ( null != inputFrameDownsync && - 1 != self . lastAllConfirmedInputFrameId && inputFrameId > self . lastAllConfirmedInputFrameId ) {
2022-09-24 04:01:50 +00:00
const lastAllConfirmedInputFrame = self . recentInputCache . getByFrameId ( self . lastAllConfirmedInputFrameId ) ;
2022-09-22 04:45:17 +00:00
for ( let i = 0 ; i < inputFrameDownsync . inputList . length ; ++ i ) {
if ( i == self . selfPlayerInfo . joinIndex - 1 ) continue ;
inputFrameDownsync . inputList [ i ] = lastAllConfirmedInputFrame . inputList [ i ] ;
}
}
return inputFrameDownsync ;
} ,
2022-09-25 15:21:12 +00:00
rollbackAndChase ( renderFrameIdSt , renderFrameIdEd , collisionSys , collisionSysMap ) {
2022-09-25 12:48:09 +00:00
if ( renderFrameSt >= renderFrameIdEd ) {
2022-09-24 04:01:50 +00:00
return ;
}
2022-09-20 15:50:01 +00:00
const self = this ;
2022-09-24 04:01:50 +00:00
const renderFrameSt = self . recentRenderCache . getByFrameId ( renderFrameIdSt ) ; // typed "RoomDownsyncFrame"
2022-09-26 02:36:46 +00:00
if ( null == renderFrameSt ) {
console . error ( "Couldn't find renderFrameId=" , renderFrameIdSt , " to rollback, recentRenderCache=" , self . _stringifyRecentRenderCache ( false ) ) ;
}
2022-09-24 04:01:50 +00:00
/ *
Reset "position" of players in "collisionSys" according to "renderFrameSt" . The easy part is that we don ' t have path - dependent - integrals to worry about like that of thermal dynamics .
* /
2022-09-22 04:45:17 +00:00
self . playerRichInfoDict . forEach ( ( playerRichInfo , playerId ) => {
2022-09-20 15:50:01 +00:00
const joinIndex = playerRichInfo . joinIndex ;
2022-09-24 04:01:50 +00:00
const collisionPlayerIndex = self . collisionPlayerIndexPrefix + joinIndex ;
const playerCollider = collisionSysMap . get ( collisionPlayerIndex ) ;
const player = renderFrameSt . players [ playerId ] ;
playerCollider . x = player . x ;
playerCollider . y = player . y ;
2022-09-22 04:45:17 +00:00
} ) ;
2022-09-21 15:59:05 +00:00
2022-09-29 04:21:04 +00:00
// [WARNING] Traverse in the order of joinIndices to guarantee determinism.
2022-09-24 04:01:50 +00:00
/ *
This function eventually calculates a "RoomDownsyncFrame" where "RoomDownsyncFrame.id == renderFrameIdEd" .
* /
2022-09-25 12:48:09 +00:00
for ( let i = renderFrameIdSt ; i < renderFrameIdEd ; ++ i ) {
2022-09-24 04:01:50 +00:00
const renderFrame = self . recentRenderCache . getByFrameId ( i ) ; // typed "RoomDownsyncFrame"
const j = self . _convertToInputFrameId ( i , self . inputDelayFrames ) ;
2022-09-25 12:48:09 +00:00
const inputList = self . getCachedInputFrameDownsyncWithPrediction ( j ) . inputList ;
2022-09-29 04:21:04 +00:00
for ( let j in self . playerRichInfoArr ) {
const joinIndex = parseInt ( j ) + 1 ;
2022-10-01 09:26:37 +00:00
const playerId = self . playerRichInfoArr [ j ] . id ;
2022-09-24 04:01:50 +00:00
const collisionPlayerIndex = self . collisionPlayerIndexPrefix + joinIndex ;
const playerCollider = collisionSysMap . get ( collisionPlayerIndex ) ;
const player = renderFrame . players [ playerId ] ;
2022-09-25 12:48:09 +00:00
const encodedInput = inputList [ joinIndex - 1 ] ;
const decodedInput = self . ctrl . decodeDirection ( encodedInput ) ;
2022-09-26 03:16:18 +00:00
const baseChange = player . speed * self . rollbackEstimatedDt * decodedInput . speedFactor ;
2022-09-25 12:48:09 +00:00
playerCollider . x += baseChange * decodedInput . dx ;
playerCollider . y += baseChange * decodedInput . dy ;
/ *
if ( 0 < encodedInput ) {
console . log ( "playerId=" , playerId , "@renderFrameId=" , i , ", delayedInputFrameId=" , j , ", baseChange=" , baseChange , ": x=" , playerCollider . x , ", y=" , playerCollider . y ) ;
}
* /
2022-09-29 04:21:04 +00:00
}
2022-09-24 04:01:50 +00:00
collisionSys . update ( ) ;
2022-09-26 02:36:46 +00:00
const result = collisionSys . createResult ( ) ; // Can I reuse a "self.latestCollisionSysResult" object throughout the whole battle?
2022-09-24 04:01:50 +00:00
2022-09-26 03:16:18 +00:00
for ( let i in self . playerRichInfoArr ) {
const joinIndex = parseInt ( i ) + 1 ;
2022-09-24 04:01:50 +00:00
const collisionPlayerIndex = self . collisionPlayerIndexPrefix + joinIndex ;
const playerCollider = collisionSysMap . get ( collisionPlayerIndex ) ;
const potentials = playerCollider . potentials ( ) ;
for ( const barrier of potentials ) {
// Test if the player collides with the wall
if ( ! playerCollider . collides ( barrier , result ) ) continue ;
// Push the player out of the wall
playerCollider . x -= result . overlap * result . overlap _x ;
playerCollider . y -= result . overlap * result . overlap _y ;
}
2022-09-26 03:16:18 +00:00
}
2022-09-21 15:59:05 +00:00
}
2022-09-24 04:01:50 +00:00
return self . _createRoomDownsyncFrameLocally ( renderFrameIdEd , collisionSys , collisionSysMap ) ;
2022-09-20 15:50:01 +00:00
} ,
_initPlayerRichInfoDict ( players , playerMetas ) {
const self = this ;
for ( let k in players ) {
const playerId = parseInt ( k ) ;
2022-09-22 04:45:17 +00:00
if ( self . playerRichInfoDict . has ( playerId ) ) continue ; // Skip already put keys
2022-09-20 15:50:01 +00:00
const immediatePlayerInfo = players [ playerId ] ;
const immediatePlayerMeta = playerMetas [ playerId ] ;
const nodeAndScriptIns = self . spawnPlayerNode ( immediatePlayerInfo . joinIndex , immediatePlayerInfo . x , immediatePlayerInfo . y ) ;
2022-09-22 04:45:17 +00:00
self . playerRichInfoDict . set ( playerId , immediatePlayerInfo ) ;
2022-09-20 15:50:01 +00:00
2022-09-22 04:45:17 +00:00
Object . assign ( self . playerRichInfoDict . get ( playerId ) , {
2022-09-20 15:50:01 +00:00
node : nodeAndScriptIns [ 0 ] ,
scriptIns : nodeAndScriptIns [ 1 ]
} ) ;
if ( self . selfPlayerInfo . id == playerId ) {
self . selfPlayerInfo = Object . assign ( self . selfPlayerInfo , immediatePlayerInfo ) ;
nodeAndScriptIns [ 1 ] . showArrowTipNode ( ) ;
}
}
2022-09-26 03:16:18 +00:00
self . playerRichInfoArr = new Array ( self . playerRichInfoDict . size ) ;
self . playerRichInfoDict . forEach ( ( playerRichInfo , playerId ) => {
self . playerRichInfoArr [ playerRichInfo . joinIndex - 1 ] = playerRichInfo ;
} ) ;
2022-09-20 15:50:01 +00:00
} ,
_stringifyRecentInputCache ( usefullOutput ) {
2022-09-26 02:36:46 +00:00
const self = this ;
2022-09-20 15:50:01 +00:00
if ( true == usefullOutput ) {
2022-09-22 09:09:49 +00:00
let s = [ ] ;
2022-09-26 02:36:46 +00:00
for ( let i = self . recentInputCache . stFrameId ; i < self . recentInputCache . edFrameId ; ++ i ) {
s . push ( JSON . stringify ( self . recentInputCache . getByFrameId ( i ) ) ) ;
}
2022-09-22 09:09:49 +00:00
return s . join ( '\n' ) ;
2022-09-20 15:50:01 +00:00
}
2022-09-26 02:36:46 +00:00
return "[stInputFrameId=" + self . recentInputCache . stFrameId + ", edInputFrameId=" + self . recentInputCache . edFrameId + ")" ;
2022-09-20 15:50:01 +00:00
} ,
2022-09-21 09:22:34 +00:00
2022-09-26 02:36:46 +00:00
_stringifyRecentRenderCache ( usefullOutput ) {
2022-09-21 09:22:34 +00:00
const self = this ;
2022-09-26 02:36:46 +00:00
if ( true == usefullOutput ) {
let s = [ ] ;
for ( let i = self . recentRenderCache . stFrameId ; i < self . recentRenderCache . edFrameId ; ++ i ) {
s . push ( JSON . stringify ( self . recentRenderCache . getByFrameId ( i ) ) ) ;
2022-09-21 09:22:34 +00:00
}
2022-09-26 02:36:46 +00:00
return s . join ( '\n' ) ;
}
return "[stRenderFrameId=" + self . recentRenderCache . stFrameId + ", edRenderFrameId=" + self . recentRenderCache . edFrameId + ")" ;
2022-09-21 09:22:34 +00:00
} ,
2022-09-26 02:36:46 +00:00
2022-09-20 15:50:01 +00:00
} ) ;