Compare commits

..

22 Commits
v0.1 ... v0.2

Author SHA1 Message Date
Wing
1e5d7d1d06 Merge pull request #2 from genxium/backend_render_frame_calc
Added rejoining feature.
2022-10-04 11:31:27 +08:00
genxium
a6731dc7d6 Minor fixes for rejoining signals. 2022-10-04 11:24:47 +08:00
genxium
1004fd45db Fixed timing for upsync confirmation merge. 2022-10-03 23:54:38 +08:00
genxium
09b12c5b16 Updated documentation. 2022-10-03 20:25:51 +08:00
genxium
9d9bea21ef Minor updates. 2022-10-03 00:22:05 +08:00
genxium
54d6e52498 Minor fix for frontend chaserRenderFrameId positioning and logging. 2022-10-02 16:19:54 +08:00
genxium
4d1de44ee5 Updated config uniformity. 2022-10-02 11:33:40 +08:00
genxium
f3a576ba13 Minor updates. 2022-10-01 23:54:48 +08:00
genxium
2264c0d362 Updated logging. 2022-10-01 20:45:52 +08:00
genxium
cd83539197 Fixed some trivial runtime errors. 2022-10-01 17:26:37 +08:00
genxium
a2a8be9068 Added backend collider initialization codes. 2022-10-01 15:14:05 +08:00
Wing
527cc94242 Minor fix on markdown file. 2022-09-30 23:32:26 +08:00
genxium
266335b7c6 Refactoring backend for periodical force confirmation. 2022-09-30 23:25:32 +08:00
genxium
14fb8e94b2 Preparation of server-side collision calc. 2022-09-26 23:09:18 +08:00
Wing
ff092a40ed Merge pull request #1 from genxium/manual_collision
Merge the manual collision.
2022-09-26 11:49:55 +08:00
genxium
80dc05a92b Fixed collision detection and camera tracking. 2022-09-26 11:42:48 +08:00
genxium
2dfd6083c5 Fixed a few indexing errors. 2022-09-26 10:36:46 +08:00
genxium
50273c981b Minor fix. 2022-09-25 23:30:34 +08:00
genxium
114e6b0501 Updated documentation. 2022-09-25 23:21:12 +08:00
genxium
cccbeb1c29 Fixed part of frame chasing dynamics, yet collision handling is still broken. 2022-09-25 20:48:09 +08:00
genxium
1cc0eed39e A temp commit after coping with many obvious runtime errors. 2022-09-25 17:16:44 +08:00
genxium
85c94a9e5d Preparation for changing collision system. 2022-09-23 16:42:44 +08:00
43 changed files with 2844 additions and 9032 deletions

43
ConcerningEdgeCases.md Normal file
View File

@@ -0,0 +1,43 @@
# Potential avalanche from local lag
Under the current "input delay" algorithm, the lag of a single player would cause all the other players to receive outdated commands, e.g. when at a certain moment
- player#1: renderFrameId = 100, significantly lagged due to local CPU overheated
- player#2: renderFrameId = 240
- player#3: renderFrameId = 239
- player#4: renderFrameId = 242
players #2, #3 #4 would receive "outdated(in their subjective feelings) but all-confirmed commands" from then on, thus forced to rollback and chase many frames - the lag due to "large range of frame-chasing" would then further deteriorate the situation - like an avalanche.
In a "no-server & p2p" setup, I couldn't think of a proper way to cope with such edge case. Solely on the frontend we could only mitigate the impact to players #2, #3, #4, e.g. a potential lag due to "large range of frame-chasing" is proactively avoided in `<proj-root>/frontend/assets/scripts/Map.js, function update(dt)`.
However in a "server as authority" setup, the server could force confirming an inputFrame without player#1's upsync, and notify player#1 to apply a "roomDownsyncFrame" as well as drop all its outdated local inputFrames.
# Start up frames
renderFrameId | generatedInputFrameId | toApplyInputFrameId
-------------------|----------------------------|----------------------
0, 1, 2, 3 | 0, _EMP_, _EMP_, _EMP_ | 0
4, 5, 6, 7 | 1, _EMP_, _EMP_, _EMP_ | 0
8, 9, 10, 11 | 2, _EMP_, _EMP_, _EMP_ | 1
12, 13, 14, 15 | 3, _EMP_, _EMP_, _EMP_ | 2
It should be reasonable to assume that inputFrameId=0 is always of all-empty content, because human has no chance of clicking at the very first render frame.
# Alignment of the current setup
The following setup is chosen deliberately for some "%4" number coincidence.
- NstDelayFrames = 2
- InputDelayFrames = 4
- InputScaleFrames = 2
If "InputDelayFrames" is changed, the impact would be as follows, kindly note that "372%4 == 0".
### pR.InputDelayFrames = 4
renderFrameId | toApplyInputFrameId
--------------------------|----------------------------------------------------
368, 369, 370, 371 | 91
372, 373, 374, 375 | 92
### pR.InputDelayFrames = 5
renderFrameId | toApplyInputFrameId
--------------------------|----------------------------------------------------
..., ..., ..., 368 | 90
369, 370, 371, 372 | 91
373, 374, 375, ... | 92

View File

@@ -3,13 +3,15 @@ If you'd like to play with the backend code seriously, please read the detailed
There could be some left over wechat-game related code pieces, but they're neither meant to work nor supported anymore.
# 1. Database Server
# 1. Building & running
The database product to be used for this project is MySQL 5.7.
## 1.1 Golang1.19.1
Documentation TBD.
We use [skeema](https://github.com/skeema/skeema) for schematic synchronization under `<proj-root>/database/skeema-repo-root/` which intentionally doesn't contain a `.skeema` file. Please read [this tutorial](https://shimo.im/doc/wQ0LvB0rlZcbHF5V) for more information.
## 1.2 MySQL
The database product to be used for this project is MySQL 5.7, you can install and manage `MySQL` server by [these scripts](https://github.com/genxium/Ubuntu14InitScripts/tree/master/database/mysql).
You can use [this node module (still under development)](https://github.com/genxium/node-mysqldiff-bridge) instead under `Windows10`, other versions of Windows are not yet tested for compatibility.
We use [skeema](https://github.com/skeema/skeema) for schematic synchronization under `<proj-root>/database/skeema-repo-root/` which intentionally doesn't contain a `.skeema` file. Please read [this tutorial](https://shimo.im/doc/wQ0LvB0rlZcbHF5V) for more information. For `Windows 10/11`, you can compile `skeema` from source and config the host to be `127.0.0.1` instead of `localhost` to use it, i.e. circumventing the pitfall for MySQL unix socket connection on Windows.
The following command(s)
```
@@ -21,33 +23,25 @@ user@proj-root/database/skeema-repo-root> skeema diff
```
is recommended to be used for checking difference from your "live MySQL server" to the latest expected schema tracked in git.
# 2. Building & running
## 1.3 Required Config Files
## 2.1 Golang1.11
See https://github.com/genxium/Go111ModulePrac for details.
## 2.2 MySQL
On a product machine, you can install and manage `MySQL` server by [these scripts](https://github.com/genxium/Ubuntu14InitScripts/tree/master/database/mysql).
## 2.3 Required Config Files
### 2.3.1 Backend
### 1.3.1 Backend
- It needs `<proj-root>/battle_srv/configs/*` which is generated by `cd <proj-root>/battle_srv && cp -r ./configs.template ./configs` and necessary customization.
### 2.3.2 Frontend
### 1.3.2 Frontend
- It needs CocosCreator v2.2.1 to build.
- A required "CocosCreator plugin `i18n`" is already enclosed in the project, if you have a globally installed "CocosCreator plugin `i18n`"(often located at `$HOME/.CocosCreator/packages/`) they should be OK to co-exist.
- It needs `<proj-root>/frontend/assets/plugin_scripts/conf.js` which is generated by `cd <proj-root>/frontend/assets/plugin_scripts && cp conf.js.template conf.js`.
## 2.4 Troubleshooting
## 1.4 Troubleshooting
### 2.4.1 Redis snapshot writing failure
### 1.4.1 Redis snapshot writing failure
```
ErrFatal {"err": "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error."}
```
Just restart your `redis-server` process.
# 3. Git configs cautions
# 2. Git configs cautions
Please make sure that you've set `ignorecase = false` in your `[core] section of <proj-root>/.git/config`.

View File

@@ -94,7 +94,7 @@ func (w *wechat) GetJsConfig(uri string) (config *JsConfig, err error) {
return
}
//TODO add cache, getTicket 获取jsapi_ticket
// TODO add cache, getTicket 获取jsapi_ticket
func (w *wechat) getTicket() (ticketStr string, err error) {
var ticket resTicket
ticket, err = w.getTicketFromServer()
@@ -131,7 +131,7 @@ func (w *wechat) GetOauth2Basic(authcode string) (result resAccessToken, err err
return
}
//UserInfo 用户授权获取到用户信息
// UserInfo 用户授权获取到用户信息
type UserInfo struct {
CommonError
OpenID string `json:"openid"`
@@ -164,7 +164,7 @@ func (w *wechat) GetMoreInfo(accessToken string, openId string) (result UserInfo
return
}
//HTTPGet get 请求
// HTTPGet get 请求
func get(uri string) ([]byte, error) {
response, err := http.Get(uri)
if err != nil {
@@ -182,7 +182,7 @@ func get(uri string) ([]byte, error) {
return body, err
}
//PostJSON post json 数据请求
// PostJSON post json 数据请求
func post(uri string, obj interface{}) ([]byte, error) {
jsonData, err := json.Marshal(obj)
if err != nil {
@@ -206,7 +206,7 @@ func post(uri string, obj interface{}) ([]byte, error) {
return ioutil.ReadAll(response.Body)
}
//Signature sha1签名
// Signature sha1签名
func signature(params ...string) string {
sort.Strings(params)
h := sha1.New()
@@ -216,7 +216,7 @@ func signature(params ...string) string {
return fmt.Sprintf("%x", h.Sum(nil))
}
//RandomStr 随机生成字符串
// RandomStr 随机生成字符串
func randomStr(length int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
@@ -228,7 +228,7 @@ func randomStr(length int) string {
return string(result)
}
//getTicketFromServer 强制从服务器中获取ticket
// getTicketFromServer 强制从服务器中获取ticket
func (w *wechat) getTicketFromServer() (ticket resTicket, err error) {
var accessToken string
accessToken, err = w.getAccessTokenFromServer()
@@ -256,7 +256,7 @@ func (w *wechat) getTicketFromServer() (ticket resTicket, err error) {
return
}
//GetAccessTokenFromServer 强制从微信服务器获取token
// GetAccessTokenFromServer 强制从微信服务器获取token
func (w *wechat) getAccessTokenFromServer() (accessToken string, err error) {
AccessTokenURL := w.config.ApiProtocol + "://" + w.config.ApiGateway + "/cgi-bin/token"
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", AccessTokenURL, w.config.AppID, w.config.AppSecret)

View File

@@ -66,7 +66,7 @@ func createMysqlData(rows *sqlx.Rows, v string) {
}
}
//加上tableName参数, 用于pre_conf_data.sqlite里bot_player表的复用 --kobako
// 加上tableName参数, 用于pre_conf_data.sqlite里bot_player表的复用 --kobako
func maybeCreateNewPlayerFromBotTable(db *sqlx.DB, tableName string) {
var ls []*dbBotPlayer
err := db.Select(&ls, "SELECT name, magic_phone_country_code, magic_phone_num, display_name FROM "+tableName)

View File

@@ -1,37 +1,46 @@
module server
go 1.19
require (
github.com/ByteArena/box2d v1.0.2
github.com/ChimeraCoder/gojson v1.0.0 // indirect
github.com/Masterminds/squirrel v0.0.0-20180815162352-8a7e65843414
github.com/davecgh/go-spew v1.1.1
github.com/fatih/color v1.7.0 // indirect
github.com/gin-contrib/cors v0.0.0-20180514151808-6f0a820f94be
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 // indirect
github.com/gin-gonic/gin v1.3.0
github.com/githubnemo/CompileDaemon v1.0.0 // indirect
github.com/go-redis/redis v6.13.2+incompatible
github.com/go-sql-driver/mysql v1.4.0
github.com/golang/protobuf v1.5.2
github.com/google/go-cmp v0.5.9 // indirect
github.com/gorilla/websocket v1.2.0
github.com/hashicorp/go-cleanhttp v0.0.0-20171218145408-d5fe4b57a186
github.com/howeyc/fsnotify v0.9.0 // indirect
github.com/imdario/mergo v0.3.6
github.com/jmoiron/sqlx v0.0.0-20180614180643-0dae4fefe7c0
github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e
github.com/robfig/cron v0.0.0-20180505203441-b41be1df6967
github.com/solarlune/resolv v0.5.1
github.com/thoas/go-funk v0.0.0-20180716193722-1060394a7713
go.uber.org/zap v1.9.1
google.golang.org/protobuf v1.28.1
)
require (
github.com/ChimeraCoder/gojson v1.0.0 // indirect
github.com/fatih/color v1.7.0 // indirect
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 // indirect
github.com/githubnemo/CompileDaemon v1.0.0 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/howeyc/fsnotify v0.9.0 // indirect
github.com/kvartborg/vector v0.0.0-20200419093813-2cba0cabb4f0 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e
github.com/mattn/go-colorable v0.0.9 // indirect
github.com/mattn/go-isatty v0.0.3 // indirect
github.com/mattn/go-sqlite3 v1.9.0
github.com/robfig/cron v0.0.0-20180505203441-b41be1df6967
github.com/thoas/go-funk v0.0.0-20180716193722-1060394a7713
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-sqlite3 v1.14.15 // indirect
github.com/ugorji/go v1.1.1 // indirect
go.uber.org/atomic v1.3.2 // indirect
go.uber.org/multierr v1.1.0 // indirect
go.uber.org/zap v1.9.1
google.golang.org/protobuf v1.28.1
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 // indirect
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 // indirect
gopkg.in/go-playground/validator.v8 v8.18.2 // indirect
gopkg.in/yaml.v2 v2.2.1 // indirect
)

View File

@@ -45,6 +45,8 @@ github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28=
github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/jmoiron/sqlx v0.0.0-20180614180643-0dae4fefe7c0 h1:5B0uxl2lzNRVkJVg+uGHxWtRt4C0Wjc6kJKo5XYx8xE=
github.com/jmoiron/sqlx v0.0.0-20180614180643-0dae4fefe7c0/go.mod h1:IiEW3SEiiErVyFdH8NTuWjSifiEQKUoyK3LNqr2kCHU=
github.com/kvartborg/vector v0.0.0-20200419093813-2cba0cabb4f0 h1:v8lWpj5957KtDMKu+xQtlu6G3ZoZR6Tn9bsfZCRG5Xw=
github.com/kvartborg/vector v0.0.0-20200419093813-2cba0cabb4f0/go.mod h1:GAX7tMJqXx9fB1BrsTWPOXy6IBRX+J461BffVPAdpwo=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
@@ -55,12 +57,18 @@ github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRU
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
github.com/robfig/cron v0.0.0-20180505203441-b41be1df6967 h1:x7xEyJDP7Hv3LVgvWhzioQqbC/KtuUhTigKlH/8ehhE=
github.com/robfig/cron v0.0.0-20180505203441-b41be1df6967/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/solarlune/resolv v0.5.1 h1:Ul6PAs/zaxiMUOEYz1Z6VeUj5k3CDcWMvSh+kivybDY=
github.com/solarlune/resolv v0.5.1/go.mod h1:HjM2f/0NoVjVdZsi26GtugX5aFbA62COEFEXkOhveRw=
github.com/thoas/go-funk v0.0.0-20180716193722-1060394a7713 h1:knaxjm6QMbUMNvuaSnJZmw0gRX4V/79JVUQiziJGM84=
github.com/thoas/go-funk v0.0.0-20180716193722-1060394a7713/go.mod h1:mlR+dHGb+4YgXkf13rkQTuzrneeHANxOm6+ZnEV9HsA=
github.com/ugorji/go v1.1.1 h1:gmervu+jDMvXTbcHQ0pd2wee85nEoE0BsVyEuzkfK8w=
@@ -71,6 +79,8 @@ go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.9.1 h1:XCJQEf3W6eZaVwhRBof6ImoYGJSITeKWsyeh3HFu/5o=
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=

View File

@@ -1,13 +1,5 @@
package models
import (
"github.com/ByteArena/box2d"
)
type Barrier struct {
X float64
Y float64
Type uint32
Boundary *Polygon2D
CollidableBody *box2d.B2Body
Boundary *Polygon2D
}

View File

@@ -1,19 +0,0 @@
package models
import (
"github.com/ByteArena/box2d"
)
type Bullet struct {
LocalIdInBattle int32 `json:"-"`
LinearSpeed float64 `json:"-"`
X float64 `json:"-"`
Y float64 `json:"-"`
Removed bool `json:"-"`
Dir *Direction `json:"-"`
StartAtPoint *Vec2D `json:"-"`
EndAtPoint *Vec2D `json:"-"`
DamageBoundary *Polygon2D `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
RemovedAtFrameId int32 `json:"-"`
}

View File

@@ -86,7 +86,7 @@ func (p *InRangePlayerCollection) NextPlayerToAttack() *InRangePlayerNode {
//TODO: 完成重构
/// Doubly circular linked list Implement
// / Doubly circular linked list Implement
type InRangePlayerNode struct {
Prev *InRangePlayerNode
Next *InRangePlayerNode

View File

@@ -33,6 +33,14 @@ func toPbVec2DList(modelInstance *Vec2DList) *pb.Vec2DList {
return toRet
}
func ToPbVec2DListMap(modelInstances map[string]*Vec2DList) map[string]*pb.Vec2DList {
toRet := make(map[string]*pb.Vec2DList, len(modelInstances))
for k, v := range modelInstances {
toRet[k] = toPbVec2DList(v)
}
return toRet
}
func toPbPolygon2DList(modelInstance *Polygon2DList) *pb.Polygon2DList {
toRet := &pb.Polygon2DList{
Polygon2DList: make([]*pb.Polygon2D, len(*modelInstance)),
@@ -43,24 +51,10 @@ func toPbPolygon2DList(modelInstance *Polygon2DList) *pb.Polygon2DList {
return toRet
}
func ToPbStrToBattleColliderInfo(intervalToPing int32, willKickIfInactiveFor int32, boundRoomId int32, stageName string, modelInstance1 StrToVec2DListMap, modelInstance2 StrToPolygon2DListMap, stageDiscreteW int32, stageDiscreteH int32, stageTileW int32, stageTileH int32) *pb.BattleColliderInfo {
toRet := &pb.BattleColliderInfo{
IntervalToPing: intervalToPing,
WillKickIfInactiveFor: willKickIfInactiveFor,
BoundRoomId: boundRoomId,
StageName: stageName,
StrToVec2DListMap: make(map[string]*pb.Vec2DList, 0),
StrToPolygon2DListMap: make(map[string]*pb.Polygon2DList, 0),
StageDiscreteW: stageDiscreteW,
StageDiscreteH: stageDiscreteH,
StageTileW: stageTileW,
StageTileH: stageTileH,
}
for k, v := range modelInstance1 {
toRet.StrToVec2DListMap[k] = toPbVec2DList(v)
}
for k, v := range modelInstance2 {
toRet.StrToPolygon2DListMap[k] = toPbPolygon2DList(v)
func ToPbPolygon2DListMap(modelInstances map[string]*Polygon2DList) map[string]*pb.Polygon2DList {
toRet := make(map[string]*pb.Polygon2DList, len(modelInstances))
for k, v := range modelInstances {
toRet[k] = toPbPolygon2DList(v)
}
return toRet
}
@@ -90,114 +84,3 @@ func toPbPlayers(modelInstances map[int32]*Player) map[int32]*pb.Player {
return toRet
}
func toPbTreasures(modelInstances map[int32]*Treasure) map[int32]*pb.Treasure {
toRet := make(map[int32]*pb.Treasure, 0)
if nil == modelInstances {
return toRet
}
for k, last := range modelInstances {
toRet[k] = &pb.Treasure{
Id: last.Id,
LocalIdInBattle: last.LocalIdInBattle,
Score: last.Score,
X: last.X,
Y: last.Y,
Removed: last.Removed,
Type: last.Type,
}
}
return toRet
}
func toPbTraps(modelInstances map[int32]*Trap) map[int32]*pb.Trap {
toRet := make(map[int32]*pb.Trap, 0)
if nil == modelInstances {
return toRet
}
for k, last := range modelInstances {
toRet[k] = &pb.Trap{
Id: last.Id,
LocalIdInBattle: last.LocalIdInBattle,
X: last.X,
Y: last.Y,
Removed: last.Removed,
Type: last.Type,
}
}
return toRet
}
func toPbBullets(modelInstances map[int32]*Bullet) map[int32]*pb.Bullet {
toRet := make(map[int32]*pb.Bullet, 0)
if nil == modelInstances {
return toRet
}
for k, last := range modelInstances {
if nil == last.StartAtPoint || nil == last.EndAtPoint {
continue
}
toRet[k] = &pb.Bullet{
LocalIdInBattle: last.LocalIdInBattle,
LinearSpeed: last.LinearSpeed,
X: last.X,
Y: last.Y,
Removed: last.Removed,
StartAtPoint: &pb.Vec2D{
X: last.StartAtPoint.X,
Y: last.StartAtPoint.Y,
},
EndAtPoint: &pb.Vec2D{
X: last.EndAtPoint.X,
Y: last.EndAtPoint.Y,
},
}
}
return toRet
}
func toPbSpeedShoes(modelInstances map[int32]*SpeedShoe) map[int32]*pb.SpeedShoe {
toRet := make(map[int32]*pb.SpeedShoe, 0)
if nil == modelInstances {
return toRet
}
for k, last := range modelInstances {
toRet[k] = &pb.SpeedShoe{
Id: last.Id,
LocalIdInBattle: last.LocalIdInBattle,
X: last.X,
Y: last.Y,
Removed: last.Removed,
Type: last.Type,
}
}
return toRet
}
func toPbGuardTowers(modelInstances map[int32]*GuardTower) map[int32]*pb.GuardTower {
toRet := make(map[int32]*pb.GuardTower, 0)
if nil == modelInstances {
return toRet
}
for k, last := range modelInstances {
toRet[k] = &pb.GuardTower{
Id: last.Id,
LocalIdInBattle: last.LocalIdInBattle,
X: last.X,
Y: last.Y,
Removed: last.Removed,
Type: last.Type,
}
}
return toRet
}

View File

@@ -3,7 +3,6 @@ package models
import (
"database/sql"
"fmt"
"github.com/ByteArena/box2d"
sq "github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
)
@@ -37,7 +36,7 @@ type Player struct {
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Dir *Direction `json:"dir,omitempty"`
Speed int32 `json:"speed,omitempty"`
Speed float64 `json:"speed,omitempty"`
BattleState int32 `json:"battleState,omitempty"`
LastMoveGmtMillis int32 `json:"lastMoveGmtMillis,omitempty"`
Score int32 `json:"score,omitempty"`
@@ -48,16 +47,15 @@ type Player struct {
DisplayName string `json:"displayName,omitempty" db:"display_name"`
Avatar string `json:"avatar,omitempty"`
FrozenAtGmtMillis int64 `json:"-" db:"-"`
AddSpeedAtGmtMillis int64 `json:"-" db:"-"`
CreatedAt int64 `json:"-" db:"created_at"`
UpdatedAt int64 `json:"-" db:"updated_at"`
DeletedAt NullInt64 `json:"-" db:"deleted_at"`
TutorialStage int `json:"-" db:"tutorial_stage"`
CollidableBody *box2d.B2Body `json:"-"`
AckingFrameId int32 `json:"ackingFrameId"`
AckingInputFrameId int32 `json:"-"`
LastSentInputFrameId int32 `json:"-"`
FrozenAtGmtMillis int64 `json:"-" db:"-"`
AddSpeedAtGmtMillis int64 `json:"-" db:"-"`
CreatedAt int64 `json:"-" db:"created_at"`
UpdatedAt int64 `json:"-" db:"updated_at"`
DeletedAt NullInt64 `json:"-" db:"deleted_at"`
TutorialStage int `json:"-" db:"tutorial_stage"`
AckingFrameId int32 `json:"ackingFrameId"`
AckingInputFrameId int32 `json:"-"`
LastSentInputFrameId int32 `json:"-"`
}
func ExistPlayerByName(name string) (bool, error) {

View File

@@ -1,14 +0,0 @@
package models
import "github.com/ByteArena/box2d"
type Pumpkin struct {
LocalIdInBattle int32 `json:"localIdInBattle,omitempty"`
LinearSpeed float64 `json:"linearSpeed,omitempty"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Removed bool `json:"removed,omitempty"`
Dir *Direction `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
RemovedAtFrameId int32 `json:"-"`
}

View File

@@ -1,8 +1,8 @@
package models
type RingBuffer struct {
Ed int32 // write index
St int32 // read index
Ed int32 // write index, open index
St int32 // read index, closed index
EdFrameId int32
StFrameId int32
N int32

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,6 @@ package models
import (
"container/heap"
"fmt"
"github.com/gorilla/websocket"
"go.uber.org/zap"
. "server/common"
"sync"
@@ -92,43 +91,13 @@ func InitRoomHeapManager() {
for i := 0; i < initialCountOfRooms; i++ {
roomCapacity := 2
joinIndexBooleanArr := make([]bool, roomCapacity)
for index, _ := range joinIndexBooleanArr {
joinIndexBooleanArr[index] = false
}
currentRoomBattleState := RoomBattleStateIns.IDLE
pq[i] = &Room{
Id: int32(i + 1),
Players: make(map[int32]*Player),
PlayerDownsyncSessionDict: make(map[int32]*websocket.Conn),
PlayerSignalToCloseDict: make(map[int32]SignalToCloseConnCbType),
Capacity: roomCapacity,
Score: calRoomScore(0, roomCapacity, currentRoomBattleState),
State: currentRoomBattleState,
Index: i,
Tick: 0,
EffectivePlayerCount: 0,
//BattleDurationNanos: int64(5 * 1000 * 1000 * 1000),
BattleDurationNanos: int64(30 * 1000 * 1000 * 1000),
ServerFPS: 60,
Treasures: make(map[int32]*Treasure),
Traps: make(map[int32]*Trap),
GuardTowers: make(map[int32]*GuardTower),
Bullets: make(map[int32]*Bullet),
SpeedShoes: make(map[int32]*SpeedShoe),
Barriers: make(map[int32]*Barrier),
Pumpkins: make(map[int32]*Pumpkin),
AccumulatedLocalIdForBullets: 0,
AllPlayerInputsBuffer: NewRingBuffer(1024),
LastAllConfirmedInputFrameId: -1,
LastAllConfirmedInputFrameIdWithChange: -1,
LastAllConfirmedInputList: make([]uint64, roomCapacity),
InputDelayFrames: 4,
InputScaleFrames: 2,
JoinIndexBooleanArr: joinIndexBooleanArr,
Id: int32(i + 1),
Capacity: roomCapacity,
Index: i,
}
roomMap[pq[i].Id] = pq[i]
pq[i].ChooseStage()
pq[i].OnDismissed()
}
heap.Init(&pq)
RoomHeapManagerIns = &pq

View File

@@ -1,17 +0,0 @@
package models
import (
"github.com/ByteArena/box2d"
)
type SpeedShoe struct {
Id int32 `json:"id,omitempty"`
LocalIdInBattle int32 `json:"localIdInBattle,omitempty"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Removed bool `json:"removed,omitempty"`
Type int32 `json:"type,omitempty"`
PickupBoundary *Polygon2D `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
RemovedAtFrameId int32 `json:"-"`
}

View File

@@ -6,8 +6,6 @@ import (
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"github.com/ByteArena/box2d"
"go.uber.org/zap"
"io/ioutil"
"math"
@@ -19,8 +17,7 @@ import (
const (
LOW_SCORE_TREASURE_TYPE = 1
HIGH_SCORE_TREASURE_TYPE = 2
SPEED_SHOES_TYPE = 3
SPEED_SHOES_TYPE = 3
LOW_SCORE_TREASURE_SCORE = 100
HIGH_SCORE_TREASURE_SCORE = 200
@@ -182,17 +179,12 @@ type Polygon2DList []*Polygon2D
type StrToVec2DListMap map[string]*Vec2DList // Note that it's deliberately NOT using "map[string]Vec2DList", for the easy of passing return value to "models/room.go".
type StrToPolygon2DListMap map[string]*Polygon2DList // Note that it's deliberately NOT using "map[string]Polygon2DList", for the easy of passing return value to "models/room.go".
func TmxPolylineToPolygon2DInB2World(pTmxMapIns *TmxMap, singleObjInTmxFile *TmxOrTsxObject, targetPolyline *TmxOrTsxPolyline) (*Polygon2D, error) {
func tmxPolylineToPolygon2D(pTmxMapIns *TmxMap, singleObjInTmxFile *TmxOrTsxObject, targetPolyline *TmxOrTsxPolyline) (*Polygon2D, error) {
if nil == targetPolyline {
return nil, nil
}
singleValueArray := strings.Split(targetPolyline.Points, " ")
pointsCount := len(singleValueArray)
if pointsCount >= box2d.B2_maxPolygonVertices {
return nil, errors.New(fmt.Sprintf("During `TmxPolylineToPolygon2DInB2World`, you have a polygon with pointsCount == %v, exceeding or equal to box2d.B2_maxPolygonVertices == %v, of polyines [%v]", pointsCount, box2d.B2_maxPolygonVertices, singleValueArray))
}
theUntransformedAnchor := &Vec2D{
X: singleObjInTmxFile.X,
@@ -218,7 +210,6 @@ func TmxPolylineToPolygon2DInB2World(pTmxMapIns *TmxMap, singleObjInTmxFile *Tmx
}
}
// Transform to B2World space coordinate.
tmp := &Vec2D{
X: thePolygon2DFromPolyline.Points[k].X,
Y: thePolygon2DFromPolyline.Points[k].Y,
@@ -231,7 +222,7 @@ func TmxPolylineToPolygon2DInB2World(pTmxMapIns *TmxMap, singleObjInTmxFile *Tmx
return thePolygon2DFromPolyline, nil
}
func TsxPolylineToOffsetsWrtTileCenterInB2World(pTmxMapIns *TmxMap, singleObjInTsxFile *TmxOrTsxObject, targetPolyline *TmxOrTsxPolyline, pTsxIns *Tsx) (*Polygon2D, error) {
func tsxPolylineToOffsetsWrtTileCenter(pTmxMapIns *TmxMap, singleObjInTsxFile *TmxOrTsxObject, targetPolyline *TmxOrTsxPolyline, pTsxIns *Tsx) (*Polygon2D, error) {
if nil == targetPolyline {
return nil, nil
}
@@ -242,10 +233,6 @@ func TsxPolylineToOffsetsWrtTileCenterInB2World(pTmxMapIns *TmxMap, singleObjInT
singleValueArray := strings.Split(targetPolyline.Points, " ")
pointsCount := len(singleValueArray)
if pointsCount >= box2d.B2_maxPolygonVertices {
return nil, errors.New(fmt.Sprintf("During `TsxPolylineToOffsetsWrtTileCenterInB2World`, you have a polygon with pointsCount == %v, exceeding or equal to box2d.B2_maxPolygonVertices == %v", pointsCount, box2d.B2_maxPolygonVertices))
}
thePolygon2DFromPolyline := &Polygon2D{
Anchor: nil,
Points: make([]*Vec2D, pointsCount),
@@ -254,7 +241,7 @@ func TsxPolylineToOffsetsWrtTileCenterInB2World(pTmxMapIns *TmxMap, singleObjInT
}
/*
[WARNING] In this case, the "Treasure"s and "GuardTower"s are put into Tmx file as "ImageObject"s, of each the "ProportionalAnchor" is (0.5, 0). Therefore we calculate that "thePolygon2DFromPolyline.Points" are "offsets(in B2World) w.r.t. the BottomCenter". See https://shimo.im/docs/SmLJJhXm2C8XMzZT for details.
[WARNING] In this case, the "Treasure"s and "GuardTower"s are put into Tmx file as "ImageObject"s, of each the "ProportionalAnchor" is (0.5, 0). Therefore the "thePolygon2DFromPolyline.Points" are "offsets w.r.t. the BottomCenter". See https://shimo.im/docs/SmLJJhXm2C8XMzZT for details.
*/
for k, value := range singleValueArray {
@@ -272,14 +259,12 @@ func TsxPolylineToOffsetsWrtTileCenterInB2World(pTmxMapIns *TmxMap, singleObjInT
thePolygon2DFromPolyline.Points[k].Y = float64(pTsxIns.TileHeight) - (coordinateValue + offsetFromTopLeftInTileLocalCoordY)
}
}
// No need to transform for B2World space coordinate because the marks in a Tsx file is already rectilinear.
}
return thePolygon2DFromPolyline, nil
}
func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, firstGid int, gidBoundariesMapInB2World map[int]StrToPolygon2DListMap) error {
func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, firstGid int, gidBoundariesMap map[int]StrToPolygon2DListMap) error {
pTsxIns := &Tsx{}
err := xml.Unmarshal(byteArrOfTsxFile, pTsxIns)
if nil != err {
@@ -297,7 +282,7 @@ func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, f
for _, tile := range pTsxIns.Tiles {
globalGid := (firstGid + int(tile.Id))
/**
Per tile xml str could be
A tile xml string could be
```
<tile id="13">
@@ -313,7 +298,7 @@ func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, f
```
, we currently REQUIRE that "`an object of a tile` with ONE OR MORE polylines must come with a single corresponding '<property name=`type` value=`...` />', and viceversa".
Refer to https://shimo.im/docs/SmLJJhXm2C8XMzZT for how we theoretically fit a "Polyline in Tsx" into a "Polygon2D" and then into the corresponding "B2BodyDef & B2Body in the `world of colliding bodies`".
Refer to https://shimo.im/docs/SmLJJhXm2C8XMzZT for how we theoretically fit a "Polyline in Tsx" into a "Polygon2D".
*/
theObjGroup := tile.ObjectGroup
@@ -332,11 +317,11 @@ func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, f
key := singleObj.Properties.Property[0].Value
var theStrToPolygon2DListMap StrToPolygon2DListMap
if existingStrToPolygon2DListMap, ok := gidBoundariesMapInB2World[globalGid]; ok {
if existingStrToPolygon2DListMap, ok := gidBoundariesMap[globalGid]; ok {
theStrToPolygon2DListMap = existingStrToPolygon2DListMap
} else {
gidBoundariesMapInB2World[globalGid] = make(StrToPolygon2DListMap, 0)
theStrToPolygon2DListMap = gidBoundariesMapInB2World[globalGid]
gidBoundariesMap[globalGid] = make(StrToPolygon2DListMap, 0)
theStrToPolygon2DListMap = gidBoundariesMap[globalGid]
}
var pThePolygon2DList *Polygon2DList
@@ -348,7 +333,7 @@ func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, f
pThePolygon2DList = theStrToPolygon2DListMap[key]
}
thePolygon2DFromPolyline, err := TsxPolylineToOffsetsWrtTileCenterInB2World(pTmxMapIns, singleObj, singleObj.Polyline, pTsxIns)
thePolygon2DFromPolyline, err := tsxPolylineToOffsetsWrtTileCenter(pTmxMapIns, singleObj, singleObj.Polyline, pTsxIns)
if nil != err {
panic(err)
}
@@ -358,18 +343,9 @@ func DeserializeTsxToColliderDict(pTmxMapIns *TmxMap, byteArrOfTsxFile []byte, f
return nil
}
func ParseTmxLayersAndGroups(pTmxMapIns *TmxMap, gidBoundariesMapInB2World map[int]StrToPolygon2DListMap) (int32, int32, int32, int32, StrToVec2DListMap, StrToPolygon2DListMap, error) {
func ParseTmxLayersAndGroups(pTmxMapIns *TmxMap, gidBoundariesMap map[int]StrToPolygon2DListMap) (int32, int32, int32, int32, StrToVec2DListMap, StrToPolygon2DListMap, error) {
toRetStrToVec2DListMap := make(StrToVec2DListMap, 0)
toRetStrToPolygon2DListMap := make(StrToPolygon2DListMap, 0)
/*
Note that both
- "Vec2D"s of "toRetStrToVec2DListMap", and
- "Polygon2D"s of "toRetStrToPolygon2DListMap"
are already transformed into the "coordinate of B2World".
-- YFLu
*/
for _, objGroup := range pTmxMapIns.ObjectGroups {
switch objGroup.Name {
@@ -379,10 +355,8 @@ func ParseTmxLayersAndGroups(pTmxMapIns *TmxMap, gidBoundariesMapInB2World map[i
if false == ok {
theVec2DListToCache := make(Vec2DList, 0)
toRetStrToVec2DListMap[objGroup.Name] = &theVec2DListToCache
pTheVec2DListToCache = toRetStrToVec2DListMap[objGroup.Name]
} else {
pTheVec2DListToCache = toRetStrToVec2DListMap[objGroup.Name]
}
pTheVec2DListToCache = toRetStrToVec2DListMap[objGroup.Name]
for _, singleObjInTmxFile := range objGroup.Objects {
theUntransformedPos := &Vec2D{
X: singleObjInTmxFile.X,
@@ -391,22 +365,15 @@ func ParseTmxLayersAndGroups(pTmxMapIns *TmxMap, gidBoundariesMapInB2World map[i
thePosInWorld := pTmxMapIns.continuousObjLayerOffsetToContinuousMapNodePos(theUntransformedPos)
*pTheVec2DListToCache = append(*pTheVec2DListToCache, &thePosInWorld)
}
case "Pumpkin", "SpeedShoe":
case "Barrier":
/*
Note that in this case, the "Polygon2D.Anchor" of each "TmxOrTsxObject" is located exactly in an overlapping with "Polygon2D.Points[0]" w.r.t. B2World.
-- YFLu
*/
// Note that in this case, the "Polygon2D.Anchor" of each "TmxOrTsxObject" is exactly overlapping with "Polygon2D.Points[0]".
var pThePolygon2DListToCache *Polygon2DList
_, ok := toRetStrToPolygon2DListMap[objGroup.Name]
if false == ok {
thePolygon2DListToCache := make(Polygon2DList, 0)
toRetStrToPolygon2DListMap[objGroup.Name] = &thePolygon2DListToCache
pThePolygon2DListToCache = toRetStrToPolygon2DListMap[objGroup.Name]
} else {
pThePolygon2DListToCache = toRetStrToPolygon2DListMap[objGroup.Name]
}
pThePolygon2DListToCache = toRetStrToPolygon2DListMap[objGroup.Name]
for _, singleObjInTmxFile := range objGroup.Objects {
if nil == singleObjInTmxFile.Polyline {
@@ -416,71 +383,12 @@ func ParseTmxLayersAndGroups(pTmxMapIns *TmxMap, gidBoundariesMapInB2World map[i
continue
}
thePolygon2DInWorld, err := TmxPolylineToPolygon2DInB2World(pTmxMapIns, singleObjInTmxFile, singleObjInTmxFile.Polyline)
thePolygon2DInWorld, err := tmxPolylineToPolygon2D(pTmxMapIns, singleObjInTmxFile, singleObjInTmxFile.Polyline)
if nil != err {
panic(err)
}
*pThePolygon2DListToCache = append(*pThePolygon2DListToCache, thePolygon2DInWorld)
}
case "LowScoreTreasure", "GuardTower", "HighScoreTreasure":
/*
Note that in this case, the "Polygon2D.Anchor" of each "TmxOrTsxObject" ISN'T located exactly in an overlapping with "Polygon2D.Points[0]" w.r.t. B2World, refer to "https://shimo.im/docs/SmLJJhXm2C8XMzZT" for details.
-- YFLu
*/
for _, singleObjInTmxFile := range objGroup.Objects {
if nil == singleObjInTmxFile.Gid {
continue
}
theGlobalGid := singleObjInTmxFile.Gid
theStrToPolygon2DListMap, ok := gidBoundariesMapInB2World[*theGlobalGid]
if false == ok {
continue
}
pThePolygon2DList, ok := theStrToPolygon2DListMap[objGroup.Name]
if false == ok {
continue
}
var pThePolygon2DListToCache *Polygon2DList
_, ok = toRetStrToPolygon2DListMap[objGroup.Name]
if false == ok {
thePolygon2DListToCache := make(Polygon2DList, 0)
toRetStrToPolygon2DListMap[objGroup.Name] = &thePolygon2DListToCache
pThePolygon2DListToCache = toRetStrToPolygon2DListMap[objGroup.Name]
} else {
pThePolygon2DListToCache = toRetStrToPolygon2DListMap[objGroup.Name]
}
for _, thePolygon2D := range *pThePolygon2DList {
theUntransformedBottomCenterAsAnchor := &Vec2D{
X: singleObjInTmxFile.X,
Y: singleObjInTmxFile.Y,
}
theTransformedBottomCenterAsAnchor := pTmxMapIns.continuousObjLayerOffsetToContinuousMapNodePos(theUntransformedBottomCenterAsAnchor)
thePolygon2DInWorld := &Polygon2D{
Anchor: &theTransformedBottomCenterAsAnchor,
Points: make([]*Vec2D, len(thePolygon2D.Points)),
TileWidth: thePolygon2D.TileWidth,
TileHeight: thePolygon2D.TileHeight,
}
if nil != singleObjInTmxFile.Width && nil != singleObjInTmxFile.Height {
thePolygon2DInWorld.TmxObjectWidth = *singleObjInTmxFile.Width
thePolygon2DInWorld.TmxObjectHeight = *singleObjInTmxFile.Height
}
for kk, p := range thePolygon2D.Points {
// [WARNING] It's intentionally recreating a copy of "Vec2D" here.
thePolygon2DInWorld.Points[kk] = &Vec2D{
X: p.X,
Y: p.Y,
}
}
*pThePolygon2DListToCache = append(*pThePolygon2DListToCache, thePolygon2DInWorld)
}
}
default:
}
}

View File

@@ -1,39 +0,0 @@
package models
import (
"github.com/ByteArena/box2d"
)
type Trap struct {
Id int32 `json:"id,omitempty"`
LocalIdInBattle int32 `json:"localIdInBattle,omitempty"`
Type int32 `json:"type,omitempty"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Removed bool `json:"removed,omitempty"`
PickupBoundary *Polygon2D `json:"-"`
TrapBullets []*Bullet `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
RemovedAtFrameId int32 `json:"-"`
}
type GuardTower struct {
Id int32 `json:"id,omitempty"`
LocalIdInBattle int32 `json:"localIdInBattle,omitempty"`
Type int32 `json:"type,omitempty"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Removed bool `json:"removed,omitempty"`
PickupBoundary *Polygon2D `json:"-"`
TrapBullets []*Bullet `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
RemovedAtFrameId int32 `json:"-"`
InRangePlayers *InRangePlayerCollection `json:"-"`
LastAttackTick int64 `json:"-"`
TileWidth float64 `json:"-"`
TileHeight float64 `json:"-"`
WidthInB2World float64 `json:"-"`
HeightInB2World float64 `json:"-"`
}

View File

@@ -1,18 +0,0 @@
package models
import (
"github.com/ByteArena/box2d"
)
type Treasure struct {
Id int32 `json:"id,omitempty"`
LocalIdInBattle int32 `json:"localIdInBattle,omitempty"`
Score int32 `json:"score,omitempty"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Removed bool `json:"removed,omitempty"`
Type int32 `json:"type,omitempty"`
PickupBoundary *Polygon2D `json:"-"`
CollidableBody *box2d.B2Body `json:"-"`
}

File diff suppressed because it is too large Load Diff

View File

@@ -240,16 +240,37 @@ func Serve(c *gin.Context) {
})
}()
playerBattleColliderInfo := models.ToPbStrToBattleColliderInfo(int32(Constants.Ws.IntervalToPing), int32(Constants.Ws.WillKickIfInactiveFor), pRoom.Id, pRoom.StageName, pRoom.RawBattleStrToVec2DListMap, pRoom.RawBattleStrToPolygon2DListMap, pRoom.StageDiscreteW, pRoom.StageDiscreteH, pRoom.StageTileW, pRoom.StageTileH)
// Construct "battleColliderInfo" to downsync
bciFrame := &pb.BattleColliderInfo{
BoundRoomId: pRoom.Id,
StageName: pRoom.StageName,
StrToVec2DListMap: models.ToPbVec2DListMap(pRoom.RawBattleStrToVec2DListMap),
StrToPolygon2DListMap: models.ToPbPolygon2DListMap(pRoom.RawBattleStrToPolygon2DListMap),
StageDiscreteW: pRoom.StageDiscreteW,
StageDiscreteH: pRoom.StageDiscreteH,
StageTileW: pRoom.StageTileW,
StageTileH: pRoom.StageTileH,
IntervalToPing: int32(Constants.Ws.IntervalToPing),
WillKickIfInactiveFor: int32(Constants.Ws.WillKickIfInactiveFor),
BattleDurationNanos: pRoom.BattleDurationNanos,
ServerFps: pRoom.ServerFps,
InputDelayFrames: pRoom.InputDelayFrames,
InputScaleFrames: pRoom.InputScaleFrames,
NstDelayFrames: pRoom.NstDelayFrames,
InputFrameUpsyncDelayTolerance: pRoom.InputFrameUpsyncDelayTolerance,
MaxChasingRenderFramesPerUpdate: pRoom.MaxChasingRenderFramesPerUpdate,
PlayerBattleState: pThePlayer.BattleState, // For frontend to know whether it's rejoining
}
resp := &pb.WsResp{
Ret: int32(Constants.RetCode.Ok),
EchoedMsgId: int32(0),
Act: models.DOWNSYNC_MSG_ACT_HB_REQ,
BciFrame: playerBattleColliderInfo,
BciFrame: bciFrame,
}
// Logger.Info("Sending downsync HeartbeatRequirements:", zap.Any("roomId", pRoom.Id), zap.Any("playerId", playerId), zap.Any("resp", resp))
Logger.Debug("Sending downsync HeartbeatRequirements:", zap.Any("roomId", pRoom.Id), zap.Any("playerId", playerId), zap.Any("resp", resp))
theBytes, marshalErr := proto.Marshal(resp)
if nil != marshalErr {

View File

@@ -1,6 +1,5 @@
"use strict";
var _ROUTE_PATH;
function _defineProperty(obj, key, value) {
@@ -29,23 +28,6 @@ var constants = {
BGM: "BGM"
}
},
PLAYER_NAME: {
1: "Merdan",
2: "Monroe",
},
SOCKET_EVENT: {
CONTROL: "control",
SYNC: "sync",
LOGIN: "login",
CREATE: "create"
},
WECHAT: {
AUTHORIZE_PATH: "/connect/oauth2/authorize",
REDIRECT_RUI_KEY: "redirect_uri=",
RESPONSE_TYPE: "response_type=code",
SCOPE: "scope=snsapi_userinfo",
FIN: "#wechat_redirect"
},
ROUTE_PATH: (_ROUTE_PATH = {
PLAYER: "/player",
JSCONFIG: "/jsconfig",
@@ -61,8 +43,6 @@ var constants = {
LIST: "/list",
READ: "/read",
PROFILE: "/profile",
WECHAT: "/wechat",
WECHATGAME: "/wechatGame",
FETCH: "/fetch",
}, _defineProperty(_ROUTE_PATH, "LOGIN", "/login"), _defineProperty(_ROUTE_PATH, "RET_CODE", "/retCode"), _defineProperty(_ROUTE_PATH, "REGEX", "/regex"), _defineProperty(_ROUTE_PATH, "SMS_CAPTCHA", "/SmsCaptcha"), _defineProperty(_ROUTE_PATH, "GET", "/get"), _ROUTE_PATH),
REQUEST_QUERY: {
@@ -138,7 +118,6 @@ var constants = {
INCORRECT_PHONE_NUMBER: '手机号不正确',
LOG_OUT: '您已在其他地方登陆',
GAME_OVER: '游戏结束,您的得分是',
WECHAT_LOGIN_FAILS: "微信登录失败",
},
CONFIRM_BUTTON_LABEL: {
RESTART: '重新开始'

View File

@@ -27,17 +27,25 @@ message Polygon2DList {
}
message BattleColliderInfo {
int32 intervalToPing = 1;
int32 willKickIfInactiveFor = 2;
int32 boundRoomId = 3;
string stageName = 1;
map<string, Vec2DList> strToVec2DListMap = 2;
map<string, Polygon2DList> strToPolygon2DListMap = 3;
int32 stageDiscreteW = 4;
int32 stageDiscreteH = 5;
int32 stageTileW = 6;
int32 stageTileH = 7;
string stageName = 4;
map<string, Vec2DList> strToVec2DListMap = 5;
map<string, Polygon2DList> strToPolygon2DListMap = 6;
int32 StageDiscreteW = 7;
int32 StageDiscreteH = 8;
int32 StageTileW = 9;
int32 StageTileH = 10;
int32 intervalToPing = 8;
int32 willKickIfInactiveFor = 9;
int32 boundRoomId = 10;
int64 battleDurationNanos = 11;
int32 serverFps = 12;
int32 inputDelayFrames = 13;
uint32 inputScaleFrames = 14;
int32 nstDelayFrames = 15;
int32 inputFrameUpsyncDelayTolerance = 16;
int32 maxChasingRenderFramesPerUpdate = 17;
int32 playerBattleState = 18;
}
message Player {
@@ -45,7 +53,7 @@ message Player {
double x = 2;
double y = 3;
Direction dir = 4;
int32 speed = 5;
double speed = 5;
int32 battleState = 6;
int32 lastMoveGmtMillis = 7;
int32 score = 10;
@@ -61,76 +69,6 @@ message PlayerMeta {
int32 joinIndex = 5;
}
message Treasure {
int32 id = 1;
int32 localIdInBattle = 2;
int32 score = 3;
double x = 4;
double y = 5;
bool removed = 6;
int32 type = 7;
}
message Bullet {
int32 localIdInBattle = 1;
double linearSpeed = 2;
double x = 3;
double y = 4;
bool removed = 5;
Vec2D startAtPoint = 6;
Vec2D endAtPoint = 7;
}
message Trap {
int32 id = 1;
int32 localIdInBattle = 2;
int32 type = 3;
double x = 4;
double y = 5;
bool removed = 6;
}
message SpeedShoe {
int32 id = 1;
int32 localIdInBattle = 2;
double x = 3;
double y = 4;
bool removed = 5;
int32 type = 6;
}
message Pumpkin {
int32 localIdInBattle = 1;
double linearSpeed = 2;
double x = 3;
double y = 4;
bool removed = 5;
}
message GuardTower {
int32 id = 1;
int32 localIdInBattle = 2;
int32 type = 3;
double x = 4;
double y = 5;
bool removed = 6;
}
message RoomDownsyncFrame {
int32 id = 1;
int32 refFrameId = 2;
map<int32, Player> players = 3;
int64 sentAt = 4;
int64 countdownNanos = 5;
map<int32, Treasure> treasures = 6;
map<int32, Trap> traps = 7;
map<int32, Bullet> bullets = 8;
map<int32, SpeedShoe> speedShoes = 9;
map<int32, Pumpkin> pumpkin = 10;
map<int32, GuardTower> guardTowers = 11;
map<int32, PlayerMeta> playerMetas = 12;
}
message InputFrameUpsync {
int32 inputFrameId = 1;
int32 encodedDir = 6;
@@ -146,6 +84,13 @@ message HeartbeatUpsync {
int64 clientTimestamp = 1;
}
message RoomDownsyncFrame {
int32 id = 1;
map<int32, Player> players = 2;
int64 countdownNanos = 3;
map<int32, PlayerMeta> playerMetas = 4;
}
message WsReq {
int32 msgId = 1;
int32 playerId = 2;

View File

@@ -8,7 +8,8 @@
"__id__": 1
},
"optimizationPolicy": 0,
"asyncLoadAssets": false
"asyncLoadAssets": false,
"readonly": false
},
{
"__type__": "cc.Node",
@@ -27,7 +28,6 @@
}
],
"_active": true,
"_level": 1,
"_components": [
{
"__id__": 11
@@ -63,17 +63,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 2,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -89,7 +78,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 2,
"groupIndex": 2,
"_id": ""
},
{
"__type__": "cc.Node",
@@ -100,7 +101,6 @@
},
"_children": [],
"_active": false,
"_level": 0,
"_components": [
{
"__id__": 3
@@ -127,17 +127,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -153,7 +142,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.Label",
@@ -163,6 +164,7 @@
"__id__": 2
},
"_enabled": true,
"_materials": [],
"_useOriginalSize": false,
"_string": "(0, 0)",
"_N$string": "(0, 0)",
@@ -200,7 +202,6 @@
},
"_children": [],
"_active": false,
"_level": 2,
"_components": [
{
"__id__": 6
@@ -227,17 +228,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -253,7 +243,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.ParticleSystem",
@@ -263,6 +265,9 @@
"__id__": 5
},
"_enabled": true,
"_materials": [],
"_srcBlendFactor": 770,
"_dstBlendFactor": 1,
"_custom": true,
"_file": {
"__uuid__": "b2687ac4-099e-403c-a192-ff477686f4f5"
@@ -271,8 +276,6 @@
"__uuid__": "472df5d3-35e7-4184-9e6c-7f41bee65ee3"
},
"_texture": null,
"_srcBlendFactor": 770,
"_dstBlendFactor": 1,
"_stopped": false,
"playOnLoad": true,
"autoRemoveOnFinish": false,
@@ -329,6 +332,7 @@
"x": 7,
"y": 7
},
"_positionType": 1,
"positionType": 1,
"emitterMode": 0,
"gravity": {
@@ -372,7 +376,6 @@
},
"_children": [],
"_active": true,
"_level": 2,
"_components": [
{
"__id__": 9
@@ -399,17 +402,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -425,7 +417,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.Sprite",
@@ -435,6 +439,13 @@
"__id__": 8
},
"_enabled": true,
"_materials": [
{
"__uuid__": "eca5d2f2-8ef6-41c2-bbe6-f9c79d09c432"
}
],
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_spriteFrame": {
"__uuid__": "a2170e4c-df31-41ef-be73-f4f605e75821"
},
@@ -449,12 +460,9 @@
"_fillStart": 0,
"_fillRange": 0,
"_isTrimmedMode": true,
"_state": 0,
"_atlas": {
"__uuid__": "030d9286-e8a2-40cf-98f8-baf713f0b8c4"
},
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_id": ""
},
{
@@ -476,6 +484,9 @@
"__id__": 1
},
"_enabled": true,
"_materials": [],
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_spriteFrame": null,
"_type": 0,
"_sizeMode": 0,
@@ -488,10 +499,7 @@
"_fillStart": 0,
"_fillRange": 0,
"_isTrimmedMode": true,
"_state": 0,
"_atlas": null,
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_id": ""
},
{
@@ -549,8 +557,8 @@
},
"_enabled": true,
"animComp": null,
"baseSpeed": 300,
"speed": 200,
"baseSpeed": 50,
"speed": 50,
"lastMovedAt": 0,
"eps": 0.1,
"magicLeanLowerBound": 0.414,

View File

@@ -8,7 +8,8 @@
"__id__": 1
},
"optimizationPolicy": 0,
"asyncLoadAssets": false
"asyncLoadAssets": false,
"readonly": false
},
{
"__type__": "cc.Node",
@@ -27,7 +28,6 @@
}
],
"_active": true,
"_level": 1,
"_components": [
{
"__id__": 11
@@ -63,17 +63,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 2,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -89,7 +78,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 2,
"groupIndex": 2,
"_id": ""
},
{
"__type__": "cc.Node",
@@ -100,7 +101,6 @@
},
"_children": [],
"_active": false,
"_level": 0,
"_components": [
{
"__id__": 3
@@ -127,17 +127,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -153,7 +142,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.Label",
@@ -163,6 +164,7 @@
"__id__": 2
},
"_enabled": true,
"_materials": [],
"_useOriginalSize": false,
"_string": "(0, 0)",
"_N$string": "(0, 0)",
@@ -200,7 +202,6 @@
},
"_children": [],
"_active": false,
"_level": 2,
"_components": [
{
"__id__": 6
@@ -227,17 +228,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -253,7 +243,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.ParticleSystem",
@@ -263,6 +265,9 @@
"__id__": 5
},
"_enabled": true,
"_materials": [],
"_srcBlendFactor": 770,
"_dstBlendFactor": 1,
"_custom": true,
"_file": {
"__uuid__": "b2687ac4-099e-403c-a192-ff477686f4f5"
@@ -271,8 +276,6 @@
"__uuid__": "472df5d3-35e7-4184-9e6c-7f41bee65ee3"
},
"_texture": null,
"_srcBlendFactor": 770,
"_dstBlendFactor": 1,
"_stopped": false,
"playOnLoad": true,
"autoRemoveOnFinish": false,
@@ -329,6 +332,7 @@
"x": 7,
"y": 7
},
"_positionType": 1,
"positionType": 1,
"emitterMode": 0,
"gravity": {
@@ -372,7 +376,6 @@
},
"_children": [],
"_active": true,
"_level": 2,
"_components": [
{
"__id__": 9
@@ -399,17 +402,6 @@
"x": 0.5,
"y": 0.5
},
"_quat": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_skewX": 0,
"_skewY": 0,
"groupIndex": 0,
"_id": "",
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
@@ -425,7 +417,19 @@
1,
1
]
}
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.Sprite",
@@ -435,6 +439,13 @@
"__id__": 8
},
"_enabled": true,
"_materials": [
{
"__uuid__": "eca5d2f2-8ef6-41c2-bbe6-f9c79d09c432"
}
],
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_spriteFrame": {
"__uuid__": "a2170e4c-df31-41ef-be73-f4f605e75821"
},
@@ -449,12 +460,9 @@
"_fillStart": 0,
"_fillRange": 0,
"_isTrimmedMode": true,
"_state": 0,
"_atlas": {
"__uuid__": "030d9286-e8a2-40cf-98f8-baf713f0b8c4"
},
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_id": ""
},
{
@@ -476,6 +484,9 @@
"__id__": 1
},
"_enabled": true,
"_materials": [],
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_spriteFrame": null,
"_type": 0,
"_sizeMode": 0,
@@ -488,10 +499,7 @@
"_fillStart": 0,
"_fillRange": 0,
"_isTrimmedMode": true,
"_state": 0,
"_atlas": null,
"_srcBlendFactor": 770,
"_dstBlendFactor": 771,
"_id": ""
},
{
@@ -549,8 +557,8 @@
},
"_enabled": true,
"animComp": null,
"baseSpeed": 300,
"speed": 200,
"baseSpeed": 50,
"speed": 50,
"lastMovedAt": 0,
"eps": 0.1,
"magicLeanLowerBound": 0.414,

View File

@@ -440,7 +440,7 @@
"array": [
0,
0,
209.7912853806815,
216.50635094610968,
0,
0,
0,
@@ -2991,9 +2991,6 @@
"loadingPrefab": {
"__uuid__": "f2a3cece-30bf-4f62-bc20-34d44a9ddf98"
},
"wechatLoginTips": {
"__id__": 68
},
"_id": "51YNpecnJBea8vzAxGdkv2"
},
{

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +0,0 @@
{
"ver": "1.2.5",
"uuid": "475b849b-44b3-4390-982d-bd0d9e695093",
"asyncLoadAssets": false,
"autoReleaseAssets": false,
"subMetas": {}
}

View File

@@ -8,11 +8,11 @@ module.export = cc.Class({
},
baseSpeed: {
type: cc.Float,
default: 300,
default: 50,
},
speed: {
type: cc.Float,
default: 300
default: 50
},
lastMovedAt: {
type: cc.Float,
@@ -35,12 +35,6 @@ module.export = cc.Class({
// LIFE-CYCLE CALLBACKS:
start() {
const self = this;
self.contactedControlledPlayers = [];
self.contactedNPCPlayers = [];
self.coveringShelterZReducers = [];
self.computedNewDifferentPosLocalToParentWithinCurrentFrame = null;
self.actionMangerSingleton = new cc.ActionManager();
self.activeDirection = {
dx: 0,
dy: 0
@@ -61,7 +55,6 @@ module.export = cc.Class({
};
const canvasNode = self.mapNode.parent;
self.mapIns = self.mapNode.getComponent("Map");
self.contactedBarriers = [];
const joystickInputControllerScriptIns = canvasNode.getComponent("TouchEventsManager");
self.ctrl = joystickInputControllerScriptIns;
self.animComp = self.node.getComponent(cc.Animation);
@@ -93,330 +86,10 @@ module.export = cc.Class({
}
},
_addCoveringShelterZReducer(comp) {
const self = this;
for (let coveringShelterZReducer of self.coveringShelterZReducers) {
if (coveringShelterZReducer._id == comp._id) {
return false;
}
}
self.coveringShelterZReducers.push(comp);
return true;
},
_removeCoveringShelterZReducer(comp) {
const self = this;
self.coveringShelterZReducers = self.coveringShelterZReducers.filter((coveringShelterZReducer) => {
return coveringShelterZReducer._id != comp._id;
});
return true;
},
_addContactedBarrier(collider) {
const self = this;
if (!self.contactedBarriers) {
cc.log("self.contactedBarriers is null or undefined" + self.contactedBarriers)
}
for (let contactedBarrier of self.contactedBarriers) {
if (contactedBarrier._id == collider._id) {
return false;
}
}
self.contactedBarriers.push(collider);
return true;
},
_removeContactedBarrier(collider) {
const self = this;
self.contactedBarriers = self.contactedBarriers.filter((contactedBarrier) => {
return contactedBarrier._id != collider._id;
});
return true;
},
_addContactedControlledPlayers(comp) {
const self = this;
for (let aComp of self.contactedControlledPlayers) {
if (aComp.uuid == comp.uuid) {
return false;
}
}
self.contactedControlledPlayers.push(comp);
return true;
},
_removeContactedControlledPlayer(comp) {
const self = this;
self.contactedControlledPlayers = self.contactedControlledPlayers.filter((aComp) => {
return aComp.uuid != comp.uuid;
});
return true;
},
_addContactedNPCPlayers(comp) {
const self = this;
for (let aComp of self.contactedNPCPlayers) {
if (aComp.uuid == comp.uuid) {
return false;
}
}
self.contactedNPCPlayers.push(comp);
return true;
},
_removeContactedNPCPlayer(comp) {
const self = this;
self.contactedNPCPlayers = self.contactedNPCPlayers.filter((aComp) => {
return aComp.uuid != comp.uuid;
});
return true;
},
_canMoveBy(vecToMoveBy) {
const self = this;
const computedNewDifferentPosLocalToParentWithinCurrentFrame = self.node.position.add(vecToMoveBy);
self.computedNewDifferentPosLocalToParentWithinCurrentFrame = computedNewDifferentPosLocalToParentWithinCurrentFrame;
if (tileCollisionManager.isOutOfMapNode(self.mapNode, computedNewDifferentPosLocalToParentWithinCurrentFrame)) {
return false;
}
const currentSelfColliderCircle = self.node.getComponent(cc.CircleCollider);
let nextSelfColliderCircle = null;
if (0 < self.contactedBarriers.length) {
/* To avoid unexpected buckling. */
const mutatedVecToMoveBy = vecToMoveBy.mul(5); // To help it escape the engaged `contactedBarriers`.
nextSelfColliderCircle = {
position: self.node.position.add(mutatedVecToMoveBy).add(currentSelfColliderCircle.offset),
radius: currentSelfColliderCircle.radius,
};
} else {
nextSelfColliderCircle = {
position: computedNewDifferentPosLocalToParentWithinCurrentFrame.add(currentSelfColliderCircle.offset),
radius: currentSelfColliderCircle.radius,
};
}
for (let contactedBarrier of self.contactedBarriers) {
let contactedBarrierPolygonLocalToParentWithinCurrentFrame = [];
for (let p of contactedBarrier.points) {
contactedBarrierPolygonLocalToParentWithinCurrentFrame.push(contactedBarrier.node.position.add(p));
}
if (cc.Intersection.pointInPolygon(nextSelfColliderCircle.position, contactedBarrierPolygonLocalToParentWithinCurrentFrame)) {
// Make sure that the player is "leaving" the PolygonCollider.
return false;
}
if (cc.Intersection.polygonCircle(contactedBarrierPolygonLocalToParentWithinCurrentFrame, nextSelfColliderCircle)) {
if (null == self.firstContactedEdge) {
return false;
}
if (null != self.firstContactedEdge && self.firstContactedEdge.associatedBarrier != contactedBarrier) {
const res = self._calculateTangentialMovementAttrs(nextSelfColliderCircle, contactedBarrier);
if (null == res.contactedEdge) {
// Otherwise, the current movement is going to transit smoothly onto the next PolygonCollider.
return false;
}
}
}
}
return true;
/*
* In a subclass, use
*
* _canMoveBy(vecToMoveBy) {
* BasePlayer.prototype._canMoveBy.call(this, vecToMoveBy);
* // Customized codes.
* }
*
* Reference http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/class.html#override
*/
},
_calculateTangentialMovementAttrs(currentSelfColliderCircle, contactedBarrier) {
/*
* Theoretically when the `contactedBarrier` is a convex polygon and the `PlayerCollider` is a circle, there can be only 1 `contactedEdge` for each `contactedBarrier`. Except only for around the corner.
*
* We should avoid the possibility of players hitting the "corners of convex polygons" by map design wherever & whenever possible.
*
*/
const self = this;
const sDir = self.activeDirection;
const currentSelfColliderCircleCentrePos = (currentSelfColliderCircle.position ? currentSelfColliderCircle.position : self.node.position.add(currentSelfColliderCircle.offset));
const currentSelfColliderCircleRadius = currentSelfColliderCircle.radius;
let contactedEdgeCandidateList = [];
let skinDepthThreshold = 0.45*currentSelfColliderCircleRadius;
for (let i = 0; i < contactedBarrier.points.length; ++i) {
const stPoint = contactedBarrier.points[i].add(contactedBarrier.offset).add(contactedBarrier.node.position);
const edPoint = (i == contactedBarrier.points.length - 1 ? contactedBarrier.points[0].add(contactedBarrier.offset).add(contactedBarrier.node.position) : contactedBarrier.points[1 + i].add(contactedBarrier.offset).add(contactedBarrier.node.position));
const tmpVSt = stPoint.sub(currentSelfColliderCircleCentrePos);
const tmpVEd = edPoint.sub(currentSelfColliderCircleCentrePos);
const crossProdScalar = tmpVSt.cross(tmpVEd);
if (0 < crossProdScalar) {
// If moving parallel along `st <-> ed`, the trajectory of `currentSelfColliderCircleCentrePos` will cut inside the polygon.
continue;
}
const dis = cc.Intersection.pointLineDistance(currentSelfColliderCircleCentrePos, stPoint, edPoint, true);
if (dis > currentSelfColliderCircleRadius) continue;
if (dis < skinDepthThreshold) continue;
contactedEdgeCandidateList.push({
st: stPoint,
ed: edPoint,
associatedBarrier: contactedBarrier,
});
}
let contactedEdge = null;
let contactedEdgeDir = null;
let largestInnerProdAbs = Number.MIN_VALUE;
if (0 < contactedEdgeCandidateList.length) {
const sDirMag = Math.sqrt(sDir.dx * sDir.dx + sDir.dy * sDir.dy);
for (let contactedEdgeCandidate of contactedEdgeCandidateList) {
const tmp = contactedEdgeCandidate.ed.sub(contactedEdgeCandidate.st);
const contactedEdgeDirCandidate = {
dx: tmp.x,
dy: tmp.y,
};
const contactedEdgeDirCandidateMag = Math.sqrt(contactedEdgeDirCandidate.dx * contactedEdgeDirCandidate.dx + contactedEdgeDirCandidate.dy * contactedEdgeDirCandidate.dy);
const innerDotProd = (sDir.dx * contactedEdgeDirCandidate.dx + sDir.dy * contactedEdgeDirCandidate.dy)/(sDirMag * contactedEdgeDirCandidateMag);
const innerDotProdThresholdMag = 0.7;
if ((0 > innerDotProd && innerDotProd > -innerDotProdThresholdMag) || (0 < innerDotProd && innerDotProd < innerDotProdThresholdMag)) {
// Intentionally left blank, in this case the player is trying to escape from the `contactedEdge`.
continue;
} else if (innerDotProd > 0) {
const abs = Math.abs(innerDotProd);
if (abs > largestInnerProdAbs) {
contactedEdgeDir = contactedEdgeDirCandidate;
contactedEdge = contactedEdgeCandidate;
}
} else {
const abs = Math.abs(innerDotProd);
if (abs > largestInnerProdAbs) {
contactedEdgeDir = {
dx: -contactedEdgeDirCandidate.dx,
dy: -contactedEdgeDirCandidate.dy,
};
contactedEdge = contactedEdgeCandidate;
}
}
}
}
return {
contactedEdgeDir: contactedEdgeDir,
contactedEdge: contactedEdge,
};
},
_calculateVecToMoveByWithChosenDir(elapsedTime, sDir) {
if (0 == sDir.dx && 0 == sDir.dy) {
return cc.v2();
}
const self = this;
const distanceToMove = (self.speed * elapsedTime);
const denominator = Math.sqrt(sDir.dx * sDir.dx + sDir.dy * sDir.dy);
const unitProjDx = (sDir.dx / denominator);
const unitProjDy = (sDir.dy / denominator);
return cc.v2(
distanceToMove * unitProjDx,
distanceToMove * unitProjDy,
);
},
_calculateVecToMoveBy(elapsedTime) {
const self = this;
// Note that `sDir` used in this method MUST BE a copy in RAM.
let sDir = {
dx: self.activeDirection.dx,
dy: self.activeDirection.dy,
};
if (0 == sDir.dx && 0 == sDir.dy) {
return cc.v2();
}
self.firstContactedEdge = null; // Reset everytime (temporary algorithm design, might change later).
if (0 < self.contactedBarriers.length) {
/*
* Hardcoded to take care of only the 1st `contactedEdge` of the 1st `contactedBarrier` for now. Each `contactedBarrier` must be "counterclockwisely convex polygonal", otherwise sliding doesn't work!
*
*/
const contactedBarrier = self.contactedBarriers[0];
const currentSelfColliderCircle = self.node.getComponent(cc.CircleCollider);
const res = self._calculateTangentialMovementAttrs(currentSelfColliderCircle, contactedBarrier);
if (res.contactedEdge) {
self.firstContactedEdge = res.contactedEdge;
sDir = res.contactedEdgeDir;
}
}
return self._calculateVecToMoveByWithChosenDir(elapsedTime, sDir);
},
update(dt) {
const self = this;
const vecToMoveBy = self._calculateVecToMoveBy(self.mapIns.rollbackEstimatedDt); // To be consistent w.r.t. rollback dynamics
// console.log("activeDirection=", self.activeDirection, "vecToMoveBy=", vecToMoveBy, ", computedNewDifferentPosLocalToParentWithinCurrentFrame=", self.computedNewDifferentPosLocalToParentWithinCurrentFrame);
if (self._canMoveBy(vecToMoveBy)) {
self.node.position = self.computedNewDifferentPosLocalToParentWithinCurrentFrame;
}
},
lateUpdate(dt) {
const self = this;
const now = new Date().getTime();
self.lastMovedAt = now;
},
onCollisionEnter(other, self) {
const playerScriptIns = self.node.getComponent("SelfPlayer");
switch (other.node.name) {
case "NPCPlayer":
if ("NPCPlayer" != self.node.name) {
other.node.getComponent('NPCPlayer').showProfileTrigger();
}
playerScriptIns._addContactedNPCPlayers(other);
break;
case "PolygonBoundaryBarrier":
playerScriptIns._addContactedBarrier(other);
break;
case "PolygonBoundaryShelter":
break;
case "PolygonBoundaryShelterZReducer":
playerScriptIns._addCoveringShelterZReducer(other);
if (1 == playerScriptIns.coveringShelterZReducers.length) {
setLocalZOrder(self.node, 2);
}
break;
default:
break;
}
},
onCollisionStay(other, self) {
// TBD.
},
onCollisionExit(other, self) {
const playerScriptIns = self.getComponent("SelfPlayer");
switch (other.node.name) {
case "NPCPlayer":
other.node.getComponent('NPCPlayer').hideProfileTrigger();
playerScriptIns._removeContactedNPCPlayer(other);
break;
case "PolygonBoundaryBarrier":
playerScriptIns._removeContactedBarrier(other);
break;
case "PolygonBoundaryShelter":
break;
case "PolygonBoundaryShelterZReducer":
playerScriptIns._removeCoveringShelterZReducer(other);
if (0 == playerScriptIns.coveringShelterZReducers.length) {
setLocalZOrder(self.node, 5);
}
break;
default:
break;
}
},
_generateRandomDirection() {

View File

@@ -22,7 +22,7 @@ cc.Class({
if (!self.mapScriptIns) return;
if (!self.mapScriptIns.selfPlayerInfo) return;
if (!self.mapScriptIns.playerRichInfoDict) return;
const selfPlayerRichInfo = self.mapScriptIns.playerRichInfoDict[self.mapScriptIns.selfPlayerInfo.id];
const selfPlayerRichInfo = self.mapScriptIns.playerRichInfoDict.get(self.mapScriptIns.selfPlayerInfo.id);
if (!selfPlayerRichInfo) return;
const selfPlayerNode = selfPlayerRichInfo.node;
if (!selfPlayerNode) return;

View File

@@ -26,19 +26,6 @@ cc.Class({
// LIFE-CYCLE CALLBACKS:
onLoad() {
// WARNING: 不能保证在ws连接成功并且拿到boundRoomId后才运行到此处。
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
const boundRoomId = window.getBoundRoomIdFromPersistentStorage();
const wxToShareMessage = {
title: '夺宝大作战',
imageUrl: 'https://mmocgame.qpic.cn/wechatgame/ibxA6JVNslX02zq6aAWCZiaWTXLYGorrVgUszo3WH1oL1CFDcFU7VKPRXPFiadxagMR/0',
imageUrlId: 'FiLZpa5FT5GgEeEagzGBsA',
query: 'expectedRoomId=' + boundRoomId,
};
console.warn("The boundRoomId for sharing: ", boundRoomId, " wxToShareMessage ", wxToShareMessage);
wx.showShareMenu();
wx.onShareAppMessage(() => (wxToShareMessage));
}
},
init() {
@@ -73,11 +60,7 @@ cc.Class({
exitBtnOnClick(evt) {
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
window.closeWSConnection();
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
cc.director.loadScene('wechatGameLogin');
} else {
cc.director.loadScene('login');
}
cc.director.loadScene('login');
},
updatePlayersInfo(playerMetas) {
@@ -107,23 +90,7 @@ cc.Class({
if (remoteUrl == null || remoteUrl == '') {
cc.log(`No avatar to show for :`);
cc.log(playerMeta);
remoteUrl = 'http://wx.qlogo.cn/mmopen/PiajxSqBRaEJUWib5D85KXWHumaxhU4E9XOn9bUpCNKF3F4ibfOj8JYHCiaoosvoXCkTmOQE1r2AKKs8ObMaz76EdA/0'
}
cc.loader.load({
url: remoteUrl,
type: 'jpg'
}, function(err, texture) {
if (null != err ) {
console.error(err);
} else {
if (null == texture) {
return;
}
const sf = new cc.SpriteFrame();
sf.setTexture(texture);
playerInfoNode.getChildByName('avatarMask').getChildByName('avatar').getComponent(cc.Sprite).spriteFrame = sf;
}
});
})();
function isEmptyString(str) {

View File

@@ -1,5 +1,6 @@
const i18n = require('LanguageData');
i18n.init(window.language); // languageID should be equal to the one we input in New Language ID input field
cc.Class({
extends: cc.Component,
@@ -59,11 +60,7 @@ cc.Class({
loadingPrefab: {
default: null,
type: cc.Prefab
},
wechatLoginTips: {
default: null,
type: cc.Label,
},
}
},
// LIFE-CYCLE CALLBACKS:
@@ -88,22 +85,18 @@ cc.Class({
self.getRetCodeList();
self.getRegexList();
const isUsingX5BlinkKernelOrWebkitWeChatKernel = window.isUsingX5BlinkKernelOrWebkitWeChatKernel();
//const isUsingX5BlinkKernelOrWebkitWeChatKernel = true;
if (!CC_DEBUG) {
self.phoneNumberTips.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.smsLoginCaptchaButton.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.phoneNumberTips.active = true;
self.smsLoginCaptchaButton.active = true;
self.captchaTips.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.phoneCountryCodeInput.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.phoneNumberInput.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.smsLoginCaptchaInput.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.captchaTips.active = true;
self.phoneCountryCodeInput.active = true;
self.phoneNumberInput.active = true;
self.smsLoginCaptchaInput.active = true;
self.phoneLabel.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.smsLoginCaptchaLabel.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
self.phoneLabel.active = true;
self.smsLoginCaptchaLabel.active = true;
self.loginButton.active = !isUsingX5BlinkKernelOrWebkitWeChatKernel;
}
self.loginButton.active = true;
self.checkPhoneNumber = self.checkPhoneNumber.bind(self);
self.checkIntAuthTokenExpire = self.checkIntAuthTokenExpire.bind(self);
self.checkCaptcha = self.checkCaptcha.bind(self);
@@ -124,15 +117,13 @@ cc.Class({
cc.error(err.message || err);
return;
}
if (false == (cc.sys.platform == cc.sys.WECHAT_GAME)) {
// Otherwise, `window.RoomDownsyncFrame` is already assigned.
let protoRoot = new protobuf.Root;
window.protobuf.parse(textAsset.text, protoRoot);
window.RoomDownsyncFrame = protoRoot.lookupType("treasurehunterx.RoomDownsyncFrame");
window.BattleColliderInfo = protoRoot.lookupType("treasurehunterx.BattleColliderInfo");
window.WsReq = protoRoot.lookupType("treasurehunterx.WsReq");
window.WsResp = protoRoot.lookupType("treasurehunterx.WsResp");
}
// Otherwise, `window.RoomDownsyncFrame` is already assigned.
let protoRoot = new protobuf.Root;
window.protobuf.parse(textAsset.text, protoRoot);
window.RoomDownsyncFrame = protoRoot.lookupType("treasurehunterx.RoomDownsyncFrame");
window.BattleColliderInfo = protoRoot.lookupType("treasurehunterx.BattleColliderInfo");
window.WsReq = protoRoot.lookupType("treasurehunterx.WsReq");
window.WsResp = protoRoot.lookupType("treasurehunterx.WsResp");
self.checkIntAuthTokenExpire().then(
() => {
const intAuthToken = JSON.parse(cc.sys.localStorage.getItem('selfPlayer')).intAuthToken;
@@ -140,19 +131,6 @@ cc.Class({
},
() => {
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
if ( (CC_DEBUG || isUsingX5BlinkKernelOrWebkitWeChatKernel) ) {
if (null != qDict && qDict["code"]) {
const code = qDict["code"];
console.log("Got the wx authcode: ", code, "while at full url: " + window.location.href);
self.useWXCodeLogin(code);
} else {
if (isUsingX5BlinkKernelOrWebkitWeChatKernel) {
self.getWechatCode(null);
} else {
// Deliberately left blank.
}
}
}
}
);
});
@@ -355,46 +333,10 @@ cc.Class({
});
},
onWechatLoggedIn(res) {
const self = this;
if (res.ret === self.retCodeDict.OK) {
self.enableInteractiveControls(false);
const date = Number(res.expiresAt);
const selfPlayer = {
expiresAt: date,
playerId: res.playerId,
intAuthToken: res.intAuthToken,
displayName: res.displayName,
avatar: res.avatar,
}
cc.sys.localStorage.setItem('selfPlayer', JSON.stringify(selfPlayer));
const qDict = window.getQueryParamDict();
const expectedRoomId = qDict["expectedRoomId"];
if (null != expectedRoomId) {
console.log("onWechatLoggedIn using expectedRoomId == " + expectedRoomId);
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
}
// To remove "code=XXX" in "query string".
window.history.replaceState(qDict, null, window.location.pathname);
self.useTokenLogin(res.intAuthToken);
} else {
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.wechatLoginTips.string = constants.ALERT.TIP_LABEL.WECHAT_LOGIN_FAILS + ", errorCode = " + res.ret;
// To remove "code=XXX" in "query string".
window.history.replaceState({}, null, window.location.pathname);
}
},
onLoggedIn(res) {
const self = this;
cc.log(`OnLoggedIn ${JSON.stringify(res)}.`)
if (res.ret === self.retCodeDict.OK) {
if(window.isUsingX5BlinkKernelOrWebkitWeChatKernel()) {
window.initWxSdk = self.initWxSdk.bind(self);
window.initWxSdk();
}
self.enableInteractiveControls(false);
const date = Number(res.expiresAt);
const selfPlayer = {
@@ -451,105 +393,4 @@ cc.Class({
}
}
},
useWXCodeLogin(_code) {
const self = this;
NetworkUtils.ajax({
url: backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER + constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.WECHAT + constants.ROUTE_PATH.LOGIN,
type: "POST",
data: {
code: _code
},
success: function(res) {
self.onWechatLoggedIn(res);
},
error: function(xhr, status, errMsg) {
console.log("Login attempt `useWXCodeLogin` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.wechatLoginTips.string = constants.ALERT.TIP_LABEL.WECHAT_LOGIN_FAILS + ", errorMsg =" + errMsg;
window.history.replaceState({}, null, window.location.pathname);
},
});
},
getWechatCode(evt) {
let self = this;
self.wechatLoginTips.string = "";
const wechatServerEndpoint = wechatAddress.PROTOCOL + "://" + wechatAddress.HOST + ((null != wechatAddress.PORT && "" != wechatAddress.PORT.trim()) ? (":" + wechatAddress.PORT) : "");
const url = wechatServerEndpoint + constants.WECHAT.AUTHORIZE_PATH + "?" + wechatAddress.APPID_LITERAL + "&" + constants.WECHAT.REDIRECT_RUI_KEY + NetworkUtils.encode(window.location.href) + "&" + constants.WECHAT.RESPONSE_TYPE + "&" + constants.WECHAT.SCOPE + constants.WECHAT.FIN;
console.log("To visit wechat auth addr: " + url);
window.location.href = url;
},
initWxSdk() {
const selfPlayer = JSON.parse(cc.sys.localStorage.getItem('selfPlayer'));
const origUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
/*
* The `shareLink` must
* - have its 2nd-order-domain registered as trusted 2nd-order under the targetd `res.jsConfig.app_id`, and
* - extracted from current window.location.href.
*/
const shareLink = origUrl;
const updateAppMsgShareDataObj = {
type: 'link', // 分享类型,music、video或link不填默认为link
dataUrl: '', // 如果type是music或video则要提供数据链接默认为空
title: document.title, // 分享标题
desc: 'Let\'s play together!', // 分享描述
link: shareLink + (cc.sys.localStorage.getItem('boundRoomId') ? "" : ("?expectedRoomId=" + cc.sys.localStorage.getItem('boundRoomId'))),
imgUrl: origUrl + "/favicon.ico", // 分享图标
success: function() {
// 设置成功
}
};
const menuShareTimelineObj = {
title: document.title, // 分享标题
link: shareLink + (cc.sys.localStorage.getItem('boundRoomId') ? "" : ("?expectedRoomId=" + cc.sys.localStorage.getItem('boundRoomId'))),
imgUrl: origUrl + "/favicon.ico", // 分享图标
success: function() {}
};
const wxConfigUrl = (window.isUsingWebkitWechatKernel() ? window.atFirstLocationHref : window.location.href);
//接入微信登录接口
NetworkUtils.ajax({
"url": backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER + constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.WECHAT + constants.ROUTE_PATH.JSCONFIG,
type: "POST",
data: {
"url": wxConfigUrl,
"intAuthToken": selfPlayer.intAuthToken,
},
success: function(res) {
if (constants.RET_CODE.OK != res.ret) {
console.log("cannot get the wsConfig. retCode == " + res.ret);
return;
}
const jsConfig = res.jsConfig;
console.log(updateAppMsgShareDataObj);
const configData = {
debug: CC_DEBUG, // 开启调试模式,调用的所有api的返回值会在客户端alert出来若要查看传入的参数可以在pc端打开参数信息会通过log打出仅在pc端时才会打印。
appId: jsConfig.app_id, // 必填,公众号的唯一标识
timestamp: jsConfig.timestamp.toString(), // 必填,生成签名的时间戳
nonceStr: jsConfig.nonce_str, // 必填,生成签名的随机串
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'],
signature: jsConfig.signature, // 必填,签名
};
console.log("config url: " + wxConfigUrl);
console.log("wx.config: ");
console.log(configData);
wx.config(configData);
console.log("Current window.location.href: " + window.location.href);
wx.ready(function() {
console.log("Here is wx.ready.")
wx.onMenuShareAppMessage(updateAppMsgShareDataObj);
wx.onMenuShareTimeline(menuShareTimelineObj);
});
wx.error(function(res) {
console.error("wx config fails and error is " + JSON.stringify(res));
});
},
error: function(xhr, status, errMsg) {
console.log("cannot get the wsConfig. errMsg == " + errMsg);
},
});
},
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,100 @@
window.RING_BUFF_CONSECUTIVE_SET = 0;
window.RING_BUFF_NON_CONSECUTIVE_SET = 1;
window.RING_BUFF_FAILED_TO_SET = 2;
var RingBuffer = function(capacity) {
this.ed = 0; // write index, open index
this.st = 0; // read index, closed index
this.edFrameId = 0;
this.stFrameId = 0;
this.n = capacity;
this.cnt = 0; // the count of valid elements in the buffer, used mainly to distinguish what "st == ed" means for "Pop" and "Get" methods
this.eles = new Array(capacity).fill(null);
};
RingBuffer.prototype.put = function(item) {
this.eles[this.ed] = item
this.edFrameId++;
this.cnt++;
this.ed++;
if (this.ed >= this.n) {
this.ed -= this.n; // Deliberately not using "%" operator for performance concern
}
};
RingBuffer.prototype.pop = function() {
if (0 == this.cnt) {
return null;
}
const item = this.eles[this.st];
this.stFrameId++;
this.cnt--;
this.st++;
if (this.st >= this.n) {
this.st -= this.n;
}
return item;
};
RingBuffer.prototype.getArrIdxByOffset = function(offsetFromSt) {
if (0 > offsetFromSt || 0 == this.cnt) {
return null;
}
let arrIdx = this.st + offsetFromSt;
if (this.st < this.ed) {
// case#1: 0...st...ed...n-1
if (this.st <= arrIdx && arrIdx < this.ed) {
return arrIdx;
}
} else {
// if this.st >= this.sd
// case#2: 0...ed...st...n-1
if (arrIdx >= this.n) {
arrIdx -= this.n
}
if (arrIdx >= this.st || arrIdx < this.ed) {
return arrIdx;
}
}
return null;
};
RingBuffer.prototype.getByFrameId = function(frameId) {
const arrIdx = this.getArrIdxByOffset(frameId - this.stFrameId);
return (null == arrIdx ? null : this.eles[arrIdx]);
};
// [WARNING] During a battle, frontend could receive non-consecutive frames (either renderFrame or inputFrame) due to resync, the buffer should handle these frames properly.
RingBuffer.prototype.setByFrameId = function(item, frameId) {
if (frameId < this.stFrameId) {
console.error("Invalid putByFrameId#1: stFrameId=", this.stFrameId, ", edFrameId=", this.edFrameId, ", incoming item=", item);
return window.RING_BUFF_FAILED_TO_SET;
}
const arrIdx = this.getArrIdxByOffset(frameId - this.stFrameId);
if (null != arrIdx) {
this.eles[arrIdx] = item;
return window.RING_BUFF_CONSECUTIVE_SET;
}
// When "null == arrIdx", should it still be deemed consecutive if "frameId == edFrameId" prior to the reset?
let ret = window.RING_BUFF_CONSECUTIVE_SET;
if (this.edFrameId < frameId) {
this.st = this.ed = 0;
this.stFrameId = this.edFrameId = frameId;
this.cnt = 0;
ret = window.RING_BUFF_NON_CONSECUTIVE_SET;
}
this.eles[this.ed] = item
this.edFrameId++;
this.cnt++;
this.ed++;
if (this.ed >= this.n) {
this.ed -= this.n; // Deliberately not using "%" operator for performance concern
}
return ret;
};
module.exports = RingBuffer;

View File

@@ -1,6 +1,6 @@
{
"ver": "1.0.5",
"uuid": "8264fb72-e348-45e4-9ab3-5bffb9a561ee",
"uuid": "9ec706f0-811c-403b-93a7-b34a7e5f8068",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,

View File

@@ -334,10 +334,6 @@ window.battleEntityTypeNameToGlobalGid = {};
TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNode) {
let toRet = {
barriers: [],
shelters: [],
shelterChainTails: [],
shelterChainHeads: [],
sheltersZReducer: [],
frameAnimations: [],
grandBoundaries: [],
};
@@ -393,8 +389,6 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
let childrenOfCurrentTile = null;
if (cc.sys.isNative) {
childrenOfCurrentTile = currentTile.getElementsByTagName("objectgroup");
} else if (cc.sys.platform == cc.sys.WECHAT_GAME) {
childrenOfCurrentTile = currentTile.childNodes;
} else {
childrenOfCurrentTile = currentTile.children;
}
@@ -404,8 +398,6 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
var currentObjectGroupUnderTile = mapInfo._parseObjectGroup(ch);
gidBoundariesMap[parentGid] = {
barriers: [],
shelters: [],
sheltersZReducer: [],
};
for (let oidx = 0; oidx < currentObjectGroupUnderTile._objects.length; ++oidx) {
const oo = currentObjectGroupUnderTile._objects[oidx];
@@ -429,22 +421,6 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
brToPushTmp.boundaryType = boundaryType;
gidBoundariesMap[parentGid].barriers.push(brToPushTmp);
break;
case "shelter":
let shToPushTmp = [];
for (let shidx = 0; shidx < polylinePoints.length; ++shidx) {
shToPushTmp.push(cc.v2(oo.x, oo.y).add(polylinePoints[shidx]));
}
shToPushTmp.boundaryType = boundaryType;
gidBoundariesMap[parentGid].shelters.push(shToPushTmp);
break;
case "shelter_z_reducer":
let shzrToPushTmp = [];
for (let shzridx = 0; shzridx < polylinePoints.length; ++shzridx) {
shzrToPushTmp.push(cc.v2(oo.x, oo.y).add(polylinePoints[shzridx]));
}
shzrToPushTmp.boundaryType = boundaryType;
gidBoundariesMap[parentGid].sheltersZReducer.push(shzrToPushTmp);
break;
default:
break;
}
@@ -510,22 +486,6 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
toPushBarriers.boundaryType = boundaryType;
toRet.barriers.push(toPushBarriers);
break;
case "shelter":
let toPushShelters = [];
for (let kk = 0; kk < polylinePoints.length; ++kk) {
toPushShelters.push(this.continuousObjLayerOffsetToContinuousMapNodePos(withTiledMapNode, object.offset.add(polylinePoints[kk])));
}
toPushShelters.boundaryType = boundaryType;
toRet.shelters.push(toPushShelters);
break;
case "shelter_z_reducer":
let toPushSheltersZReducer = [];
for (let kkk = 0; kkk < polylinePoints.length; ++kkk) {
toPushSheltersZReducer.push(this.continuousObjLayerOffsetToContinuousMapNodePos(withTiledMapNode, object.offset.add(polylinePoints[kkk])));
}
toPushSheltersZReducer.boundaryType = boundaryType;
toRet.sheltersZReducer.push(toPushSheltersZReducer);
break;
default:
break;
}
@@ -536,7 +496,7 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
let layerDOMTrees = [];
const mapDomTree = mapInfo._parser._parseXML(tiledMapIns.tmxAsset.tmxXmlStr).documentElement;
const mapDOMAllChildren = (cc.sys.platform == cc.sys.WECHAT_GAME ? mapDomTree.childNodes : mapDomTree.children);
const mapDOMAllChildren = (mapDomTree.children);
for (let mdtIdx = 0; mdtIdx < mapDOMAllChildren.length; ++mdtIdx) {
const tmpCh = mapDOMAllChildren[mdtIdx];
if (mapInfo._shouldIgnoreNode(tmpCh)) {
@@ -585,23 +545,6 @@ TileCollisionManager.prototype.extractBoundaryObjects = function (withTiledMapNo
}
toRet.barriers.push(brToPushTmp);
}
for (let shidx = 0; shidx < gidBoundaries.shelters.length; ++shzridx) {
const theShelter = gidBoundaries.shelters[shidx]; // An array of cc.v2 points.
let shToPushTmp = [];
for (let tshidx = 0; tshidx < theShelter.length; ++tshidx) {
shToPushTmp.push(topLeftOfWholeTsxTileInMapNode.add(cc.v2(theShelter[tshidx].x, -theShelter[tshidx].y)));
}
toRet.shelters.push(shToPushTmp);
}
for (let shzridx = 0; shzridx < gidBoundaries.sheltersZReducer.length; ++shzridx) {
const theShelter = gidBoundaries.sheltersZReducer[shzridx]; // An array of cc.v2 points.
let shzrToPushTmp = [];
for (let tshzridx = 0; tshzridx < theShelter.length; ++tshzridx) {
shzrToPushTmp.push(topLeftOfWholeTsxTileInMapNode.add(cc.v2(theShelter[tshzridx].x, -theShelter[tshzridx].y)));
}
toRet.sheltersZReducer.push(shzrToPushTmp);
}
continue;
default:
@@ -637,6 +580,7 @@ TileCollisionManager.prototype.isOutOfMapNode = function (tiledMapNode, continuo
};
TileCollisionManager.prototype.initMapNodeByTiledBoundaries = function(mapScriptIns, mapNode, extractedBoundaryObjs) {
// TODO: TO DEPRECATE!
const tiledMapIns = mapNode.getComponent(cc.TiledMap);
if (extractedBoundaryObjs.grandBoundaries) {
window.grandBoundary = [];
@@ -683,47 +627,6 @@ TileCollisionManager.prototype.initMapNodeByTiledBoundaries = function(mapScript
frameAnimInType.push(animNode);
}
for (let boundaryObj of extractedBoundaryObjs.shelterChainTails) {
const newShelter = cc.instantiate(mapScriptIns.polygonBoundaryShelterPrefab);
const newBoundaryOffsetInMapNode = cc.v2(boundaryObj[0].x, boundaryObj[0].y);
newShelter.setPosition(newBoundaryOffsetInMapNode);
newShelter.setAnchorPoint(cc.v2(0, 0));
const newShelterColliderIns = newShelter.getComponent(cc.PolygonCollider);
newShelterColliderIns.points = [];
for (let p of boundaryObj) {
newShelterColliderIns.points.push(p.sub(newBoundaryOffsetInMapNode));
}
newShelter.pTiledLayer = boundaryObj.pTiledLayer;
newShelter.tileDiscretePos = boundaryObj.tileDiscretePos;
if (null != boundaryObj.imageObject) {
newShelter.imageObject = boundaryObj.imageObject;
newShelter.tailOrHead = "tail";
window.addToGlobalShelterChainVerticeMap(newShelter.imageObject.imageObjectNode); // Deliberately NOT adding at the "traversal of shelterChainHeads".
}
newShelter.boundaryObj = boundaryObj;
mapScriptIns.node.addChild(newShelter);
}
for (let boundaryObj of extractedBoundaryObjs.shelterChainHeads) {
const newShelter = cc.instantiate(mapScriptIns.polygonBoundaryShelterPrefab);
const newBoundaryOffsetInMapNode = cc.v2(boundaryObj[0].x, boundaryObj[0].y);
newShelter.setPosition(newBoundaryOffsetInMapNode);
newShelter.setAnchorPoint(cc.v2(0, 0));
const newShelterColliderIns = newShelter.getComponent(cc.PolygonCollider);
newShelterColliderIns.points = [];
for (let p of boundaryObj) {
newShelterColliderIns.points.push(p.sub(newBoundaryOffsetInMapNode));
}
newShelter.pTiledLayer = boundaryObj.pTiledLayer;
newShelter.tileDiscretePos = boundaryObj.tileDiscretePos;
if (null != boundaryObj.imageObject) {
newShelter.imageObject = boundaryObj.imageObject;
newShelter.tailOrHead = "head";
}
newShelter.boundaryObj = boundaryObj;
mapScriptIns.node.addChild(newShelter);
}
mapScriptIns.barrierColliders = [];
for (let boundaryObj of extractedBoundaryObjs.barriers) {
const newBarrier = cc.instantiate(mapScriptIns.polygonBoundaryBarrierPrefab);
@@ -739,19 +642,6 @@ TileCollisionManager.prototype.initMapNodeByTiledBoundaries = function(mapScript
mapScriptIns.node.addChild(newBarrier);
}
for (let boundaryObj of extractedBoundaryObjs.sheltersZReducer) {
const newShelter = cc.instantiate(mapScriptIns.polygonBoundaryShelterZReducerPrefab);
const newBoundaryOffsetInMapNode = cc.v2(boundaryObj[0].x, boundaryObj[0].y);
newShelter.setPosition(newBoundaryOffsetInMapNode);
newShelter.setAnchorPoint(cc.v2(0, 0));
const newShelterColliderIns = newShelter.getComponent(cc.PolygonCollider);
newShelterColliderIns.points = [];
for (let p of boundaryObj) {
newShelterColliderIns.points.push(p.sub(newBoundaryOffsetInMapNode));
}
mapScriptIns.node.addChild(newShelter);
}
const allLayers = tiledMapIns.getLayers();
for (let layer of allLayers) {
const layerType = layer.getProperty("type");
@@ -759,10 +649,6 @@ TileCollisionManager.prototype.initMapNodeByTiledBoundaries = function(mapScript
case "barrier_and_shelter":
setLocalZOrder(layer.node, 3);
break;
case "shelter_preview":
layer.node.opacity = 100;
setLocalZOrder(layer.node, 500);
break;
default:
break;
}

View File

@@ -1,19 +1,24 @@
window.DIRECTION_DECODER = [
[0, 0],
[0, +1],
[0, -1],
[+2, 0],
[-2, 0],
[+2, +1],
[-2, -1],
[+2, -1],
[-2, +1],
[+2, 0],
[-2, 0],
[0, +1],
[0, -1],
[0, 0, null],
[0, +1, null],
[0, -1, null],
[+2, 0, null],
[-2, 0, null],
[+2, +1, null],
[-2, -1, null],
[+2, -1, null],
[-2, +1, null],
[+2, 0, null],
[-2, 0, null],
[0, +1, null],
[0, -1, null],
];
for (let k in window.DIRECTION_DECODER) {
const length = Math.sqrt(window.DIRECTION_DECODER[k][0]*window.DIRECTION_DECODER[k][0] + window.DIRECTION_DECODER[k][1]*window.DIRECTION_DECODER[k][1]);
window.DIRECTION_DECODER[k][2] = (0 == length ? 0 : (1.0/length));
}
cc.Class({
extends: cc.Component,
properties: {
@@ -114,43 +119,6 @@ cc.Class({
this.initialized = true;
},
justifyMapNodePosAndScale(linearSpeedBase, zoomingSpeedBase) {
const self = this;
if (false == self.mapScriptIns._inputControlEnabled) return;
if (null != self._cachedMapNodePosTarget) {
while (self.maxMovingBufferLength < self._cachedMapNodePosTarget.length) {
self._cachedMapNodePosTarget.shift();
}
if (0 < self._cachedMapNodePosTarget.length && 0 == self.mapNode.getNumberOfRunningActions()) {
const nextMapNodePosTarget = self._cachedMapNodePosTarget.shift();
const linearSpeed = linearSpeedBase;
const finalDiffVec = nextMapNodePosTarget.pos.sub(self.mapNode.position);
const finalDiffVecMag = finalDiffVec.mag();
if (self.linearMovingEps > finalDiffVecMag) {
// Jittering.
// cc.log("Map node moving by finalDiffVecMag == %s is just jittering.", finalDiffVecMag);
return;
}
const durationSeconds = finalDiffVecMag / linearSpeed;
cc.log("Map node moving to %o in %s/%s == %s seconds.", nextMapNodePosTarget.pos, finalDiffVecMag, linearSpeed, durationSeconds);
const bufferedTargetPos = cc.v2(nextMapNodePosTarget.pos.x, nextMapNodePosTarget.pos.y);
self.mapNode.runAction(cc.sequence(
cc.moveTo(durationSeconds, bufferedTargetPos),
cc.callFunc(() => {
if (self._isMapOverMoved(self.mapNode.position)) {
self.mapNode.setPosition(bufferedTargetPos);
}
}, self)
));
}
}
if (null != self._cachedZoomRawTarget && false == self._cachedZoomRawTarget.processed) {
cc.log(`Processing self._cachedZoomRawTarget == ${self._cachedZoomRawTarget}`);
self._cachedZoomRawTarget.processed = true;
self.mapNode.setScale(self._cachedZoomRawTarget.scale);
}
},
_initTouchEvent() {
const self = this;
const translationListenerNode = (self.translationListenerNode ? self.translationListenerNode : self.mapNode);
@@ -377,7 +345,8 @@ cc.Class({
}
return {
dx: mapped[0],
dy: mapped[1]
dy: mapped[1],
speedFactor: mapped[2],
}
},

View File

@@ -1,628 +0,0 @@
const i18n = require('LanguageData');
i18n.init(window.language); // languageID should be equal to the one we input in New Language ID input field
const WECHAT_ON_HIDE_TARGET_ACTION = {
SHARE_CHAT_MESSAGE: 8,
CLOSE: 3,
};
const pbStructRoot = require('./modules/room_downsync_frame_proto_bundle.forcemsg.js');
window.RoomDownsyncFrame = pbStructRoot.treasurehunterx.RoomDownsyncFrame;
window.BattleColliderInfo = pbStructRoot.treasurehunterx.BattleColliderInfo;
cc.Class({
extends: cc.Component,
properties: {
cavasNode: {
default: null,
type: cc.Node
},
backgroundNode: {
default: null,
type: cc.Node
},
loadingPrefab: {
default: null,
type: cc.Prefab
},
tipsLabel: {
default: null,
type: cc.Label,
},
downloadProgress: {
default: null,
type: cc.ProgressBar,
},
writtenBytes: {
default: null,
type: cc.Label,
},
expectedToWriteBytes: {
default: null,
type: cc.Label,
},
handlerProgress: {
default: null,
type: cc.ProgressBar,
},
handledUrlsCount: {
default: null,
type: cc.Label,
},
toHandledUrlsCount: {
default: null,
type: cc.Label,
},
},
// LIFE-CYCLE CALLBACKS:
onLoad() {
wx.onShow((res) => {
console.log("+++++ wx onShow(), onShow.res ", res);
window.expectedRoomId = res.query.expectedRoomId;
});
wx.onHide((res) => {
// Reference https://developers.weixin.qq.com/minigame/dev/api/wx.exitMiniProgram.html.
console.log("+++++ wx onHide(), onHide.res: ", res);
if (
WECHAT_ON_HIDE_TARGET_ACTION == res.targetAction
||
"back" == res.mode // After "WeChat v7.0.4 on iOS"
||
"close" == res.mode
) {
window.clearLocalStorageAndBackToLoginScene();
} else {
// Deliberately left blank.
}
});
const self = this;
self.getRetCodeList();
self.getRegexList();
self.showTips(i18n.t("login.tips.AUTO_LOGIN_1"));
self.checkIntAuthTokenExpire().then(
() => {
self.showTips(i18n.t("login.tips.AUTO_LOGIN_2"));
const intAuthToken = JSON.parse(cc.sys.localStorage.getItem('selfPlayer')).intAuthToken;
self.useTokenLogin(intAuthToken);
},
() => {
// 调用wx.login然后请求登录。
wx.authorize({
scope: "scope.userInfo",
success() {
self.showTips(i18n.t("login.tips.WECHAT_AUTHORIZED_AND_INT_AUTH_TOKEN_LOGGING_IN"));
wx.login({
success(res) {
console.log("wx login success, res: ", res);
const code = res.code;
wx.getUserInfo({
success(res) {
const userInfo = res.userInfo;
console.log("Get user info ok: ", userInfo);
self.useWxCodeMiniGameLogin(code, userInfo);
},
fail(err) {
console.error(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"), err);
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
self.createAuthorizeThenLoginButton();
},
})
},
fail(err) {
if (err) {
console.error(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"), err);
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
self.createAuthorizeThenLoginButton();
}
},
});
},
fail(err) {
console.error(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"), err);
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
self.createAuthorizeThenLoginButton();
}
})
}
);
},
createAuthorizeThenLoginButton(tips) {
const self = this;
let sysInfo = wx.getSystemInfoSync();
//获取微信界面大小
let width = sysInfo.screenWidth;
let height = sysInfo.screenHeight;
let button = wx.createUserInfoButton({
type: 'text',
text: '',
style: {
left: 0,
top: 0,
width: width,
height: height,
backgroundColor: '#00000000', //最后两位为透明度
color: '#ffffff',
fontSize: 20,
textAlign: "center",
lineHeight: height,
},
});
button.onTap((res) => {
console.log(res);
if (null != res.userInfo) {
const userInfo = res.userInfo;
self.showTips(i18n.t("login.tips.WECHAT_AUTHORIZED_AND_INT_AUTH_TOKEN_LOGGING_IN"));
wx.login({
success(res) {
console.log('wx.login success, res:', res);
const code = res.code;
self.useWxCodeMiniGameLogin(code, userInfo);
button.destroy();
},
fail(err) {
console.err(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"), err);
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
},
});
} else {
self.showTips(i18n.t("login.tips.PLEASE_AUTHORIZE_WECHAT_LOGIN_FIRST"));
}
})
},
onDestroy() {
console.log("+++++++ WechatGameLogin onDestroy()");
},
showTips(text) {
if (this.tipsLabel != null) {
this.tipsLabel.string = text;
} else {
console.log('Login scene showTips failed')
}
},
getRetCodeList() {
const self = this;
self.retCodeDict = constants.RET_CODE;
},
getRegexList() {
const self = this;
self.regexList = {
EMAIL: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
PHONE: /^\+?[0-9]{8,14}$/,
STREET_META: /^.{5,100}$/,
LNG_LAT_TEXT: /^[0-9]+(\.[0-9]{4,6})$/,
SEO_KEYWORD: /^.{2,50}$/,
PASSWORD: /^.{6,50}$/,
SMS_CAPTCHA_CODE: /^[0-9]{4}$/,
ADMIN_HANDLE: /^.{4,50}$/,
};
},
onSMSCaptchaGetButtonClicked(evt) {
var timerEnable = true;
const self = this;
if (!self.checkPhoneNumber('getCaptcha')) {
return;
}
NetworkUtils.ajax({
url: backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER +
constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.SMS_CAPTCHA + constants.ROUTE_PATH.GET,
type: 'GET',
data: {
phoneCountryCode: self.phoneCountryCodeInput.getComponent(cc.EditBox).string,
phoneNum: self.phoneNumberInput.getComponent(cc.EditBox).string
},
success: function(res) {
switch (res.ret) {
case constants.RET_CODE.OK:
self.phoneNumberTips.getComponent(cc.Label).string = '';
self.captchaTips.getComponent(cc.Label).string = '';
break;
case constants.RET_CODE.DUPLICATED:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.DUPLICATED");
break;
case constants.RET_CODE.INCORRECT_PHONE_COUNTRY_CODE:
case constants.RET_CODE.INCORRECT_PHONE_NUMBER:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.PHONE_ERR");
break;
case constants.RET_CODE.IS_TEST_ACC:
self.smsLoginCaptchaInput.getComponent(cc.EditBox).string = res.smsLoginCaptcha;
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.TEST_USER");
timerEnable = false;
// clearInterval(self.countdownTimer);
break;
case constants.RET_CODE.SMS_CAPTCHA_REQUESTED_TOO_FREQUENTLY:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.SMS_CAPTCHA_FREEQUENT_REQUIRE");
default:
break;
}
if (timerEnable)
self.countdownTime(self);
}
});
},
countdownTime(self) {
self.smsLoginCaptchaButton.off('click', self.onSMSCaptchaGetButtonClicked);
self.smsLoginCaptchaButton.removeChild(self.smsGetCaptchaNode);
self.smsWaitCountdownNode.parent = self.smsLoginCaptchaButton;
var total = 20; // Magic number
self.countdownTimer = setInterval(function() {
if (total === 0) {
self.smsWaitCountdownNode.parent.removeChild(self.smsWaitCountdownNode);
self.smsGetCaptchaNode.parent = self.smsLoginCaptchaButton;
self.smsWaitCountdownNode.getChildByName('WaitTimeLabel').getComponent(cc.Label).string = 20;
self.smsLoginCaptchaButton.on('click', self.onSMSCaptchaGetButtonClicked);
clearInterval(self.countdownTimer);
} else {
total--;
self.smsWaitCountdownNode.getChildByName('WaitTimeLabel').getComponent(cc.Label).string = total;
}
}, 1000)
},
checkIntAuthTokenExpire() {
return new Promise((resolve, reject) => {
if (!cc.sys.localStorage.getItem("selfPlayer")) {
reject();
return;
}
const selfPlayer = JSON.parse(cc.sys.localStorage.getItem('selfPlayer'));
(selfPlayer.intAuthToken && new Date().getTime() < selfPlayer.expiresAt) ? resolve() : reject();
})
},
checkPhoneNumber(type) {
const self = this;
const phoneNumberRegexp = self.regexList.PHONE;
var phoneNumberString = self.phoneNumberInput.getComponent(cc.EditBox).string;
if (phoneNumberString) {
return true;
if (!phoneNumberRegexp.test(phoneNumberString)) {
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.PHONE_ERR");
return false;
} else {
return true;
}
} else {
if (type === 'getCaptcha' || type === 'login') {
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.PHONE_ERR");
}
return false;
}
},
checkCaptcha(type) {
const self = this;
const captchaRegexp = self.regexList.SMS_CAPTCHA_CODE;
var captchaString = self.smsLoginCaptchaInput.getComponent(cc.EditBox).string;
if (captchaString) {
if (self.smsLoginCaptchaInput.getComponent(cc.EditBox).string.length !== 4 || (!captchaRegexp.test(captchaString))) {
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.CAPTCHA_ERR");
return false;
} else {
return true;
}
} else {
if (type === 'login') {
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.CAPTCHA_ERR");
}
return false;
}
},
useTokenLogin(_intAuthToken) {
var self = this;
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.LOGIN,
type: "POST",
data: {
intAuthToken: _intAuthToken
},
success: function(resp) {
self.onLoggedIn(resp);
},
error: function(xhr, status, errMsg) {
console.log("Login attempt `useTokenLogin` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage()
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
self.createAuthorizeThenLoginButton();
},
timeout: function() {
self.enableInteractiveControls(true);
},
});
},
enableInteractiveControls(enabled) {},
onLoginButtonClicked(evt) {
const self = this;
if (!self.checkPhoneNumber('login') || !self.checkCaptcha('login')) {
return;
}
self.loginParams = {
phoneCountryCode: self.phoneCountryCodeInput.getComponent(cc.EditBox).string,
phoneNum: self.phoneNumberInput.getComponent(cc.EditBox).string,
smsLoginCaptcha: self.smsLoginCaptchaInput.getComponent(cc.EditBox).string
};
self.enableInteractiveControls(false);
NetworkUtils.ajax({
url: backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER +
constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.SMS_CAPTCHA + constants.ROUTE_PATH.LOGIN,
type: "POST",
data: self.loginParams,
success: function(resp) {
self.onLoggedIn(resp);
},
error: function(xhr, status, errMsg) {
console.log("Login attempt `onLoginButtonClicked` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage()
},
timeout: function() {
self.enableInteractiveControls(true);
}
});
},
onWechatLoggedIn(res) {
const self = this;
if (constants.RET_CODE.OK == res.ret) {
//根据服务器返回信息设置selfPlayer
self.enableInteractiveControls(false);
const date = Number(res.expiresAt);
const selfPlayer = {
expiresAt: date,
playerId: res.playerId,
intAuthToken: res.intAuthToken,
displayName: res.displayName,
avatar: res.avatar,
}
cc.sys.localStorage.setItem('selfPlayer', JSON.stringify(selfPlayer));
self.useTokenLogin(res.intAuthToken);
} else {
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.showTips(i18n.t("login.tips.WECHAT_LOGIN_FAILED_TAP_SCREEN_TO_RETRY") + ", errorCode = " + res.ret);
self.createAuthorizeThenLoginButton();
}
},
onLoggedIn(res) {
const self = this;
console.log("OnLoggedIn: ", res);
if (constants.RET_CODE.OK == res.ret) {
if (window.isUsingX5BlinkKernelOrWebkitWeChatKernel()) {
window.initWxSdk = self.initWxSdk.bind(self);
window.initWxSdk();
}
self.enableInteractiveControls(false);
const date = Number(res.expiresAt);
const selfPlayer = {
expiresAt: date,
playerId: res.playerId,
intAuthToken: res.intAuthToken,
avatar: res.avatar,
displayName: res.displayName,
name: res.name,
}
cc.sys.localStorage.setItem("selfPlayer", JSON.stringify(selfPlayer));
console.log("cc.sys.localStorage.selfPlayer = ", cc.sys.localStorage.getItem("selfPlayer"));
if (self.countdownTimer) {
clearInterval(self.countdownTimer);
}
cc.director.loadScene('default_map');
} else {
console.warn('onLoggedIn failed!')
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.enableInteractiveControls(true);
switch (res.ret) {
case constants.RET_CODE.DUPLICATED:
this.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.DUPLICATED");
break;
case constants.RET_CODE.TOKEN_EXPIRED:
this.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.LOGIN_TOKEN_EXPIRED");
break;
case constants.RET_CODE.SMS_CAPTCHA_NOT_MATCH:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.SMS_CAPTCHA_NOT_MATCH");
break;
case constants.RET_CODE.INCORRECT_CAPTCHA:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.SMS_CAPTCHA_NOT_MATCH");
break;
case constants.RET_CODE.SMS_CAPTCHA_CODE_NOT_EXISTING:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.SMS_CAPTCHA_NOT_MATCH");
break;
case constants.RET_CODE.INCORRECT_PHONE_NUMBER:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.INCORRECT_PHONE_NUMBER");
break;
case constants.RET_CODE.INVALID_REQUEST_PARAM:
self.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.INCORRECT_PHONE_NUMBER");
break;
case constants.RET_CODE.INCORRECT_PHONE_COUNTRY_CODE:
case constants.RET_CODE.INCORRECT_PHONE_NUMBER:
this.captchaTips.getComponent(cc.Label).string = i18n.t("login.tips.INCORRECT_PHONE_NUMBER");
break;
default:
break;
}
self.showTips(i18n.t("login.tips.AUTO_LOGIN_FAILED_WILL_USE_MANUAL_LOGIN"));
self.createAuthorizeThenLoginButton();
}
},
useWXCodeLogin(_code) {
const self = this;
NetworkUtils.ajax({
url: backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER + constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.WECHAT + constants.ROUTE_PATH.LOGIN,
type: "POST",
data: {
code: _code
},
success: function(res) {
self.onWechatLoggedIn(res);
},
error: function(xhr, status, errMsg) {
console.log("Login attempt `onLoginButtonClicked` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.showTips(i18n.t("login.tips.WECHAT_LOGIN_FAILED_TAP_SCREEN_TO_RETRY") + ", errorMsg =" + errMsg);
},
timeout: function() {
console.log("Login attempt `onLoginButtonClicked` timed out, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.showTips(i18n.t("login.tips.WECHAT_LOGIN_FAILED_TAP_SCREEN_TO_RETRY") + ", errorMsg =" + errMsg);
},
});
},
// 对比useWxCodeLogin函数只是请求了不同url
useWxCodeMiniGameLogin(_code, _userInfo) {
const self = this;
NetworkUtils.ajax({
url: backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER + constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.WECHATGAME + constants.ROUTE_PATH.LOGIN,
type: "POST",
data: {
code: _code,
avatarUrl: _userInfo.avatarUrl,
nickName: _userInfo.nickName,
},
success: function(res) {
self.onWechatLoggedIn(res);
},
error: function(xhr, status, errMsg) {
console.log("Login attempt `onLoginButtonClicked` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.showTips(i18n.t("login.tips.WECHAT_LOGIN_FAILED_TAP_SCREEN_TO_RETRY") + ", errorMsg =" + errMsg);
self.createAuthorizeThenLoginButton();
},
timeout: function() {
console.log("Login attempt `onLoginButtonClicked` failed, about to execute `clearBoundRoomIdInBothVolatileAndPersistentStorage`.");
cc.sys.localStorage.removeItem("selfPlayer");
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
self.showTips(i18n.t("login.tips.WECHAT_LOGIN_FAILED_TAP_SCREEN_TO_RETRY"));
self.createAuthorizeThenLoginButton();
},
});
},
getWechatCode(evt) {
let self = this;
self.showTips("");
const wechatServerEndpoint = wechatAddress.PROTOCOL + "://" + wechatAddress.HOST + ((null != wechatAddress.PORT && "" != wechatAddress.PORT.trim()) ? (":" + wechatAddress.PORT) : "");
const url = wechatServerEndpoint + constants.WECHAT.AUTHORIZE_PATH + "?" + wechatAddress.APPID_LITERAL + "&" + constants.WECHAT.REDIRECT_RUI_KEY + NetworkUtils.encode(window.location.href) + "&" + constants.WECHAT.RESPONSE_TYPE + "&" + constants.WECHAT.SCOPE + constants.WECHAT.FIN;
console.log("To visit wechat auth addr: ", url);
window.location.href = url;
},
initWxSdk() {
const selfPlayer = JSON.parse(cc.sys.localStorage.getItem('selfPlayer'));
const origUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
/*
* The `shareLink` must
* - have its 2nd-order-domain registered as trusted 2nd-order under the targetd `res.jsConfig.app_id`, and
* - extracted from current window.location.href.
*/
const shareLink = origUrl;
const updateAppMsgShareDataObj = {
type: 'link', // 分享类型,music、video或link不填默认为link
dataUrl: '', // 如果type是music或video则要提供数据链接默认为空
title: document.title, // 分享标题
desc: 'Let\'s play together!', // 分享描述
link: shareLink + (cc.sys.localStorage.getItem('boundRoomId') ? "" : ("?expectedRoomId=" + cc.sys.localStorage.getItem('boundRoomId'))),
imgUrl: origUrl + "/favicon.ico", // 分享图标
success: function() {
// 设置成功
}
};
const menuShareTimelineObj = {
title: document.title, // 分享标题
link: shareLink + (cc.sys.localStorage.getItem('boundRoomId') ? "" : ("?expectedRoomId=" + cc.sys.localStorage.getItem('boundRoomId'))),
imgUrl: origUrl + "/favicon.ico", // 分享图标
success: function() {}
};
const wxConfigUrl = (window.isUsingWebkitWechatKernel() ? window.atFirstLocationHref : window.location.href);
//接入微信登录接口
NetworkUtils.ajax({
"url": backendAddress.PROTOCOL + '://' + backendAddress.HOST + ':' + backendAddress.PORT + constants.ROUTE_PATH.API + constants.ROUTE_PATH.PLAYER + constants.ROUTE_PATH.VERSION + constants.ROUTE_PATH.WECHAT + constants.ROUTE_PATH.JSCONFIG,
type: "POST",
data: {
"url": wxConfigUrl,
"intAuthToken": selfPlayer.intAuthToken,
},
success: function(res) {
if (constants.RET_CODE.OK != res.ret) {
console.warn("Failed to get `wsConfig`: ", res);
return;
}
const jsConfig = res.jsConfig;
const configData = {
debug: CC_DEBUG, // 开启调试模式,调用的所有api的返回值会在客户端alert出来若要查看传入的参数可以在pc端打开参数信息会通过log打出仅在pc端时才会打印。
appId: jsConfig.app_id, // 必填,公众号的唯一标识
timestamp: jsConfig.timestamp.toString(), // 必填,生成签名的时间戳
nonceStr: jsConfig.nonce_str, // 必填,生成签名的随机串
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'],
signature: jsConfig.signature, // 必填,签名
};
console.log("config url: ", wxConfigUrl);
console.log("wx.config: ", configData);
wx.config(configData);
console.log("Current window.location.href: ", window.location.href);
wx.ready(function() {
console.log("Here is wx.ready.")
wx.onMenuShareAppMessage(updateAppMsgShareDataObj);
wx.onMenuShareTimeline(menuShareTimelineObj);
});
wx.error(function(res) {
console.error("wx config fails and error is ", JSON.stringify(res));
});
},
error: function(xhr, status, errMsg) {
console.error("Failed to get `wsConfig`: ", errMsg);
},
});
},
update(dt) {
const self = this;
if (null != wxDownloader && 0 < wxDownloader.totalBytesExpectedToWriteForAllTasks) {
self.writtenBytes.string = wxDownloader.totalBytesWrittenForAllTasks;
self.expectedToWriteBytes.string = wxDownloader.totalBytesExpectedToWriteForAllTasks;
self.downloadProgress.progress = 1.0*wxDownloader.totalBytesWrittenForAllTasks/wxDownloader.totalBytesExpectedToWriteForAllTasks;
}
const totalUrlsToHandle = (wxDownloader.immediateHandleItemCount + wxDownloader.immediateReadFromLocalCount + wxDownloader.immediatePackDownloaderCount);
const totalUrlsHandled = (wxDownloader.immediateHandleItemCompleteCount + wxDownloader.immediateReadFromLocalCompleteCount + wxDownloader.immediatePackDownloaderCompleteCount);
if (null != wxDownloader && 0 < totalUrlsToHandle) {
self.handledUrlsCount.string = totalUrlsHandled;
self.toHandledUrlsCount.string = totalUrlsToHandle;
self.handlerProgress.progress = 1.0*totalUrlsHandled/totalUrlsToHandle;
}
}
});

View File

@@ -1,10 +1,18 @@
const RingBuffer = require('./RingBuffer');
window.UPSYNC_MSG_ACT_HB_PING = 1;
window.UPSYNC_MSG_ACT_PLAYER_CMD = 2;
window.UPSYNC_MSG_ACT_PLAYER_COLLIDER_ACK = 3;
window.DOWNSYNC_MSG_ACT_PLAYER_ADDED_AND_ACKED = -98;
window.DOWNSYNC_MSG_ACT_PLAYER_READDED_AND_ACKED = -97;
window.DOWNSYNC_MSG_ACT_BATTLE_READY_TO_START = -1;
window.DOWNSYNC_MSG_ACT_BATTLE_START = 0;
window.DOWNSYNC_MSG_ACT_HB_REQ = 1;
window.DOWNSYNC_MSG_ACT_INPUT_BATCH = 2;
window.DOWNSYNC_MSG_ACT_ROOM_FRAME = 3;
window.DOWNSYNC_MSG_ACT_BATTLE_STOPPED = 3;
window.DOWNSYNC_MSG_ACT_FORCED_RESYNC = 4;
window.sendSafely = function(msgStr) {
/**
@@ -74,8 +82,6 @@ function _base64ToUint8Array(base64) {
origBytes[i] = origBinaryStr.charCodeAt(i);
}
return origBytes;
} else if (cc.sys.platform == cc.sys.WECHAT_GAME) {
return Buffer.from(base64, 'base64');
} else {
return null;
}
@@ -86,16 +92,12 @@ function _base64ToArrayBuffer(base64) {
}
window.getExpectedRoomIdSync = function() {
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
return window.expectedRoomId;
const qDict = window.getQueryParamDict();
if (qDict) {
return qDict["expectedRoomId"];
} else {
const qDict = window.getQueryParamDict();
if (qDict) {
return qDict["expectedRoomId"];
} else {
if (window.history && window.history.state) {
return window.history.state.expectedRoomId;
}
if (window.history && window.history.state) {
return window.history.state.expectedRoomId;
}
}
@@ -129,10 +131,6 @@ window.initPersistentSessionClient = function(onopenCb, expectedRoomId) {
if (null != expectedRoomId) {
console.log("initPersistentSessionClient with expectedRoomId == " + expectedRoomId);
urlToConnect = urlToConnect + "&expectedRoomId=" + expectedRoomId;
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
// This is a dirty hack. -- YFLu
window.expectedRoomId = null;
}
} else {
window.boundRoomId = getBoundRoomIdFromPersistentStorage();
if (null != window.boundRoomId) {
@@ -143,10 +141,6 @@ window.initPersistentSessionClient = function(onopenCb, expectedRoomId) {
const currentHistoryState = window.history && window.history.state ? window.history.state : {};
if (cc.sys.platform != cc.sys.WECHAT_GAME) {
window.history.replaceState(currentHistoryState, document.title, window.location.pathname);
}
const clientSession = new WebSocket(urlToConnect);
clientSession.binaryType = 'arraybuffer'; // Make 'event.data' of 'onmessage' an "ArrayBuffer" instead of a "Blob"
@@ -167,14 +161,41 @@ window.initPersistentSessionClient = function(onopenCb, expectedRoomId) {
case window.DOWNSYNC_MSG_ACT_HB_REQ:
window.handleHbRequirements(resp); // 获取boundRoomId并存储到localStorage
break;
case window.DOWNSYNC_MSG_ACT_ROOM_FRAME:
if (window.handleRoomDownsyncFrame) {
window.handleRoomDownsyncFrame(resp.rdf);
}
case window.DOWNSYNC_MSG_ACT_PLAYER_ADDED_AND_ACKED:
mapIns.onPlayerAdded(resp.rdf);
break;
case window.DOWNSYNC_MSG_ACT_PLAYER_READDED_AND_ACKED:
// Deliberately left blank for now
mapIns.hideFindingPlayersGUI();
break;
case window.DOWNSYNC_MSG_ACT_BATTLE_READY_TO_START:
mapIns.onBattleReadyToStart(resp.rdf.playerMetas);
break;
case window.DOWNSYNC_MSG_ACT_BATTLE_START:
mapIns.onRoomDownsyncFrame(resp.rdf);
break;
case window.DOWNSYNC_MSG_ACT_BATTLE_STOPPED:
mapIns.onBattleStopped();
break;
case window.DOWNSYNC_MSG_ACT_INPUT_BATCH:
if (window.handleInputFrameDownsyncBatch) {
window.handleInputFrameDownsyncBatch(resp.inputFrameDownsyncBatch);
mapIns.onInputFrameDownsyncBatch(resp.inputFrameDownsyncBatch);
break;
case window.DOWNSYNC_MSG_ACT_FORCED_RESYNC:
if (null == resp.inputFrameDownsyncBatch || 0 >= resp.inputFrameDownsyncBatch.length) {
console.error("Got empty inputFrameDownsyncBatch upon resync@localRenderFrameId=", mapIns.renderFrameId, ", @lastAllConfirmedRenderFrameId=", mapIns.lastAllConfirmedRenderFrameId, "@lastAllConfirmedInputFrameId=", mapIns.lastAllConfirmedInputFrameId, ", @localRecentInputCache=", mapIns._stringifyRecentInputCache(false), ", the incoming resp=\n", JSON.stringify(resp, null, 2));
return;
}
// Unless upon ws session lost and reconnected, it's maintained true that "inputFrameDownsyncBatch[0].inputFrameId == frontend.lastAllConfirmedInputFrameId+1", and in this case we should try to keep frontend moving only by "frontend.recentInputCache" to avoid jiggling of synced positions
const inputFrameIdConsecutive = (resp.inputFrameDownsyncBatch[0].inputFrameId == mapIns.lastAllConfirmedInputFrameId + 1);
const renderFrameIdConsecutive = (resp.rdf.id <= mapIns.renderFrameId + mapIns.renderFrameIdLagTolerance);
if (inputFrameIdConsecutive && renderFrameIdConsecutive) {
console.log("Got consecutive resync@localRenderFrameId=", mapIns.renderFrameId, ", @lastAllConfirmedRenderFrameId=", mapIns.lastAllConfirmedRenderFrameId, "@lastAllConfirmedInputFrameId=", mapIns.lastAllConfirmedInputFrameId, ", @localRecentInputCache=", mapIns._stringifyRecentInputCache(false), ", the incoming resp=\n", JSON.stringify(resp));
mapIns.onInputFrameDownsyncBatch(resp.inputFrameDownsyncBatch);
} else {
console.warn("Got forced resync@localRenderFrameId=", mapIns.renderFrameId, ", @lastAllConfirmedRenderFrameId=", mapIns.lastAllConfirmedRenderFrameId, "@lastAllConfirmedInputFrameId=", mapIns.lastAllConfirmedInputFrameId, ", @localRecentInputCache=", mapIns._stringifyRecentInputCache(false), ", the incoming resp=\n", JSON.stringify(resp, null, 2));
// The following order of execution is important
const dumpRenderCacheRet = mapIns.onRoomDownsyncFrame(resp.rdf);
mapIns.onInputFrameDownsyncBatch(resp.inputFrameDownsyncBatch, dumpRenderCacheRet);
}
break;
default:
@@ -254,10 +275,6 @@ window.clearLocalStorageAndBackToLoginScene = function(shouldRetainBoundRoomIdIn
if (true != shouldRetainBoundRoomIdInBothVolatileAndPersistentStorage) {
window.clearBoundRoomIdInBothVolatileAndPersistentStorage();
}
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
cc.director.loadScene('wechatGameLogin');
} else {
cc.director.loadScene('login');
}
cc.director.loadScene('login');
};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{
"ver": "1.0.5",
"uuid": "da0a517f-5c74-4fc0-ba89-dbcee184b13e",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@@ -33,20 +33,21 @@
"design-resolution-height": 640,
"design-resolution-width": 960,
"excluded-modules": [
"Spine Skeleton",
"Collider",
"DragonBones",
"RichText",
"Geom Utils",
"Mesh",
"MotionStreak",
"Physics",
"PageView",
"PageViewIndicator",
"RichText",
"Slider",
"Spine Skeleton",
"StudioComponent",
"VideoPlayer",
"WebView",
"Physics",
"StudioComponent",
"3D",
"Mesh",
"Geom Utils",
"3D Primitive"
],
"facebook": {
@@ -74,7 +75,7 @@
"height": 640,
"width": 960
},
"start-scene": "current",
"use-customize-simulator": false,
"use-project-simulator-setting": false
"use-customize-simulator": true,
"use-project-simulator-setting": false,
"start-scene": "current"
}